text stringlengths 14 6.51M |
|---|
unit Utilities;
interface
uses ComCtrls,DB,Classes,SysUtils,Math, ADODB, DBTables, StdCtrls,
DBITypes, Definitions, Forms, IniFiles,
xpEdit, xpCheckBox, xpCombo, xpGroupBox, Controls, ExtCtrls,
MAPI, Windows, Dialogs;
{Conversion utilities}
Function BoolToStr(Bool : Boolean) : String;
Function BoolToStr_Blank_Y(Bool : Boolean) : String;
Function VarRecToStr(VarRec : TVarRec) : String;
Function StringToBoolean(sTemp : String) : Boolean;
{List view utilities}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
const DisplayFormats : Array of String;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
Procedure FillInListViewRow( ListView : TListView;
const Values : Array of const;
SelectLastItem : Boolean;
bChecked : Boolean);
Procedure ChangeListViewRow( ListView : TListView;
const Values : Array of const;
Index : Integer);
Function GetColumnValueForItem(ListView : TListView;
ColumnNumber : Integer;
Index : Integer) : String; {-1 means selected}
Procedure GetColumnValuesForItem(ListView : TListView;
ValuesList : TStringList;
Index : Integer); {-1 means selected}
Procedure SelectListViewItem(ListView : TListView;
RowNumber : Integer);
Procedure DeleteSelectedListViewRow(ListView : TListView);
{String utilities}
Function ForceLength(StringLength : Integer;
SourceString : String): String;
Function _Compare(String1,
String2 : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(Char1,
Char2 : Char;
Comparison : Integer) : Boolean; overload;
Function _Compare( String1 : String;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
Function _Compare(String1 : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(Int1,
Int2 : LongInt;
Comparison : Integer) : Boolean; overload;
Function _Compare( Int1 : LongInt;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
Function _Compare(Real1,
Real2 : Extended;
Comparison : Integer) : Boolean; overload;
Function _Compare(Logical1 : Boolean;
Logical2String : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(DateTime1,
DateTime2 : TDateTime;
Comparison : Integer) : Boolean; overload;
Function StripLeadingAndEndingDuplicateChar(TempStr : String;
CharToStrip : Char) : String;
Procedure ParseCommaDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
Procedure ParseTabDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
Function FormatSQLString(TempStr : String) : String;
Function ShiftRightAddZeroes(SourceStr : String) : String; overload;
Function ShiftRightAddZeroes(SourceStr : String;
StrLength : Integer) : String; overload;
Function IncrementNumericString(sNumericStr : String;
iIncrement : LongInt) : String;
{ADO utilities}
Procedure _Query( Query : TADOQuery;
const Expression : Array of String);
Procedure _QueryExec( Query : TADOQuery;
const Expression : Array of String);
{Windows utilities}
{I\O utilities}
Function FormatExtractField(TempStr : String) : String;
Procedure WriteCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of String);
Procedure WritelnCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of String);
Procedure CopyDBaseTable(SourceTable : TTable;
FileName : String);
{DBase table routines}
Function _Locate( Table : TTable;
const KeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
Function _SetRange( Table : TTable;
const StartKeyFieldValues : Array of const;
const EndKeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
Procedure InitializeFieldsForRecord(Table : TDataset);
Function _InsertRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
InsertRecordOptions : TInsertRecordOptions) : Boolean;
Function _UpdateRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
UpdateRecordOptions : TInsertRecordOptions) : Boolean;
Function _SetFilter(Table : TTable;
_Filter : String) : Boolean;
Function _OpenTable(Table : TTable;
_TableName : String;
_DatabaseName : String; {Blank means PASSystem.}
_IndexName : String;
TableOpenOptions : TTableOpenOptions) : Boolean;
Function _OpenTablesForForm(Form : TForm;
TableOpenOptions : TTableOpenOptions) : Boolean;
Procedure _CloseTablesForForm(Form : TForm);
Function SumTableColumn(Table : TTable;
FieldName : String) : Double; overload;
Function SumTableColumn( Table : TTable;
FieldName : String;
const ConditionalFieldNames : Array of String;
const ConditionalValues : Array of const) : Double; overload;
{Ini file routines}
Function LoadIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean;
UseCustomFilePath : Boolean) : Boolean;
Function LoadIniFileToStringList(FileName : String;
slComponentNames : TStringList;
slComponentValues : TStringList) : Boolean;
Function SaveIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean;
UseCustomFilePath : Boolean) : Boolean;
{General utilities}
Function GetDateTime : String;
Function SaveSelectedListBoxItems(Component : TComponent) : TStringList;
Function StringListToCommaDelimitedString(StringList : TStringList) : String;
implementation
type
TFindKeyFunction = Function( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
{==============================================================================
Conversion utilities
BoolToStr
BoolToStr_Blank_Y
VarRecToStr
==============================================================================}
Function BoolToStr(Bool : Boolean) : String;
begin
If Bool
then Result := 'True'
else Result := 'False';
end; {BoolToStr}
{====================================================}
Function BoolToStr_Blank_Y(Bool : Boolean) : String;
{Return blank for false and Y for true.}
begin
If Bool
then Result := 'Y'
else Result := ' ';
end; {BoolToStr_Blank_Y}
{==============================================================================}
Function VarRecToStr(VarRec : TVarRec) : String;
const
BoolChars : Array[Boolean] of Char = ('F', 'T');
begin
Result := '';
with VarRec do
case VType of
vtInteger : Result := IntToStr(VInteger);
vtBoolean : Result := BoolChars[VBoolean];
vtChar : Result := VChar;
vtExtended : Result := FloatToStr(VExtended^);
vtString : Result := VString^;
vtPChar : Result := VPChar;
vtObject : Result := VObject.ClassName;
vtClass : Result := VClass.ClassName;
vtAnsiString : Result := PChar(VANSIString);
vtCurrency : Result := CurrToStr(VCurrency^);
vtVariant : Result := string(VVariant^);
vtInt64 : Result := IntToStr(VInt64^);
//vtWideString : Result := string(VWideString);
end; {VarRec.VType}
end; {VarRecToStr}
{==============================================================================}
Function StringToBoolean(sTemp : String) : Boolean;
begin
Result := _Compare(sTemp, ['T', 'True', 'Y', '1', 'Yes', 'true'], coEqual);
end; {StringToBoolean}
{==============================================================================
List view utilities
FillInListView
FillInListViewRow
ChangeListViewRow
GetColumnValueForItem
GetColumnValuesForItem
SelectListViewItem
DeleteSelectedListViewRow
===============================================================================}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
{Fill in a TListView from a table using the values of the fields in the order they are passed in.
Note that any select or filter needs to be done prior to calling this procedure.}
var
I : Integer;
Item : TListItem;
Value, FieldName : String;
Done, FirstTimeThrough : Boolean;
begin
FirstTimeThrough := True;
If ReverseOrder
then Dataset.Last
else Dataset.First;
ListView.Enabled := False;
ListView.Items.Clear;
with Dataset do
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
If ReverseOrder
then Prior
else Next;
If ReverseOrder
then Done := BOF
else Done := EOF;
If not Done
then
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(FieldNames) do
try
FieldName := VarRecToStr(FieldNames[I]);
try
Value := Dataset.FieldByName(FieldName).AsString;
except
Value := '';
end;
case Dataset.FieldByName(FieldName).DataType of
ftDate : If _Compare(Value, coNotBlank)
then
try
Value := FormatDateTime(DateFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftDateTime : If _Compare(FieldName, 'Time', coContains)
then
try
Value := FormatDateTime(TimeFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftBoolean : try
Value := BoolToStr_Blank_Y(Dataset.FieldByName(FieldName).AsBoolean);
except
Value := '';
end;
end; {case Dataset.FieldByName(FieldName).DataType of}
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
end; {If not Done}
until Done;
ListView.Enabled := True;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListView}
{==============================================================================}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
const DisplayFormats : Array of String;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
{Fill in a TListView from a table using the values of the fields in the order they are passed in.
Note that any select or filter needs to be done prior to calling this procedure.}
var
I : Integer;
Item : TListItem;
Value, FieldName : String;
Done, FirstTimeThrough : Boolean;
begin
FirstTimeThrough := True;
If ReverseOrder
then Dataset.Last
else Dataset.First;
ListView.Enabled := False;
ListView.Items.Clear;
with Dataset do
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
If ReverseOrder
then Prior
else Next;
If ReverseOrder
then Done := BOF
else Done := EOF;
If not Done
then
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(FieldNames) do
try
FieldName := VarRecToStr(FieldNames[I]);
try
Value := Dataset.FieldByName(FieldName).AsString;
except
Value := '';
end;
case Dataset.FieldByName(FieldName).DataType of
ftDate : If _Compare(Value, coNotBlank)
then
try
Value := FormatDateTime(DateFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftDateTime : If _Compare(FieldName, 'Time', coContains)
then
try
Value := FormatDateTime(TimeFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftBoolean : try
Value := BoolToStr_Blank_Y(Dataset.FieldByName(FieldName).AsBoolean);
except
Value := '';
end;
ftFloat,
ftInteger : try
Value := FormatFloat(DisplayFormats[I], Dataset.FieldByName(FieldName).AsFloat);
except
Value := '';
end;
end; {case Dataset.FieldByName(FieldName).DataType of}
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
end; {If not Done}
until Done;
ListView.Enabled := True;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListView}
{==============================================================================}
Procedure FillInListViewRow( ListView : TListView;
const Values : Array of const;
SelectLastItem : Boolean;
bChecked : Boolean);
{Fill in a TListView from an array of values in the order they are passed in.}
var
Item : TListItem;
Value : String;
I : Integer;
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(Values) do
try
Value := VarRecToStr(Values[I]);
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
Item.Checked := bChecked;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListViewRow}
{==============================================================================}
Procedure ChangeListViewRow( ListView : TListView;
const Values : Array of const;
Index : Integer);
{Fill in a TListView from an array of values in the order they are passed in.}
var
Item : TListItem;
Value : String;
I : Integer;
begin
Item := ListView.Items[Index];
For I := 0 to High(Values) do
try
Value := VarRecToStr(Values[I]);
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
ListView.Refresh;
end; {FillInListViewRow}
{==============================================================================}
Function GetColumnValueForItem(ListView : TListView;
ColumnNumber : Integer;
Index : Integer) : String; {-1 for selected item}
var
TempItem : TListItem;
begin
Result := '';
If _Compare(Index, -1, coEqual)
then TempItem := ListView.Selected
else
try
TempItem := ListView.Items[Index];
except
TempItem := nil;
end;
If (TempItem <> nil)
then
begin
If _Compare(ColumnNumber, 0, coEqual)
then
try
Result := TempItem.Caption;
except
end
else
try
Result := TempItem.SubItems[ColumnNumber - 1];
except
end;
end; {If (TempItem <> nil)}
end; {GetColumnValueForItem}
{==============================================================================}
Procedure GetColumnValuesForItem(ListView : TListView;
ValuesList : TStringList;
Index : Integer); {-1 means selected}
var
I : Integer;
TempItem : TListItem;
begin
ValuesList.Clear;
If _Compare(Index, -1, coEqual)
then TempItem := ListView.Selected
else
try
TempItem := ListView.Items[Index];
except
TempItem := nil;
end;
with ListView do
For I := 0 to (Columns.Count - 1) do
If _Compare(I, 0, coEqual)
then ValuesList.Add(TempItem.Caption)
else ValuesList.Add(TempItem.SubItems[I - 1]);
end; {GetColumnValuesForItem}
{==============================================================================}
Procedure SelectListViewItem(ListView : TListView;
RowNumber : Integer);
begin
with ListView do
If _Compare(RowNumber, (Items.Count - 1), coLessThanOrEqual)
then
begin
Selected := Items[RowNumber];
Refresh;
end;
end; {SelectListViewItem}
{==============================================================================}
Procedure DeleteSelectedListViewRow(ListView : TListView);
var
Index : Integer;
SelectedItem : TListItem;
ItemDeleted : Boolean;
begin
Index := 0;
ItemDeleted := False;
SelectedItem := ListView.Selected;
with ListView do
while ((not ItemDeleted) and
_Compare(Index, (Items.Count - 1), coLessThanOrEqual)) do
begin
If (Items[Index] = SelectedItem)
then
try
ItemDeleted := True;
Items.Delete(Index);
except
end;
Inc(Index);
end; {while ((not Deleted) and ...}
end; {DeleteSelectedListViewRow}
{==============================================================================
String functions
ForceLength
_Compare (many versions overloaded)
StripLeadingAndEndingDuplicateChar
ParseCommaDelimitedStringIntoFields
ParseTabDelimitedStringIntoFields
FormatSQLString
ShiftRightAddZeroes
{==============================================================================}
Function ForceLength(StringLength : Integer;
SourceString : String): String;
begin
Result := Copy(SourceString, 1, StringLength);
while (Length(Result) < StringLength) do
Result := Result + ' ';
end; {ForceLength}
{============================================================================}
Function _Compare(String1,
String2 : String;
Comparison : Integer) : Boolean; overload;
{String compare}
var
SubstrLen : Integer;
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
String2 := ANSIUpperCase(Trim(String2));
case Comparison of
coEqual : Result := (String1 = String2);
coGreaterThan : Result := (String1 > String2);
coLessThan : Result := (String1 < String2);
coGreaterThanOrEqual : Result := (String1 >= String2);
coLessThanOrEqual : Result := (String1 <= String2);
coNotEqual : Result := (String1 <> String2);
{CHG11251997-2: Allow for selection on blank or not blank.}
coBlank : Result := (Trim(String1) = '');
coNotBlank : Result := (Trim(String1) <> '');
coContains : Result := (Pos(Trim(String2), String1) > 0);
{CHG09111999-1: Add starts with.}
coStartsWith :
begin
String2 := Trim(String2);
SubstrLen := Length(String2);
Result := (ForceLength(SubstrLen, String1) = ForceLength(SubstrLen, String2));
end;
coDoesNotStartWith :
begin
String2 := Trim(String2);
SubstrLen := Length(String2);
Result := (ForceLength(SubstrLen, String1) <> ForceLength(SubstrLen, String2));
end;
coMatchesOrFirstItemBlank :
begin
If _Compare(String1, coBlank)
then Result := True
else Result := _Compare(String1, String2, coEqual);
end; {coMatchesOrFirstItemBlank}
coMatchesPartialOrFirstItemBlank :
begin
If _Compare(String1, coBlank)
then Result := True
else
If (Length(String1) > Length(String2))
then Result := _Compare(String1, String2, coStartsWith)
else Result := _Compare(String2, String1, coStartsWith);
end; {coMatchesPartialOrBlank}
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Char1,
Char2 : Char;
Comparison : Integer) : Boolean; overload;
{Character compare}
begin
Result := False;
Char1 := UpCase(Char1);
Char2 := UpCase(Char2);
case Comparison of
coEqual : Result := (Char1 = Char2);
coGreaterThan : Result := (Char1 > Char2);
coLessThan : Result := (Char1 < Char2);
coGreaterThanOrEqual : Result := (Char1 >= Char2);
coLessThanOrEqual : Result := (Char1 <= Char2);
coNotEqual : Result := (Char1 <> Char2);
coBlank : Result := (Char1 = ' ');
coNotBlank : Result := (Char1 <> ' ');
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare( String1 : String;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
{String compare - multiple values}
var
I : Integer;
String2 : String;
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
For I := 0 to High(ComparisonValues) do
try
String2 := ANSIUpperCase(Trim(VarRecToStr(ComparisonValues[I])));
Result := Result or _Compare(String1, String2, Comparison);
except
end;
end; {_Compare}
{============================================================================}
Function _Compare(String1 : String;
Comparison : Integer) : Boolean; overload;
{Special string version for blank \ non blank compare.
Note that the regular string _Compare can be used too if the 2nd string is blank.}
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
case Comparison of
coBlank : Result := (Trim(String1) = '');
coNotBlank : Result := (Trim(String1) <> '');
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Int1,
Int2 : LongInt;
Comparison : Integer) : Boolean; overload;
{Integer version}
begin
Result := False;
case Comparison of
coEqual : Result := (Int1 = Int2);
coGreaterThan : Result := (Int1 > Int2);
coLessThan : Result := (Int1 < Int2);
coGreaterThanOrEqual : Result := (Int1 >= Int2);
coLessThanOrEqual : Result := (Int1 <= Int2);
coNotEqual : Result := (Int1 <> Int2);
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare( Int1 : LongInt;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
{Integer version}
var
I : Integer;
Int2 : LongInt;
begin
Result := False;
For I := 0 to High(ComparisonValues) do
try
Int2 := StrToInt(VarRecToStr(ComparisonValues[I]));
Result := Result or _Compare(Int1, Int2, Comparison);
except
end;
end; {_Compare}
{============================================================================}
Function _Compare(Real1,
Real2 : Extended;
Comparison : Integer) : Boolean; overload;
{Float version}
begin
Result := False;
case Comparison of
coEqual : Result := (RoundTo(Real1, -4) = RoundTo(Real2, -4));
coGreaterThan : Result := (RoundTo(Real1, -4) > RoundTo(Real2, -4));
coLessThan : Result := (RoundTo(Real1, -4) < RoundTo(Real2, -4));
coGreaterThanOrEqual : Result := (RoundTo(Real1, -4) >= RoundTo(Real2, -4));
coLessThanOrEqual : Result := (RoundTo(Real1, -4) <= RoundTo(Real2, -4));
coNotEqual : Result := (RoundTo(Real1, -4) <> RoundTo(Real2, -4));
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Logical1 : Boolean;
Logical2String : String;
Comparison : Integer) : Boolean; overload;
{For booleans only coEqual and coNotEqual apply.}
var
Logical2 : Boolean;
begin
Result := False;
{CHG04102003-3(2.06r): Allow for Yes/No in boolean fields.}
Logical2 := False;
Logical2String := Trim(ANSIUpperCase(Logical2String));
{FXX04292003-1(2.07): Added Yes and Y, but made it so that True and T did not work.}
If ((Logical2String = 'YES') or
(Logical2String = 'Y') or
(Logical2String = 'NO') or
(Logical2String = 'N') or
(Logical2String = 'TRUE') or
(Logical2String = 'T'))
then Logical2 := True;
case Comparison of
coEqual : Result := (Logical1 = Logical2);
coNotEqual : Result := (Logical1 <> Logical2);
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(DateTime1,
DateTime2 : TDateTime;
Comparison : Integer) : Boolean; overload;
{Date \ time version}
begin
Result := False;
case Comparison of
coEqual : Result := (DateTime1 = DateTime2);
coGreaterThan : Result := (DateTime1 > DateTime2);
coLessThan : Result := (DateTime1 < DateTime2);
coGreaterThanOrEqual : Result := (DateTime1 >= DateTime2);
coLessThanOrEqual : Result := (DateTime1 <= DateTime2);
coNotEqual : Result := (DateTime1 <> DateTime2);
end; {case Comparison of}
end; {_Compare}
{===========================================================================}
Function StripLeadingAndEndingDuplicateChar(TempStr : String;
CharToStrip : Char) : String;
begin
Result := TempStr;
If ((Length(Result) > 1) and
(Result[1] = CharToStrip) and
(Result[Length(Result)] = CharToStrip))
then
begin
Delete(Result, Length(Result), 1);
Delete(Result, 1, 1);
end;
end; {StripLeadingAndEndingDuplicateChar}
{===========================================================================}
Procedure ParseCommaDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
var
InEmbeddedQuote : Boolean;
CurrentField : String;
I : Integer;
begin
FieldList.Clear;
InEmbeddedQuote := False;
CurrentField := '';
For I := 1 to Length(TempStr) do
begin
If (TempStr[I] = '"')
then InEmbeddedQuote := not InEmbeddedQuote;
{New field if we have found comma and we are not in an embedded quote.}
If ((TempStr[I] = ',') and
(not InEmbeddedQuote))
then
begin
{If the field starts and ends with a double quote, strip it.}
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(CurrentField);
FieldList.Add(CurrentField);
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
CurrentField := '';
end
else CurrentField := CurrentField + TempStr[I];
end; {For I := 1 to Length(TempStr) do}
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(Trim(CurrentField));
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
FieldList.Add(Trim(CurrentField));
end; {ParseCommaDelimitedStringIntoFields}
{===========================================================================}
Procedure ParseTabDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
var
CurrentField : String;
TabPos : Integer;
Done : Boolean;
begin
FieldList.Clear;
CurrentField := '';
Done := False;
while ((not Done) and
(SysUtils.Trim(TempStr) <> '')) do
begin
TabPos := Pos(Chr(9), TempStr);
If (TabPos = 0)
then
begin
Done := True;
CurrentField := TempStr;
end
else
begin
CurrentField := Copy(TempStr, 1, (TabPos - 1));
Delete(TempStr, 1, TabPos);
end;
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(CurrentField);
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
FieldList.Add(Trim(CurrentField));
CurrentField := '';
end; {while ((not Done) and ...}
end; {ParseTabDelimitedStringIntoFields}
{=======================================================================}
Function FormatSQLString(TempStr : String) : String;
begin
Result := '''' + TempStr + '''';
end;
{===================================================================}
Function Take(len:integer;vec:String): String;
begin
vec:=copy(vec,1,len);
while length(vec)<len do vec:=concat(vec,' ');
take:=vec;
end;
{============================================================================}
Function ShiftRightAddZeroes(SourceStr : String) : String; overload;
var
TempLen : Integer;
begin
TempLen := Length(SourceStr);
Result := SourceStr;
If _Compare(Result, coBlank)
then Result := StringOfChar('0', TempLen)
else
while (Result[TempLen] = ' ') do
begin
Delete(Result, TempLen, 1);
Result := '0' + Result;
end;
end; {ShiftRightAddZeroes}
{============================================================================}
Function ShiftRightAddZeroes(SourceStr : String;
StrLength : Integer) : String; overload;
var
TempLen : Integer;
begin
SourceStr := Take(StrLength, Trim(SourceStr));
TempLen := Length(SourceStr);
If _Compare(SourceStr, coBlank)
then SourceStr := StringOfChar('0', TempLen)
else
while (SourceStr[TempLen] = ' ') do
begin
Delete(SourceStr, TempLen, 1);
SourceStr := '0' + SourceStr;
end;
Result := SourceStr;
end; {ShiftRightAddZeroes}
{===================================================================}
Function IncrementNumericString(sNumericStr : String;
iIncrement : LongInt) : String;
begin
try
Result := IntToStr(StrToInt(sNumericStr) + iIncrement);
except
Result := '';
end;
end; {IncrementNumericString}
{========================================================================
ADO routines.
_Query
_QueryExec
=========================================================================}
Procedure _Query( Query : TADOQuery;
const Expression : Array of String);
var
I : Integer;
begin
with Query.SQL do
begin
Clear;
For I := 0 to High(Expression) do
Add(Expression[I]);
end;
try
Query.Open;
except
end;
end; {_Query}
{========================================================================}
Procedure _QueryExec( Query : TADOQuery;
const Expression : Array of String);
var
I : Integer;
begin
with Query.SQL do
begin
Clear;
For I := 0 to High(Expression) do
Add(Expression[I]);
end;
try
Query.ExecSQL;
except
end;
end; {_QueryExec}
{========================================================================
I/O routines.
FormatExtractField
WriteCommaDelimitedLine
WritelnCommaDelimitedLine
CopyDBaseTable
=========================================================================}
Function FormatExtractField(TempStr : String) : String;
begin
{If there is an embedded quote, surround the field in double quotes.}
If (Pos('|', TempStr) > 0)
then TempStr := '"' + TempStr + '"';
Result := '|' + TempStr;
end; {FormatExtractField}
{==================================================================}
Procedure WriteCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of String);
var
I : Integer;
TempStr : String;
begin
For I := 0 to High(Fields) do
begin
GlblCurrentCommaDelimitedField := GlblCurrentCommaDelimitedField + 1;
TempStr := Fields[I];
If (GlblCurrentCommaDelimitedField = 1)
then Write(ExtractFile, TempStr)
else Write(ExtractFile, FormatExtractField(TempStr));
end; {For I := 0 to High(Fields) do}
end; {WriteCommaDelimitedLine}
{==================================================================}
Procedure WritelnCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of String);
begin
If (High(Fields) > 0)
then WriteCommaDelimitedLine(ExtractFile, Fields);
Writeln(ExtractFile);
GlblCurrentCommaDelimitedField := 0;
end; {WritelnCommaDelimitedLine}
{=============================================================
DBase Table Routines
=============================================================}
Procedure CopyDBaseTable(SourceTable : TTable;
FileName : String);
{Copy a sort file template to a temporary sort file using BatchMove.}
var
TblDesc: CRTblDesc;
PtrFldDesc, PtrIdxDesc: Pointer;
CursorProp: CURProps;
begin
SourceTable.Open;
Check(DbiGetCursorProps(SourceTable.Handle, CursorProp));
// Allocate memory for field descriptors
PtrFldDesc := AllocMem(SizeOf(FLDDesc) * CursorProp.iFields);
PtrIdxDesc := AllocMem(SizeOf(IDXDesc) * CursorProp.iIndexes);
try
Check(DbiGetFieldDescs(SourceTable.Handle, PtrFldDesc));
Check(DbiGetIndexDescs(SourceTable.Handle, PtrIdxDesc));
FillChar(TblDesc, SizeOf(TblDesc), #0);
with TblDesc do
begin
StrPCopy(szTblName, FileName);
StrCopy(szTblType, CursorProp.szTableType);
iFldCount := CursorProp.iFields;
pfldDesc := PtrFldDesc;
iIdxCount := CursorProp.iIndexes;
pIdxDesc := PtrIdxDesc;
end;
Check(DbiCreateTable(SourceTable.DBHandle, True, TblDesc));
finally
FreeMem(PtrFldDesc);
FreeMem(PtrIdxDesc);
end;
SourceTable.Close;
end; {CopyDBaseTable}
{===================================================}
Function FindKeyDBase( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
var
I : Integer;
TempValue : String;
begin
with Table do
begin
SetKey;
For I := 0 to High(Values) do
try
TempValue := VarRecToStr(Values[I]);
FieldByName(IndexFieldNameList[I]).Text := TempValue;
except
end;
Result := GotoKey;
end; {with Table do}
end; {FindKeyDBase}
{===================================================}
Function FindNearestDBase( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
begin
SetKey;
For I := 0 to High(Values) do
try
FieldByName(IndexFieldNameList[I]).Text := VarRecToStr(Values[I]);
except
end;
GotoNearest;
end; {with Table do}
end; {FindNearestDBase}
{==========================================================================}
Procedure ParseIndexExpressionIntoFields(Table : TTable;
IndexFieldNameList : TStringList);
var
IndexPosition, PlusPos : Integer;
IndexExpression, TempFieldName : String;
begin
IndexFieldNameList.Clear;
IndexPosition := Table.IndexDefs.IndexOf(Table.IndexName);
IndexExpression := Table.IndexDefs[IndexPosition].FieldExpression;
{Strip out the ')', 'DTOS(', 'STR('.}
IndexExpression := StringReplace(IndexExpression, ')', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'DTOS(', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'TTOS(', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'STR(', '', [rfReplaceAll, rfIgnoreCase]);
repeat
PlusPos := Pos('+', IndexExpression);
If (PlusPos > 0)
then TempFieldName := Copy(IndexExpression, 1, (PlusPos - 1))
else TempFieldName := IndexExpression;
IndexFieldNameList.Add(TempFieldName);
If (PlusPos > 0)
then Delete(IndexExpression, 1, PlusPos)
else IndexExpression := '';
until (IndexExpression = '');
end; {ParseIndexExpressionIntoFields}
{==========================================================================}
Function _Locate( Table : TTable;
const KeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
{Note that IndexName can be blank if you want to use the current index.}
var
LocateFunction : TFindKeyFunction;
IndexFieldNameList : TStringList;
begin
Table.First;
IndexFieldNameList := TStringList.Create;
LocateFunction := FindKeyDBase;
If (loPartialKey in LocateOptions)
then LocateFunction := FindNearestDBase;
If ((loChangeIndex in LocateOptions) and
(Trim(IndexName) <> ''))
then Table.IndexName := IndexName;
ParseIndexExpressionIntoFields(Table, IndexFieldNameList);
Result := LocateFunction(Table, IndexFieldNameList, KeyFieldValues);
IndexFieldNameList.Free;
end; {_Locate}
{==========================================================================}
Function _SetRange( Table : TTable;
const StartKeyFieldValues : Array of const;
const EndKeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
{Note that IndexName can be blank if you want to use the current index.}
var
IndexFieldNameList : TStringList;
TempValue : String;
I : Integer;
begin
Result := True;
IndexFieldNameList := TStringList.Create;
If ((loChangeIndex in LocateOptions) and
(Trim(IndexName) <> ''))
then Table.IndexName := IndexName;
ParseIndexExpressionIntoFields(Table, IndexFieldNameList);
{Now do the set range.}
with Table do
try
CancelRange;
SetRangeStart;
For I := 0 to (IndexFieldNameList.Count - 1) do
FieldByName(IndexFieldNameList[I]).Text := VarRecToStr(StartKeyFieldValues[I]);
SetRangeEnd;
For I := 0 to (IndexFieldNameList.Count - 1) do
begin
If (loSameEndingRange in LocateOptions)
then TempValue := VarRecToStr(StartKeyFieldValues[I])
else TempValue := VarRecToStr(EndKeyFieldValues[I]);
FieldByName(IndexFieldNameList[I]).Text := TempValue;
end; {For I := 0 to (IndexFieldNameList.Count - 1) do}
ApplyRange;
except
Result := False;
end; {with Table do}
IndexFieldNameList.Free;
end; {_SetRange}
{====================================================================}
Procedure InitializeFieldsForRecord(Table : TDataset);
var
I : Integer;
begin
with Table do
For I := 0 to (Fields.Count - 1) do
begin
If (Fields[I].DataType in [ftString])
then
try
Fields[I].Value := '';
except
end;
If (Fields[I].DataType in [ftSmallInt, ftInteger, ftWord,
ftFloat, ftCurrency, ftLargeInt, ftBCD])
then
try
Fields[I].Value := 0;
except
end;
If (Fields[I].DataType = ftBoolean)
then
try
Fields[I].AsBoolean := False;
except
end;
end; {For I := 0 to (Fields.Count) do}
end; {InitializeFieldsForRecord}
{===============================================================}
Function _InsertRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
InsertRecordOptions : TInsertRecordOptions) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
try
Insert;
If not (irSuppressInitializeFields in InsertRecordOptions)
then InitializeFieldsForRecord(Table);
For I := 0 to High(_FieldNames) do
try
FieldByName(VarRecToStr(_FieldNames[I])).AsString := VarRecToStr(_FieldValues[I]);
except
end;
If not (irSuppressPost in InsertRecordOptions)
then Post;
except
Cancel;
Result := False;
end;
end; {_InsertRecord}
{===============================================================}
Function _UpdateRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
UpdateRecordOptions : TInsertRecordOptions) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
try
Edit;
For I := 0 to High(_FieldNames) do
try
FieldByName(VarRecToStr(_FieldNames[I])).AsString := VarRecToStr(_FieldValues[I]);
except
end;
If not (irSuppressPost in UpdateRecordOptions)
then Post;
except
Cancel;
Result := False;
end;
end; {_UpdateRecord}
{=========================================================================}
Function _SetFilter(Table : TTable;
_Filter : String) : Boolean;
begin
Result := True;
with Table do
try
Filtered := False;
Filter := _Filter;
Filtered := True;
except
Result := False;
end;
end; {_SetFilter}
{==============================================================================}
Function _OpenTable(Table : TTable;
_TableName : String;
_DatabaseName : String; {Blank means PASSystem.}
_IndexName : String;
TableOpenOptions : TTableOpenOptions) : Boolean;
begin
Result := True;
with Table do
try
Close;
TableType := ttDBase;
If not (toOpenAsIs in TableOpenOptions)
then
begin
If _Compare(_DatabaseName, coBlank)
then DatabaseName := 'PASSystem'
else DatabaseName := _DatabaseName;
If _Compare(_IndexName, coNotBlank)
then IndexName := _IndexName;
Exclusive := (toExclusive in TableOpenOptions);
ReadOnly := (toReadOnly in TableOpenOptions);
end; {If not (toOpenAsIs in TableOpenOptions)}
Open;
except
Result := False;
end;
end; {_OpenTable}
{=======================================================================}
Function _OpenTablesForForm(Form : TForm;
TableOpenOptions : TTableOpenOptions) : Boolean;
var
I : Integer;
TableName : String;
begin
Result := True;
with Form do
begin
For I := 1 to (ComponentCount - 1) do
If ((Components[I] is TTable) and
_Compare(TTable(Components[I]).TableName, coNotBlank) and
((not (toNoReOpen in TableOpenOptions)) or
(not TTable(Components[I]).Active)))
then
begin
TableName := TTable(Components[I]).TableName;
If not _OpenTable(TTable(Components[I]), TableName, '', '', TableOpenOptions)
then Result := False;
end; {If ((Components[I] is TTable) and ...}
end; {with Form do}
end; {_OpenTablesForForm}
{================================================================================}
Procedure _CloseTablesForForm(Form : TForm);
{Close all the tables on the form.}
var
I : Integer;
begin
with Form do
For I := 1 to (ComponentCount - 1) do
If (Components[I] is TTable)
then
try
with Components[I] as TTable do
If Active
then Close;
except
end;
end; {CloseTablesForForm}
{===========================================================================}
Function SumTableColumn(Table : TTable;
FieldName : String) : Double; overload;
var
Done, FirstTimeThrough : Boolean;
begin
Done := False;
FirstTimeThrough := True;
Result := 0;
Table.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Table.Next;
If Table.EOF
then Done := True;
If not Done
then
try
Result := Result + Table.FieldByName(FieldName).AsFloat;
except
end;
until Done;
end; {SumTableColumn}
{===========================================================================}
Function SumTableColumn( Table : TTable;
FieldName : String;
const ConditionalFieldNames : Array of String;
const ConditionalValues : Array of const) : Double; overload;
var
Done, FirstTimeThrough, MeetsConditions : Boolean;
I : Integer;
begin
FirstTimeThrough := True;
Result := 0;
Table.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Table.Next;
Done := Table.EOF;
If not Done
then
begin
MeetsConditions := True;
For I := 0 to High(ConditionalFieldNames) do
try
If _Compare(Table.FieldByName(ConditionalFieldNames[I]).Text, VarRecToStr(ConditionalValues[I]), coNotEqual)
then MeetsConditions := False;
except
end;
If MeetsConditions
then
try
Result := Result + Table.FieldByName(FieldName).AsFloat;
except
end;
end; {If not Done}
until Done;
end; {SumTableColumn}
{==============================================================================
Ini file routines
LoadIniFile
LoadIniFileToStringList
SaveIniFile
==============================================================================}
Function LoadIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean;
UseCustomFilePath: Boolean) : Boolean;
var
_FileExists : Boolean;
I, X, EqualsPos : Integer;
ComponentName, ComponentValue,
sIniFileName, sConfigFileName,
sTableName, sDatabaseName : String;
IniFile : TIniFile;
SectionValues, slSelectedTables : TStringList;
Component : TComponent;
tmrPropagateTables : TTimer;
begin
Result := True;
if UseCustomFilePath
then
begin
sIniFileName := FileName;
sConfigFileName := FileName + '2';
end
else
begin
sIniFileName := GetCurrentDir + FileName;
sConfigFileName := GetCurrentDir + FileName + '2';
end;
_FileExists := FileExists(sIniFileName);
tmrPropagateTables := TTimer.Create(nil);
tmrPropagateTables.Interval := 1;
tmrPropagateTables.Enabled := False;
If (_FileExists or
((not _FileExists) and
CreateFileOnNotExist))
then
begin
IniFile := TIniFile.Create(sIniFileName);
SectionValues := TStringList.Create;
slSelectedTables := TStringList.Create;
If FileExists(sConfigFileName)
then slSelectedTables.LoadFromFile(sConfigFileName);
IniFile.ReadSectionValues(sct_Components, SectionValues);
For I := 0 to (SectionValues.Count - 1) do
begin
EqualsPos := Pos('=', SectionValues[I]);
ComponentName := Copy(SectionValues[I], 1, (EqualsPos - 1));
ComponentValue := Copy(SectionValues[I], (EqualsPos + 1), 255);
Component := Form.FindComponent(ComponentName);
If (Component <> nil)
then
begin
If (Component is TPanel)
then
try
TPanel(Component).Caption := ComponentValue;
except
end;
If (Component is TXPEdit)
then
try
TXPEdit(Component).Text := ComponentValue;
except
end;
If (Component is TXPComboBox)
then
try
TXPComboBox(Component).Text := ComponentValue;
If (TXPComboBox(Component).Name = 'cbxDBaseDatabase')
then
begin
sDatabaseName := ComponentValue;
end;
except
end;
If (Component is TXPCheckBox)
then
try
TXPCheckBox(Component).Checked := _Compare(ComponentValue, 'TRUE', coEqual);
except
end;
If (Component is TListBox)
then
begin
if (Component.Name = 'lbxTables')
then
begin
Session.GetTableNames(sDatabaseName, '*.*', False, False, TListBox(Component).Items);
tmrPropagateTables.Enabled := True;
for X := 0 to TListBox(Component).Count-1 do
begin
sTableName := TListBox(Component).Items[X];
if (slSelectedTables.IndexOf(sTableName) <> -1)
then TListBox(Component).Selected[X] := True
else
end;
end;
end;
end; {If (Component <> nil)}
end; {For I := 0 to (SectionValues.Count - 1) do}
IniFile.Free;
SectionValues.Free;
end {If FileExists(IniFileName)}
else Result := False;
end; {LoadIniFile}
{==============================================================================}
Function LoadIniFileToStringList(FileName : String;
slComponentNames : TStringList;
slComponentValues : TStringList) : Boolean;
var
I, iEqualsPos : Integer;
IniFile : TIniFile;
slSectionValues : TStringList;
begin
Result := True;
slComponentNames.Clear;
slComponentValues.Clear;
If FileExists(FileName)
then
begin
IniFile := TIniFile.Create(FileName);
slSectionValues := TStringList.Create;
IniFile.ReadSectionValues(sct_Components, slSectionValues);
For I := 0 to (slSectionValues.Count - 1) do
begin
iEqualsPos := Pos('=', slSectionValues[I]);
slComponentNames.Add(Copy(slSectionValues[I], 1, (iEqualsPos - 1)));
slComponentValues.Add(Copy(slSectionValues[I], (iEqualsPos + 1), 255));
end; {For I := 0 to (SectionValues.Count - 1) do}
IniFile.Free;
slSectionValues.Free;
end {If FileExists(IniFileName)}
else Result := False;
end; {LoadIniFileToStringList}
{============================================================================}
Function SaveIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean;
UseCustomFilePath : Boolean) : Boolean;
var
_FileExists, SaveValue : Boolean;
I, X : Integer;
ComponentName, ComponentValue,
sIniFileName, sConfigFileName : String;
slTableSelection : TStringList;
IniFile : TIniFile;
Component : TComponent;
begin
Result := True;
slTableSelection := TStringList.Create;
if UseCustomFilePath
then
begin
sIniFileName := FileName;
sConfigFileName := FileName + '2';
end
else
begin
sIniFileName := GetCurrentDir + FileName;
sConfigFileName := GetCurrentDir + FileName + '2';
end;
_FileExists := FileExists(sIniFileName);
If (_FileExists or
((not _FileExists) and
CreateFileOnNotExist))
then
begin
IniFile := TIniFile.Create(sIniFileName);
For I := 0 to (Form.ComponentCount - 1) do
begin
Component := Form.Components[I];
ComponentName := TControl(Component).Name;
ComponentValue := '';
SaveValue := False;
If (Component is TPanel)
then
begin
ComponentValue := TPanel(Component).Caption;
SaveValue := True;
end;
If (Component is TXPEdit)
then
begin
ComponentValue := TXPEdit(Component).Text;
SaveValue := True;
end;
If (Component is TXPComboBox)
then
begin
ComponentValue := TXPComboBox(Component).Text;
SaveValue := True;
end;
If (Component is TXPCheckBox)
then
begin
ComponentValue := BoolToStr(TXPCheckBox(Component).Checked);
SaveValue := True;
end;
If (Component is TListBox)
then
begin
For x := 0 to (TListBox(Component).Items.Count - 1) do
begin
if TListBox(Component).Selected[x]
then slTableSelection.Append(TListBox(Component).Items[x]);
end;
ComponentValue := 'True';
SaveValue := True;
end;
If SaveValue
then IniFile.WriteString(sct_Components, ComponentName, ComponentValue);
end; {For I := 0 to (Form.ComponentCount - 1) do}
IniFile.Free;
end {If FileExists(sIniFileName)}
else Result := False;
slTableSelection.SaveToFile(sConfigFileName);
end; {SaveIniFile}
{==========================================================}
Function GetDateTime : String;
begin
Result := 'Date: ' + FormatDateTime(DateFormat, Date) +
' Time: ' + FormatDateTime(TimeFormat, Now);
end; {GetDateTime}
{CHG12112013(MPT):Add function to return selected items in a listbox to TSringList}
{==========================================================}
Function SaveSelectedListBoxItems(Component : TComponent) : TStringList;
var
slSelectedItems : TStringList;
I : Integer;
begin
slSelectedItems := TStringList.Create;
For I := 0 to (TListBox(Component).Items.Count - 1) do
begin
if TListBox(Component).Selected[I]
then slSelectedItems.Append(TListBox(Component).Items[I]);
end;
Result := slSelectedItems;
end;
{CHG12112013(MPT):Add function to return stringlist as comma delimited string}
{==========================================================}
Function StringListToCommaDelimitedString(StringList : TStringList) : String;
var
sResultString : String;
I : Integer;
begin
For I:=0 to StringList.Count-1 do
begin
sResultString := sResultString + StringList[I];
If (I < StringList.Count-1)
then sResultString := sResultString + ', ';
end;
Result := sResultString;
end;
end.
|
unit _fmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ValEdit, Vcl.ExtCtrls;
type
TfmMain = class(TForm)
Config: TValueListEditor;
procedure ConfigValidate(Sender: TObject; ACol, ARow: Integer;
const KeyName, KeyValue: string);
procedure ConfigSetEditText(Sender: TObject; ACol, ARow: Integer;
const Value: string);
private
{ Private declarations }
FFileName: String;
procedure Initialize;
procedure GetValues;
procedure WritePosition;
protected
procedure WndProc(var Message: TMessage); override;
public
{ Public declarations }
procedure AfterConstruction; override;
end;
var
fmMain: TfmMain;
implementation
uses
System.IniFiles, System.IOUtils;
var
ConfigName: String;
{$R *.dfm}
{ TfmMain }
procedure TempObjectProc(AInstance: TObject; AProc: TProc<TObject>);
begin
try
AProc(AInstance);
finally
AInstance.Free;
end;
end;
procedure IniProc(const AFileName: String; AProc: TProc<TIniFile>);
begin
if AFileName.IsEmpty = False then begin
TempObjectProc(TIniFile.Create(AFileName), TProc<TObject>(AProc));
end;
end;
procedure GetKeyList(Ini: TIniFile; AList: TStrings);
begin
if Assigned(Ini) then begin
TempObjectProc(TStringList.Create, TProc<TObject>(procedure (SectionList: TStringList)
var
I: Integer;
begin
SectionList.Duplicates := dupIgnore;
SectionList.Sorted := True;
Ini.ReadSections(SectionList);
SectionList.Sorted := False;
for I := Pred(SectionList.Count) downto 0 do begin
if Ini.ReadBool(SectionList.Strings[I], 'Define', False) then begin
SectionList.Delete(I);
end else begin
SectionList.Strings[I] := SectionList.Strings[I] + '=';
end;
end;
AList.Assign(SectionList);
end));
end else begin
IniProc(ConfigName, procedure (Ini: TIniFile)
begin
GetKeyList(Ini, AList);
end);
end;
end;
procedure GetValueList(Ini: TIniFile; AList: TStrings; const KeyName: string);
var
Section: string;
Value: string;
begin
if Assigned(Ini) then begin
Value := KeyName;
repeat
Section := Value;
Value := Ini.ReadString(Value, 'Type', '');
until Value.IsEmpty;
AList.CommaText := Ini.ReadString(Section, 'ValueList', '');
end else begin
IniProc(ConfigName, procedure (Ini: TIniFile)
begin
GetValueList(Ini, AList, KeyName);
end);
end;
end;
procedure TfmMain.AfterConstruction;
begin
inherited;
Initialize;
if FFileName.IsEmpty = False then begin
Caption := Format('%s - %s', [Application.Title, ExtractFileName(FFileName)]);
GetValues;
end else begin
Application.MessageBox('FileName is not defined.', PChar(Application.Title), MB_ICONERROR or MB_OK);
Application.ShowMainForm := False;
Application.Terminate;
end;
end;
procedure TfmMain.ConfigSetEditText(Sender: TObject; ACol, ARow: Integer;
const Value: string);
var
iIndex: Integer;
begin
iIndex := ARow - (Config.RowCount - Config.Strings.Count);
if not iIndex in [0..Pred(Config.Strings.Count)] then begin
Exit;
end;
if Value.IsEmpty and not TFile.Exists(FFileName) then begin
Exit;
end;
TempObjectProc(TStringList.Create, TProc<TObject>(procedure (Key: TStringList)
begin
Key.Delimiter := '/';
Key.DelimitedText := Config.Strings.Names[iIndex];
IniProc(FFileName, procedure (Ini: TIniFile)
begin
Ini.WriteString(Key.Strings[0], Key.Strings[1], Value);
end);
end));
end;
procedure TfmMain.ConfigValidate(Sender: TObject; ACol, ARow: Integer;
const KeyName, KeyValue: string);
var
ItemProps: TItemProp;
I: Integer;
begin
ItemProps := Config.ItemProps[KeyName];
if ItemProps.HasPickList then begin
for I := 0 to Pred(ItemProps.PickList.Count) do begin
if Pos(KeyValue, ItemProps.PickList.Strings[I]) = 1 then begin
Config.Values[Keyname] := ItemProps.PickList.Strings[I];
end;
end;
end;
end;
procedure TfmMain.Initialize;
var
Value: string;
Pos: array[0..Pred(4)] of Integer;
begin
if ParamCount > 0 then begin
if TFile.Exists(ParamStr(1)) then begin
ConfigName := ParamStr(1);
end;
end;
IniProc(ConfigName, procedure (Ini: TIniFile)
var
I: Integer;
begin
// Key
GetKeyList(Ini, Config.Strings);
// PickList
for I := 0 to Pred(Config.Strings.Count) do begin
GetValueList(Ini, Config.ItemProps[I].PickList, Config.Keys[I + 1]);
if Config.ItemProps[I].PickList.Count > 0 then begin
Config.ItemProps[I].EditStyle := esPickList;
end;
Value := Ini.ReadString(Config.Keys[I + 1], 'Desc', '');
if not Value.IsEmpty then begin
Config.ItemProps[I].KeyDesc := Value;
end;
end;
// Config
FFileName := Ini.ReadString('Config', 'FileName', '');
if FFileName.IsEmpty = False then begin
FFileName := ExtractFilePath(ParamStr(0)) + FFileName;
end;
TempObjectProc(TStringList.Create, TProc<TObject>(procedure (Reader: TStringList)
begin
Reader.CommaText := Ini.ReadString('Config', 'Position', '');
if (Reader.Count >= 4)
and TryStrToInt(Reader.Strings[0], Pos[0])
and TryStrToInt(Reader.Strings[1], Pos[1])
and TryStrToInt(Reader.Strings[2], Pos[2])
and TryStrToInt(Reader.Strings[3], Pos[3]) then begin
Position := poDesigned;
SetBounds(Pos[0], Pos[1], Pos[2], Pos[3]);
end;
end));
end);
end;
procedure TfmMain.WritePosition;
begin
IniProc(ConfigName, procedure (Ini: TIniFile)
begin
TempObjectProc(TStringList.Create, TProc<TObject>(procedure (Reader: TStringList)
begin
Reader.Add(IntToStr(Left));
Reader.Add(IntToStr(Top));
Reader.Add(IntToStr(Width));
Reader.Add(IntToStr(Height));
Ini.WriteString('Config', 'Position', Reader.CommaText);
end));
end);
end;
procedure TfmMain.WndProc(var Message: TMessage);
begin
inherited;
if Message.Msg = WM_WINDOWPOSCHANGED then begin
if not (fsCreating in FormState) then begin
WritePosition;
end;
end;
end;
procedure TfmMain.GetValues;
begin
TempObjectProc(TStringList.Create, TProc<TObject>(procedure (Key: TStringList)
begin
Key.Delimiter := '/';
IniProc(FFileName, procedure (Ini: TIniFile)
var
I: Integer;
Value: String;
begin
for I := 0 to Pred(Config.Strings.Count) do begin
Key.DelimitedText := Config.Strings.Names[I];
if Key.Count >= 2 then begin
Value := Ini.ReadString(Key.Strings[0], Key.Strings[1], '');
if Value.IsEmpty = False then begin
Config.Strings.ValueFromIndex[I] := Value;
end;
end;
end;
end);
end));
end;
Initialization
ConfigName := ChangeFileExt(ParamStr(0), '.ini');
end.
|
unit uPicasaOAuth2;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.OleCtrls,
uPicasaProvider,
uDBForm,
SHDocVw,
MSHTML;
type
TFormPicasaOAuth = class(TDBForm)
WbApplicationRequest: TWebBrowser;
TmrCheckCode: TTimer;
procedure TmrCheckCodeTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FAccessUrl: string;
FApplicationCode: string;
procedure LoadLanguage;
protected
function GetFormID: string; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AccessUrl: string); reintroduce;
property ApplicationCode: string read FApplicationCode;
end;
implementation
{$R *.dfm}
constructor TFormPicasaOAuth.Create(AOwner: TComponent; AccessUrl: string);
begin
FAccessUrl := AccessUrl;
inherited Create(AOwner);
FApplicationCode := '';
end;
procedure TFormPicasaOAuth.FormCreate(Sender: TObject);
begin
LoadLanguage;
WbApplicationRequest.Navigate(FAccessUrl);
end;
function TFormPicasaOAuth.GetFormID: string;
begin
Result := 'Picasa';
end;
procedure TFormPicasaOAuth.LoadLanguage;
begin
Caption := L('Picasa authorisation');
end;
procedure TFormPicasaOAuth.TmrCheckCodeTimer(Sender: TObject);
var
S: string;
P: Integer;
begin
//Success code=4/wt1Yb_mFV9wbyZQ0-uluJFvjwqsC
if WbApplicationRequest.Document <> nil then
begin
S := IHTMLDocument2(WbApplicationRequest.Document).title;
if Pos(AnsiUpperCase('access_denied'), AnsiUpperCase(S)) > 0 then
Close;
if Pos('SUCCESS', AnsiUpperCase(S)) > 0 then
begin
P := Pos('=', S);
if P > 0 then
begin
S := Copy(S, P + 1, Length(S) - P);
FApplicationCode := S;
Close;
end;
end;
end;
end;
end.
|
{ *************************************************** }
{ TAsSearchBox component }
{ written by HADJI BOULANOUAR (Anoirsoft) }
{ }
{ Email : anoirsoft.com@gmail.com }
{ Web : http://www.anoirsoft.com }
{ }
{ *************************************************** }
unit uAsSrchBoxDsgn;
interface
uses
Classes, DesignIntf, DesignEditors, DBReg, System.TypInfo, Vcl.Dialogs , uAsSrchBox;
type
TSearchItemFieldProperty = class(TDataFieldProperty)
public
procedure GetValueList(List: TStrings); override;
end;
TAsSearchBoxEditor=class(TComponentEditor)
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): string; override;
procedure ExecuteVerb(Index: Integer); override;
end;
procedure Register;
implementation
uses
DB;
procedure TSearchItemFieldProperty.GetValueList(List: TStrings);
var
Item: TSearchItem;
ADataSet: TDataSet;
begin
Item := GetComponent(0) as TSearchItem;
ADataSet := TSearchItems(Item.Collection).SourceDATA;
if (ADataSet <> nil) then
ADataSet.GetFieldNames(List);
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(string), TSearchItem, 'FieldName',
TSearchItemFieldProperty);
RegisterComponentEditor(TAsSearchBox, TAsSearchBoxEditor);
end;
{ TAsSearchBoxEditor }
procedure TAsSearchBoxEditor.ExecuteVerb(Index: Integer);
begin
inherited;
case Index of
0: (Component as TAsSearchBox).RetrieveALLFields;
1: ShowMessage('TAsSearchBox component'#10#13+
'written by HADJI BOULANOUAR (Anoirsoft)'#10#13+'Email : anoirsoft.com@gmail.com'#10#13+'Web : http://www.anoirsoft.com' );
end;
end;
function TAsSearchBoxEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := '&Retrieve all fields';
1: Result := '&About';
end;
end;
function TAsSearchBoxEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
end.
|
unit Glass.Blur;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls,
FMX.Graphics, FMX.Effects, Glass;
type
TBlurGlass = class(TGlass)
private
FBlur: TBlurEffect;
function GetSoftness: Single;
procedure SetSoftness(Value: Single);
protected
procedure ProcessChildEffect(const AParentScreenshotBitmap: TBitmap); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Softness: Single read GetSoftness write SetSoftness;
end;
procedure Register;
implementation
uses
FMX.Forms, System.Math, System.Types;
{ TGlass }
constructor TBlurGlass.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// Create blur
FBlur := TBlurEffect.Create(nil);
FBlur.Softness := 0.5;
end;
destructor TBlurGlass.Destroy;
begin
FBlur.Free;
inherited Destroy;
end;
function TBlurGlass.GetSoftness: Single;
begin
Result := FBlur.Softness;
end;
procedure TBlurGlass.SetSoftness(Value: Single);
begin
FBlur.Softness := Value;
end;
procedure TBlurGlass.ProcessChildEffect(const AParentScreenshotBitmap: TBitmap);
begin
inherited;
FBlur.ProcessEffect(Canvas, AParentScreenshotBitmap, FBlur.Softness);
end;
procedure Register;
begin
RegisterComponents('Glass', [TBlurGlass]);
end;
end.
|
unit DrawSpectrumForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,table_func_lib, ExtCtrls, TeeProcs, TeEngine, Chart,Series,colorimetry_lib,
StdCtrls, Buttons;
type
TForm2 = class(TForm)
Chart1: TChart;
Button1: TButton;
SaveDialog1: TSaveDialog;
GroupBox1: TGroupBox;
txtGraphName: TLabeledEdit;
txtXName: TLabeledEdit;
txtYName: TLabeledEdit;
BitBtn1: TBitBtn;
GroupBox2: TGroupBox;
ListBox1: TListBox;
txtDataName: TLabeledEdit;
txtDataXName: TLabeledEdit;
txtDataYName: TLabeledEdit;
BitBtn2: TBitBtn;
txtDescription: TMemo;
Label1: TLabel;
Button2: TButton;
SaveDialog2: TSaveDialog;
Button3: TButton;
OpenDialog1: TOpenDialog;
CheckBox1: TCheckBox;
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Chart1AfterDraw(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure txtGraphNameChange(Sender: TObject);
procedure txtXNameChange(Sender: TObject);
procedure txtYNameChange(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure txtDataNameChange(Sender: TObject);
procedure txtDataXNameChange(Sender: TObject);
procedure txtDataYNameChange(Sender: TObject);
procedure txtDescriptionChange(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
private
{ Private declarations }
series: array of table_func;
col: colorimetry_funcs;
public
{ Public declarations }
visible_only: Boolean;
procedure AddSpectrum(data: table_func);
procedure Clear;
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.AddSpectrum(data: table_func);
var i: Integer;
begin
i:=Length(series);
SetLength(series,i+1);
series[i]:=table_func.Create;
series[i].assign(data);
series[i].normalize;
series[i].chart_series:=TLineSeries.Create(chart1);
series[i].chart_series.ParentChart:=chart1;
if (series[i].title='') then series[i].title:='Series'+IntToStr(i);
series[i].chart_series.Title:=series[i].title;
if (series[i].Xname<>'') then begin
chart1.BottomAxis.Title.Caption:=series[i].Xname;
txtXName.Text:=series[i].Xname;
end;
if (series[i].Yname<>'') then begin
chart1.LeftAxis.Title.Caption:=series[i].Yname;
txtYName.Text:=series[i].Yname;
end;
ListBox1.AddItem(series[i].chart_series.Title,series[i]);
if (ListBox1.Items.Count=1) then begin
ListBox1.ItemIndex:=0;
ListBox1Click(Form2);
end;
// series[i].draw;
end;
procedure TForm2.Clear;
var i:Integer;
begin
for i:=0 to High(series) do begin
series[i].chart_series.Free;
series[i].Free;
end;
SetLength(series,0);
ListBox1.Clear;
end;
procedure TForm2.FormPaint(Sender: TObject);
var i,n: Integer;
begin
n:=Length(Series);
chart1.MarginBottom:=100-(100 div (n+1));
if visible_only then begin
chart1.BottomAxis.Automatic:=false;
chart1.BottomAxis.Maximum:=720;
chart1.BottomAxis.Minimum:=380;
end
else chart1.BottomAxis.Automatic:=true;
for i:=0 to High(Series) do begin
series[i].draw;
end;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
col:=colorimetry_funcs.Create;
checkbox1Click(Form2);
end;
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// col.Free;
end;
procedure TForm2.Chart1AfterDraw(Sender: TObject);
var i,j,hei,offset: Integer;
x: Real;
begin
hei:=chart1.ClientHeight div (Length(form2.series)+1);
offset:=hei div 10;
with chart1 do begin
for j:=0 to High(form2.Series) do begin
col.Clear;
for i:=ChartRect.Left to ChartRect.Right do begin
x:=BottomAxis.CalcPosPoint(i);
col.AddMonochr(i,x,form2.series[j][x]);
end;
for i:=ChartRect.Left to ChartRect.Right do begin
Canvas.Pen.Color:=col.ColorFromTable(i);
Canvas.MoveTo(i,hei*(j+1)+offset);
// Canvas.LineTo(i,ChartRect.Bottom+hei*(j+2)-offset);
Canvas.LineTo(i,hei*(j+2));
end;
Canvas.TextOut(ChartRect.Right+10,(hei*(2*j+3) div 2),form2.series[j].title);
Canvas.Brush.Color:=col.ColorOfRGBSum;
Canvas.FillRect(RECT(ChartRect.Right+10,(hei*(2*j+3) div 2)+offset,ChartRect.Right+10+offset,(hei*(2*j+3) div 2)+2*offset));
Canvas.Rectangle(ChartRect.Right+10,(hei*(2*j+3) div 2)+offset,ChartRect.Right+10+offset,(hei*(2*j+3) div 2)+2*offset);
end;
end;
end;
procedure TForm2.FormDestroy(Sender: TObject);
var i:Integer;
begin
col.Free;
for i:=0 to High(series) do begin
series[i].chart_series.Free;
series[i].Free;
end;
ListBox1.Clear;
SetLength(series,0);
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
if SaveDialog1.Execute then
chart1.SaveToBitmapFile(SaveDialog1.FileName);
end;
procedure TForm2.txtGraphNameChange(Sender: TObject);
begin
chart1.Title.Text.Clear;
chart1.Title.Text.Add(txtGraphName.Text);
end;
procedure TForm2.txtXNameChange(Sender: TObject);
begin
chart1.BottomAxis.Title.Caption:=txtXName.Text;
end;
procedure TForm2.txtYNameChange(Sender: TObject);
begin
chart1.LeftAxis.Title.Caption:=txtYName.Text;
end;
procedure TForm2.ListBox1Click(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
txtDataName.Text:=obj.title;
txtDataXName.Text:=obj.Xname;
txtDataYName.Text:=obj.Yname;
txtDescription.Text:=obj.description;
end;
procedure TForm2.txtDataNameChange(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
obj.title:=txtDataName.Text;
obj.chart_series.Title:=obj.title;
ListBox1.Items[ListBox1.ItemIndex]:=txtDataName.Text;
end;
procedure TForm2.txtDataXNameChange(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
obj.Xname:=txtDataXName.Text;
end;
procedure TForm2.txtDataYNameChange(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
obj.Yname:=txtDataYName.Text;
end;
procedure TForm2.txtDescriptionChange(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
obj.description:=txtDescription.Text;
end;
procedure TForm2.Button2Click(Sender: TObject);
var obj: table_func;
begin
obj:=(ListBox1.items.objects[ListBox1.itemIndex] as table_func);
if SaveDialog2.Execute then obj.SaveToFile(SaveDialog2.FileName);
end;
procedure TForm2.BitBtn2Click(Sender: TObject);
begin
txtXName.Text:=txtDataXName.Text;
txtYName.Text:=txtDataYName.Text;
end;
procedure TForm2.BitBtn1Click(Sender: TObject);
begin
txtDataXName.Text:=txtXName.Text;
txtDataYName.Text:=txtYName.Text;
end;
procedure TForm2.Button3Click(Sender: TObject);
var obj: table_func;
begin
if OpenDialog1.Execute then begin
obj:=table_func.Create(OpenDialog1.FileName);
AddSpectrum(obj);
form2.Refresh;
end;
end;
procedure TForm2.CheckBox1Click(Sender: TObject);
begin
visible_only:=CheckBox1.Checked;
form2.Refresh;
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0031.PAS
Description: Pythagorean Triples
Author: MARK LEWIS
Date: 08-27-93 21:47
*)
Program PYTHAGOREAN_TRIPLES;
{written by Mark Lewis, April 1, 1990}
{developed and written in Turbo Pascal v3.0}
Const
hicnt = 100;
ZERO = 0;
Type
PythagPtr = ^PythagRec; {Pointer to find the Record}
PythagRec = Record {the Record we are storing}
A : Real;
B : Real;
C : Real;
total : Real;
next : PythagPtr {Pointer to next Record in line}
end;
Var
Root : PythagPtr; {the starting point}
QUIT : Boolean;
ch : Char;
Procedure listdispose(Var root : pythagptr);
Var
holder : pythagptr;
begin
if root <> nil then {if we have Records in the list}
Repeat {...}
holder := root^.next; {save location of next Record}
dispose(root); {remove this Record}
root := holder; {go to next Record}
Until root = nil; {Until they are all gone}
end;
Procedure findpythag(Var root : pythagptr);
Var
x,y,z,stored : Integer;
xy,zz,xx,yy : Real;
abandon : Boolean;
workrec : pythagrec;
last,current : pythagptr;
begin
stored := zero; {init count at ZERO}
For z := 1 to hicnt do {start loop 3}
begin
zz := sqr(z); {square loop counter}
if zz < zero then
zz := 65536.0 + zz; {twiddle For negatives}
For y := 1 to hicnt do {start loop 2}
begin
yy := sqr(y); {square loop counter}
if yy < zero then
yy := 65536.0 + yy; {twiddle For negatives}
For x := 1 to hicnt do {start loop 1}
begin
abandon := False; {keep this one}
xx := sqr(x); {square loop counter}
xy := xx + yy; {add sqr(loop2) and sqr(loop1)}
if not ((xy <> zz) or ((xy = zz) and (xy = 1.0))) then
begin
With workrec do
begin
a := x; {put them into our storage Record}
b := y;
c := z;
total := zz;
end;
if root = nil then {is this the first Record?}
begin
new(root); {allocate space}
workrec.next := nil; {anchor the Record}
root^ := workrec; {store it}
stored := succ(stored); {how many found?}
end
else {this is not the first Record}
begin
current := root; {save where we are now}
Repeat {walk Records looking For dups}
if (current^.total = workrec.total) then
abandon := True; {is this one a dup?}{abandon it}
last := current; {save where we are}
current := current^.next {go to next Record}
Until (current = nil) or abandon;
if not abandon then {save this one?}
begin
{we're going to INSERT this Record into the}
{line between the ones greater than and less}
{than the A Var in the Record}
{ie: 5,12,13 goes between 3,4,5 and 6,8,10}
if root^.a > workrec.a then
begin
new(root); {allocate mem For this one}
workrec.next := last; {point to next rec}
root^ := workrec; {save this one}
stored := succ(stored); {how many found?}
end
else {insert between last^.next and current}
begin
new(last^.next); {allocate memory}
workrec.next := current; {point to current}
last^.next^ := workrec; {save this one}
stored := succ(stored); {how many found?}
end;
end;
end;
end;
end;
end;
end;
Writeln('I have found and stored ',stored,' Pythagorean Triples.');
end;
Procedure showRecord(workrec : pythagrec);
begin
With workrec do
begin
Writeln('A = ',a:6:0,' ',sqr(a):6:0);
Writeln('B = ',b:6:0,' ',sqr(b):6:0,' ',sqr(a)+sqr(b):6:0);
Writeln('C = ',c:6:0,' ',sqr(c):6:0,' <-^');
end
end;
Procedure viewlist(root : pythagptr);
Var
(*i : Integer;*)
current : pythagptr;
begin
if root = nil then
begin
Writeln('<< Your list is empty! >>');
Write('>> Press (CR) to continue: ');
readln;
end
else
begin
Writeln('Viewing Records');
current := root;
While current <> nil do
begin
showRecord(current^);
Write('Press (CR) to view next Record. . . ');
readln;
current := current^.next
end;
end
end;
begin
Writeln('PYTHAGOREAN TRIPLES');
Writeln('-------------------');
Writeln;
Writeln('Remember the formula For a Right Triangle?');
Writeln('A squared + B squared = C squared');
Writeln;
Writeln('I call the set of numbers that fits this formula');
Writeln(' Pythagorean Triples');
Writeln;
Writeln('This Program Uses a "brute force" method of finding all');
Writeln('the Pythagorean Triples between 1 and 100');
Writeln;
root := nil;
quit := False;
Repeat
Writeln('Command -> [F]ind, [V]iew, [D]ispose, [Q]uit ');
readln(ch);
Case ch of
'q','Q' : quit := True;
'f','F' : findpythag(root);
'v','V' : viewlist(root);
'd','D' : listdispose(root);
end;
Until quit;
if root <> nil then
listdispose(root);
Writeln('Normal Program Termination');
end.
|
unit MeshProcessingBase;
interface
uses BasicMathsTypes, BasicDataTypes, LOD, Mesh;
type
TMeshProcessingBase = class
protected
FLOD: TLOD;
procedure DoMeshProcessing(var _Mesh: TMesh); virtual; abstract;
procedure BackupVector2f(const _Source: TAVector2f; var _Destination: TAVector2f);
procedure BackupVector3f(const _Source: TAVector3f; var _Destination: TAVector3f);
procedure BackupVector4f(const _Source: TAVector4f; var _Destination: TAVector4f);
function GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer;
function FindMeshCenter(var _Vertices: TAVector3f): TVector3f;
procedure FilterAndFixColours(var _Colours: TAVector4f);
public
constructor Create(var _LOD: TLOD); virtual;
procedure Execute;
end;
implementation
uses Math;
constructor TMeshProcessingBase.Create(var _LOD: TLOD);
begin
FLOD := _LOD;
end;
procedure TMeshProcessingBase.Execute;
var
i: integer;
begin
for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do
begin
DoMeshProcessing(FLOD.Mesh[i]);
end;
end;
function TMeshProcessingBase.GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer;
begin
Result := _VertexID;
while Result > _MaxVertexID do
begin
Result := _VertexEquivalences[Result];
end;
end;
procedure TMeshProcessingBase.BackupVector2f(const _Source: TAVector2f; var _Destination: TAVector2f);
var
i : integer;
begin
for i := Low(_Source) to High(_Source) do
begin
_Destination[i].U := _Source[i].U;
_Destination[i].V := _Source[i].V;
end;
end;
procedure TMeshProcessingBase.BackupVector3f(const _Source: TAVector3f; var _Destination: TAVector3f);
var
i : integer;
begin
for i := Low(_Source) to High(_Source) do
begin
_Destination[i].X := _Source[i].X;
_Destination[i].Y := _Source[i].Y;
_Destination[i].Z := _Source[i].Z;
end;
end;
function TMeshProcessingBase.FindMeshCenter(var _Vertices: TAVector3f): TVector3f;
var
v : integer;
MaxPoint,MinPoint: TVector3f;
begin
if High(_Vertices) >= 0 then
begin
MinPoint.X := _Vertices[0].X;
MinPoint.Y := _Vertices[0].Y;
MinPoint.Z := _Vertices[0].Z;
MaxPoint.X := _Vertices[0].X;
MaxPoint.Y := _Vertices[0].Y;
MaxPoint.Z := _Vertices[0].Z;
// Find mesh scope.
for v := 1 to High(_Vertices) do
begin
if (_Vertices[v].X < MinPoint.X) and (_Vertices[v].X <> -NAN) then
begin
MinPoint.X := _Vertices[v].X;
end;
if _Vertices[v].X > MaxPoint.X then
begin
MaxPoint.X := _Vertices[v].X;
end;
if (_Vertices[v].Y < MinPoint.Y) and (_Vertices[v].Y <> -NAN) then
begin
MinPoint.Y := _Vertices[v].Y;
end;
if _Vertices[v].Y > MaxPoint.Y then
begin
MaxPoint.Y := _Vertices[v].Y;
end;
if (_Vertices[v].Z < MinPoint.Z) and (_Vertices[v].Z <> -NAN) then
begin
MinPoint.Z := _Vertices[v].Z;
end;
if _Vertices[v].Z > MaxPoint.Z then
begin
MaxPoint.Z := _Vertices[v].Z;
end;
end;
Result.X := (MinPoint.X + MaxPoint.X) / 2;
Result.Y := (MinPoint.Y + MaxPoint.Y) / 2;
Result.Z := (MinPoint.Z + MaxPoint.Z) / 2;
end
else
begin
Result.X := 0;
Result.Y := 0;
Result.Z := 0;
end;
end;
procedure TMeshProcessingBase.FilterAndFixColours(var _Colours: TAVector4f);
var
i : integer;
begin
for i := Low(_Colours) to High(_Colours) do
begin
// Avoid problematic colours:
if _Colours[i].X < 0 then
_Colours[i].X := 0
else if _Colours[i].X > 1 then
_Colours[i].X := 1;
if _Colours[i].Y < 0 then
_Colours[i].Y := 0
else if _Colours[i].Y > 1 then
_Colours[i].Y := 1;
if _Colours[i].Z < 0 then
_Colours[i].Z := 0
else if _Colours[i].Z > 1 then
_Colours[i].Z := 1;
if _Colours[i].W < 0 then
_Colours[i].W := 0
else if _Colours[i].W > 1 then
_Colours[i].W := 1;
end;
end;
procedure TMeshProcessingBase.BackupVector4f(const _Source: TAVector4f; var _Destination: TAVector4f);
var
i : integer;
begin
for i := Low(_Source) to High(_Source) do
begin
_Destination[i].X := _Source[i].X;
_Destination[i].Y := _Source[i].Y;
_Destination[i].Z := _Source[i].Z;
_Destination[i].W := _Source[i].W;
end;
end;
end.
|
unit pkcs11_attribute;
interface
uses
Controls,
pkcs11_api, pkcs11t;
type
PCK_OBJECT_CLASS = ^CK_OBJECT_CLASS;
PCK_BBOOL = ^CK_BBOOL;
PCK_CERTIFICATE_TYPE = ^CK_CERTIFICATE_TYPE;
PCK_ULONG = ^CK_ULONG;
PCK_KEY_TYPE = ^CK_KEY_TYPE;
PCK_DATE = ^CK_DATE;
PCK_MECHANISM_TYPE = ^CK_MECHANISM_TYPE;
PCK_ATTRIBUTE_PTR = ^CK_ATTRIBUTE_PTR;
PCK_HW_FEATURE_TYPE = ^CK_HW_FEATURE_TYPE;
TAttributeDataType = (
adtObjClass, // CK_OBJECT_CLASS
adtBoolean, // CK_BBOOL
adtString, // RFC 2279 string
adtBigInteger, // Big integer
adtByteArray, // byte array
adtCertificateType, // CK_CERTIFICATE_TYPE
adtNumber, // CK_ULONG
adtKeyType, // CK_KEY_TYPE
adtDate, // CK_DATE
adtMechanismType, // CK_MECHANISM_TYPE
adtMechanismTypeSet, // CK_MECHANISM_TYPE_PTR
adtUnknown, // ???
adtAttributeSet, // CK_ATTRIBUTE_PTR
adtHWFeatureType // CK_HW_FEATURE_TYPE
);
TPKCS11Attribute = class (TPKCS11API)
private
FAttribType: CK_ATTRIBUTE_TYPE;
FLength: Cardinal;
FRawData: Ansistring;
function MapPKCS11AttrTypeToDelphiAttrType(pkcs11AttrType: CK_ATTRIBUTE_TYPE):
TAttributeDataType;
protected
function GetAttribTypeStr(): String;
function GetLength(): Cardinal;
procedure SetAttrStruct(struct: CK_ATTRIBUTE);
function ObjectClassToString(objClass: CK_OBJECT_CLASS): String;
function HWFeatureTypeToString(HWFeatureType: CK_HW_FEATURE_TYPE): String;
function KeyTypeToString(keyType: CK_KEY_TYPE): String;
function CertificateTypeToString(certType: CK_CERTIFICATE_TYPE): String;
function CopyBinary(ptr: PByte; len: Integer): Ansistring;
// Get methods...
function GetValueAsObjClass(): CK_OBJECT_CLASS;
function GetValueAsBoolean(): Boolean;
function GetValueAsString(): Ansistring;
function GetValueAsBigInteger(): Ansistring;
function GetValueAsByteArray(): Ansistring;
function GetValueAsCertificateType(): CK_CERTIFICATE_TYPE;
function GetValueAsNumber(): CK_ULONG;
function GetValueAsKeyType(): CK_KEY_TYPE;
function GetValueAsDate(): TDate;
function GetValueAsMechanismType(): CK_MECHANISM_TYPE;
// function GetValueAsMechanismTypeSet(): array of CK_MECHANISM_TYPE;
// function GetValueAsAttributeSet(): array of CK_ATTRIBUTE_TYPE;
function GetValueAsHWFeatureType(): CK_HW_FEATURE_TYPE;
// Set methods...
procedure SetValueAsObjClass(Value: CK_OBJECT_CLASS);
procedure SetValueAsBoolean(Value: Boolean);
procedure SetValueAsString(Value: Ansistring);
procedure SetValueAsBigInteger(Value: Ansistring);
procedure SetValueAsByteArray(Value: Ansistring);
procedure SetValueAsCertificateType(Value: CK_CERTIFICATE_TYPE);
procedure SetValueAsNumber(Value: CK_ULONG);
procedure SetValueAsKeyType(Value: CK_KEY_TYPE);
procedure SetValueAsDate(Value: TDate);
procedure SetValueAsMechanismType(Value: CK_MECHANISM_TYPE);
// procedure SetValueAsMechanismTypeSet(value: array of CK_MECHANISM_TYPE);
// procedure SetValueAsAttributeSet(value: array of CK_ATTRIBUTE_TYPE);
procedure SetValueAsHWFeatureType(Value: CK_HW_FEATURE_TYPE);
function DisplayValue_BigInteger(): String;
public
PKCS11API: TObject;
property AttribType: CK_ATTRIBUTE_TYPE Read FAttribType Write FAttribType;
property AttribTypeStr: String Read GetAttribTypeStr;
property AttrLength: Cardinal Read GetLength;
property ValueAsRawData: Ansistring Read FRawData Write FRawData;
function DisplayValue(): String;
function AttributeTypeToString(attrType: CK_ATTRIBUTE_TYPE): String;
property AttrStruct: CK_ATTRIBUTE Write SetAttrStruct;
// Note: Only one of the following members will be populated, depending on
// FAttribType
property ValueAsObjClass: CK_OBJECT_CLASS Read GetValueAsObjClass Write SetValueAsObjClass;
property ValueAsBoolean: Boolean Read GetValueAsBoolean Write SetValueAsBoolean;
property ValueAsString: Ansistring Read GetValueAsString Write SetValueAsString;
property ValueAsBigInteger: Ansistring Read GetValueAsBigInteger Write SetValueAsBigInteger;
property ValueAsByteArray: Ansistring Read GetValueAsByteArray Write SetValueAsByteArray;
property ValueAsCertificateType: CK_CERTIFICATE_TYPE
Read GetValueAsCertificateType Write SetValueAsCertificateType;
property ValueAsNumber: Cardinal Read GetValueAsNumber Write SetValueAsNumber;
property ValueAsKeyType: CK_KEY_TYPE Read GetValueAsKeyType Write SetValueAsKeyType;
property ValueAsDate: TDate Read GetValueAsDate Write SetValueAsDate;
property ValueAsMechanismType: CK_MECHANISM_TYPE
Read GetValueAsMechanismType Write SetValueAsMechanismType;
// property ValueAsMechanismTypeSet: array of CK_MECHANISM_TYPE read GetValueAsMechanismTypeSet write SetValueAsMechanismTypeSet;
// property ValueAsAttributeSet: array of CK_ATTRIBUTE_TYPE read GetValueAsAttributeSet write SetValueAsAttributeSet;
property ValueAsHWFeatureType: CK_HW_FEATURE_TYPE
Read GetValueAsHWFeatureType Write SetValueAsHWFeatureType;
end;
// NOTICE: When an attribute template is destroyed, all attribute objects it
// contains will also be destroyed.
TPKCS11AttributeTemplate = class
protected
FAttributes: array of TPKCS11Attribute;
function GetCount(): Integer;
function GetAttribute(idx: Integer): TPKCS11Attribute;
procedure SetAttribute(idx: Integer; attr: TPKCS11Attribute);
public
property Count: Integer Read GetCount;
property Attribute[idx: Integer]: TPKCS11Attribute Read GetAttribute Write SetAttribute;
constructor Create();
destructor Destroy(); override;
// Add an existing attribute/add a new attribute, return it
function Add(attr: TPKCS11Attribute): TPKCS11Attribute; overload;
function Add(): TPKCS11Attribute; overload;
end;
implementation
uses
DateUtils,
SDUGeneral, SDUi18n,
SysUtils;
function TPKCS11Attribute.MapPKCS11AttrTypeToDelphiAttrType(pkcs11AttrType: CK_ATTRIBUTE_TYPE):
TAttributeDataType;
begin
Result := adtUnknown;
case pkcs11AttrType of
// The following attribute types are defined:
CKA_CLASS: Result := adtObjClass;
CKA_TOKEN: Result := adtBoolean;
CKA_PRIVATE: Result := adtBoolean;
CKA_LABEL: Result := adtString;
CKA_APPLICATION: Result := adtString;
CKA_VALUE: Result := adtByteArray; // or could be adtBigInteger
// CKA_OBJECT_ID is new for v2.10
CKA_OBJECT_ID: Result := adtByteArray;
CKA_CERTIFICATE_TYPE: Result := adtCertificateType;
CKA_ISSUER: Result := adtByteArray;
CKA_SERIAL_NUMBER: Result := adtByteArray;
// CKA_AC_ISSUER, CKA_OWNER, and CKA_ATTR_TYPES are new
// for v2.10
CKA_AC_ISSUER: Result := adtByteArray;
CKA_OWNER: Result := adtByteArray;
CKA_ATTR_TYPES: Result := adtByteArray;
// CKA_TRUSTED is new for v2.11
CKA_TRUSTED: Result := adtBoolean;
// CKA_CERTIFICATE_CATEGORY ...
// CKA_CHECK_VALUE are new for v2.20
CKA_CERTIFICATE_CATEGORY: Result := adtNumber;
CKA_JAVA_MIDP_SECURITY_DOMAIN: Result := adtByteArray;
CKA_URL: Result := adtString;
CKA_HASH_OF_SUBJECT_PUBLIC_KEY: Result := adtByteArray;
CKA_HASH_OF_ISSUER_PUBLIC_KEY: Result := adtByteArray;
CKA_CHECK_VALUE: Result := adtByteArray;
CKA_KEY_TYPE: Result := adtKeyType;
CKA_SUBJECT: Result := adtByteArray;
CKA_ID: Result := adtByteArray;
CKA_SENSITIVE: Result := adtBoolean;
CKA_ENCRYPT: Result := adtBoolean;
CKA_DECRYPT: Result := adtBoolean;
CKA_WRAP: Result := adtBoolean;
CKA_UNWRAP: Result := adtBoolean;
CKA_SIGN: Result := adtBoolean;
CKA_SIGN_RECOVER: Result := adtBoolean;
CKA_VERIFY: Result := adtBoolean;
CKA_VERIFY_RECOVER: Result := adtBoolean;
CKA_DERIVE: Result := adtBoolean;
CKA_START_DATE: Result := adtDate;
CKA_END_DATE: Result := adtDate;
CKA_MODULUS: Result := adtBigInteger;
CKA_MODULUS_BITS: Result := adtNumber;
CKA_PUBLIC_EXPONENT: Result := adtBigInteger;
CKA_PRIVATE_EXPONENT: Result := adtBigInteger;
CKA_PRIME_1: Result := adtBigInteger;
CKA_PRIME_2: Result := adtBigInteger;
CKA_EXPONENT_1: Result := adtBigInteger;
CKA_EXPONENT_2: Result := adtBigInteger;
CKA_COEFFICIENT: Result := adtBigInteger;
CKA_PRIME: Result := adtBigInteger;
CKA_SUBPRIME: Result := adtBigInteger;
CKA_BASE: Result := adtBigInteger;
// CKA_PRIME_BITS and CKA_SUB_PRIME_BITS are new for v2.11
CKA_PRIME_BITS: Result := adtNumber;
CKA_SUBPRIME_BITS: Result := adtNumber;
// Value of CKA_SUBPRIME_BITS = CKA_SUB_PRIME_BITS
// CKA_SUB_PRIME_BITS: result := adtNumber;
// (To retain backwards-compatibility)
CKA_VALUE_BITS: Result := adtNumber;
CKA_VALUE_LEN: Result := adtNumber;
// CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE,
// CKA_ALWAYS_SENSITIVE, CKA_MODIFIABLE, CKA_ECDSA_PARAMS,
// and CKA_EC_POINT are new for v2.0
CKA_EXTRACTABLE: Result := adtBoolean;
CKA_LOCAL: Result := adtBoolean;
CKA_NEVER_EXTRACTABLE: Result := adtBoolean;
CKA_ALWAYS_SENSITIVE: Result := adtBoolean;
// CKA_KEY_GEN_MECHANISM is new for v2.11
CKA_KEY_GEN_MECHANISM: Result := adtMechanismType;
CKA_MODIFIABLE: Result := adtBoolean;
// CKA_ECDSA_PARAMS is deprecated in v2.11,
// CKA_EC_PARAMS is preferred.
CKA_ECDSA_PARAMS: Result := adtByteArray;
// Value of CKA_ECDSA_PARAMS = CKA_EC_PARAMS
// CKA_EC_PARAMS: result := adtByteArray;
CKA_EC_POINT: Result := adtByteArray;
// CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
// are new for v2.10. Deprecated in v2.11 and onwards.
CKA_SECONDARY_AUTH: Result := adtUnknown;
CKA_AUTH_PIN_FLAGS: Result := adtUnknown;
// CKA_ALWAYS_AUTHENTICATE ...
// CKA_UNWRAP_TEMPLATE are new for v2.20
CKA_ALWAYS_AUTHENTICATE: Result := adtBoolean;
CKA_WRAP_WITH_TRUSTED: Result := adtBoolean;
CKA_WRAP_TEMPLATE: Result := adtAttributeSet;
CKA_UNWRAP_TEMPLATE: Result := adtAttributeSet;
// CKA_OTP... atttributes are new for PKCS #11 v2.20 amendment 3.
CKA_OTP_FORMAT: Result := adtUnknown;
CKA_OTP_LENGTH: Result := adtUnknown;
CKA_OTP_TIME_INTERVAL: Result := adtUnknown;
CKA_OTP_USER_FRIENDLY_MODE: Result := adtUnknown;
CKA_OTP_CHALLENGE_REQUIREMENT: Result := adtUnknown;
CKA_OTP_TIME_REQUIREMENT: Result := adtUnknown;
CKA_OTP_COUNTER_REQUIREMENT: Result := adtUnknown;
CKA_OTP_PIN_REQUIREMENT: Result := adtUnknown;
CKA_OTP_COUNTER: Result := adtUnknown;
CKA_OTP_TIME: Result := adtUnknown;
CKA_OTP_USER_IDENTIFIER: Result := adtUnknown;
CKA_OTP_SERVICE_IDENTIFIER: Result := adtUnknown;
CKA_OTP_SERVICE_LOGO: Result := adtUnknown;
CKA_OTP_SERVICE_LOGO_TYPE: Result := adtUnknown;
// CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT, and CKA_HAS_RESET
// are new for v2.10
CKA_HW_FEATURE_TYPE: Result := adtHWFeatureType;
CKA_RESET_ON_INIT: Result := adtBoolean;
CKA_HAS_RESET: Result := adtBoolean;
// The following attributes are new for v2.20
CKA_PIXEL_X: Result := adtNumber;
CKA_PIXEL_Y: Result := adtNumber;
CKA_RESOLUTION: Result := adtNumber;
CKA_CHAR_ROWS: Result := adtNumber;
CKA_CHAR_COLUMNS: Result := adtNumber;
CKA_COLOR: Result := adtBoolean;
CKA_BITS_PER_PIXEL: Result := adtNumber;
CKA_CHAR_SETS: Result := adtString;
CKA_ENCODING_METHODS: Result := adtString;
CKA_MIME_TYPES: Result := adtString;
CKA_MECHANISM_TYPE: Result := adtMechanismType;
CKA_REQUIRED_CMS_ATTRIBUTES: Result := adtByteArray;
CKA_DEFAULT_CMS_ATTRIBUTES: Result := adtByteArray;
CKA_SUPPORTED_CMS_ATTRIBUTES: Result := adtByteArray;
CKA_ALLOWED_MECHANISMS: Result := adtMechanismTypeSet;
CKA_VENDOR_DEFINED: Result := adtUnknown;
end;
end;
// Note: This function is a slightly modified version of
// SDUGeneral.SDUPrettyPrintHexStrSimple(...)
function TPKCS11Attribute.DisplayValue_BigInteger(): String;
var
i: Integer;
useBigInteger: String;
begin
Result := '0x';
// If the BigInteger has no data, render as "0" (zero)
useBigInteger := ValueAsBigInteger;
if (System.length(useBigInteger) = 0) then begin
useBigInteger := #0;
end;
for i := 1 to System.length(useBigInteger) do begin
Result := Result + inttohex(Ord(useBigInteger[i]), 2);
end;
end;
function TPKCS11Attribute.DisplayValue(): String;
begin
Result := '<unhandled attrib type>';
case MapPKCS11AttrTypeToDelphiAttrType(AttribType) of
adtObjClass: Result := ObjectClassToString(ValueAsObjClass);
adtBoolean: Result := SDUBoolToStr(ValueAsBoolean);
adtString: Result := ValueAsString;
adtBigInteger: Result := DisplayValue_BigInteger();
adtByteArray: Result := SDUPrettyPrintHexStrSimple(ValueAsByteArray);
adtCertificateType: Result := CertificateTypeToString(ValueAsCertificateType);
adtNumber: Result := IntToStr(ValueAsNumber);
adtKeyType: Result := KeyTypeToString(ValueAsKeyType);
adtDate:
begin
Result := '<no date>';
if (ValueAsDate <> 0) then begin
Result := DateToStr(ValueAsDate);
end;
end;
adtMechanismType: Result := IntToStr(ValueAsMechanismType);
adtMechanismTypeSet: Result := '<Mechanism set>';
adtAttributeSet: Result := '<Attribute set>';
adtHWFeatureType: Result := HWFeatureTypeToString(ValueAsHWFeatureType);
end;
end;
function TPKCS11Attribute.GetAttribTypeStr(): String;
begin
Result := AttributeTypeToString(FAttribType);
end;
function TPKCS11Attribute.AttributeTypeToString(attrType: CK_ATTRIBUTE_TYPE): String;
begin
Result := RS_UNKNOWN;
case attrType of
CKA_CLASS: Result := 'CKA_CLASS';
CKA_TOKEN: Result := 'CKA_TOKEN';
CKA_PRIVATE: Result := 'CKA_PRIVATE';
CKA_LABEL: Result := 'CKA_LABEL';
CKA_APPLICATION: Result := 'CKA_APPLICATION';
CKA_VALUE: Result := 'CKA_VALUE';
CKA_OBJECT_ID: Result := 'CKA_OBJECT_ID';
CKA_CERTIFICATE_TYPE: Result := 'CKA_CERTIFICATE_TYPE';
CKA_ISSUER: Result := 'CKA_ISSUER';
CKA_SERIAL_NUMBER: Result := 'CKA_SERIAL_NUMBER';
CKA_AC_ISSUER: Result := 'CKA_AC_ISSUER';
CKA_OWNER: Result := 'CKA_OWNER';
CKA_ATTR_TYPES: Result := 'CKA_ATTR_TYPES';
CKA_TRUSTED: Result := 'CKA_TRUSTED';
CKA_CERTIFICATE_CATEGORY: Result := 'CKA_CERTIFICATE_CATEGORY';
CKA_JAVA_MIDP_SECURITY_DOMAIN: Result := 'CKA_JAVA_MIDP_SECURITY_DOMAIN';
CKA_URL: Result := 'CKA_URL';
CKA_HASH_OF_SUBJECT_PUBLIC_KEY: Result := 'CKA_HASH_OF_SUBJECT_PUBLIC_KEY';
CKA_HASH_OF_ISSUER_PUBLIC_KEY: Result := 'CKA_HASH_OF_ISSUER_PUBLIC_KEY';
CKA_CHECK_VALUE: Result := 'CKA_CHECK_VALUE';
CKA_KEY_TYPE: Result := 'CKA_KEY_TYPE';
CKA_SUBJECT: Result := 'CKA_SUBJECT';
CKA_ID: Result := 'CKA_ID';
CKA_SENSITIVE: Result := 'CKA_SENSITIVE';
CKA_ENCRYPT: Result := 'CKA_ENCRYPT';
CKA_DECRYPT: Result := 'CKA_DECRYPT';
CKA_WRAP: Result := 'CKA_WRAP';
CKA_UNWRAP: Result := 'CKA_UNWRAP';
CKA_SIGN: Result := 'CKA_SIGN';
CKA_SIGN_RECOVER: Result := 'CKA_SIGN_RECOVER';
CKA_VERIFY: Result := 'CKA_VERIFY';
CKA_VERIFY_RECOVER: Result := 'CKA_VERIFY_RECOVER';
CKA_DERIVE: Result := 'CKA_DERIVE';
CKA_START_DATE: Result := 'CKA_START_DATE';
CKA_END_DATE: Result := 'CKA_END_DATE';
CKA_MODULUS: Result := 'CKA_MODULUS';
CKA_MODULUS_BITS: Result := 'CKA_MODULUS_BITS';
CKA_PUBLIC_EXPONENT: Result := 'CKA_PUBLIC_EXPONENT';
CKA_PRIVATE_EXPONENT: Result := 'CKA_PRIVATE_EXPONENT';
CKA_PRIME_1: Result := 'CKA_PRIME_1';
CKA_PRIME_2: Result := 'CKA_PRIME_2';
CKA_EXPONENT_1: Result := 'CKA_EXPONENT_1';
CKA_EXPONENT_2: Result := 'CKA_EXPONENT_2';
CKA_COEFFICIENT: Result := 'CKA_COEFFICIENT';
CKA_PRIME: Result := 'CKA_PRIME';
CKA_SUBPRIME: Result := 'CKA_SUBPRIME';
CKA_BASE: Result := 'CKA_BASE';
CKA_PRIME_BITS: Result := 'CKA_PRIME_BITS';
CKA_SUBPRIME_BITS: Result := 'CKA_SUBPRIME_BITS';
//CKA_SUB_PRIME_BITS: result := 'CKA_SUB_PRIME_BITS';
CKA_VALUE_BITS: Result := 'CKA_VALUE_BITS';
CKA_VALUE_LEN: Result := 'CKA_VALUE_LEN';
CKA_EXTRACTABLE: Result := 'CKA_EXTRACTABLE';
CKA_LOCAL: Result := 'CKA_LOCAL';
CKA_NEVER_EXTRACTABLE: Result := 'CKA_NEVER_EXTRACTABLE';
CKA_ALWAYS_SENSITIVE: Result := 'CKA_ALWAYS_SENSITIVE';
CKA_KEY_GEN_MECHANISM: Result := 'CKA_KEY_GEN_MECHANISM';
CKA_MODIFIABLE: Result := 'CKA_MODIFIABLE';
CKA_ECDSA_PARAMS: Result := 'CKA_ECDSA_PARAMS';
//CKA_EC_PARAMS: result := 'CKA_EC_PARAMS';
CKA_EC_POINT: Result := 'CKA_EC_POINT';
CKA_SECONDARY_AUTH: Result := 'CKA_SECONDARY_AUTH';
CKA_AUTH_PIN_FLAGS: Result := 'CKA_AUTH_PIN_FLAGS';
CKA_ALWAYS_AUTHENTICATE: Result := 'CKA_ALWAYS_AUTHENTICATE';
CKA_WRAP_WITH_TRUSTED: Result := 'CKA_WRAP_WITH_TRUSTED';
CKA_WRAP_TEMPLATE: Result := 'CKA_WRAP_TEMPLATE';
CKA_UNWRAP_TEMPLATE: Result := 'CKA_UNWRAP_TEMPLATE';
CKA_OTP_FORMAT: Result := 'CKA_OTP_FORMAT';
CKA_OTP_LENGTH: Result := 'CKA_OTP_LENGTH';
CKA_OTP_TIME_INTERVAL: Result := 'CKA_OTP_TIME_INTERVAL';
CKA_OTP_USER_FRIENDLY_MODE: Result := 'CKA_OTP_USER_FRIENDLY_MODE';
CKA_OTP_CHALLENGE_REQUIREMENT: Result := 'CKA_OTP_CHALLENGE_REQUIREMENT';
CKA_OTP_TIME_REQUIREMENT: Result := 'CKA_OTP_TIME_REQUIREMENT';
CKA_OTP_COUNTER_REQUIREMENT: Result := 'CKA_OTP_COUNTER_REQUIREMENT';
CKA_OTP_PIN_REQUIREMENT: Result := 'CKA_OTP_PIN_REQUIREMENT';
CKA_OTP_COUNTER: Result := 'CKA_OTP_COUNTER';
CKA_OTP_TIME: Result := 'CKA_OTP_TIME';
CKA_OTP_USER_IDENTIFIER: Result := 'CKA_OTP_USER_IDENTIFIER';
CKA_OTP_SERVICE_IDENTIFIER: Result := 'CKA_OTP_SERVICE_IDENTIFIER';
CKA_OTP_SERVICE_LOGO: Result := 'CKA_OTP_SERVICE_LOGO';
CKA_OTP_SERVICE_LOGO_TYPE: Result := 'CKA_OTP_SERVICE_LOGO_TYPE';
CKA_HW_FEATURE_TYPE: Result := 'CKA_HW_FEATURE_TYPE';
CKA_RESET_ON_INIT: Result := 'CKA_RESET_ON_INIT';
CKA_HAS_RESET: Result := 'CKA_HAS_RESET';
CKA_PIXEL_X: Result := 'CKA_PIXEL_X';
CKA_PIXEL_Y: Result := 'CKA_PIXEL_Y';
CKA_RESOLUTION: Result := 'CKA_RESOLUTION';
CKA_CHAR_ROWS: Result := 'CKA_CHAR_ROWS';
CKA_CHAR_COLUMNS: Result := 'CKA_CHAR_COLUMNS';
CKA_COLOR: Result := 'CKA_COLOR';
CKA_BITS_PER_PIXEL: Result := 'CKA_BITS_PER_PIXEL';
CKA_CHAR_SETS: Result := 'CKA_CHAR_SETS';
CKA_ENCODING_METHODS: Result := 'CKA_ENCODING_METHODS';
CKA_MIME_TYPES: Result := 'CKA_MIME_TYPES';
CKA_MECHANISM_TYPE: Result := 'CKA_MECHANISM_TYPE';
CKA_REQUIRED_CMS_ATTRIBUTES: Result := 'CKA_REQUIRED_CMS_ATTRIBUTES';
CKA_DEFAULT_CMS_ATTRIBUTES: Result := 'CKA_DEFAULT_CMS_ATTRIBUTES';
CKA_SUPPORTED_CMS_ATTRIBUTES: Result := 'CKA_SUPPORTED_CMS_ATTRIBUTES';
CKA_ALLOWED_MECHANISMS: Result := 'CKA_ALLOWED_MECHANISMS';
CKA_VENDOR_DEFINED: Result := 'CKA_VENDOR_DEFINED';
end;
end;
function TPKCS11Attribute.GetLength(): Cardinal;
begin
Result := FLength;
end;
function TPKCS11Attribute.CopyBinary(ptr: PByte; len: Integer): Ansistring;
var
i: Integer;
begin
Result := '';
for i := 0 to (len - 1) do begin
Result := Result + Ansichar(PByte(ptr)^);
Inc(ptr);
end;
end;
procedure TPKCS11Attribute.SetAttrStruct(struct: CK_ATTRIBUTE);
begin
FAttribType := struct.attrType;
FLength := struct.ulValueLen;
FRawData := CopyBinary(struct.pValue, struct.ulValueLen);
end;
function TPKCS11Attribute.ObjectClassToString(objClass: CK_OBJECT_CLASS): String;
begin
Result := RS_UNKNOWN;
case objClass of
CKO_DATA: Result := 'CKO_DATA';
CKO_CERTIFICATE: Result := 'CKO_CERTIFICATE';
CKO_PUBLIC_KEY: Result := 'CKO_PUBLIC_KEY';
CKO_PRIVATE_KEY: Result := 'CKO_PRIVATE_KEY';
CKO_SECRET_KEY: Result := 'CKO_SECRET_KEY';
CKO_HW_FEATURE: Result := 'CKO_HW_FEATURE';
CKO_DOMAIN_PARAMETERS: Result := 'CKO_DOMAIN_PARAMETERS';
CKO_MECHANISM: Result := 'CKO_MECHANISM';
CKO_OTP_KEY: Result := 'CKO_OTP_KEY';
CKO_VENDOR_DEFINED: Result := 'CKO_VENDOR_DEFINED';
end;
end;
function TPKCS11Attribute.HWFeatureTypeToString(HWFeatureType: CK_HW_FEATURE_TYPE): String;
begin
Result := RS_UNKNOWN;
case HWFeatureType of
CKH_MONOTONIC_COUNTER: Result := 'CKH_MONOTONIC_COUNTER';
CKH_CLOCK: Result := 'CKH_CLOCK';
CKH_USER_INTERFACE: Result := 'CKH_USER_INTERFACE';
CKH_VENDOR_DEFINED: Result := 'CKH_VENDOR_DEFINED';
end;
end;
function TPKCS11Attribute.KeyTypeToString(keyType: CK_KEY_TYPE): String;
begin
Result := RS_UNKNOWN;
case keyType of
CKK_RSA: Result := 'CKK_RSA';
CKK_DSA: Result := 'CKK_DSA';
CKK_DH: Result := 'CKK_DH';
CKK_ECDSA: Result := 'CKK_ECDSA';
//CKK_EC: result := 'CKK_EC';
CKK_X9_42_DH: Result := 'CKK_X9_42_DH';
CKK_KEA: Result := 'CKK_KEA';
CKK_GENERIC_SECRET: Result := 'CKK_GENERIC_SECRET';
CKK_RC2: Result := 'CKK_RC2';
CKK_RC4: Result := 'CKK_RC4';
CKK_DES: Result := 'CKK_DES';
CKK_DES2: Result := 'CKK_DES2';
CKK_DES3: Result := 'CKK_DES3';
CKK_CAST: Result := 'CKK_CAST';
CKK_CAST3: Result := 'CKK_CAST3';
CKK_CAST5: Result := 'CKK_CAST5';
//CKK_CAST128: result := 'CKK_CAST128';
CKK_RC5: Result := 'CKK_RC5';
CKK_IDEA: Result := 'CKK_IDEA';
CKK_SKIPJACK: Result := 'CKK_SKIPJACK';
CKK_BATON: Result := 'CKK_BATON';
CKK_JUNIPER: Result := 'CKK_JUNIPER';
CKK_CDMF: Result := 'CKK_CDMF';
CKK_AES: Result := 'CKK_AES';
CKK_BLOWFISH: Result := 'CKK_BLOWFISH';
CKK_TWOFISH: Result := 'CKK_TWOFISH';
CKK_SECURID: Result := 'CKK_SECURID';
CKK_HOTP: Result := 'CKK_HOTP';
CKK_ACTI: Result := 'CKK_ACTI';
CKK_CAMELLIA: Result := 'CKK_CAMELLIA';
CKK_ARIA: Result := 'CKK_ARIA';
CKK_VENDOR_DEFINED: Result := 'CKK_VENDOR_DEFINED';
end;
end;
function TPKCS11Attribute.CertificateTypeToString(certType: CK_CERTIFICATE_TYPE): String;
begin
Result := RS_UNKNOWN;
case certType of
CKC_X_509: Result := 'CKC_X_509';
CKC_X_509_ATTR_CERT: Result := 'CKC_X_509_ATTR_CERT';
CKC_WTLS: Result := 'CKC_WTLS';
CKC_VENDOR_DEFINED: Result := 'CKC_VENDOR_DEFINED';
end;
end;
function TPKCS11Attribute.GetValueAsObjClass(): CK_OBJECT_CLASS;
begin
Result := (PCK_OBJECT_CLASS(PAnsiChar(FRawData)))^;
end;
function TPKCS11Attribute.GetValueAsBoolean(): Boolean;
begin
Result := (((PCK_BBOOL(PAnsiChar(FRawData)))^) = CK_TRUE);
end;
function TPKCS11Attribute.GetValueAsString(): Ansistring;
begin
Result := FRawData;
end;
function TPKCS11Attribute.GetValueAsBigInteger(): Ansistring;
begin
Result := FRawData;
end;
function TPKCS11Attribute.GetValueAsByteArray(): Ansistring;
begin
Result := FRawData;
end;
function TPKCS11Attribute.GetValueAsCertificateType(): CK_CERTIFICATE_TYPE;
begin
Result := (PCK_CERTIFICATE_TYPE(PAnsiChar(FRawData)))^;
end;
function TPKCS11Attribute.GetValueAsNumber(): CK_ULONG;
begin
if (length(FRawData) < sizeof(Result)) then begin
Result := 0;
end else begin
Result := (PCK_ULONG(FRawData))^;
end;
end;
function TPKCS11Attribute.GetValueAsKeyType(): CK_KEY_TYPE;
begin
Result := (PCK_KEY_TYPE(PAnsiChar(FRawData)))^;
end;
function TPKCS11Attribute.GetValueAsDate(): TDate;
var
tmpCK_DATE: CK_DATE;
begin
Result := 0;
if (length(FRawData) >= sizeof(tmpCK_DATE)) then begin
tmpCK_DATE := (PCK_DATE(PAnsiChar(FRawData)))^;
Result := CK_DATEToDate(tmpCK_DATE);
end;
end;
function TPKCS11Attribute.GetValueAsMechanismType(): CK_MECHANISM_TYPE;
begin
Result := (PCK_MECHANISM_TYPE(PAnsiChar(FRawData)))^;
end;
function TPKCS11Attribute.GetValueAsHWFeatureType(): CK_HW_FEATURE_TYPE;
begin
Result := (PCK_HW_FEATURE_TYPE(PAnsiChar(FRawData)))^;
end;
procedure TPKCS11Attribute.SetValueAsObjClass(Value: CK_OBJECT_CLASS);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
procedure TPKCS11Attribute.SetValueAsBoolean(Value: Boolean);
var
tmpCK_BBOOL: CK_BBOOL;
begin
tmpCK_BBOOL := CK_TRUE;
if not (Value) then begin
tmpCK_BBOOL := CK_FALSE;
end;
FRawData := CopyBinary(@tmpCK_BBOOL, sizeof(tmpCK_BBOOL));
end;
procedure TPKCS11Attribute.SetValueAsString(Value: Ansistring);
begin
FRawData := Value;
end;
procedure TPKCS11Attribute.SetValueAsBigInteger(Value: Ansistring);
begin
FRawData := Value;
end;
procedure TPKCS11Attribute.SetValueAsByteArray(Value: Ansistring);
begin
FRawData := Value;
end;
procedure TPKCS11Attribute.SetValueAsCertificateType(Value: CK_CERTIFICATE_TYPE);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
procedure TPKCS11Attribute.SetValueAsNumber(Value: CK_ULONG);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
procedure TPKCS11Attribute.SetValueAsKeyType(Value: CK_KEY_TYPE);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
procedure TPKCS11Attribute.SetValueAsDate(Value: TDate);
var
tmpCK_DATE: CK_DATE;
begin
tmpCK_DATE := DateToCK_DATE(Value);
FRawData := CopyBinary(@tmpCK_DATE, sizeof(tmpCK_DATE));
end;
procedure TPKCS11Attribute.SetValueAsMechanismType(Value: CK_MECHANISM_TYPE);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
procedure TPKCS11Attribute.SetValueAsHWFeatureType(Value: CK_HW_FEATURE_TYPE);
begin
FRawData := CopyBinary(@Value, sizeof(Value));
end;
constructor TPKCS11AttributeTemplate.Create();
begin
inherited;
SetLength(FAttributes, 0);
end;
destructor TPKCS11AttributeTemplate.Destroy();
var
i: Integer;
begin
for i := low(FAttributes) to high(FAttributes) do begin
FAttributes[i].Free();
end;
inherited;
end;
function TPKCS11AttributeTemplate.GetCount(): Integer;
begin
Result := length(FAttributes);
end;
function TPKCS11AttributeTemplate.GetAttribute(idx: Integer): TPKCS11Attribute;
begin
Assert(
(idx >= 0) and (idx < Count),
'Index out of bounds'
);
Result := FAttributes[idx];
end;
procedure TPKCS11AttributeTemplate.SetAttribute(idx: Integer; attr: TPKCS11Attribute);
begin
Assert(
(idx >= 0) and (idx < Count),
'Index out of bounds'
);
FAttributes[idx] := attr;
end;
// Add an existing attribute/add a new attribute, return it
function TPKCS11AttributeTemplate.Add(attr: TPKCS11Attribute): TPKCS11Attribute;
begin
SetLength(FAttributes, (length(FAttributes) + 1));
// -1 because the array indexes from 0
FAttributes[(length(FAttributes) - 1)] := attr;
Result := attr;
end;
function TPKCS11AttributeTemplate.Add(): TPKCS11Attribute;
var
newAttr: TPKCS11Attribute;
begin
newAttr := TPKCS11Attribute.Create();
// Junk data
newAttr.AttribType := CKA_CLASS;
newAttr.ValueAsObjClass := CKO_DATA;
Result := Add(newAttr);
end;
end.
|
unit uPaymentStoreCredit;
interface
uses
uPayment, DBClient, SysUtils;
type
TPaymentStoreCredit = class(TPayment)
private
FIDCustomerCredit: Integer;
FCreditList : TClientDataSet;
procedure UpdateCustomerCredit(AUsing: Boolean);
procedure UpdateUsedCreditList;
procedure InsertStoreCredit;
function AddCustomerCredit(AIDPessoa, AIDUser, AIDStore, AIDLancamento: Integer;
ACreditDate, AExpirationDate: TDateTime; AAmount: Double;
var AIDCustomerCredit: Integer): Boolean;
protected
procedure OnProcessPayment; override;
procedure BeforeDeletePayment; override;
function GetPaymentType: Integer; override;
public
property IDCustomerCredit: Integer read FIDCustomerCredit write FIDCustomerCredit;
property CreditList : TClientDataSet read FCreditList write FCreditList;
end;
implementation
uses ADODB, Variants, uSystemConst, DB;
{ TPaymentStoreCredit }
function TPaymentStoreCredit.GetPaymentType: Integer;
begin
Result := PAYMENT_TYPE_CREDIT;
end;
procedure TPaymentStoreCredit.BeforeDeletePayment;
begin
inherited;
UpdateCustomerCredit(True);
end;
procedure TPaymentStoreCredit.OnProcessPayment;
begin
inherited;
FTraceControl.TraceIn(Self.ClassName, 'OnProcessPayment');
if PaymentValue > 0 then
UpdateUsedCreditList
else
InsertStoreCredit;
FTraceControl.TraceOut;
end;
procedure TPaymentStoreCredit.UpdateCustomerCredit(AUsing: Boolean);
begin
FTraceControl.TraceIn(Self.ClassName, '.UpdateCustomerCredit');
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE CustomerCredit ' +
'SET IsUsed = 1, IDLancamento = :IDLancamento ' +
'WHERE IDCustomerCredit = :IDCustomerCredit';
Parameters.ParamByName('IDCustomerCredit').Value := FIDCustomerCredit;
if AUsing then
Parameters.ParamByName('IDLancamento').Value := FIDPayment
else
Parameters.ParamByName('IDLancamento').Value := NULL;
Execute;
finally
Free;
end;
FTraceControl.TraceOut;
end;
procedure TPaymentStoreCredit.UpdateUsedCreditList;
var
cValue : Currency;
IDCustomerCredit : Integer;
begin
FTraceControl.TraceIn(Self.ClassName, 'UpdateUsedCreditList');
if Assigned(CreditList) then
with CreditList do
begin
cValue := PaymentValue;
First;
while not EOF do
begin
cValue := cValue - FieldByName('Amount').AsCurrency;
FADOConnection.Execute(Format('UPDATE CustomerCredit SET IsUsed = 1 WHERE IDCustomerCredit = %D', [FieldByName('IDCustomerCredit').AsInteger]));
if cValue = 0 then
Break;
if cValue < 0 then
begin
AddCustomerCredit(FieldByName('IDPessoa').AsInteger,
FieldByName('IDUser').AsInteger,
FieldByName('IDStore').AsInteger,
FieldByName('IDLancamento').AsInteger,
FieldByName('CreditDate').AsDateTime,
FieldByName('ExpirationDate').AsDateTime,
ABS(cValue),
IDCustomerCredit);
Break;
end;
Next;
end;
end;
FTraceControl.TraceOut;
end;
function TPaymentStoreCredit.AddCustomerCredit(AIDPessoa, AIDUser,
AIDStore, AIDLancamento: Integer; ACreditDate,
AExpirationDate: TDateTime; AAmount: Double;
var AIDCustomerCredit: Integer): Boolean;
var
iError : Integer;
begin
FTraceControl.TraceIn(Self.ClassName, '.AddCustomerCredit');
fIDCustomerCredit := -1;
with TADOStoredProc.Create(nil) do
begin
Connection := FADOConnection;
ProcedureName := 'sp_PreSale_AddCustomerCredit;1';
Parameters.Refresh;
Parameters.ParamByName('@IDPessoa').Value := AIDPessoa;
Parameters.ParamByName('@IDUser').Value := AIDUser;
Parameters.ParamByName('@IDStore').Value := AIDStore;
Parameters.ParamByName('@CreditDate').Value := ACreditDate;
if AExpirationDate = 0 then
Parameters.ParamByName('@ExpirationDate').Value := Null
else
Parameters.ParamByName('@ExpirationDate').Value := AExpirationDate;
Parameters.ParamByName('@Amount').Value := AAmount;
if AIDLancamento = 0 then
Parameters.ParamByName('@IDLancamento').Value := Null
else
Parameters.ParamByName('@IDLancamento').Value := AIDLancamento;
Parameters.ParamByName('@IDCustomerCredit').Value := 0;
ExecProc;
iError := Parameters.ParambyName('@RETURN_VALUE').Value;
if (iError = 0) then
begin
AIDCustomerCredit := Parameters.ParamByName('@IDCustomerCredit').Value;
Result := True;
end
else
begin
Result := False;
raise Exception.Create('sp_PreSale_AddCustomerCredit Error ' + IntToStr(iError));
end;
end;
FTraceControl.TraceOut;
end;
procedure TPaymentStoreCredit.InsertStoreCredit;
var
FID : Integer;
begin
AddCustomerCredit(IDCustomer,
IDUser,
IDStore,
0,
Now,
0,
ABS(PaymentValue),
FID);
end;
end.
|
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MongoDB,
FireDAC.Phys.MongoDBDef, System.Rtti, System.JSON.Types, System.JSON.Readers,
System.JSON.BSON, System.JSON.Builders, FireDAC.Phys.MongoDBWrapper,
FireDAC.VCLUI.Wait, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB, FireDAC.Comp.Client,
FireDAC.Comp.UI, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.Comp.DataSet, FireDAC.Phys.MongoDBDataSet, Vcl.Grids, Vcl.DBGrids;
type
TForm1 = class(TForm)
memStatus: TMemo;
Panel1: TPanel;
btnCnn: TButton;
FDPhysMongoDriverLink1: TFDPhysMongoDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
btnFind: TButton;
memResult: TMemo;
Mongodb_demo: TFDConnection;
dbgQuery: TDBGrid;
DataSource1: TDataSource;
FDMongoQuery1: TFDMongoQuery;
btnQuery: TButton;
dbgDataSet: TDBGrid;
FDMongoDataSet1: TFDMongoDataSet;
DataSource2: TDataSource;
btnStart: TButton;
btnCommit: TButton;
btnRollback: TButton;
procedure btnCnnClick(Sender: TObject);
procedure btnFindClick(Sender: TObject);
procedure btnQueryClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnCommitClick(Sender: TObject);
procedure btnRollbackClick(Sender: TObject);
private
{ Private declarations }
FCon: TMongoConnection;
oCrs: IMongoCursor;
oSes: TMongoSession;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses System.Threading;
procedure TForm1.btnCnnClick(Sender: TObject);
begin
try
Mongodb_demo.Open;
memStatus.Text := 'Connected!';
FCon := TMongoConnection(Mongodb_demo.CliObj);
except
on E: Exception do
begin
memStatus.Text := E.Message;
end;
end;
end;
procedure TForm1.btnFindClick(Sender: TObject);
begin
memResult.Text := '';
FDMongoDataSet1.Close;
oCrs := FCon.Databases['sample_restaurants'].Collections['restaurants'].Find()
.Match().Add('cuisine', 'Italian').&End;
var
aTask := TTask.Create(
Procedure
begin
Screen.Cursor := crHourGlass;
memResult.Lines.BeginUpdate;
try
while oCrs.Next do
memResult.Lines.Add(oCrs.Doc.AsJSON);
finally
Screen.Cursor := crDefault;
memResult.Lines.EndUpdate;
memResult.SelStart := 0;
memResult.SelLength := 1;
end;
end);
aTask.Start;
FDMongoDataSet1.Cursor := oCrs;
FDMongoDataSet1.Open;
end;
procedure TForm1.btnQueryClick(Sender: TObject);
begin
FDMongoQuery1.Close;
FDMongoQuery1.QMatch := '{"cuisine": "Italian", "address.zipcode": "10075"}';
FDMongoQuery1.Open;
end;
procedure TForm1.btnStartClick(Sender: TObject);
begin
if not Mongodb_demo.InTransaction then
Mongodb_demo.StartTransaction;
end;
procedure TForm1.btnCommitClick(Sender: TObject);
begin
if Mongodb_demo.InTransaction then
begin
if FDMongoQuery1.State in [dsEdit, dsInsert] then
FDMongoQuery1.Post;
Mongodb_demo.Commit;
end;
end;
procedure TForm1.btnRollbackClick(Sender: TObject);
begin
if Mongodb_demo.InTransaction then
begin
if FDMongoQuery1.State in [dsEdit, dsInsert] then
FDMongoQuery1.Cancel;
Mongodb_demo.Rollback;
end;
end;
end.
|
unit Controle;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, Variants,
Contnrs, SqlExpr, StrUtils, Provider, DBClient, IniFiles, ConexaoBanco;
type
TControle = class
private
oID: Integer;
oConexao: TConexaoBanco;
oSQLQuery: TSQLQuery;
oSQLResult: TSQLQuery;
oDspResult: TDataSetProvider;
oCdsResult: TClientDataSet;
oSQLLista: TSQLQuery;
oDspLista: TDataSetProvider;
oCdsLista: TClientDataSet;
oTransaction: TTransactionDesc;
public
constructor Create;
destructor Destroy; override;
procedure StartTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
function InTransaction: Boolean;
property SqlQuery: TSQLQuery read oSQLQuery write oSQLQuery;
property SqlResult: TSQLQuery read oSQLResult write oSQLResult;
property DspResult: TDataSetProvider read oDspResult write oDspResult;
property CdsResult: TClientDataSet read oCdsResult write oCdsResult;
property SqlLista: TSQLQuery read oSQLLista write oSQLLista;
property DspLista: TDataSetProvider read oDspLista write oDspLista;
property CdsLista: TClientDataSet read oCdsLista write oCdsLista;
end;
implementation
{ TControle }
procedure TControle.CommitTransaction;
begin
if Self.oConexao.ConexaoBanco.InTransaction then
Self.oConexao.ConexaoBanco.Commit(oTransaction);
end;
constructor TControle.Create;
procedure ConfigurarSQLQ(pSQL: TSQLQuery; pNameSQL: string);
begin
pSQL.SQLConnection := oConexao.ConexaoBanco;
pSQL.Name := pNameSQL;
end;
procedure ConfigurarDSP(pSQL: TSQLQuery; pDSP: TDataSetProvider; pNameDSP: string);
begin
pDSP.DataSet := pSQL;
pDSP.Options := pDSP.Options + [poCascadeDeletes, poCascadeUpdates, poAllowCommandText, poUseQuoteChar];
pDSP.Name := pNameDSP;
end;
procedure ConfigurarCDS(pDSP: TDataSetProvider; pCDS: TClientDataSet; pNameCDS: string);
begin
pCDS.ProviderName := pDSP.Name;
pCDS.Name := pNameCDS;
end;
begin
oConexao := TConexaoBanco.Create;
{$REGION 'Objeto Query'}
oSQLQuery := TSQLQuery.Create(Application);
ConfigurarSQLQ(oSQLQuery, 'oSQLQuery');
{$ENDREGION}
{$REGION 'Objeto Result'}
oSQLResult := TSQLQuery.Create(Application);
oDspResult := TDataSetProvider.Create(Application);
oCdsResult := TClientDataSet.Create(Application);
ConfigurarSQLQ(oSQLResult, 'oSQLResult');
ConfigurarDSP(oSQLResult, oDspResult, 'oDspResult');
ConfigurarCDS(oDspResult, oCdsResult, 'oCdsResult');
{$ENDREGION}
{$REGION 'Objeto Lista'}
oSQLLista := TSQLQuery.Create(Application);
oDspLista := TDataSetProvider.Create(Application);
oCdsLista := TClientDataSet.Create(Application);
ConfigurarSQLQ(oSQLLista, 'oSQLLista');
ConfigurarDSP(oSQLLista, oDspLista, 'oDspLista');
ConfigurarCDS(oDspLista, oCdsLista, 'oCdsLista');
{$ENDREGION}
oTransaction.TransactionID := Random(oID);
end;
destructor TControle.Destroy;
begin
inherited;
end;
function TControle.InTransaction: Boolean;
begin
Result := Self.oConexao.ConexaoBanco.InTransaction;
end;
procedure TControle.RollbackTransaction;
begin
if Self.oConexao.ConexaoBanco.InTransaction then
Self.oConexao.ConexaoBanco.Rollback(oTransaction);
end;
procedure TControle.StartTransaction;
begin
if (not Self.oConexao.ConexaoBanco.InTransaction) then
Self.oConexao.ConexaoBanco.StartTransaction(oTransaction);
end;
end.
|
unit uAdministrator;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DCBasicTypes, DCClassesUtf8, DCOSUtils, uFindEx, uFileCopyEx;
procedure PushPop(var Elevate: TDuplicates);
function FileExistsUAC(const FileName: String): Boolean;
function FileGetAttrUAC(const FileName: String; FollowLink: Boolean = False): TFileAttrs;
function FileGetAttrUAC(const FileName: String; out Attr: TFileAttributeData): Boolean;
function FileSetAttrUAC(const FileName: String; Attr: TFileAttrs): Boolean;
function FileSetTimeUAC(const FileName: String;
ModificationTime: DCBasicTypes.TFileTime;
CreationTime : DCBasicTypes.TFileTime = 0;
LastAccessTime : DCBasicTypes.TFileTime = 0): LongBool;
function FileSetReadOnlyUAC(const FileName: String; ReadOnly: Boolean): Boolean;
function FileCopyAttrUAC(const sSrc, sDst: String;
Options: TCopyAttributesOptions): TCopyAttributesOptions;
function FileOpenUAC(const FileName: String; Mode: LongWord): System.THandle;
function FileCreateUAC(const FileName: String; Mode: LongWord): System.THandle;
function FileCopyUAC(const Source, Target: String; Options: UInt32;
UpdateProgress: TFileCopyProgress; UserData: Pointer): Boolean;
function DeleteFileUAC(const FileName: String): LongBool;
function RenameFileUAC(const OldName, NewName: String): LongBool;
function FindFirstUAC(const Path: String; Flags: UInt32; out SearchRec: TSearchRecEx): Integer;
function FindNextUAC(var SearchRec: TSearchRecEx): Integer;
procedure FindCloseUAC(var SearchRec: TSearchRecEx);
function ForceDirectoriesUAC(const Path: String): Boolean;
function CreateDirectoryUAC(const Directory: String): Boolean;
function RemoveDirectoryUAC(const Directory: String): Boolean;
function DirectoryExistsUAC(const Directory : String): Boolean;
function CreateSymbolicLinkUAC(const Path, LinkName: String) : Boolean;
function CreateHardLinkUAC(const Path, LinkName: String) : Boolean;
type
{ TFileStreamUAC class }
TFileStreamUAC = class(TFileStreamEx)
public
constructor Create(const AFileName: String; Mode: LongWord); override;
end;
{ TStringListUAC }
TStringListUAC = class(TStringListEx)
public
procedure LoadFromFile(const FileName: String); override;
procedure SaveToFile(const FileName: String); override;
end;
threadvar
ElevateAction: TDuplicates;
implementation
uses
RtlConsts, DCStrUtils, LCLType, uShowMsg, uElevation, uSuperUser,
fElevation;
resourcestring
rsElevationRequired = 'You need to provide administrator permission';
rsElevationRequiredDelete = 'to delete this object:';
rsElevationRequiredOpen = 'to open this object:';
rsElevationRequiredCopy = 'to copy this object:';
rsElevationRequiredCreate = 'to create this object:';
rsElevationRequiredRename = 'to rename this object:';
rsElevationRequiredHardLink = 'to create this hard link:';
rsElevationRequiredSymLink = 'to create this symbolic link:';
rsElevationRequiredGetAttributes = 'to get attributes of this object:';
rsElevationRequiredSetAttributes = 'to set attributes of this object:';
procedure PushPop(var Elevate: TDuplicates);
var
AValue: TDuplicates;
begin
AValue:= ElevateAction;
ElevateAction:= Elevate;
Elevate:= AValue;
end;
function RequestElevation(const Message, FileName: String): Boolean;
var
Text: String;
begin
case ElevateAction of
dupAccept: Exit(True);
dupError: Exit(False);
end;
Text:= rsElevationRequired + LineEnding;
Text += Message + LineEnding + FileName;
case ShowElevation(mbSysErrorMessage, Text) of
mmrOK: Result:= True;
mmrSkip: Result:= False;
mmrSkipAll: begin
Result:= False;
ElevateAction:= dupError;
end;
mmrAll: begin
Result:= True;
ElevateAction:= dupAccept;
end;
end;
end;
function FileExistsUAC(const FileName: String): Boolean;
var
LastError: Integer;
begin
Result:= mbFileExists(FileName);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredGetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileExists(FileName)
else
SetLastOSError(LastError);
end;
end;
function FileGetAttrUAC(const FileName: String; FollowLink: Boolean): TFileAttrs;
var
LastError: Integer;
begin
if not FollowLink then
Result:= mbFileGetAttr(FileName)
else begin
Result:= mbFileGetAttrNoLinks(FileName);
end;
if (Result = faInvalidAttributes) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredGetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileGetAttr(FileName, FollowLink)
else
SetLastOSError(LastError);
end;
end;
function FileGetAttrUAC(const FileName: String; out Attr: TFileAttributeData): Boolean;
var
LastError: Integer;
begin
Result:= mbFileGetAttr(FileName, Attr);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredGetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileGetAttr(FileName, Attr)
else
SetLastOSError(LastError);
end;
end;
function FileSetAttrUAC(const FileName: String; Attr: TFileAttrs): Boolean;
var
LastError: Integer;
begin
Result:= mbFileSetAttr(FileName, Attr);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredSetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileSetAttr(FileName, Attr)
else
SetLastOSError(LastError);
end;
end;
function FileSetTimeUAC(const FileName: String;
ModificationTime: DCBasicTypes.TFileTime;
CreationTime : DCBasicTypes.TFileTime;
LastAccessTime : DCBasicTypes.TFileTime): LongBool;
var
LastError: Integer;
begin
Result:= mbFileSetTime(FileName, ModificationTime, CreationTime, LastAccessTime);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredSetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileSetTime(FileName, ModificationTime, CreationTime, LastAccessTime)
else
SetLastOSError(LastError);
end;
end;
function FileSetReadOnlyUAC(const FileName: String; ReadOnly: Boolean): Boolean;
var
LastError: Integer;
begin
Result:= mbFileSetReadOnly(FileName, ReadOnly);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredSetAttributes, FileName) then
Result:= TWorkerProxy.Instance.FileSetReadOnly(FileName, ReadOnly)
else
SetLastOSError(LastError);
end;
end;
function FileCopyAttrUAC(const sSrc, sDst: String;
Options: TCopyAttributesOptions): TCopyAttributesOptions;
var
Option: TCopyAttributesOption;
Errors: TCopyAttributesResult;
begin
Result:= mbFileCopyAttr(sSrc, sDst, Options, @Errors);
if (Result <> []) then
begin
for Option in Result do
begin
if ElevationRequired(Errors[Option]) then
begin
if RequestElevation(rsElevationRequiredSetAttributes, sDst) then
Result:= TWorkerProxy.Instance.FileCopyAttr(sSrc, sDst, Result)
else
SetLastOSError(Errors[Option]);
Break;
end;
end;
end;
end;
function FileOpenUAC(const FileName: String; Mode: LongWord): System.THandle;
var
LastError: Integer;
begin
Result:= mbFileOpen(FileName, Mode);
if (Result = feInvalidHandle) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredOpen, FileName) then
Result:= TWorkerProxy.Instance.FileOpen(FileName, Mode)
else
SetLastOSError(LastError);
end;
end;
function FileCreateUAC(const FileName: String; Mode: LongWord): System.THandle;
var
LastError: Integer;
begin
Result:= mbFileCreate(FileName, Mode);
if (Result = feInvalidHandle) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredCreate, FileName) then
Result:= TWorkerProxy.Instance.FileCreate(FileName, Mode)
else
SetLastOSError(LastError);
end;
end;
function FileCopyUAC(const Source, Target: String; Options: UInt32;
UpdateProgress: TFileCopyProgress; UserData: Pointer): Boolean;
var
LastError: Integer;
begin
Result:= FileCopyEx(Source, Target, Options, UpdateProgress, UserData);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredCopy, Source) then
Result:= TWorkerProxy.Instance.FileCopy(Source, Target, Options, UpdateProgress, UserData)
else
SetLastOSError(LastError);
end;
end;
function DeleteFileUAC(const FileName: String): LongBool;
var
LastError: Integer;
begin
Result:= mbDeleteFile(FileName);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredDelete, FileName) then
Result:= TWorkerProxy.Instance.DeleteFile(FileName)
else
SetLastOSError(LastError);
end;
end;
function RenameFileUAC(const OldName, NewName: String): LongBool;
var
LastError: Integer;
begin
Result:= mbRenameFile(OldName, NewName);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredRename, OldName) then
Result:= TWorkerProxy.Instance.RenameFile(OldName, NewName)
else
SetLastOSError(LastError);
end;
end;
function CreateDirectoryUAC(const Directory: String): Boolean;
var
LastError: Integer;
begin
Result:= mbCreateDir(Directory);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredCreate, Directory) then
Result:= TWorkerProxy.Instance.CreateDirectory(Directory)
else
SetLastOSError(LastError);
end;
end;
function RemoveDirectoryUAC(const Directory: String): Boolean;
var
LastError: Integer;
begin
Result:= mbRemoveDir(Directory);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredDelete, Directory) then
Result:= TWorkerProxy.Instance.RemoveDirectory(Directory)
else
SetLastOSError(LastError);
end;
end;
function DirectoryExistsUAC(const Directory: String): Boolean;
var
LastError: Integer;
begin
Result:= mbDirectoryExists(Directory);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredGetAttributes, Directory) then
Result:= TWorkerProxy.Instance.DirectoryExists(Directory)
else
SetLastOSError(LastError);
end;
end;
function CreateHardLinkUAC(const Path, LinkName: String): Boolean;
var
LastError: Integer;
begin
Result:= CreateHardLink(Path, LinkName);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredHardLink, LinkName) then
Result:= TWorkerProxy.Instance.CreateHardLink(Path, LinkName)
else
SetLastOSError(LastError);
end;
end;
function CreateSymbolicLinkUAC(const Path, LinkName: String): Boolean;
var
LastError: Integer;
begin
Result:= CreateSymLink(Path, LinkName);
if (not Result) and ElevationRequired then
begin
LastError:= GetLastOSError;
if RequestElevation(rsElevationRequiredSymLink, LinkName) then
Result:= TWorkerProxy.Instance.CreateSymbolicLink(Path, LinkName)
else
SetLastOSError(LastError);
end;
end;
function FindFirstUAC(const Path: String; Flags: UInt32; out
SearchRec: TSearchRecEx): Integer;
begin
Result:= FindFirstEx(Path, Flags, SearchRec);
if (Result <> 0) and ElevationRequired(Result) then
begin
if RequestElevation(rsElevationRequiredOpen, Path) then
begin
SearchRec.Flags:= SearchRec.Flags or fffElevated;
Result:= TWorkerProxy.Instance.FindFirst(Path, Flags, SearchRec)
end;
end;
end;
function FindNextUAC(var SearchRec: TSearchRecEx): Integer;
begin
if (SearchRec.Flags and fffElevated <> 0) then
Result:= TWorkerProxy.Instance.FindNext(SearchRec)
else
Result:= FindNextEx(SearchRec);
end;
procedure FindCloseUAC(var SearchRec: TSearchRecEx);
begin
if (SearchRec.Flags and fffElevated <> 0) then
TWorkerProxy.Instance.FindClose(SearchRec)
else
FindCloseEx(SearchRec);
end;
function ForceDirectoriesUAC(const Path: String): Boolean;
var
Index: Integer;
ADirectory: String;
ADirectoryPath: String;
begin
if Path = '' then Exit;
ADirectoryPath := IncludeTrailingPathDelimiter(Path);
Index:= 1;
if Pos('\\', ADirectoryPath) = 1 then // if network path
begin
Index := CharPos(PathDelim, ADirectoryPath, 3); // index of the end of computer name
Index := CharPos(PathDelim, ADirectoryPath, Index + 1); // index of the end of first remote directory
end;
// Move past path delimiter at the beginning.
if (Index = 1) and (ADirectoryPath[Index] = PathDelim) then
Index := Index + 1;
while Index <= Length(ADirectoryPath) do
begin
if ADirectoryPath[Index] = PathDelim then
begin
ADirectory:= Copy(ADirectoryPath, 1, Index - 1);
if not DirectoryExistsUAC(ADirectory) then
begin
Result:= CreateDirectoryUAC(ADirectory);
if not Result then Exit;
end;
end;
Inc(Index);
end;
Result := True;
end;
{ TFileStreamUAC }
constructor TFileStreamUAC.Create(const AFileName: String; Mode: LongWord);
var
AHandle: System.THandle;
begin
if (Mode and fmCreate) <> 0 then
begin
AHandle:= FileCreateUAC(AFileName, Mode);
if AHandle = feInvalidHandle then
raise EFCreateError.CreateFmt(SFCreateError, [AFileName])
else
inherited Create(AHandle);
end
else
begin
AHandle:= FileOpenUAC(AFileName, Mode);
if AHandle = feInvalidHandle then
raise EFOpenError.CreateFmt(SFOpenError, [AFilename])
else
inherited Create(AHandle);
end;
FFileName:= AFileName;
end;
{ TStringListUAC }
procedure TStringListUAC.LoadFromFile(const FileName: String);
var
fsFileStream: TFileStreamUAC;
begin
fsFileStream:= TFileStreamUAC.Create(FileName, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(fsFileStream);
finally
fsFileStream.Free;
end;
end;
procedure TStringListUAC.SaveToFile(const FileName: String);
var
fsFileStream: TFileStreamUAC;
begin
fsFileStream:= TFileStreamUAC.Create(FileName, fmCreate);
try
SaveToStream(fsFileStream);
finally
fsFileStream.Free;
end;
end;
end.
|
unit ufrmCXLookup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Datasnap.DSProxyRest, uDMClient,
uClientClasses, Datasnap.DSClientRest, Data.DB, Data.SqlExpr,
Datasnap.Provider, Datasnap.DBClient, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, cxControls, cxStyles, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, cxDBData, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, Vcl.StdCtrls, cxButtons, cxContainer, Vcl.ComCtrls,
dxCore, cxDateUtils, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
cxLabel, Vcl.ExtCtrls, dxBarBuiltInMenu, cxPC, cxCheckBox;
type
TLookupClient = class(TDSAdminRestClient)
private
public
FLookupCommand: TDSRestCommand;
function GetLookupData(aCommandName: String; aStartDate: TDateTime = 0;
aEndDate: TDateTime = 0; aStringFilter: String = ''): TDataSet; overload;
procedure PrepareCommand(aCommandName: String); overload;
end;
TfrmCXLookup = class(TForm)
pnlHeader: TPanel;
lblHeader: TLabel;
lblFilterData: TcxLabel;
StartDate: TcxDateEdit;
EndDate: TcxDateEdit;
btnRefresh: TcxButton;
lblsdFilter: TcxLabel;
Panel1: TPanel;
Panel2: TPanel;
lbEscape: TLabel;
btnClose: TcxButton;
btnOK: TcxButton;
Label1: TLabel;
cxGrid: TcxGrid;
cxGridView: TcxGridDBTableView;
cxlvMaster: TcxGridLevel;
pmSelect: TPopupMenu;
CheckSelected1: TMenuItem;
UnCheckSelected1: TMenuItem;
N1: TMenuItem;
CheckAll1: TMenuItem;
UncheckAll1: TMenuItem;
lbBenchmark: TLabel;
procedure btnRefreshClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure CheckAll1Click(Sender: TObject);
procedure CheckSelected1Click(Sender: TObject);
procedure cxGridViewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo:
TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState;
var AHandled: Boolean);
procedure cxGridViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure UncheckAll1Click(Sender: TObject);
procedure UnCheckSelected1Click(Sender: TObject);
private
FCDS: TClientDataset;
FCommandName: String;
FData: TClientDataset;
FMultiSelect: Boolean;
FStartExecute: TDatetime;
FStringFilter: String;
function CopyDataset(Source: TDataset): TClientDataSet;
procedure InitView;
procedure SetCheckSelected(IsChecked: Boolean = True; IsSelectAll: Boolean =
False);
procedure SetMultiSelect(const Value: Boolean);
procedure SetResultData;
property CDS: TClientDataset read FCDS write FCDS;
{ Private declarations }
protected
FLookupClient: TLookupClient;
function GetDatasetFromServer: TDataSet; dynamic;
procedure HideDateParams;
procedure RefreshDataSet;
public
constructor Create(ARestConn: TDSRestConnection; aMultiSelect: Boolean =
False); reintroduce;
class function Execute(aCaption, aCommand: String; aStartDate: TDateTime = 0;
aEndDate: TDateTime = 0; aMultiSelect: Boolean = False): TfrmCXLookup;
overload;
class function Execute(ADataSet: TClientDataSet; aMultiSelect: Boolean = False;
aCaption: String = 'Lookup Data'): TfrmCXLookup; overload;
class function Execute(aCaption, aCommand, aStringFilter: String; aStartDate:
TDateTime = 0; aEndDate: TDateTime = 0; aMultiSelect: Boolean = False):
TfrmCXLookup; overload;
procedure HideFields(FieldNames: Array Of String);
procedure Reset;
procedure ShowFieldsOnly(FieldNames: Array Of String);
property CommandName: String read FCommandName write FCommandName;
property Data: TClientDataset read FData write FData;
property StartExecute: TDatetime read FStartExecute write FStartExecute;
property StringFilter: String read FStringFilter write FStringFilter;
{ Public declarations }
published
property MultiSelect: Boolean read FMultiSelect write SetMultiSelect;
end;
var
frmCXLookup: TfrmCXLookup;
const
check_flag : String = 'check_flag';
implementation
uses
uDBUtils, uDXUtils, System.DateUtils, uAppUtils;
{$R *.dfm}
procedure TfrmCXLookup.btnRefreshClick(Sender: TObject);
begin
RefreshDataSet;
end;
procedure TfrmCXLookup.btnCloseClick(Sender: TObject);
begin
Self.ModalResult := mrCancel;
end;
procedure TfrmCXLookup.btnOKClick(Sender: TObject);
begin
if not Assigned(FCDS) then
Self.ModalResult := mrNone
else begin
SetResultData;
if MultiSelect then
begin
FData.First;
if Self.Data.RecordCount = 0 then
begin
TAppUtils.Warning('Tidak ada data yang dipilih');
exit;
end
end;
if not Self.Data.Eof then
Self.ModalResult := mrOk;
end;
end;
constructor TfrmCXLookup.Create(ARestConn: TDSRestConnection; aMultiSelect:
Boolean = False);
begin
inherited Create(nil);
StringFilter := '';
StartExecute := Now();
FLookupClient := TLookupClient.Create(ARestConn, False);
Self.MultiSelect := aMultiSelect;
end;
procedure TfrmCXLookup.CheckAll1Click(Sender: TObject);
begin
SetCheckSelected(True, True);
end;
procedure TfrmCXLookup.CheckSelected1Click(Sender: TObject);
begin
SetCheckSelected(True);
end;
function TfrmCXLookup.CopyDataset(Source: TDataset): TClientDataSet;
var
i: Integer;
lFieldName: string;
lRecNo: Integer;
begin
Result := nil;
if Source = nil then exit;
Result := TClientDataSet.Create(Self);
Result.FieldDefs.Assign(Source.FieldDefs);
Result.FieldDefs.Add(check_flag, ftBoolean);
// Result.AddField(check_flag,ftBoolean);
for i := 0 to Result.FieldDefs.Count-1 do
begin
Result.FieldDefs[i].Required := False;
If Result.FieldDefs[i].DataType = ftAutoInc then
Result.FieldDefs[i].DataType := ftInteger;
end;
Result.CreateDataSet;
for i := 0 to Result.Fields.Count-1 do
begin
Result.Fields[i].ReadOnly := False;
end;
lRecNo := Source.RecNo;
Source.DisableControls;
Result.DisableControls;
Try
Source.First;
While not Source.Eof do
begin
Result.Append;
Result.FieldByName(check_flag).AsBoolean := False;
for i:=0 to Source.FieldCount-1 do
begin
lFieldName := Source.Fields[i].FieldName;
Result.FieldByName(lFieldName).Value := Source.FieldByName(lFieldName).Value;
end;
Result.Post;
Source.Next;
end;
Result.First;
Finally
Source.RecNo := lRecNo;
Source.EnableControls;
Result.EnableControls;
end;
end;
procedure TfrmCXLookup.cxGridViewCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift:
TShiftState; var AHandled: Boolean);
begin
If not Self.MultiSelect then
begin
btnOK.Click;
end else
begin
CDS.Edit;
CDS.FieldByName(check_flag).AsBoolean := not CDS.FieldByName(check_flag).AsBoolean;
CDS.Post;
end;
end;
procedure TfrmCXLookup.cxGridViewKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
if Key = VK_RETURN then btnOK.Click;
end;
class function TfrmCXLookup.Execute(aCaption, aCommand: String; aStartDate:
TDateTime = 0; aEndDate: TDateTime = 0; aMultiSelect: Boolean = False):
TfrmCXLookup;
begin
Result := TfrmCXLookup.Create(DMClient.RestConn, aMultiSelect);
// Result.MultiSelect := aMultiSelect;
Result.lblHeader.Caption := aCaption;
Result.CommandName := aCommand;
Result.StartDate.Date := aStartDate;
Result.EndDate.Date := aEndDate;
if (aStartDate = 0) and (aEndDate = 0) then Result.HideDateParams;
Result.RefreshDataSet;
end;
class function TfrmCXLookup.Execute(ADataSet: TClientDataSet; aMultiSelect:
Boolean = False; aCaption: String = 'Lookup Data'): TfrmCXLookup;
begin
Result := TfrmCXLookup.Create(DMClient.RestConn, aMultiSelect);
Result.lblHeader.Caption := aCaption;
Result.HideDateParams;
If aMultiSelect then
Result.CDS := Result.CopyDataset(aDataSet)
else
Result.CDS := aDataSet;
Result.btnRefresh.Visible := False;
Result.initView;
end;
class function TfrmCXLookup.Execute(aCaption, aCommand, aStringFilter: String;
aStartDate: TDateTime = 0; aEndDate: TDateTime = 0; aMultiSelect: Boolean =
False): TfrmCXLookup;
begin
Result := TfrmCXLookup.Create(DMClient.RestConn, aMultiSelect);
// Result.MultiSelect := aMultiSelect;
Result.StringFilter := aStringFilter;
Result.lblHeader.Caption := aCaption;
Result.CommandName := aCommand;
Result.StartDate.Date := aStartDate;
Result.EndDate.Date := aEndDate;
if (aStartDate = 0) and (aEndDate = 0) then Result.HideDateParams;
Result.RefreshDataSet;
end;
procedure TfrmCXLookup.FormKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
If Key = VK_ESCAPE then Self.Close;
if Key = VK_RETURN then btnOK.Click;
end;
procedure TfrmCXLookup.FormShow(Sender: TObject);
var
ms: Integer;
begin
ms := MilliSecondsBetween(StartExecute, Now());
lbBenchmark.Caption := 'Debug Benchmark = ' + IntToStr(ms) + ' ms';
end;
procedure TfrmCXLookup.HideDateParams;
begin
lblFilterData.Visible := False;
StartDate.Visible := False;
lblsdFilter.Visible := False;
EndDate.Visible := False;
end;
procedure TfrmCXLookup.HideFields(FieldNames: Array Of String);
begin
Self.cxGridView.SetVisibleColumns(FieldNames, False);
end;
procedure TfrmCXLookup.InitView;
var
i: Integer;
lCheckCol: TcxGridDBColumn;
begin
if FCDS = nil then exit;
cxGridView.LoadFromCDS(CDS, True, False);
for i:=0 to cxGridView.ColumnCount-1 do
begin
cxGridView.Columns[i].Options.Editing := False;
If Assigned(cxGridView.Columns[i].Properties) then
cxGridView.Columns[i].Properties.ReadOnly := True;
end;
// exit;
lCheckCol := cxGridView.GetColumnByFieldName(check_flag);
if Assigned(lCheckCol) then
begin
lCheckCol.Options.Editing := True;
lCheckCol.DataBinding.ValueType := 'Boolean';
lCheckCol.PropertiesClass := TcxCheckBoxProperties;
lCheckCol.Properties.ReadOnly := False;
lCheckCol.Index := 0;
lCheckCol.Caption := ' [X] ';
TcxCheckBoxProperties(lCheckCol).ImmediatePost := True;
end;
cxGridView.OptionsBehavior.BestFitMaxRecordCount := 200;
cxGridView.ApplyBestFit;
end;
function TfrmCXLookup.GetDatasetFromServer: TDataSet;
begin
Result := FLookupClient.GetLookupData(CommandName, StartDate.Date, EndDate.Date, StringFilter);
end;
procedure TfrmCXLookup.ShowFieldsOnly(FieldNames: Array Of String);
begin
Self.cxGridView.SetVisibleColumnsOnly(FieldNames, True);
Self.cxGridView.SetVisibleColumns([check_flag], True);
end;
procedure TfrmCXLookup.RefreshDataSet;
var
ADataSet: TDataSet;
begin
ADataSet := GetDatasetFromServer;
if Assigned(FCDS) then
FreeAndNil(FCDS);
if Assigned(ADataset) then
begin
if not MultiSelect then
CDS := TDBUtils.DSToCDS(ADataSet, Self, True)
else
CDS := Self.CopyDataset(ADataSet)
end;
if CDS <> nil then initView;
end;
procedure TfrmCXLookup.Reset;
begin
if Self.MultiSelect then
begin
CDS.DisableControls;
Try
while not CDS.Eof do
begin
CDS.FieldByName(check_flag).AsBoolean := False;
CDS.Next;
end;
Finally
CDS.EnableControls;
End;
end;
end;
procedure TfrmCXLookup.SetCheckSelected(IsChecked: Boolean = True; IsSelectAll:
Boolean = False);
var
i: Integer;
lAfterPostNotify: TDataSetNotifyEvent;
lRecNo: Integer;
begin
lAfterPostNotify := CDS.AfterPost;
CDS.AfterPost := nil;
cxGridView.DataController.BeginUpdate;
Try
If not Assigned(cxGridView.GetColumnByFieldName(check_flag)) then exit;
// If IsSelectAll then DCMain.SelectAll;
If not IsSelectAll then
begin
// cShowProgressDlg('Checking Process',cxGridView.Controller.SelectedRecordCount);
for i := 0 to cxGridView.Controller.SelectedRecordCount-1 do
begin
cxGridView.Controller.SelectedRecords[i].Focused := True;
With cxGridView.DataController.DataSource.DataSet do
begin
Edit;
FieldByName(check_flag).AsBoolean := IsChecked;
Post;
end;
// cStepProgressDlg;
end;
end else //optimize performance for select all
begin
// cShowProgressDlg('Checking Process',CDS.RecordCount);
lRecNo := CDS.RecNo;
CDS.DisableControls;
CDS.First;
while not CDS.eof do
begin
CDS.Edit;
CDS.FieldByName(check_flag).AsBoolean := IsChecked;
CDS.Post;
CDS.Next;
// cStepProgressDlg;
end;
CDS.RecNo := lRecNo;
CDS.EnableControls;
end;
// If MultiSelect then CountSelected;
Finally
// cStopProgressDlg;
CDS.AfterPost := lAfterPostNotify;
cxGridView.DataController.EndUpdate;
End;
end;
procedure TfrmCXLookup.SetMultiSelect(const Value: Boolean);
begin
FMultiSelect := Value;
If not FMultiSelect then
begin
// CDS.AfterPost := nil;
Self.cxGrid.PopupMenu := nil;
Self.cxGridView.SetVisibleColumns([check_flag], False);
end;
// else begin
// CDS.AfterPost := CDSAfterPost;
// end;
Self.cxGridView.OptionsSelection.MultiSelect := FMultiSelect;
end;
procedure TfrmCXLookup.SetResultData;
begin
if not Assigned(FCDS) then exit;
//post pending data (check)
if FCDS.State in [dsEdit, dsInsert] then
FCDS.Post;
if not Assigned(FData) then
FData := TClientDataSet.Create(Self);
FData.CloneCursor(Self.CDS, True);
if MultiSelect then
begin
FData.Filtered := True;
FData.Filter := check_flag + ' = True ';
FData.First;
end else
FData.RecNo := FCDS.RecNo;
end;
procedure TfrmCXLookup.UncheckAll1Click(Sender: TObject);
begin
SetCheckSelected(False, True);
end;
procedure TfrmCXLookup.UnCheckSelected1Click(Sender: TObject);
begin
SetCheckSelected(False);
end;
function TLookupClient.GetLookupData(aCommandName: String; aStartDate:
TDateTime = 0; aEndDate: TDateTime = 0; aStringFilter: String = ''):
TDataSet;
var
ResultParamIdx: Integer;
begin
ResultParamIdx := 0;
if FLookupCommand = nil then
begin
FLookupCommand := Fconnection.CreateCommand;
FLookupCommand.RequestType := 'GET';
FLookupCommand.Text := aCommandName;
FLookupCommand.Prepare();
end;
if (aStartDate <> 0) or (aEndDate <> 0) then
begin
FLookupCommand.Parameters[0].Value.AsDateTime := aStartDate;
FLookupCommand.Parameters[1].Value.AsDateTime := aEndDate;
ResultParamIdx := 2;
if (aStringFilter <> '') then
begin
FLookupCommand.Parameters[2].Value.AsString := aStringFilter;
ResultParamIdx := 3;
end;
end;
FLookupCommand.Execute;
Result := TCustomSQLDataSet.Create(nil,
FLookupCommand.Parameters[ResultParamIdx].Value.GetDBXReader(False), True);
Result.Open;
if FInstanceOwner then
FLookupCommand.FreeOnExecute(Result);
end;
procedure TLookupClient.PrepareCommand(aCommandName: String);
begin
if FLookupCommand = nil then
begin
FLookupCommand := Fconnection.CreateCommand;
FLookupCommand.RequestType := 'GET';
FLookupCommand.Text := aCommandName;
FLookupCommand.Prepare();
end;
end;
end.
|
unit Demo.GanttChart.ComputingStartEndDuration;
interface
uses
System.Classes, System.SysUtils, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_GanttChart_ComputingStartEndDuration = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_GanttChart_ComputingStartEndDuration.GenerateChart;
function ToMilliseconds(Minutes: Integer): Integer;
begin
Result := Minutes * 60 * 1000;
end;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_GANTT_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Resource'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Duration'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percent Complete'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Dependencies')
]);
Chart.Data.AddRow(['toTrain', 'Walk to train stop', 'walk', null, null, toMilliseconds(5), 100, null]);
Chart.Data.AddRow(['music', 'Listen to music', 'music', null, null, toMilliseconds(70), 100, null]);
Chart.Data.AddRow(['wait', 'Wait for train', 'wait', null, null, toMilliseconds(10), 100, 'toTrain']);
Chart.Data.AddRow(['train', 'Train ride', 'train', null, null, toMilliseconds(45), 75, 'wait']);
Chart.Data.AddRow(['toWork', 'Walk to work', 'walk', null, null, toMilliseconds(10), 0, 'train']);
Chart.Data.AddRow(['work', 'Sit down at desk', null, null, null, toMilliseconds(2), 0, 'toWork']);
// Options
Chart.Options.Gantt('defaultStartDateMillis', EncodeDate(2015, 4, 28));
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="margin: auto; width: 80%; height: 100%; padding: 100px;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_GanttChart_ComputingStartEndDuration);
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BVE.SVG2Image.VCL, Vcl.StdCtrls,
Vcl.ExtCtrls, BVE.SVG2Control.VCL;
type
TForm1 = class(TForm)
SVG2Image1: TSVG2Image;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure SVG2Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SVG2Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.Math;
{$R *.dfm}
// You can download the cards SVG from this location:
// http://svg-cards.sourceforge.net/
// Then, set the SVG2Image1 FileName property to the downloaded svg file
// A couple of cards to show at random
const
cards: array[0..9] of string = ('7_diamond', '10_spade', '1_spade',
'3_heart', 'queen_heart', '5_diamond', '2_club', 'jack_diamond',
'king_club', 'black_joker');
procedure TForm1.SVG2Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
SVG2Image1.RootID := 'back';
end;
procedure TForm1.SVG2Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i: integer;
begin
i := RandomRange(0, 9);
Caption := cards[i];
SVG2Image1.RootID := cards[i];
end;
end.
|
unit HandlebarsTestCase;
{$mode objfpc}{$H+}
interface
uses
fpjson, Handlebars, LuiJSONUtils, TestFramework;
type
{ THandlebarsTestCase }
THandlebarsTestCase = class(TTestCase)
protected
procedure CheckRender(const Template: String; const Elements : Array of Const;
const Expected: String);
procedure CheckRender(const Template, DataString, Expected: String);
end;
implementation
function RenderAndFree(const Template: String; Data: TJSONObject): String;
begin
Result := RenderTemplate(Template, Data);
Data.Free;
end;
function RenderString(const Template, DataString: String): String;
var
Data: TJSONObject;
begin
Data := StrToJSON(DataString) as TJSONObject;
Result := RenderTemplate(Template, Data);
Data.Free;
end;
{ THandlebarsTestCase }
procedure THandlebarsTestCase.CheckRender(const Template: String;
const Elements: array of const; const Expected: String);
begin
CheckEquals(Expected, RenderAndFree(Template, TJSONObject.Create(Elements)));
end;
procedure THandlebarsTestCase.CheckRender(const Template, DataString,
Expected: String);
begin
CheckEquals(Expected, RenderString(Template, DataString));
end;
end.
|
unit UnitFormMain;
{===============================================================================
CodeRage 9 - Demo for TTask
This code shows how to use a parallel Task procedure.
Author: Danny Wind
===============================================================================}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Ani;
type
TFormMain = class(TForm)
ButtonTask1: TButton;
ScrollBarActivity: TScrollBar;
FloatAnimationActivity: TFloatAnimation;
LabelTask1: TLabel;
procedure ButtonTask1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
uses
System.Threading;
procedure TFormMain.ButtonTask1Click(Sender: TObject);
var
lValue: Integer;
begin
LabelTask1.Text := '--';
TTask.Run( procedure
begin
{Some calculation that takes time}
Sleep(3000);
lValue := Random(10);
TThread.Synchronize(nil, procedure
begin
LabelTask1.Text := lValue.ToString;
end);
end );
end;
end.
|
unit DPM.IDE.DesignManager;
interface
uses
System.Classes;
type
IDPMIDEDesignManager = interface
['{31ADC6E0-7B8E-4203-A635-7D02FC4C0FC7}']
end;
TDPMIDEDesignManager = class(TInterfacedObject, IDPMIDEDesignManager)
private
FPaths : TStringList;
protected
procedure RemovePath(const APath : string);
procedure EnsurePath(const APath: string);
public
constructor Create;
destructor Destroy;override;
end;
implementation
uses
WinApi.Windows,
System.SysUtils,
System.StrUtils;
{ TDPMIDEDesignManager }
constructor TDPMIDEDesignManager.Create;
var
i: Integer;
begin
FPaths := TStringList.Create;
FPaths.Duplicates := TDuplicates.dupIgnore;
FPaths.CaseSensitive := false;
FPaths.Sorted := false;
FPaths.Delimiter := ';';
FPaths.DelimitedText := GetEnvironmentVariable('PATH');
for i := 0 to FPaths.Count -1 do
FPaths.Objects[i] := TObject(1); //set the reference count for the path entry so we don't remove ones that
// that were there on startup.
end;
destructor TDPMIDEDesignManager.Destroy;
begin
FPaths.Free;
inherited;
end;
procedure SetEnvironmentVariable(const Name, Value: string);
begin
WinApi.Windows.SetEnvironmentVariable(PChar(Name), PChar(Value));
end;
procedure TDPMIDEDesignManager.EnsurePath(const APath: string);
var
i : integer;
count : integer;
begin
i := FPaths.IndexOf(APath);
if i = -1 then
begin
FPaths.InsertObject(0, APath, TObject(1));
SetEnvironmentVariable('PATH', FPaths.DelimitedText);
end
else
begin
//already there, so just increment the reference count;
count := Integer(FPaths.Objects[i]);
Inc(count);
FPaths.Objects[i] := TObject(count);
end;
end;
procedure TDPMIDEDesignManager.RemovePath(const APath: string);
var
i : integer;
count : integer;
begin
i := FPaths.IndexOf(APath);
if i = -1 then
exit;
count := Integer(FPaths.Objects[i]);
if count > 1 then
begin
Dec(count);
FPaths.Objects[i] := TObject(count);
end
else
begin
FPaths.Delete(i);
SetEnvironmentVariable('PATH', FPaths.DelimitedText);
end;
end;
end.
|
unit uFrmDataBaseSet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfrmDataBaseSet = class(TForm)
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
edtAddr: TEdit;
edtUser: TEdit;
edtPassWord: TEdit;
btnOk: TButton;
btnCancel: TButton;
procedure btnOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
function SaveCfg: Boolean;
procedure LoadCfg;
public
{ Public declarations }
end;
var
frmDataBaseSet: TfrmDataBaseSet;
implementation
uses IniFiles, WMFBData_Impl;
{$R *.dfm}
procedure TfrmDataBaseSet.LoadCfg;
var
aFilePath: string;
aIni: TIniFile;
begin
aFilePath := ExtractFilePath(ParamStr(0)) + ServerCfgFile;
if not FileExists(aFilePath) then
begin
FileCreate(aFilePath)
end;
aIni := TIniFile.Create(aFilePath);
try
edtAddr.Text := aIni.ReadString('DataBase', 'ServerAddr', '127.0.0.1');
edtPassWord.Text := aIni.ReadString('DataBase', 'Password', '123456');
edtUser.Text := aIni.ReadString('DataBase', 'User', 'sa');
finally
aIni.Free;
end;
end;
function TfrmDataBaseSet.SaveCfg: Boolean;
var
aFilePath: string;
aIni: TIniFile;
begin
Result := False;
aFilePath := ExtractFilePath(ParamStr(0)) + ServerCfgFile;
if not FileExists(aFilePath) then
begin
FileCreate(aFilePath)
end;
aIni := TIniFile.Create(aFilePath);
try
aIni.WriteString('DataBase', 'ServerAddr', Trim(edtAddr.Text));
aIni.WriteString('DataBase', 'Password', Trim(edtPassWord.Text));
aIni.WriteString('DataBase', 'User', Trim(edtUser.Text));
Result := True;
finally
aIni.Free;
end;
end;
procedure TfrmDataBaseSet.btnOkClick(Sender: TObject);
begin
if SaveCfg() then
ModalResult := mrOk;
end;
procedure TfrmDataBaseSet.FormShow(Sender: TObject);
begin
LoadCfg();
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtBase,
NtLocalization,
NtTranslator,
NtLanguageDlg;
procedure TForm1.FormCreate(Sender: TObject);
resourcestring
STwo = 'Two';
begin
Label2.Caption := STwo;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if TNtLanguageDialog.Select('en') then
FormCreate(Self);
end;
initialization
// If a resource DLL has been loaded then check if the version of DLL and application match.
// If not then make application not to use the DLL.
if LoadedResourceLocale <> '' then
begin
if not TNtResource.DoesVersionMatch then
begin
// Inform user that versions do not match
ShowMessage(Format(
'The version of "%0:s" resource DLL file does not match to "%1:s" application file.'#13#10 +
'The application can not run correctly because the old resource DLL may cause the application to crash.'#13#10 +
'The application rejected the DLL and is now using resource of EXE file.',
[TNtBase.GetLanguageFile(Application.ExeName, LoadedResourceLocale), Application.ExeName]));
// Force application not to use the resource DLL
TNtTranslator.SetNew('');
end;
end;
end.
|
unit stackatd; {Абстрактный тип - стек}
interface
type usertype = string;
type stacktype = ^stacks;
stacks = record
x : usertype;
link : stacktype
end;
type stack = object
public
constructor init; {инициализация}
procedure addstack (info : usertype); {добавить в стек}
procedure popstack (var info : usertype; var Success : boolean); {взять из стека}
procedure changestack(var Success : boolean); {меняет стек наоборот}
destructor deletestack; {очистить стек}
private
top : stacktype;
end;
implementation
constructor stack.init;
begin
top := nil
end;
procedure stack.addstack (info : usertype);
var p : stacktype;
begin
p := top;
new (top);
top^.x := info;
top^.link := p
end;
procedure stack.popstack (var info : usertype; var Success : boolean);
var p : stacktype;
begin
if top = nil then
Success := false
else begin
info := top^.x;
p := top;
top := top^.link;
dispose (p);
Success := true
end
end;
procedure stack.changestack (var Success : boolean);
var x : string;
temp : stack;
begin
temp.init;
if top = nil then
Success := false
else begin
While top <> nil do begin
popstack (x, success);
temp.addstack (x);
Success := true
end;
while success do begin
temp.popstack (x, success);
if success then
addstack (x)
end;
Success := true;
temp.deletestack
end
end;
destructor stack.deletestack;
var p : stacktype;
begin
while top <> nil do begin
p := top;
top := top^.link;
dispose (p)
end
end;
end.
|
program lab_8;
function getIdGroupByNameGroup(arrNumGroup: array of string; nGroup:string):integer;
var
idGroup: integer;
begin
for idGroup:= 0 to Length(arrNumGroup) - 1 do
begin
if (arrNumGroup[idGroup] = nGroup) then
begin
getIdGroupByNameGroup:= idGroup;
break
end;
end;
end;
procedure setBestSubject(arrSubject: array of string; averageMarksSubjects:array of real; numberStudents: integer;
var bestsSubjects: set of string);
var
idSubject: integer;
numberSubject: integer:= Length(arrSubject);
maxMarkSubject: real:= 0;
begin
//calculation mark subject
for idSubject:= 0 to (numberSubject - 1) do
begin
averageMarksSubjects[idSubject]:= averageMarksSubjects[idSubject] / numberStudents;
//find max mark subject
if (maxMarkSubject < averageMarksSubjects[idSubject]) then
maxMarkSubject:= averageMarksSubjects[idSubject];
end;
for idSubject:= 0 to Length(averageMarksSubjects) - 1 do
begin
if (averageMarksSubjects[idSubject] = maxMarkSubject) then
begin
include(bestsSubjects, arrSubject[idSubject]);
end;
end;
end;
procedure sortGroups(var averageMarksGroups:array of real; numberStudentInGroup: array of byte;
var arrNumGroup: array of string);
var
idGroup, i, j: integer;
tempNGroup: string;
tempMarks: real;
numberGroup: integer:= Length(arrNumGroup);
begin
//calculation marks groups
for idGroup:= 0 to numberGroup - 1 do
begin
if (averageMarksGroups[idGroup] <> 0) then
averageMarksGroups[idGroup]:= averageMarksGroups[idGroup]/numberStudentInGroup[idGroup];
writeln(arrNumGroup[idGroup],' -> ',averageMarksGroups[idGroup],';');
end;
for i:= 0 to numberGroup - 1 do
for j:= i + 1 to numberGroup - 1 do
begin
if (averageMarksGroups[j] > averageMarksGroups[i]) then
begin
//for maks
tempMarks:= averageMarksGroups[i];
averageMarksGroups[i]:= averageMarksGroups[j];
averageMarksGroups[j]:= tempMarks;
//for name groups
tempNGroup:= arrNumGroup[i];
arrNumGroup[i]:= arrNumGroup[j];
arrNumGroup[j]:= tempNGroup;
end;
end;
end;
type
session = record
surname: string;
group: string;
subject: record
maths: integer;
physics: integer;
programming: integer;
end;
end;
calculations = record
end;
var
summerSession: array of session;
arrSurname: array of string:=(
'Поух', 'Арт', 'Гирень',
'Сухоцкая', 'Мелешко', 'Крупский'
);
arrNumGroup: array of string:=(
'ПЗТ-23', 'ПЗТ-24', 'ПЗТ-25'
);
arrSubject: array of string:=(
'maths', 'physics', 'programming'
);
averageMarksStudents, averageMarksGroups, averageMarksSubjects: array of real;
numberStudentInGroup: array of byte;
notBestStudent: string:= 'Увы, таких нет';
isGroup: set of string;
bestsSubjects: set of string;
bestsStudents: set of string:=[
notBestStudent
];
numberStudents: integer:= Length(arrSurname);
numberGroup: integer:= Length(arrNumGroup);
numberSubject: integer:= Length(arrSubject);
idStudent, idGroup, i: integer;
begin
//Set length array
SetLength(summerSession, numberStudents);
SetLength(averageMarksStudents, numberStudents);
SetLength(averageMarksGroups, numberGroup);
SetLength(averageMarksSubjects, numberSubject);
SetLength(numberStudentInGroup, numberGroup);
//set information about student
for idStudent:= 0 to (numberStudents - 1) do
with summerSession[idStudent] do
begin
writeln;
writeln('//--------------------//');
surname:= arrSurname[idStudent];
writeln('ФИО: ', surname);
group:= arrNumGroup[random(numberGroup)];
writeln('Группа: ', group);
writeln;
writeln('Оценки по предметам:');
subject.maths:= random(11);
writeln('Математика: ', subject.maths);
subject.physics:= random(11);
writeln('Физика: ', subject.physics);
subject.programming:= random(11);
writeln('Программирование: ', subject.programming);
end;
for idStudent:= 0 to (numberStudents - 1) do
with summerSession[idStudent] do
begin
//calculation average mark students
averageMarksStudents[idStudent]:= (subject.maths + subject.physics + subject.programming)/numberGroup;
//calculation subject
averageMarksSubjects[0]:= averageMarksSubjects[0] + subject.maths;
averageMarksSubjects[1]:= averageMarksSubjects[1] + subject.physics;
averageMarksSubjects[2]:= averageMarksSubjects[2] + subject.programming;
//calculation average mark group
idGroup:= getIdGroupByNameGroup(arrNumGroup, group);
averageMarksGroups[idGroup]:= averageMarksGroups[idGroup] + averageMarksStudents[idStudent];
numberStudentInGroup[idGroup]:= numberStudentInGroup[idGroup] + 1;
//best students
if (averageMarksStudents[idStudent] >= 9) then
begin
exclude(bestsStudents, notBestStudent);
include(bestsStudents, surname);
end;
end;
setBestSubject(arrSubject, averageMarksSubjects, numberStudents, bestsSubjects);
writeln;
writeln('//--------Итоги---------//');
writeln('Фамилии лучших студентов -> ', bestsStudents);
writeln('Название предметов, которые были сданы лучше всего -> ', bestsSubjects);
writeln('Средняя успеваемость студентов в группе:');
sortGroups(averageMarksGroups, numberStudentInGroup, arrNumGroup);
writeln('Номера группа в порядке убывания успеваемости студентов -> ', arrNumGroup);
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jpeg, ExtCtrls, Math;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Label5: TLabel;
Label6: TLabel;
Image1: TImage;
Image2: TImage;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function fa(x:real):real;
begin
fa:=1/(sqrt(x*x-x+1))
end;
function fb(x:real):real;
begin
fb:=cos(x)/(4+(sin(x)*sin(x)));
end;
procedure LevPr1(a,b:real;n:integer);
var
h,x,c1:real; i:integer;
begin
h:=(b-a)/n;
for i:=0 to n-1 do
begin
x:=a+h*i;
c1:=c1+fa(x);
end;
c1:=c1*h;
c1:=SimpleRoundTo(c1,-6);
Form1.Memo1.Lines.Add(floattostr(c1));
end;
procedure PravPr1(a,b:real;n:integer);
var
x,h,c2:real; i:integer;
begin
h:=(b-a)/n;
for i:=1 to n do
begin
x:=a+h*i;
c2:=c2+fa(x);
end;
c2:=c2*h;
c2:=SimpleRoundTo(c2,-6);
Form1.Memo1.Lines.Add(floattostr(c2));
end;
procedure SredPr1(a,b:real;n:integer);
var
x,h,c3:real; i:integer;
begin
h:=(b-a)/n;
for i:=0 to n-1 do
begin
x:=a+h*i;
c3:=c3+fa(x+h/2);
end;
c3:=c3*h;
c3:=SimpleRoundTo(c3,-6);
Form1.Memo1.Lines.Add(floattostr(c3));
end;
procedure Simps1(a,b:real;n:integer);
var
x,h,c,z,y1:real; i:integer;
begin
h:=(b-a)/n;
c:=fa(a)+fa(b);
z:=1;
x:=a+h;
for i:=1 to n-1 do
begin
c:=c+((3+z)*fa(x));
x:=x+h;
z:=-z;
end;
y1:=c*h/3;
y1:=SimpleRoundTo(y1,-6);
Form1.Memo1.Lines.Add(floattostr(y1));
end;
procedure Trapec1(a,b:real;n:integer);
var
x,h,c:real; i:integer;
begin
h:=(b-a)/n;
for i:=1 to n-1 do
begin
x:=a+h*i;
c:=c+fa(x+h/2);
end;
c:=(c*h)+(( fa(a)+fa(b))/2)*h;
c:=SimpleRoundTo(c,-6);
Form1.Memo1.Lines.Add(floattostr(c));
end;
procedure LevPr2(a,b:real;n:integer);
var
h,x,ci1:real; i:integer;
begin
h:=(b-a)/n;
for i:=0 to n do
begin
x:=a+h*i;
ci1:=ci1+fb(x);
end;
ci1:=ci1*h;
ci1:=SimpleRoundTo(ci1,-6);
Form1.Memo1.Lines.Add(floattostr(ci1));
end;
procedure PravPr2(a,b:real;n:integer);
var
x,h,ci2:real; i:integer;
begin
h:=(b-a)/n;
for i:=1 to n-1 do
begin
x:=a+h*i;
ci2:=ci2+fb(x);
end;
ci2:=ci2*h;
ci2:=SimpleRoundTo(ci2,-6);
Form1.Memo1.Lines.Add(floattostr(ci2));
end;
procedure SredPr2(a,b:real;n:integer);
var
x,h,ci3:real; i:integer;
begin
h:=(b-a)/n;
for i:=0 to n-1 do
begin
x:=a+h*i;
ci3:=ci3+fb(x+h/2);
end;
ci3:=ci3*h;
ci3:=SimpleRoundTo(ci3,-6);
Form1.Memo1.Lines.Add(floattostr(ci3));
end;
procedure Simps2(a,b:real;n:integer);
var
x,h,c,z,y2:real; i:integer;
begin
h:=(b-a)/n;
c:=fb(a)+fb(b);
z:=1;
x:=a+h;
for i:=1 to n-1 do
begin
c:=c+((3+z)*fb(x));
x:=x+h;
z:=-z;
end;
y2:=c*h/3;
y2:=SimpleRoundTo(y2,-6);
Form1.Memo1.Lines.Add(floattostr(y2));
end;
procedure Trapec2(a,b:real;n:integer);
var
x,h,ci4:real; i:integer;
begin
h:=(b-a)/n;
for i:=0 to n-1 do
begin
x:=a+h*i;
ci4:=ci4+fb(x+h/2);
end;
ci4:=(ci4*h)+(( fb(a)+fb(b))/2)*h;
ci4:=SimpleRoundTo(ci4,-6);
Form1.Memo1.Lines.Add(floattostr(ci4));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
a,b,e,I1,I2,t,o6,o7,o8,o9,o10:real; n,k:integer;
begin
a:=strtofloat(Edit1.Text);
b:=strtofloat(Edit2.Text);
n:=strtoint(Edit3.Text);
Form1.Memo1.Lines.Add('Методом левых прямоугольников: ');
LevPr1(a,b,n);
Form1.Memo1.Lines.Add('Методом правых прямоугольников: ');
PravPr1(a,b,n);
Form1.Memo1.Lines.Add('Методом средних прямоугольников: ');
SredPr1(a,b,n);
Form1.Memo1.Lines.Add('Методом Симпсона: ');
Simps1(a,b,n);
Form1.Memo1.Lines.Add('Методом трапеций: ');
Trapec1(a,b,n);
Form1.Memo1.Lines.Add('----------------------------------')
end;
procedure TForm1.Button2Click(Sender: TObject);
var
a,b,e,I1,I2,t,o1,o2,o3,o4,o5:real; n,k:integer;
begin
a:=strtofloat(Edit1.Text);
b:=strtofloat(Edit2.Text);
n:=strtoint(Edit3.Text);
Form1.Memo1.Lines.Add('Методом левых прямоугольников: ');
LevPr2(a,b,n);
Form1.Memo1.Lines.Add('Методом правых прямоугольников: ');
PravPr2(a,b,n);
Form1.Memo1.Lines.Add('Методом средних прямоугольников: ');
SredPr2(a,b,n);
Form1.Memo1.Lines.Add('Методом Симпсона: ');
Simps2(a,b,n);
Form1.Memo1.Lines.Add('Методом трапеций: ');
Trapec2(a,b,n);
Form1.Memo1.Lines.Add('-----------------------------------')
end;
end.
|
{
This application uses runtime packages. It means that all VCL resource strings such
as message dialog text are not compiled into MessageDlg.exe but are in vclXXX.bpl (vcl250.bpl in Delphi 10.2 Tokyo).
This is why you also have to localize teh package file.
- MessageDlg.exe Original English EXE.
- MessageDlg.fi Finnish resources for the EXE.
- vcl250.bpl Original English package file.
- vcl250.fi Finnish resources for the package file.
}
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
LanguageButton: TButton;
ShowButton: TButton;
procedure LanguageButtonClick(Sender: TObject);
procedure ShowButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
UITypes,
NtTranslator,
NtLanguageDlg;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
TNtLanguageDialog.Select('en');
end;
procedure TForm1.ShowButtonClick(Sender: TObject);
resourcestring
SMsg = 'Hello World';
begin
MessageDlg(SMsg, mtInformation, [mbYes, mbNo, mbHelp], 0);
end;
end.
|
{
Catarinka Loopers
TStringLoop, TSepStringLoop, TCSVLoop
Copyright (c) 2003-2019 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Tired of limited for-to loops? TStringLoop makes it easy to iterate over each
string in a string list while, optionally, looking for defined patterns.
Usage Examples:
Use TStringLoop to iterate over each string in a string list:
s := TStringLoop.Create(listbox1.items);
while s.found do
showmessage(s.current);
s.free;
Use TSepStringLoop instead to do the same with a separated string:
s := TSepStringLoop.Create('str1;str2;str3',';');
while s.found do
showmessage(s.current);
s.free;
Call Stop, Stop(aVariant) or Break to end the loop:
while s.found do
if s.currentlower = 'somestring' then
result := s.stop(true); // stops the loop, returning true
Use the Pattern property to call a variety of chainable pattern matching
methods:
while s.found do
if s.pattern.begins(['http://','https://']).ends('.com').match then
showmessage(s.current);
Call Reset if you want to repeat from the beginning:
while s.found do
showmessage(s.current);
s.reset;
while s.found do
showmessage(s.current);
ChangeLog:
22.08.2020:
- Added CurrentNameValue and NameValueSeparator properties for dealign with
lines that are name value pair like: somename=somevalue
26.08.2017:
- Moved TStringLoop's CSV methods to a separate class (TCSVLoop)
- Reset TSepStringLoop when setting a new string
05.08.2017:
- Added Pattern property that allows to call pattern matching functions
- Removed Contains() which now can be called through Pattern property.
Example:
Pattern.Contains().Match or .MatchI
- Added overloaded Stop() with result.
}
unit CatStringLoop;
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils, System.Variants,
{$ELSE}
Classes, SysUtils, Variants,
{$ENDIF}
CatStrings, CatPatterns;
{ TStringLoop loops through a string list }
type
TStringLoop = class
protected
fCurrent: string;
fList: TStringList;
fNameValueSeparator: string;
fPattern: TStringPattern;
fPosition: integer;
function GetCount: integer;
function GetCountAsStr: string;
function GetCurrentNameValue:TCatNameValue;
function GetCurrentLower: string;
function GetCurrentUpper: string;
procedure SetCurrent(const s: string); virtual;
procedure SetCurrentLine(const s: string);
public
constructor Create(const sl: tstrings = nil); overload; virtual;
constructor Create(const list:string); overload;
destructor Destroy; override;
procedure Load(const sl: tstrings);
procedure LoadFromString(const s: string);
procedure LoadFromFile(const filename: string);
procedure Reset; virtual;
procedure Reverse;
procedure Stop; overload;
function Stop(aReturn:Variant):Variant; overload;
procedure Clear;
function Found: boolean;
function Index(const zerostart: boolean = true): integer;
function IndexAsStr: string;
function IndexOf(const s: string): integer;
procedure Delete;
// properties
property Count: integer read GetCount;
property CountAsStr:string read GetCountAsStr;
property Current: string read fCurrent write SetCurrentLine;
property CurrentNameValue: TCatNameValue read GetCurrentNameValue;
property CurrentLower: string read GetCurrentLower;
property CurrentUpper: string read GetCurrentUpper;
property NameValueSeparator: string read fNameValueSeparator write fNameValueSeparator;
property List: TStringList read FList;
property Pattern: TStringPattern read fPattern;
end;
{ TSepStringLoop loops through a pipe-separated string.
A different separator can be used }
type
TSepStringLoop = class
protected
fCount: integer;
fCurrent: string;
fPattern: TStringPattern;
fPos: integer;
fTags: string; // a separated string
fSeparator: string;
procedure SetTags(const s: string);
procedure SetCurrent(const s: string);
public
constructor Create(const tags: string = ''; const asep: string = '|');
destructor Destroy; override;
function Found: boolean;
procedure Reset;
procedure Stop; overload;
function Stop(aReturn:Variant):Variant; overload;
// properties
property Count: integer read fCount;
property Current: string read fCurrent;
property Pattern: TStringPattern read fPattern;
property Position: integer read fPos;
property Separator: string read fSeparator write fSeparator;
property Tags: string read fTags write SetTags;
end;
{ TCSVLoop loops through a comma-separated value (CSV) list }
type
TCSVLoop = class(TStringLoop)
protected
fCSV: TStringList;
function GetLine(const l: integer): string;
procedure SetLine(const l: integer; const v: string);
procedure SetCurrent(const s: string); override;
function GetValue(const s: string): string;
procedure SetValue(const s: string; const v: string);
public
constructor Create(const sl: tstrings = nil); override;
destructor Destroy; override;
procedure Reset; override;
// properties
property Lines[const l: integer]: string read GetLine write SetLine;
property Values[const s: string]: string read GetValue
write SetValue; default;
end;
implementation
function TStringLoop.GetCount: integer;
begin
result := fList.Count;
end;
procedure TStringLoop.Delete;
begin
fList.Delete(FPosition - 1);
end;
procedure TStringLoop.Stop;
begin
FPosition := fList.Count;
end;
function TStringLoop.Stop(aReturn:Variant):Variant;
begin
Result := aReturn;
Stop;
end;
function TStringLoop.GetCurrentUpper: string;
begin
result := uppercase(FCurrent);
end;
function TStringLoop.GetCurrentLower: string;
begin
result := lowercase(FCurrent);
end;
function TStringLoop.GetCurrentNameValue: TCatNameValue;
begin
result := StrToNameValue(FCurrent, fNameValueSeparator);
end;
function TStringLoop.IndexAsStr: string;
begin
result := inttostr(FPosition);
end;
function TStringLoop.GetCountAsStr: string;
begin
result := inttostr(fList.Count);
end;
function TStringLoop.IndexOf(const s: string): integer;
begin
result := fList.IndexOf(s);
end;
function TStringLoop.Index(const zerostart: boolean = true): integer;
begin
result := FPosition;
if zerostart then
result := FPosition - 1;
end;
procedure TStringLoop.Clear;
begin
fList.Clear;
Reset;
end;
// Replaces the content of the current line with a new string
procedure TStringLoop.SetCurrentLine(const s: string);
begin
SetCurrent(s);
fList[FPosition - 1] := s;
end;
procedure TStringLoop.SetCurrent(const s: string);
begin
FCurrent := s;
FPattern.Text := s;
end;
function TStringLoop.Found: boolean;
var
i: integer;
begin
result := false;
i := FPosition;
if i < fList.Count then
begin
result := true;
SetCurrent(fList[i]);
FPosition := FPosition + 1;
end;
end;
procedure TStringLoop.Reset;
begin
FPosition := 0;
SetCurrent(emptystr);
end;
procedure TStringLoop.Reverse;
var outlst:TStringList; i:integer;
begin
outlst := TStringList.Create;
for i := fList.Count - 1 downto 0 do
outlst.Add(fList[i]);
fList.Text := outlst.Text;
outlst.Free;
end;
procedure TStringLoop.LoadFromFile(const filename: string);
begin
fList.LoadFromFile(filename);
Reset;
end;
procedure TStringLoop.LoadFromString(const s: string);
begin
fList.text := s;
Reset;
end;
procedure TStringLoop.Load(const sl: tstrings);
begin
LoadFromString(sl.text);
end;
constructor TStringLoop.Create(const sl: tstrings = nil);
begin
fNameValueSeparator := '=';
fList := tstringlist.Create;
fPattern := TStringPattern.Create;
fPattern.AllowLock := false;
if sl <> nil then
Load(sl);
Reset;
end;
constructor TStringLoop.Create(const list:string);
begin
Create;
LoadFromString(list);
end;
destructor TStringLoop.Destroy;
begin
fPattern.Free;
fList.free;
inherited;
end;
{------------------------------------------------------------------------------}
{TCSVLoop}
procedure TCSVLoop.Reset;
begin
inherited Reset;
fcsv.Clear;
end;
procedure TCSVLoop.SetCurrent(const s: string);
begin
inherited SetCurrent(s);
fcsv.commatext := FCurrent;
end;
function TCSVLoop.GetLine(const l: integer): string;
begin
try
result := fcsv[l];
except
end;
end;
procedure TCSVLoop.SetLine(const l: integer; const v: string);
begin
try
fcsv[l] := v;
except
end;
SetCurrentLine(fcsv.commatext);
end;
function TCSVLoop.GetValue(const s: string): string;
begin
result := fcsv.Values[s];
end;
procedure TCSVLoop.SetValue(const s, v: string);
begin
fcsv.Values[s] := v;
SetCurrentLine(fcsv.commatext);
end;
constructor TCSVLoop.Create(const sl: tstrings = nil);
begin
fcsv := tstringlist.Create;
inherited Create(sl);
end;
destructor TCSVLoop.Destroy;
begin
inherited;
fcsv.Free;
end;
{------------------------------------------------------------------------------}
{TSepStringLoop}
function TSepStringLoop.Found: boolean;
begin
result := false;
if fTags = emptystr then
exit;
fCount := occurs(fSeparator, fTags) + 1;
if fPos < fCount then
begin
fPos := fPos + 1;
SetCurrent(gettoken(fTags, fSeparator, fPos));
result := true;
end;
end;
procedure TSepStringLoop.SetTags(const s: string);
begin
fTags := s;
Reset;
end;
procedure TSepStringLoop.Reset;
begin
SetCurrent(emptystr);
fPos := 0;
end;
procedure TSepStringLoop.SetCurrent(const s: string);
begin
fCurrent := s;
fPattern.Text := s;
end;
procedure TSepStringLoop.Stop;
begin
fPos := fCount;
end;
function TSepStringLoop.Stop(aReturn:Variant):Variant;
begin
Result := aReturn;
Stop;
end;
constructor TSepStringLoop.Create(const tags: string = '';
const asep: string = '|');
begin
fPattern := TStringPattern.Create;
fPattern.AllowLock := false;
SetTags(tags);
fSeparator := asep;
end;
destructor TSepStringLoop.Destroy;
begin
fPattern.Free;
inherited;
end;
end.
|
unit Unit4;
interface
function GetValue: String;
implementation
function GetValue: String;
begin
Result := 'This is another sample';
end;
end.
|
unit nsUtils;
interface
uses
Windows, Messages, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ShellAPI, CommCtrl, Registry, ShlObj, ActiveX,
WinSvc, nsGlobals, nsTypes, IdSMTP, IdExplicitTLSClientServerBase, MMSystem,
nsCrypt, Math, TypInfo, IdSSLOpenSSL, FileCtrl, SysUtils;
procedure SetFileModifiedTime(const AFileName: string; const ADateTime: TDateTime);
function MangleFileName(const AFileName: string): string;
function IntToFontStyle(AValue: integer): TFontStyles;
function FontStyleToInt(AStyle: TFontStyles): integer;
function GetLastLocalResponse: string;
function FolderExists(const Directory: string): Boolean;
function FindTreeNode(ATreeView: TTreeView; AData: Pointer): TTreeNode;
function FindListItem(AListView: TListView; AData: TNSItem): TListItem;
procedure SaveSettings;
procedure RestoreSettings;
procedure SaveFormSettings(AForm: TForm);
procedure RestoreFormSettings(AForm: TForm);
procedure GetDefaultProxySettings(var ProxyServer, ProxyPort: string);
procedure CreateImageLists;
procedure DestroyImageLists;
procedure NSChangeNotify(hWndSender: HWnd; uMsg: DWORD; dwFlags: DWORD; ANSCollection: TNSCollection;
ANSItem: TNSItem);
function FormatSize(const ASize: int64; AExactSize: Boolean): string;
procedure PlaySoundEvent(const AEventLabel: string);
function ExecWait(const Cmd: string; const ATimeOut: integer): integer;
procedure ExecuteApp(const Cmd: string);
procedure WriteAppPathToRegistry;
function CopyFileRaw(lpSrcName: PChar; lpDstName: PChar; lpProgressRoutine: TFNProgressRoutine;
lpData: Pointer; pbCancel: PBool; dwCopyFlags: DWORD): Boolean;
function ConnectToNAS(const AWnd: HWND; const ANetPath, AUserName, APassword: string;
var AConnection: string): Boolean;
procedure DisconnectNAS(const AConnection: string);
function IsValidEmail(email: string): Boolean;
function GetDrives: string;
function GetCDDrives: string;
function FileGetSize(const AFileName: string): int64; overload;
function FileGetSize(const ASR: TSearchRec): int64; overload;
function FileGetSize(const ASR: TFTPSearchRec): int64; overload;
function FileGetModified(const ASR: TSearchRec): TDateTime; overload;
function FileGetModified(const ASR: TFTPSearchRec): TDateTime; overload;
function TicksToTime(const ATicks: cardinal): string;
procedure UpdateVistaFonts(const AForm: TCustomForm);
function SelectDir(const Caption: string; var Directory: string; Root: TRootFolder = rfDesktop;
Options: TSelectDirExtOpts = [sdNewFolder]): Boolean;
implementation
const
PrivateKey3 = '@vTjmrl)8#4bdrf_988uyhUTbhjbh_cvzx&*5l';
// 29.04.2004
// New Table to allow some additional symbols in filenames
HashTable: array[Ansichar] of Ansichar = (
#0, #8, #7, #23, #6, #124, #4, #2, #1, #10, #9, #26, #14, #34, #12, #22, #25,
#17, #24, #20, #19, #31, #15, #3, #18, #16, #11, #30, #29, #28, #27, #21, #69,
#169, #13, #167, #91, #181, #146, #61, #148, #242, #42, #194, #137, #138, #88, #47, #109,
#85, #120, #115, #114, #102, #121, #83, #87, #105, #180, #147, #60, #39, #62, #63, #96,
#89, #70, #110, #118, #32, #66, #81, #95, #76, #108, #79, #73, #77, #90, #75, #113,
#71, #97, #55, #101, #49, #106, #56, #46, #65, #78, #36, #92, #93, #247, #72, #64,
#82, #112, #104, #119, #84, #53, #103, #99, #57, #86, #122, #74, #48, #67, #116, #98,
#80, #52, #51, #111, #117, #68, #100, #50, #54, #107, #125, #5, #123, #252, #214, #170,
#153, #177, #143, #196, #240, #249, #182, #176, #44, #45, #139, #164, #154, #204, #131, #202,
#210, #38, #59, #40, #152, #155, #151, #149, #129, #141, #150, #163, #171, #190, #217, #185,
#243, #213, #156, #140, #187, #168, #35, #166, #33, #128, #157, #183, #253, #238, #175, #136,
#130, #207, #179, #58, #37, #135, #172, #241, #160, #186, #165, #239, #237, #158, #244, #198,
#193, #43, #224, #132, #255, #192, #209, #200, #215, #144, #230, #142, #208, #232, #178, #205,
#199, #145, #219, #212, #162, #127, #201, #223, #159, #222, #211, #231, #251, #218, #216, #195,
#233, #250, #245, #228, #254, #203, #220, #206, #225, #235, #234, #246, #189, #174, #188, #133,
#184, #41, #161, #191, #227, #236, #94, #248, #134, #226, #221, #126, #173, #229, #197);
procedure SetFileModifiedTime(const AFileName: string; const ADateTime: TDateTime);
var
hFile: integer;
lpSystemTime: TSystemTime;
lpFileTime: TFileTime;
lpLocalFileTime: TFileTime;
begin
hFile := FileOpen(AFileName, fmOpenReadWrite or fmShareDenyWrite);
if hFile <> -1 then
try
DateTimeToSystemTime(ADateTime, lpSystemTime);
SystemTimeToFileTime(lpSystemTime, lpLocalFileTime);
LocalFileTimeToFileTime(lpLocalFileTime, lpFileTime);
SetFileTime(hFile, @lpFileTime, nil, @lpFileTime);
finally
FileClose(hFile);
end;
end;
function MangleFileName(const AFileName: string): string;
var
Ansi: AnsiString;
Extn: String;
Index: integer;
begin
Result := AFileName;
Extn := ExtractFileExt(Result);
if Extn <> EmptyStr then
SetLength(Result, Length(Result) - Length(Extn));
Ansi := AnsiString(Result);
for Index := 1 to Length(Ansi) do
Ansi[Index] := HashTable[Ansi[Index]];
Result := String(Ansi) + Extn;
end;
function FontStyleToInt(AStyle: TFontStyles): integer;
var
fs: TFontStyle;
begin
Result := 0;
for fs := Low(TFontStyle) to High(TFontStyle) do
if fs in AStyle then
Result := Result or (1 shl Ord(fs));
end;
function IntToFontStyle(AValue: integer): TFontStyles;
var
fs: TFontStyle;
begin
Result := [];
for fs := Low(TFontStyle) to High(TFontStyle) do
if ((1 shl Ord(fs)) and AValue <> 0) then
Result := Result + [fs];
end;
procedure GetDefaultProxySettings(var ProxyServer, ProxyPort: string);
var
usep: Boolean;
S: string;
begin
usep := False;
ProxyPort := EmptyStr;
ProxyServer := EmptyStr;
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
if OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', False) then
begin
if ValueExists('ProxyEnable') then
usep := boolean(ReadInteger('ProxyEnable'));
if usep then
begin
if ValueExists('ProxyServer') then
S := ReadString('ProxyServer');
if AnsiPos('ftp', S) > 0 then
begin
S := Copy(S, AnsiPos('ftp', S) + 4, MaxInt);
if AnsiPos(sColon, S) > 0 then
begin
ProxyServer := Copy(S, 1, AnsiPos(sColon, S) - 1);
Delete(S, 1, AnsiPos(sColon, S));
end;
if AnsiPos(';', S) > 0 then
ProxyPort := Copy(S, 1, AnsiPos(';', S) - 1)
else
ProxyPort := S;
end;
end
else
begin
ProxyPort := '';
ProxyServer := '';
end;
CloseKey;
end;
finally
Free;
end;
end;
procedure NSChangeNotify(hWndSender: HWnd; uMsg: DWORD; dwFlags: DWORD; ANSCollection: TNSCollection;
ANSItem: TNSItem);
var
I: integer;
begin
if (NSN_FLUSH and dwFlags <> 0) then
begin
for I := 0 to Screen.FormCount - 1 do
if Screen.Forms[I].Handle <> hWndSender then
SendMessage(
Screen.Forms[I].Handle,
uMsg,
WParam(ANSCollection),
LParam(ANSItem)
);
end
else
begin
for I := 0 to Screen.FormCount - 1 do
if Screen.Forms[I].Handle <> hWndSender then
PostMessage(
Screen.Forms[I].Handle,
uMsg,
WParam(ANSCollection),
LParam(ANSItem)
);
end;
end;
function FindTreeNode(ATreeView: TTreeView; AData: Pointer): TTreeNode;
var
Current: TTreeNode;
begin
Result := nil;
Current := ATreeView.Items.GetFirstNode;
while Current <> nil do
if Current.Data = AData then
begin
Result := Current;
Exit;
end
else
Current := Current.GetNext;
end;
function FindListItem(AListView: TListView; AData: TNSItem): TListItem;
var
I: integer;
begin
Result := nil;
for I := 0 to AListView.Items.Count - 1 do
if AData = AListView.Items[I].Data then
begin
Result := AListView.Items[I];
Break;
end;
end;
function FormatSize(const ASize: int64; AExactSize: Boolean): string;
const
gigs = 1024*1024*1024;
megs = 1024*1024;
kils = 1024;
begin
if ASize > gigs then
Result := FloatToStrF(ASize / gigs, ffFixed, 15, 2) + ' GB'
else if ASize > megs then
Result := FloatToStrF(ASize / megs, ffFixed, 15, 2) + ' MB'
else if ASize > kils then
Result := FloatToStrF(ASize / kils, ffFixed, 15, 2) + ' KB'
else
Result := IntToStr(ASize) + ' bytes';
if AExactSize and (ASize > kils) then
Result := Result + ' (' + IntToStr(ASize) + ' bytes)';
end;
{var
FileInfo: TSHFileInfo;
}
procedure CreateImageLists;
var
cx, cy: integer;
Icon: HICON;
FileInfo: TSHFileInfo;
begin
// Small icons
cx := GetSystemMetrics(SM_CXSMICON);
cy := GetSystemMetrics(SM_CYSMICON);
g_hmShell := GetModuleHandle(PChar('Shell32.dll'));
if g_hmShell = 0 then
Exit;
{ SHGetFileInfo(PChar(Application.ExeName), FILE_ATTRIBUTE_NORMAL, FileInfo, SizeOf(FileInfo),
SHGFI_SMALLICON or SHGFI_SYSICONINDEX or SHGFI_ICON);
g_hiRoot := FileInfo.iIcon;
SHGetFileInfo(PChar(ACollection[i].DisplayName), FILE_ATTRIBUTE_DIRECTORY, FileInfo, SizeOf(FileInfo),
SHGFI_SMALLICON or SHGFI_SYSICONINDEX or SHGFI_ICON or
SHGFI_USEFILEATTRIBUTES);
g_hiFolder := FileInfo.iIcon;
SHGetFileInfo(PChar(ACollection[i].DisplayName), FILE_ATTRIBUTE_DIRECTORY, FileInfo, SizeOf(FileInfo),
SHGFI_SMALLICON or SHGFI_SYSICONINDEX or SHGFI_ICON or SHGFI_OPENICON or
SHGFI_USEFILEATTRIBUTES or SHGFI_DISPLAYNAME);
Node.SelectedIndex := FileInfo.iIcon;
g_hiFolderOpen := FileInfo.iIcon;
}
if g_himlSmall <> 0 then
ImageList_Destroy(g_himlSmall);
g_himlSmall := ImageList_Create(cx, cy, ILC_COLOR32 or ILC_MASK, 8, 0);
if g_himlSmall = 0 then
Exit;
Icon := LoadImage(hInstance, PChar('MAINICON'), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlSmall, Icon);
DestroyIcon(Icon);
Icon := LoadImage(g_hmShell, PChar(4), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlSmall, Icon);
DestroyIcon(Icon);
Icon := LoadImage(g_hmShell, PChar(5), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlSmall, Icon);
DestroyIcon(Icon);
// g_himDriveConnected := LoadImage(g_hmShell, PChar(10), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
// g_himDriveNotConnected := LoadImage(g_hmShell, PChar(11), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
(*
hShDoc := LoadLibrary('shdocvw.dll');
if hShDoc <> 0 then
begin
g_himLock := LoadImage(hShDoc, PChar(103), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
FreeLibrary(hShDoc);
end;
*)
// System Image List Small
FillChar(FileInfo, SizeOf(FileInfo), #0);
g_himlSysSmall := SHGetFileInfo('C:\', 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
// Large icons
cx := GetSystemMetrics(SM_CXICON);
cy := GetSystemMetrics(SM_CYICON);
if g_himlLarge <> 0 then
ImageList_Destroy(g_himlLarge);
g_himlLarge := ImageList_Create(cx, cy, ILC_COLOR32 or ILC_MASK, 8, 0);
if g_himlLarge = 0 then
Exit;
Icon := LoadImage(hInstance, PChar('MAINICON'), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlLarge, Icon);
DestroyIcon(Icon);
Icon := LoadImage(g_hmShell, PChar(4), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlLarge, Icon);
DestroyIcon(Icon);
Icon := LoadImage(g_hmShell, PChar(5), IMAGE_ICON, cx, cy, LR_DEFAULTCOLOR);
ImageList_AddIcon(g_himlLarge, Icon);
DestroyIcon(Icon);
end;
procedure DestroyImageLists;
begin
if g_himlSmall <> 0 then
ImageList_Destroy(g_himlSmall);
if g_himlLarge <> 0 then
ImageList_Destroy(g_himlLarge);
// if g_himlSysSmall <> 0 then ImageList_Destroy(g_himlSysSmall);
// DestroyIcon(g_himDriveNotConnected);
// DestroyIcon(g_himDriveConnected);
// DestroyIcon(g_himLock);
FreeLibrary(g_hmShell);
end;
procedure RestoreSettings;
const
Section1: string = 'Settings';
Section2: string = 'LastValues';
var
Hash: string;
begin
with TRegIniFile.Create(REG_ROOT) do
try
GetDefaultProxySettings(g_ProxyName, g_ProxyPort);
g_ConnectType := TFTPConnectType(ReadInteger(Section1, 'ConnectionType', 0));
if g_ConnectType = ftpcUseProxy then
begin
g_ProxyName := ReadString(Section1, 'ProxyServer', g_ProxyName);
g_ProxyPort := ReadString(Section1, 'ProxyPort', g_ProxyPort);
end;
g_drNormal.Color := COLORREF(ReadInteger(Section1, 'NormalColor', clBlack));
g_drNormal.Style := IntToFontStyle(ReadInteger(Section1, 'NormalStyle', 0));
g_drBackup.Color := COLORREF(ReadInteger(Section1, 'BackupColor', clNavy));
g_drBackup.Style := IntToFontStyle(ReadInteger(Section1, 'BackupStyle', 1));
g_drRestore.Color := COLORREF(ReadInteger(Section1, 'RestoreColor', clGreen));
g_drRestore.Style := IntToFontStyle(ReadInteger(Section1, 'RestoreStyle', 1));
// g_drDelete.Color := COLORREF(ReadInteger(Section1, 'DeleteColor', clGray));
// g_drDelete.Style := IntToFontStyle(ReadInteger(Section1, 'DeleteStyle', 1));
// g_LargeIcons := ReadBool(Section1, 'LargeIcons', True);
// g_NoTextLabels := ReadBool(Section1, 'NoTextLabels', False);
// g_CollisionFolder := ReadString(Section1, 'CollisionFolder', 'Collision');
g_LastSelDir := ReadString(Section2, 'LastRestoreDirectory', EmptyStr);
g_LastMedia := ReadInteger(Section2, 'LastMedia', 0);
g_LastServer := ReadString(Section2, 'LastServer', EmptyStr);
g_LastUserName := ReadString(Section2, 'LastUserName', EmptyStr);
g_LastHostDir := ReadString(Section2, 'LastHostDir', EmptyStr);
g_LastLocalFolder := ReadString(Section2, 'LastLocalFolder', g_LastLocalFolder);
if not DirectoryExists(g_LastLocalFolder) then
g_LastLocalFolder := IncludeTrailingPathDelimiter(g_WorkingDir) + 'Backups';
g_LastNetPath := ReadString(Section2, 'LastNetPath', EmptyStr);
g_LastCollisionAction := TCollisionAction(ReadInteger(Section2, 'LastCollisionAction', 0));
g_DontAskCollision := ReadBool(Section1, 'DontAskCollision', False);
g_RecipEMail := ReadString(Section1, 'RecipEMail', g_RecipEMail);
g_RecipName := ReadString(Section1, 'RecipName', g_RecipName);
g_SenderEMail := ReadString(Section1, 'SenderEMail', g_SenderEMail);
g_SenderName := ReadString(Section1, 'SenderName', Application.Title);
g_SMTPServer := ReadString(Section1, 'SMTPServer', EmptyStr);
g_SMTPPort := ReadInteger(Section1, 'SMTPPort', 25);
g_SMTPAccount := ReadString(Section1, 'SMTPAccount', EmptyStr);
g_AuthenticationType := TIdSMTPAuthenticationType(ReadInteger(Section1, 'SMTPAuthentication', 0));
g_UseSSL := ReadBool(Section1, 'UseSSL', g_UseSSL);
g_UseTLS := TIdUseTLS(ReadInteger(Section1, 'UseTLS', 0));
Hash := ReadString(Section1, 'SMTPPwd4', EmptyStr);
g_SMTPPassword := TWinCrypt.CryptText(Hash, PrivateKey3, False);
g_PlaySounds := ReadBool(Section1, 'PlaySounds', g_PlaySounds);
g_LastExe1 := ReadString(Section2, 'LastExternalExe1', g_LastExe1);
g_LastExe2 := ReadString(Section2, 'LastExternalExe2', g_LastExe2);
g_WaitExe1 := ReadBool(Section2, 'WaitExternalExe1', g_WaitExe1);
g_WaitExe2 := ReadBool(Section2, 'WaitExternalExe2', g_WaitExe2);
g_DefaultBackupLast := ReadBool(Section1, 'DefaultBackupLast', g_DefaultBackupLast);
g_DefaultBackupDefined := ReadBool(Section1, 'DefaultBackupDefined', g_DefaultBackupDefined);
g_DefaultBackupMedia := ReadInteger(Section1, 'DefaultBackupMedia', g_DefaultBackupMedia);
g_DefaultLocalFolder := ReadString(Section1, 'DefaultLocalFolder', g_DefaultLocalFolder);
if not DirectoryExists(g_DefaultLocalFolder) then
g_DefaultLocalFolder := IncludeTrailingPathDelimiter(g_WorkingDir) + 'Backups\';
ForceDirectories(g_DefaultLocalFolder);
g_DefaultHostName := ReadString(Section1, 'DefaultHostName', g_DefaultHostName);
g_DefaultPort := ReadString(Section1, 'DefaultPort', g_DefaultPort);
g_DefaultUserName := ReadString(Section1, 'DefaultUserName', g_DefaultUserName);
Hash := ReadString(Section1, 'DefaultPassword4', EmptyStr);
g_DefaultPassword := TWinCrypt.CryptText(Hash, PrivateKey3, False);
g_DefaultHostDirName := ReadString(Section1, 'DefaultHostDirName', g_DefaultHostDirName);
g_DefaultUsePassive := ReadBool(Section1, 'DefaultUsePassive', g_DefaultUsePassive);
g_DefaultHangUpOnCompleted := ReadBool(Section1, 'DefaultHangUpOnCompleted', g_DefaultHangUpOnCompleted);
g_ProcessImmediately := ReadBool(Section1, 'ProcessImmediately', g_ProcessImmediately);
g_ViewLogMode := TViewLogMode(ReadInteger(Section1, 'ViewLogMode', 0));
g_ActivationCode := ReadString(Section1, 'ActivationCode', '');
g_LastTheme := ReadInteger(Section1, 'Theme', g_LastTheme);
g_ProjectsDir := ReadString(Section1, 'ProjDir', g_ProjectsDir);
g_LogDir := ReadString(Section1, 'LogDir', g_LogDir);
g_ReadSpeed := ReadInteger(Section1, 'ReadSpeed', g_ReadSpeed);
g_WriteSpeed := ReadInteger(Section1, 'WriteSpeed', g_WriteSpeed);
g_ShowHidden := ReadBool(Section1, 'ShowHidden', g_ShowHidden);
g_SSLVersion := TidSSLVersion(ReadInteger(Section1, 'SSLVersion', Ord(g_SSLVersion)));
finally
Free;
end;
end;
procedure SaveSettings;
const
Section1: string = 'Settings';
Section2: string = 'LastValues';
var
Hash: string;
begin
with TRegIniFile.Create(REG_ROOT) do
try
WriteInteger(Section1, 'ConnectionType', Ord(g_ConnectType));
if g_ConnectType = ftpcUseProxy then
begin
WriteString(Section1, 'ProxyServer', g_ProxyName);
WriteString(Section1, 'ProxyPort', g_ProxyPort);
end;
WriteInteger(Section1, 'NormalColor', g_drNormal.Color);
WriteInteger(Section1, 'NormalStyle', FontStyleToInt(g_drNormal.Style));
WriteInteger(Section1, 'RestoreColor', g_drRestore.Color);
WriteInteger(Section1, 'RestoreStyle', FontStyleToInt(g_drRestore.Style));
WriteInteger(Section1, 'BackupColor', g_drBackup.Color);
WriteInteger(Section1, 'BackupStyle', FontStyleToInt(g_drBackup.Style));
// WriteInteger(Section1, 'DeleteColor', g_drDelete.Color);
// WriteInteger(Section1, 'DeleteStyle', FontStyleToInt(g_drDelete.Style));
// WriteBool(Section1, 'LargeIcons', g_LargeIcons);
// WriteBool(Section1, 'NoTextLabels', g_NoTextLabels);
WriteBool(Section1, 'DontAskCollision', g_DontAskCollision);
// WriteString(Section1, 'CollisionFolder', g_CollisionFolder);
WriteString(Section2, 'LastRestoreDirectory', g_LastSelDir);
WriteInteger(Section2, 'LastMedia', g_LastMedia);
WriteString(Section2, 'LastServer', g_LastServer);
WriteString(Section2, 'LastUserName', g_LastUserName);
WriteString(Section2, 'LastHostDir', g_LastHostDir);
WriteString(Section2, 'LastLocalFolder', g_LastLocalFolder);
WriteString(Section2, 'LastNetPath', g_LastNetPath);
WriteInteger(Section2, 'LastCollisionAction', Ord(g_LastCollisionAction));
WriteString(Section2, 'LastExternalExe1', g_LastExe1);
WriteString(Section2, 'LastExternalExe2', g_LastExe2);
WriteBool(Section2, 'WaitExternalExe1', g_WaitExe1);
WriteBool(Section2, 'WaitExternalExe2', g_WaitExe2);
WriteString(Section1, 'RecipEMail', g_RecipEMail);
WriteString(Section1, 'RecipName', g_RecipName);
WriteString(Section1, 'SenderEMail', g_SenderEMail);
WriteString(Section1, 'SenderName', g_SenderName);
WriteString(Section1, 'SMTPServer', g_SMTPServer);
WriteInteger(Section1, 'SMTPPort', g_SMTPPort);
WriteString(Section1, 'SMTPAccount', g_SMTPAccount);
WriteInteger(Section1, 'SMTPAuthentication', Ord(g_AuthenticationType));
WriteBool(Section1, 'UseSSL', g_UseSSL);
WriteInteger(Section1, 'UseTLS', Ord(g_UseTLS));
Hash := TWinCrypt.CryptText(g_SMTPPassword, PrivateKey3, True);
WriteString(Section1, 'SMTPPwd4', Hash);
WriteBool(Section1, 'PlaySounds', g_PlaySounds);
WriteBool(Section1, 'DefaultBackupLast', g_DefaultBackupLast);
WriteBool(Section1, 'DefaultBackupDefined', g_DefaultBackupDefined);
WriteInteger(Section1, 'DefaultBackupMedia', g_DefaultBackupMedia);
WriteString(Section1, 'DefaultLocalFolder', g_DefaultLocalFolder);
WriteString(Section1, 'DefaultHostName', g_DefaultHostName);
WriteString(Section1, 'DefaultPort', g_DefaultPort);
WriteString(Section1, 'DefaultUserName', g_DefaultUserName);
Hash := TWinCrypt.CryptText(g_DefaultPassword, PrivateKey3, True);
WriteString(Section1, 'DefaultPassword4', Hash);
WriteString(Section1, 'DefaultHostDirName', g_DefaultHostDirName);
WriteBool(Section1, 'DefaultUsePassive', g_DefaultUsePassive);
WriteBool(Section1, 'DefaultHangUpOnCompleted', g_DefaultHangUpOnCompleted);
WriteBool(Section1, 'ProcessImmediately', g_ProcessImmediately);
WriteInteger(Section1, 'ViewLogMode', Ord(g_ViewLogMode));
WriteString(Section1, 'ActivationCode', g_ActivationCode);
WriteInteger(Section1, 'Theme', g_LastTheme);
// 2.1
WriteString(Section1, 'ProjDir', g_ProjectsDir);
WriteString(Section1, 'LogDir', g_LogDir);
WriteInteger(Section1, 'ReadSpeed', g_ReadSpeed);
WriteInteger(Section1, 'WriteSpeed', g_WriteSpeed);
WriteBool(Section1, 'ShowHidden', g_ShowHidden);
WriteInteger(Section1, 'SSLVersion', Ord(g_SSLVersion));
finally
Free;
end;
end;
procedure SaveFormSettings(AForm: TForm);
var
WindowPlacement: TWindowPlacement;
begin
with TRegistry.Create do
try
FillChar(WindowPlacement, SizeOf(TWindowPlacement), #0);
WindowPlacement.Length := SizeOf(TWindowPlacement);
GetWindowPlacement(AForm.Handle, @WindowPlacement);
if OpenKey(REG_FORMS, True) then
try
WriteBinaryData(AForm.ClassName, WindowPlacement, SizeOf(TWindowPlacement));
finally
CloseKey;
end;
finally
Free;
end;
end;
procedure RestoreFormSettings(AForm: TForm);
var
WindowPlacement: TWindowPlacement;
X: integer;
Y: integer;
begin
with TRegistry.Create do
try
FillChar(WindowPlacement, SizeOf(TWindowPlacement), #0);
WindowPlacement.Length := SizeOf(TWindowPlacement);
GetWindowPlacement(AForm.Handle, @WindowPlacement);
if OpenKey(REG_FORMS, False) then
try
ReadBinaryData(AForm.ClassName, WindowPlacement, SizeOf(TWindowPlacement));
finally
CloseKey;
end
else
begin
X := (Screen.Width - AForm.Width) div 2;
Y := (Screen.Height - AForm.Height) div 2;
WindowPlacement.rcNormalPosition := Rect(X, Y, X + AForm.Width, Y + AForm.Height);
end;
SetWindowPlacement(AForm.Handle, @WindowPlacement);
finally
Free;
end;
end;
function FolderExists(const Directory: string): Boolean;
var
code: integer;
begin
code := GetFileAttributes(PChar(Directory));
g_dwLastError := GetLastError;
Result := (code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and code <> 0);
end;
function GetLastLocalResponse: string;
begin
//Result := SysErrorMessage(g_dwLastError);
Result := Format('%s (Code: %d)', [SysErrorMessage(g_dwLastError), g_dwLastError]);
end;
procedure PlaySoundEvent(const AEventLabel: string);
begin
if g_PlaySounds then
PlaySound(PChar(AEventLabel), 0, SND_APPLICATION or SND_ASYNC or SND_NOWAIT or SND_NODEFAULT);
end;
function ExecWait(const Cmd: string; const ATimeOut: integer): integer;
var
ProcessInfo: TProcessInformation;
hProcess: THandle;
ReturnCode: cardinal;
StartupInfo: TStartupInfo;
begin
Result := 0;
FillChar(StartupInfo, SizeOf(StartupInfo), 0);
if not CreateProcess(nil, PChar(Cmd), nil, nil, False, CREATE_DEFAULT_ERROR_MODE +
NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then
begin
Result := GetLastError;
Exit;
end;
hProcess := ProcessInfo.hProcess; // save the process handle
//Close the thread handle as soon as it is no longer needed
CloseHandle(ProcessInfo.hThread);
ReturnCode := WaitForSingleObject(hProcess, ATimeOut * 60000);
if ReturnCode = WAIT_FAILED then
begin
Result := GetLastError;
Exit;
end;
// The process terminated
// ChkBool(GetExitCodeProcess(hProcess, dword(Result)),
// 'Error in GetExitCodeProcess');
// Close the process handle as soon as it is no longer needed
CloseHandle(hProcess);
end;
procedure ExecuteApp(const Cmd: string);
begin
ShellExecute(0, 'open', PChar(Cmd), '', '', SW_SHOWNORMAL);
end;
procedure WriteAppPathToRegistry;
begin
with TRegistry.Create do
try
RootKey := HKEY_CURRENT_USER;
OpenKey(REG_ROOT, True);
WriteString('ExePath', Application.ExeName);
finally
Free;
end;
end;
{function CDRWDiskTypeNameByType(AType: TCDDriveType): string;
begin
Result := GetEnumName(TypeInfo(TCDDriveType), Ord(AType));
Delete(Result, 1, 2);
Result := StringReplace(Result, '_', '-', [rfReplaceAll]);
Result := StringReplace(Result, 'Plus', '+', [rfIgnoreCase, rfReplaceAll]);
end;
function CDRWIsCDDrive(AInfo: TCDDeviceInfo): Boolean;
var
TmpInfo: TCDDeviceInfo;
P1, P2: PCDDeviceInfo;
begin
FillChar(TmpInfo, SizeOf(TCDDeviceInfo), #0);
P1 := @TmpInfo;
P2 := @AInfo;
Result := not CompareMem(P1, P2, SizeOf(TCDDeviceInfo));
end;
}
function GetDrives: string;
var
I: cardinal;
Pc, Pc2: PChar;
begin
I := GetLogicalDriveStrings(0, nil);
GetMem(Pc, I);
Pc2 := Pc;
try
Result := '';
GetLogicalDriveStrings(I, Pc);
while (Pc <> nil) and (StrLen(Pc) > 0) do
begin
Result := Result + string(Pc) + #13#10;
Inc(Pc, 4);
end;
finally
FreeMem(Pc2);
end;
end;
function GetCDDrives: string;
var
I: cardinal;
Pc, Pc2: PChar;
begin
I := GetLogicalDriveStrings(0, nil);
GetMem(Pc, I);
Pc2 := Pc;
try
Result := '';
GetLogicalDriveStrings(I, Pc);
while (Pc <> nil) and (StrLen(Pc) > 0) do
begin
if GetDriveType(Pc) = DRIVE_CDROM then
Result := Result + string(Pc) + #13#10;
Inc(Pc, 4);
end;
finally
FreeMem(Pc2);
end;
end;
function FileGetSize(const AFileName: string): int64; overload;
var
SR: TSearchRec;
begin
if FindFirst(AFileName, faAnyFile and not faDirectory, SR) = 0 then
begin
Result := SR.Size;
FindClose(SR);
end
else
Result := -1;
end;
function FileGetSize(const ASR: TSearchRec): int64; overload;
begin
Result := ASR.Size;
end;
function FileGetSize(const ASR: TFTPSearchRec): int64; overload;
begin
Result := Int64(ASR.Size);
end;
function FileGetModified(const ASR: TSearchRec): TDateTime; overload;
begin
(*
if FileTimeToLocalFileTime(ASR.FindData.ftLastWriteTime, LocalFileTime) then
begin
FileTimeToSystemTime(LocalFileTime, LSystemTime);
with LSystemTime do
Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end
else
*)
try
//Result := FileDateToDateTime(ASR.Time);
Result := ASR.TimeStamp;
except
Result := Now;
end;
end;
function FileGetModified(const ASR: TFTPSearchRec): TDateTime; overload;
begin
(*
if FileTimeToLocalFileTime(ASR.FindData.ftLastWriteTime, LocalFileTime) then
begin
FileTimeToSystemTime(LocalFileTime, LSystemTime);
with LSystemTime do
Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end
else
*)
try
Result := FileDateToDateTime(ASR.Time);
except
Result := Now;
end;
end;
function TicksToTime(const ATicks: cardinal): string;
var
DT: TTime;
begin
DT := ATicks / MSecsPerDay;
Result := FormatDateTime('h:nn:ss', DT);
end;
type
TAccControl = class(TControl);
procedure UpdateVistaFonts(const AForm: TCustomForm);
var
I: integer;
begin
if SysUtils.Win32MajorVersion < 6 then
Exit;
AForm.Font.Name := 'Segoe UI';
AForm.Font.Size := 9;
for I := 0 to AForm.ComponentCount - 1 do
if AForm.Components[I] is TControl then
if (TAccControl(AForm.Components[I]).Font.Size = 11) and
(TAccControl(AForm.Components[I]).Font.Name = 'Tahoma') then
begin
TAccControl(AForm.Components[I]).Font.Name := 'Segoe UI';
TAccControl(AForm.Components[I]).Font.Size := 12;
end;
end;
const
FILE_READ_ATTRIBUTES = $80;
FSCTL_GET_RETRIEVAL_POINTERS = 589939; //(($00000009) shr 16) or ((28) shr 14) or ((3) shr 2) or (0);
type
ULONGLONG = ULONG;
PULONGLONG = ^ULONGLONG;
TClusters = array of LONGLONG;
STARTING_VCN_INPUT_BUFFER = record
StartingVcn: LARGE_INTEGER;
end;
PSTARTING_VCN_INPUT_BUFFER = ^STARTING_VCN_INPUT_BUFFER;
Extents = record
NextVcn: LARGE_INTEGER;
Lcn: LARGE_INTEGER;
end;
RETRIEVAL_POINTERS_BUFFER = record
ExtentCount: DWORD;
StartingVcn: LARGE_INTEGER;
Extents: array[0..0] of Extents;
end;
PRETRIEVAL_POINTERS_BUFFER = ^RETRIEVAL_POINTERS_BUFFER;
function GetFileClusters(lpFileName: PChar; ClusterSize: int64; ClCount: PInt64; var FileSize: int64): TClusters;
var
hFile: THandle;
OutSize: ULONG;
Bytes, Cls, CnCount, r: ULONG;
Clusters: TClusters;
PrevVCN, lcn: LARGE_INTEGER;
InBuf: STARTING_VCN_INPUT_BUFFER;
OutBuf: PRETRIEVAL_POINTERS_BUFFER;
begin
Clusters := nil;
hFile := CreateFile(lpFileName, FILE_READ_ATTRIBUTES, FILE_SHARE_READ or FILE_SHARE_WRITE or
FILE_SHARE_DELETE, nil, OPEN_EXISTING, 0, 0);
if (hFile <> INVALID_HANDLE_VALUE) then
begin
FileSize := GetFileSize(hFile, nil);
OutSize := SizeOf(RETRIEVAL_POINTERS_BUFFER) + (FileSize div ClusterSize) * SizeOf(OutBuf^.Extents);
GetMem(OutBuf, OutSize);
InBuf.StartingVcn.QuadPart := 0;
if (DeviceIoControl(hFile, FSCTL_GET_RETRIEVAL_POINTERS, @InBuf, SizeOf(InBuf), OutBuf,
OutSize, Bytes, nil)) then
begin
ClCount^ := (FileSize + ClusterSize - 1) div ClusterSize;
SetLength(Clusters, ClCount^);
PrevVCN := OutBuf^.StartingVcn;
Cls := 0;
r := 0;
while (r < OutBuf^.ExtentCount) do
begin
Lcn := OutBuf^.Extents[r].Lcn;
CnCount := ULONG(OutBuf^.Extents[r].NextVcn.QuadPart - PrevVCN.QuadPart);
while (CnCount > 0) do
begin
Clusters[Cls] := Lcn.QuadPart;
Dec(CnCount);
Inc(Cls);
Inc(Lcn.QuadPart);
end;
PrevVCN := OutBuf^.Extents[r].NextVcn;
Inc(r);
end;
end;
FreeMem(OutBuf);
CloseHandle(hFile);
end;
Result := Clusters;
end;
type
TCopyProgressRoutine = function(TotalFileSize: int64; TotalBytesTransferred: int64;
StreamSize: int64; StreamBytesTransferred: int64; dwStreamNumber: DWORD; dwCallbackReason: DWORD;
hSourceFile: THandle; hDestinationFile: THandle; lpData: Pointer): DWORD; stdcall;
function CopyFileRaw(lpSrcName: PChar; lpDstName: PChar; lpProgressRoutine: TFNProgressRoutine;
lpData: Pointer; pbCancel: PBool; dwCopyFlags: DWORD): Boolean;
var
FileSize, ClusterSize, BlockSize, FullSize, CopyedSize: int64;
Clusters: TClusters;
r, ClCount: ULONG;
Bytes: ULONG;
hDrive, hFile: THandle;
SecPerCl, BtPerSec, FreeClusters, NumOfClusters: DWORD;
Buff: PByte;
Offset: LARGE_INTEGER;
Name: array[0..6] of char;
rslt: integer;
begin
Result := True;
try
Name[0] := lpSrcName[0];
Name[1] := ':';
Name[2] := char(0);
FreeClusters := 0;
NumOfClusters := 0;
GetDiskFreeSpace(Name, SecPerCl, BtPerSec, FreeClusters, NumOfClusters);
ClusterSize := SecPerCl * BtPerSec;
Clusters := GetFileClusters(lpSrcName, ClusterSize, @ClCount, FileSize);
FullSize := FileSize;
if (Clusters <> nil) then
begin
Name[0] := '\';
Name[1] := '\';
Name[2] := '.';
Name[3] := '\';
Name[4] := lpSrcName[0];
Name[5] := ':';
Name[6] := char(0);
hDrive := CreateFile(Name, GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
if hDrive <> INVALID_HANDLE_VALUE then
try
hFile := CreateFile(lpDstName, GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0);
if (hFile <> INVALID_HANDLE_VALUE) then
try
GetMem(Buff, ClusterSize);
try
r := 0;
CopyedSize := 0;
while (r < ClCount) do
begin
if Assigned(@lpProgressRoutine) then
begin
rslt := TCopyProgressRoutine(lpProgressRoutine)(ClCount, r, FullSize,
CopyedSize, 0, 4, hDrive, hFile, lpData);
if rslt = PROGRESS_STOP then
Abort;
end;
Offset.QuadPart := ClusterSize * Clusters[r];
SetFilePointer(hDrive, Offset.LowPart, @Offset.HighPart, FILE_BEGIN);
ReadFile(hDrive, Buff^, ClusterSize, Bytes, nil);
BlockSize := Min(FileSize, ClusterSize);
WriteFile(hFile, Buff^, BlockSize, Bytes, nil);
CopyedSize := CopyedSize + BlockSize;
FileSize := FileSize - BlockSize;
Inc(r);
end;
finally
FreeMem(Buff);
end;
finally
CloseHandle(hFile);
end;
finally
CloseHandle(hDrive);
end;
end;
except
Result := False;
end;
end;
function ConnectToNAS(const AWnd: HWND; const ANetPath, AUserName, APassword: string;
var AConnection: string): Boolean;
var
lpNetResource: TNetResource;
lpAccessName: array[0..MAX_PATH] of char;
lpBufferSize: DWORD;
lpUserID: PChar;
lpPassword: PChar;
lpResult: DWORD;
begin
FillChar(lpNetResource, SizeOf(TNetResource), #0);
lpNetResource.dwType := RESOURCETYPE_DISK;
lpNetResource.lpRemoteName := PChar(ExcludeTrailingPathDelimiter(ANetPath));
FillChar(lpAccessName[0], MAX_PATH + 1, #0);
lpBufferSize := MAX_PATH;
if AUserName <> EmptyStr then
lpUserID := PChar(AUserName)
else
lpUserID := nil;
if APassword <> EmptyStr then
lpPassword := PChar(APassword)
else
lpPassword := nil;
Result := WNetUseConnection(AWnd, lpNetResource, lpPassword, lpUserID, 0, lpAccessName, lpBufferSize, lpResult) = ERROR_SUCCESS;
g_dwLastError := GetLastError;
if not Result then
begin
if AWnd <> 0 then
MessageBox(AWnd, PChar(GetLastLocalResponse), PChar(sError), $00000030);
Exit;
end;
AConnection := StrPas(lpAccessName);
end;
(*
function ConnectToNAS(const AWnd: HWND; const ANetPath, AUserName, APassword: string;
var AConnection: string): boolean;
var
lpNetResource: TNetResource;
lpAccessName: array[0..MAX_PATH] of char;
lpBufferSize: DWORD;
lpUserID: PChar;
lpPassword: PChar;
lpResult: DWORD;
begin
FillChar(lpNetResource, SizeOf(TNetResource), #0);
lpNetResource.dwType := RESOURCETYPE_DISK;
lpNetResource.lpRemoteName := PChar(ANetPath);
FillChar(lpAccessName[0], MAX_PATH + 1, #0);
lpBufferSize := MAX_PATH;
if AUserName <> EmptyStr then
lpUserID := PChar(AUserName)
else
lpUserID := nil;
if APassword <> EmptyStr then
lpPassword := PChar(APassword)
else
lpPassword := nil;
Result := WNetUseConnection(AWnd, lpNetResource, lpPassword, lpUserID, 0, lpAccessName, lpBufferSize, lpResult) =
ERROR_SUCCESS;
g_dwLastError := GetLastError;
if not Result then
begin
if AWnd <> 0 then
MessageBox(AWnd, PChar(GetLastLocalResponse), PChar(sError), $00000030);
Exit;
end;
AConnection := StrPas(lpAccessName);
end;
*)
procedure DisconnectNAS(const AConnection: string);
begin
WNetCancelConnection2(PChar(AConnection), 0, True);
end;
const
DomainExt: array[1..259] of string = ('AC', 'AD', 'AE', 'AERO', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR',
'AS', 'AT', 'AU', 'AW', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI',
'BIZ', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA',
'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'COM', 'COOP',
'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC',
'EDU', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'EU', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR',
'GA', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GOV', 'GP', 'GQ', 'GR', 'GS',
'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'INFO',
'INT', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM',
'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LU', 'LV', 'LY',
'MA', 'MC', 'MD', 'MG', 'MH', 'MIL', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT',
'MU', 'MUSEUM', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NAME', 'NC', 'NE', 'NET', 'NF', 'NG',
'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'ORG', 'PA', 'PE', 'PF', 'PG', 'PH',
'PK', 'PL', 'PM', 'PN', 'PR', 'PRO', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RU',
'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SHOP', 'SI', 'SJ', 'SK', 'SL', 'SM',
'SN', 'SO', 'SR', 'ST', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK',
'TM', 'TN', 'TO', 'TP', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UK', 'UM', 'US',
'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'YU',
'ZA', 'ZM', 'ZR', 'ZW');
function IsValidEmail(email: string): Boolean;
var
nameStr, DomainExtension, DomainStr: string;
ok: Boolean;
a, b, i: integer;
begin
email := trim(email);
Result := False;
if email <> '' then //darf nicht leer sein
if length(email) > 6 then //darf nicht kleiner als 7 sein
if pos('@', email) > 0 then //muss @ enthalten
if pos('.', email) > 0 then //muss . enthalten
begin
a := pos('@', email);
b := length(email);
nameStr := copy(email, 1, a - 1);
if nameStr = '' then //One or more characters before the "@"
exit;
if not CharInSet(nameStr[1], ['0'..'9', 'a'..'z', 'A'..'Z']) then //Name muß mit Ziffer oder Buchstabe beginnen
exit;
for i := 1 to length(nameStr) do
//Nur Ziffern und Buchstaben (ohne Umlaute) sowie Punkt '.', Bindestrich '-' und Unterstrich '_'.
if not CharInSet(nameStr[i], ['0'..'9', 'a'..'z', 'A'..'Z', '.', '-', '_', '&']) then
exit;
DomainStr := copy(email, a + 1, b - a);
if DomainStr = '' then
exit;
if pos('.', DomainStr) = 0 then //domainstr must contain a period that is not the first character
exit;
if DomainStr[1] = '.' then //domainstr must contain a period that is not the first character
exit;
if not CharInSet(DomainStr[length(DomainStr)], ['A'..'Z', 'a'..'z', 'ä', 'ü', 'ö', 'Ä', 'Ü', 'Ö']) then
//The last character must be an alphabetic character
exit;
DomainExtension := '';
for i := length(DomainStr) downto 1 do
begin
if DomainStr[i] <> '.' then
DomainExtension := DomainStr[i] + DomainExtension
else
break;
end;
ok := False;
for i := low(DomainExt) to high(DomainExt) do
begin
if uppercase(DomainExtension) = DomainExt[i] then
begin
ok := True;
break;
end;
end;
if not OK then
exit;
Result := True;
end;
end;
function SelectDir(const Caption: string; var Directory: string; Root: TRootFolder = rfDesktop;
Options: TSelectDirExtOpts = [sdNewFolder]): Boolean;
var
RootDir: String;
begin
RootDir := '';
Result := SelectDirectory(Caption, RootDir, Directory, Options + [sdNewUI]);
end;
end.
|
{Un conjunto de corredores entrenan para una carrera, corriendo una hora cada uno
de los 7 días de la semana y teniendo como meta alcanzar en dicha hora, una mínima de
X kms.
En un archivo de texto se graba la meta X en la primera línea y en las restantes el nombre
(10 caracteres como máximo) y los 7 días de cada corredor, uno por línea.
20
bbb 5 10 15 19 9 5 0
hhh 2 30 6 9 10 30 9
ccc 1 5 30 15 8 20 25
aaa 5 10 0 20 40 25 15
Se pide desarrollar un programa Pascal, correctamente modularizado que lea y almacene
los nombres en un vector y los tramos en una matriz.
a.-Generar un arreglo con los nombres de los corredores que superaron la meta
establecida algún día de la semana. Imprimirlo
b.- Calcule e imprima, cuantos días no alcanzo la meta el corredor con promedio diario
máximo
Ejemplo N=4 Meta Semanal = 20
bbb 5 10 15 15 10 5 0
hhh 10 20 5 10 10 30 5
ccc 5 5 10 1 10 15 25
aaa 5 10 25 20 40 25 15
Promedios: bbb 8.57
hhh 12.85
ccc 10.14
aaa 20.00
Respuestas:
a. ( hhh, ccc, aaa)
b. 3 días (4to corredor) }
Program TipoParcial2;
Type
St3 = string[3];
TM = array[1..100, 1..100] of byte;
TV = array[1..10] of st3;
Procedure LeerArchivo(Var Kms:TM; Var Nombres:TV; Var Meta:byte; Var N,M:byte);
Var
j:byte;
arch:text;
begin
N:= 0;
M:= 7;
assign(arch,'TipoParcial2.txt');reset(arch);
readln(arch,Meta);
while not eof (arch) do
begin
N:= N + 1;
read(arch,Nombres[N]);
For j:= 1 to M do
begin
If (j <> M) then
read(arch,Kms[N,j])
Else
readln(arch,Kms[N,j]);
end;
end;
close(arch);
end;
Procedure GenerarArray(Kms:TM; Nombres:TV; N,M:byte; Meta:byte; Var A:TV; Var K:byte);
Var
i,j:byte;
begin
K:= 0;
For i:= 1 to N do
begin
j:= 1;
while (j <= 7) and (Kms[i,j] < Meta) do
j:= j + 1;
If (j <= 7) then
begin
K:= K + 1;
A[K]:= Nombres[i];
end;
end;
end;
Procedure Imprime(A:TV; K:byte);
Var
i:byte;
begin
For i:= 1 to K do
write(A[i]:4);
end;
Function Suma(Kms:TM; Fila:byte):byte;
Var
j,Sum:byte;
begin
Sum:= 0;
For j:= 1 to 7 do
Sum:= Sum + Kms[Fila,j];
Suma:= Sum;
end;
Function PosicionMaximoPromedio(Kms:TM; N:byte):byte;
Var
i,PosMax:byte;
MaxProm,Prom:real;
begin
MaxProm:= 0;
PosMax:= 0;
For i:= 1 to N do
begin
Prom:= Suma(Kms,i)/ 7;
If (Prom > MaxProm) then
begin
MaxProm:= Prom;
PosMax:= i;
end;
end;
PosicionMaximoPromedio:= PosMax;
end;
Function CantidadDias(Kms:TM; Fila:byte; Meta:real):byte;
Var
j,Cant:byte;
begin
Cant:= 0;
For j:= 1 to 7 do
If (Meta > Kms[Fila,j]) then
Cant:= Cant + 1;
CantidadDias:= Cant;
end;
Var
Kms:TM;
Nombres,A:TV;
N,M,K,Meta,PosMax:byte;
Begin
LeerArchivo(Kms,Nombres,Meta,N,M);
GenerarArray(Kms,Nombres,N,M,Meta,A,K);
write('A- Corredores que superaron la meta algun dia de la semana:');
Imprime(A,K);
writeln;
writeln;
PosMax:= PosicionMaximoPromedio(Kms,N);
writeln('B- ',Nombres[PosMax], ' no alcanzo la meta en ',CantidadDias(Kms,PosMax,Meta),' dias');
end.
|
unit ibSHDMLExporterTreeEditors;
interface
uses
SHDesignIntf,
Windows, Classes, Controls, Types, Messages, StdCtrls,
VirtualTrees,
pSHSynEdit;
type
PTreeRec = ^TTreeRec;
TTreeRec = record
ObjectName: string;
Description: string;
DestinationTable: string;
WhereClause: string;
UseAsUpdateField: Boolean;
Changed: Boolean;
ImageIndex: Integer;
IsDummy: Boolean;
end;
TNotifyRegistrationEditor = procedure(AEditor: TpSHSynEdit) of object;
TDMLExporterObjectEditLink = class(TInterfacedObject, IVTEditLink)
private
FEdit: TWinControl; // One of the property editor classes.
FTree: TVirtualStringTree; // A back reference to the tree calling.
FNode: PVirtualNode; // The node being edited.
FColumn: Integer; // The column of the node being edited.
FOnRegistryEditor: TNotifyRegistrationEditor;
procedure SetOnRegistryEditor(const Value: TNotifyRegistrationEditor);
protected
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
public
destructor Destroy; override;
function BeginEdit: Boolean; stdcall;
function CancelEdit: Boolean; stdcall;
function EndEdit: Boolean; stdcall;
function GetBounds: TRect; stdcall;
function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean; stdcall;
procedure ProcessMessage(var Message: TMessage); stdcall;
procedure SetBounds(R: TRect); stdcall;
property OnRegistryEditor: TNotifyRegistrationEditor read FOnRegistryEditor
write SetOnRegistryEditor;
end;
implementation
uses SynEdit;
{ TPropertyEditLink }
destructor TDMLExporterObjectEditLink.Destroy;
begin
FEdit.Free;
inherited;
end;
procedure TDMLExporterObjectEditLink.SetOnRegistryEditor(
const Value: TNotifyRegistrationEditor);
begin
FOnRegistryEditor := Value;
end;
procedure TDMLExporterObjectEditLink.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN,
VK_DOWN,
VK_UP:
begin
if (Shift = []) then
begin
// Forward the keypress to the tree. It will asynchronously change the focused node.
PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0);
Key := 0;
end;
end;
end;
end;
function TDMLExporterObjectEditLink.BeginEdit: Boolean;
begin
Result := True;
FEdit.Show;
FEdit.SetFocus;
end;
function TDMLExporterObjectEditLink.CancelEdit: Boolean;
begin
Result := True;
FEdit.Hide;
end;
function TDMLExporterObjectEditLink.EndEdit: Boolean;
var
Data: PTreeRec;
Buffer: array[0..1024] of Char;
S: WideString;
begin
Result := True;
Data := FTree.GetNodeData(FNode);
case FColumn of
0, 1:;
2:
begin
with FEdit as TCheckBox do
begin
if Checked <> Data.UseAsUpdateField then
begin
Data.UseAsUpdateField := Checked;
Data.Changed := True;
FTree.InvalidateNode(FNode);
end;
end;
end;
3:
begin
GetWindowText(FEdit.Handle, Buffer, 1024);
S := Buffer;
if S <> Data.WhereClause then
begin
Data.WhereClause := S;
Data.Changed := True;
FTree.InvalidateNode(FNode);
end;
end;
4:
begin
GetWindowText(FEdit.Handle, Buffer, 1024);
S := Buffer;
if S <> Data.DestinationTable then
begin
Data.DestinationTable := S;
Data.Changed := True;
FTree.InvalidateNode(FNode);
end;
end;
end;
FEdit.Hide;
FTree.SetFocus;
end;
function TDMLExporterObjectEditLink.GetBounds: TRect;
begin
Result := FEdit.BoundsRect;
end;
function TDMLExporterObjectEditLink.PrepareEdit(Tree: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex): Boolean;
var
Data: PTreeRec;
begin
Result := True;
FTree := Tree as TVirtualStringTree;
FNode := Node;
FColumn := Column;
// determine what edit type actually is needed
FEdit.Free;
FEdit := nil;
Data := FTree.GetNodeData(Node);
case FColumn of
0, 1: Result := False;
2:
begin
FEdit := TCheckBox.Create(nil);
with FEdit as TCheckBox do
begin
Visible := False;
Parent := Tree;
Checked := Data.UseAsUpdateField;
OnKeyDown := EditKeyDown;
FEdit.Perform(WM_LBUTTONDOWN, MK_LBUTTON, 1 shl 16 + 1);
FEdit.Perform(WM_LBUTTONUP, MK_LBUTTON, 1 shl 16 + 1);
end;
end;
3:
begin
FEdit := TpSHSynEdit.Create(nil);
if Assigned(FOnRegistryEditor) then
FOnRegistryEditor(TpSHSynEdit(FEdit));
with FEdit as TpSHSynEdit do
begin
Visible := False;
Parent := Tree;
Lines.Text := Data.WhereClause;
OnKeyDown := EditKeyDown;
end;
end;
4:
begin
FEdit := TEdit.Create(nil);
with FEdit as TEdit do
begin
Visible := False;
Parent := Tree;
Text := Data.DestinationTable;
OnKeyDown := EditKeyDown;
end;
end;
end;
end;
procedure TDMLExporterObjectEditLink.ProcessMessage(var Message: TMessage);
begin
FEdit.WindowProc(Message);
end;
procedure TDMLExporterObjectEditLink.SetBounds(R: TRect);
var
Dummy: Integer;
NewRect: TRect;
begin
// Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn)
// we have to set the edit's width explicitly to the width of the column.
FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right);
case FColumn of
0, 1:;
2:
begin
// CheckBox for UPDATE StatementType
NewRect := R;
NewRect.Left := R.Left + ((R.Right - R.Left) div 2) - 6;
FEdit.BoundsRect := NewRect;
end;
3:
begin
// Editor (SynEdit) for Additional Conditions
NewRect := R;
NewRect.Bottom := (R.Bottom - R.Top) * 5 + R.Top;
NewRect.Right := FTree.ClientRect.Right;
if NewRect.Bottom > FTree.ClientRect.Bottom then
begin
NewRect.Top := NewRect.Top - (NewRect.Bottom - FTree.ClientRect.Bottom);
NewRect.Bottom:= FTree.ClientRect.Bottom;
end;
FEdit.BoundsRect := NewRect;
end;
4: FEdit.BoundsRect := R;
end;
end;
end.
|
unit ToolsUnit;
interface
uses
System.Classes,
System.StrUtils,
System.SysUtils,
Vcl.ExtCtrls,
Vcl.Graphics,
Vcl.ComCtrls,
Vcl.Forms,
Vcl.Controls,
ImageHistoryUnit,
uEditorTypes,
uTranslate,
uMemory;
type
TToolsPanelClass = class(TPanel)
private
{ Private declarations }
FOnClose: TNotifyEvent;
FSetImagePointer: TSetPointerToNewImage;
FCancelPointerToImage: TSetPointerToNewImage;
FCancelTempImage: TCancelTemporaryImage;
FSetTempImage: TSetPointerToNewImage;
FImageHistory: TBitmapHistory;
FProgress: TProgressBar;
FEditor: TImageEditorForm;
procedure SetOnClose(const Value: TNotifyEvent);
procedure SetImage(const Value: TBitmap);
procedure SetSetImagePointer(const Value: TSetPointerToNewImage);
procedure SetCancelTempImage(const Value: TCancelTemporaryImage);
procedure SetSetTempImage(const Value: TSetPointerToNewImage);
procedure SetImageHistory(const Value: TBitmapHistory);
procedure SetProgress(const Value: TProgressBar);
protected
FImage: TBitmap;
function LangID: string; virtual; abstract;
public
{ Public declarations }
procedure Init; virtual;
function L(StringToTranslate : string) : string;
class function ID: string; virtual;
function GetProperties: string; virtual; abstract;
procedure SetProperties(Properties: string); virtual; abstract;
function GetValueByName(Properties, name: string): string;
function GetBoolValueByName(Properties, name: string; default: Boolean = False): Boolean;
function GetIntValueByName(Properties, name: string; default: Integer = 0): Integer;
procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); virtual; abstract;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClosePanel; virtual;
property OnClosePanel: TNotifyEvent read FOnClose write SetOnClose;
property Image: TBitmap read FImage write SetImage;
procedure MakeTransform; virtual;
property SetImagePointer: TSetPointerToNewImage read FSetImagePointer write SetSetImagePointer;
property SetTempImage: TSetPointerToNewImage read FSetTempImage write SetSetTempImage;
property CancelTempImage: TCancelTemporaryImage read FCancelTempImage write SetCancelTempImage;
property ImageHistory: TBitmapHistory read FImageHistory write SetImageHistory;
property Progress: TProgressBar read FProgress write SetProgress;
property Editor: TImageEditorForm read FEditor write FEditor;
property CancelPointerToImage: TSetPointerToNewImage read FCancelPointerToImage write FCancelPointerToImage;
end;
implementation
{ TToolsPanelClass }
procedure TToolsPanelClass.ClosePanel;
begin
//do nothing
end;
constructor TToolsPanelClass.Create(AOwner: TComponent);
begin
inherited;
FOnClose := nil;
FImage := nil;
FSetImagePointer := nil;
FProgress := nil;
Parent := AOwner as TWinControl;
end;
destructor TToolsPanelClass.Destroy;
begin
inherited;
end;
function TToolsPanelClass.GetBoolValueByName(Properties, name: string; Default: Boolean): Boolean;
var
Val: string;
begin
Val := GetValueByName(Properties, name);
if Val = '' then
Result := Default
else
Result := AnsiUpperCase(Val) = 'TRUE';
end;
function TToolsPanelClass.GetIntValueByName(Properties, name: string; Default: Integer): Integer;
var
Val: string;
begin
Val := GetValueByName(Properties, name);
Result := StrToIntDef(Val, Default);
end;
function TToolsPanelClass.GetValueByName(Properties, name: string): string;
var
Str: string;
Pbegin, Pend: Integer;
begin
Pbegin := Pos('[', Properties);
Pend := PosEx(';]', Properties, Pbegin);
Str := Copy(Properties, Pbegin, Pend - Pbegin + 1);
Pbegin := Pos(name + '=', Str) + Length(name) + 1;
Pend := PosEx(';', Str, Pbegin);
Result := Copy(Str, Pbegin, Pend - Pbegin);
//
end;
class function TToolsPanelClass.ID: string;
begin
Result := '{73899C26-6964-494E-B5F6-46E65BD50DB7}';
end;
procedure TToolsPanelClass.Init;
begin
//
end;
function TToolsPanelClass.L(StringToTranslate: string): string;
begin
Result := TTranslateManager.Instance.SmartTranslate(StringToTranslate, LangID);
end;
procedure TToolsPanelClass.MakeTransform;
begin
//
end;
procedure TToolsPanelClass.SetCancelTempImage(const Value: TCancelTemporaryImage);
begin
FCancelTempImage := Value;
end;
procedure TToolsPanelClass.SetImage(const Value: TBitmap);
begin
if Value = nil then
F(FImage);
FImage := Value;
end;
procedure TToolsPanelClass.SetImageHistory(const Value: TBitmapHistory);
begin
FImageHistory := Value;
end;
procedure TToolsPanelClass.SetOnClose(const Value: TNotifyEvent);
begin
FOnClose := Value;
end;
procedure TToolsPanelClass.SetProgress(const Value: TProgressBar);
begin
FProgress := Value;
end;
procedure TToolsPanelClass.SetSetImagePointer(const Value: TSetPointerToNewImage);
begin
FSetImagePointer := Value;
end;
procedure TToolsPanelClass.SetSetTempImage(const Value: TSetPointerToNewImage);
begin
FSetTempImage := Value;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VENDA_ORCAMENTO_CABECALHO]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit VendaOrcamentoCabecalhoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
VendedorVO, ViewPessoaTransportadoraVO, ViewPessoaClienteVO, VendaCondicoesPagamentoVO,
VendaOrcamentoDetalheVO;
type
TVendaOrcamentoCabecalhoVO = class(TVO)
private
FID: Integer;
FID_VENDA_CONDICOES_PAGAMENTO: Integer;
FID_VENDEDOR: Integer;
FID_TRANSPORTADORA: Integer;
FID_CLIENTE: Integer;
FTIPO: String;
FCODIGO: String;
FDATA_CADASTRO: TDateTime;
FDATA_ENTREGA: TDateTime;
FVALIDADE: TDateTime;
FTIPO_FRETE: String;
FVALOR_SUBTOTAL: Extended;
FVALOR_FRETE: Extended;
FTAXA_COMISSAO: Extended;
FVALOR_COMISSAO: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_TOTAL: Extended;
FOBSERVACAO: String;
FSITUACAO: String;
//Transientes
FVendedorNome: String;
FTransportadoraNome: String;
FClienteNome: String;
FVendaCondicoesPagamentoNome: String;
FVendedorVO: TVendedorVO;
FTransportadoraVO: TViewPessoaTransportadoraVO;
FClienteVO: TViewPessoaClienteVO;
FVendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO;
FListaVendaOrcamentoDetalheVO: TListaVendaOrcamentoDetalheVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdVendaCondicoesPagamento: Integer read FID_VENDA_CONDICOES_PAGAMENTO write FID_VENDA_CONDICOES_PAGAMENTO;
property VendaCondicoesPagamentoNome: String read FVendaCondicoesPagamentoNome write FVendaCondicoesPagamentoNome;
property IdVendedor: Integer read FID_VENDEDOR write FID_VENDEDOR;
property VendedorNome: String read FVendedorNome write FVendedorNome;
property IdTransportadora: Integer read FID_TRANSPORTADORA write FID_TRANSPORTADORA;
property TransportadoraNome: String read FTransportadoraNome write FTransportadoraNome;
property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE;
property ClienteNome: String read FClienteNome write FClienteNome;
property Tipo: String read FTIPO write FTIPO;
property Codigo: String read FCODIGO write FCODIGO;
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
property DataEntrega: TDateTime read FDATA_ENTREGA write FDATA_ENTREGA;
property Validade: TDateTime read FVALIDADE write FVALIDADE;
property TipoFrete: String read FTIPO_FRETE write FTIPO_FRETE;
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
property TaxaComissao: Extended read FTAXA_COMISSAO write FTAXA_COMISSAO;
property ValorComissao: Extended read FVALOR_COMISSAO write FVALOR_COMISSAO;
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL;
property Observacao: String read FOBSERVACAO write FOBSERVACAO;
property Situacao: String read FSITUACAO write FSITUACAO;
//Transientes
property TransportadoraVO: TViewPessoaTransportadoraVO read FTransportadoraVO write FTransportadoraVO;
property ClienteVO: TViewPessoaClienteVO read FClienteVO write FClienteVO;
property VendedorVO: TVendedorVO read FVendedorVO write FVendedorVO;
property VendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO read FVendaCondicoesPagamentoVO write FVendaCondicoesPagamentoVO;
property ListaVendaOrcamentoDetalheVO: TListaVendaOrcamentoDetalheVO read FListaVendaOrcamentoDetalheVO write FListaVendaOrcamentoDetalheVO;
end;
TListaVendaOrcamentoCabecalhoVO = specialize TFPGObjectList<TVendaOrcamentoCabecalhoVO>;
implementation
constructor TVendaOrcamentoCabecalhoVO.Create;
begin
inherited;
FTransportadoraVO := TViewPessoaTransportadoraVO.Create;
FClienteVO := TViewPessoaClienteVO.Create;
FVendedorVO := TVendedorVO.Create;
FVendaCondicoesPagamentoVO := TVendaCondicoesPagamentoVO.Create;
FListaVendaOrcamentoDetalheVO := TListaVendaOrcamentoDetalheVO.Create;
end;
destructor TVendaOrcamentoCabecalhoVO.Destroy;
begin
FreeAndNil(FTransportadoraVO);
FreeAndNil(FClienteVO);
FreeAndNil(FVendedorVO);
FreeAndNil(FVendaCondicoesPagamentoVO);
FreeAndNil(FListaVendaOrcamentoDetalheVO);
inherited;
end;
initialization
Classes.RegisterClass(TVendaOrcamentoCabecalhoVO);
finalization
Classes.UnRegisterClass(TVendaOrcamentoCabecalhoVO);
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmCollectionListBox
Purpose : Allow for multi-line/multi-height "listbox" type functionality. Also
allowing for Icons to be specified for each item.
Date : 04-24-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmCollectionListBox;
interface
{$I CompilerDefines.INC}
uses Messages, Windows, Forms, Controls, ImgList, Graphics, Classes, sysutils;
type
TrmCollectionListBox = class;
TrmListBoxCollectionItem = class(TCollectionItem)
private
FTextData: TStringList;
FLCount: integer; //Number of lines of text with the current font and display rect;
fLStart: integer; //Calculated line start of the current record;
fLRect: TRect; //Calculated Lines display Rect;
FAlignment: TAlignment;
fImageIndex: integer;
fCenterImage: boolean;
FData: TObject;
procedure SetAlignment(Value: TAlignment);
procedure SetTextData(const Value: TStringList);
procedure SetImageIndex(Value: Integer);
procedure SetCenterImage(const Value: boolean);
function GetText: string;
procedure SetText(const Value: string);
property Text: string read GetText write SetText;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property Data: TObject read fData write fData;
property LCount: integer read fLCount write fLCount;
property LStart: integer read fLStart write fLStart;
property LRect: TRect read fLRect write fLRect;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property TextData: TstringList read FTextData write SetTextData;
property ImageIndex: Integer read fImageIndex write SetImageIndex default -1;
property CenterImage: boolean read fCenterImage write SetCenterImage default false;
end;
TrmListBoxCollection = class(TCollection)
private
FCollectionListBox: TrmCollectionListBox;
FOnUpdate: TNotifyEvent;
function GetItem(Index: Integer): TrmListBoxCollectionItem;
procedure SetItem(Index: Integer; Value: TrmListBoxCollectionItem);
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
public
constructor Create(CollectionListBox: TrmCollectionListBox);
function Add: TrmListBoxCollectionItem;
procedure Delete(Index: Integer);
function Insert(Index: Integer): TrmListBoxCollectionItem;
property Items[Index: Integer]: TrmListBoxCollectionItem read GetItem write SetItem; default;
property OnCollectionUpdate: TNotifyEvent read fOnUpdate write fOnUpdate;
end;
TrmCollectionListBox = class(TCustomControl)
private
fItems: TrmListBoxCollection;
fSelectedItemIndex: integer;
fFocusedItemIndex: integer;
fTopIndex : integer;
fVScrollSize: longint;
fVScrollPos: longint;
fTotalLineCount : integer;
fFocusRect: TRect;
FBorderStyle: TBorderStyle;
FImageChangeLink: TChangeLink;
FImages: TCustomImageList;
fOddColor: TColor;
fClick: TNotifyEvent;
fAutoSelect: boolean;
procedure ImageListChange(Sender: TObject);
procedure SetImages(Value: TCustomImageList);
procedure SetItems(const Value: TrmListBoxCollection);
procedure SetOddColor(const Value: TColor);
procedure SetItemIndex(const Value: integer);
procedure SetBorderStyle(const Value: TBorderStyle);
procedure cmFOCUSCHANGED(var MSG:TMessage); message CM_FOCUSCHANGED;
procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
procedure CalcVScrollSize(startIndex: integer);
procedure UpdateVScrollSize;
function UpdateVScrollPos(newPos: integer): boolean;
procedure WMSize(var Msg: TWMSize); message WM_SIZE;
procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
function VisibleLineCount: integer;
function LineHeight: integer;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function TopItemIndex: integer;
public
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
procedure loaded; override;
function Add(aText: string; aImageIndex: integer; aData: TObject): integer;
function Insert(Index: integer; aText: string; aImageIndex: integer; aData: TObject): integer;
procedure Delete(Index: integer);
property ItemIndex: integer read fselectedItemIndex write SetItemIndex;
published
property AutoSelect : boolean read fAutoSelect write fAutoSelect default false;
property Collection: TrmListBoxCollection read fItems write setItems;
property Images: TCustomImageList read FImages write SetImages;
property OddColor: TColor read fOddColor write SetOddColor default clInfoBk;
property Align;
property Anchors;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property Color default clWindow;
property Constraints;
property Ctl3D;
property Font;
property ParentColor default False;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default true;
property Visible;
property OnClick: TNotifyEvent read fClick write fClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
implementation
uses rmMsgList, rmLibrary;
{ TrmListBoxCollectionItem }
constructor TrmListBoxCollectionItem.Create(Collection: TCollection);
begin
fImageIndex := -1;
FTextData := TStringList.create;
inherited Create(Collection);
end;
procedure TrmListBoxCollectionItem.Assign(Source: TPersistent);
begin
if Source is TrmListBoxCollectionItem then
begin
TextData.Assign(TrmListBoxCollectionItem(Source).TextData);
Alignment := TrmListBoxCollectionItem(Source).Alignment;
ImageIndex := TrmListBoxCollectionItem(Source).ImageIndex;
end
else
inherited Assign(Source);
end;
procedure TrmListBoxCollectionItem.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Changed(False);
end;
end;
procedure TrmListBoxCollectionItem.SetTextData(const Value: TStringList);
begin
fTextData.Assign(Value);
Changed(False);
end;
procedure TrmListBoxCollectionItem.SetImageIndex(Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
Changed(False);
end;
end;
procedure TrmListBoxCollectionItem.SetCenterImage(const Value: boolean);
begin
if fCenterImage <> value then
begin
fCenterImage := value;
changed(false);
end;
end;
function TrmListBoxCollectionItem.GetText: string;
begin
result := FTextData.Text;
end;
destructor TrmListBoxCollectionItem.Destroy;
begin
FTextData.free;
inherited;
end;
procedure TrmListBoxCollectionItem.SetText(const Value: string);
begin
FTextData.text := Value;
end;
{ TrmListBoxCollection }
constructor TrmListBoxCollection.Create(CollectionListBox: TrmCollectionListBox);
begin
inherited Create(TrmListBoxCollectionItem);
FCollectionListBox := CollectionListBox;
end;
function TrmListBoxCollection.Add: TrmListBoxCollectionItem;
begin
Result := TrmListBoxCollectionItem(inherited Add);
end;
function TrmListBoxCollection.GetItem(Index: Integer): TrmListBoxCollectionItem;
begin
Result := TrmListBoxCollectionItem(inherited GetItem(Index));
end;
function TrmListBoxCollection.GetOwner: TPersistent;
begin
Result := FCollectionListBox;
end;
procedure TrmListBoxCollection.SetItem(Index: Integer; Value: TrmListBoxCollectionItem);
begin
inherited SetItem(Index, Value);
end;
procedure TrmListBoxCollection.Update(Item: TCollectionItem);
begin
inherited;
if assigned(fOnUpdate) then
fOnUpdate(item);
end;
procedure TrmListBoxCollection.Delete(Index: Integer);
begin
inherited Delete(index);
end;
function TrmListBoxCollection.Insert(
Index: Integer): TrmListBoxCollectionItem;
begin
Result := TrmListBoxCollectionItem(inherited Insert(index));
end;
{ TrmCollectionListBox }
constructor TrmCollectionListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csClickEvents, csDoubleClicks, csOpaque];
if not NewStyleControls then
ControlStyle := ControlStyle + [csFramed];
Width := 121;
Height := 97;
TabStop := True;
ParentColor := False;
fVScrollPos := 0;
fVScrollSize := 0;
fselectedItemIndex := -1;
fTopIndex := 0;
ffocusedItemIndex := 0;
fOddColor := clInfoBk;
Color := clWindow;
fborderstyle := bsSingle;
fAutoSelect := false;
fItems := TrmListBoxCollection.create(self);
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
procedure TrmCollectionListBox.CreateParams(var Params: TCreateParams);
const
BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER);
begin
inherited CreateParams(Params);
with Params do
begin
Style := Style or WS_VSCROLL;
WindowClass.style := CS_DBLCLKS;
Style := Style or BorderStyles[FBorderStyle];
if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
procedure TrmCollectionListBox.SetImages(Value: TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
CalcVScrollSize(-1);
invalidate;
end;
end;
procedure TrmCollectionListBox.ImageListChange(Sender: TObject);
begin
Invalidate;
end;
procedure TrmCollectionListBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Images) then
Images := nil;
end;
procedure TrmCollectionListBox.setItems(const Value: TrmListBoxCollection);
begin
if fitems <> value then
begin
fItems.assign(Value);
invalidate;
end;
end;
destructor TrmCollectionListBox.destroy;
begin
FImageChangeLink.Free;
fItems.Free;
inherited Destroy;
end;
procedure TrmCollectionListBox.CalcVScrollSize(startIndex: integer);
var
loop: integer;
wCalcSize : integer;
wImageRect, wTextRect, wCalcRect: TRect;
wFHeight: integer;
wStr : string;
begin
if csloading in componentstate then exit;
if csDestroying in ComponentState then exit;
if assigned(fImages) then
begin
wImageRect := Rect(0, 0, FImages.Width, FImages.Height);
wTextRect := Rect(fImages.Width + 2, 0, clientwidth - (fImages.Width + 2), FImages.Height);
end
else
begin
wImageRect := Rect(0, 0, 0, 0);
wTextRect := Rect(2, 0, clientwidth, 0);
end;
if startindex = -1 then
begin
loop := 0;
wCalcSize := 0;
end
else
begin
loop := startindex;
if startindex >= 1 then
wcalcSize := fitems.Items[startindex-1].lstart + fitems.Items[startindex-1].lcount
else
wCalcSize := 0;
end;
wFHeight := LineHeight;
while loop < fItems.Count do
begin
with fItems.Items[loop] do
begin
wCalcRect := wTextRect;
wstr := trim(Text);
DrawText(Canvas.Handle, pchar(wStr), length(wStr), wCalcRect, DT_WORDBREAK or DT_CALCRECT);
if (wCalcRect.Bottom - wCalcRect.Top) < (wImageRect.Bottom-wImageRect.Top) then
wCalcRect.Bottom := wImageRect.Bottom;
LCount := (wCalcRect.Bottom - wCalcRect.Top) div wFHeight;
if LCount = 0 then
lCount := 1;
if (((wCalcRect.Bottom - wCalcRect.Top) mod wFHeight) > (wFHeight div 2)) then
lCount := lCount + 1;
LStart := wCalcSize;
LRect := rect(wCalcRect.left, wCalcRect.Top, clientwidth, wCalcRect.bottom);
inc(wCalcSize, LCount);
end;
inc(loop);
end;
fTotalLineCount := wCalcSize;
UpdateVScrollSize;
end;
procedure TrmCollectionListBox.loaded;
begin
inherited;
CalcVScrollSize(-1);
end;
procedure TrmCollectionListBox.WMSize(var Msg: TWMSize);
begin
inherited;
CalcVScrollSize(-1);
UpdateVScrollPos(fVScrollPos + 1);
UpdateVScrollPos(fVScrollPos - 1);
Invalidate;
end;
procedure TrmCollectionListBox.Paint;
var
index: integer;
wImageRect, wCalcRect: TRect;
wFHeight, cheight, wcalcheight: integer;
DrawFlags: integer;
wStr : string;
wImageAdjust : integer;
begin
if csDestroying in ComponentState then exit;
wFHeight := LineHeight;
index := TopItemIndex;
if index = -1 then
begin
fFocusRect := rect(0, 0, clientwidth, wFHeight);
if Focused then
Canvas.DrawFocusRect(fFocusRect)
else
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(rect(0, 0, clientwidth, wFHeight));
end;
exit;
end;
if assigned(fImages) then
wImageRect := Rect(0, 0, FImages.Width, FImages.Height)
else
wImageRect := Rect(0, 0, 0, 0);
wimageAdjust := 0;
cheight := VisibleLineCount;
while (cheight > 0) and (index < fItems.count) do
begin
with fItems.Items[index] do
begin
DrawFlags := DT_WORDBREAK;
if FAlignment = taCenter then
DrawFlags := DrawFlags or DT_CENTER;
if FAlignment = taRightJustify then
DrawFlags := DrawFlags or DT_RIGHT;
wCalcRect := LRect;
OffsetRect(wCalcRect, 0, ((LStart - fVScrollPos) * wFHeight)+wImageAdjust);
if assigned(fimages) and ((lcount*wfHeight) < fimages.height) then
inc(wimageAdjust, fimages.height - (lcount*wfHeight));
if wCalcRect.Top < 0 then
wcalcheight := (LStart - fVScrollPos) - lCount
else
wCalcheight := lcount;
dec(cheight, wcalcheight);
if index = fSelectedItemIndex then
begin
if assigned(fimages) then
begin
Canvas.Brush.Color := clHighlight;
Canvas.fillrect(rect(0, wCalcRect.top, wImageRect.right, wCalcRect.Bottom));
if odd(index) then
canvas.brush.color := color
else
canvas.brush.color := oddcolor;
Canvas.fillrect(rect(wImageRect.right, wCalcRect.top, wCalcRect.right, wCalcRect.Bottom));
end
else
begin
Canvas.Font.Color := clHighLightText;
Canvas.Brush.Color := clHighlight;
wCalcRect.Right := ClientWidth;
Canvas.fillrect(rect(0, wCalcRect.top, wCalcRect.right, wCalcRect.Bottom));
end;
end
else
begin
Canvas.Font.Color := Font.Color;
if odd(index) then
canvas.brush.color := color
else
canvas.brush.color := oddcolor;
wCalcRect.Right := ClientWidth;
Canvas.fillrect(rect(0, wCalcRect.top, wCalcRect.right, wCalcRect.Bottom));
end;
if assigned(FImages) then
begin
if fCenterImage then
FImages.Draw(canvas, 0, wCalcRect.Top + (((wCalcRect.Bottom - wCalcRect.Top) div 2) - (fImages.Height div 2)), fImageIndex)
else
FImages.Draw(canvas, 0, wCalcRect.Top, fImageIndex);
end;
wstr := Trim(Text);
DrawText(Canvas.Handle, pchar(wstr), length(wstr), wCalcRect, DrawFlags);
if (index = fFocusedItemIndex) then
begin
fFocusRect := rect(0, wCalcRect.Top, clientwidth, wCalcRect.bottom);
if focused then
Canvas.DrawFocusRect(fFocusRect);
end;
end;
inc(index);
end;
if cHeight > 0 then
begin
Canvas.Brush.Color := color;
Canvas.FillRect(rect(0, wCalcRect.Bottom, clientwidth, wCalcRect.Bottom + ((cHeight + 1) * wFHeight)));
end;
end;
procedure TrmCollectionListBox.UpdateVScrollSize;
var
wScrollInfo: TScrollInfo;
begin
fVScrollSize := fTotalLineCount - VisibleLineCount;
with wScrollInfo do
begin
cbSize := sizeof(TScrollInfo);
fMask := SIF_RANGE or SIF_DISABLENOSCROLL;
nMin := 0;
nMax := fVScrollSize;
end;
SetScrollInfo(Handle, SB_VERT, wScrollInfo, True);
end;
procedure TrmCollectionListBox.WMVScroll(var Msg: TWMVScroll);
var
newPos: integer;
begin
inherited;
case Msg.ScrollCode of
SB_BOTTOM: newPos := fItems.Items[fItems.Count - 1].LStart;
SB_LINEDOWN: newPos := fVScrollPos + 1;
SB_LINEUP: newPos := fVScrollPos - 1;
SB_TOP: newPos := 0;
SB_PAGEDOWN: newPos := fVScrollPos + VisibleLineCount;
SB_PAGEUP: newPos := fVScrollPos - VisibleLineCount;
SB_THUMBPOSITION: newPos := Msg.Pos;
SB_THUMBTRACK: newPos := msg.Pos;
else
exit;
end;
if UpdateVScrollPos(newPos) then
Invalidate;
end;
function TrmCollectionListBox.UpdateVScrollPos(newPos: integer): Boolean;
var
wScrollInfo: TScrollInfo;
begin
result := false;
if (newPos <= 0) and (fVScrollPos = 0) then
exit;
if (newPos > fVScrollSize) and (fVScrollPos = fVScrollSize) then
exit;
if (newPos = fVscrollPos) then
exit;
result := true;
if newpos < 0 then
fVScrollPos := 0
else if newpos > fVscrollSize then
fVScrollPos := fVScrollSize
else
fVScrollPos := newPos;
if fVScrollPos < 0 then
fVScrollPos := 0;
with wScrollInfo do
begin
cbSize := sizeof(TScrollInfo);
fMask := SIF_POS;
nPos := fVScrollPos;
end;
SetScrollInfo(Handle, SB_VERT, wScrollInfo, True);
end;
function TrmCollectionListBox.VisibleLineCount: integer;
begin
result := (clientheight div LineHeight);
end;
function TrmCollectionListBox.LineHeight: integer;
var
TM: tagTextMetricA;
begin
GetTextMetrics(Canvas.Handle, TM);
result := TM.tmHeight;
end;
function TrmCollectionListBox.Add(aText: string; aImageIndex: integer; aData: TObject): integer;
begin
with fItems.Add do
begin
TextData.text := aText;
ImageIndex := aImageIndex;
Data := aData;
result := ItemIndex;
end;
CalcVScrollSize(fItems.count-1);
UpdateVScrollSize;
invalidate;
end;
procedure TrmCollectionListBox.Delete(Index: integer);
begin
fItems.delete(index);
CalcVScrollSize(index-1);
UpdateVScrollSize;
invalidate;
end;
function TrmCollectionListBox.Insert(Index: integer; aText: string; aImageIndex: integer;
aData: TObject): integer;
begin
with fItems.Insert(Index) do
begin
TextData.text := aText;
ImageIndex := aImageIndex;
Data := aData;
result := ItemIndex;
end;
CalcVScrollSize(-1);
UpdateVScrollSize;
invalidate;
end;
procedure TrmCollectionListBox.SetOddColor(const Value: TColor);
begin
if fOddColor <> Value then
begin
fOddColor := Value;
invalidate;
end;
end;
procedure TrmCollectionListBox.CMFontChanged(var Message: TMessage);
begin
inherited;
Canvas.Font.assign(font);
CalcVScrollSize(-1);
invalidate;
end;
procedure TrmCollectionListBox.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
index: integer;
found: boolean;
wTextRect, wCalcRect: TRect;
wFHeight, cheight: integer;
DrawFlags: integer;
wStr : String;
begin
inherited;
if Button = mbLeft then
begin
if CanFocus then
setfocus;
try
index := TopItemIndex;
if index <> -1 then
begin
wFHeight := LineHeight;
wTextRect := Rect(0, 0, clientwidth, 0);
cheight := VisibleLineCount;
found := false;
while (cheight > 0) and (index < fItems.count) and not found do
begin
with fItems.Items[index] do
begin
DrawFlags := DT_WORDBREAK;
if FAlignment = taCenter then
DrawFlags := DrawFlags or DT_CENTER;
if FAlignment = taRightJustify then
DrawFlags := DrawFlags or DT_RIGHT;
wCalcRect := wTextRect;
wStr := trim(Text);
DrawText(Canvas.Handle, pchar(wstr), length(wstr), wCalcRect, DrawFlags or DT_CALCRECT);
wCalcRect.Right := clientwidth;
OffsetRect(wCalcRect, 0, (LStart - fVScrollPos) * wFHeight);
found := ptinrect(wCalcRect, Point(x, y));
if found then
break;
dec(cheight, (LStart - fVScrollPos) - lCount);
end;
inc(index);
end;
if found then
begin
ItemIndex := index;
fFocusedItemIndex := index;
end
else
ItemIndex := -1;
end
else
ItemIndex := -1;
finally
if assigned(fClick) then
fClick(self);
end;
end;
end;
procedure TrmCollectionListBox.SetItemIndex(const Value: integer);
begin
if fSelectedItemIndex <> value then
begin
fSelectedItemIndex := Value;
invalidate;
end;
end;
procedure TrmCollectionListBox.SetBorderStyle(const Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TrmCollectionListBox.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTARROWS;
end;
procedure TrmCollectionListBox.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if fItems.Count > 0 then
begin
case key of
vk_end: fFocusedItemIndex := fItems.count-1;
vk_DOWN: inc(fFocusedItemIndex);
vk_up: dec(fFocusedItemIndex);
vk_home: fFocusedItemIndex := 0;
vk_space, vk_Return:
begin
fSelectedItemIndex := fFocusedItemIndex;
invalidate;
exit;
end;
else
exit;
end;
if fFocusedItemIndex < 0 then
fFocusedItemIndex := 0;
if fFocusedItemIndex >= fItems.count then
fFocusedItemIndex := fItems.Count-1;
UpdateVScrollPos(fItems[fFocusedItemIndex].fLStart);
if fAutoSelect then
fSelectedItemIndex := fFocusedItemIndex;
Invalidate;
end;
end;
function TrmCollectionListBox.TopItemIndex: integer;
{var
index: integer;
found: boolean;}
begin
{ index := 0;
found := false;
if fVScrollSize > -1 then
begin
while (not found) and (index < fItems.Count) do
begin
found := (fVScrollPos >= fItems.Items[index].LStart) and (fVScrollPos <= (fItems.Items[index].lStart + fItems.Items[index].LCount));
if not found then
inc(index);
end;
end
else
begin
if fItems.count > 0 then
index := 0
else
index := -1;
found := true;
end;
if not found then
result := -1
else
result := index;}
result := fTopIndex;
end;
procedure TrmCollectionListBox.cmFOCUSCHANGED(var MSG: TMessage);
begin
inherited;
invalidate;
end;
procedure TrmCollectionListBox.CMBorderChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TrmCollectionListBox.CMCtl3DChanged(var Message: TMessage);
begin
if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd;
inherited;
end;
end.
|
/// <summary>
/// plain api of libProj c library
/// </summary>
/// <remarks>
/// currently using Proj4 api functions
/// </remarks>
unit LibPROJApi;
interface
uses Types, SysUtils;
type
TPJ_LOG_FUNCTION =
procedure (app_data: pointer; level: integer; msg: Pointer) of object; cdecl;
TProjPJ = type Pointer;
TProjCtx = type Pointer;
/// <summary>
/// This function converts a string representation of a coordinate system
/// definition into a projPJ object suitable for use with other API
/// functions. On failure the function will return NULL and set <see cref="LibPROJApi|PJ_strerrno(Integer)">
/// pj_errno</see>.
/// </summary>
/// <param name="def">
/// The definition in the general form. <see href="https://github.com/OSGeo/proj.4/wiki/GenParms/">
/// See PROJ.4 documentation</see>
/// </param>
/// <returns>
/// <b>nil</b> if error (u must see last error code) and else pointer to
/// Coordinate system object
/// </returns>
/// <remarks>
/// Coordinate system objects allocated with pj_init_plus() should be
/// deallocated with <see cref="LibPROJApi|PJ_free(Pointer,Boolean)">
/// pj_free()</see>.
/// </remarks>
function PJ_init_plus(const def: string): TProjPJ; cdecl;
/// <summary>
/// Returns TRUE if input coordinate system object is geographic.
/// </summary>
/// <param name="p">
/// input coordinate system handle.
/// </param>
function PJ_is_geographic(p: TProjPJ): Boolean;
/// <summary>
/// Returns TRUE if input coordinate system object is geocentric.
/// </summary>
/// <param name="p">
/// input coordinate system handle. <br />
/// </param>
function PJ_is_geocentric(p: TProjPJ): Boolean;
/// <summary>
/// Return a projection handle defining the lat/long coordinate system on
/// which a projection is based. If the coordinate system passed in is
/// latlong, a clone of the same will be returned.
/// </summary>
/// <param name="p">
/// input projection handle.
/// </param>
function PJ_latlong_from_proj(p: TProjPJ): TProjPJ;
/// <param name="src">
/// source (input) coordinate system handle.
/// </param>
/// <param name="dst">
/// destination (output) coordinate system handle.
/// </param>
/// <param name="x">
/// x coordinate value.
/// </param>
/// <param name="y">
/// y coordinate value. <br />
/// </param>
/// <param name="angular">
/// false if x/y values in degrees and source or dest coordinate system is geographic.
/// </param>
/// <returns>
/// The return is zero on success, or a PROJ.4 error code.
/// </returns>
/// <remarks>
/// If there is an overall failure, an error code will be returned from the
/// function. Input value that are HUGE_VAL will not be transformed.
/// </remarks>
function PJ_transform_point2D(src, dst: TProjPJ; var x, y: Double; angular:
Boolean): Integer; overload;
/// <param name="src">
/// source (input) coordinate system handle.
/// </param>
/// <param name="dst">
/// destination (output) coordinate system handle.
/// </param>
/// <param name="x">
/// x coordinate value.
/// </param>
/// <param name="y">
/// y coordinate value. <br />
/// </param>
/// <param name="angular">
/// false if x/y values in degrees.
/// </param>
/// <returns>
/// The return is zero on success, or a PROJ.4 error code.
/// </returns>
/// <remarks>
/// If there is an overall failure, an error code will be returned from the
/// function. Input value that are HUGE_VAL will not be transformed.
/// </remarks>
function PJ_transform_point2D(src, dst: TProjPJ; x, y: PDouble; angular:
Boolean): Integer; overload;
/// <param name="src">
/// source (input) coordinate system handle.
/// </param>
/// <param name="dst">
/// destination (output) coordinate system handle.
/// </param>
/// <param name="x">
/// pointer to first x coordinate value.
/// </param>
/// <param name="y">
/// pointer to first y coordinate value. <br />
/// </param>
/// <param name="count">
/// point counts.
/// </param>
/// <param name="angular">
/// false if x/y values in degrees.
/// </param>
/// <returns>
/// The return is zero on success, or a PROJ.4 error code.
/// </returns>
/// <remarks>
/// If there is an overall failure, an error code will be returned from the
/// function. Input value that are HUGE_VAL will not be transformed.
/// </remarks>
function PJ_transform_points2D(src, dst: TProjPJ; x, y: PDouble; count:
Integer; angular: Boolean): Integer;
/// <summary>
/// Returns the PROJ.4 command string that would produce this definition
/// expanded as much as possible. For instance +init= calls and +datum=
/// definitions would be expanded.
/// </summary>
/// <param name="p">
/// coordinate system handle.
/// </param>
function PJ_get_definition(p: TProjPJ): string;
/// <summary>
/// returns 0 if full definitions presented coordinate system handles is
/// same. <br />
/// </summary>
/// <param name="p1">
/// first coordinate system handle.
/// </param>
/// <param name="p2">
/// second coordinate system handle. <br />
/// </param>
/// <returns>
/// <para>
/// -1 if error
/// </para>
/// <para>
/// 0 if definitions same
/// </para>
/// <para>
/// 1 if definitions not same <br />
/// </para>
/// </returns>
function PJ_is_same_definition(p1, p2: TProjPJ): Integer;
/// <summary>
/// cleanup memory associated with libproj coordinate system object. <br />
/// </summary>
/// <param name="p">
/// coordinate system handle.
/// </param>
procedure PJ_free(var p: TProjPJ);
/// <summary>
/// get libproj version string
/// </summary>
function PJ_get_version_string(): string;
/// <summary>
/// validates ProjPJ handle
/// </summary>
function PJ_is_valid(p: TProjPJ): Boolean;
/// <summary>
/// get string description of libproj error code
/// </summary>
/// <param name="errno">
/// libproj error code
/// </param>
function PJ_strerrno(errno: integer): string;
/// <summary>
/// Fetch the internal definition of the spheroid.
/// </summary>
/// <param name="p">
/// coordinate system handle.
/// </param>
/// <param name="major_axis">
/// value of major axis in meters
/// </param>
/// <param name="eccentricity_squared">
/// square of eccentricity
/// </param>
/// <remarks>
/// <para>
/// You can compute "minor axis" from eccentricity_squared as:
/// </para>
/// <para>
/// <i>b = a * sqrt(1 - e2)</i>
/// </para>
/// </remarks>
function PJ_get_spheroid_defn(p: TProjPJ; out major_axis, eccentricity_squared: Double): Boolean;
function PJ_get_errno(): Integer;
implementation
uses
Math,{$IFDEF MSWINDOWS}PROJ.Crtl, Windows{$ENDIF};
var
FDefaultContext: TProjCtx = nil;
const
PJ_RAD_TO_DEG = 57.295779513082320876798154814105000; //(1*180 / PI)
PJ_DEG_TO_RAD = 0.017453292519943295769236907684886;
// obj\$(Platform)\$(Config)
NAME_PREFIX = {$IFDEF WIN32}'_'{$ELSE}''{$ENDIF};
{$REGION 'external declarations to avoid linker errors'}
{$IFNDEF WIN32}
procedure nad_cvt(); external;
function pj_sinu(p1: Pointer): Pointer; external;
function bchgen(): integer; external;
function bch2bps: integer; external;
function pj_deriv(): Integer; external;
function dmstor_ctx: Double; external;
function pj_gc_readcatalog(): Pointer; external;
procedure nad_free(var ct: Pointer); external;
procedure nad_ctable_load(); external;
procedure nad_ctable2_load(); external;
procedure nad_ctable2_init(); external;
procedure nad_ctable_init(); external;
function pj_ctx_ftell(): Cardinal; external;
procedure pj_gridinfo_free( ct: Pointer; var Pointer); external;
procedure pj_gridinfo_init; external;
procedure pj_datum_set; external;
procedure pj_prime_meridians; external;
procedure pj_ctx_get_errno; external;
procedure pj_aea; external;
procedure pj_s_aea; external;
procedure pj_aeqd; external;
procedure pj_s_aeqd; external;
procedure pj_airy; external;
procedure pj_s_airy; external;
procedure pj_aitoff; external;
procedure pj_s_aitoff; external;
procedure pj_alsk; external;
procedure pj_s_alsk; external;
procedure pj_apian; external;
procedure pj_s_apian; external;
procedure pj_august; external;
procedure pj_s_august; external;
procedure pj_axisswap; external;
procedure pj_s_axisswap; external;
procedure pj_bacon; external;
procedure pj_s_bacon; external;
procedure pj_bipc; external;
procedure pj_s_bipc; external;
procedure pj_boggs; external;
procedure pj_s_boggs; external;
procedure pj_bonne; external;
procedure pj_s_bonne; external;
procedure pj_calcofi; external;
procedure pj_s_calcofi; external;
procedure pj_cart; external;
procedure pj_s_cart; external;
procedure pj_cass; external;
procedure pj_s_cass; external;
procedure pj_cc; external;
procedure pj_s_cc; external;
procedure pj_ccon; external;
procedure pj_s_ccon; external;
procedure pj_cea; external;
procedure pj_s_cea; external;
procedure pj_chamb; external;
procedure pj_s_chamb; external;
procedure pj_collg; external;
procedure pj_s_collg; external;
procedure pj_comill; external;
procedure pj_s_comill; external;
procedure pj_crast; external;
procedure pj_s_crast; external;
procedure pj_deformation; external;
procedure pj_s_deformation; external;
procedure pj_denoy; external;
procedure pj_s_denoy; external;
procedure pj_eck1; external;
procedure pj_s_eck1; external;
procedure pj_eck2; external;
procedure pj_s_eck2; external;
procedure pj_eck3; external;
procedure pj_s_eck3; external;
procedure pj_eck4; external;
procedure pj_s_eck4; external;
procedure pj_eck5; external;
procedure pj_s_eck5; external;
procedure pj_eck6; external;
procedure pj_s_eck6; external;
procedure pj_eqc; external;
procedure pj_s_eqc; external;
procedure pj_eqdc; external;
procedure pj_s_eqdc; external;
procedure pj_euler; external;
procedure pj_s_euler; external;
procedure pj_etmerc; external;
procedure pj_s_etmerc; external;
procedure pj_fahey; external;
procedure pj_s_fahey; external;
procedure pj_fouc; external;
procedure pj_s_fouc; external;
procedure pj_fouc_s; external;
procedure pj_s_fouc_s; external;
procedure pj_gall; external;
procedure pj_s_gall; external;
procedure pj_geoc; external;
procedure pj_s_geoc; external;
procedure pj_geocent; external;
procedure pj_s_geocent; external;
procedure pj_geos; external;
procedure pj_s_geos; external;
procedure pj_gins8; external;
procedure pj_s_gins8; external;
procedure pj_gn_sinu; external;
procedure pj_s_gn_sinu; external;
procedure pj_gnom; external;
procedure pj_s_gnom; external;
procedure pj_goode; external;
procedure pj_s_goode; external;
procedure pj_gs48; external;
procedure pj_s_gs48; external;
procedure pj_gs50; external;
procedure pj_s_gs50; external;
procedure pj_hammer; external;
procedure pj_s_hammer; external;
procedure pj_hatano; external;
procedure pj_s_hatano; external;
procedure pj_healpix; external;
procedure pj_s_healpix; external;
procedure pj_rhealpix; external;
procedure pj_s_rhealpix; external;
procedure pj_helmert; external;
procedure pj_s_helmert; external;
procedure pj_hgridshift; external;
procedure pj_s_hgridshift; external;
procedure pj_horner; external;
procedure pj_s_horner; external;
procedure pj_igh; external;
procedure pj_s_igh; external;
procedure pj_imw_p; external;
procedure pj_s_imw_p; external;
procedure pj_isea; external;
procedure pj_s_isea; external;
procedure pj_kav5; external;
procedure pj_s_kav5; external;
procedure pj_kav7; external;
procedure pj_s_kav7; external;
procedure pj_krovak; external;
procedure pj_s_krovak; external;
procedure pj_labrd; external;
procedure pj_s_labrd; external;
procedure pj_laea; external;
procedure pj_s_laea; external;
procedure pj_lagrng; external;
procedure pj_s_lagrng; external;
procedure pj_larr; external;
procedure pj_s_larr; external;
procedure pj_lask; external;
procedure pj_s_lask; external;
procedure pj_lonlat; external;
procedure pj_s_lonlat; external;
procedure pj_latlon; external;
procedure pj_s_latlon; external;
procedure pj_latlong; external;
procedure pj_s_latlong; external;
procedure pj_longlat; external;
procedure pj_s_longlat; external;
procedure pj_lcc; external;
procedure pj_s_lcc; external;
procedure pj_lcca; external;
procedure pj_s_lcca; external;
procedure pj_leac; external;
procedure pj_s_leac; external;
procedure pj_lee_os; external;
procedure pj_s_lee_os; external;
procedure pj_loxim; external;
procedure pj_s_loxim; external;
procedure pj_lsat; external;
procedure pj_s_lsat; external;
procedure pj_mbt_s; external;
procedure pj_s_mbt_s; external;
procedure pj_mbt_fps; external;
procedure pj_s_mbt_fps; external;
procedure pj_mbtfpp; external;
procedure pj_s_mbtfpp; external;
procedure pj_mbtfpq; external;
procedure pj_s_mbtfpq; external;
procedure pj_mbtfps; external;
procedure pj_s_mbtfps; external;
procedure pj_merc; external;
procedure pj_s_merc; external;
procedure pj_mil_os; external;
procedure pj_s_mil_os; external;
procedure pj_mill; external;
procedure pj_s_mill; external;
procedure pj_misrsom; external;
procedure pj_s_misrsom; external;
procedure pj_s_moll; external;
procedure pj_molodensky; external;
procedure pj_s_molodensky; external;
procedure pj_murd1; external;
procedure pj_s_murd1; external;
procedure pj_murd2; external;
procedure pj_s_murd2; external;
procedure pj_murd3; external;
procedure pj_s_murd3; external;
procedure pj_natearth; external;
procedure pj_s_natearth; external;
procedure pj_natearth2; external;
procedure pj_s_natearth2; external;
procedure pj_nell; external;
procedure pj_s_nell; external;
procedure pj_nell_h; external;
procedure pj_s_nell_h; external;
procedure pj_nicol; external;
procedure pj_s_nicol; external;
procedure pj_nsper; external;
procedure pj_s_nsper; external;
procedure pj_nzmg; external;
procedure pj_s_nzmg; external;
procedure pj_ob_tran; external;
procedure pj_s_ob_tran; external;
procedure pj_ocea; external;
procedure pj_s_ocea; external;
procedure pj_oea; external;
procedure pj_s_oea; external;
procedure pj_omerc; external;
procedure pj_s_omerc; external;
procedure pj_ortel; external;
procedure pj_s_ortel; external;
procedure pj_ortho; external;
procedure pj_s_ortho; external;
procedure pj_pconic; external;
procedure pj_s_pconic; external;
procedure pj_patterson; external;
procedure pj_s_patterson; external;
procedure pj_pipeline; external;
procedure pj_s_pipeline; external;
procedure pj_poly; external;
procedure pj_s_poly; external;
procedure pj_putp1; external;
procedure pj_s_putp1; external;
procedure pj_putp2; external;
procedure pj_s_putp2; external;
procedure pj_putp3; external;
procedure pj_s_putp3; external;
procedure pj_putp3p; external;
procedure pj_s_putp3p; external;
procedure pj_putp4p; external;
procedure pj_s_putp4p; external;
procedure pj_putp5; external;
procedure pj_s_putp5; external;
procedure pj_putp5p; external;
procedure pj_s_putp5p; external;
procedure pj_putp6; external;
procedure pj_s_putp6; external;
procedure pj_putp6p; external;
procedure pj_s_putp6p; external;
procedure pj_qua_aut; external;
procedure pj_s_qua_aut; external;
procedure pj_qsc; external;
procedure pj_s_qsc; external;
procedure pj_robin; external;
procedure pj_s_robin; external;
procedure pj_rpoly; external;
procedure pj_s_rpoly; external;
procedure pj_sch; external;
procedure pj_s_sch; external;
procedure pj_s_sinu; external;
procedure pj_somerc; external;
procedure pj_s_somerc; external;
procedure pj_stere; external;
procedure pj_s_stere; external;
procedure pj_sterea; external;
procedure pj_s_sterea; external;
procedure pj_gstmerc; external;
procedure pj_s_gstmerc; external;
procedure pj_tcc; external;
procedure pj_s_tcc; external;
procedure pj_tcea; external;
procedure pj_s_tcea; external;
procedure pj_times; external;
procedure pj_s_times; external;
procedure pj_tissot; external;
procedure pj_s_tissot; external;
procedure pj_tmerc; external;
procedure pj_s_tmerc; external;
procedure pj_tpeqd; external;
procedure pj_s_tpeqd; external;
procedure pj_tpers; external;
procedure pj_s_tpers; external;
procedure pj_unitconvert; external;
procedure pj_s_unitconvert; external;
procedure pj_ups; external;
procedure pj_s_ups; external;
procedure pj_urm5; external;
procedure pj_s_urm5; external;
procedure pj_urmfps; external;
procedure pj_s_urmfps; external;
procedure pj_utm; external;
procedure pj_s_utm; external;
procedure pj_vandg; external;
procedure pj_s_vandg; external;
procedure pj_vandg2; external;
procedure pj_s_vandg2; external;
procedure pj_vandg3; external;
procedure pj_s_vandg3; external;
procedure pj_vandg4; external;
procedure pj_s_vandg4; external;
procedure pj_vitk1; external;
procedure pj_s_vitk1; external;
procedure pj_vgridshift; external;
procedure pj_s_vgridshift; external;
procedure pj_wag1; external;
procedure pj_s_wag1; external;
procedure pj_wag2; external;
procedure pj_s_wag2; external;
procedure pj_wag3; external;
procedure pj_s_wag3; external;
procedure pj_wag4; external;
procedure pj_s_wag4; external;
procedure pj_wag5; external;
procedure pj_s_wag5; external;
procedure pj_wag6; external;
procedure pj_s_wag6; external;
procedure pj_wag7; external;
procedure pj_s_wag7; external;
procedure pj_webmerc; external;
procedure pj_s_webmerc; external;
procedure pj_weren; external;
procedure pj_s_weren; external;
procedure pj_wink1; external;
procedure pj_s_wink1; external;
procedure pj_wink2; external;
procedure pj_s_wink2; external;
procedure pj_wintri; external;
procedure pj_s_wintri; external;
procedure pj_fwd4d; external;
procedure pj_inv4d; external;
procedure dmstor; external;
procedure pj_ellipsoid; external;
procedure pj_rouss; external;
procedure pj_s_rouss; external;
procedure pj_inv3d; external;
procedure pj_strdup; external;
procedure pj_find_file; external;
procedure pj_has_inverse; external;
procedure pj_inherit_ellipsoid_def; external;
procedure pj_left; external;
procedure pj_make_args; external;
procedure pj_right; external;
procedure pj_trim_argc; external;
procedure pj_trim_argv; external;
procedure proj_get_path_count; external;
procedure proj_get_searchpath; external;
procedure rtodms; external;
procedure pj_approx_2D_trans; external;
procedure pj_approx_3D_trans; external;
procedure proj_create_argv; external;
procedure proj_destroy; external;
procedure proj_log_error; external;
procedure proj_vgrid_init; external;
procedure proj_vgrid_value; external;
procedure proj_hgrid_apply; external;
procedure proj_hgrid_init; external;
procedure proj_create; external;
procedure proj_hgrid_value; external;
procedure pj_expand_init; external;
procedure pj_factors; external;
procedure pj_fwd; external;
procedure pj_inv; external;
procedure pj_fwd3d; external;
procedure pj_set_ctx; external;
procedure pj_vlog; external;
procedure pj_ctx_fopen; external;
procedure pj_apply_vgridshift; external;
procedure pj_apply_gridshift_2; external;
procedure proj_mdist_ini; external;
procedure proj_mdist; external;
procedure proj_inv_mdist; external;
procedure pj_eqearth; external;
procedure pj_s_eqearth; external;
{$ELSE}
procedure _nad_cvt(); external;
function _pj_sinu(p1: Pointer): Pointer; external;
function _bchgen(): integer; external;
function _bch2bps: integer; external;
function _pj_deriv(): Integer; external;
function _dmstor_ctx: Double; external;
function _pj_gc_readcatalog(): Pointer; external;
procedure _nad_free(var ct: Pointer); external;
procedure _nad_ctable_load(); external;
procedure _nad_ctable2_load(); external;
procedure _nad_ctable2_init(); external;
procedure _nad_ctable_init(); external;
function _pj_ctx_ftell(): Cardinal; external;
procedure _pj_gridinfo_free( ct: Pointer; var Pointer); external;
procedure _pj_gridinfo_init; external;
procedure _pj_datum_set; external;
procedure _pj_prime_meridians; external;
procedure _pj_ctx_get_errno; external;
procedure _pj_aea; external;
procedure _pj_s_aea; external;
procedure _pj_aeqd; external;
procedure _pj_s_aeqd; external;
procedure _pj_airy; external;
procedure _pj_s_airy; external;
procedure _pj_aitoff; external;
procedure _pj_s_aitoff; external;
procedure _pj_alsk; external;
procedure _pj_s_alsk; external;
procedure _pj_apian; external;
procedure _pj_s_apian; external;
procedure _pj_august; external;
procedure _pj_s_august; external;
procedure _pj_axisswap; external;
procedure _pj_s_axisswap; external;
procedure _pj_bacon; external;
procedure _pj_s_bacon; external;
procedure _pj_bipc; external;
procedure _pj_s_bipc; external;
procedure _pj_boggs; external;
procedure _pj_s_boggs; external;
procedure _pj_bonne; external;
procedure _pj_s_bonne; external;
procedure _pj_calcofi; external;
procedure _pj_s_calcofi; external;
procedure _pj_cart; external;
procedure _pj_s_cart; external;
procedure _pj_cass; external;
procedure _pj_s_cass; external;
procedure _pj_cc; external;
procedure _pj_s_cc; external;
procedure _pj_ccon; external;
procedure _pj_s_ccon; external;
procedure _pj_cea; external;
procedure _pj_s_cea; external;
procedure _pj_chamb; external;
procedure _pj_s_chamb; external;
procedure _pj_collg; external;
procedure _pj_s_collg; external;
procedure _pj_comill; external;
procedure _pj_s_comill; external;
procedure _pj_crast; external;
procedure _pj_s_crast; external;
procedure _pj_deformation; external;
procedure _pj_s_deformation; external;
procedure _pj_denoy; external;
procedure _pj_s_denoy; external;
procedure _pj_eck1; external;
procedure _pj_s_eck1; external;
procedure _pj_eck2; external;
procedure _pj_s_eck2; external;
procedure _pj_eck3; external;
procedure _pj_s_eck3; external;
procedure _pj_eck4; external;
procedure _pj_s_eck4; external;
procedure _pj_eck5; external;
procedure _pj_s_eck5; external;
procedure _pj_eck6; external;
procedure _pj_s_eck6; external;
procedure _pj_eqc; external;
procedure _pj_s_eqc; external;
procedure _pj_eqdc; external;
procedure _pj_s_eqdc; external;
procedure _pj_euler; external;
procedure _pj_s_euler; external;
procedure _pj_etmerc; external;
procedure _pj_s_etmerc; external;
procedure _pj_fahey; external;
procedure _pj_s_fahey; external;
procedure _pj_fouc; external;
procedure _pj_s_fouc; external;
procedure _pj_fouc_s; external;
procedure _pj_s_fouc_s; external;
procedure _pj_gall; external;
procedure _pj_s_gall; external;
procedure _pj_geoc; external;
procedure _pj_s_geoc; external;
procedure _pj_geocent; external;
procedure _pj_s_geocent; external;
procedure _pj_geos; external;
procedure _pj_s_geos; external;
procedure _pj_gins8; external;
procedure _pj_s_gins8; external;
procedure _pj_gn_sinu; external;
procedure _pj_s_gn_sinu; external;
procedure _pj_gnom; external;
procedure _pj_s_gnom; external;
procedure _pj_goode; external;
procedure _pj_s_goode; external;
procedure _pj_gs48; external;
procedure _pj_s_gs48; external;
procedure _pj_gs50; external;
procedure _pj_s_gs50; external;
procedure _pj_hammer; external;
procedure _pj_s_hammer; external;
procedure _pj_hatano; external;
procedure _pj_s_hatano; external;
procedure _pj_healpix; external;
procedure _pj_s_healpix; external;
procedure _pj_rhealpix; external;
procedure _pj_s_rhealpix; external;
procedure _pj_helmert; external;
procedure _pj_s_helmert; external;
procedure _pj_hgridshift; external;
procedure _pj_s_hgridshift; external;
procedure _pj_horner; external;
procedure _pj_s_horner; external;
procedure _pj_igh; external;
procedure _pj_s_igh; external;
procedure _pj_imw_p; external;
procedure _pj_s_imw_p; external;
procedure _pj_isea; external;
procedure _pj_s_isea; external;
procedure _pj_kav5; external;
procedure _pj_s_kav5; external;
procedure _pj_kav7; external;
procedure _pj_s_kav7; external;
procedure _pj_krovak; external;
procedure _pj_s_krovak; external;
procedure _pj_labrd; external;
procedure _pj_s_labrd; external;
procedure _pj_laea; external;
procedure _pj_s_laea; external;
procedure _pj_lagrng; external;
procedure _pj_s_lagrng; external;
procedure _pj_larr; external;
procedure _pj_s_larr; external;
procedure _pj_lask; external;
procedure _pj_s_lask; external;
procedure _pj_lonlat; external;
procedure _pj_s_lonlat; external;
procedure _pj_latlon; external;
procedure _pj_s_latlon; external;
procedure _pj_latlong; external;
procedure _pj_s_latlong; external;
procedure _pj_longlat; external;
procedure _pj_s_longlat; external;
procedure _pj_lcc; external;
procedure _pj_s_lcc; external;
procedure _pj_lcca; external;
procedure _pj_s_lcca; external;
procedure _pj_leac; external;
procedure _pj_s_leac; external;
procedure _pj_lee_os; external;
procedure _pj_s_lee_os; external;
procedure _pj_loxim; external;
procedure _pj_s_loxim; external;
procedure _pj_lsat; external;
procedure _pj_s_lsat; external;
procedure _pj_mbt_s; external;
procedure _pj_s_mbt_s; external;
procedure _pj_mbt_fps; external;
procedure _pj_s_mbt_fps; external;
procedure _pj_mbtfpp; external;
procedure _pj_s_mbtfpp; external;
procedure _pj_mbtfpq; external;
procedure _pj_s_mbtfpq; external;
procedure _pj_mbtfps; external;
procedure _pj_s_mbtfps; external;
procedure _pj_merc; external;
procedure _pj_s_merc; external;
procedure _pj_mil_os; external;
procedure _pj_s_mil_os; external;
procedure _pj_mill; external;
procedure _pj_s_mill; external;
procedure _pj_misrsom; external;
procedure _pj_s_misrsom; external;
procedure _pj_s_moll; external;
procedure _pj_molodensky; external;
procedure _pj_s_molodensky; external;
procedure _pj_murd1; external;
procedure _pj_s_murd1; external;
procedure _pj_murd2; external;
procedure _pj_s_murd2; external;
procedure _pj_murd3; external;
procedure _pj_s_murd3; external;
procedure _pj_natearth; external;
procedure _pj_s_natearth; external;
procedure _pj_natearth2; external;
procedure _pj_s_natearth2; external;
procedure _pj_nell; external;
procedure _pj_s_nell; external;
procedure _pj_nell_h; external;
procedure _pj_s_nell_h; external;
procedure _pj_nicol; external;
procedure _pj_s_nicol; external;
procedure _pj_nsper; external;
procedure _pj_s_nsper; external;
procedure _pj_nzmg; external;
procedure _pj_s_nzmg; external;
procedure _pj_ob_tran; external;
procedure _pj_s_ob_tran; external;
procedure _pj_ocea; external;
procedure _pj_s_ocea; external;
procedure _pj_oea; external;
procedure _pj_s_oea; external;
procedure _pj_omerc; external;
procedure _pj_s_omerc; external;
procedure _pj_ortel; external;
procedure _pj_s_ortel; external;
procedure _pj_ortho; external;
procedure _pj_s_ortho; external;
procedure _pj_pconic; external;
procedure _pj_s_pconic; external;
procedure _pj_patterson; external;
procedure _pj_s_patterson; external;
procedure _pj_pipeline; external;
procedure _pj_s_pipeline; external;
procedure _pj_poly; external;
procedure _pj_s_poly; external;
procedure _pj_putp1; external;
procedure _pj_s_putp1; external;
procedure _pj_putp2; external;
procedure _pj_s_putp2; external;
procedure _pj_putp3; external;
procedure _pj_s_putp3; external;
procedure _pj_putp3p; external;
procedure _pj_s_putp3p; external;
procedure _pj_putp4p; external;
procedure _pj_s_putp4p; external;
procedure _pj_putp5; external;
procedure _pj_s_putp5; external;
procedure _pj_putp5p; external;
procedure _pj_s_putp5p; external;
procedure _pj_putp6; external;
procedure _pj_s_putp6; external;
procedure _pj_putp6p; external;
procedure _pj_s_putp6p; external;
procedure _pj_qua_aut; external;
procedure _pj_s_qua_aut; external;
procedure _pj_qsc; external;
procedure _pj_s_qsc; external;
procedure _pj_robin; external;
procedure _pj_s_robin; external;
procedure _pj_rpoly; external;
procedure _pj_s_rpoly; external;
procedure _pj_sch; external;
procedure _pj_s_sch; external;
procedure _pj_s_sinu; external;
procedure _pj_somerc; external;
procedure _pj_s_somerc; external;
procedure _pj_stere; external;
procedure _pj_s_stere; external;
procedure _pj_sterea; external;
procedure _pj_s_sterea; external;
procedure _pj_gstmerc; external;
procedure _pj_s_gstmerc; external;
procedure _pj_tcc; external;
procedure _pj_s_tcc; external;
procedure _pj_tcea; external;
procedure _pj_s_tcea; external;
procedure _pj_times; external;
procedure _pj_s_times; external;
procedure _pj_tissot; external;
procedure _pj_s_tissot; external;
procedure _pj_tmerc; external;
procedure _pj_s_tmerc; external;
procedure _pj_tpeqd; external;
procedure _pj_s_tpeqd; external;
procedure _pj_tpers; external;
procedure _pj_s_tpers; external;
procedure _pj_unitconvert; external;
procedure _pj_s_unitconvert; external;
procedure _pj_ups; external;
procedure _pj_s_ups; external;
procedure _pj_urm5; external;
procedure _pj_s_urm5; external;
procedure _pj_urmfps; external;
procedure _pj_s_urmfps; external;
procedure _pj_utm; external;
procedure _pj_s_utm; external;
procedure _pj_vandg; external;
procedure _pj_s_vandg; external;
procedure _pj_vandg2; external;
procedure _pj_s_vandg2; external;
procedure _pj_vandg3; external;
procedure _pj_s_vandg3; external;
procedure _pj_vandg4; external;
procedure _pj_s_vandg4; external;
procedure _pj_vitk1; external;
procedure _pj_s_vitk1; external;
procedure _pj_vgridshift; external;
procedure _pj_s_vgridshift; external;
procedure _pj_wag1; external;
procedure _pj_s_wag1; external;
procedure _pj_wag2; external;
procedure _pj_s_wag2; external;
procedure _pj_wag3; external;
procedure _pj_s_wag3; external;
procedure _pj_wag4; external;
procedure _pj_s_wag4; external;
procedure _pj_wag5; external;
procedure _pj_s_wag5; external;
procedure _pj_wag6; external;
procedure _pj_s_wag6; external;
procedure _pj_wag7; external;
procedure _pj_s_wag7; external;
procedure _pj_webmerc; external;
procedure _pj_s_webmerc; external;
procedure _pj_weren; external;
procedure _pj_s_weren; external;
procedure _pj_wink1; external;
procedure _pj_s_wink1; external;
procedure _pj_wink2; external;
procedure _pj_s_wink2; external;
procedure _pj_wintri; external;
procedure _pj_s_wintri; external;
procedure _pj_fwd4d; external;
procedure _pj_inv4d; external;
procedure _dmstor; external;
procedure _pj_expand_init; external;
procedure _pj_factors; external;
procedure _pj_fwd; external;
procedure _pj_inv; external;
procedure _pj_fwd3d; external;
procedure _pj_set_ctx; external;
procedure _pj_vlog; external;
procedure _pj_ctx_fopen; external;
procedure _pj_apply_vgridshift; external;
procedure _pj_apply_gridshift_2; external;
procedure _proj_mdist_ini; external;
procedure _proj_mdist; external;
procedure _proj_inv_mdist; external;
procedure _pj_ellipsoid; external;
procedure _pj_rouss; external;
procedure _pj_s_rouss; external;
procedure _pj_inv3d; external;
procedure _pj_strdup; external;
procedure _pj_find_file; external;
procedure _pj_has_inverse; external;
procedure _pj_inherit_ellipsoid_def; external;
procedure _pj_left; external;
procedure _pj_make_args; external;
procedure _pj_right; external;
procedure _pj_trim_argc; external;
procedure _pj_trim_argv; external;
procedure _proj_get_path_count; external;
procedure _proj_get_searchpath; external;
procedure _rtodms; external;
procedure _pj_approx_2D_trans; external;
procedure _pj_approx_3D_trans; external;
procedure _proj_create_argv; external;
procedure _proj_destroy; external;
procedure _proj_log_error; external;
procedure _proj_vgrid_init; external;
procedure _proj_vgrid_value; external;
procedure _proj_hgrid_apply; external;
procedure _proj_hgrid_init; external;
procedure _proj_create; external;
procedure _proj_hgrid_value; external;
procedure _pj_eqearth; external;
procedure _pj_s_eqearth; external;
{$ENDIF}
{$ENDREGION}
{$REGION 'precompiled lib proj c code'}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_aeqd.o'} {$ELSE} {$L 'PJ_aeqd.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_gnom.o'} {$ELSE} {$L 'PJ_gnom.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_laea.o'} {$ELSE} {$L 'PJ_laea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_mod_ster.o'} {$ELSE} {$L 'PJ_mod_ster.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_nsper.o'} {$ELSE} {$L 'PJ_nsper.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_nzmg.o'} {$ELSE} {$L 'PJ_nzmg.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_ortho.o'} {$ELSE} {$L 'PJ_ortho.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_stere.o'} {$ELSE} {$L 'PJ_stere.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_sterea.o'} {$ELSE} {$L 'PJ_sterea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'proj_rouss.o'} {$ELSE} {$L 'proj_rouss.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_aea.o'} {$ELSE} {$L 'PJ_aea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_bipc.o'} {$ELSE} {$L 'PJ_bipc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_bonne.o'} {$ELSE} {$L 'PJ_bonne.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eqdc.o'} {$ELSE} {$L 'PJ_eqdc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_imw_p.o'} {$ELSE} {$L 'PJ_imw_p.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_lcc.o'} {$ELSE} {$L 'PJ_lcc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_poly.o'} {$ELSE} {$L 'PJ_poly.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_rpoly.o'} {$ELSE} {$L 'PJ_rpoly.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_sconics.o'} {$ELSE} {$L 'PJ_sconics.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_lcca.o'} {$ELSE} {$L 'PJ_lcca.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_ccon.o'} {$ELSE} {$L 'PJ_ccon.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_cass.o'} {$ELSE} {$L 'PJ_cass.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_cc.o'} {$ELSE} {$L 'PJ_cc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_cea.o'} {$ELSE} {$L 'PJ_cea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eqc.o'} {$ELSE} {$L 'PJ_eqc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_gall.o'} {$ELSE} {$L 'PJ_gall.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_labrd.o'} {$ELSE} {$L 'PJ_labrd.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_lsat.o'} {$ELSE} {$L 'PJ_lsat.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_misrsom.o'} {$ELSE} {$L 'PJ_misrsom.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_merc.o'} {$ELSE} {$L 'PJ_merc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_mill.o'} {$ELSE} {$L 'PJ_mill.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_ocea.o'} {$ELSE} {$L 'PJ_ocea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_omerc.o'} {$ELSE} {$L 'PJ_omerc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_patterson.o'} {$ELSE} {$L 'PJ_patterson.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_somerc.o'} {$ELSE} {$L 'PJ_somerc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_tcc.o'} {$ELSE} {$L 'PJ_tcc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_tcea.o'} {$ELSE} {$L 'PJ_tcea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_tmerc.o'} {$ELSE} {$L 'PJ_tmerc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_geos.o'} {$ELSE} {$L 'PJ_geos.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_gstmerc.o'} {$ELSE} {$L 'PJ_gstmerc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'proj_etmerc.o'} {$ELSE} {$L 'proj_etmerc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_comill.o'} {$ELSE} {$L 'PJ_comill.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_airy.o'} {$ELSE} {$L 'PJ_airy.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_aitoff.o'} {$ELSE} {$L 'PJ_aitoff.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_august.o'} {$ELSE} {$L 'PJ_august.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_bacon.o'} {$ELSE} {$L 'PJ_bacon.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_chamb.o'} {$ELSE} {$L 'PJ_chamb.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_hammer.o'} {$ELSE} {$L 'PJ_hammer.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_lagrng.o'} {$ELSE} {$L 'PJ_lagrng.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_larr.o'} {$ELSE} {$L 'PJ_larr.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_lask.o'} {$ELSE} {$L 'PJ_lask.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_nocol.o'} {$ELSE} {$L 'PJ_nocol.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_ob_tran.o'} {$ELSE} {$L 'PJ_ob_tran.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_oea.o'} {$ELSE} {$L 'PJ_oea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_sch.o'} {$ELSE} {$L 'PJ_sch.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_tpeqd.o'} {$ELSE} {$L 'PJ_tpeqd.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_vandg.o'} {$ELSE} {$L 'PJ_vandg.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_vandg2.o'} {$ELSE} {$L 'PJ_vandg2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_vandg4.o'} {$ELSE} {$L 'PJ_vandg4.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_wag7.o'} {$ELSE} {$L 'PJ_wag7.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_latlong.o'} {$ELSE} {$L 'PJ_latlong.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_krovak.o'} {$ELSE} {$L 'PJ_krovak.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_geoc.o'} {$ELSE} {$L 'PJ_geoc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_geocent.o'} {$ELSE} {$L 'pj_geocent.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_healpix.o'} {$ELSE} {$L 'PJ_healpix.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_qsc.o'} {$ELSE} {$L 'PJ_qsc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_boggs.o'} {$ELSE} {$L 'PJ_boggs.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_collg.o'} {$ELSE} {$L 'PJ_collg.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_crast.o'} {$ELSE} {$L 'PJ_crast.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_denoy.o'} {$ELSE} {$L 'PJ_denoy.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eck1.o'} {$ELSE} {$L 'PJ_eck1.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eck2.o'} {$ELSE} {$L 'PJ_eck2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eck3.o'} {$ELSE} {$L 'PJ_eck3.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eck4.o'} {$ELSE} {$L 'PJ_eck4.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eck5.o'} {$ELSE} {$L 'PJ_eck5.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_fahey.o'} {$ELSE} {$L 'PJ_fahey.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_fouc_s.o'} {$ELSE} {$L 'PJ_fouc_s.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_gins8.o'} {$ELSE} {$L 'PJ_gins8.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_gn_sinu.o'} {$ELSE} {$L 'PJ_gn_sinu.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_goode.o'} {$ELSE} {$L 'PJ_goode.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_igh.o'} {$ELSE} {$L 'PJ_igh.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_hatano.o'} {$ELSE} {$L 'PJ_hatano.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_loxim.o'} {$ELSE} {$L 'PJ_loxim.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_mbt_fps.o'} {$ELSE} {$L 'PJ_mbt_fps.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_mbtfpp.o'} {$ELSE} {$L 'PJ_mbtfpp.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_mbtfpq.o'} {$ELSE} {$L 'PJ_mbtfpq.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_moll.o'} {$ELSE} {$L 'PJ_moll.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_nell.o'} {$ELSE} {$L 'PJ_nell.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_nell_h.o'} {$ELSE} {$L 'PJ_nell_h.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_putp2.o'} {$ELSE} {$L 'PJ_putp2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_putp3.o'} {$ELSE} {$L 'PJ_putp3.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_putp4p.o'} {$ELSE} {$L 'PJ_putp4p.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_putp5.o'} {$ELSE} {$L 'PJ_putp5.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_putp6.o'} {$ELSE} {$L 'PJ_putp6.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_robin.o'} {$ELSE} {$L 'PJ_robin.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_sts.o'} {$ELSE} {$L 'PJ_sts.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_urm5.o'} {$ELSE} {$L 'PJ_urm5.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_urmfps.o'} {$ELSE} {$L 'PJ_urmfps.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_wag2.o'} {$ELSE} {$L 'PJ_wag2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_wag3.o'} {$ELSE} {$L 'PJ_wag3.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_wink1.o'} {$ELSE} {$L 'PJ_wink1.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_wink2.o'} {$ELSE} {$L 'PJ_wink2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_isea.o'} {$ELSE} {$L 'PJ_isea.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_calcofi.o'} {$ELSE} {$L 'PJ_calcofi.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_natearth.o'} {$ELSE} {$L 'PJ_natearth.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_natearth2.o'} {$ELSE} {$L 'PJ_natearth2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_times.o'} {$ELSE} {$L 'PJ_times.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_eqearth.o'} {$ELSE} {$L 'PJ_eqearth.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'aasincos.o'} {$ELSE} {$L 'aasincos.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'adjlon.o'} {$ELSE} {$L 'adjlon.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'bch2bps.o'} {$ELSE} {$L 'bch2bps.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'bchgen.o'} {$ELSE} {$L 'bchgen.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_gauss.o'} {$ELSE} {$L 'pj_gauss.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'biveval.o'} {$ELSE} {$L 'biveval.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'dmstor.o'} {$ELSE} {$L 'dmstor.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'mk_cheby.o'} {$ELSE} {$L 'mk_cheby.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_auth.o'} {$ELSE} {$L 'pj_auth.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_deriv.o'} {$ELSE} {$L 'pj_deriv.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_ell_set.o'} {$ELSE} {$L 'pj_ell_set.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_ellps.o'} {$ELSE} {$L 'pj_ellps.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_errno.o'} {$ELSE} {$L 'pj_errno.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_factors.o'} {$ELSE} {$L 'pj_factors.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_fwd.o'} {$ELSE} {$L 'pj_fwd.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_init.o'} {$ELSE} {$L 'pj_init.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_inv.o'} {$ELSE} {$L 'pj_inv.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_list.o'} {$ELSE} {$L 'pj_list.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_malloc.o'} {$ELSE} {$L 'pj_malloc.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_mlfn.o'} {$ELSE} {$L 'pj_mlfn.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_msfn.o'} {$ELSE} {$L 'pj_msfn.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_open_lib.o'} {$ELSE} {$L 'pj_open_lib.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_param.o'} {$ELSE} {$L 'pj_param.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_phi2.o'} {$ELSE} {$L 'pj_phi2.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_pr_list.o'} {$ELSE} {$L 'pj_pr_list.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_qsfn.o'} {$ELSE} {$L 'pj_qsfn.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_strerrno.o'} {$ELSE} {$L 'pj_strerrno.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_tsfn.o'} {$ELSE} {$L 'pj_tsfn.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_units.o'} {$ELSE} {$L 'pj_units.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_zpoly1.o'} {$ELSE} {$L 'pj_zpoly1.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'rtodms.o'} {$ELSE} {$L 'rtodms.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'vector1.o'} {$ELSE} {$L 'vector1.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_release.o'} {$ELSE} {$L 'pj_release.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'geocent.o'} {$ELSE} {$L 'geocent.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_transform.o'} {$ELSE} {$L 'pj_transform.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_datum_set.o'} {$ELSE} {$L 'pj_datum_set.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_datums.o'} {$ELSE} {$L 'pj_datums.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_apply_gridshift.o'} {$ELSE} {$L 'pj_apply_gridshift.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_gc_reader.o'} {$ELSE} {$L 'pj_gc_reader.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_gridcatalog.o'} {$ELSE} {$L 'pj_gridcatalog.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'nad_cvt.o'} {$ELSE} {$L 'nad_cvt.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'nad_init.o'} {$ELSE} {$L 'nad_init.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'nad_intr.o'} {$ELSE} {$L 'nad_intr.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_utils.o'} {$ELSE} {$L 'pj_utils.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_gridlist.o'} {$ELSE} {$L 'pj_gridlist.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_gridinfo.o'} {$ELSE} {$L 'pj_gridinfo.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'proj_mdist.o'} {$ELSE} {$L 'proj_mdist.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_mutex.o'} {$ELSE} {$L 'pj_mutex.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_initcache.o'} {$ELSE} {$L 'pj_initcache.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_ctx.o'} {$ELSE} {$L 'pj_ctx.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_fileapi.o'} {$ELSE} {$L 'pj_fileapi.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_log.o'} {$ELSE} {$L 'pj_log.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_apply_vgridshift.o'} {$ELSE} {$L 'pj_apply_vgridshift.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_strtod.o'} {$ELSE} {$L 'pj_strtod.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_internal.o'} {$ELSE} {$L 'pj_internal.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'pj_math.o'} {$ELSE} {$L 'pj_math.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'proj_4D_api.o'} {$ELSE} {$L 'proj_4D_api.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_cart.o'} {$ELSE} {$L 'PJ_cart.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_pipeline.o'} {$ELSE} {$L 'PJ_pipeline.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_horner.o'} {$ELSE} {$L 'PJ_horner.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_helmert.o'} {$ELSE} {$L 'PJ_helmert.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_vgridshift.o'} {$ELSE} {$L 'PJ_vgridshift.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_hgridshift.o'} {$ELSE} {$L 'PJ_hgridshift.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_unitconvert.o'} {$ELSE} {$L 'PJ_unitconvert.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_molodensky.o'} {$ELSE} {$L 'PJ_molodensky.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_deformation.o'} {$ELSE} {$L 'PJ_deformation.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'PJ_axisswap.o'} {$ELSE} {$L 'PJ_axisswap.obj'} {$ENDIF} {$ENDIF}
{$IFDEF MSWINDOWS} {$IFDEF WIN64} {$L 'geodesic.o'} {$ELSE} {$L 'geodesic.obj'} {$ENDIF} {$ENDIF}
{$ENDREGION}
{$REGION 'api calls'}
function _pj_is_latlong(p: TProjPJ): integer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_is_latlong';
function _pj_is_geocent(p: TProjPJ): integer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_is_geocent';
function _pj_latlong_from_proj(p: TProjPJ): TProjPJ; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_latlong_from_proj';
procedure _pj_free(p: TProjPJ); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_free';
function _pj_transform(src,dst: TProjPJ; point_count,point_offset: integer; x,y,z: PDouble): Integer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_transform';
function _pj_get_def(p: TProjPJ): PAnsiString; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_def';
function _pj_strerrno(errno: Integer): Pointer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_strerrno';
function _pj_get_release(): Pointer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_release';
function _pj_ctx_fgets(ctx: TProjCtx; line: PByte; Size: Integer; _file: PInteger): PByte; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_ctx_fgets';
procedure _pj_log(ctx: TProjCtx; level: Integer; fmt: MarshaledAString); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_log'; varargs;
procedure _pj_get_spheroid_defn(p: TProjPJ; major_axis: PDouble; eccentricity_squared: PDouble); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_spheroid_defn';
function _pj_get_errno_ref(): PInteger; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_errno_ref';
function _pj_context_errno(ctx: TProjCtx): Integer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'proj_context_errno';
function _pj_ctx_alloc: TProjCtx; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_ctx_alloc';
function _pj_get_default_ctx(): TProjCtx; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_default_ctx';
function _pj_get_ctx(p: TProjPJ): TProjCtx; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_get_ctx';
function _pj_init_plus_ctx(ctx: TProjCtx; defn: MarshaledAString): TProjPJ; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_init_plus_ctx';
function _pj_init_plus(const def: MarshaledAString): TProjPJ; overload; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_init_plus';
procedure _pj_ctx_free( ctx: TProjCtx ); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_ctx_free';
procedure _pj_ctx_set_debug( ctx: TProjCtx; lvl: Integer ); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_ctx_set_debug';
function _pj_set_log_level(ctx: TProjCtx; lvl: Integer): Integer; cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'proj_log_level';
procedure _pj_ctx_set_logger(ctx: TProjCtx; logger: Pointer); cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'pj_ctx_set_logger';
function _pj_torad (angle_in_degrees: double): double;cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'proj_torad';
function _pj_todeg (angle_in_radians: double): double;cdecl; external {$IFDEF MSWINDOWS}name NAME_PREFIX+{$ENDIF}'proj_todeg';
{$ENDREGION 'Api calls'}
{$IFDEF MSWINDOWS}
function _sinx_impl(x: double; n: cardinal; m: integer): double; cdecl; inline;
begin
if x.IsNan or x.IsInfinity then
Result := Math.NaN
else
begin
if n and $01 <> 0 then
result := system.cos(x)
else
result := system.sin(x);
if n and $02 <> 0 then
Result := -Result;
end;
end;
{$IFDEF WIN64}
function _Sinx(x: double; n: cardinal; m: integer): double; cdecl; inline;
begin
result := _sinx_impl(x,n,m);
end;
function _Log(x: double): double;cdecl; inline;
begin
Result := System.Ln(x);
end;
function _Cosh(v: double): double;cdecl; inline;
begin
Result := Math.Cosh(v);
end;
function _Sinh(v: double): double;cdecl; inline;
begin
Result := Math.Sinh(v);
end;
function _FNan(): single; cdecl; inline;
begin
Result := Math.NaN;
end;
function _Inf(): Double;cdecl; inline;
begin
Result := Math.Infinity;
end;
procedure exit(status: integer); external msvcrt name 'exit';
{$ELSE}
function _fabs(v: double): double; cdecl; inline;
begin
result := System.Abs(v);
end;
function __Sinx(const x: double; n: cardinal; m: integer): double; cdecl; inline;
begin
result := _sinx_impl(x,n,m);
end;
function __Inf(): Double; cdecl; inline;
begin
Result := Math.Infinity;
end;
function __Log(x: double): double; cdecl; inline;
begin
Result := System.Ln(x);
end;
function __Sinh(v: double): double; cdecl; inline;
begin
Result := Math.Sinh(v);
end;
function __Cosh(v: double): double; cdecl; inline;
begin
Result := Math.Cosh(v);
end;
function __FNan(): single; cdecl; inline;
begin
Result := Math.NaN;
end;
function _ldexp(const x: Double; const p: integer): double; cdecl; inline;
begin
Result := Math.Ldexp(x,p);
end;
{$ENDIF}
{$ENDIF}
//------------------------------------------------
// helper functions
function CStringPointerToString(Value: MarshaledAString): string;
begin
Result := TMarshal.ReadStringAsAnsi(TPtrWrapper.Create(Value));
end;
function StringToCStringPointer(const Value: string): Pointer;
var
m: TMarshaller;
begin
Result := m.AsAnsi(Value).ToPointer;
end;
//------------------------------------------------
procedure _default_stderr_log_handler(appdata: Pointer; level: Integer; msg: Pointer); cdecl;
var
MsgText: string;
function LogLevelCodeToString(value: Integer): string;
begin
Result := '';
case value of
1: Result := 'libPROJ error: ';
2: Result := 'libPROJ debug: ';
3: Result := 'libPROJ trace: ';
4: Result := 'libPROJ tell: ';
end;
end;
begin
MsgText := CStringPointerToString(msg);
if MsgText <> '' then
begin
MsgText := LogLevelCodeToString(level) + MsgText;
{$IFDEF MSWINDOWS}
if IsConsole then
Writeln( MsgText )
else
OutputDebugString( PChar( MsgText ));
{$ENDIF}
end;
end;
function PJ_init_plus(const def: string): TProjPJ;
var
ctx: TProjCtx;
m: TMarshaller;
begin
Result := nil;
if not Assigned(FDefaultContext) then
begin
ctx := _pj_get_default_ctx;
{$IfOpt D+}
_pj_ctx_set_logger(ctx,@_default_stderr_log_handler);
_pj_ctx_set_debug(ctx,4);
_pj_set_log_level(ctx,4);
_pj_log(ctx,4,m.AsAnsi( '"%s"' ).ToPointer,m.AsAnsi('using proj internal context').ToPointer);
{$endif}
end
else
ctx := FDefaultContext;
if ctx <> nil then
begin
{$IfOpt D+}
_pj_log(ctx,3,m.AsAnsi( '"%s"' ).ToPointer,m.AsAnsi(
'create projection for '+def).ToPointer);
{$endif}
Result := _pj_init_plus_ctx(ctx, m.AsAnsi( def ).ToPointer );
{$IfOpt D+}
if Result = nil then
begin
_pj_log(ctx,3,m.AsAnsi( '"%s"' ).ToPointer,m.AsAnsi(
'projection for '+def+
' failed witn '+ _pj_context_errno(ctx).ToString + ' code').ToPointer);
end
else
_pj_log(ctx,3,m.AsAnsi( '"%s"' ).ToPointer,m.AsAnsi(
'projection for '+def+' created').ToPointer);
{$endif}
end;
end;
function PJ_is_geographic(p: TProjPJ): Boolean;
begin
Result := Boolean(_pj_is_latlong(p));
end;
function PJ_is_geocentric(p: TProjPJ): Boolean;
begin
Result := Boolean(_pj_is_geocent(p));
end;
function PJ_latlong_from_proj(p: TProjPJ): TProjPJ;
begin
Result := _pj_latlong_from_proj(p);
end;
function PJ_get_version_string(): string;
begin
Result := 'proj ' + CStringPointerToString(_pj_get_release());
end;
function PJ_strerrno(errno: integer): string;
begin
Result := CStringPointerToString(_pj_strerrno(errno));
end;
function PJ_get_spheroid_defn(p: TProjPJ; out major_axis,
eccentricity_squared: Double): Boolean;
begin
Result := PJ_is_valid(p);// Assigned(p);
if Result then
_pj_get_spheroid_defn(p,@major_axis,@eccentricity_squared);
end;
function PJ_get_errno(): Integer;
begin
Result := _pj_get_errno_ref()^;
end;
function PJ_transform_points2D(src, dst: TProjPJ; x, y: PDouble; count:
Integer; angular: Boolean): Integer;
var
degSrc, degDst: Boolean;
i: Integer;
_x,_y, z: PDouble;
begin
Result := -1;
if PJ_is_valid(src) and PJ_is_valid(dst) then
begin
Result := PJ_is_same_definition(src,dst);
// projections differs
if Result = 0 then //
begin
if not angular then
begin
degSrc := PJ_is_geographic(src);
degDst := PJ_is_geographic(dst);
end
else
begin
degSrc := False;
degDst := False;
end;
if degSrc then
begin
_x := x;
_y := y;
for i := 0 to count -1 do
begin
_x^ := _pj_torad(x^); // PJ_DEG_TO_RAD * _x^;
_y^ := _pj_torad(_y^); // PJ_DEG_TO_RAD * _y^;
Inc(_x);
Inc(_y);
end;
end;
z := nil;
Result := _pj_transform(src,dst,count,1,x,y,z);
if Result = 0 then
begin
if degDst then
begin
_x := x;
_y := y;
for i := 0 to count -1 do
begin
_x^ := _pj_todeg(_x^); // PJ_RAD_TO_DEG * _x^;
_y^ := _pj_todeg(_y^); // PJ_RAD_TO_DEG * _y^;
Inc(_x);
Inc(_y);
end;
end;
end;
end
end;
end;
function PJ_transform_point2D(src, dst: TProjPJ; x, y: PDouble; angular:
Boolean): Integer;
begin
Result := PJ_transform_points2D(src,dst,x,y,1,angular);
end;
function PJ_transform_point2D(src, dst: TProjPJ; var x, y: Double; angular:
Boolean): Integer;
begin
Result := PJ_transform_point2D(src,dst,@x,@y,angular);
end;
function PJ_get_definition(p: TProjPJ): string;
var
d: Pointer;
begin
d := _pj_get_def(p);
if d <> nil then
begin
Result := CStringPointerToString( d );
FreeMem( d );
end
end;
function PJ_is_same_definition(p1, p2: TProjPJ): Integer;
var d1,d2: string;
begin
Result := -2;
if PJ_is_valid(p1) and PJ_is_valid(p2) then
begin
Result := -1;
d1 := PJ_get_definition(p1);
d2 := PJ_get_definition(p2);
if (d1 <> '') and (d2 <> '') then
Result := Integer(SameText(d1,d2))
end;
end;
function PJ_is_valid(p: TProjPJ): Boolean;
begin
Result := Assigned(p);
end;
procedure PJ_free(var p: TProjPJ);
begin
if PJ_is_valid(p) then
begin
_pj_free(p);
p := nil;
end;
end;
initialization
FDefaultContext := _pj_ctx_alloc();
if Assigned(FDefaultContext) then
begin
_pj_ctx_set_logger(FDefaultContext,@_default_stderr_log_handler);
{$IfOpt D+}
_pj_ctx_set_debug(FDefaultContext,4);
_pj_set_log_level(FDefaultContext,4);
{$endif}
end;
finalization
if Assigned(FDefaultContext) then
begin
_pj_ctx_free(FDefaultContext);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Restore;
interface
uses
VSoft.CancellationToken,
DPM.Core.Configuration.Interfaces,
DPM.Core.Logging,
DPM.Core.Package.Interfaces,
DPM.Console.ExitCodes,
DPM.Console.Command.Base,
DPM.Core.Package.Installer.Interfaces;
type
TRestoreCommand = class(TBaseCommand)
private
FPackageInstaller : IPackageInstaller;
FContext : IPackageInstallerContext;
protected
function Execute(const cancellationToken : ICancellationToken) : TExitCode;override;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager; const packageInstaller : IPackageInstaller; const context : IPackageInstallerContext);reintroduce;
end;
implementation
uses
System.SysUtils,
DPM.Core.Types,
DPM.Core.Options.Common,
DPM.Core.Options.Restore;
{ TRestoreCommand }
constructor TRestoreCommand.Create(const logger: ILogger; const configurationManager: IConfigurationManager; const packageInstaller: IPackageInstaller; const context : IPackageInstallerContext);
begin
inherited Create(logger, configurationManager);
FPackageInstaller := packageInstaller;
FContext := context;
end;
function TRestoreCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode;
begin
TRestoreOptions.Default.ApplyCommon(TCommonOptions.Default);
//project path - if it's empty, specify the current directory
//do this before validation!
if TRestoreOptions.Default.ProjectPath = '' then
TRestoreOptions.Default.ProjectPath := GetCurrentDir;
if not TRestoreOptions.Default.Validate(Logger) then
begin
result := TExitCode.InvalidArguments;
exit;
end;
if not FPackageInstaller.Restore(cancellationToken, TRestoreOptions.Default, FContext) then
result := TExitCode.Error
else
result := TExitCode.OK;
end;
end.
|
unit intTask;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
System.Classes,
Vcl.Graphics,
Vcl.OleServer,
System.Variants,
System.Win.StdVCL;
const
LIBID_TaskScheduler: TGUID = '{E34CB9F1-C7F7-424C-BE29-027DCC09363A}';
IID_ITaskFolderCollection: TGUID = '{79184A66-8664-423F-97F1-637356A5D812}';
IID_ITaskFolder: TGUID = '{8CFAC062-A080-4C15-9A88-AA7C2AF80DFC}';
IID_IRegisteredTask: TGUID = '{9C86F320-DEE3-4DD1-B972-A303F26B061E}';
IID_IRunningTask: TGUID = '{653758FB-7B9A-4F1E-A471-BEEB8E9B834E}';
IID_IRunningTaskCollection: TGUID = '{6A67614B-6828-4FEC-AA54-6D52E8F1F2DB}';
IID_ITaskDefinition: TGUID = '{F5BC8FC5-536D-4F77-B852-FBC1356FDEB6}';
IID_IRegistrationInfo: TGUID = '{416D8B73-CB41-4EA1-805C-9BE9A5AC4A74}';
IID_ITriggerCollection: TGUID = '{85DF5081-1B24-4F32-878A-D9D14DF4CB77}';
IID_ITrigger: TGUID = '{09941815-EA89-4B5B-89E0-2A773801FAC3}';
IID_IRepetitionPattern: TGUID = '{7FB9ACF1-26BE-400E-85B5-294B9C75DFD6}';
IID_ITaskSettings: TGUID = '{8FD4711D-2D02-4C8C-87E3-EFF699DE127E}';
IID_IIdleSettings: TGUID = '{84594461-0053-4342-A8FD-088FABF11F32}';
IID_INetworkSettings: TGUID = '{9F7DEA84-C30B-4245-80B6-00E9F646F1B4}';
IID_IPrincipal: TGUID = '{D98D51E5-C9B4-496A-A9C1-18980261CF0F}';
IID_IActionCollection: TGUID = '{02820E19-7B98-4ED2-B2E8-FDCCCEFF619B}';
IID_IAction: TGUID = '{BAE54997-48B1-4CBE-9965-D6BE263EBEA4}';
IID_IRegisteredTaskCollection: TGUID = '{86627EB4-42A7-41E4-A4D9-AC33A72F2D52}';
IID_ITaskService: TGUID = '{2FABA4C7-4DA9-4013-9697-20CC3FD40F85}';
IID_ITaskHandler: TGUID = '{839D7762-5121-4009-9234-4F0D19394F04}';
IID_ITaskHandlerStatus: TGUID = '{EAEC7A8F-27A0-4DDC-8675-14726A01A38A}';
IID_ITaskVariables: TGUID = '{3E4C9351-D966-4B8B-BB87-CEBA68BB0107}';
IID_ITaskNamedValuePair: TGUID = '{39038068-2B46-4AFD-8662-7BB6F868D221}';
IID_ITaskNamedValueCollection: TGUID = '{B4EF826B-63C3-46E4-A504-EF69E4F7EA4D}';
IID_IIdleTrigger: TGUID = '{D537D2B0-9FB3-4D34-9739-1FF5CE7B1EF3}';
IID_ILogonTrigger: TGUID = '{72DADE38-FAE4-4B3E-BAF4-5D009AF02B1C}';
IID_ISessionStateChangeTrigger: TGUID = '{754DA71B-4385-4475-9DD9-598294FA3641}';
IID_IEventTrigger: TGUID = '{D45B0167-9653-4EEF-B94F-0732CA7AF251}';
IID_ITimeTrigger: TGUID = '{B45747E0-EBA7-4276-9F29-85C5BB300006}';
IID_IDailyTrigger: TGUID = '{126C5CD8-B288-41D5-8DBF-E491446ADC5C}';
IID_IWeeklyTrigger: TGUID = '{5038FC98-82FF-436D-8728-A512A57C9DC1}';
IID_IMonthlyTrigger: TGUID = '{97C45EF1-6B02-4A1A-9C0E-1EBFBA1500AC}';
IID_IMonthlyDOWTrigger: TGUID = '{77D025A3-90FA-43AA-B52E-CDA5499B946A}';
IID_IBootTrigger: TGUID = '{2A9C35DA-D357-41F4-BBC1-207AC1B1F3CB}';
IID_IRegistrationTrigger: TGUID = '{4C8FEC3A-C218-4E0C-B23D-629024DB91A2}';
IID_IExecAction: TGUID = '{4C3D624D-FD6B-49A3-B9B7-09CB3CD3F047}';
IID_IShowMessageAction: TGUID = '{505E9E68-AF89-46B8-A30F-56162A83D537}';
IID_IComHandlerAction: TGUID = '{6D2FD252-75C5-4F66-90BA-2A7D8CC3039F}';
IID_IEmailAction: TGUID = '{10F62C64-7E16-4314-A0C2-0C3683F99D40}';
CLASS_TaskScheduler_: TGUID = '{0F87369F-A4E5-4CFC-BD3E-73E6154572DD}';
CLASS_TaskHandlerPS: TGUID = '{F2A69DB7-DA2C-4352-9066-86FEE6DACAC9}';
CLASS_TaskHandlerStatusPS: TGUID = '{9F15266D-D7BA-48F0-93C1-E6895F6FE5AC}';
type
_TASK_STATE = TOleEnum;
const
TASK_STATE_UNKNOWN = $00;
TASK_STATE_DISABLED = $01;
TASK_STATE_QUEUED = $02;
TASK_STATE_READY = $03;
TASK_STATE_RUNNING = $04;
type
_TASK_TRIGGER_TYPE2 = TOleEnum;
const
TASK_TRIGGER_EVENT = $00;
TASK_TRIGGER_TIME = $01;
TASK_TRIGGER_DAILY = $02;
TASK_TRIGGER_WEEKLY = $03;
TASK_TRIGGER_MONTHLY = $04;
TASK_TRIGGER_MONTHLYDOW = $05;
TASK_TRIGGER_IDLE = $06;
TASK_TRIGGER_REGISTRATION = $07;
TASK_TRIGGER_BOOT = $08;
TASK_TRIGGER_LOGON = $09;
TASK_TRIGGER_SESSION_STATE_CHANGE = $0B;
type
_TASK_INSTANCES_POLICY = TOleEnum;
const
TASK_INSTANCES_PARALLEL = $00;
TASK_INSTANCES_QUEUE = $01;
TASK_INSTANCES_IGNORE_NEW = $02;
TASK_INSTANCES_STOP_EXISTING = $03;
type
_TASK_COMPATIBILITY = TOleEnum;
const
TASK_COMPATIBILITY_AT = $00;
TASK_COMPATIBILITY_V1 = $01;
TASK_COMPATIBILITY_V2 = $02;
type
_TASK_LOGON_TYPE = TOleEnum;
const
TASK_LOGON_NONE = $00;
TASK_LOGON_PASSWORD = $01;
TASK_LOGON_S4U = $02;
TASK_LOGON_INTERACTIVE_TOKEN = $03;
TASK_LOGON_GROUP = $04;
TASK_LOGON_SERVICE_ACCOUNT = $05;
TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD = $06;
type
_TASK_RUNLEVEL = TOleEnum;
const
TASK_RUNLEVEL_LUA = $00;
TASK_RUNLEVEL_HIGHEST = $01;
type
_TASK_ACTION_TYPE = TOleEnum;
const
TASK_ACTION_EXEC = $00;
TASK_ACTION_COM_HANDLER = $05;
TASK_ACTION_SEND_EMAIL = $06;
TASK_ACTION_SHOW_MESSAGE = $07;
type
_TASK_SESSION_STATE_CHANGE_TYPE = TOleEnum;
const
TASK_CONSOLE_CONNECT = $01;
TASK_CONSOLE_DISCONNECT = $02;
TASK_REMOTE_CONNECT = $03;
TASK_REMOTE_DISCONNECT = $04;
TASK_SESSION_LOCK = $07;
TASK_SESSION_UNLOCK = $08;
type
_TASK_RUN_FLAGS = TOleEnum;
const
TASK_RUN_NO_FLAGS = $00;
TASK_RUN_AS_SELF = $01;
TASK_RUN_IGNORE_CONSTRAINTS = $02;
TASK_RUN_USE_SESSION_ID = $04;
TASK_RUN_USER_SID = $08;
type
_TASK_ENUM_FLAGS = TOleEnum;
const
TASK_ENUM_HIDDEN = $01;
type
_TASK_CREATION = TOleEnum;
const
TASK_VALIDATE_ONLY = $01;
TASK_CREATE = $02;
TASK_UPDATE = $04;
TASK_CREATE_OR_UPDATE = $06;
TASK_DISABLE = $08;
TASK_DONT_ADD_PRINCIPAL_ACE = $10;
TASK_IGNORE_REGISTRATION_TRIGGERS = $20;
type
ITaskFolder = interface;
IRunningTaskCollection = interface;
ITaskDefinition = interface;
IRegisteredTask = interface;
IRegisteredTaskCollection = interface;
IRunningTask = interface;
IRegistrationInfo = interface;
ITriggerCollection = interface;
ITaskSettings = interface;
IPrincipal = interface;
IActionCollection = interface;
ITrigger = interface;
IRepetitionPattern = interface;
IIdleSettings = interface;
INetworkSettings = interface;
IAction = interface;
TaskScheduler2 = interface (IDispatch)
['{2FABA4C7-4DA9-4013-9697-20CC3FD40F85}']
function GetFolder(const Path: WideString): ITaskFolder safecall;
function GetRunningTasks(flags: Integer): IRunningTaskCollection
safecall;
function NewTask(flags: LongWord): ITaskDefinition safecall;
procedure Connect(serverName: OleVariant; user: OleVariant;
domain: OleVariant; password: OleVariant) safecall;
function Get_Connected: WordBool safecall;
function Get_TargetServer: WideString safecall;
function Get_ConnectedUser: WideString safecall;
function Get_ConnectedDomain: WideString safecall;
function Get_HighestVersion: LongWord safecall;
property Connected:WordBool read Get_Connected;
property TargetServer:WideString read Get_TargetServer;
property ConnectedUser:WideString read Get_ConnectedUser;
property ConnectedDomain:WideString read Get_ConnectedDomain;
property HighestVersion:LongWord read Get_HighestVersion;
end;
TaskHandlerPS = interface (IUnknown)
['{839D7762-5121-4009-9234-4F0D19394F04}']
function Start(const pHandlerServices: IUnknown;
const Data: WideString): HRESULT stdcall;
function Stop(var pRetCode: HRESULT): HRESULT stdcall;
function Pause: HRESULT stdcall;
function Resume: HRESULT stdcall;
end;
TaskHandlerStatusPS = interface (IUnknown)
['{EAEC7A8F-27A0-4DDC-8675-14726A01A38A}']
function UpdateStatus(percentComplete: SmallInt;
const statusMessage: WideString): HRESULT stdcall;
function TaskCompleted(taskErrCode: HRESULT): HRESULT stdcall;
end;
PUserType1 = ^_SYSTEMTIME;
ITaskFolderCollection = interface (IDispatch)
['{79184A66-8664-423F-97F1-637356A5D812}']
function Get_Count: Integer safecall;
function Get_Item(index: OleVariant): ITaskFolder safecall;
function Get__NewEnum: IUnknown safecall;
property Count:Integer read Get_Count;
property Item[index: OleVariant]: ITaskFolder read Get_Item; default;
property _NewEnum: IUnknown read Get__NewEnum;
end;
ITaskFolderCollectionDisp = dispinterface
['{79184A66-8664-423F-97F1-637356A5D812}']
{published}
property Count: Integer readonly dispid $60020000;
property Item: ITaskFolder readonly dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
end platform;
ITaskFolder = interface (IDispatch)
['{8CFAC062-A080-4C15-9A88-AA7C2AF80DFC}']
function Get_Name: WideString safecall;
function Get_Path: WideString safecall;
function GetFolder(const Path: WideString): ITaskFolder safecall;
function GetFolders(flags: Integer): ITaskFolderCollection safecall;
function CreateFolder(const subFolderName: WideString;
sddl: OleVariant): ITaskFolder safecall;
procedure DeleteFolder(const subFolderName: WideString; flags: Integer)
safecall;
function GetTask(const Path: WideString): IRegisteredTask safecall;
function GetTasks(flags: Integer): IRegisteredTaskCollection safecall;
procedure DeleteTask(const Name: WideString; flags: Integer) safecall;
function RegisterTask(const Path: WideString;
const XmlText: WideString; flags: Integer; UserId: OleVariant;
password: OleVariant; LogonType: TOleEnum; sddl: OleVariant):
IRegisteredTask safecall;
function RegisterTaskDefinition(const Path: WideString;
const pDefinition: ITaskDefinition; flags: Integer;
UserId: OleVariant; password: OleVariant; LogonType: TOleEnum;
sddl: OleVariant): IRegisteredTask safecall;
function GetSecurityDescriptor(securityInformation: Integer):
WideString safecall;
procedure SetSecurityDescriptor(const sddl: WideString; flags: Integer)
safecall;
property Name:WideString read Get_Name;
property Path:WideString read Get_Path;
end;
ITaskFolderDisp = dispinterface
['{8CFAC062-A080-4C15-9A88-AA7C2AF80DFC}']
{published}
property Name: WideString readonly dispid $1;
property Path: WideString readonly dispid $0;
function GetFolder(const Path: WideString): ITaskFolder;
function GetFolders(flags: Integer): ITaskFolderCollection;
function CreateFolder(const subFolderName: WideString;
sddl: OleVariant): ITaskFolder;
procedure DeleteFolder(const subFolderName: WideString;
flags: Integer);
function GetTask(const Path: WideString): IRegisteredTask;
function GetTasks(flags: Integer): IRegisteredTaskCollection;
procedure DeleteTask(const Name: WideString; flags: Integer);
function RegisterTask(const Path: WideString;
const XmlText: WideString; flags: Integer; UserId: OleVariant;
password: OleVariant; LogonType: TOleEnum; sddl: OleVariant):
IRegisteredTask;
function RegisterTaskDefinition(const Path: WideString;
const pDefinition: ITaskDefinition; flags: Integer;
UserId: OleVariant; password: OleVariant; LogonType: TOleEnum;
sddl: OleVariant): IRegisteredTask;
function GetSecurityDescriptor(securityInformation: Integer):
WideString;
procedure SetSecurityDescriptor(const sddl: WideString;
flags: Integer);
end platform;
IRegisteredTask = interface (IDispatch)
['{9C86F320-DEE3-4DD1-B972-A303F26B061E}']
function Get_Name: WideString safecall;
function Get_Path: WideString safecall;
function Get_State: TOleEnum safecall;
function Get_Enabled: WordBool safecall;
procedure Set_Enabled(pEnabled: WordBool) safecall;
function Run(params: OleVariant): IRunningTask safecall;
function RunEx(params: OleVariant; flags: Integer; sessionID: Integer;
const user: WideString): IRunningTask safecall;
function GetInstances(flags: Integer): IRunningTaskCollection safecall;
function Get_LastRunTime: TDateTime safecall;
function Get_LastTaskResult: Integer safecall;
function Get_NumberOfMissedRuns: Integer safecall;
function Get_NextRunTime: TDateTime safecall;
function Get_Definition: ITaskDefinition safecall;
function Get_Xml: WideString safecall;
function GetSecurityDescriptor(securityInformation: Integer):
WideString safecall;
procedure SetSecurityDescriptor(const sddl: WideString; flags: Integer)
safecall;
procedure Stop(flags: Integer) safecall;
procedure GetRunTimes(var pstStart: _SYSTEMTIME;
var pstEnd: _SYSTEMTIME; var pCount: LongWord;
var pRunTimes: PUserType1) safecall;
property Name:WideString read Get_Name;
property Path:WideString read Get_Path;
property State:TOleEnum read Get_State;
property Enabled:WordBool read Get_Enabled write Set_Enabled;
property LastRunTime:TDateTime read Get_LastRunTime;
property LastTaskResult:Integer read Get_LastTaskResult;
property NumberOfMissedRuns:Integer read Get_NumberOfMissedRuns;
property NextRunTime:TDateTime read Get_NextRunTime;
property Definition:ITaskDefinition read Get_Definition;
property Xml:WideString read Get_Xml;
end;
IRegisteredTaskDisp = dispinterface
['{9C86F320-DEE3-4DD1-B972-A303F26B061E}']
{published}
property Name: WideString readonly dispid $1;
property Path: WideString readonly dispid $0;
property State: TOleEnum readonly dispid $2;
property Enabled: WordBool dispid $3;
function Run(params: OleVariant): IRunningTask;
function RunEx(params: OleVariant; flags: Integer; sessionID: Integer;
const user: WideString): IRunningTask;
function GetInstances(flags: Integer): IRunningTaskCollection;
property LastRunTime: TDateTime readonly dispid $8;
property LastTaskResult: Integer readonly dispid $9;
property NumberOfMissedRuns: Integer readonly dispid $B;
property NextRunTime: TDateTime readonly dispid $C;
property Definition: ITaskDefinition readonly dispid $D;
property Xml: WideString readonly dispid $E;
function GetSecurityDescriptor(securityInformation: Integer):
WideString;
procedure SetSecurityDescriptor(const sddl: WideString;
flags: Integer);
procedure Stop(flags: Integer);
procedure GetRunTimes(var pstStart: OleVariant; var pstEnd: OleVariant;
var pCount: LongWord; var pRunTimes: OleVariant);
end platform;
IRunningTask = interface (IDispatch)
['{653758FB-7B9A-4F1E-A471-BEEB8E9B834E}']
function Get_Name: WideString safecall;
function Get_InstanceGuid: WideString safecall;
function Get_Path: WideString safecall;
function Get_State: TOleEnum safecall;
function Get_CurrentAction: WideString safecall;
procedure Stop safecall;
procedure Refresh safecall;
function Get_EnginePID: LongWord safecall;
property Name:WideString read Get_Name;
property InstanceGuid:WideString read Get_InstanceGuid;
property Path:WideString read Get_Path;
property State:TOleEnum read Get_State;
property CurrentAction:WideString read Get_CurrentAction;
property EnginePID:LongWord read Get_EnginePID;
end;
IRunningTaskDisp = dispinterface
['{653758FB-7B9A-4F1E-A471-BEEB8E9B834E}']
{published}
property Name: WideString readonly dispid $1;
property InstanceGuid: WideString readonly dispid $0;
property Path: WideString readonly dispid $2;
property State: TOleEnum readonly dispid $3;
property CurrentAction: WideString readonly dispid $4;
procedure Stop;
procedure Refresh;
property EnginePID: LongWord readonly dispid $7;
end platform;
IRunningTaskCollection = interface (IDispatch)
['{6A67614B-6828-4FEC-AA54-6D52E8F1F2DB}']
function Get_Count: Integer safecall;
function Get_Item(index: OleVariant): IRunningTask safecall;
function Get__NewEnum: IUnknown safecall;
property Count: Integer read Get_Count;
property Item[index: OleVariant]: IRunningTask read Get_Item; default;
property _NewEnum:IUnknown read Get__NewEnum;
end;
IRunningTaskCollectionDisp = dispinterface
['{6A67614B-6828-4FEC-AA54-6D52E8F1F2DB}']
{published}
property Count: Integer readonly dispid $1;
property Item: IRunningTask readonly dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
end platform;
ITaskDefinition = interface (IDispatch)
['{F5BC8FC5-536D-4F77-B852-FBC1356FDEB6}']
function Get_RegistrationInfo: IRegistrationInfo safecall;
procedure Set_RegistrationInfo(const ppRegistrationInfo: IRegistrationInfo)
safecall;
function Get_Triggers: ITriggerCollection safecall;
procedure Set_Triggers(const ppTriggers: ITriggerCollection) safecall;
function Get_Settings: ITaskSettings safecall;
procedure Set_Settings(const ppSettings: ITaskSettings) safecall;
function Get_Data: WideString safecall;
procedure Set_Data(const pData: WideString) safecall;
function Get_Principal: IPrincipal safecall;
procedure Set_Principal(const ppPrincipal: IPrincipal) safecall;
function Get_Actions: IActionCollection safecall;
procedure Set_Actions(const ppActions: IActionCollection) safecall;
function Get_XmlText: WideString safecall;
procedure Set_XmlText(const pXml: WideString) safecall;
property RegistrationInfo:IRegistrationInfo read Get_RegistrationInfo
write Set_RegistrationInfo;
property Triggers:ITriggerCollection read Get_Triggers
write Set_Triggers;
property Settings:ITaskSettings read Get_Settings write Set_Settings;
property Data:WideString read Get_Data write Set_Data;
property Principal:IPrincipal read Get_Principal write Set_Principal;
property Actions:IActionCollection read Get_Actions write Set_Actions;
property XmlText:WideString read Get_XmlText write Set_XmlText;
end;
ITaskDefinitionDisp = dispinterface
['{F5BC8FC5-536D-4F77-B852-FBC1356FDEB6}']
{published}
property RegistrationInfo: IRegistrationInfo dispid $1;
property Triggers: ITriggerCollection dispid $2;
property Settings: ITaskSettings dispid $7;
property Data: WideString dispid $B;
property Principal: IPrincipal dispid $C;
property Actions: IActionCollection dispid $D;
property XmlText: WideString dispid $E;
end platform;
IRegistrationInfo = interface (IDispatch)
['{416D8B73-CB41-4EA1-805C-9BE9A5AC4A74}']
function Get_Description: WideString safecall;
procedure Set_Description(const pDescription: WideString) safecall;
function Get_Author: WideString safecall;
procedure Set_Author(const pAuthor: WideString) safecall;
function Get_Version: WideString safecall;
procedure Set_Version(const pVersion: WideString) safecall;
function Get_Date: WideString safecall;
procedure Set_Date(const pDate: WideString) safecall;
function Get_Documentation: WideString safecall;
procedure Set_Documentation(const pDocumentation: WideString) safecall;
function Get_XmlText: WideString safecall;
procedure Set_XmlText(const pText: WideString) safecall;
function Get_URI: WideString safecall;
procedure Set_URI(const pUri: WideString) safecall;
function Get_SecurityDescriptor: OleVariant safecall;
procedure Set_SecurityDescriptor(pSddl: OleVariant) safecall;
function Get_Source: WideString safecall;
procedure Set_Source(const pSource: WideString) safecall;
property Description:WideString read Get_Description
write Set_Description;
property Author:WideString read Get_Author write Set_Author;
property Version:WideString read Get_Version write Set_Version;
property Date:WideString read Get_Date write Set_Date;
property Documentation:WideString read Get_Documentation
write Set_Documentation;
property XmlText:WideString read Get_XmlText write Set_XmlText;
property URI:WideString read Get_URI write Set_URI;
property SecurityDescriptor:OleVariant read Get_SecurityDescriptor
write Set_SecurityDescriptor;
property Source:WideString read Get_Source write Set_Source;
end;
IRegistrationInfoDisp = dispinterface
['{416D8B73-CB41-4EA1-805C-9BE9A5AC4A74}']
{published}
property Description: WideString dispid $1;
property Author: WideString dispid $2;
property Version: WideString dispid $4;
property Date: WideString dispid $5;
property Documentation: WideString dispid $6;
property XmlText: WideString dispid $9;
property URI: WideString dispid $A;
property SecurityDescriptor: OleVariant dispid $B;
property Source: WideString dispid $C;
end platform;
ITriggerCollection = interface (IDispatch)
['{85DF5081-1B24-4F32-878A-D9D14DF4CB77}']
function Get_Count: Integer safecall;
function Get_Item(index: Integer): ITrigger safecall;
function Get__NewEnum: IUnknown safecall;
function Create(Type_: TOleEnum): ITrigger safecall;
procedure Remove(index: OleVariant) safecall;
procedure Clear safecall;
property Count:Integer read Get_Count;
property Item[index: Integer]: ITrigger read Get_Item; default;
property _NewEnum:IUnknown read Get__NewEnum;
end;
ITriggerCollectionDisp = dispinterface
['{85DF5081-1B24-4F32-878A-D9D14DF4CB77}']
{published}
property Count: Integer readonly dispid $1;
property Item: ITrigger readonly dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
function Create(Type_: TOleEnum): ITrigger;
procedure Remove(index: OleVariant);
procedure Clear;
end platform;
ITrigger = interface (IDispatch)
['{09941815-EA89-4B5B-89E0-2A773801FAC3}']
function Get_type_: TOleEnum safecall;
function Get_Id: WideString safecall;
procedure Set_Id(const pId: WideString) safecall;
function Get_Repetition: IRepetitionPattern safecall;
procedure Set_Repetition(const ppRepeat: IRepetitionPattern) safecall;
function Get_ExecutionTimeLimit: WideString safecall;
procedure Set_ExecutionTimeLimit(const pTimeLimit: WideString)
safecall;
function Get_StartBoundary: WideString safecall;
procedure Set_StartBoundary(const pStart: WideString) safecall;
function Get_EndBoundary: WideString safecall;
procedure Set_EndBoundary(const pEnd: WideString) safecall;
function Get_Enabled: WordBool safecall;
procedure Set_Enabled(pEnabled: WordBool) safecall;
property type_:TOleEnum read Get_type_;
property Id:WideString read Get_Id write Set_Id;
property Repetition:IRepetitionPattern read Get_Repetition
write Set_Repetition;
property ExecutionTimeLimit:WideString read Get_ExecutionTimeLimit
write Set_ExecutionTimeLimit;
property StartBoundary:WideString read Get_StartBoundary
write Set_StartBoundary;
property EndBoundary:WideString read Get_EndBoundary
write Set_EndBoundary;
property Enabled:WordBool read Get_Enabled write Set_Enabled;
end;
ITriggerDisp = dispinterface
['{09941815-EA89-4B5B-89E0-2A773801FAC3}']
{published}
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IRepetitionPattern = interface (IDispatch)
['{7FB9ACF1-26BE-400E-85B5-294B9C75DFD6}']
function Get_Interval: WideString safecall;
procedure Set_Interval(const pInterval: WideString) safecall;
function Get_Duration: WideString safecall;
procedure Set_Duration(const pDuration: WideString) safecall;
function Get_StopAtDurationEnd: WordBool safecall;
procedure Set_StopAtDurationEnd(pStop: WordBool) safecall;
property Interval:WideString read Get_Interval write Set_Interval;
property Duration:WideString read Get_Duration write Set_Duration;
property StopAtDurationEnd:WordBool read Get_StopAtDurationEnd
write Set_StopAtDurationEnd;
end;
IRepetitionPatternDisp = dispinterface
['{7FB9ACF1-26BE-400E-85B5-294B9C75DFD6}']
{published}
property Interval: WideString dispid $1;
property Duration: WideString dispid $2;
property StopAtDurationEnd: WordBool dispid $3;
end platform;
ITaskSettings = interface (IDispatch)
['{8FD4711D-2D02-4C8C-87E3-EFF699DE127E}']
function Get_AllowDemandStart: WordBool safecall;
procedure Set_AllowDemandStart(pAllowDemandStart: WordBool) safecall;
function Get_RestartInterval: WideString safecall;
procedure Set_RestartInterval(const pRestartInterval: WideString)
safecall;
function Get_RestartCount: SYSINT safecall;
procedure Set_RestartCount(pRestartCount: SYSINT) safecall;
function Get_MultipleInstances: TOleEnum safecall;
procedure Set_MultipleInstances(pPolicy: TOleEnum) safecall;
function Get_StopIfGoingOnBatteries: WordBool safecall;
procedure Set_StopIfGoingOnBatteries(pStopIfOnBatteries: WordBool)
safecall;
function Get_DisallowStartIfOnBatteries: WordBool safecall;
procedure Set_DisallowStartIfOnBatteries(pDisallowStart: WordBool)
safecall;
function Get_AllowHardTerminate: WordBool safecall;
procedure Set_AllowHardTerminate(pAllowHardTerminate: WordBool)
safecall;
function Get_StartWhenAvailable: WordBool safecall;
procedure Set_StartWhenAvailable(pStartWhenAvailable: WordBool)
safecall;
function Get_XmlText: WideString safecall;
procedure Set_XmlText(const pText: WideString) safecall;
function Get_RunOnlyIfNetworkAvailable: WordBool safecall;
procedure Set_RunOnlyIfNetworkAvailable(pRunOnlyIfNetworkAvailable: WordBool)
safecall;
function Get_ExecutionTimeLimit: WideString safecall;
procedure Set_ExecutionTimeLimit(const pExecutionTimeLimit: WideString)
safecall;
function Get_Enabled: WordBool safecall;
procedure Set_Enabled(pEnabled: WordBool) safecall;
function Get_DeleteExpiredTaskAfter: WideString safecall;
procedure Set_DeleteExpiredTaskAfter(const pExpirationDelay: WideString)
safecall;
function Get_Priority: SYSINT safecall;
procedure Set_Priority(pPriority: SYSINT) safecall;
function Get_Compatibility: TOleEnum safecall;
procedure Set_Compatibility(pCompatLevel: TOleEnum) safecall;
function Get_Hidden: WordBool safecall;
procedure Set_Hidden(pHidden: WordBool) safecall;
function Get_IdleSettings: IIdleSettings safecall;
procedure Set_IdleSettings(const ppIdleSettings: IIdleSettings)
safecall;
function Get_RunOnlyIfIdle: WordBool safecall;
procedure Set_RunOnlyIfIdle(pRunOnlyIfIdle: WordBool) safecall;
function Get_WakeToRun: WordBool safecall;
procedure Set_WakeToRun(pWake: WordBool) safecall;
function Get_NetworkSettings: INetworkSettings safecall;
procedure Set_NetworkSettings(const ppNetworkSettings: INetworkSettings)
safecall;
property AllowDemandStart:WordBool read Get_AllowDemandStart
write Set_AllowDemandStart;
property RestartInterval:WideString read Get_RestartInterval
write Set_RestartInterval;
property RestartCount:SYSINT read Get_RestartCount
write Set_RestartCount;
property MultipleInstances:TOleEnum read Get_MultipleInstances
write Set_MultipleInstances;
property StopIfGoingOnBatteries:WordBool
read Get_StopIfGoingOnBatteries write Set_StopIfGoingOnBatteries;
property DisallowStartIfOnBatteries:WordBool
read Get_DisallowStartIfOnBatteries
write Set_DisallowStartIfOnBatteries;
property AllowHardTerminate:WordBool read Get_AllowHardTerminate
write Set_AllowHardTerminate;
property StartWhenAvailable:WordBool read Get_StartWhenAvailable
write Set_StartWhenAvailable;
property XmlText:WideString read Get_XmlText write Set_XmlText;
property RunOnlyIfNetworkAvailable:WordBool
read Get_RunOnlyIfNetworkAvailable
write Set_RunOnlyIfNetworkAvailable;
property ExecutionTimeLimit:WideString read Get_ExecutionTimeLimit
write Set_ExecutionTimeLimit;
property Enabled:WordBool read Get_Enabled write Set_Enabled;
property DeleteExpiredTaskAfter:WideString
read Get_DeleteExpiredTaskAfter write Set_DeleteExpiredTaskAfter;
property Priority:SYSINT read Get_Priority write Set_Priority;
property Compatibility:TOleEnum read Get_Compatibility
write Set_Compatibility;
property Hidden:WordBool read Get_Hidden write Set_Hidden;
property IdleSettings:IIdleSettings read Get_IdleSettings
write Set_IdleSettings;
property RunOnlyIfIdle:WordBool read Get_RunOnlyIfIdle
write Set_RunOnlyIfIdle;
property WakeToRun:WordBool read Get_WakeToRun write Set_WakeToRun;
property NetworkSettings:INetworkSettings read Get_NetworkSettings
write Set_NetworkSettings;
end;
ITaskSettingsDisp = dispinterface
['{8FD4711D-2D02-4C8C-87E3-EFF699DE127E}']
{published}
property AllowDemandStart: WordBool dispid $3;
property RestartInterval: WideString dispid $4;
property RestartCount: SYSINT dispid $5;
property MultipleInstances: TOleEnum dispid $6;
property StopIfGoingOnBatteries: WordBool dispid $7;
property DisallowStartIfOnBatteries: WordBool dispid $8;
property AllowHardTerminate: WordBool dispid $9;
property StartWhenAvailable: WordBool dispid $A;
property XmlText: WideString dispid $B;
property RunOnlyIfNetworkAvailable: WordBool dispid $C;
property ExecutionTimeLimit: WideString dispid $D;
property Enabled: WordBool dispid $E;
property DeleteExpiredTaskAfter: WideString dispid $F;
property Priority: SYSINT dispid $10;
property Compatibility: TOleEnum dispid $11;
property Hidden: WordBool dispid $12;
property IdleSettings: IIdleSettings dispid $13;
property RunOnlyIfIdle: WordBool dispid $14;
property WakeToRun: WordBool dispid $15;
property NetworkSettings: INetworkSettings dispid $16;
end platform;
IIdleSettings = interface (IDispatch)
['{84594461-0053-4342-A8FD-088FABF11F32}']
function Get_IdleDuration: WideString safecall;
procedure Set_IdleDuration(const pDelay: WideString) safecall;
function Get_WaitTimeout: WideString safecall;
procedure Set_WaitTimeout(const pTimeout: WideString) safecall;
function Get_StopOnIdleEnd: WordBool safecall;
procedure Set_StopOnIdleEnd(pStop: WordBool) safecall;
function Get_RestartOnIdle: WordBool safecall;
procedure Set_RestartOnIdle(pRestart: WordBool) safecall;
property IdleDuration:WideString read Get_IdleDuration
write Set_IdleDuration;
property WaitTimeout:WideString read Get_WaitTimeout
write Set_WaitTimeout;
property StopOnIdleEnd:WordBool read Get_StopOnIdleEnd
write Set_StopOnIdleEnd;
property RestartOnIdle:WordBool read Get_RestartOnIdle
write Set_RestartOnIdle;
end;
IIdleSettingsDisp = dispinterface
['{84594461-0053-4342-A8FD-088FABF11F32}']
{published}
property IdleDuration: WideString dispid $1;
property WaitTimeout: WideString dispid $2;
property StopOnIdleEnd: WordBool dispid $3;
property RestartOnIdle: WordBool dispid $4;
end platform;
INetworkSettings = interface (IDispatch)
['{9F7DEA84-C30B-4245-80B6-00E9F646F1B4}']
function Get_Name: WideString safecall;
procedure Set_Name(const pName: WideString) safecall;
function Get_Id: WideString safecall;
procedure Set_Id(const pId: WideString) safecall;
property Name:WideString read Get_Name write Set_Name;
property Id:WideString read Get_Id write Set_Id;
end;
INetworkSettingsDisp = dispinterface
['{9F7DEA84-C30B-4245-80B6-00E9F646F1B4}']
{published}
property Name: WideString dispid $1;
property Id: WideString dispid $2;
end platform;
IPrincipal = interface (IDispatch)
['{D98D51E5-C9B4-496A-A9C1-18980261CF0F}']
function Get_Id: WideString safecall;
procedure Set_Id(const pId: WideString) safecall;
function Get_DisplayName: WideString safecall;
procedure Set_DisplayName(const pName: WideString) safecall;
function Get_UserId: WideString safecall;
procedure Set_UserId(const pUser: WideString) safecall;
function Get_LogonType: TOleEnum safecall;
procedure Set_LogonType(pLogon: TOleEnum) safecall;
function Get_GroupId: WideString safecall;
procedure Set_GroupId(const pGroup: WideString) safecall;
function Get_RunLevel: TOleEnum safecall;
procedure Set_RunLevel(pRunLevel: TOleEnum) safecall;
property Id:WideString read Get_Id write Set_Id;
property DisplayName:WideString read Get_DisplayName
write Set_DisplayName;
property UserId:WideString read Get_UserId write Set_UserId;
property LogonType:TOleEnum read Get_LogonType write Set_LogonType;
property GroupId:WideString read Get_GroupId write Set_GroupId;
property RunLevel:TOleEnum read Get_RunLevel write Set_RunLevel;
end;
IPrincipalDisp = dispinterface
['{D98D51E5-C9B4-496A-A9C1-18980261CF0F}']
{published}
property Id: WideString dispid $1;
property DisplayName: WideString dispid $2;
property UserId: WideString dispid $3;
property LogonType: TOleEnum dispid $4;
property GroupId: WideString dispid $5;
property RunLevel: TOleEnum dispid $6;
end platform;
IActionCollection = interface (IDispatch)
['{02820E19-7B98-4ED2-B2E8-FDCCCEFF619B}']
function Get_Count: Integer safecall;
function Get_Item(index: Integer): IAction safecall;
function Get__NewEnum: IUnknown safecall;
function Get_XmlText: WideString safecall;
procedure Set_XmlText(const pText: WideString) safecall;
function Create(Type_: TOleEnum): IAction safecall;
procedure Remove(index: OleVariant) safecall;
procedure Clear safecall;
function Get_Context: WideString safecall;
procedure Set_Context(const pContext: WideString) safecall;
property Count:Integer read Get_Count;
property Item[index: Integer]: IAction read Get_Item; default;
property _NewEnum:IUnknown read Get__NewEnum;
property XmlText:WideString read Get_XmlText write Set_XmlText;
property Context:WideString read Get_Context write Set_Context;
end;
IActionCollectionDisp = dispinterface
['{02820E19-7B98-4ED2-B2E8-FDCCCEFF619B}']
{published}
property Count: Integer readonly dispid $1;
property Item: IAction readonly dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
property XmlText: WideString dispid $2;
function Create(Type_: TOleEnum): IAction;
procedure Remove(index: OleVariant);
procedure Clear;
property Context: WideString dispid $6;
end platform;
IAction = interface (IDispatch)
['{BAE54997-48B1-4CBE-9965-D6BE263EBEA4}']
function Get_Id: WideString safecall;
procedure Set_Id(const pId: WideString) safecall;
function Get_type_: TOleEnum safecall;
property Id:WideString read Get_Id write Set_Id;
property type_:TOleEnum read Get_type_;
end;
IActionDisp = dispinterface
['{BAE54997-48B1-4CBE-9965-D6BE263EBEA4}']
{published}
property Id: WideString dispid $1;
property type_: TOleEnum readonly dispid $2;
end platform;
IRegisteredTaskCollection = interface (IDispatch)
['{86627EB4-42A7-41E4-A4D9-AC33A72F2D52}']
function Get_Count: Integer safecall;
function Get_Item(index: OleVariant): IRegisteredTask safecall;
function Get__NewEnum: IUnknown safecall;
property Count:Integer read Get_Count;
property Item[index: OleVariant]: IRegisteredTask
read Get_Item; default;
property _NewEnum:IUnknown read Get__NewEnum;
end;
IRegisteredTaskCollectionDisp = dispinterface
['{86627EB4-42A7-41E4-A4D9-AC33A72F2D52}']
{published}
property Count: Integer readonly dispid $60020000;
property Item: IRegisteredTask readonly
dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
end platform;
ITaskService = TaskScheduler2;
ITaskServiceDisp = dispinterface
['{2FABA4C7-4DA9-4013-9697-20CC3FD40F85}']
{published}
function GetFolder(const Path: WideString): ITaskFolder;
function GetRunningTasks(flags: Integer): IRunningTaskCollection;
function NewTask(flags: LongWord): ITaskDefinition;
procedure Connect(serverName: OleVariant; user: OleVariant;
domain: OleVariant; password: OleVariant);
property Connected: WordBool readonly dispid $5;
property TargetServer: WideString readonly dispid $0;
property ConnectedUser: WideString readonly dispid $6;
property ConnectedDomain: WideString readonly dispid $7;
property HighestVersion: LongWord readonly dispid $8;
end platform;
ITaskHandler = TaskHandlerPS;
ITaskHandlerStatus = TaskHandlerStatusPS;
ITaskVariables = interface (IUnknown)
['{3E4C9351-D966-4B8B-BB87-CEBA68BB0107}']
function GetInput(var pInput: WideString): HRESULT stdcall;
function SetOutput(const input: WideString): HRESULT stdcall;
function GetContext(var pContext: WideString): HRESULT stdcall;
end;
ITaskNamedValuePair = interface (IDispatch)
['{39038068-2B46-4AFD-8662-7BB6F868D221}']
function Get_Name: WideString safecall;
procedure Set_Name(const pName: WideString) safecall;
function Get_Value: WideString safecall;
procedure Set_Value(const pValue: WideString) safecall;
property Name:WideString read Get_Name write Set_Name;
property Value:WideString read Get_Value write Set_Value;
end;
ITaskNamedValuePairDisp = dispinterface
['{39038068-2B46-4AFD-8662-7BB6F868D221}']
{published}
property Name: WideString dispid $0;
property Value: WideString dispid $1;
end platform;
ITaskNamedValueCollection = interface (IDispatch)
['{B4EF826B-63C3-46E4-A504-EF69E4F7EA4D}']
function Get_Count: Integer safecall;
function Get_Item(index: Integer): ITaskNamedValuePair safecall;
function Get__NewEnum: IUnknown safecall;
function Create(const Name: WideString; const Value: WideString):
ITaskNamedValuePair safecall;
procedure Remove(index: Integer) safecall;
procedure Clear safecall;
property Count:Integer read Get_Count;
property Item[index: Integer]: ITaskNamedValuePair
read Get_Item; default;
property _NewEnum:IUnknown read Get__NewEnum;
end;
ITaskNamedValueCollectionDisp = dispinterface
['{B4EF826B-63C3-46E4-A504-EF69E4F7EA4D}']
{published}
property Count: Integer readonly dispid $1;
property Item: ITaskNamedValuePair readonly
dispid $0;
property _NewEnum: IUnknown readonly dispid $FFFFFFFC;
function Create(const Name: WideString; const Value: WideString):
ITaskNamedValuePair;
procedure Remove(index: Integer);
procedure Clear;
end platform;
IIdleTrigger = interface (ITrigger)
['{D537D2B0-9FB3-4D34-9739-1FF5CE7B1EF3}']
end;
IIdleTriggerDisp = dispinterface
['{D537D2B0-9FB3-4D34-9739-1FF5CE7B1EF3}']
{published}
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
ILogonTrigger = interface (ITrigger)
['{72DADE38-FAE4-4B3E-BAF4-5D009AF02B1C}']
function Get_Delay: WideString safecall;
procedure Set_Delay(const pDelay: WideString) safecall;
function Get_UserId: WideString safecall;
procedure Set_UserId(const pUser: WideString) safecall;
property Delay:WideString read Get_Delay write Set_Delay;
property UserId:WideString read Get_UserId write Set_UserId;
end;
ILogonTriggerDisp = dispinterface
['{72DADE38-FAE4-4B3E-BAF4-5D009AF02B1C}']
{published}
property Delay: WideString dispid $14;
property UserId: WideString dispid $15;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
ISessionStateChangeTrigger = interface (ITrigger)
['{754DA71B-4385-4475-9DD9-598294FA3641}']
function Get_Delay: WideString safecall;
procedure Set_Delay(const pDelay: WideString) safecall;
function Get_UserId: WideString safecall;
procedure Set_UserId(const pUser: WideString) safecall;
function Get_StateChange: TOleEnum safecall;
procedure Set_StateChange(pType: TOleEnum) safecall;
property Delay:WideString read Get_Delay write Set_Delay;
property UserId:WideString read Get_UserId write Set_UserId;
property StateChange:TOleEnum read Get_StateChange
write Set_StateChange;
end;
ISessionStateChangeTriggerDisp = dispinterface
['{754DA71B-4385-4475-9DD9-598294FA3641}']
{published}
property Delay: WideString dispid $14;
property UserId: WideString dispid $15;
property StateChange: TOleEnum dispid $16;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IEventTrigger = interface (ITrigger)
['{D45B0167-9653-4EEF-B94F-0732CA7AF251}']
function Get_Subscription: WideString safecall;
procedure Set_Subscription(const pQuery: WideString) safecall;
function Get_Delay: WideString safecall;
procedure Set_Delay(const pDelay: WideString) safecall;
function Get_ValueQueries: ITaskNamedValueCollection safecall;
procedure Set_ValueQueries(const ppNamedXPaths: ITaskNamedValueCollection)
safecall;
property Subscription:WideString read Get_Subscription
write Set_Subscription;
property Delay:WideString read Get_Delay write Set_Delay;
property ValueQueries:ITaskNamedValueCollection read Get_ValueQueries
write Set_ValueQueries;
end;
IEventTriggerDisp = dispinterface
['{D45B0167-9653-4EEF-B94F-0732CA7AF251}']
{published}
property Subscription: WideString dispid $14;
property Delay: WideString dispid $15;
property ValueQueries: ITaskNamedValueCollection dispid $16;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
ITimeTrigger = interface (ITrigger)
['{B45747E0-EBA7-4276-9F29-85C5BB300006}']
function Get_RandomDelay: WideString safecall;
procedure Set_RandomDelay(const pRandomDelay: WideString) safecall;
property RandomDelay:WideString read Get_RandomDelay
write Set_RandomDelay;
end;
ITimeTriggerDisp = dispinterface
['{B45747E0-EBA7-4276-9F29-85C5BB300006}']
{published}
property RandomDelay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IDailyTrigger = interface (ITrigger)
['{126C5CD8-B288-41D5-8DBF-E491446ADC5C}']
function Get_DaysInterval: SmallInt safecall;
procedure Set_DaysInterval(pDays: SmallInt) safecall;
function Get_RandomDelay: WideString safecall;
procedure Set_RandomDelay(const pRandomDelay: WideString) safecall;
property DaysInterval:SmallInt read Get_DaysInterval
write Set_DaysInterval;
property RandomDelay:WideString read Get_RandomDelay
write Set_RandomDelay;
end;
IDailyTriggerDisp = dispinterface
['{126C5CD8-B288-41D5-8DBF-E491446ADC5C}']
{published}
property DaysInterval: SmallInt dispid $19;
property RandomDelay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IWeeklyTrigger = interface (ITrigger)
['{5038FC98-82FF-436D-8728-A512A57C9DC1}']
function Get_DaysOfWeek: SmallInt safecall;
procedure Set_DaysOfWeek(pDays: SmallInt) safecall;
function Get_WeeksInterval: SmallInt safecall;
procedure Set_WeeksInterval(pWeeks: SmallInt) safecall;
function Get_RandomDelay: WideString safecall;
procedure Set_RandomDelay(const pRandomDelay: WideString) safecall;
property DaysOfWeek:SmallInt read Get_DaysOfWeek write Set_DaysOfWeek;
property WeeksInterval:SmallInt read Get_WeeksInterval
write Set_WeeksInterval;
property RandomDelay:WideString read Get_RandomDelay
write Set_RandomDelay;
end;
IWeeklyTriggerDisp = dispinterface
['{5038FC98-82FF-436D-8728-A512A57C9DC1}']
{published}
property DaysOfWeek: SmallInt dispid $19;
property WeeksInterval: SmallInt dispid $1A;
property RandomDelay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IMonthlyTrigger = interface (ITrigger)
['{97C45EF1-6B02-4A1A-9C0E-1EBFBA1500AC}']
function Get_DaysOfMonth: Integer safecall;
procedure Set_DaysOfMonth(pDays: Integer) safecall;
function Get_MonthsOfYear: SmallInt safecall;
procedure Set_MonthsOfYear(pMonths: SmallInt) safecall;
function Get_RunOnLastDayOfMonth: WordBool safecall;
procedure Set_RunOnLastDayOfMonth(pLastDay: WordBool) safecall;
function Get_RandomDelay: WideString safecall;
procedure Set_RandomDelay(const pRandomDelay: WideString) safecall;
property DaysOfMonth:Integer read Get_DaysOfMonth
write Set_DaysOfMonth;
property MonthsOfYear:SmallInt read Get_MonthsOfYear
write Set_MonthsOfYear;
property RunOnLastDayOfMonth:WordBool read Get_RunOnLastDayOfMonth
write Set_RunOnLastDayOfMonth;
property RandomDelay:WideString read Get_RandomDelay
write Set_RandomDelay;
end;
IMonthlyTriggerDisp = dispinterface
['{97C45EF1-6B02-4A1A-9C0E-1EBFBA1500AC}']
{published}
property DaysOfMonth: Integer dispid $19;
property MonthsOfYear: SmallInt dispid $1A;
property RunOnLastDayOfMonth: WordBool dispid $1B;
property RandomDelay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IMonthlyDOWTrigger = interface (ITrigger)
['{77D025A3-90FA-43AA-B52E-CDA5499B946A}']
function Get_DaysOfWeek: SmallInt safecall;
procedure Set_DaysOfWeek(pDays: SmallInt) safecall;
function Get_WeeksOfMonth: SmallInt safecall;
procedure Set_WeeksOfMonth(pWeeks: SmallInt) safecall;
function Get_MonthsOfYear: SmallInt safecall;
procedure Set_MonthsOfYear(pMonths: SmallInt) safecall;
function Get_RunOnLastWeekOfMonth: WordBool safecall;
procedure Set_RunOnLastWeekOfMonth(pLastWeek: WordBool) safecall;
function Get_RandomDelay: WideString safecall;
procedure Set_RandomDelay(const pRandomDelay: WideString) safecall;
property DaysOfWeek:SmallInt read Get_DaysOfWeek write Set_DaysOfWeek;
property WeeksOfMonth:SmallInt read Get_WeeksOfMonth
write Set_WeeksOfMonth;
property MonthsOfYear:SmallInt read Get_MonthsOfYear
write Set_MonthsOfYear;
property RunOnLastWeekOfMonth:WordBool read Get_RunOnLastWeekOfMonth
write Set_RunOnLastWeekOfMonth;
property RandomDelay:WideString read Get_RandomDelay
write Set_RandomDelay;
end;
IMonthlyDOWTriggerDisp = dispinterface
['{77D025A3-90FA-43AA-B52E-CDA5499B946A}']
{published}
property DaysOfWeek: SmallInt dispid $19;
property WeeksOfMonth: SmallInt dispid $1A;
property MonthsOfYear: SmallInt dispid $1B;
property RunOnLastWeekOfMonth: WordBool dispid $1C;
property RandomDelay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IBootTrigger = interface (ITrigger)
['{2A9C35DA-D357-41F4-BBC1-207AC1B1F3CB}']
function Get_Delay: WideString safecall;
procedure Set_Delay(const pDelay: WideString) safecall;
property Delay:WideString read Get_Delay write Set_Delay;
end;
IBootTriggerDisp = dispinterface
['{2A9C35DA-D357-41F4-BBC1-207AC1B1F3CB}']
{published}
property Delay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IRegistrationTrigger = interface (ITrigger)
['{4C8FEC3A-C218-4E0C-B23D-629024DB91A2}']
function Get_Delay: WideString safecall;
procedure Set_Delay(const pDelay: WideString) safecall;
property Delay:WideString read Get_Delay write Set_Delay;
end;
IRegistrationTriggerDisp = dispinterface
['{4C8FEC3A-C218-4E0C-B23D-629024DB91A2}']
{published}
property Delay: WideString dispid $14;
property type_: TOleEnum readonly dispid $1;
property Id: WideString dispid $2;
property Repetition: IRepetitionPattern dispid $3;
property ExecutionTimeLimit: WideString dispid $4;
property StartBoundary: WideString dispid $5;
property EndBoundary: WideString dispid $6;
property Enabled: WordBool dispid $7;
end platform;
IExecAction = interface (IAction)
['{4C3D624D-FD6B-49A3-B9B7-09CB3CD3F047}']
function Get_Path: WideString safecall;
procedure Set_Path(const pPath: WideString) safecall;
function Get_Arguments: WideString safecall;
procedure Set_Arguments(const pArgument: WideString) safecall;
function Get_WorkingDirectory: WideString safecall;
procedure Set_WorkingDirectory(const pWorkingDirectory: WideString)
safecall;
property Path:WideString read Get_Path write Set_Path;
property Arguments:WideString read Get_Arguments write Set_Arguments;
property WorkingDirectory:WideString read Get_WorkingDirectory
write Set_WorkingDirectory;
end;
IExecActionDisp = dispinterface
['{4C3D624D-FD6B-49A3-B9B7-09CB3CD3F047}']
{published}
property Path: WideString dispid $A;
property Arguments: WideString dispid $B;
property WorkingDirectory: WideString dispid $C;
property Id: WideString dispid $1;
property type_: TOleEnum readonly dispid $2;
end platform;
IShowMessageAction = interface (IAction)
['{505E9E68-AF89-46B8-A30F-56162A83D537}']
function Get_Title: WideString safecall;
procedure Set_Title(const pTitle: WideString) safecall;
function Get_MessageBody: WideString safecall;
procedure Set_MessageBody(const pMessageBody: WideString) safecall;
property Title:WideString read Get_Title write Set_Title;
property MessageBody:WideString read Get_MessageBody
write Set_MessageBody;
end;
IShowMessageActionDisp = dispinterface
['{505E9E68-AF89-46B8-A30F-56162A83D537}']
{published}
property Title: WideString dispid $A;
property MessageBody: WideString dispid $B;
property Id: WideString dispid $1;
property type_: TOleEnum readonly dispid $2;
end platform;
IComHandlerAction = interface (IAction)
['{6D2FD252-75C5-4F66-90BA-2A7D8CC3039F}']
function Get_ClassId: WideString safecall;
procedure Set_ClassId(const pClsid: WideString) safecall;
function Get_Data: WideString safecall;
procedure Set_Data(const pData: WideString) safecall;
property ClassId:WideString read Get_ClassId write Set_ClassId;
property Data:WideString read Get_Data write Set_Data;
end;
IComHandlerActionDisp = dispinterface
['{6D2FD252-75C5-4F66-90BA-2A7D8CC3039F}']
{published}
property ClassId: WideString dispid $A;
property Data: WideString dispid $B;
property Id: WideString dispid $1;
property type_: TOleEnum readonly dispid $2;
end platform;
IEmailAction = interface (IAction)
['{10F62C64-7E16-4314-A0C2-0C3683F99D40}']
function Get_Server: WideString safecall;
procedure Set_Server(const pServer: WideString) safecall;
function Get_Subject: WideString safecall;
procedure Set_Subject(const pSubject: WideString) safecall;
function Get_To_: WideString safecall;
procedure Set_To_(const pTo: WideString) safecall;
function Get_Cc: WideString safecall;
procedure Set_Cc(const pCc: WideString) safecall;
function Get_Bcc: WideString safecall;
procedure Set_Bcc(const pBcc: WideString) safecall;
function Get_ReplyTo: WideString safecall;
procedure Set_ReplyTo(const pReplyTo: WideString) safecall;
function Get_From: WideString safecall;
procedure Set_From(const pFrom: WideString) safecall;
function Get_HeaderFields: ITaskNamedValueCollection safecall;
procedure Set_HeaderFields(const ppHeaderFields: ITaskNamedValueCollection)
safecall;
function Get_Body: WideString safecall;
procedure Set_Body(const pBody: WideString) safecall;
function Get_Attachments: PSafeArray safecall;
procedure Set_Attachments(pAttachements: PSafeArray) safecall;
property Server:WideString read Get_Server write Set_Server;
property Subject:WideString read Get_Subject write Set_Subject;
property To_:WideString read Get_To_ write Set_To_;
property Cc:WideString read Get_Cc write Set_Cc;
property Bcc:WideString read Get_Bcc write Set_Bcc;
property ReplyTo:WideString read Get_ReplyTo write Set_ReplyTo;
property From:WideString read Get_From write Set_From;
property HeaderFields:ITaskNamedValueCollection read Get_HeaderFields
write Set_HeaderFields;
property Body:WideString read Get_Body write Set_Body;
property Attachments:PSafeArray read Get_Attachments
write Set_Attachments;
end;
IEmailActionDisp = dispinterface
['{10F62C64-7E16-4314-A0C2-0C3683F99D40}']
{published}
property Server: WideString dispid $A;
property Subject: WideString dispid $B;
property To_: WideString dispid $C;
property Cc: WideString dispid $D;
property Bcc: WideString dispid $E;
property ReplyTo: WideString dispid $F;
property From: WideString dispid $10;
property HeaderFields: ITaskNamedValueCollection dispid $11;
property Body: WideString dispid $12;
property Attachments: OleVariant dispid $13;
property Id: WideString dispid $1;
property type_: TOleEnum readonly dispid $2;
end platform;
implementation
end.
|
unit uTableSignersList;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, uTableSignersData, uTableStrings, uTableSigners,
Buttons, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, Grids, DBGrids, ActnList, uActionControl,
Menus, StdCtrls;
type
TfmTableSignersList = class(TForm)
Panel1: TPanel;
AddButton: TSpeedButton;
RefreshButton: TSpeedButton;
SignersGridDBTableView1: TcxGridDBTableView;
SignersGridLevel1: TcxGridLevel;
SignersGrid: TcxGrid;
SignersGridTableView1: TcxGridTableView;
SignersTableView: TcxGridDBTableView;
ID_TABLE_SIGNER: TcxGridDBColumn;
FIO: TcxGridDBColumn;
NAME_POST: TcxGridDBColumn;
KIND: TcxGridDBColumn;
ID: TcxGridDBColumn;
NAME_OBJECT: TcxGridDBColumn;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
ModifyButton: TSpeedButton;
InfoButton: TSpeedButton;
ExitButton: TSpeedButton;
DeleteButton: TSpeedButton;
TableSignersActions: TActionList;
AddTableSigner: TAction;
RefreshTableSigner: TAction;
ModifyTableSigner: TAction;
InfoTableSigner: TAction;
DeleteTableSigner: TAction;
ActionControl: TqFActionControl;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
CloseAction: TAction;
N7: TMenuItem;
Panel2: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton6: TSpeedButton;
RealSignersGridDBTableView1: TcxGridDBTableView;
RealSignersGridLevel1: TcxGridLevel;
RealSignersGrid: TcxGrid;
RealSignersGridDBTableView1ID_TABLE_SIGNER_REAL: TcxGridDBColumn;
RealSignersGridDBTableView1ID_PCARD: TcxGridDBColumn;
RealSignersGridDBTableView1DATE_BEG: TcxGridDBColumn;
RealSignersGridDBTableView1DATE_END: TcxGridDBColumn;
RealSignersGridDBTableView1FIO: TcxGridDBColumn;
Panel3: TPanel;
Label1: TLabel;
AddRealSigner: TAction;
ModifyRealSigner: TAction;
InfoRealSigner: TAction;
DeleteRealSigner: TAction;
RealSignersActControl: TqFActionControl;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
procedure CloseActionExecute(Sender: TObject);
private
Sprav: TTableSigners;
public
constructor Create(AOwner: TComponent; Sprav: TTableSigners); reintroduce;
end;
var
fmTableSignersList: TfmTableSignersList;
implementation
{$R *.dfm}
constructor TfmTableSignersList.Create(AOwner: TComponent; Sprav: TTableSigners);
begin
inherited Create(AOwner);
Self.Sprav := Sprav;
end;
procedure TfmTableSignersList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then Action := caFree;
end;
procedure TfmTableSignersList.FormCreate(Sender: TObject);
begin
Caption := tbl_TableSignersCaption;
Hint := tbl_TableSignersCaption;
FIO.Caption := tbl_TableSignerFIOCaption;
Name_Post.Caption := tbl_TableSignerNamePostCaption;
Name_Object.Caption := tbl_TableSignerNameObjectCaption;
end;
procedure TfmTableSignersList.FormDestroy(Sender: TObject);
begin
if FormStyle = fsMDIChild then Sprav.Free;
end;
procedure TfmTableSignersList.ExitButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfmTableSignersList.CloseActionExecute(Sender: TObject);
begin
Close;
end;
end.
|
unit doll_lib;
interface
type
array_of_longint = array of longint;
procedure answer(C, X, Y: array_of_longint);
implementation
uses sysutils, doll;
const
P_MAX: longint = 20000000;
S_MAX: longint = 400000;
var
M, N: longint;
A: array of longint;
S: longint;
IC, IX, IY: array of longint;
function read_longint(): longint;
var
x: longint;
begin
if eof() then begin
writeln(stderr, 'Error while reading input');
halt(1);
end;
{$I-}
read(x);
{$I+}
if ioresult() <> 0 then begin
writeln(stderr, 'Error while reading input');
halt(1);
end;
exit(x);
end;
procedure wrong_answer(MSG: ansistring);
begin
writeln('Wrong Answer: ', MSG);
halt(0);
end;
procedure simulate();
var
P, pos, i, j, k: longint;
state: array of boolean;
str: ansistring;
file_log: text;
begin
if S > S_MAX then begin
writestr(str, 'over ', S_MAX, ' switches');
wrong_answer(str);
end;
for i := 0 to M do begin
if not ((-S <= IC[i]) and (IC[i] <= M)) then begin
wrong_answer('wrong serial number');
end;
end;
for j := 1 to S do begin
if not ((-S <= IX[j - 1]) and (IX[j - 1] <= M)) then begin
wrong_answer('wrong serial number');
end;
if not ((-S <= IY[j - 1]) and (IY[j - 1] <= M)) then begin
wrong_answer('wrong serial number');
end;
end;
P := 0;
setlength(state, S + 1);
for j := 0 to S do begin
state[j] := false;
end;
pos := IC[0];
k := 0;
assign(file_log, 'log.txt');
rewrite(file_log);
writeln(file_log, 0);
while true do begin
writeln(file_log, pos);
if pos < 0 then begin
P := P + 1;
if P > P_MAX then begin
close(file_log);
writestr(str, 'over ', P_MAX, ' inversions');
wrong_answer(str);
end;
state[-pos] := not state[-pos];
if state[-pos] then begin
pos := IX[-(1 + pos)];
end else begin
pos := IY[-(1 + pos)];
end;
end else begin
if pos = 0 then begin
break;
end;
if k >= N then begin
close(file_log);
wrong_answer('wrong motion');
end;
if pos <> A[k] then begin
close(file_log);
wrong_answer('wrong motion');
end;
k := k + 1;
pos := IC[pos];
end;
end;
close(file_log);
if k <> N then begin
wrong_answer('wrong motion');
end;
for j := 1 to S do begin
if state[j] then begin
wrong_answer('state ''Y''');
end;
end;
writeln('Accepted: ', S, ' ', P);
end;
var
answered: boolean;
procedure answer(C, X, Y: array_of_longint);
var
i, j: longint;
begin
if answered then begin
wrong_answer('answered not exactly once');
end;
answered := true;
if length(C) <> M + 1 then begin
wrong_answer('wrong array length');
end;
if length(X) <> length(Y) then begin
wrong_answer('wrong array length');
end;
S := length(X);
setlength(IC, M + 1);
setlength(IX, S);
setlength(IY, S);
for i := 0 to M do begin
IC[i] := C[low(C) + i];
end;
for j := 1 to S do begin
IX[j - 1] := X[low(X) + (j - 1)];
IY[j - 1] := Y[low(Y) + (j - 1)];
end;
end;
var
i, j, k: longint;
file_out: text;
begin
M := read_longint();
N := read_longint();
setlength(A, N);
for k := 0 to N - 1 do begin
A[k] := read_longint();
end;
answered := false;
create_circuit(M, A);
if not answered then begin
wrong_answer('answered not exactly once');
end;
assign(file_out, 'out.txt');
rewrite(file_out);
writeln(file_out, S);
for i := 0 to M do begin
writeln(file_out, IC[i]);
end;
for j := 1 to S do begin
writeln(file_out, IX[j - 1], ' ', IY[j - 1]);
end;
close(file_out);
simulate();
end.
|
unit UIntUtils;
{ A missing RTL function written by Warren Postma. }
{$DEFINE CPUX86}
interface
function TryStrToUINT64(StrValue:String; var uValue:UInt64 ):Boolean;
function StrToUINT64(Value:String):UInt64;
function InterlockedExchangeAdd64(var Addend: UInt64; Value: UInt64): UInt64;
implementation
uses SysUtils,Character;
function InterlockedCompareExchange64(var Destination:UInt64;ExChange,Comperand:UInt64):UInt64;
stdcall;external 'kernel32.dll' name 'InterlockedCompareExchange64';
{$R-}
function TryStrToUINT64(StrValue:String; var uValue:UInt64 ):Boolean;
var
Start,Base,Digit:Integer;
n:Integer;
Nextvalue:UInt64;
begin
result := false;
Base := 10;
Start := 1;
StrValue := Trim(UpperCase(StrValue));
if StrValue='' then
exit;
if StrValue[1]='-' then
exit;
if StrValue[1]='$' then
begin
Base := 16;
Start := 2;
if Length(StrValue)>17 then // $+16 hex digits = max hex length.
exit;
end;
uValue := 0;
for n := Start to Length(StrValue) do
begin
if Character.IsDigit(StrValue[n]) then
Digit := Ord(StrValue[n])-Ord('0')
else if (Base=16) and (StrValue[n] >= 'A') and (StrValue[n] <= 'F') then
Digit := (Ord(StrValue[n])-Ord('A'))+10
else
exit;// invalid digit.
Nextvalue := (uValue*base)+digit;
if (Nextvalue<uValue) then
exit;
uValue := Nextvalue;
end;
result := true; // success.
end;
function StrToUINT64(Value:String):UInt64;
begin
if not TryStrToUINT64(Value,result) then
raise EConvertError.Create('Invalid uint64 value');
end;
{$R+}
function InterlockedExchangeAdd64(var Addend: UInt64; Value: UInt64): UInt64;
begin
repeat
Result := Addend;
until (InterlockedCompareExchange64(Addend, Result + Value, Result) = Result);
end;
//{$IFDEF CPUX86}
//function InterlockedExchangeAdd64(var Addend: Int64; Value: longword): Int64; register;
//asm
// PUSH EDI
// PUSH ESI
// PUSH EBX
//
// MOV EDI, EAX
// MOV ESI, EDX
//
// MOV EAX, [EDI]
// MOV EDX, [EDI+4]
//@@1:
// MOV ECX, EDX
// MOV EBX, EAX
//
// ADD EBX, ESI
// ADC ECX, 0
//
//LOCK CMPXCHG8B [EDI]
// JNZ @@1
//
// POP EBX
// POP ESI
// POP EDI
//end;
//{$ENDIF}
//
//{$IFDEF CPUX64}
//function InterlockedExchangeAdd64(var Addend: Int64; Value: longword): Int64; register;
//asm
// .NOFRAME
// MOV RAX, RDX
// LOCK XADD [RCX], RAX
//end;
//{$ENDIF}
end.
|
Unit FileObjectNameXXXRequest;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows,
IRPMonRequest, IRPMonDll;
Type
TFileObjectNameAssignedRequest = Class (TDriverRequest)
Public
Constructor Create(Var ARequest:REQUEST_FILE_OBJECT_NAME_ASSIGNED); Overload;
Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
end;
TFileObjectNameDeletedRequest = Class (TDriverRequest)
Public
Constructor Create(Var ARequest:REQUEST_FILE_OBJECT_NAME_DELETED); Overload;
Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
end;
Implementation
Uses
SysUtils;
(** TFileObjectNameAssignedRequest **)
Constructor TFileObjectNameAssignedRequest.Create(Var ARequest:REQUEST_FILE_OBJECT_NAME_ASSIGNED);
Var
fn : PWideChar;
rawReq : PREQUEST_FILE_OBJECT_NAME_ASSIGNED;
tmpFileName : WideString;
begin
Inherited Create(ARequest.Header);
rawReq := PREQUEST_FILE_OBJECT_NAME_ASSIGNED(FRaw);
SetFileObject(rawReq.FileObject);
fn := PWideChar(PByte(rawReq) + SizeOf(REQUEST_FILE_OBJECT_NAME_ASSIGNED));
SetLength(tmpFileName, rawReq.FileNameLength Div SizeOf(WideChar));
CopyMemory(PWideChar(tmpFileName), fn, rawReq.FileNameLength);
SetFileName(tmpFileName);
end;
Function TFileObjectNameAssignedRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverObject,
rlmctDriverName : Result := False;
Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize);
end;
end;
Function TFileObjectNameAssignedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverObject,
rlmctDriverName : Result := False;
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
(** TFileObjectNameDeletedRequest **)
Constructor TFileObjectNameDeletedRequest.Create(Var ARequest:REQUEST_FILE_OBJECT_NAME_DELETED);
begin
Inherited Create(ARequest.Header);
SetFileObject(ARequest.FileObject);
end;
Function TFileObjectNameDeletedRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverObject,
rlmctDriverName : Result := False;
Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize);
end;
end;
Function TFileObjectNameDeletedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverObject,
rlmctDriverName : Result := False;
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
End.
|
//
// 677. 键值映射
//
// 实现一个 MapSum 类里的两个方法,insert 和 sum。
//
// 对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
//
// 对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
//
// 示例 1:
//
// 输入: insert("apple", 3), 输出: Null
// 输入: sum("ap"), 输出: 3
// 输入: insert("app", 2), 输出: Null
// 输入: sum("ap"), 输出: 5
//
// class MapSum {
//
// /** Initialize your data structure here. */
// public MapSum() {
//
// }
//
// public void insert(String key, int val) {
//
// }
//
// public int sum(String prefix) {
//
// }
// }
//
// /**
// * Your MapSum object will be instantiated and called as such:
// * MapSum obj = new MapSum();
// * obj.insert(key,val);
// * int param_2 = obj.sum(prefix);
// */
unit DSA.Leetcode._677;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Tree.BSTMap,
DSA.Utils;
type
TMapSum = class
private
type
TNode = class
private
type
TreeMap = specialize TBSTMap<char, TNode, TComparer_chr>;
public
Value: integer;
Next: TreeMap;
constructor Create(newValue: integer = 0);
end;
var
__root: TNode;
function __sum(node: TNode): integer;
public
constructor Create;
procedure Insert(word: string; val: integer);
function Sum(prefix: string): integer;
end;
procedure Main();
implementation
procedure Main();
var
ms: TMapSum;
i: integer;
begin
ms := TMapSum.Create;
with ms do
begin
Insert('apple', 3);
i := Sum('ap');
Writeln(i);
Insert('app', 2);
i := Sum('ap');
Writeln(i);
end;
end;
{ TMapSum.TNode }
constructor TMapSum.TNode.Create(newValue: integer);
begin
Value := newValue;
Next := TreeMap.Create;
end;
{ TMapSum }
constructor TMapSum.Create;
begin
__root := TNode.Create();
end;
procedure TMapSum.Insert(word: string; val: integer);
var
cur: TNode;
i: integer;
c: char;
begin
cur := __root;
for i := low(word) to high(word) do
begin
c := word[i];
if cur.Next.Contains(c) = False then
cur.Next.Add(c, TNode.Create());
cur := cur.Next.Get(c).PValue^;
end;
cur.Value := val;
end;
function TMapSum.Sum(prefix: string): integer;
var
cur: TNode;
i: integer;
c: char;
begin
cur := __root;
for i := 0 to prefix.Length - 1 do
begin
c := prefix.Chars[i];
if cur.Next.Get(c).PValue = nil then
Exit(0);
cur := cur.Next.Get(c).PValue^;
end;
Result := __sum(cur);
end;
function TMapSum.__sum(node: TNode): integer;
var
res: integer;
c: char;
begin
if node.Next.IsEmpty then
Exit(node.Value);
res := node.Value;
for c in node.Next.KeySets.ToArray do
begin
res := res + __sum(node.Next.Get(c).PValue^);
end;
Result := res;
end;
end.
|
program hello(output);
const message = 'hello world!';
begin
writeln(message)
end.
|
unit UMixer;
interface
uses UFlow;
type
Mixer = class
function calculate(flows: array of Flow): Flow;
end;
implementation
function Mixer.calculate(flows: array of Flow): Flow;
begin
var mass_flow := 0.0;
foreach var f in flows do
mass_flow += f.mass_flow_rate;
var mass_fractions := ArrFill(
flows[0].mass_fractions.Length, 0.0);
foreach var i in mass_fractions.Indices do
foreach var f in flows do
mass_fractions[i] += f.mass_flow_rate * f.mass_fractions[i] / mass_flow;
var cp := 0.0;
foreach var f in flows do
cp += f.mass_flow_rate * f.cp / mass_flow;
var temperature := 0.0;
foreach var f in flows do
temperature += f.mass_flow_rate * f.cp * f.temperature / mass_flow / cp;
result := new Flow(mass_flow, mass_fractions, temperature)
end;
end. |
unit uConverterRADServer;
// EMS Resource Module
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, Soap.InvokeRegistry,
Soap.Rio, Soap.SOAPHTTPClient, Converter;
type
[ResourceName('Currency')]
TCurrencyResource1 = class(TDataModule)
HTTPRIO1: THTTPRIO;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FwsConverter: ConverterSoap;
procedure SetwsConverter(const Value: ConverterSoap);
public
property wsConverter : ConverterSoap read FwsConverter write SetwsConverter;
published
procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
Xml.xmldom, Xml.omnixmldom, XSBuiltIns;
procedure TCurrencyResource1.DataModuleCreate(Sender: TObject);
begin
wsConverter := HTTPRIO1 as ConverterSoap;
end;
procedure TCurrencyResource1.DataModuleDestroy(Sender: TObject);
begin
wsConverter := nil;
end;
procedure TCurrencyResource1.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
begin
// Sample code
DefaultDOMVendor := sOmniXmlVendor;
AResponse.Body.SetValue(TJSONString.Create( DateToStr(wsConverter.GetLastUpdateDate.AsDateTime)), True) ;
end;
procedure TCurrencyResource1.GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LItem: string;
Amount : TXSDecimal;
begin
if AContext.User = nil then
EEMSHTTPError.RaiseUnauthorized('', 'User Required');
if not AContext.User.Groups.Contains('testgroup') then
EEMSHTTPError.RaiseForbidden('','Test Group Required');
DefaultDOMVendor := sOmniXmlVendor;
LItem := ARequest.Params.Values['item'];
Amount := TXSDecimal.Create;
Amount.DecimalString := LItem;
AResponse.Body.SetValue(TJSONString.Create(
wsConverter.GetConversionAmount('USD','BRL',DateTimeToXSDateTime(Date-2),Amount).DecimalString ), True)
end;
procedure TCurrencyResource1.SetwsConverter(const Value: ConverterSoap);
begin
FwsConverter := Value;
end;
procedure Register;
begin
RegisterResource(TypeInfo(TCurrencyResource1));
end;
initialization
Register;
end.
|
unit USahObjects;
{ Alexandre Hirzel Collection of OpenGL objects }
interface
uses
OpenGL1x,
GLVectorGeometry,
GLVectorFileObjects,
GLScene;
// Cube of radius 1 centred on the origin
procedure BuildCube(const Tile: double = 1);
// Cube of radius 1 centred on the origin
procedure BuildStarField(const nbStars: integer);
procedure BuildCross(const Radius: single);
procedure BuildSphere(var Mesh: TMeshObject; const Depth: integer = 0);
function BuildPotatoid(var Mesh: TMeshObject; const Deviance: single = 0.2;
const Depth: integer = 1; ActualDepth: integer = -1): boolean;
type
tglVector = array [0 .. 3] of GLFloat;
tglMatrix = array [0 .. 15] of GLFloat; // Transformation matrix, by columns
tMovingCamera = class(tObject)
private
protected
public
ux, uy, uz: single; // U: Horizontal vector (Left to right) (World system)
vx, vy, vz: single; // V: Vertical vector (bottom-up screen) (World system)
nx, ny, nz: single; // N: Normal vector (into the screen) (World system)
x, y, z: single; // Coordinates (World system)
ru, rv, rn: single; // Angular speed; [deg./sec] (Camera system)
Speed: single; // Speed (along S) [1/sec]
sx, sy, sz: single; // Speed vector (multiplied by Speed) (World system)
SpeedMatrix: tglMatrix;
GLobject: TGLBaseSceneObject;
procedure Accelerate(const au, av, an: single); // Change the speed vector
procedure Apply; // Rotate and translate the glWorld accordingly
procedure ApplyFrontView; // Look in the direction of movement
constructor Create;
destructor Destroy; override;
procedure GoThatWay; // Set the velocity vector toward the direction of view
procedure Move(const du, dv, dn: single);
// Translation in the camera system
procedure Pitch(const Angle: single); // U rotation
procedure ResetAttitude;
procedure Roll(const Angle: single); // N rotation
procedure ComputeSpeed;
procedure Translate(const dx, dy, dz: single);
// Translation in the world system
procedure UpdateAll(const Time: double);
// Compute new coordinates and angles
procedure UpdateAttitude(const Time: double); // Compute new angles
procedure UpdatePosition(const Time: double); // Compute new coordinates
procedure Yaw(const Angle: single); // V rotation
end; // record
tRealMovingCamera = class(tMovingCamera)
{ Implement vibration and gyroscopic effects }
protected
Vibx, Viby, Vibz: single;
public
InU, InV, InN: single; // Mass inertia along the three axes
procedure Apply;
procedure GyroPitch(const Moment: single); // U rotation
procedure GyroRoll(const Moment: single); // N rotation
procedure Vibrate(const Vibration: single);
procedure GyroYaw(const Moment: single); // V rotation
end; // class
// ==================================================================
implementation
// ==================================================================
procedure BuildCube(const Tile: double = 1);
{ Cube of size 2 (vertices between -1 and 1) centred on the origine.
If a texture is applied it will be tiled Tile times along each direction }
begin
// Front Face
glBegin(GL_QUADS);
glNormal3f(0.0, 0.0, 1.0);
glTexCoord2f(0.0, 0.0);
glVertex3f(-1, -1, 1);
glTexCoord2f(Tile, 0.0);
glVertex3f(1, -1, 1);
glTexCoord2f(Tile, Tile);
glVertex3f(1, 1, 1);
glTexCoord2f(0.0, Tile);
glVertex3f(-1, 1, 1);
glEnd();
// Back Face
glBegin(GL_QUADS);
glNormal3f(0.0, 0.0, -1.0);
glTexCoord2f(Tile, 0.0);
glVertex3f(-1, -1, -1);
glTexCoord2f(Tile, Tile);
glVertex3f(-1, 1, -1);
glTexCoord2f(0.0, Tile);
glVertex3f(1, 1, -1);
glTexCoord2f(0.0, 0.0);
glVertex3f(1, -1, -1);
glEnd();
// Top Face
glBegin(GL_QUADS);
glNormal3f(0.0, 1.0, 0.0);
glTexCoord2f(0.0, Tile);
glVertex3f(-1, 1, -1);
glTexCoord2f(0.0, 0.0);
glVertex3f(-1, 1, 1);
glTexCoord2f(Tile, 0.0);
glVertex3f(1, 1, 1);
glTexCoord2f(Tile, Tile);
glVertex3f(1, 1, -1);
glEnd();
// Bottom Face
glBegin(GL_QUADS);
glNormal3f(0.0, -1.0, 0.0);
glTexCoord2f(Tile, Tile);
glVertex3f(-1, -1, -1);
glTexCoord2f(0.0, Tile);
glVertex3f(1, -1, -1);
glTexCoord2f(0.0, 0.0);
glVertex3f(1, -1, 1);
glTexCoord2f(Tile, 0.0);
glVertex3f(-1, -1, 1);
glEnd();
// Right face
glBegin(GL_QUADS);
glNormal3f(1.0, 0.0, 0.0);
glTexCoord2f(Tile, 0.0);
glVertex3f(1, -1, -1);
glTexCoord2f(Tile, Tile);
glVertex3f(1, 1, -1);
glTexCoord2f(0.0, Tile);
glVertex3f(1, 1, 1);
glTexCoord2f(0.0, 0.0);
glVertex3f(1, -1, 1);
glEnd();
// Left Face
glBegin(GL_QUADS);
glNormal3f(-1.0, 0.0, 0.0);
glTexCoord2f(0.0, 0.0);
glVertex3f(-1, -1, -1);
glTexCoord2f(Tile, 0.0);
glVertex3f(-1, -1, 1);
glTexCoord2f(Tile, Tile);
glVertex3f(-1, 1, 1);
glTexCoord2f(0.0, Tile);
glVertex3f(-1, 1, -1);
glEnd();
end;
procedure BuildStarField(const nbStars: integer);
{ Stars randomly placed on a sphere of radius 1 }
var
i: integer;
a, b: double;
c, s: double;
cb, sb: double;
Mag: single;
begin
glPointSize(1);
glBegin(GL_POINTS);
glColor3d(1, 1, 1);
for i := 1 to Round(0.75 * nbStars) do
begin
a := random * 2 * pi;
b := random * pi - pi / 2;
SinCosine(a, s, c);
SinCosine(b, sb, cb);
Mag := random * 0.5 + 0.3;
glColor3d(Mag, Mag, Mag);
glVertex3f(c * cb, s * cb, sb);
end; // for i
glEnd();
glPointSize(2);
glBegin(GL_POINTS);
glColor3d(1, 1, 1);
for i := 1 to Round(0.25 * nbStars) do
begin
a := random * 2 * pi;
b := random * pi - pi / 2;
SinCosine(a, s, c);
SinCosine(b, sb, cb);
Mag := random * 0.5 + 0.3;
glColor3d(Mag, Mag, Mag);
glVertex3f(c * cb, s * cb, sb);
end; // for i
glEnd();
end;
procedure BuildCross(const Radius: single);
begin
glBegin(GL_LINES);
glVertex3f(-Radius, 0, 0);
glVertex3f(+Radius, 0, 0);
glEnd;
glBegin(GL_LINES);
glVertex3f(0, -Radius, 0);
glVertex3f(0, +Radius, 0);
glEnd;
end;
procedure Normalize(var v: array of single);
var
d: double;
begin
d := sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
v[0] := v[0] / d;
v[1] := v[1] / d;
v[2] := v[2] / d;
end;
procedure NormCrossProd(const v1, v2: array of single;
var Result: array of single);
{ var
i, j :GLint;
length :single; }
begin
Result[0] := v1[1] * v2[2] - v1[2] * v2[1];
Result[1] := v1[2] * v2[0] - v1[0] * v2[2];
Result[2] := v1[0] * v2[1] - v1[1] * v2[0];
Normalize(Result);
end;
procedure CartToPol(v: array of single; var Theta, Phi: single);
var
CosPhi: single;
begin
Normalize(v);
Phi := ArcSine(v[1]);
if Abs(v[1]) < 1 then
begin
CosPhi := sqrt(1 - sqr(v[1]));
Theta := ArcCosine(v[0] / CosPhi);
if v[2] < 0 then
Theta := -Theta;
end
else
Theta := 0;
end;
procedure SpheroidAddTriangle(var Mesh: TMeshObject;
const v1, v2, v3: array of single);
var
j: integer;
d1, d2, norm: array [0 .. 2] of single;
Theta, Phi: array [0 .. 2] of single;
begin
for j := 0 to 2 do
begin
d1[j] := v1[j] - v2[j];
d2[j] := v2[j] - v3[j];
end; // for j
NormCrossProd(d1, d2, norm);
CartToPol(v1, Theta[0], Phi[0]);
CartToPol(v2, Theta[1], Phi[1]);
CartToPol(v3, Theta[2], Phi[2]);
if (Abs(SignStrict(Theta[0]) + SignStrict(Theta[1]) + SignStrict(Theta[2])) < 3) and
(Abs(Theta[0] * Theta[1] * Theta[2]) > 8) then
begin
if Theta[0] < 0 then
Theta[0] := Theta[0] + 2 * pi;
if Theta[1] < 0 then
Theta[1] := Theta[1] + 2 * pi;
if Theta[2] < 0 then
Theta[2] := Theta[2] + 2 * pi;
end; // if
Mesh.Vertices.add(v1[0], v1[1], v1[2]);
// Mesh.Normals.add ((v1[0]+norm[0])/2,(v1[1]+norm[1])/2,(v1[2]+norm[2])/2);
Mesh.Normals.add(norm[0], norm[1], norm[2]);
Mesh.TexCoords.add(Theta[0] / pi / 2 + 0.5, Phi[0] / pi + 0.5);
Mesh.Vertices.add(v2[0], v2[1], v2[2]);
// Mesh.Normals.add ((v2[0]+norm[0])/2,(v2[1]+norm[1])/2,(v2[2]+norm[2])/2);
Mesh.Normals.add(norm[0], norm[1], norm[2]);
Mesh.TexCoords.add(Theta[1] / pi / 2 + 0.5, Phi[1] / pi + 0.5);
Mesh.Vertices.add(v3[0], v3[1], v3[2]);
// Mesh.Normals.add ((v3[0]+norm[0])/2,(v3[1]+norm[1])/2,(v3[2]+norm[2])/2);
Mesh.Normals.add(norm[0], norm[1], norm[2]);
Mesh.TexCoords.add(Theta[2] / pi / 2 + 0.5, Phi[2] / pi + 0.5);
end;
procedure BuildSphere(var Mesh: TMeshObject; const Depth: integer = 0);
{ Polyhedron and Subdivide algorithms from OpenGL Red Book }
procedure Subdivide(const v1, v2, v3: array of single; const Depth: integer);
var
v12, v23, v31: array [0 .. 2] of single;
i: integer;
begin
if Depth = 0 then
SpheroidAddTriangle(Mesh, v1, v2, v3)
else
begin
for i := 0 to 2 do
begin
v12[i] := v1[i] + v2[i];
v23[i] := v2[i] + v3[i];
v31[i] := v3[i] + v1[i];
end; // for
Normalize(v12);
Normalize(v23);
Normalize(v31);
Subdivide(v1, v12, v31, Depth - 1);
Subdivide(v2, v23, v12, Depth - 1);
Subdivide(v3, v31, v23, Depth - 1);
Subdivide(v12, v23, v31, Depth - 1);
end; // else
end;
const
x = 0.525731112119133606; // Chosen for a radius-1 icosahedron
z = 0.850650808352039932; //
vdata: array [0 .. 11, 0 .. 2] of single = ( // 12 vertices
(-x, 0.0, z), (x, 0.0, z), (-x, 0.0, -z), (x, 0.0, -z), (0.0, z, x),
(0.0, z, -x), (0.0, -z, x), (0.0, -z, -x), (z, x, 0.0), (-z, x, 0.0),
(z, -x, 0.0), (-z, -x, 0.0));
tindices: array [0 .. 19, 0 .. 2] of glInt = ( // 20 faces
(0, 4, 1), (0, 9, 4), (9, 5, 4), (4, 5, 8), (4, 8, 1), (8, 10, 1),
(8, 3, 10), (5, 3, 8), (5, 2, 3), (2, 7, 3), (7, 10, 3), (7, 6, 10),
(7, 11, 6), (11, 0, 6), (0, 1, 6), (6, 1, 10), (9, 0, 11), (9, 11, 2),
(9, 2, 5), (7, 2, 11));
var
i: integer;
begin
for i := 0 to 19 do
begin
Subdivide(vdata[tindices[i, 0], 0], vdata[tindices[i, 1], 0],
vdata[tindices[i, 2], 0], Depth);
end; // for
end;
function BuildPotatoid(var Mesh: TMeshObject; const Deviance: single = 0.2;
const Depth: integer = 1; ActualDepth: integer = -1): boolean;
{ Fractal process to build a random potatoid. Depth correspond to the depth
of the recursive process. Use ActualDepth to generate a same potatoid at
various level of details }
const
Reduction = 2;
type
pEdge = ^tEdge;
tEdge = record
c1, c2: pEdge;
r: single;
end; // record
var
i, j: integer;
vdata2: array [0 .. 11, 0 .. 2] of single;
rr: single;
Edges: array [0 .. 11, 0 .. 11] of pEdge;
i0, i1, i2: integer;
DeltaDepth: integer;
procedure SubdividePotatoid(const v1, v2, v3: array of single;
Edges: array of pEdge; const Deviance: single; const Depth: integer);
var
v12, v23, v31: array [0 .. 2] of single;
i: integer;
inEdges: array [0 .. 2] of pEdge;
begin
if Depth = DeltaDepth then
SpheroidAddTriangle(Mesh, v1, v2, v3);
if Depth > -DeltaDepth then
begin
for i := 0 to 2 do
begin
v12[i] := (v1[i] + v2[i]) / 2;
v23[i] := (v2[i] + v3[i]) / 2;
v31[i] := (v3[i] + v1[i]) / 2;
end; // for
for i := 0 to 2 do
begin
v12[i] := v12[i] * Edges[0]^.r; // Apply the deviance
v31[i] := v31[i] * Edges[1]^.r;
v23[i] := v23[i] * Edges[2]^.r;
if Edges[i]^.c1 = nil then
begin
New(Edges[i]^.c1);
Edges[i]^.c1^.r := exp((random * 2 - 1) * (Deviance / Reduction));
// New division of the Edges
Edges[i]^.c1^.c1 := nil;
Edges[i]^.c1^.c2 := nil;
New(Edges[i]^.c2);
Edges[i]^.c2^.r := Edges[i]^.c1^.r; // New division of the Edges
Edges[i]^.c2^.c1 := nil;
Edges[i]^.c2^.c2 := nil;
end; // i
New(inEdges[i]);
inEdges[i]^.r := exp((random * 2 - 1) * (Deviance / Reduction));
inEdges[i]^.c1 := nil;
inEdges[i]^.c2 := nil;
end; // for
SubdividePotatoid(v1, v12, v31, [Edges[0]^.c1, Edges[1]^.c1, inEdges[0]],
Deviance / Reduction, Depth - 1);
SubdividePotatoid(v2, v23, v12, [Edges[2]^.c1, Edges[0]^.c2, inEdges[1]],
Deviance / Reduction, Depth - 1);
SubdividePotatoid(v3, v31, v23, [Edges[1]^.c2, Edges[2]^.c2, inEdges[2]],
Deviance / Reduction, Depth - 1);
SubdividePotatoid(v12, v23, v31, [inEdges[1], inEdges[0], inEdges[2]],
Deviance / Reduction, Depth - 1);
Dispose(inEdges[0]);
Dispose(inEdges[1]);
Dispose(inEdges[2]);
end; // else
end;
procedure DisposeEdge(Edge: pEdge);
begin
if Edge^.c1 <> nil then
DisposeEdge(Edge^.c1);
if Edge^.c2 <> nil then
DisposeEdge(Edge^.c2);
Dispose(Edge);
end;
const
x = 0.525731112119133606; // Chosen for a radius-1 icosahedron
z = 0.850650808352039932; //
vdata: array [0 .. 11, 0 .. 2] of single = ( // 12 vertices
(-x, 0.0, z), (x, 0.0, z), (-x, 0.0, -z), (x, 0.0, -z), (0.0, z, x),
(0.0, z, -x), (0.0, -z, x), (0.0, -z, -x), (z, x, 0.0), (-z, x, 0.0),
(z, -x, 0.0), (-z, -x, 0.0));
tindices: array [0 .. 19, 0 .. 2] of glInt = ( // 20 faces
(0, 4, 1), (0, 9, 4), (9, 5, 4), (4, 5, 8), (4, 8, 1), (8, 10, 1),
(8, 3, 10), (5, 3, 8), (5, 2, 3), (2, 7, 3), (7, 10, 3), (7, 6, 10),
(7, 11, 6), (11, 0, 6), (0, 1, 6), (6, 1, 10), (9, 0, 11), (9, 11, 2),
(9, 2, 5), (7, 2, 11));
begin
{ Result:=False; }
if ActualDepth < Depth then
ActualDepth := Depth;
DeltaDepth := ActualDepth - Depth;
Mesh.Mode := momTriangles;
Mesh.Vertices.Clear;
Mesh.Normals.Clear;
Mesh.TexCoords.Clear;
for i := 0 to 11 do
begin // randomize vertices
rr := exp((random * 2 - 1) * (Deviance));
for j := 0 to 2 do
vdata2[i, j] := vdata[i, j] * rr;
end; // for i
try
for i := 1 to 11 do
begin // randomize Edges
for j := 0 to i - 1 do
begin
New(Edges[i, j]);
Edges[i, j]^.r := exp((random * 2 - 1) * (Deviance / Reduction));
Edges[j, i] := Edges[i, j];
Edges[i, j]^.c1 := nil;
Edges[i, j]^.c2 := nil;
end; // for
end; // for i
for i := 0 to 19 do
begin // Draw triangles
i0 := tindices[i, 0];
i1 := tindices[i, 1];
i2 := tindices[i, 2];
SubdividePotatoid(Slice(vdata2[i0], 3), Slice(vdata2[i1], 3),
Slice(vdata2[i2], 3), [Edges[i0, i1], Edges[i0, i2], Edges[i1, i2]],
Deviance / Reduction, ActualDepth);
end; // for
finally
for i := 1 to 11 do
begin // Dispose of pointers
for j := 0 to i - 1 do
begin
DisposeEdge(Edges[i, j]);
end; // for
end; // for i
end; // finally
Result := True;
end;
{ *********************************************************************** }
{ *********************************************************************** }
{ CAMERA OBJECT
{*********************************************************************** }
{ *********************************************************************** }
{ tMovingCamera }
procedure tMovingCamera.Accelerate(const au, av, an: single);
begin
sx := sx + au * ux + av * vx + an * nx;
sy := sy + au * uy + av * vy + an * ny;
sz := sz + au * uz + av * vz + an * nz;
end;
procedure tMovingCamera.Apply;
{ dx, dy and dz must have been computed beforehand }
begin
with GLobject do
begin
Position.SetVector(x, y, z);
Direction.SetVector(nx, ny, nz);
Up.SetVector(vx, vy, vz);
end; // with
end;
procedure tMovingCamera.ApplyFrontView;
{ Z directed along the speed vector, X and Y are in the ship's horizontal plane }
var
{ sx1,sy1,sz1, } s: single;
begin
s := 1 / Speed;
SpeedMatrix[0] := ux;
SpeedMatrix[4] := vx;
SpeedMatrix[8] := sx * s;
SpeedMatrix[12] := x;
SpeedMatrix[1] := uy;
SpeedMatrix[5] := vy;
SpeedMatrix[9] := sy * s;
SpeedMatrix[13] := y;
SpeedMatrix[2] := uz;
SpeedMatrix[6] := vz;
SpeedMatrix[10] := sz * s;
SpeedMatrix[14] := z;
SpeedMatrix[3] := 0;
SpeedMatrix[7] := 0;
SpeedMatrix[11] := 0;
SpeedMatrix[15] := 1;
glMultMatrixf(@SpeedMatrix);
end;
procedure tMovingCamera.ComputeSpeed;
begin
Speed := sqrt(sqr(sx) + sqr(sy) + sqr(sz));
end;
constructor tMovingCamera.Create;
begin
inherited Create;
ResetAttitude;
end;
destructor tMovingCamera.Destroy;
begin
inherited Destroy;
end;
procedure tMovingCamera.GoThatWay;
begin
sx := nx * Speed;
sy := ny * Speed;
sz := nz * Speed;
end;
procedure tMovingCamera.Move(const du, dv, dn: single);
begin
x := x + (du * ux + dv * vx + dn * nx);
y := y + (du * uy + dv * vy + dn * ny);
z := z + (du * uz + dv * vz + dn * nz);
end;
procedure tMovingCamera.Pitch(const Angle: single);
var
tempx, tempy, tempz: single;
cosine, sine: double;
begin
tempx := vx;
tempy := vy;
tempz := vz;
SinCosine(DegToRadian(Angle), sine, cosine);
vx := tempx * cosine - nx * sine;
vy := tempy * cosine - ny * sine;
vz := tempz * cosine - nz * sine;
nx := tempx * sine + nx * cosine;
ny := tempy * sine + ny * cosine;
nz := tempz * sine + nz * cosine;
end;
procedure tMovingCamera.ResetAttitude;
begin
ux := 1;
uy := 0;
uz := 0;
vx := 0;
vy := 1;
vz := 0;
nx := 0;
ny := 0;
nz := -1;
end;
procedure tMovingCamera.Roll(const Angle: single);
var
tempx, tempy, tempz: single;
cosine, sine: double;
begin
tempx := ux;
tempy := uy;
tempz := uz;
SinCosine(DegToRadian(Angle), sine, cosine);
ux := tempx * cosine - vx * sine;
uy := tempy * cosine - vy * sine;
uz := tempz * cosine - vz * sine;
vx := tempx * sine + vx * cosine;
vy := tempy * sine + vy * cosine;
vz := tempz * sine + vz * cosine;
end;
procedure tMovingCamera.Translate(const dx, dy, dz: single);
begin
x := x + dx;
y := y + dy;
z := z + dz;
end;
procedure tMovingCamera.UpdateAll(const Time: double);
begin
UpdatePosition(Time);
UpdateAttitude(Time);
end;
procedure tMovingCamera.UpdateAttitude(const Time: double);
begin
Pitch(ru * Time);
Yaw(rv * Time);
Roll(rn * Time);
end;
procedure tMovingCamera.UpdatePosition(const Time: double);
begin
Translate(sx * Time, sy * Time, sz * Time);
end;
procedure tMovingCamera.Yaw(const Angle: single);
var
tempx, tempy, tempz: single;
cosine, sine: double;
begin
tempx := ux;
tempy := uy;
tempz := uz;
SinCosine(DegToRadian(Angle), sine, cosine);
ux := tempx * cosine + nx * sine;
uy := tempy * cosine + ny * sine;
uz := tempz * cosine + nz * sine;
nx := -tempx * sine + nx * cosine;
ny := -tempy * sine + ny * cosine;
nz := -tempz * sine + nz * cosine;
end;
{ tRealMovingCamera }
procedure tRealMovingCamera.Apply;
begin
with GLobject do
begin
Position.x := x + Vibx;
Position.y := y + Viby;
Position.z := z + Vibz;
Direction.SetVector(nx, ny, nz);
Up.SetVector(vx, vy, vz);
end; // with
Vibx := 0;
Viby := 0;
Vibz := 0;
end;
procedure tRealMovingCamera.GyroPitch(const Moment: single);
{ Input axis: U }
var
dWu, dWv, dWn: single; // Rotation acceleration
Ini, Ino, Inr: single; // Inertia along input, output and rotor axes
ri, ro, rr: single; // Rotation speeds on each axis
begin
Ini := InU;
ri := DegToRadian(ru);
{ Rotor axis: V, Output axis: N }
Inr := InV;
rr := DegToRadian(rv);
Ino := InN;
ro := DegToRadian(rn);
dWu := (Moment - (Inr - Ino) * rr * ro) / InU;
dWn := (-(Ini - Inr) * ri * rr) / InN;
{ Rotor axis: N, Output axis: V }
Inr := InN;
rr := DegToRadian(rn);
Ino := InV;
ro := DegToRadian(rv);
dWu := dWu + (Moment - (Inr - Ino) * rr * ro) / InU;
dWv := -(Ini - Inr) * ri * rr / InV;
ru := ru + RadianToDeg(dWu);
rv := rv + RadianToDeg(dWv);
rn := rn + RadianToDeg(dWn);
end;
procedure tRealMovingCamera.GyroRoll(const Moment: single);
{ Input axis: N }
var
dWu, dWv, dWn: single; // Rotation acceleration
Ini, Ino, Inr: single; // Inertia along input, output and rotor axes
ri, ro, rr: single; // Rotation speeds on each axis
begin
Ini := InN;
ri := DegToRadian(rn);
{ Rotor axis: V, Output axis: U }
Inr := InV;
rr := DegToRadian(rv);
Ino := InU;
ro := DegToRadian(ru);
dWn := (Moment - (Inr - Ino) * rr * ro) / InN;
dWu := (-(Ini - Inr) * ri * rr) / InU;
{ Rotor axis: U, Output axis: V }
Inr := InU;
rr := DegToRadian(ru);
Ino := InV;
ro := DegToRadian(rv);
dWn := dWn + (Moment - (Inr - Ino) * rr * ro) / InN;
dWv := -(Ini - Inr) * ri * rr / InV;
ru := ru + RadianToDeg(dWu);
rv := rv + RadianToDeg(dWv);
rn := rn + RadianToDeg(dWn);
end;
procedure tRealMovingCamera.GyroYaw(const Moment: single);
{ Input axis: V }
var
dWu, dWv, dWn: single; // Rotation acceleration
Ini, Ino, Inr: single; // Inertia along input, output and rotor axes
ri, ro, rr: single; // Rotation speeds on each axis
begin
Ini := InV;
ri := DegToRadian(rv);
{ Rotor axis: U, Output axis: N }
Inr := InU;
rr := DegToRadian(ru);
Ino := InN;
ro := DegToRadian(rn);
dWv := (Moment - (Inr - Ino) * rr * ro) / InV;
dWn := (-(Ini - Inr) * ri * rr) / InN;
{ Rotor axis: N, Output axis: U }
Inr := InN;
rr := DegToRadian(rn);
Ino := InU;
ro := DegToRadian(ru);
dWv := dWv + (Moment - (Inr - Ino) * rr * ro) / InV;
dWu := -(Ini - Inr) * ri * rr / InU;
ru := ru + RadianToDeg(dWu);
rv := rv + RadianToDeg(dWv);
rn := rn + RadianToDeg(dWn);
end;
procedure tRealMovingCamera.Vibrate(const Vibration: single);
begin
Vibx := random * 2 * Vibration - Vibration;
Viby := random * 2 * Vibration - Vibration;
Vibz := random * 2 * Vibration - Vibration;
end;
end.
|
unit uFrmPagaVendedor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
PAIDETODOS, DBCtrls, DateBox, Db, DBTables, Grids,
StdCtrls, Mask, ComCtrls, LblEffct, ExtCtrls, Buttons,
Menus, ADODB, SuperComboADO, ppProd, ppClass, ppReport, ppComm, ppRelatv, ppDB,
ppDBPipe, ppModule, raCodMod, ppBands, ppCache, ppPrnabl, ppCtrls,
daDataModule, DBGrids, ppVar, siComp, siLangRT, SMDBGrid, ppEndUsr;
type
TFrmPagaVendedor = class(TFrmParent)
dsHistPag: TDataSource;
quHistPag: TADOQuery;
Panel10: TPanel;
lblTip: TLabel;
Label3: TLabel;
Panel4: TPanel;
Panel11: TPanel;
spPayCommission: TADOStoredProc;
Label11: TLabel;
btPrint: TSpeedButton;
spDelPayComiss: TADOStoredProc;
mnuPayment: TPopupMenu;
DeletePayment1: TMenuItem;
quHistPagDataLancamento: TDateTimeField;
quHistPagIDLancamento: TIntegerField;
spHelp: TSpeedButton;
quHistPagValorNominal: TFloatField;
quSalesPersonCommis: TADOQuery;
quSalesPersonCommisIDInvoice: TIntegerField;
quSalesPersonCommisFirstName: TStringField;
quSalesPersonCommisLastName: TStringField;
quSalesPersonCommisInvoiceDate: TDateTimeField;
quSalesPersonCommisMovSale: TBCDField;
quSalesPersonCommisMovCost: TBCDField;
quSalesPersonCommisModel: TStringField;
quSalesPersonCommisDescription: TStringField;
quSalesPersonCommisMovCommission: TBCDField;
dsSalesPersonCommis: TDataSource;
ppSalesPersonCommis: TppDBPipeline;
quSalesPersonCommisSalesPerson: TStringField;
Panel5: TPanel;
Label4: TLabel;
Label12: TLabel;
Label13: TLabel;
Shape1: TShape;
Label16: TLabel;
Label17: TLabel;
Label20: TLabel;
Label24: TLabel;
Adjusted: TLabel;
pnlInicio: TPanel;
Label25: TLabel;
Label26: TLabel;
Panel6: TPanel;
scPessoa: TSuperComboADO;
editPayDate: TDateBox;
dbInicio: TDateBox;
dbFim: TDateBox;
btRefresh: TSpeedButton;
Label1: TLabel;
editCommission: TEdit;
Label19: TLabel;
Label9: TLabel;
editExtorno: TEdit;
editCorrecao: TEdit;
editValor: TEdit;
rpSalesPerson: TppReport;
ppHeaderBand2: TppHeaderBand;
ppLabel14: TppLabel;
ppLabel15: TppLabel;
ppDetailBand2: TppDetailBand;
ppDBText10: TppDBText;
ppDBText11: TppDBText;
ppDBText12: TppDBText;
ppDBText13: TppDBText;
ppDBText14: TppDBText;
ppDBText15: TppDBText;
ppFooterBand2: TppFooterBand;
ppGroup3: TppGroup;
ppGroupHeaderBand3: TppGroupHeaderBand;
ppDBText16: TppDBText;
ppGroupFooterBand3: TppGroupFooterBand;
ppDBCalc7: TppDBCalc;
ppDBCalc8: TppDBCalc;
ppDBCalc9: TppDBCalc;
ppGroup4: TppGroup;
ppGroupHeaderBand4: TppGroupHeaderBand;
ppDBText17: TppDBText;
ppDBText18: TppDBText;
ppLine2: TppLine;
ppDBText19: TppDBText;
ppGroupFooterBand4: TppGroupFooterBand;
ppDBCalc10: TppDBCalc;
ppDBCalc11: TppDBCalc;
ppDBCalc12: TppDBCalc;
raCodeModule1: TraCodeModule;
daDataModule2: TdaDataModule;
spCalcComiss: TADOStoredProc;
quHistPagUsuario: TStringField;
Label6: TLabel;
Label7: TLabel;
sbPaymentType: TSuperComboADO;
scBanckAccount: TSuperComboADO;
Label5: TLabel;
Label2: TLabel;
btPreviewCommission: TSpeedButton;
btAddCommission: TSpeedButton;
ppLabel1: TppLabel;
ppLabel2: TppLabel;
ppLabel3: TppLabel;
ppLabel4: TppLabel;
ppLabel5: TppLabel;
ppLabel10: TppLabel;
ppLine1: TppLine;
ppLabel6: TppLabel;
ppSystemVariable2: TppSystemVariable;
ppLabel7: TppLabel;
grdPayment: TSMDBGrid;
ppDesigner: TppDesigner;
quSPCommisAll: TADOQuery;
quSPCommisAllIDInvoice: TIntegerField;
quSPCommisAllFirstName: TStringField;
quSPCommisAllLastName: TStringField;
quSPCommisAllSalesPerson: TStringField;
quSPCommisAllInvoiceDate: TDateTimeField;
quSPCommisAllMovSale: TBCDField;
quSPCommisAllMovCost: TBCDField;
quSPCommisAllModel: TStringField;
quSPCommisAllDescription: TStringField;
quSPCommisAllMovCommission: TBCDField;
quSalesPersonCommisSaleCode: TStringField;
quSalesPersonCommisInvoiceCode: TStringField;
quSPCommisAllSaleCode: TStringField;
quSPCommisAllInvoiceCode: TStringField;
quSalesPersonCommisPreSaleDate: TDateTimeField;
quSPCommisAllPreSaleDate: TDateTimeField;
quSalesPersonCommisDesiredMarkup: TBCDField;
quSPCommisAllDesiredMarkup: TBCDField;
quSPCommisAllMarkup: TBCDField;
quSalesPersonCommisMarkup: TBCDField;
quSPCommisAllItemNetValue: TBCDField;
quSalesPersonCommisItemNetValue: TBCDField;
quSPCommisAllGroupID: TIntegerField;
quSPCommisAllService: TBooleanField;
quSalesPersonCommisDiscount: TBCDField;
quSPCommisAllDiscount: TBCDField;
quSalesPersonCommisQty: TFloatField;
quSPCommisAllQty: TFloatField;
quSalesPersonCommisFullName: TStringField;
quSPCommisAllFullName: TStringField;
ppSalesPersonCommisppField21: TppField;
procedure FormShow(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure dbInicioChange(Sender: TObject);
procedure btPrintClick(Sender: TObject);
procedure dsHistPagDataChange(Sender: TObject; Field: TField);
procedure DeletePayment1Click(Sender: TObject);
procedure btRefreshClick(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure grdPaymentDblClick(Sender: TObject);
procedure btAddCommissionClick(Sender: TObject);
procedure rpSalesPersonPreviewFormCreate(Sender: TObject);
procedure btPreviewCommissionClick(Sender: TObject);
procedure sbPaymentTypeSelectItem(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure scPessoaSelectItem(Sender: TObject);
private
Extorno, Correcao, Commis, Valor: Currency;
Inside: Boolean;
Merda: Boolean;
bIsOffice: Boolean;
bCommOnPaid: Boolean;
procedure Refresh;
procedure SPRefreshWhere(sWhere: String);
procedure PrintSalesPerson(iPaid: Integer);
procedure HistPagClose;
procedure HistPagOpen;
procedure HistPagRefresh;
public
function DesignReport:Boolean;
end;
implementation
uses uDM, XBase, uPrintComissReceipt, uMsgBox, uMsgConstant, uPassword,
uNumericFunctions, uSqlFunctions, uDateTimeFunctions, uDMGlobal,
uSystemConst;
{$R *.DFM}
procedure TFrmPagaVendedor.HistPagClose;
begin
with quHistPag do
if Active then
Close;
end;
procedure TFrmPagaVendedor.HistPagOpen;
begin
with quHistPag do
if not Active then
begin
Parameters.ParambyName('IDPessoa').Value := StrToInt(scPessoa.LookUpValue);
Open;
end;
end;
procedure TFrmPagaVendedor.HistPagRefresh;
begin
HistPagClose;
HistPagOpen;
end;
procedure TFrmPagaVendedor.PrintSalesPerson(iPaid: Integer);
var
i: Integer;
sWhere, sPaidField: String;
sWhereClause: TStringList;
begin
sWhereClause := TStringList.Create;
try
if not bIsOffice then
begin
sWhereClause.Add(' I.IDInvoice IS NOT NULL');
sWhereClause.Add(' I.InvoiceDate >= ' + QuotedStr( FormatDateTime('mm/dd/yyyy', (dbInicio.Date))));
sWhereClause.Add(' I.InvoiceDate < ' + QuotedStr( FormatDateTime('mm/dd/yyyy', (dbFim.Date+1))));
sPaidField := ' CP.IDLancPag ';
end
else
begin
sPaidField := ' CP.IDLancPag ';
if iPaid = 0 then
begin
sWhereClause.Add(' I.PreSaleDate >= ' + QuotedStr( FormatDateTime('mm/dd/yyyy', (dbInicio.Date))));
sWhereClause.Add(' I.PreSaleDate < ' + QuotedStr( FormatDateTime('mm/dd/yyyy', (dbFim.Date+1))));
end;
end;
if iPaid = 0 then
sWhereClause.Add(sPaidField+' IS NULL')
else
sWhereClause.Add(sPaidField+' = ' + IntToStr(iPaid));
sWhereClause.Add(' C.ComissionID = ' + scPessoa.LookUpValue);
sWhereClause.Add(' IsNull(I.Canceled, 0) = 0 ');
if bIsOffice and bCommOnPaid then
sWhereClause.Add(' IDPreSale IN (SELECT IDPreSale FROM Fin_Lancamento (NOLOCK) ) ');
for i := 0 to sWhereClause.Count-1 do
if i = 0 then
sWhere := sWhereClause.Strings[i]
else
sWhere := sWhere + ' AND ' + sWhereClause.Strings[i];
finally
FreeAndNil(sWhereClause);
end;
SPRefreshWhere(sWhere);
if DM.fPrintReceipt.CommissionReportPreview then
rpSalesPerson.DeviceType := 'Screen'
else
rpSalesPerson.DeviceType := 'Printer';
rpSalesPerson.PrinterSetup.Copies := DM.fPrintReceipt.CommissionReportNumCopy;
if DM.fPrintReceipt.CommissionReportPath <> '[SYSTEM]' then
if FileExists(DM.fPrintReceipt.CommissionReportPath) then
begin
rpSalesPerson.Template.FileName := DM.fPrintReceipt.CommissionReportPath;
rpSalesPerson.Template.LoadFromFile;
end;
if DM.fPrintReceipt.CommissionReportPrinter <> '' then
rpSalesPerson.PrinterSetup.PrinterName := DM.fPrintReceipt.CommissionReportPrinter;
try
rpSalesPerson.Print;
except
raise;
end;
end;
procedure TFrmPagaVendedor.SPRefreshWhere(sWhere: String);
var
sOldSQL: String;
begin
with TADOQuery(dsSalesPersonCommis.DataSet) do
begin
Close;
sOldSQL := SQL.Text;
SQL.Clear;
SQL.Text := ChangeWhereClause(sOldSQL, sWhere, True);
Parameters.ParamByName('IDVendedor').Value := StrToInt(scPessoa.LookUpValue);
Open;
end;
end;
procedure TFrmPagaVendedor.Refresh;
begin
if Merda then
Abort;
// Se uma das datas for em branco aborta
if scPessoa.LookUpValue = '' then
begin
MsgBox(MSG_INF_CHOOSE_NAME, vbOKOnly + vbInformation);
scPessoa.SetFocus;
Abort;
end;
Screen.Cursor := crHourGlass;
// Refresh do Historio de Pagamentos
HistPagRefresh;
// Recalculo do valor da comissão
with spCalcComiss do
begin
Parameters.ParambyName('@IDVendedor').Value := StrToInt(scPessoa.LookUpValue);
Parameters.ParambyName('@DataInicio').Value := dbInicio.Date;
Parameters.ParambyName('@DataFim').Value := dbFim.Date+1;
Parameters.ParambyName('@IsPre').Value := bIsOffice;
Parameters.ParambyName('@IsPaid').Value := bCommOnPaid;
ExecProc;
Commis := Parameters.ParambyName('@Commission').Value;
Extorno := Parameters.ParambyName('@Extorno').Value;
Correcao := Parameters.ParambyName('@Correcao').Value;
Valor := MyRound(Commis - Extorno + Correcao, 2);
editCommission.Text := FloatToStrF(Commis, ffCurrency, 20, 2);
editExtorno.Text := FloatToStrF(Extorno, ffCurrency, 20, 2);
editCorrecao.Text := FloatToStrF(Correcao, ffCurrency, 20, 2);
editValor.Text := MyFloatToStr(valor);
end;
btAddCommission.Enabled := Valor <> 0;
btPreviewCommission.Enabled := Valor <> 0;
Screen.Cursor := crDefault;
end;
procedure TFrmPagaVendedor.FormShow(Sender: TObject);
var
Day, Month, Year: Word;
begin
inherited;
Merda := True;
if DM.fSystem.SrvParam[PARAM_TREAT_HOLD_AS_INVOICE] then
begin
dbInicio.Date := FirstDateMonth;
dbFim.Date := LastDateMonth;
end
else
begin
DecodeDate(Date, Year, Month, Day);
editPayDate.Date := Date;
dbFim.Date := EncodeDate(Year, Month, 1) - 1;
if Month = 1 then
begin
Month := 12;
Year := Year - 1;
end
else
begin
Month := Month -1;
end;
dbInicio.Date := EncodeDate(Year, Month, 1);
end;
Merda := False;
scPessoa.SetFocus;
sbPaymentType.LookUpValue := '1';
scBanckAccount.LookUpValue := IntToStr(DM.GetContaCorrente(MyStrToInt('1'), DM.fStore.ID));
//Funcao para nao ver commissoes de outros funcionarios
if not Password.HasFuncRight(50) then
begin
scPessoa.LookUpValue := IntToStr(DM.fUser.IDCommission);
scPessoa.Enabled := False;
btAddCommission.Visible := False;
dbInicio.SetFocus;
end;
bIsOffice := not DM.fSystem.SrvParam[PARAM_CALC_COMMISSION_ON_INVOICE];
bCommOnPaid := DM.fSystem.SrvParam[PARAM_CALC_COMM_ON_PAID_HOLD];
if bIsOffice then
dsSalesPersonCommis.DataSet := quSPCommisAll
else
dsSalesPersonCommis.DataSet := quSalesPersonCommis;
end;
procedure TFrmPagaVendedor.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmPagaVendedor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
scPessoa.SpcWhereClause := '';
HistPagClose;
Action := caFree;
end;
procedure TFrmPagaVendedor.dbInicioChange(Sender: TObject);
begin
inherited;
if TestDate(dbInicio.Text) then
begin
//#Rod - Trunc
spCalcComiss.Parameters.ParambyName('@DataInicio').Value := Int(dbInicio.Date);
end;
if TestDate(dbFim.Text) then
begin
spCalcComiss.Parameters.ParambyName('@DataFim').Value := Int(dbFim.Date) + 1;
end;
end;
procedure TFrmPagaVendedor.btPrintClick(Sender: TObject);
begin
inherited;
if MsgBox(MSG_QST_CONFIRM_REPRINT, vbYesNo + vbQuestion) = vbNo then
Exit;
// Imprime recibo
with TPrintComissReceipt.Create(Self) do
Start(quHistPagIDLancamento.AsInteger, COMIS_SALESPRSON, True);
end;
procedure TFrmPagaVendedor.dsHistPagDataChange(Sender: TObject;
Field: TField);
begin
inherited;
btPrint.Enabled := not (quHistPag.EOF and quHistPag.BOF);
end;
procedure TFrmPagaVendedor.DeletePayment1Click(Sender: TObject);
begin
inherited;
if MsgBox(MSG_QST_DELETE, vbYesNo + vbQuestion) = vbYes then
begin
with spDelPayComiss do
begin
Parameters.ParambyName('@IDVendedor').Value := StrToInt(scPessoa.LookUpValue);
Parameters.ParambyName('@IDLancamento').Value := quHistPagIDLancamento.AsInteger;
ExecProc;
end;
Refresh;
end;
end;
procedure TFrmPagaVendedor.btRefreshClick(Sender: TObject);
begin
inherited;
if TestDate(dbFim.Text) or TestDate(dbInicio.Text) then
Refresh;
end;
procedure TFrmPagaVendedor.spHelpClick(Sender: TObject);
begin
inherited;
Application.HelpContext(1880);
end;
procedure TFrmPagaVendedor.grdPaymentDblClick(Sender: TObject);
begin
inherited;
Screen.Cursor := crHourGlass;
with quHistPag do
if not (EOF and BOF) then
PrintSalesPerson(quHistPagIDLancamento.AsInteger);
Screen.Cursor := crDefault;
end;
procedure TFrmPagaVendedor.btAddCommissionClick(Sender: TObject);
var
MyValor: Double;
iIDLanc: integer;
begin
inherited;
MyValor := MyStrToFloat(editValor.text);
if MyRound(MyValor, 2) = 0 then
begin
MsgBox(MSG_INF_NOT_EMPTY_VALUES, vbOKOnly + vbInformation);
Exit;
end;
if sbPaymentType.LookUpValue = '' then
begin
MsgBox(MSG_INF_CHOOSE_PAYTYPE, vbOKOnly + vbInformation);
sbPaymentType.SetFocus;
Exit;
end;
if scBanckAccount.LookUpValue = '' then
begin
MsgBox(MSG_INF_CHOOSE_BANK, vbOKOnly + vbInformation);
scBanckAccount.SetFocus;
Exit;
end;
if editPayDate.Text = '' then
begin
MsgBox(MSG_CRT_NO_DATE, vbOKOnly + vbInformation);
editPayDate.SetFocus;
Exit;
end;
if MsgBox(MSG_QST_CONFIRM_PAYMENT, vbYesNo + vbQuestion) = vbNo then
Exit;
with spPayCommission do
begin
Parameters.ParambyName('@IDVendedor').Value := StrToInt(scPessoa.LookUpValue);
Parameters.ParambyName('@IDStore').Value := DM.fStore.ID;
Parameters.ParambyName('@IDMeioPag').Value := MyStrToInt(sbPaymentType.LookUpValue);
Parameters.ParambyName('@IDContaCorrente').Value := MyStrToInt(scBanckAccount.LookUpValue);
Parameters.ParambyName('@PayDate').Value := editPayDate.Date;
Parameters.ParambyName('@Commission').Value := MyValor;
Parameters.ParambyName('@DataIni').Value := spCalcComiss.Parameters.ParambyName('@DataInicio').Value;
Parameters.ParambyName('@DataFim').Value := spCalcComiss.Parameters.ParambyName('@DataFim').Value;
Parameters.ParambyName('@IDUser').Value := DM.fUser.ID;
Parameters.ParambyName('@IsPre').Value := bIsOffice;
Parameters.ParambyName('@IsPaid').Value := bCommOnPaid;
ExecProc;
end;
MsgBox(MSG_INF_PART1_COMMISS_PAIED + editValor.text + MSG_INF_PART2_COMMISS_PAIED, vbOKOnly + vbInformation);
Refresh;
// Imprime recibo
if MsgBox(MSG_QST_CONFIRM_PRINT_RECEIPET, vbYesNo + vbQuestion) = vbYes then
with TPrintComissReceipt.Create(Self) do
Start(spPayCommission.Parameters.ParambyName('@IDLancamento').Value, COMIS_SALESPRSON, False);
end;
procedure TFrmPagaVendedor.rpSalesPersonPreviewFormCreate(Sender: TObject);
begin
inherited;
rpSalesPerson.PreviewForm.WindowState := WSMAXIMIZED;
end;
procedure TFrmPagaVendedor.btPreviewCommissionClick(Sender: TObject);
begin
inherited;
PrintSalesPerson(0);
end;
procedure TFrmPagaVendedor.sbPaymentTypeSelectItem(Sender: TObject);
begin
inherited;
if sbPaymentType.LookUpValue <> '' then
scBanckAccount.LookUpValue := IntToStr(DM.GetContaCorrente(MyStrToInt(sbPaymentType.LookUpValue), DM.fStore.ID));
end;
procedure TFrmPagaVendedor.FormCreate(Sender: TObject);
begin
inherited;
if fIsRestricForm then
begin
btAddCommission.Visible := False;
DeletePayment1.Enabled := False;
end;
end;
function TFrmPagaVendedor.DesignReport: Boolean;
begin
Result := True;
try
ppDesigner.ShowModal;
except
Result := False;
end;
end;
procedure TFrmPagaVendedor.scPessoaSelectItem(Sender: TObject);
var
i, j: Integer;
sStores,
sUser: TStringList;
CanView: Boolean;
begin
inherited;
//Ver comissoes de outras lojas
if (not Password.HasFuncRight(51)) then
begin
if (scPessoa.LookUpValue = '') then
Exit;
try
sStores := TStringList.Create;
sUser := TStringList.Create;
CanView := False;
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('Select StoresAccess From SystemUser (NOLOCK) Where ComissionID = ' + scPessoa.LookUpValue);
Open;
sStores.CommaText := Fields[0].AsString;
Close;
end;
sUser.CommaText := DM.fStore.StoreList;
sStores.Sort;
for i:=0 to sUser.Count-1 do
if sStores.Find(sUser.Strings[i], j) then
begin
CanView := True;
Break;
end;
finally
FreeAndNil(sStores);
FreeAndNil(sUser);
end;
if not CanView then
begin
scPessoa.LookUpValue := '';
scPessoa.Text := '';
MsgBox(MSG_CRT_OTHER_COMMISS_NOT_ALLOW, vbOKOnly + vbCritical);
end;
end;
end;
end.
|
unit Unit2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics,
Dialogs, ExtCtrls, StdCtrls,
ComCtrls, ColorBox;
type
TFigure = object
private
x, y: integer;
connect: TPaintBox;
public
procedure Init(a, b: integer; assoc: TPaintBox);
end;
TSquare = object(TFigure)
private
size: integer;
public
procedure Init(a, b, s: integer; assoc: TPaintBox);
procedure Draw(clr: TColor);
end;
TCircle = object(TFigure)
private
size: integer;
public
procedure Init(a, b, s: integer; assoc: TPaintBox);
procedure Draw(clr: TColor);
end;
implementation
procedure TFigure.Init(a, b: integer; assoc: TPaintBox);
begin
Self.x := a;
Self.y := b;
Self.connect := assoc;
end;
procedure TSquare.Init(a, b, s: integer; assoc: TPaintBox);
begin
inherited Init(a, b, assoc);
Self.size := s;
end;
procedure TSquare.Draw(clr: TColor);
begin
Self.connect.canvas.brush.color := clr;
Self.connect.canvas.rectangle(x, y, x + size, y + size);
end;
procedure TCircle.Init(a, b, s: integer; assoc: TPaintBox);
begin
inherited Init(a, b, assoc);
Self.size := s;
end;
procedure TCircle.Draw(clr: TColor);
begin
Self.connect.canvas.brush.color := clr;
Self.connect.canvas.ellipse(x, y, x + size, y + size);
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFDownLoadItem;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefDownLoadItemRef = class(TCefBaseRefCountedRef, ICefDownLoadItem)
protected
function IsValid: Boolean;
function IsInProgress: Boolean;
function IsComplete: Boolean;
function IsCanceled: Boolean;
function GetCurrentSpeed: Int64;
function GetPercentComplete: Integer;
function GetTotalBytes: Int64;
function GetReceivedBytes: Int64;
function GetStartTime: TDateTime;
function GetEndTime: TDateTime;
function GetFullPath: ustring;
function GetId: Cardinal;
function GetUrl: ustring;
function GetOriginalUrl: ustring;
function GetSuggestedFileName: ustring;
function GetContentDisposition: ustring;
function GetMimeType: ustring;
public
class function UnWrap(data: Pointer): ICefDownLoadItem;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
function TCefDownLoadItemRef.GetContentDisposition: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_content_disposition(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetCurrentSpeed: Int64;
begin
Result := PCefDownloadItem(FData)^.get_current_speed(PCefDownloadItem(FData));
end;
function TCefDownLoadItemRef.GetEndTime: TDateTime;
begin
Result := CefTimeToDateTime(PCefDownloadItem(FData)^.get_end_time(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetFullPath: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_full_path(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetId: Cardinal;
begin
Result := PCefDownloadItem(FData)^.get_id(PCefDownloadItem(FData));
end;
function TCefDownLoadItemRef.GetMimeType: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_mime_type(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetOriginalUrl: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_original_url(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetPercentComplete: Integer;
begin
Result := PCefDownloadItem(FData)^.get_percent_complete(PCefDownloadItem(FData));
end;
function TCefDownLoadItemRef.GetReceivedBytes: Int64;
begin
Result := PCefDownloadItem(FData)^.get_received_bytes(PCefDownloadItem(FData));
end;
function TCefDownLoadItemRef.GetStartTime: TDateTime;
begin
Result := CefTimeToDateTime(PCefDownloadItem(FData)^.get_start_time(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetSuggestedFileName: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_suggested_file_name(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.GetTotalBytes: Int64;
begin
Result := PCefDownloadItem(FData)^.get_total_bytes(PCefDownloadItem(FData));
end;
function TCefDownLoadItemRef.GetUrl: ustring;
begin
Result := CefStringFreeAndGet(PCefDownloadItem(FData)^.get_url(PCefDownloadItem(FData)));
end;
function TCefDownLoadItemRef.IsCanceled: Boolean;
begin
Result := PCefDownloadItem(FData)^.is_canceled(PCefDownloadItem(FData)) <> 0;
end;
function TCefDownLoadItemRef.IsComplete: Boolean;
begin
Result := PCefDownloadItem(FData)^.is_complete(PCefDownloadItem(FData)) <> 0;
end;
function TCefDownLoadItemRef.IsInProgress: Boolean;
begin
Result := PCefDownloadItem(FData)^.is_in_progress(PCefDownloadItem(FData)) <> 0;
end;
function TCefDownLoadItemRef.IsValid: Boolean;
begin
Result := PCefDownloadItem(FData)^.is_valid(PCefDownloadItem(FData)) <> 0;
end;
class function TCefDownLoadItemRef.UnWrap(data: Pointer): ICefDownLoadItem;
begin
if data <> nil then
Result := Create(data) as ICefDownLoadItem else
Result := nil;
end;
end.
|
unit uglobal;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,IniFiles;
// ;
var
// LAMW_SETTINGS: TIniFile;
//LAMW_MANAGER : TINIPROPE
// FILE CONFIGURATION NAME
LAMW_SETTINGS_PATH: String = 'lamw4linuxconfi.ini';
LAMW_SETTINGS_SECTION : String = 'LAMWManagerSettings';
// LAMW MANAGER DATA
BRIDGE_ROOT : string = 'bridge-root.sh';
LAMW_MAIN_SCRIPT : string = 'lamw-manager';
LAMW_PACKAGE_SCRIPT:string = 'lamw-package';
CLEAN_INSTALL_FLAG : boolean = false;
INSTALL_STATE : boolean = False;
USE_OLD_SDK : boolean = true;
LAMW_MGR_VERSION: string = 'LAMW Manager v0.3.0-testing'+sLineBreak+sLineBreak+'LAMW Manager is a command line tool,like APT, to automate the installation, configuration and upgrade the framework LAMW - Lazarus Android Module Wizard'+ sLineBreak + sLineBreak + 'Created by Daniel Oliveira'+sLineBreak + '2018-2019;
// PROXY SETTINGS
PROXY_SERVER : string = '';
PORT_SERVER : integer = 3128;
USE_AUTH_PROXY : boolean = false;
PASSWORD_PROXY : string ='';
//PROXY FLAGS
USE_PROXY : boolean = false;
TRANSPARENT_PROXY_FLAG : boolean = false;
ALTERNATIVE_PROXY_SET_FLAG : boolean = false;
AUTENTICATION_PROXY_FLAG : boolean = false;
implementation
{procedure initLAMWSettings;
var
aux : TStringList;
begin
if ( FileExists(GetCurrentDir + '/' + LAMW_SETTINGS_PATH) ) then
begin //carregar configurações
writeln('exists');
aux := TStringList.Create;
LAMW_SETTINGS :=TIniFile.Create(GetCurrentDir + '/' + LAMW_SETTINGS_PATH);
// LAMW_SETTINGS.FileName();
LAMW_SETTINGS.ReadSection(LAMW_SETTINGS_SECTION,aux);
writeln(aux.ToString());
end
else begin
writeln('not exists');
end;
end;
}
End.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 1995, 2001 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ Русификация: 1999-2002 Polaris Software }
{ http://polesoft.da.ru }
{ *************************************************************************** }
unit BrkrConst;
interface
resourcestring
sOnlyOneDataModuleAllowed = 'Допустим только один модуль данных на приложение';
sNoDataModulesRegistered = 'Не зарегистрировано ни одного модуля данных';
sNoDispatcherComponent = 'Не найдено ни одного компонента-диспетчера в модуле данных';
{$IFNDEF VER130}
sNoWebModulesActivated = 'Нет автоматически активированных модулей данных';
{$ENDIF}
sTooManyActiveConnections = 'Достигнут максимум конкурирующих соединений. ' +
'Повторите попытку позже';
sInternalServerError = '<html><title>Внутренняя Ошибка Сервера 500</title>'#13#10 +
'<h1>Внутренняя Ошибка Сервера 500</h1><hr>'#13#10 +
'Исключительная ситуация: %s<br>'#13#10 +
'Сообщение: %s<br></html>'#13#10;
sDocumentMoved = '<html><title>Документ перемещен 302</title>'#13#10 +
'<body><h1>Объект перемещен</h1><hr>'#13#10 +
'Этот объект может быть найден <a HREF="%s">здесь.</a><br>'#13#10 +
'<br></body></html>'#13#10;
implementation
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2021 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Core.OpenAPI;
interface
uses
System.SysUtils, System.Classes, System.JSON, System.Generics.Collections,
System.Rtti, System.RegularExpressions,
OpenAPI.Model.Classes,
OpenAPI.Model.Schema,
OpenAPI.Neon.Serializers,
Neon.Core.Types,
Neon.Core.Persistence,
Neon.Core.Persistence.JSON,
Neon.Core.Persistence.JSON.Schema,
Neon.Core.Serializers.RTL,
WiRL.Core.Declarations,
WiRL.Core.Exceptions,
WiRL.Core.Metadata,
WiRL.Core.Metadata.XMLDoc,
WiRL.Configuration.Auth,
WiRL.Configuration.Neon,
WiRL.Configuration.OpenAPI,
WiRL.Core.Application,
WiRL.http.Accept.MediaType,
WiRL.http.Filters;
type
TOpenAPIv3Engine = class
private
FDocument: TOpenAPIDocument;
FApplication: TWiRLApplication;
FConfigurationOpenAPI: TWiRLConfigurationOpenAPI;
FConfigurationNeon: TWiRLConfigurationNeon;
FSwaggerResource: string;
function AddOperation(AMethod: TWiRLProxyMethod; AOpenAPIPath: TOpenAPIPathItem; const ATagName: string): TOpenAPIOperation;
procedure AddResource(AResource: TWiRLProxyResource);
function CreateParameter(AParameter: TWiRLProxyParameter): TOpenAPIParameter;
protected
constructor Create(AApplication: TWiRLApplication; const ASwaggerResource: string); overload;
procedure ProcessXMLDoc;
function Build(): TJSONObject;
public
class function Generate(AApplication: TWiRLApplication; const ASwaggerResource: string): TJSONObject; overload;
end;
implementation
uses
System.StrUtils, System.TypInfo,
WiRL.Rtti.Utils,
WiRL.Core.Utils,
WiRL.http.Server;
{ TOpenAPIv3Engine }
function TOpenAPIv3Engine.Build: TJSONObject;
var
LRes: TWiRLProxyResource;
LPair: TPair<string, TWiRLProxyResource>;
begin
ProcessXMLDoc();
for LPair in FApplication.Proxy.Resources do
begin
LRes := LPair.Value;
case LRes.Auth.AuthType of
None: ;
Unknown: ;
Basic:
begin
FDocument.Components.AddSecurityHttp('basic_auth', 'Basic Authentication', 'basic', '');
FDocument.Components.AddSecurityHttp('jwt_auth', 'JWT (Bearer) Authentication', 'bearer', 'JWT');
end;
Cookie:
begin
FDocument.Components.AddSecurityApiKey('cookie_auth', 'Cookie Based authentication', LRes.Auth.HeaderName, TAPIKeyLocation.Cookie);
//FDocument.Components.AddSecurityHttp('jwt_auth', 'JWT (Bearer) Authentication', 'bearer', 'JWT');
end;
end;
end;
for LPair in FApplication.Proxy.Resources do
begin
LRes := LPair.Value;
if LRes.IsSwagger(FSwaggerResource) then
Continue;
// Adds a tag to the tags array
// Tags are a group (resource) of operations (methods)
FDocument.AddTag(LRes.Name, LRes.Summary);
FDocument.Components.AddSchema('Error')
.SetJSONFromClass(TWebExceptionSchema);
AddResource(LRes);
end;
Result := TNeon.ObjectToJSON(FDocument, TOpenAPISerializer.GetNeonConfig) as TJSONObject;
end;
constructor TOpenAPIv3Engine.Create(AApplication: TWiRLApplication; const ASwaggerResource: string);
begin
FSwaggerResource := ASwaggerResource;
FApplication := AApplication;
FConfigurationNeon := FApplication.GetConfiguration<TWiRLConfigurationNeon>;
FConfigurationOpenAPI := FApplication.GetConfiguration<TWiRLConfigurationOpenAPI>;
FDocument := FConfigurationOpenAPI.Document;
end;
function TOpenAPIv3Engine.AddOperation(AMethod: TWiRLProxyMethod;
AOpenAPIPath: TOpenAPIPathItem; const ATagName: string): TOpenAPIOperation;
var
LResponseStatus: TWiRLProxyMethodResponse;
LParam: TWiRLProxyParameter;
LProduce, LConsume: TMediaType;
LResponse: TOpenAPIResponse;
LMediaType: TOpenAPIMediaType;
LParameter: TOpenAPIParameter;
LRequestBody: TOpenAPIRequestBody;
begin
Result := AOpenAPIPath.AddOperation(TOperationType.FromString(AMethod.HttpVerb.ToLower));
Result.Summary := 'Function ' + AMethod.Name;
Result.Description := AMethod.Summary;
// Add a reference tag
Result.AddTag(ATagName);
// Describes input params
for LParam in AMethod.Params do
begin
// if it's BodyParam or FormParam then
// Add as requestBody
if LParam.Kind = TMethodParamType.Body then
begin
LRequestBody := Result.SetRequestBody(LParam.Summary);
// Add Request's MediaTypes (if param is BodyParam)
for LConsume in AMethod.Consumes do
begin
LMediaType := LRequestBody.AddMediaType(LConsume.Value);
if Assigned(LParam.Entity) then
begin
if not FDocument.Components.SchemaExists(LParam.Entity.Name) then
begin
FDocument.Components
.AddSchema(LParam.Entity.Name)
.SetJSONFromType(LParam.RttiParam.ParamType);
end;
LMediaType.Schema.SetSchemaReference(LParam.Entity.Name);
end
else
LMediaType.Schema.SetJSONFromType(LParam.RttiParam.ParamType);
end;
Continue;
end;
if LParam.Kind = TMethodParamType.MultiPart then
begin
{ TODO -opaolo -c : finire 09/06/2021 16:06:03 }
Continue;
end;
LParameter := CreateParameter(LParam);
AOpenAPIPath.Parameters.Add(LParameter);
end;
if AMethod.IsFunction then
begin
if not AMethod.Responses.Contains(TStatusCategory.Success) then
AMethod.Responses.AddResponse(200, AMethod.Summary);
if not AMethod.Responses.Contains(TStatusCategory.ClientError) or
not AMethod.Responses.Contains(TStatusCategory.ServerError) then
AMethod.Responses.AddResponse(500, 'Generic Server Error');
// ResponseStatus Attribute
for LResponseStatus in AMethod.Responses do
begin
LResponse := Result.AddResponse(LResponseStatus.Code);
LResponse.Description := LResponseStatus.Description;
case LResponseStatus.Category of
Informational: ;
Success:
begin
for LProduce in AMethod.Produces do
begin
LMediaType := LResponse.AddMediaType(LProduce.Value);
if Assigned(AMethod.MethodResult.Entity) then
begin
if not FDocument.Components.SchemaExists(AMethod.MethodResult.RttiType.Name) then
begin
FDocument.Components
.AddSchema(AMethod.MethodResult.RttiType.Name)
.SetJSONFromType(AMethod.MethodResult.RttiType);
end;
LMediaType.Schema.SetSchemaReference(AMethod.MethodResult.Entity.Name);
end;
LMediaType.Schema.SetJSONFromType(AMethod.MethodResult.RttiType);
end;
end;
Redirection: ;
ClientError, ServerError:
begin
LMediaType := LResponse.AddMediaType('application/json');
LMediaType.Schema.Reference.Ref := '#/components/schemas/' + 'Error';
end;
Custom: ;
end;
end;
end;
if Length(AMethod.Auth.Roles) > 0 then
Result.Security.AddSecurityRequirement(
FDocument.Components.SecuritySchemes, 'jwt_auth', []
);
if AMethod.AuthHandler then
Result.Security.AddSecurityRequirement(
FDocument.Components.SecuritySchemes, 'basic_auth', []
);
end;
procedure TOpenAPIv3Engine.AddResource(AResource: TWiRLProxyResource);
var
LFullPath: string;
LMethod: TWiRLProxyMethod;
LPathItem: TOpenAPIPathItem;
begin
if AResource.Path <> '' then
begin
// Loop on every method of the current resource object
for LMethod in AResource.Methods do
begin
if LMethod.Name <> '' then
begin
LFullPath := IncludeLeadingSlash(CombineURL(AResource.Path, LMethod.Path));
// If the resource is already documented add the information on
// the same json object
LPathItem := FDocument.AddPath(LFullPath);
AddOperation(LMethod, LPathItem, AResource.Name);
end;
end;
end;
end;
function TOpenAPIv3Engine.CreateParameter(AParameter: TWiRLProxyParameter): TOpenAPIParameter;
function GetParamLocation(AParameter: TWiRLProxyParameter): string;
begin
Result := '';
case AParameter.Kind of
TMethodParamType.Path: Result := 'path';
TMethodParamType.Query: Result := 'query';
TMethodParamType.Header: Result := 'header';
TMethodParamType.Cookie: Result := 'cookie';
end;
end;
var
LParamType: string;
begin
LParamType := GetParamLocation(AParameter);
if LParamType.IsEmpty then
Result := nil
else
begin
Result := TOpenAPIParameter.Create;
Result.Name := AParameter.Name;
Result.In_ := LParamType;
// Read the parameter's annotation (NotNull, Min, Max, etc...)
if LParamType = 'path' then
Result.Required := True
else
Result.Required := False;
Result.Description := AParameter.Summary;
Result.Schema.SetJSONFromType(AParameter.RttiParam.ParamType);
end;
end;
class function TOpenAPIv3Engine.Generate(AApplication: TWiRLApplication;
const ASwaggerResource: string): TJSONObject;
var
LEngine: TOpenAPIv3Engine;
begin
LEngine := TOpenAPIv3Engine.Create(AApplication, ASwaggerResource);
try
Result := LEngine.Build();
finally
LEngine.Free;
end;
end;
procedure TOpenAPIv3Engine.ProcessXMLDoc;
var
LContext: TWiRLXMLDocContext;
begin
LContext.Proxy := FApplication.Proxy;
LContext.XMLDocFolder := TWiRLTemplatePaths.Render(FConfigurationOpenAPI.FolderXMLDoc);
TWiRLProxyEngineXMLDoc.Process(LContext);
end;
end.
|
unit DSA.Graph.Edge;
interface
uses
Classes,
SysUtils,
Math,
Rtti,
DSA.Interfaces.Comparer;
type
TEdge<T> = class
private type
TEdge_T = TEdge<T>;
IC = IComparer<T>;
TC = TComparer<T>;
var
__a, __b: integer; // 边的两个端点
__weight: T; // 边的权值
public
constructor Create; overload;
constructor Create(a, b: integer; weight: T); overload;
destructor Destroy; override;
/// <summary> 返回第一个顶点 </summary>
function VertexA: integer;
/// <summary> 返回第二个顶点 </summary>
function VertexB: integer;
/// <summary> 返回权值 </summary>
function Weight: T;
/// <summary> 给定一个顶点, 返回另一个顶点 </summary>
function OtherVertex(x: integer): integer;
function ToString: string; override;
class function compare(a, b: TEdge_T): integer;
type
TEdgeComparer = class(TInterfacedObject, IComparer<TEdge_T>)
public
constructor Default;
function compare(const left, right: TEdge_T): integer;
end;
end;
implementation
{ TEdge }
constructor TEdge<T>.Create(a, b: integer; weight: T);
begin
__a := a;
__b := b;
__weight := weight;
end;
constructor TEdge<T>.Create;
begin
Self.Create(0, 0, default (T));
end;
class function TEdge<T>.compare(a, b: TEdge_T): integer;
var
c: IC;
begin
c := TC.Default;
Result := c.compare(a.weight, b.weight);
end;
destructor TEdge<T>.Destroy;
begin
inherited Destroy;
end;
function TEdge<T>.OtherVertex(x: integer): integer;
begin
Assert((x = __a) or (x = __b));
Result := IfThen(x = __a, __b, __a);
end;
function TEdge<T>.ToString: string;
begin
Result := __a.ToString + '-' + __b.ToString + ': ' + TValue.From<T>(weight)
.ToString;
end;
function TEdge<T>.VertexA: integer;
begin
Result := __a;
end;
function TEdge<T>.VertexB: integer;
begin
Result := __b;
end;
function TEdge<T>.weight: T;
begin
Result := __weight;
end;
{ TEdge<T>.TEdgeComparer }
function TEdge<T>.TEdgeComparer.compare(const left, right: TEdge_T): integer;
var
cmp: IC;
begin
cmp := TC.Default;
Result := cmp.compare(left.weight, right.weight);
end;
constructor TEdge<T>.TEdgeComparer.Default;
begin
inherited Create();
end;
end.
|
unit E_MonitoringServerParams;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Windows, Registry,
E_Logger;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//--------------------- class TMonitoringServerParams --------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//! Запись с параметрами Службы Monitoring Server
(*!
Содержит параметры подключения к БД и другие настройки службы
*)
//------------------------------------------------------------------------------
type
TMonitoringServerParams = record
//! Период опроса директории на наличие новых данных
Period: Smallint;
//! Строка соединения с базой данных
DBConnectionString: string[255];
//! Таймаут соединения с БД
DBTimeOut: Smallint;
//! Рабочая директория
WorkDir: string[255];
//! Количество дней от текущей даты, определяющие данные для архивации
ArcAfter: Smallint;
//! Время ежедневной архивации
ArcTime: TTime;
//! Часовой пояс (разница с Гринвичем в часах)
TimeZone: Integer;
//! Признак объединения последовательных остановок в стоянку
StopJoin: Boolean;
//! Признак использования модуля экспедитора для анализа плана-факта
PlanFactByExpeditor: Boolean;
end;
//------------------------------------------------------------------------------
//! Функция записи параметров в реестр
//------------------------------------------------------------------------------
{! @param in
rcMonitoringParams - запись с параметрами
@return
Вернет True в случае удачного выполнения. Иначе - False.
}
function SaveMonitoringParamsToRegistry(
var AMonitoringParams: TMonitoringServerParams;
const ALogger: TLogger
): Boolean;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//! Функция загрузки параметров из реестра
//------------------------------------------------------------------------------
{! @param in
rcMonitoringParams - запись с параметрами
@return
Вернет True в случае удачного выполнения. Иначе - False.
}
function LoadMonitoringParamsFromRegistry(
var RMonitoringParams: TMonitoringServerParams;
const ALogger: TLogger
): Boolean;
//------------------------------------------------------------------------------
//! Функция проверки существования ветки параметров в реестре
//------------------------------------------------------------------------------
{! @return
Вернет True если указанный ключ существует. Иначе - False.
}
function MonitoringParamsKeyExists(): Boolean;
//------------------------------------------------------------------------------
const
//! Ветка реестра с параметрами
cMonitoringParamsKey = '\System\CurrentControlSet\Services\ILSMonitoringServer\Parameters';
//! Название параметра в реестре
cParamName = 'MonitoringServerParams';
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// Реализация функции записи параметров в реестр
//------------------------------------------------------------------------------
function SaveMonitoringParamsToRegistry(
var AMonitoringParams: TMonitoringServerParams;
const ALogger: TLogger
): Boolean;
var
//! Объект для работы с реестром
LRegistry: TRegistry;
//------------------------------------------------------------------------------
begin
Result := True;
LRegistry := TRegistry.Create();
LRegistry.RootKey := HKEY_LOCAL_MACHINE;
try
LRegistry.OpenKey( cMonitoringParamsKey , True );
LRegistry.WriteBinaryData( cParamName, AMonitoringParams, SizeOf( AMonitoringParams ) );
LRegistry.CloseKey();
except
on Ex: Exception
do begin
Result := False;
ALogger.ErrorToLog( 'Ошибка записи параметров в реестр:'#13#10 + Ex.Message );
end;
end;
LRegistry.Free();
end;
//------------------------------------------------------------------------------
// Реализация функции загрузки параметров из реестра
//------------------------------------------------------------------------------
function LoadMonitoringParamsFromRegistry(
var RMonitoringParams: TMonitoringServerParams;
const ALogger: TLogger
): Boolean;
var
//! Объект для работы с реестром
LRegistry: TRegistry;
//! Число байт
LByteCount: Integer;
//------------------------------------------------------------------------------
begin
Result := True;
LRegistry := TRegistry.Create();
LRegistry.RootKey := HKEY_LOCAL_MACHINE;
if not LRegistry.KeyExists( cMonitoringParamsKey )
then begin
Result := False;
ALogger.ErrorToLog( 'Отсутствует ветка реестра. Возможно, служба не установлена.' );
end
else begin
try
LRegistry.OpenKey( cMonitoringParamsKey, True );
FillChar( RMonitoringParams, SizeOf( RMonitoringParams ), 0 );
LByteCount := LRegistry.ReadBinaryData( cParamName, RMonitoringParams, SizeOf( RMonitoringParams ) );
if ( LByteCount < SizeOf( RMonitoringParams ) )
then LRegistry.ReadBinaryData( cParamName, RMonitoringParams, LByteCount );
LRegistry.CloseKey;
except
on Ex: Exception
do begin
Result := False;
ALogger.ErrorToLog( 'Ошибка чтения параметров из реестра:'#13#10 + Ex.Message );
end;
end;
end;
LRegistry.Free();
end;
//------------------------------------------------------------------------------
// Реализация функции проверки существования ветки параметров в реестре
//------------------------------------------------------------------------------
function MonitoringParamsKeyExists(): Boolean;
var
//! Объект для работы с реестром
LRegistry: TRegistry;
//------------------------------------------------------------------------------
begin
LRegistry := TRegistry.Create();
LRegistry.RootKey := HKEY_LOCAL_MACHINE;
Result := LRegistry.KeyExists( cMonitoringParamsKey );
LRegistry.Free();
end;
end.
|
unit DSA.Graph.ShortestPath;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.Utils;
type
TShortestPath = class
private
__g: IGraph; // 图的引用
__s: integer; // 起始点
__visited: TArray_bool; // 记录dfs的过程中节点是否被访问
__from: TArray_int; // 记录路径, __from[i]表示查找的路径上i的上一个节点
__ord: TArray_int; // 记录路径中节点的次序。ord[i]表示i节点在路径中的次序。
public
constructor Create(g: IGraph; s: integer);
destructor Destroy; override;
/// <summary> 查询从s点到w点是否有路径 </summary>
function HasPath(w: integer): boolean;
/// <summary> 查询从s点到w点的路径, 存放在list中 </summary>
procedure Path(w: integer; list: TArrayList_int);
/// <summary> 打印出从s点到w点的路径 </summary>
procedure ShowPath(w: integer);
/// <summary> 查看从s点到w点的最短路径长度 </summary>
function length(w: integer): integer;
end;
procedure Main;
implementation
uses
DSA.Graph.Path,
DSA.Graph.SparseGraph;
procedure Main;
var
fileName: string;
g: TSparseGraph;
dfs: TPath;
bfs: TShortestPath;
begin
fileName := FILE_PATH + GRAPH_FILE_NAME_2;
g := TSparseGraph.Create(7, False);
TDSAUtils.ReadGraph(g as IGraph, fileName);
g.Show;
dfs := TPath.Create(g, 0);
Write('DFS: ');
dfs.ShowPath(6);
bfs := TShortestPath.Create(g, 0);
Write('BFS: ');
bfs.ShowPath(6);
end;
{ TShortestPath }
constructor TShortestPath.Create(g: IGraph; s: integer);
var
i: integer;
queue: TQueue_int;
v: integer;
begin
Assert((s >= 0) and (s < g.Vertex));
__g := g;
__s := s;
SetLength(__visited, __g.Vertex);
SetLength(__from, __g.Vertex);
SetLength(__ord, __g.Vertex);
for i := 0 to __g.Vertex - 1 do
begin
__visited[i] := False;
__from[i] := -1;
__ord[i] := -1;
end;
queue := TQueue_int.Create;
// 无向图最短路径算法, 从s开始广度优先遍历整张图
queue.EnQueue(s);
__visited[s] := True;
__ord[s] := 0;
while queue.IsEmpty = False do
begin
v := queue.DeQueue;
for i in __g.AdjIterator(v) do
begin
if not __visited[i] then
begin
queue.EnQueue(i);
__visited[i] := True;
__from[i] := v;
__ord[i] := __ord[v] + 1;
end;
end;
end;
end;
destructor TShortestPath.Destroy;
begin
inherited Destroy;
end;
function TShortestPath.HasPath(w: integer): boolean;
begin
Assert((w >= 0) and (w < __g.Vertex));
Result := __visited[w];
end;
function TShortestPath.length(w: integer): integer;
begin
Assert((w >= 0) and (w < __g.Vertex));
Result := __ord[w];
end;
procedure TShortestPath.Path(w: integer; list: TArrayList_int);
var
s: TStack_int;
p: integer;
begin
Assert(HasPath(w));
s := TStack_int.Create;
// 通过__from数组逆向查找到从s到w的路径, 存放到栈中
p := w;
while p <> -1 do
begin
s.Push(p);
p := __from[p];
end;
// 从栈中依次取出元素, 获得顺序的从s到w的路径
while not s.IsEmpty do
begin
list.AddLast(s.Peek);
s.Pop;
end;
end;
procedure TShortestPath.ShowPath(w: integer);
var
list: TArrayList_int;
i: integer;
begin
list := TArrayList_int.Create;
Path(w, list);
for i := 0 to list.GetSize - 1 do
begin
Write(list[i]);
if i = list.GetSize - 1 then
Writeln
else
Write(' -> ');
end;
end;
end.
|
(* CodeDef: HDO, 2004-02-06
-------
Definition of the MiniPascal byte code.
===================================================================*)
UNIT CodeDef;
INTERFACE
CONST
maxCodeLen = 100;
TYPE
OpCode = ( (*operands:*)
LoadConstOpc, (*num = numerical literal*)
LoadValOpc, (*addr = address of variable for value to load*)
LoadAddrOpc, (*addr = address of variable*)
StoreOpc,
AddOpc,
SubOpc,
MulOpc,
DivOpc,
ReadOpc, (*addr = address of variable to read*)
WriteOpc,
EndOpc);
CodeArray = ARRAY [1 .. maxCodeLen] OF BYTE;
PROCEDURE StoreCode(fileName: STRING; ca: CodeArray);
PROCEDURE LoadCode(fileName: STRING; VAR ca: CodeArray; VAR ok: BOOLEAN);
IMPLEMENTATION
PROCEDURE StoreCode(fileName: STRING; ca: CodeArray);
(*-----------------------------------------------------------------*)
VAR
f: FILE OF CodeArray;
BEGIN
Assign(f, fileName);
ReWrite(f);
Write(f, ca);
Close(f);
END; (*StoreCode*)
PROCEDURE LoadCode(fileName: STRING; VAR ca: CodeArray; VAR ok: BOOLEAN);
(*-----------------------------------------------------------------*)
VAR
f: FILE OF CodeArray;
BEGIN
Assign(f, fileName);
(*$I-*)
Reset(f);
(*$I+*)
ok := IOResult = 0;
IF NOT ok THEN
Exit;
Read(f, ca);
Close(f);
END; (*LoadCode*)
END. (*CodeDef*) |
unit uSessionPasswords;
interface
uses
System.Classes,
System.SysUtils,
System.SyncObjs,
Data.DB,
Dmitry.Utils.System,
UnitINI,
UnitCrypting,
uMemory,
uAppUtils,
uLogger,
uCDMappingTypes,
GraphicCrypt;
type
TSessionPasswords = class
private
FSync: TCriticalSection;
FINIPasswods: TStrings;
FPasswodsInSession: TStrings;
public
constructor Create;
destructor Destroy; override;
procedure AddForSession(Pass: string);
procedure ClearSession;
function FindForFile(FileName: string): string;
function FindForBlobStream(DF: TField): string;
procedure SaveInSettings(Pass: string);
procedure LoadINIPasswords;
procedure SaveINIPasswords;
procedure ClearINIPasswords;
procedure GetPasswordsFromParams;
end;
function SessionPasswords: TSessionPasswords;
implementation
var
FSessionPasswords: TSessionPasswords = nil;
function SessionPasswords: TSessionPasswords;
begin
if FSessionPasswords = nil then
FSessionPasswords := TSessionPasswords.Create;
Result := FSessionPasswords;
end;
constructor TSessionPasswords.Create;
begin
FSync := TCriticalSection.Create;
FPasswodsInSession := TStringList.Create;
FINIPasswods := TStringList.Create;
LoadINIPasswords;
end;
destructor TSessionPasswords.Destroy;
begin
F(FINIPasswods);
F(FPasswodsInSession);
F(FSync);
inherited;
end;
procedure TSessionPasswords.GetPasswordsFromParams;
var
PassParam, Pass: string;
begin
PassParam := GetParamStrDBValue('/AddPass');
PassParam := AnsiDequotedStr(PassParam, '"');
for Pass in PassParam.Split(['!']) do
AddForSession(Pass);
end;
procedure TSessionPasswords.ClearINIPasswords;
begin
FINIPasswods.Clear;
SaveINIPasswords;
end;
procedure TSessionPasswords.AddForSession(Pass: String);
var
I: Integer;
begin
FSync.Enter;
try
for I := 0 to FPasswodsInSession.Count - 1 do
if FPasswodsInSession[I] = Pass then
Exit;
FPasswodsInSession.Add(Pass);
finally
FSync.Leave;
end;
end;
procedure TSessionPasswords.ClearSession;
begin
FSync.Enter;
try
FPasswodsInSession.Clear;
finally
FSync.Leave;
end;
end;
function TSessionPasswords.FindForFile(FileName: String): String;
var
I : Integer;
begin
Result := '';
FSync.Enter;
try
FileName := ProcessPath(FileName);
for I := 0 to FPasswodsInSession.Count - 1 do
if ValidPassInCryptGraphicFile(FileName, FPasswodsInSession[I]) then
begin
Result := FPasswodsInSession[I];
Exit;
end;
for I := 0 to FINIPasswods.Count - 1 do
if ValidPassInCryptGraphicFile(FileName, FINIPasswods[I]) then
begin
Result := FINIPasswods[I];
Exit;
end;
finally
FSync.Leave;
end;
end;
function TSessionPasswords.FindForBlobStream(DF : TField): String;
var
I : Integer;
begin
Result := '';
FSync.Enter;
try
for I := 0 to FPasswodsInSession.Count - 1 do
if ValidPassInCryptBlobStreamJPG(DF, FPasswodsInSession[I]) then
begin
Result := FPasswodsInSession[I];
Exit;
end;
for I := 0 to FINIPasswods.Count - 1 do
if ValidPassInCryptBlobStreamJPG(DF, FINIPasswods[I]) then
begin
Result := FINIPasswods[I];
Exit;
end;
finally
FSync.Leave;
end;
end;
procedure TSessionPasswords.SaveInSettings(Pass: String);
var
I: integer;
begin
FSync.Enter;
try
for I := 0 to FINIPasswods.Count - 1 do
if FINIPasswods[I] = Pass then
Exit;
FINIPasswods.Add(Pass);
SaveINIPasswords;
finally
FSync.Leave;
end;
end;
procedure TSessionPasswords.LoadINIPasswords;
var
Reg: TBDRegistry;
S: string;
begin
Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER);
try
try
F(FINIPasswods);
Reg.OpenKey(GetRegRootKey, True);
S := '';
if Reg.ValueExists('INI') then
S := Reg.ReadString('INI');
S := HexStringToString(S);
if Length(S) > 0 then
FINIPasswods := DeCryptTStrings(S, 'dbpass')
else
FINIPasswods := TStringList.Create;
except
on E: Exception do
EventLog(':TDBKernel::ReadActivateKey() throw exception: ' + E.message);
end;
finally
F(Reg);
end;
end;
procedure TSessionPasswords.SaveINIPasswords;
var
Reg: TBDRegistry;
S: string;
begin
Reg := TBDRegistry.Create(REGISTRY_CURRENT_USER);
try
Reg.OpenKey(GetRegRootKey, True); // todo!
S := CryptTStrings(FINIPasswods, 'dbpass');
S := StringToHexString(S);
Reg.WriteString('INI', S);
except
on E: Exception do
EventLog(':TDBKernel::ReadActivateKey() throw exception: ' + E.message);
end;
Reg.Free;
end;
initialization
finalization
F(FSessionPasswords);
end.
|
unit Z180_CPU;
{$mode objfpc}{$H+}
{$inline on}
{$coperators off}
{$rangechecks off}
//{$define Z180TRAP}
interface
uses
Classes, SysUtils;
type
{ TZ180Cpu }
TZ180Cpu = class
private // Attribute
type
TregAF = bitpacked record
case byte of
0: (Value: word); // 16Bit Register-Paar AF
1: (F: byte; // 8Bit Register F (lower 8Bit)
A: byte); // 8Bit Register A (upper 8Bit)
2: (Flag: bitpacked array[0..15] of boolean); // Flag bits
end;
TregBC = packed record
case byte of
0: (Value: word); // 16Bit Register-Paar BC
1: (C: byte; // 8Bit Register C (lower 8Bit)
B: byte); // 8Bit Register B (upper 8Bit)
end;
TregDE = packed record
case byte of
0: (Value: word); // 16Bit Register-Paar DE
1: (E: byte; // 8Bit Register E (lower 8Bit)
D: byte); // 8Bit Register D (upper 8Bit)
end;
TregHL = packed record
case byte of
0: (Value: word); // 16Bit Register-Paar HL
1: (L: byte; // 8Bit Register L (lower 8Bit)
H: byte); // 8Bit Register H (upper 8Bit)
end;
TbitReg8 = bitpacked record
case byte of
0: (Value: byte); // 8Bit Register Value
2: (bit: bitpacked array[0..7] of boolean); // Bit Data
end;
Treg16 = packed record
case byte of
0: (Value: word); // 16Bit Register
1: (low: byte; // lower 8Bit
high: byte); // upper 8Bit
end;
Treg32 = packed record
case byte of
0: (Value: dword); // 32Bit Register
1: (low: byte; // lower 8Bit
high: byte; // upper 8Bit
bank: byte; // bank 4bit
nv: byte); // not used
end;
TIntMode = (IM0, IM1, IM2);
TAcsiDmaMode = (OFF, ASCI0SEND, ASCI1SEND, ASCI0RECEIVE, ASCI1RECEIVE);
var
// Variablen fuer die Takt- und Machinen-Zyklen Verarbeitung
machineCycles, clockCycles: DWord;
extraWaitCycles, ioWaitCycles, memWaitCycles: DWord;
clockShift: byte;
// 1. Z180Cpu Standard-Registersatz
regAF: TregAF; // 16Bit Register-Paar AF
regBC: TregBC; // 16Bit Register-Paar BC
regDE: TRegDE; // 16Bit Register-Paar DE
regHL: TregHL; // 16Bit Register-Paar HL
// 2. Z180Cpu Standard-Registersatz
// diese werden nur als 16Bit Registerpaar abgebildet,
// da diese nur ueber die 'EX' bzw. 'EXX' Befehle zu erreichen sind
regAF_: word;
regBC_: word;
regDE_: word;
regHL_: word;
// Abbildung des Z180Cpu Spezial-Registersatzes
regI: byte; // 8Bit Register I
regR: byte; // 8Bit Register R
regPC: Treg16; // 16Bit Register PC
regSP: Treg16; // 16Bit Register SP
regIX: Treg16; // 16Bit Register IX
regIY: Treg16; // 16Bit Register IY
// Abbildung der internen Z180Cpu I/O-Register
ioCNTLA0: TbitReg8; // ASCI-Channel 0 Control Register A
ioCNTLA1: TbitReg8; // ASCI-Channel 1 Control Register A
ioCNTLB0: TbitReg8; // ASCI-Channel 0 Control Register B
ioCNTLB1: TbitReg8; // ASCI-Channel 1 Control Register B
ioSTAT0: TbitReg8; // ASCI-Channel 0 Status
ioSTAT1: TbitReg8; // ASCI-Channel 1 Status
ioTDR0: byte; // ASCI-Channel 0 Transmit Data Register
ioTDR1: byte; // ASCI-Channel 1 Transmit Data Register
ioRDR0: byte; // ASCI-Channel 0 Receive Data Register
ioRDR1: byte; // ASCI-Channel 1 Receive Data Register
ioCNTR: TbitReg8; // CSI/O Control Register
ioTRD: byte; // CSI/O Transmit/Receive Data Register
ioTMDR0: Treg16; // Timer-Channel 0 Data Register
ioRLDR0: Treg16; // Timer-Channel 0 Reload Register
ioTCR: TbitReg8; // Timer Control Register
ioTMDR1: Treg16; // Timer-Channel 1 Data Register
ioRLDR1: Treg16; // Timer-Channel 1 Reload Register
ioFRC: byte; // Free Running Counter
ioCMR: TbitReg8; // Clock Multiplier Register
ioCCR: TbitReg8; // CPU Control Register
ioSAR0: Treg32; // DMA-Channel 0 Source Address Register
ioDAR0: Treg32; // DMA-Channel 0 Destination Address Register
ioBCR0: Treg32; // DMA-Channel 0 Byte Count Register (32Bit um vollen 64K Transfer zu handeln)
ioMAR1: Treg32; // DMA-Channel 1 Memory Address Register
ioIAR1: Treg16; // DMA-Channel 1 I/O Address Register
ioBCR1: Treg32; // DMA-Channel 1 Byte Count Register (32Bit um vollen 64K Transfer zu handeln)
ioDSTAT: TbitReg8; // DMA Status Register
ioDMODE: TbitReg8; // DMA Mode Register
ioDCNTL: TbitReg8; // DMA/WAIT Control Register
ioIL: byte; // Interrupt Vector Low Register
ioITC: TbitReg8; // INT/TRAP Control Register
ioRCR: TbitReg8; // Refresh Control Register
ioCBR: byte; // MMU Common Base Register
ioBBR: byte; // MMU Bank Base Register
ioCBAR: byte; // MMU Common/Base Register
ioOMCR: TbitReg8; // Operation Mode Control Register
ioICR: TbitReg8; // I/O Control Register
// Interrupt- und Betriebsmodus Flags
IFF1: boolean; // Interrupt-Enable Flag 1
IFF2: boolean; // Interrupt-Enable Flag 2
SLP, tmpSLP: boolean; // Sleep-Mode enabled
HALT, tmpHALT: boolean; // Halt-Mode enabled
intMode: TIntMode; // Interrupt mode (IM0, IM1, IM2)
// Abbildung der moeglichen internen Interrupts. Externe Interrupts werden nicht unterstuetzt
intTRAP: boolean; // OP-Code Trap Prio 1
intPRT0: boolean; // Programmable Reload Timer0 Interrupt Prio 2
intPRT1: boolean; // Programmable ReloadTimer1 Interrupt Prio 3
intDMA0: boolean; // DMA-Channel0 Interrupt Prio 4
intDMA1: boolean; // DMA-Channel1 Interrupt Prio 5
intCSIO: boolean; // Clocked Serial-IO Interrupt Prio 6
intASCI0: boolean; // ASCI-Channel0 Interrupt Prio 7
intASCI1: boolean; // ASCI-Channel1 Interrupt Prio 8
// Hilfsvariablen fuer die ASCI Funktion
asciPhiDevideRatio0, asciPhiDevideRatio1: dword; // Teilungsfaktor fuer den Baudraten-Takt
asciClockCount0, asciClockCount1: dword; // Takt-Zaehler fuer den Baudraten-Takt
shiftModeRatio0, shiftModeRatio1: byte; // Gesamtzahl der zu Übertragenden Bits pro Datenbyte
transmitShiftCount0, transmitShiftCount1: byte; // Bit-Zaehler fuer das Senden von Daten
receiveShiftCount0, receiveShiftCount1: byte; // Bit-Zaehler fuer das Empfangen von Daten
TSR0, TSR1: byte; // Sende Schiebe-Register (nicht per I/O Ansprechbar)
RSR0, RSR1: byte; // Empfangs Schiebe-Register (nicht per I/O Ansprechbar)
asciTSR0E, asciTSR1E: boolean; // Hilfsflag 'Transmit Shift Register Empty'
asciRSR0F, asciRSR1F: boolean; // Hilfsflag 'Receive Shift Register Full'
// Hilfsvariablen fuer die PRT Funktion
prtClockCount: byte; // Takt-Zaehler fuer die Programmable Reload Timer
bufTMDR0H, bufTMDR1H: byte; // Puffer-Variable fuer Timer Data Register High
isBufTMDR0H, isBufTMDR1H: boolean; // Flags fuer die Daten-Pufferung
// Hilfsvariablen für den DMA Controller
dmaBurstMode: boolean; // zeigt an ob DMA-Channel 0 im Cycles-Steal oder im Burst-Mode arbeitet
dreq0: boolean; // DMA Request Channel 0
dreq1: boolean; // DMA Request Channel 1
tend0: boolean; // Transfer End Channel 0
tend1: boolean; // Transfer End Channel 1
asciDmaMode: TAcsiDmaMode;
// Hilfsarrays
mmu: array[0..15] of dword; // Array für schnelle MMU-Berechnung
parity: array[0..255] of boolean; // Array für schnelle Parity-Berechnung
// statische Arrays fuer ASCI- und Wait-Cycles
const
asciDevide: array[0..7] of byte = (1, 2, 4, 8, 16, 32, 64, 0);
asciTransLength: array[0..7] of byte = (9, 10, 10, 11, 10, 11, 11, 12);
memCycles: array[0..3] of byte = (0, 1, 2, 3);
ioCycles: array[0..3] of byte = (0, 2, 3, 4);
// Konstanten fuer die Status-Flags der CPU
const
C = $00; // Carry Flag
N = $01; // Negative Flag
PV = $02; // Parity/Overflow Flag
H = $04; // Half Carry Flag
Z = $06; // Zero Flag
S = $07; // Sign Flag
// Konstanten fuer die internen I/O Bit-Adressen
const
MOD0 = $00; // Mode Selection 0
MOD1 = $01; // Mode Selection 1
MOD2 = $02; // Mode Selection 2
MODsel = $07; // Mode Selection
MPBR_EFR = $03; // Multi Processor Bit Receive/Error Flag Reset
RTS0 = $04; // Request to Send
CKA1D = $04; // CKA1 Disable
TE = $05; // ASCI Transmit Enable
RE = $06; // ASCI Receive Enable
MPE = $07; // Multi Processor Enable
SS0 = $00; // Clock Source and Speed Select 0
SS1 = $01; // Clock Source and Speed Select 1
SS2 = $02; // Clock Source and Speed Select 0
SSsel = $07; // Clock Source and Speed Select
DR = $03; // Divide Ratio
PEO = $04; // Parity Even or Odd
CTS_PS = $05; // Clear to send/Prescale
MP = $06; // Multi Processor
MPBT = $07; // Multi Processor Bit Transmit
TIE = $00; // Transmit Interrupt Enable
TDRE = $01; // Transmit Data Register Empty
DCD0 = $02; // Data Carrier Detect
CTS1e = $02; // CTS1 Enable
RIE = $03; // Receive Interrupt Enable
FE = $04; // Framing Error
PE = $05; // Parity Error
OVRN = $06; // Overrun Error
RDRF = $07; // Receive Data Register Full
TEcsio = $04; // CSI/O Transmit Enable
REcsio = $05; // CSI/O Receive Enable
EIE = $06; // End Interrupt Enable
EF = $07; // End Flag
TDE0 = $00; // Timer Down Count Enable 0
TDE1 = $01; // Timer Down Count Enable 1
TOC0 = $02; // Timer Output Control 0
TOC1 = $03; // Timer Output Control 1
TIE0 = $04; // Timer Interrupt Enable 0
TIE1 = $05; // Timer Interrupt Enable 1
TIF0 = $06; // Timer Interrupt Flag 0
TIF1 = $07; // Timer Interrupt Flag 1
DME = $00; // DMA Master enable
DIE0 = $02; // DMA Interrupt Enable 0
DIE1 = $03; // DMA Interrupt Enable 1
DWE0 = $04; // DMA Enable Bit Write Enable 0
DWE1 = $05; // DMA Enable Bit Write Enable 1
DE0 = $06; // DMA Enable Channel 0
DE1 = $07; // DMA Enable Channel 0
MMOD = $01; // Memory MODE select
SM0 = $02; // Channel 0 Source Mode 0
SM1 = $03; // Channel 0 Source Mode 1
SMsel = $0C; // Channel 0 Source
DM0 = $04; // Channel 0 Destination Mode 0
DM1 = $05; // Channel 0 Destination Mode 1
DMsel = $30; // Channel 0 Destination
DIM0 = $00; // DMA Channel 1 I/O Memory Mode Select 0
DIM1 = $01; // DMA Channel 1 I/O Memory Mode Select 1
DIMsel = $03; // DMA Channel 1 I/O Memory Mode Select
DMS0 = $02; // DREQ0 Select
DMS1 = $03; // DREQ1 Select
IWI0 = $04; // I/O Wait Insertion 0
IWI1 = $05; // I/O Wait Insertion 1
IWIsel = $30; // I/O Wait Insertion
MWI0 = $06; // Memory Wait Insertion 0
MWI1 = $07; // Memory Wait Insertion 1
MWIsel = $C0; // Memory Wait Insertion
ITE0 = $00; // INT 0 Enable
ITE1 = $01; // INT 1 Enable
ITE2 = $02; // INT 2 Enable
UFO = $06; // Unidentified Fetch Object
TRAP = $07; // TRAP
CYC0 = $00; // Refresh Cycle select 0
CYC1 = $01; // Refresh Cycle select 1
REFW = $06; // Refresh Wait State
REFE = $07; // Refresh Enable
IOC = $05; // I/O Compatibility
M1TE = $06; // M1 Temporary Enable
M1E = $07; // M1 Enable
IOSTP = $05; // I/O Stop
IOA6 = $06; // internal I/O Address 0
IOA7 = $07; // internal I/O Address 1
IOAsel = $C0; // internal I/O Address
protected // Attribute
public // Attribute
// Datenstruktur für den export der CPU Core-Register Daten
type
TCoreData = record
A1: byte;
F1: byte;
B1: byte;
C1: byte;
BC1: word;
BCi1: byte;
D1: byte;
E1: byte;
DE1: word;
DEi1: byte;
H1: byte;
L1: byte;
HL1: word;
HLi1: byte;
A2: byte;
F2: byte;
B2: byte;
C2: byte;
BC2: word;
BCi2: byte;
D2: byte;
E2: byte;
DE2: word;
DEi2: byte;
H2: byte;
L2: byte;
HL2: word;
HLi2: byte;
I: byte;
R: byte;
IX: word;
IY: word;
SP: word;
SPi: byte;
PC: word;
PCi: byte;
PCmmu: longword;
IFF1: boolean;
IFF2: boolean;
intMode: byte;
end;
// Datenstruktur für den export der CPU IO-Register Daten
TIoData = record
CNTLA0: byte; // ASCI-Channel 0 Control Register A
CNTLA1: byte; // ASCI-Channel 1 Control Register A
CNTLB0: byte; // ASCI-Channel 0 Control Register B
CNTLB1: byte; // ASCI-Channel 1 Control Register B
STAT0: byte; // ASCI-Channel 0 Status
STAT1: byte; // ASCI-Channel 1 Status
TDR0: byte; // ASCI-Channel 0 Transmit Data Register
TDR1: byte; // ASCI-Channel 1 Transmit Data Register
RDR0: byte; // ASCI-Channel 0 Receive Data Register
RDR1: byte; // ASCI-Channel 1 Receive Data Register
CNTR: byte; // CSI/O Control Register
TRD: byte; // CSI/O Transmit/Receive Data Register
TMDR0L: byte; // Timer-Channel 0 Data Register low
TMDR0H: byte; // Timer-Channel 0 Data Register high
RLDR0L: byte; // Timer-Channel 0 Reload Register low
RLDR0H: byte; // Timer-Channel 0 Reload Register high
TCR: byte; // Timer Control Register
TMDR1L: byte; // Timer-Channel 1 Data Register low
TMDR1H: byte; // Timer-Channel 1 Data Register high
RLDR1L: byte; // Timer-Channel 1 Reload Register low
RLDR1H: byte; // Timer-Channel 1 Reload Register high
FRC: byte; // Free Running Counter
SAR0L: byte; // DMA-Channel 0 Source Address Register low
SAR0H: byte; // DMA-Channel 0 Source Address Register high
SAR0B: byte; // DMA-Channel 0 Source Address Register bank
DAR0L: byte; // DMA-Channel 0 Destination Address Register low
DAR0H: byte; // DMA-Channel 0 Destination Address Register high
DAR0B: byte; // DMA-Channel 0 Destination Address Register bank
BCR0L: byte; // DMA-Channel 0 Byte Count Register low
BCR0H: byte; // DMA-Channel 0 Byte Count Register high
MAR1L: byte; // DMA-Channel 1 Memory Address Register low
MAR1H: byte; // DMA-Channel 1 Memory Address Register high
MAR1B: byte; // DMA-Channel 1 Memory Address Register bank
IAR1L: byte; // DMA-Channel 1 I/O Address Register low
IAR1H: byte; // DMA-Channel 1 I/O Address Register high
BCR1L: byte; // DMA-Channel 1 Byte Count Register low
BCR1H: byte; // DMA-Channel 1 Byte Count Register high
DSTAT: byte; // DMA Status Register
DMODE: byte; // DMA Mode Register
DCNTL: byte; // DMA/WAIT Control Register
IL: byte; // Interrupt Vector Low Register
ITC: byte; // INT/TRAP Control Register
RCR: byte; // Refresh Control Register
CBR: byte; // MMU Common Base Register
BBR: byte; // MMU Bank Base Register
CBAR: byte; // MMU Common/Base Register
OMCR: byte; // Operation Mode Control Register
ICR: byte; // I/O Control Register
end;
public // Konstruktor/Destruktor
constructor Create; overload;
destructor Destroy; override;
private // Methoden
function memRead(const addr: word): byte;
procedure memWrite(const addr: word; const Value: byte);
function ioRead(const portHI: byte; const portLO: byte): byte;
procedure ioWrite(const portHI: byte; const portLO: byte; const Data: byte);
procedure calcMmuPageTable;
function calcAsciPhiDevide(asciControlRegister: byte): dword;
function readOpCode(const addr: DWord): byte;
procedure doAsci0;
procedure doAsci1;
procedure doPrt0;
procedure doPrt1;
procedure doDma0;
procedure doDma1;
procedure inc8Bit(var Value: byte);
procedure dec8Bit(var Value: byte);
procedure addA8Bit(const Value: byte);
procedure adcA8Bit(const Value: byte);
procedure subA8Bit(const Value: byte);
procedure sbcA8Bit(const Value: byte);
procedure andA8Bit(const Value: byte);
procedure xorA8Bit(const Value: byte);
procedure orA8Bit(const Value: byte);
procedure cpA8Bit(const Value: byte);
procedure rlc8Bit(var Value: byte);
procedure rrc8Bit(var Value: byte);
procedure rl8Bit(var Value: byte);
procedure rr8Bit(var Value: byte);
procedure sla8Bit(var Value: byte);
procedure sra8Bit(var Value: byte);
procedure srl8Bit(var Value: byte);
procedure tstBit(const Bit: byte; const Value: byte);
procedure resBit(const Bit: byte; var Value: byte);
procedure setBit(const Bit: byte; var Value: byte);
procedure tstA8Bit(const Value: byte);
function inreg8Bit(const portHi: byte; const portLo: byte): byte;
procedure addHL16Bit(const Value: word);
procedure adcHL16Bit(const Value: word);
procedure sbcHL16Bit(const Value: word);
procedure addIX16Bit(const Value: word);
procedure addIY16Bit(const Value: word);
procedure push(const Value: word);
procedure pop(var Value: word);
procedure execOp00Codes;
procedure execOpCbCodes;
procedure execOpDdCodes;
procedure execOpDdCbCodes;
procedure execOpFdCodes;
procedure execOpFdCbCodes;
procedure execOpEdCodes;
protected // Methoden
public // Methoden
procedure reset;
procedure clrSlpHalt;
procedure exec(opCount: DWord = 1);
function getCoreData: TCoreData;
function getIoRegData: TIoData;
procedure setDREQ0;
procedure setDREQ1;
function getTEND0: boolean;
function getTEND1: boolean;
end;
var
Z180Cpu: TZ180Cpu;
implementation
uses
System_Memory, System_InOut;
// --------------------------------------------------------------------------------
constructor TZ180Cpu.Create;
var
Value, Data: byte;
begin
inherited Create;
asciClockCount0 := 0;
transmitShiftCount0 := 0;
receiveShiftCount0 := 0;
asciTSR0E := True;
asciRSR0F := False;
asciClockCount1 := 0;
transmitShiftCount1 := 0;
receiveShiftCount1 := 0;
asciTSR1E := True;
asciRSR1F := False;
prtClockCount := 0;
isBufTMDR0H := False;
isBufTMDR1H := False;
machineCycles := 0;
clockCycles := 0;
extraWaitCycles := 0;
clockShift := 0;
memWaitCycles := 0;
ioWaitCycles := 0;
// Initialisieren des Parity-Arrays
for Value := 0 to 255 do begin
Data := Value;
Data := Data xor Data shr 4;
Data := Data xor Data shr 2;
Data := Data xor Data shr 1;
parity[Value] := ((Data and $01) = $00);
end;
end;
// --------------------------------------------------------------------------------
destructor TZ180Cpu.Destroy;
begin
inherited Destroy;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.memRead(const addr: word): byte; inline;
begin
extraWaitCycles := extraWaitCycles + memWaitCycles;
Result := SystemMemory.Read(mmu[((addr shr 12) and $0F)] or (addr and $0FFF));
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.memWrite(const addr: word; const Value: byte); inline;
begin
extraWaitCycles := extraWaitCycles + memWaitCycles;
SystemMemory.Write((mmu[((addr shr 12) and $0F)] or (addr and $0FFF)), Value);
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.ioRead(const portHI: byte; const portLO: byte): byte;
begin
extraWaitCycles := extraWaitCycles + ioWaitCycles;
Result := SystemInOut.cpuIoRead(((portHI shl 8) + portLO));
if ((portLo <= (ioICR.Value and IOAsel) + $3F) and (portLo >= (ioICR.Value and IOAsel)) and (portHi = $00)) then begin
case (portLO and $3F) of
$00: begin //portCNTLA0
Result := (ioCNTLA0.Value and $FF);
end;
$01: begin //portCNTLA1
Result := (ioCNTLA1.Value and $FF);
end;
$02: begin //portCNTLB0
Result := (ioCNTLB0.Value and $FF);
end;
$03: begin //portCNTLB1
Result := (ioCNTLB1.Value and $FF);
end;
$04: begin //portSTAT0
Result := (ioSTAT0.Value and $FF);
end;
$05: begin //portSTAT1
Result := (ioSTAT1.Value and $FF);
end;
$06: begin //portTDR0
Result := (ioTDR0 and $FF);
end;
$07: begin //portTDR1
Result := (ioTDR1 and $FF);
end;
$08: begin //portRDR0
Result := (ioRDR0 and $FF);
ioSTAT0.bit[RDRF] := False; // Bit 'Receive Data Register Full' loeschen
end;
$09: begin //portRDR1
Result := (ioRDR1 and $FF);
ioSTAT1.bit[RDRF] := False; // Bit 'Receive Data Register Full' loeschen
end;
$0A: begin //portCNTR
Result := (ioCNTR.Value and $F7);
end;
$0B: begin //portTRD
Result := (ioTRD and $FF);
end;
$0C: begin //portTMDR0L
bufTMDR0H := (ioTMDR0.high and $FF); // Lesereihenfolge Low-Byte , High-Byte !
isBufTMDR0H := True; // High-Byte puffern. Z8018x Family MPU User Manual Seite 158
Result := (ioTMDR0.low and $FF);
ioTCR.bit[TIF0] := False; // Timer 0 Interrupt Flag beim lesen von TMDR0L loeschen
end;
$0D: begin //portTMDR0H
if (isBufTMDR0H = True) then begin // wenn gepuffertes High-Byte vorhanden
Result := bufTMDR0H; // dann dieses auslesen
isBufTMDR0H := False; // und Puffer-Marker loeschen.
end
else begin
Result := (ioTMDR0.high and $FF);
end;
ioTCR.bit[TIF0] := False; // Timer 0 Interrupt Flag beim lesen von TMDR0H loeschen
end;
$0E: begin //portRLDR0L
Result := (ioRLDR0.low and $FF);
end;
$0F: begin //portRLDR0H
Result := (ioRLDR0.high and $FF);
end;
$10: begin //portTCR
Result := (ioTCR.Value and $FF);
ioTCR.bit[TIF0] := False; // Timer 0 Interrupt Flag und
ioTCR.bit[TIF1] := False; // Timer 1 Interrupt Flag und beim lesen von TCR loeschen
end;
$14: begin //portTMDR1L
bufTMDR1H := (ioTMDR1.high and $FF); // Lesereihenfolge Low-Byte , High-Byte !
isBufTMDR1H := True; // High-Byte puffern. Z8018x Family MPU User Manual Seite 158
Result := (ioTMDR1.low and $FF);
ioTCR.bit[TIF1] := False; // Timer 1 Interrupt Flag beim lesen von TMDR1L loeschen
end;
$15: begin //portTMDR1H
if (isBufTMDR1H = True) then begin // wenn gepuffertes High-Byte vorhanden
Result := bufTMDR1H; // dann dieses auslesen
isBufTMDR1H := False; // und Puffer-Marker loeschen.
end
else begin
Result := (ioTMDR1.high and $FF);
end;
ioTCR.bit[TIF1] := False; // Timer 1 Interrupt Flag beim lesen von TMDR1H loeschen
end;
$16: begin //portRLDR1L
Result := (ioRLDR1.low and $FF);
end;
$17: begin //portRLDR1H
Result := (ioRLDR1.high and $FF);
end;
$18: begin //portFRC
Result := (ioFRC and $FF);
end;
$1E: begin //portCMR
Result := (ioCMR.Value and $FF);
end;
$1F: begin //portCCR
Result := (ioCCR.Value and $FF);
end;
$20: begin //portSAR0L
Result := (ioSAR0.low and $FF);
end;
$21: begin //portSAR0H
Result := (ioSAR0.high and $FF);
end;
$22: begin //portSAR0B
Result := (ioSAR0.bank and $0F);
end;
$23: begin //portDAR0L
Result := (ioDAR0.low and $FF);
end;
$24: begin //portDAR0H
Result := (ioDAR0.high and $FF);
end;
$25: begin //portDAR0B
Result := (ioDAR0.bank and $0F);
end;
$26: begin //portBCR0L
Result := (ioBCR0.low and $FF);
end;
$27: begin //portBCR0H
Result := (ioBCR0.high and $FF);
end;
$28: begin //portMAR1L
Result := (ioMAR1.low and $FF);
end;
$29: begin //portMAR1H
Result := (ioMAR1.high and $FF);
end;
$2A: begin //portMAR1B
Result := (ioMAR1.bank and $0F);
end;
$2B: begin //portIAR1L
Result := (ioIAR1.low and $FF);
end;
$2C: begin //portIAR1H
Result := (ioIAR1.high and $FF);
end;
$2E: begin //portBCR1L
Result := (ioBCR1.low and $FF);
end;
$2F: begin //portBCR1H
Result := (ioBCR1.high and $FF);
end;
$30: begin //portDSTAT
Result := (ioDSTAT.Value and $CD);
end;
$31: begin //portDMODE
Result := (ioDMODE.Value and $3E);
end;
$32: begin //portDCNTL
Result := (ioDCNTL.Value and $FF);
end;
$33: begin //portIL
Result := (ioIL and $E0);
end;
$34: begin //portITC
Result := (ioITC.Value and $C7);
end;
$36: begin //portRCR
Result := (ioRCR.Value and $C3);
end;
$38: begin //portCBR
Result := (ioCBR and $FF);
end;
$39: begin //portBBR
Result := (ioBBR and $FF);
end;
$3A: begin //portCBAR
Result := (ioCBAR and $FF);
end;
$3E: begin //portOMCR
Result := (ioOMCR.Value and $A0);
end;
$3F: begin //portICR
Result := (ioICR.Value and $E0);
end;
end;
end
else begin
extraWaitCycles := extraWaitCycles + 1;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.ioWrite(const portHI: byte; const portLO: byte; const Data: byte);
begin
extraWaitCycles := extraWaitCycles + ioWaitCycles;
SystemInOut.cpuIoWrite(((portHI shl 8) + portLO), Data);
if ((portLo <= (ioICR.Value and IOAsel) + $3F) and (portLo >= (ioICR.Value and IOAsel)) and (portHi = $00)) then begin
case (portLO and $3F) of
$00: begin //portCNTLA0
ioCNTLA0.Value := ((ioCNTLA0.Value and not $FF) or (Data and $FF));
shiftModeRatio0 := asciTransLength[ioCNTLA0.Value and MODSEL]; // bei Aenderungen 'shiftModeRatio' neu bestimmen
if (not ioCNTLA0.bit[MPBR_EFR]) then begin // wenn Bit MPBR_EFR mit 0 beschrieben wird
ioSTAT0.bit[OVRN] := False; // in STAT0 Bits OVRN,PE und FE loeschen
ioSTAT0.bit[PE] := False;
ioSTAT0.bit[FE] := False;
ioCNTLA0.bit[MPBR_EFR] := True; // und Bit MPBR_EFR wieder auf 1 setzen
end;
end;
$01: begin //portCNTLA1
ioCNTLA1.Value := ((ioCNTLA1.Value and not $FF) or (Data and $FF));
shiftModeRatio1 := asciTransLength[ioCNTLA1.Value and MODSEL]; // bei Aenderungen 'shiftModeRatio' neu bestimmen
if (not ioCNTLA1.bit[MPBR_EFR]) then begin // wenn Bit MPBR_EFR mit 0 beschrieben wird
ioSTAT1.bit[OVRN] := False; // in STAT0 Bits OVRN,PE und FE loeschen
ioSTAT1.bit[PE] := False;
ioSTAT1.bit[FE] := False;
ioCNTLA1.bit[MPBR_EFR] := True; // und Bit MPBR_EFR wieder auf 1 setzen
end;
end;
$02: begin //portCNTLB0
ioCNTLB0.Value := ((ioCNTLB0.Value and not $FF) or (Data and $FF));
asciPhiDevideRatio0 := (calcAsciPhiDevide(ioCNTLB0.Value) shr clockShift); // bei Aenderungen die 'Baud-Rate' neu berechnen
end;
$03: begin //portCNTLB1
ioCNTLB1.Value := ((ioCNTLB1.Value and not $FF) or (Data and $FF));
asciPhiDevideRatio1 := (calcAsciPhiDevide(ioCNTLB1.Value) shr clockShift); // bei Aenderungen die 'Baud-Rate' neu berechnen
end;
$04: begin //portSTAT0
ioSTAT0.Value := ((ioSTAT0.Value and not $09) or (Data and $09));
end;
$05: begin //portSTAT1
ioSTAT1.Value := ((ioSTAT1.Value and not $0D) or (Data and $0D));
end;
$06: begin //portTDR0
ioTDR0 := ((ioTDR0 and not $FF) or (Data and $FF));
ioSTAT0.bit[TDRE] := False; // und Transmit Data Register Empty loeschen
end;
$07: begin //portTDR1
ioTDR1 := ((ioTDR1 and not $FF) or (Data and $FF));
ioSTAT1.bit[TDRE] := False; // und Transmit Data Register Empty loeschen
end;
$08: begin //portRDR0
ioRDR0 := ((ioRDR0 and not $FF) or (Data and $FF));
end;
$09: begin //portRDR1
ioRDR1 := ((ioRDR1 and not $FF) or (Data and $FF));
end;
$0A: begin //portCNTR
ioCNTR.Value := ((ioCNTR.Value and not $77) or (Data and $77));
end;
$0B: begin //portTRD
ioTRD := ((ioTRD and not $FF) or (Data and $FF));
end;
$0C, $0D: begin
if ((portLO and $3F) = $0C) then begin //portTMDR0L
ioTMDR0.low := ((ioTMDR0.low and not $FF) or (Data and $FF));
end
else begin //portTMDR0H
ioTMDR0.high := ((ioTMDR0.high and not $FF) or (Data and $FF));
end;
end;
$0E, $0F: begin
if ((portLO and $3F) = $0E) then begin //portRLDR0L
ioRLDR0.low := ((ioRLDR0.low and not $FF) or (Data and $FF));
end
else begin //portRLDR0H
ioRLDR0.high := ((ioRLDR0.high and not $FF) or (Data and $FF));
end;
end;
$10: begin //portTCR
ioTCR.Value := ((ioTCR.Value and not $3F) or (Data and $3F));
end;
$14, $15: begin
if ((portLO and $3F) = $14) then begin //portTMDR1L
ioTMDR1.low := ((ioTMDR1.low and not $FF) or (Data and $FF));
end
else begin //portTMDR1H
ioTMDR1.high := ((ioTMDR1.high and not $FF) or (Data and $FF));
end;
end;
$16, $17: begin //portRLDR1L
if ((portLO and $3F) = $16) then begin //portRLDR1L
ioRLDR1.low := ((ioRLDR1.low and not $FF) or (Data and $FF));
end
else begin //portRLDR1H
ioRLDR1.high := ((ioRLDR1.high and not $FF) or (Data and $FF));
end;
end;
$18: begin //portFRC
ioFRC := ((ioFRC and not $00) or (Data and $00));
end;
$1E, $1F: begin
if ((portLO and $3F) = $1E) then begin //portCMR
ioCMR.Value := ((ioCMR.Value and not $80) or (Data and $80));
end
else begin //portCCR
ioCCR.Value := ((ioCCR.Value and not $FF) or (Data and $FF));
end;
if not (ioCMR.bit[7] or ioCCR.bit[7]) then begin
clockShift := 0;
end
else if (ioCMR.bit[7] or ioCCR.bit[7]) then begin
clockShift := 1;
end
else if (ioCMR.bit[7] and ioCCR.bit[7]) then begin
clockShift := 2;
end;
asciPhiDevideRatio0 := (calcAsciPhiDevide(ioCNTLB0.Value) shr clockShift);
asciPhiDevideRatio1 := (calcAsciPhiDevide(ioCNTLB1.Value) shr clockShift);
end;
$20: begin //portSAR0L
ioSAR0.low := ((ioSAR0.low and not $FF) or (Data and $FF));
end;
$21: begin //portSAR0H
ioSAR0.high := ((ioSAR0.high and not $FF) or (Data and $FF));
end;
$22: begin //portSAR0B
ioSAR0.bank := ((ioSAR0.bank and not $0F) or (Data and $0F));
end;
$23: begin //portDAR0L
ioDAR0.low := ((ioDAR0.low and not $FF) or (Data and $FF));
end;
$24: begin //portDAR0H
ioDAR0.high := ((ioDAR0.high and not $FF) or (Data and $FF));
end;
$25: begin //portDAR0B
ioDAR0.bank := ((ioDAR0.bank and not $0F) or (Data and $0F));
end;
$26: begin //portBCR0L
ioBCR0.low := ((ioBCR0.low and not $FF) or (Data and $FF));
end;
$27: begin //portBCR0H
ioBCR0.high := ((ioBCR0.high and not $FF) or (Data and $FF));
end;
$28: begin //portMAR1L
ioMAR1.low := ((ioMAR1.low and not $FF) or (Data and $FF));
end;
$29: begin //portMAR1H
ioMAR1.high := ((ioMAR1.high and not $FF) or (Data and $FF));
end;
$2A: begin //portMAR1B
ioMAR1.bank := ((ioMAR1.bank and not $0F) or (Data and $0F));
end;
$2B: begin //portIAR1L
ioIAR1.low := ((ioIAR1.low and not $FF) or (Data and $FF));
end;
$2C: begin //portIAR1H
ioIAR1.high := ((ioIAR1.high and not $FF) or (Data and $FF));
end;
$2E: begin //portBCR1L
ioBCR1.low := ((ioBCR1.low and not $FF) or (Data and $FF));
end;
$2F: begin //portBCR1H
ioBCR1.high := ((ioBCR1.high and not $FF) or (Data and $FF));
end;
$30, $31: begin
if ((portLO and $3F) = $30) then begin //portDSTAT
ioDSTAT.Value := ((ioDSTAT.Value and not $FC) or (Data and $FC));
if ((ioDSTAT.bit[DE0]) and (not ioDSTAT.bit[DWE0])) then begin
case (ioDMODE.Value and (DMsel or SMsel)) of
$0C, $1C: begin // 64k-I/O SAR0 to Memory DAR0 transfer
if (ioDCNTL.bit[DMS0] and (ioSAR0.low = $08) and ((ioSAR0.bank and $03) = $01)) then begin
asciDmaMode := ASCI0RECEIVE;
end;
if (ioDCNTL.bit[DMS0] and (ioSAR0.low = $09) and ((ioSAR0.bank and $03) = $02)) then begin
asciDmaMode := ASCI1RECEIVE;
end;
end;
$30, $34: begin // Memory SAR0 to 64k-I/O DAR0 transfer
if (ioDCNTL.bit[DMS0] and (ioDAR0.low = $06) and ((ioDAR0.bank and $03) = $01)) then begin
asciDmaMode := ASCI0SEND;
end;
if (ioDCNTL.bit[DMS0] and (ioDAR0.low = $07) and ((ioDAR0.bank and $03) = $02)) then begin
asciDmaMode := ASCI1SEND;
end;
end;
end;
ioDSTAT.bit[DME] := True;
ioDSTAT.bit[DWE0] := True;
end;
if ((ioDSTAT.bit[DE1]) and (not ioDSTAT.bit[DWE1])) then begin
ioDSTAT.bit[DME] := True;
ioDSTAT.bit[DWE1] := True;
end;
end
else begin //portDMODE
ioDMODE.Value := ((ioDMODE.Value and not $3E) or (Data and $3E));
end;
// DMA Burst-Mode kann nur aktiv werden, wenn Memory to Memory Transfer gesetzt.
// um0050.pdf Seite 97
if (ioDSTAT.bit[DME] and ioDSTAT.bit[DE0]) then begin
if (ioDMODE.bit[MMOD] and not ((ioDMODE.Value and (DMsel or SMsel)) = (DMsel or SMsel))) then begin
dmaBurstMode := True;
end
else begin
dmaBurstMode := False;
end;
end;
end;
$32: begin //portDCNTL
ioDCNTL.Value := ((ioDCNTL.Value and not $FF) or (Data and $FF));
memWaitCycles := memCycles[((ioDCNTL.Value and MWIsel) shr $06)]; // bei Aenderungen die Wait-Cycles neu setzen
ioWaitCycles := ioCycles[((ioDCNTL.Value and IWIsel) shr $04)]; // bei Aenderungen die Wait-Cycles neu setzen
end;
$33: begin //portIL
ioIL := ((ioIL and not $E0) or (Data and $E0));
end;
$34: begin //portITC
ioITC.Value := ((ioITC.Value and not $87) or (Data and $87));
end;
$36: begin //portRCR
ioRCR.Value := ((ioRCR.Value and not $C3) or (Data and $C3));
end;
$38: begin //portCBR
ioCBR := ((ioCBR and not $FF) or (Data and $FF));
calcMmuPageTable;
end;
$39: begin //portBBR
ioBBR := ((ioBBR and not $FF) or (Data and $FF));
calcMmuPageTable;
end;
$3A: begin //portCBAR
ioCBAR := ((ioCBAR and not $FF) or (Data and $FF));
calcMmuPageTable;
end;
$3E: begin //portOMCR
ioOMCR.Value := ((ioOMCR.Value and not $E0) or (Data and $E0));
end;
$3F: begin //portICR
ioICR.Value := ((ioICR.Value and not $E0) or (Data and $E0));
end;
end;
end
else begin
extraWaitCycles := extraWaitCycles + 1;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.calcMmuPageTable;
var
addr, page: DWord;
baseArea, commonArea: DWord;
begin
baseArea := (ioCBAR and $0F);
commonArea := ((ioCBAR and $F0) shr 4);
for page := 0 to 15 do begin
addr := (page shl 12);
if (page >= baseArea) then begin
if (page >= commonArea) then begin
addr := addr + (ioCBR shl 12);
end
else begin
addr := addr + (ioBBR shl 12);
end;
end;
mmu[page] := addr;
end;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.calcAsciPhiDevide(asciControlRegister: byte): dword;
var
valuePS, valueDR: byte;
begin
valuePS := 10;
valueDR := 16;
if ((asciControlRegister and $20) <> $00) then begin
valuePS := 30;
end;
if ((asciControlRegister and $08) <> $00) then begin
valueDR := 64;
end;
Result := ((valuePS * valueDR * asciDevide[asciControlRegister and SSsel]) and $FFFFFFFF);
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.readOpCode(const addr: DWord): byte; inline;
begin
regR := (regR + 1) and $7F; // Die letzten 7 Bit von Register R werden bei jedem OpCode Read um 1 hochgezaehlt
extraWaitCycles := extraWaitCycles + memWaitCycles;
Result := SystemMemory.Read((mmu[((addr shr 12) and $0F)] or (addr and $0FFF)));
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doAsci0;
begin
if (ioCNTLA0.bit[TE] and (not asciTSR0E)) then begin // ist Senden enabled und liegen Daten im TSR
Inc(transmitShiftCount0); // den Bitshift-Takt
if (transmitShiftCount0 >= shiftModeRatio0) then begin // entsprechend des Datenformats triggern
SystemInOut.cpuTXA0(TSR0); // und nach den entsprechenden Shift-Takten die Daten ausgeben
asciTSR0E := True; // Flags und
transmitShiftCount0 := 0; // Bitshift-Takt Zaehler korrigieren
end;
end;
if (ioCNTLA0.bit[RE] and (not asciRSR0F) and SystemInOut.cpuCanReadRXA0()) then begin // ist Empfangen enabled, RSR leer und neue Daten verfuegbar
Inc(receiveShiftCount0); // den Bitshift-Takt
if (receiveShiftCount0 >= shiftModeRatio0) then begin // entsprechend des Datenformats triggern
RSR0 := SystemInOut.cpuRXA0(); // und nach den entsprechenden Shift-Takten die Daten einlesen
asciRSR0F := True; // Flags und
receiveShiftCount0 := 0; // Bitshift-Takt Zaehler korrigieren
end;
end;
if (ioSTAT0.bit[TIE] and ioSTAT0.bit[TDRE]) then begin // wenn Transmit-Interrupts enabled und TDR leer
intASCI0 := True; // ASCI0-Interrupt ausloesen
end;
if (ioSTAT0.bit[RDRF] and asciRSR0F) then begin // wenn RDR voll und RSR voll
ioSTAT0.bit[OVRN] := True; // OVERRUN Flag setzen
end;
if (ioSTAT0.bit[RIE] and (ioSTAT0.bit[RDRF] or ioSTAT0.bit[OVRN])) then begin // wenn Receive-Interrupts enabled und RDRF oder OVRN gesetzt
intASCI0 := True; // ASCI0-Interrupt ausloesen
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doAsci1;
begin
if (ioCNTLA1.bit[TE] and (not asciTSR1E)) then begin // ist Senden enabled und liegen Daten im TSR
Inc(transmitShiftCount1); // den Bitshift-Takt
if (transmitShiftCount1 >= shiftModeRatio1) then begin // entsprechend des Datenformats triggern
SystemInOut.cpuTXA1(TSR1); // und nach den entsprechenden Shift-Takten die Daten ausgeben
asciTSR1E := True; // Flags und
transmitShiftCount1 := 0; // Bitshift-Takt Zaehler korrigieren
end;
end;
if (ioCNTLA1.bit[RE] and (not asciRSR1F) and SystemInOut.cpuCanReadRXA1()) then begin // ist Empfangen enabled, RSR leer und neue Daten verfuegbar
Inc(receiveShiftCount1); // den Bitshift-Takt
if (receiveShiftCount1 >= shiftModeRatio1) then begin // entsprechend des Datenformats triggern
RSR1 := SystemInOut.cpuRXA1(); // und nach den entsprechenden Shift-Takten die Daten einlesen
asciRSR1F := True; // Flags und
receiveShiftCount1 := 0; // Bitshift-Takt Zaehler korrigieren
end;
end;
if (ioSTAT1.bit[TIE] and ioSTAT1.bit[TDRE]) then begin // wenn Transmit-Interrupts enabled und TDR leer
intASCI1 := True; // ASCI1-Interrupt ausloesen
end;
if (ioSTAT1.bit[RDRF] and asciRSR1F) then begin // wenn RDR voll und RSR voll
ioSTAT1.bit[OVRN] := True; // OVERRUN Flag setzen
end;
if (ioSTAT1.bit[RIE] and (ioSTAT1.bit[RDRF] or ioSTAT1.bit[OVRN])) then begin // wenn Receive-Interrupts enabled und RDRF oder OVRN gesetzt
intASCI1 := True; // ASCI1-Interrupt ausloesen
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doPrt0;
begin
Dec(ioTMDR0.Value);
if (ioTMDR0.Value = 0) then begin // Counter auf 0 ?
ioTMDR0.Value := ioRLDR0.Value; // aus dem Reload-Register neu laden
if (ioTCR.bit[TIE0]) then begin // und falls Interrupts eingeschaltet
ioTCR.bit[TIF0] := True; // Channel 0 Interrupt Flag setzen
intPRT0 := True; // und PRT-Interrupt generieren
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doPrt1;
begin
Dec(ioTMDR1.Value);
if (ioTMDR1.Value = 0) then begin // Counter auf 0 ?
ioTMDR1.Value := ioRLDR1.Value; // aus dem Reload-Register neu laden
if (ioTCR.bit[TIE1]) then begin // und falls Interrupts eingeschaltet
ioTCR.bit[TIF1] := True; // Channel 1 Interrupt Flag setzen
intPRT1 := True; // und PRT-Interrupt generieren
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doDma0;
begin
if (ioBCR0.Value = 0) then begin
ioBCR0.Value := $10000; // Vorbelegung fuer vollen 64K Transfer
end;
if (ioBCR0.Value = 1) then begin
tend0 := True; // beim letzten anstehenden DMA-Transfer TEND0 setzen
end;
case (ioDMODE.Value and (DMsel or SMsel)) of
$00: begin // Memory SAR0++ to Memory DAR0++ transfer
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Inc(ioDAR0.Value);
Inc(ioSAR0.Value);
Dec(ioBCR0.Value);
end;
$04: begin // Memory SAR0-- to Memory DAR0++ transfer
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Inc(ioDAR0.Value);
Dec(ioSAR0.Value);
Dec(ioBCR0.Value);
end;
$08: begin // Memory SAR0 to Memory DAR0++ transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Inc(ioDAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$0C: begin // 64k-I/O SAR0 to Memory DAR0++ transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, ioRead(ioSAR0.high, ioSAR0.low));
clockCycles := clockCycles + memWaitCycles + 6;
Inc(ioDAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$10: begin // Memory SAR0++ to Memory DAR0-- transfer
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Dec(ioDAR0.Value);
Inc(ioSAR0.Value);
Dec(ioBCR0.Value);
end;
$14: begin // Memory SAR0-- to Memory DAR0-- transfer
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Dec(ioDAR0.Value);
Dec(ioSAR0.Value);
Dec(ioBCR0.Value);
end;
$18: begin // Memory SAR0 to Memory DAR0-- transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Dec(ioDAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$1C: begin // 64k-I/O SAR0 to Memory DAR0-- transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, ioRead(ioSAR0.high, ioSAR0.low));
clockCycles := clockCycles + memWaitCycles + 6;
Dec(ioDAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$20: begin // Memory SAR0++ to Memory DAR0 transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Inc(ioSAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$24: begin // Memory SAR0-- to Memory DAR0 transfer
if (dreq0) then begin
systemmemory.Write(ioDAR0.Value, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + (2 * memWaitCycles) + 6;
Dec(ioSAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$30: begin // Memory SAR0++ to 64k-I/O DAR0 transfer
if (dreq0) then begin
ioWrite(ioDAR0.high, ioDAR0.low, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + memWaitCycles + 6;
Inc(ioSAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
$34: begin // Memory SAR0-- to 64k-I/O DAR0 transfer
if (dreq0) then begin
ioWrite(ioDAR0.high, ioDAR0.low, systemmemory.Read(ioSAR0.Value));
clockCycles := clockCycles + memWaitCycles + 6;
Dec(ioSAR0.Value);
Dec(ioBCR0.Value);
dreq0 := False;
end;
end;
end;
if (ioBCR0.Value = 0) then begin // aktueller DMA-Transfer beendet
ioDSTAT.bit[DE0] := False; // DMA0-Enable loeschen
dmaBurstMode := False;
if (not ioDSTAT.bit[DE1]) then begin // nur wenn Channel 1 nicht (noch) aktiv
ioDSTAT.bit[DME] := False; // DMA Main Enable loeschen
end;
if (ioDSTAT.bit[DIE0]) then begin // und falls Interrupts eingeschaltet
intDMA0 := True; // DMA0-Interrupt generieren
end;
if (not (asciDmaMode = OFF)) then begin // wenn der Transfer ein Memory <-> ASCI war
asciDmaMode := OFF; // den ASCI-DMA-MODE ausschalten
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.doDma1;
begin
if (ioBCR1.Value = 0) then begin
ioBCR1.Value := $10000; // Vorbelegung fuer vollen 64K Transfer
end;
if (ioBCR1.Value = 1) then begin
tend1 := True; // beim letzten anstehenden DMA-Transfehr TEND1 setzen
end;
case (ioDCNTL.Value and DMsel) of
$00: begin // Memory MAR1++ to I/O IAR1 transfer
if (dreq1) then begin
ioWrite(ioIAR1.high, ioIAR1.low, systemmemory.Read(ioMAR1.Value));
clockCycles := clockCycles + memWaitCycles + 6;
Inc(ioMAR1.Value);
Dec(ioBCR1.Value);
dreq1 := False;
end;
end;
$01: begin // Memory MAR1-- to I/O IAR1 transfer
if (dreq1) then begin
ioWrite(ioIAR1.high, ioIAR1.low, systemmemory.Read(ioMAR1.Value));
clockCycles := clockCycles + memWaitCycles + 6;
Dec(ioMAR1.Value);
Dec(ioBCR1.Value);
dreq1 := False;
end;
end;
$02: begin // I/O IAR1 to Memory MAR1++ transfer
if (dreq1) then begin
systemmemory.Write(ioMAR1.Value, ioRead(ioIAR1.high, ioIAR1.low));
clockCycles := clockCycles + memWaitCycles + 6;
Inc(ioMAR1.Value);
Dec(ioBCR1.Value);
dreq1 := False;
end;
end;
$03: begin // I/O IAR1 to Memory MAR1-- transfer
if (dreq1) then begin
systemmemory.Write(ioMAR1.Value, ioRead(ioIAR1.high, ioIAR1.low));
clockCycles := clockCycles + memWaitCycles + 6;
Dec(ioMAR1.Value);
Dec(ioBCR1.Value);
dreq1 := False;
end;
end;
end;
if (ioBCR1.Value = 0) then begin // aktueller DMA-Transfer beendet
ioDSTAT.bit[DE1] := False; // DMA1-Enable loeschen
if (not ioDSTAT.bit[DE0]) then begin // nur wenn Channel 0 nicht (noch) aktiv
ioDSTAT.bit[DME] := False; // DMA Main Enable loeschen
end;
if (ioDSTAT.bit[DIE1]) then begin // und falls Interrupts eingeschaltet
intDMA1 := True; // DMA1-Interrupt generieren
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.reset;
begin
regI := $00;
regR := $00;
regPC.Value := $0000;
regSP.Value := $0000;
IFF1 := False;
IFF2 := False;
HALT := False;
SLP := False;
tmpHALT := False;
tmpSLP := False;
dmaBurstMode := False;
dreq0 := False;
dreq1 := False;
tend0 := False;
tend1 := False;
intMode := IM0;
asciDmaMode := OFF;
ioCNTLA0.Value := $08;
ioCNTLA1.Value := $08;
ioCNTLB0.Value := $07;
ioCNTLB1.Value := $07;
ioSTAT0.Value := $02;
ioSTAT1.Value := $02;
ioTDR0 := $00;
ioTDR1 := $00;
ioRDR0 := $00;
ioRDR1 := $00;
ioCNTR.Value := $0F;
ioTRD := $00;
ioTMDR0.Value := $FFFF;
ioRLDR0.Value := $FFFF;
ioTCR.Value := $00;
ioTMDR1.Value := $FFFF;
ioRLDR1.Value := $FFFF;
ioFRC := $FF;
ioCMR.Value := $7F;
ioCCR.Value := $00;
ioSAR0.Value := $000000;
ioDAR0.Value := $000000;
ioBCR0.Value := $0000;
ioMAR1.Value := $000000;
ioIAR1.Value := $0000;
ioBCR1.Value := $0000;
ioDSTAT.Value := $32;
ioDMODE.Value := $C1;
ioDCNTL.Value := $F0;
ioIL := $00;
ioITC.Value := $01;
ioRCR.Value := $FC;
ioCBR := $00;
ioBBR := $00;
ioCBAR := $F0;
ioOMCR.Value := $FF;
ioICR.Value := $1F;
intTRAP := False;
intPRT0 := False;
intPRT1 := False;
intDMA0 := False;
intDMA1 := False;
intCSIO := False;
intASCI0 := False;
intASCI1 := False;
asciPhiDevideRatio0 := calcAsciPhiDevide(ioCNTLB0.Value);
shiftModeRatio0 := asciTransLength[ioCNTLA0.Value and MODSEL];
asciPhiDevideRatio1 := calcAsciPhiDevide(ioCNTLB1.Value);
shiftModeRatio1 := asciTransLength[ioCNTLA1.Value and MODSEL];
memWaitCycles := memCycles[((ioDCNTL.Value and MWIsel) shr $06)];
ioWaitCycles := ioCycles[((ioDCNTL.Value and IWIsel) shr $04)];
calcMmuPageTable;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.clrSlpHalt;
begin
HALT := False;
SLP := False;
tmpHALT := False;
tmpSLP := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.exec(opCount: DWord);
var
vectorAddress: word;
begin
while (opCount >= 1) do begin
Dec(opCount);
if (not (HALT or SLP or dmaBurstMode)) then begin
extraWaitCycles := 0;
execOp00Codes;
clockCycles := clockCycles + extraWaitCycles;
end
else begin
machineCycles := 1;
clockCycles := 1;
end;
while (machineCycles >= 1) do begin // Zaehlschleife fuer Maschinen-Zyklen
Dec(machineCycles);
if ((not SLP) and ioDSTAT.bit[DME]) then begin
if (ioDSTAT.bit[DE0]) then begin
doDma0;
end;
// DMA-Channel 1 darf nur laufen wenn DMA-Channel 0 nicht im Burst-Modus ist !!!
if ((not dmaBurstMode) and (ioDSTAT.bit[DE1])) then begin
doDma1;
end;
end;
end;
while (clockCycles >= 1) do begin // Zaehlschleife um den 'Systemtakt Phi' abbilden zu koennen
Dec(clockCycles);
if (not SLP) then begin
Dec(ioFRC); // FRC (Free running counter) wird bei jedem t_state um 1 heruntergezaehlt. Z8018x Family MPU User Manual Seite 172
end;
if (ioCNTLA0.bit[TE] or ioCNTLA0.bit[RE]) then begin // nur wenn ASCI0 Senden oder Empfangen soll
Inc(asciClockCount0); // wird der 'Takt' fuer ASCI0 gestartet
if (asciClockCount0 >= asciPhiDevideRatio0) then begin // nach Ablauf der entsprechenden System-Takte
asciClockCount0 := 0; // wird der Baudraten-Takt getriggert
if ((not ioSTAT0.bit[TDRE]) and asciTSR0E) then begin // ist TSR leer und liegen neue Daten im TDR
TSR0 := ioTDR0; // werden diese ins TSR kopiert
asciTSR0E := False; // und die Status-Flags entsprechend setzen
ioSTAT0.bit[TDRE] := True;
if (asciDmaMode = ASCI0SEND) then begin // falls ASCI DMA-Mode aktiv
dreq0 := True; // dann einen DMA-Request auslösen
end;
end;
if ((not ioSTAT0.bit[RDRF]) and asciRSR0F) then begin // ist RDR leer und liegen neue Daten im RSR
ioRDR0 := RSR0; // werden diese ins RDR kopier
asciRSR0F := False; // und die Status-Flags entsprechend setzen
ioSTAT0.bit[RDRF] := True;
if (asciDmaMode = ASCI0RECEIVE) then begin // falls ASCI DMA-Mode aktiv
dreq0 := True; // dann einen DMA-Request auslösen
end;
end;
doAsci0;
end;
end;
if (ioCNTLA1.bit[TE] or ioCNTLA1.bit[RE]) then begin// nur wenn ASCI1 Senden oder Empfangen soll
Inc(asciClockCount1); // wird der 'Takt' fuer ASCI1 gestartet
if (asciClockCount1 >= asciPhiDevideRatio1) then begin // nach Ablauf der entsprechenden System-Takte
asciClockCount1 := 0; // wird der Baudraten-Takt getriggert
if ((not ioSTAT1.bit[TDRE]) and asciTSR1E) then begin// ist TSR leer und liegen neue Daten im TDR
TSR1 := ioTDR1; // werden diese ins TSR kopiert
asciTSR1E := False; // und die Status-Flags entsprechend setzen
ioSTAT1.bit[TDRE] := True;
if (asciDmaMode = ASCI1SEND) then begin // falls ASCI DMA-Mode aktiv
dreq1 := True; // dann einen DMA-Request auslösen
end;
end;
if ((not ioSTAT1.bit[RDRF]) and asciRSR1F) then begin // ist RDR leer und liegen neue Daten im RSR
ioRDR1 := RSR1; // werden diese ins RDR kopier
asciRSR1F := False; // und die Status-Flags entsprechend setzen
ioSTAT1.bit[RDRF] := True;
if (asciDmaMode = ASCI1RECEIVE) then begin // falls ASCI DMA-Mode aktiv
dreq1 := True; // dann einen DMA-Request auslösen
end;
end;
doAsci1;
end;
end;
if ((not SLP) and (ioTCR.bit[TDE0] or ioTCR.bit[TDE1])) then begin // sobald einer der beiden PRT-Kanaele aktiv ist
Inc(prtClockCount); // wird der 'Takt' gestartet
if (prtClockCount >= 20) then begin // nach 20 Systemtakten
prtClockCount := 0; // wird der PRT-Takt getriggert
if (ioTCR.bit[TDE0]) then begin // PRT-Channel 0 aktiv
doPrt0;
end;
if (ioTCR.bit[TDE1]) then begin // PRT-Channel 1 aktiv
doPrt1;
end;
end;
end;
end;
// nach jeder OpCode Ausfuehrung werden moegliche Interrupts geprueft
// da nur interne Interrupts implementiert sind, wird auch nur diese
// Interrupt-Behandlung abgebildet
// Seite 81 , Abbildung 41 und Seite 82 , Tabelle 9
if (IFF1) then begin
if (intPRT0) then begin
tmpHALT := False;
tmpSLP := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $04));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intPRT0 := False;
end
else if (intPRT1) then begin
tmpHALT := False;
tmpSLP := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $06));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intPRT1 := False;
end
else if (intDMA0) then begin
tmpHALT := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $08));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intDMA0 := False;
end
else if (intDMA1) then begin
tmpHALT := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $0A));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intDMA1 := False;
end
else if (intCSIO) then begin // CSIO-Funktion derzeit noch nicht implementiert
tmpHALT := False;
tmpSLP := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $0C));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intCSIO := False;
end
else if (intASCI0) then begin
tmpHALT := False;
tmpSLP := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $0E));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intASCI0 := False;
end
else if (intASCI1) then begin
tmpHALT := False;
tmpSLP := False;
push(regPC.Value);
vectorAddress := ((regI shl 8) or ((ioIL and $E0) or $10));
regPC.low := memRead(vectorAddress);
regPC.high := memRead(vectorAddress + 1);
intASCI1 := False;
end;
end;
HALT := tmpHALT;
SLP := tmpSLP;
end;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.getCoreData: TCoreData;
var
coreData: TCoreData;
begin
with coreData do begin
A1 := regAF.A;
F1 := regAF.F;
B1 := regBC.B;
C1 := regBC.C;
BC1 := regBC.Value;
BCi1 := SystemMemory.Read(mmu[((regBC.Value shr 12) and $0F)] or (regBC.Value and $0FFF));
D1 := regDE.D;
E1 := regDE.E;
DE1 := regDE.Value;
DEi1 := SystemMemory.Read(mmu[((regDE.Value shr 12) and $0F)] or (regDE.Value and $0FFF));
H1 := regHL.H;
L1 := regHL.L;
HL1 := regHL.Value;
HLi1 := SystemMemory.Read(mmu[((regHL.Value shr 12) and $0F)] or (regHL.Value and $0FFF));
A2 := (regAF_ and $FF00) shr 8;
F2 := (regAF_ and $00FF);
B2 := (regBC_ and $FF00) shr 8;
C2 := (regBC_ and $00FF);
BC2 := regBC_;
BCi2 := SystemMemory.Read(mmu[((regBC_ shr 12) and $0F)] or (regBC_ and $0FFF));
D2 := (regDE_ and $FF00) shr 8;
E2 := (regDE_ and $00FF);
DE2 := regDE_;
DEi2 := SystemMemory.Read(mmu[((regDE_ shr 12) and $0F)] or (regDE_ and $0FFF));
H2 := (regHL_ and $FF00) shr 8;
L2 := (regHL_ and $00FF);
HL2 := regHL_;
HLi2 := SystemMemory.Read(mmu[((regHL_ shr 12) and $0F)] or (regHL_ and $0FFF));
I := regI;
R := regR;
IX := regIX.Value;
IY := regIY.Value;
SP := regSP.Value;
SPi := systemmemory.Read(mmu[((regSP.Value shr 12) and $0F)] or (regSP.Value and $0FFF));
PC := regPC.Value;
PCi := systemmemory.Read(mmu[((regPC.Value shr 12) and $0F)] or (regPC.Value and $0FFF));
PCmmu := mmu[((regPC.Value shr 12) and $0F)] or (regPC.Value and $0FFF);
IFF1 := IFF1;
IFF2 := IFF2;
intMode := intMode;
end;
Result := coreData;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.getIoRegData: TIoData;
var
ioRegData: TIoData;
begin
with ioRegData do begin
CNTLA0 := ioCNTLA0.Value;
CNTLA1 := ioCNTLA1.Value;
CNTLB0 := ioCNTLB0.Value;
CNTLB1 := ioCNTLB1.Value;
STAT0 := ioSTAT0.Value;
STAT1 := ioSTAT1.Value;
TDR0 := ioTDR0;
TDR1 := ioTDR1;
RDR0 := ioRDR0;
RDR1 := ioRDR1;
CNTR := ioCNTR.Value;
TRD := ioTRD;
TMDR0L := ioTMDR0.low;
TMDR0H := ioTMDR0.high;
RLDR0L := ioRLDR0.low;
RLDR0H := ioRLDR0.high;
TCR := ioTCR.Value;
TMDR1L := ioTMDR1.low;
TMDR1H := ioTMDR1.high;
RLDR1L := ioRLDR1.low;
RLDR1H := ioRLDR1.high;
FRC := ioFRC;
SAR0L := ioSAR0.low;
SAR0H := ioSAR0.high;
SAR0B := ioSAR0.bank;
DAR0L := ioDAR0.low;
DAR0H := ioDAR0.high;
DAR0B := ioDAR0.bank;
BCR0L := ioBCR0.low;
BCR0H := ioBCR0.high;
MAR1L := ioMAR1.low;
MAR1H := ioMAR1.high;
MAR1B := ioMAR1.bank;
IAR1L := ioIAR1.low;
IAR1H := ioIAR1.high;
BCR1L := ioBCR1.low;
BCR1H := ioBCR1.high;
DSTAT := ioDSTAT.Value;
DMODE := ioDMODE.Value;
DCNTL := ioDCNTL.Value;
IL := ioIL;
ITC := ioITC.Value;
RCR := ioRCR.Value;
CBR := ioCBR;
BBR := ioBBR;
CBAR := ioCBAR;
OMCR := ioOMCR.Value;
ICR := ioICR.Value;
end;
Result := ioRegData;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.setDREQ0;
begin
dreq0 := True;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.setDREQ1;
begin
dreq1 := True;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.getTEND0: boolean;
var
tmpTend: boolean;
begin
tmpTend := tend0;
tend0 := False;
Result := tmpTend;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.getTEND1: boolean;
var
tmpTend: boolean;
begin
tmpTend := tend1;
tend1 := False;
Result := tmpTend;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.inc8Bit(var Value: byte);
begin
Inc(Value);
regAF.Flag[H] := ((Value and $0F) = $00); // H is set if carry from bit 3; reset otherwise
regAF.Flag[PV] := (Value = $80); // P/V is set if r was 7FH before operation; reset otherwise
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.dec8Bit(var Value: byte);
begin
Dec(Value);
regAF.Flag[H] := ((Value and $0F) = $0F); // H is set if borrow from bit 4, reset otherwise
regAF.Flag[PV] := (Value = $7F); // P/V is set if r was 80H before operation; reset otherwise
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[N] := True;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.addA8Bit(const Value: byte);
var
tmpA: byte;
begin
tmpA := (regAF.A + Value);
regAF.Flag[PV] := (((regAF.A xor (not Value)) and (regAF.A xor tmpA) and $80) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[H] := ((((regAF.A and $0F) + (Value and $0F)) and $10) <> $00); // H is set if carry from bit 3; reset otherwise
regAF.Flag[S] := ((tmpA and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpA = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := (((regAF.A + Value) and $100) <> $00); // C is set if carry from bit 7; reset otherwise
regAF.Flag[N] := False;
regAF.A := tmpA;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.adcA8Bit(const Value: byte);
var
carry: byte;
tmpA: byte;
begin
carry := byte(regAF.Flag[C]);
tmpA := (regAF.A + Value + carry);
regAF.Flag[PV] := (((regAF.A xor (not Value)) and ((regAF.A xor tmpA) and $80)) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[H] := ((((regAF.A and $0F) + (Value and $0F) + carry) and $10) <> $00); // H is set if carry from bit 3; reset otherwise
regAF.Flag[S] := ((tmpA and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpA = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := (((regAF.A + Value + carry) and $100) <> $00); // C is set if carry from bit 7; reset otherwise
regAF.Flag[N] := False;
regAF.A := tmpA;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.subA8Bit(const Value: byte);
var
tmp: integer;
tmpA: byte;
begin
tmp := (regAF.A - Value);
tmpA := (tmp and $FF);
regAF.Flag[H] := ((((regAF.A and $0F) - (Value and $0F)) and $10) <> $00); // H is set if borrow from bit 4; reset otherwise
regAF.Flag[PV] := ((((regAF.A xor Value) and (regAF.A xor tmpA)) and $80) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[S] := ((tmpA and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpA = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := ((tmp and $100) <> $00); // C is set if borrow; reset otherwise
regAF.Flag[N] := True;
regAF.A := tmpA;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.sbcA8Bit(const Value: byte);
var
carry: byte;
tmpA: byte;
begin
carry := byte(regAF.Flag[C]);
tmpA := (regAF.A - Value - carry);
regAF.Flag[H] := ((((regAF.A and $0F) - (Value and $0F) - carry) and $10) <> $00); // H is set if borrow from bit 4; reset otherwise
regAF.Flag[PV] := ((((regAF.A xor Value) and (regAF.A xor tmpA)) and $80) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[S] := ((tmpA and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpA = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := (((regAF.A - Value - carry) and $100) <> $00); // C is set if borrow; reset otherwise
regAF.Flag[N] := True;
regAF.A := tmpA;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.andA8Bit(const Value: byte);
begin
regAF.A := (regAF.A and Value);
regAF.Flag[S] := ((regAF.A and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (regAF.A = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[regAF.A]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := True;
regAF.Flag[N] := False;
regAF.Flag[C] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.xorA8Bit(const Value: byte);
begin
regAF.A := (regAF.A xor Value);
regAF.Flag[S] := ((regAF.A and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (regAF.A = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[regAF.A]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
regAF.Flag[C] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.orA8Bit(const Value: byte);
begin
regAF.A := (regAF.A or Value);
regAF.Flag[S] := ((regAF.A and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (regAF.A = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[regAF.A]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
regAF.Flag[C] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.cpA8Bit(const Value: byte);
var
test: byte;
begin
test := (regAF.A - Value);
regAF.Flag[S] := ((test and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (test = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[H] := ((((regAF.A and $0F) - (Value and $0F)) and $10) <> $00); // H is set if borrow from bit 4; reset otherwise
regAF.Flag[PV] := (((regAF.A xor Value) and (regAF.A xor test) and $80) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[C] := ((regAF.A - Value) < $00); // C is set if borrow; reset otherwise
regAF.Flag[N] := True;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.rlc8Bit(var Value: byte);
begin
regAF.Flag[C] := ((Value and $80) <> $00); // C is data from bit 7 of source register
Value := ((Value shl 1) or byte(regAF.Flag[C]));
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.rrc8Bit(var Value: byte);
begin
regAF.Flag[C] := ((Value and $01) <> $00); // C is data from bit 0 of source register
Value := ((Value shr 1) or (byte(regAF.Flag[C]) shl 7));
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.rl8Bit(var Value: byte);
var
tmpCarry: boolean;
begin
tmpCarry := regAF.Flag[C];
regAF.Flag[C] := ((Value and $80) <> $00); // C is data from bit 7 of source register
Value := ((Value shl 1) or byte(tmpCarry));
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.rr8Bit(var Value: byte);
var
tmpCarry: boolean;
begin
tmpCarry := regAF.Flag[C];
regAF.Flag[C] := ((Value and $01) <> $00); // C is data from bit 0 of source register
Value := ((Value shr 1) or (byte(tmpCarry) shl 7));
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.sla8Bit(var Value: byte);
begin
regAF.Flag[C] := ((Value and $80) <> $00); // C is data from bit 7 of source register
Value := (Value shl 1);
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.sra8Bit(var Value: byte);
var
tmpValue: byte;
begin
regAF.Flag[C] := ((Value and $01) <> $00); // C is data from bit 0 of source register
tmpValue := ((Value shr 1) or (Value and $80));
regAF.Flag[PV] := parity[tmpValue]; // P/V is set if parity even; reset otherwise
regAF.Flag[S] := ((tmpValue and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpValue = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
Value := tmpValue;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.srl8Bit(var Value: byte);
begin
regAF.Flag[C] := ((Value and $01) <> $00); // C is data from bit 0 of source register
Value := (Value shr 1);
regAF.Flag[S] := ((Value and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (Value = $00); // Z is set if result is zero; reset otherwise
regAF.Flag[PV] := parity[Value]; // P/V is set if parity even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.tstBit(const Bit: byte; const Value: byte);
begin
regAF.Flag[Z] := (Value and (1 shl Bit) = $00); // Z is set if specified bit is 0; reset otherwise
regAF.Flag[H] := True;
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.resBit(const Bit: byte; var Value: byte);
begin
Value := (Value and not (1 shl Bit));
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.setBit(const Bit: byte; var Value: byte);
begin
Value := (Value or (1 shl Bit));
end;
// -------------------------------------------------------------------------------
procedure TZ180Cpu.tstA8Bit(const Value: byte);
var
tmpByte: byte;
begin
tmpByte := (regAF.A and Value);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if the result is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if the result is zero; reset otherwise
regAF.Flag[PV] := parity[tmpByte]; // P/V is set if parity is even; reset otherwise
regAF.Flag[H] := True;
regAF.Flag[N] := False;
regAF.Flag[C] := False;
end;
// --------------------------------------------------------------------------------
function TZ180Cpu.inreg8Bit(const portHi: byte; const portLo: byte): byte;
var
tmpByte: byte;
begin
tmpByte := ioRead(portHi, portLo);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if input data is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if input data is zero; reset otherwise
regAF.Flag[PV] := parity[tmpByte]; // P/V is set if parity is even; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
Result := tmpByte;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.addHL16Bit(const Value: word);
begin
regAF.Flag[H] := ((regHL.Value and $0FFF) + (Value and $0FFF) > $0FFF); // H is set if carry out of bit 11; reset otherwise
regAF.Flag[C] := ((regHL.Value + Value) > $FFFF); // C is set if carry from bit 15; reset otherwise
regHL.Value := (regHL.Value + Value);
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.adcHL16Bit(const Value: word);
var
carry: byte;
tmpHL: dword;
begin
carry := byte(regAF.Flag[C]);
tmpHL := (regHL.Value + Value + carry);
regAF.Flag[S] := ((tmpHL and $8000) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpHL = $0000); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := ((tmpHL and $10000) <> $00); // C is set if carry from bit 15; reset otherwise
regAF.Flag[PV] := (((regHL.Value xor (not Value)) and (regHL.Value xor tmpHL) and $8000) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[H] := ((((regHL.Value and $0FFF) + (Value and $0FFF) + carry) and $1000) <> $00); // H is set if carry out of bit 11; reset otherwise
regAF.Flag[N] := False;
regHL.Value := tmpHL;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.sbcHL16Bit(const Value: word);
var
carry: byte;
tmpHL: dword;
begin
carry := byte(regAF.Flag[C]);
tmpHL := (regHL.Value - Value - carry);
regAF.Flag[S] := ((tmpHL and $8000) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpHL = $0000); // Z is set if result is zero; reset otherwise
regAF.Flag[C] := ((tmpHL and $10000) <> $00); // C is set if borrow; reset otherwise
regAF.Flag[PV] := (((regHL.Value xor Value) and (regHL.Value xor tmpHL) and $8000) <> $00); // P/V is set if overflow; reset otherwise
regAF.Flag[H] := ((((regHL.Value and $0FFF) - (Value and $0FFF) - carry) and $1000) <> $00); // H is set if borrow from bit 12; reset otherwise
regAF.Flag[N] := True;
regHL.Value := tmpHL and $FFFF;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.addIX16Bit(const Value: word);
begin
regAF.Flag[H] := ((regIX.Value and $0FFF) + (Value and $0FFF) > $0FFF); // H is set if carry out of bit 11; reset otherwise
regAF.Flag[C] := ((regIX.Value + Value) > $FFFF); // C is set if carry from bit 15; reset otherwise
regIX.Value := (regIX.Value + Value);
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.addIY16Bit(const Value: word);
begin
regAF.Flag[H] := ((regIY.Value and $0FFF) + (Value and $0FFF) > $0FFF); // H is set if carry out of bit 11; reset otherwise
regAF.Flag[C] := ((regIY.Value + Value) > $FFFF); // C is set if carry from bit 15; reset otherwise
regIY.Value := (regIY.Value + Value);
regAF.Flag[N] := False;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.push(const Value: word); inline;
begin
Dec(regSP.Value);
memWrite(regSP.Value, ((Value and $FF00) shr 8));
Dec(regSP.Value);
memWrite(regSP.Value, (Value and $00FF));
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.pop(var Value: word); inline;
var
popLow, popHigh: byte;
begin
popLow := memRead(regSP.Value);
Inc(regSP.Value);
popHigh := memRead(regSP.Value);
Inc(regSP.Value);
Value := (popHigh shl 8) + popLow;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOp00Codes;
var
opCode, jmpOffset, tmpByte: byte;
tmpWord: Treg16;
tmpFlag: boolean;
begin
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$00: begin // OP-Code 0x00 : NOP
machineCycles := 1;
clockCycles := 3;
end;
$01: begin // OP-Code 0x01 : LD BC,nn;
regBC.C := memRead(regPC.Value);
Inc(regPC.Value);
regBC.B := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$02: begin // OP-Code 0x02 : LD (BC),A
memWrite(regBC.Value, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$03: begin // OP-Code 0x03 : INC BC
Inc(regBC.Value);
machineCycles := 2;
clockCycles := 4;
end;
$04: begin // OP-Code 0x04 : INC B
inc8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$05: begin // OP-Code 0x05 : DEC B
dec8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$06: begin // OP-Code 0x06 : LD B,n
regBC.B := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$07: begin // OP-Code 0x07 : RLCA
regAF.Flag[C] := ((regAF.A and $80) <> $00);
regAF.A := ((regAF.A shl 1) or byte(regAF.Flag[C]));
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$08: begin // OP-Code 0x08 : EX AF,AF'
tmpWord.Value := regAF.Value;
regAF.Value := regAF_;
regAF_ := tmpWord.Value;
machineCycles := 2;
clockCycles := 4;
end;
$09: begin // OP-Code 0x09 : ADD HL,BC
addHL16Bit(regBC.Value);
machineCycles := 5;
clockCycles := 7;
end;
$0A: begin // OP-Code 0x0A : LD A,(BC)
regAF.A := memRead(regBC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$0B: begin // OP-Code 0x0B : DEC BC
Dec(regBC.Value);
machineCycles := 2;
clockCycles := 4;
end;
$0C: begin // OP-Code 0x0C : INC C
inc8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$0D: begin // OP-Code 0x0D : DEC C
dec8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$0E: begin // OP-Code 0x0E : LD C,n
regBC.C := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$0F: begin // OP-Code 0x0F : RRCA
regAF.Flag[C] := ((regAF.A and $01) <> $00);
regAF.A := ((regAF.A shr 1) or (byte(regAF.Flag[C]) shl 7));
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$10: begin // OP-Code 0x10 : DJNZ d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
Dec(regBC.B);
if (regBC.B <> $00) then begin
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 5;
clockCycles := 9;
end
else begin
machineCycles := 3;
clockCycles := 7;
end;
end;
$11: begin // OP-Code 0x11 : LD DE,nn
regDE.E := memRead(regPC.Value);
Inc(regPC.Value);
regDE.D := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$12: begin // OP-Code 0x12 : LD (DE),A
memWrite(regDE.Value, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$13: begin // OP-Code 0x13 : INC DE
Inc(regDE.Value);
machineCycles := 2;
clockCycles := 4;
end;
$14: begin // OP-Code 0x14 : INC D
inc8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$15: begin // OP-Code 0x15 : DEC D
dec8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$16: begin // OP-Code 0x16 : LD D,n
regDE.D := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$17: begin // OP-Code 0x17 : RLA
tmpFlag := ((regAF.A and $80) <> $00);
regAF.A := ((regAF.A shl 1) or byte(regAF.Flag[C]));
regAF.Flag[C] := tmpFlag;
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$18: begin // OP-Code 0x18 : JR d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 4;
clockCycles := 8;
end;
$19: begin // OP-Code 0x19 : ADD HL,DE
addHL16Bit(regDE.Value);
machineCycles := 5;
clockCycles := 7;
end;
$1A: begin // OP-Code 0x1A : LD A,(DE)
regAF.A := memRead(regDE.Value);
machineCycles := 2;
clockCycles := 6;
end;
$1B: begin // OP-Code 0x1B : DEC DE
Dec(regDE.Value);
machineCycles := 2;
clockCycles := 4;
end;
$1C: begin // OP-Code 0x1C : INC E
inc8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$1D: begin // OP-Code 0x1D : DEC E
dec8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$1E: begin // OP-Code 0x1E : LD E,n
regDE.E := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$1F: begin // OP-Code 0x1F : RRA
tmpFlag := ((regAF.A and $01) <> $00);
regAF.A := ((regAF.A shr 1) or (byte(regAF.Flag[C]) shl 7));
regAF.Flag[C] := tmpFlag;
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$20: begin // OP-Code 0x20 : JR NZ,d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = False) then begin
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 4;
clockCycles := 8;
end
else begin
machineCycles := 2;
clockCycles := 6;
end;
end;
$21: begin // OP-Code 0x21 : LD HL,nn
regHL.L := memRead(regPC.Value);
Inc(regPC.Value);
regHL.H := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$22: begin // OP-Code 0x22 : LD (nn),HL
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regHL.L);
memWrite(tmpWord.Value + 1, regHL.H);
machineCycles := 6;
clockCycles := 16;
end;
$23: begin // OP-Code 0x23 : INC HL
Inc(regHL.Value);
machineCycles := 2;
clockCycles := 4;
end;
$24: begin // OP-Code 0x24 : INC H
inc8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$25: begin // OP-Code 0x25 : DEC H
dec8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$26: begin // OP-Code 0x26 : LD H,n
regHL.H := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$27: begin // OP-Code 0x27 : DAA
//NOTE: original Z80 DAA implementation mit Carry Flag.
// Die Z180CPU verarbeitet das Carry Flag nicht!!!
tmpByte := $00;
if (regAF.Flag[H] or ((regAF.A and $0F) > $09)) then begin
tmpByte := tmpByte or $06;
end;
if (regAF.Flag[C] or (regAF.A > $9F)) then begin
tmpByte := tmpByte or $60;
end;
if ((regAF.A > $8F) and ((regAF.A and $0F) > $09)) then begin
tmpByte := tmpByte or $60;
end;
if (regAF.A > $99) then begin
regAF.Flag[C] := True;
end;
if (regAF.Flag[N]) then begin
regAF.Flag[H] := ((((regAF.A and $0F) - (tmpByte and $0f)) and $10) <> $00);
regAF.A := (regAF.A - tmpByte);
end
else begin
regAF.Flag[H] := ((((regAF.A and $0F) + (tmpByte and $0F)) and $10) <> $00);
regAF.A := (regAF.A + tmpByte);
end;
regAF.Flag[PV] := parity[regAF.A];
regAF.Flag[S] := ((regAF.A and $80) <> $00);
regAF.Flag[Z] := (regAF.A = $00);
machineCycles := 2;
clockCycles := 4;
end;
$28: begin // OP-Code 0x28 : JR Z,d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = True) then begin
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 4;
clockCycles := 8;
end
else begin
machineCycles := 2;
clockCycles := 6;
end;
end;
$29: begin // OP-Code 0x29 : ADD HL,HL
addHL16Bit(regHL.Value);
machineCycles := 5;
clockCycles := 7;
end;
$2A: begin // OP-Code 0x2A : LD HL,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regHL.L := memRead(tmpWord.Value);
regHL.H := memRead(tmpWord.Value + 1);
machineCycles := 5;
clockCycles := 15;
end;
$2B: begin // OP-Code 0x2B : DEC HL
Dec(regHL.Value);
machineCycles := 2;
clockCycles := 4;
end;
$2C: begin // OP-Code 0x2C : INC L
inc8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$2D: begin // OP-Code 0x2D : DEC L
dec8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$2E: begin // OP-Code 0x2E : LD L,n
regHL.L := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$2F: begin // OP-Code 0x2F : CPL
regAF.A := (regAF.A xor $FF);
regAF.Flag[H] := True;
regAF.Flag[N] := True;
machineCycles := 1;
clockCycles := 3;
end;
$30: begin // OP-Code 0x30 : JR NC,d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = False) then begin
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 4;
clockCycles := 8;
end
else begin
machineCycles := 2;
clockCycles := 6;
end;
end;
$31: begin // OP-Code 0x31 : LD SP,nn
regSP.low := memRead(regPC.Value);
Inc(regPC.Value);
regSP.high := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$32: begin // OP-Code 0x32 : LD (nn),A
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regAF.A);
machineCycles := 5;
clockCycles := 13;
end;
$33: begin // OP-Code 0x33 : INC SP
Inc(regSP.Value);
machineCycles := 2;
clockCycles := 4;
end;
$34: begin // OP-Code 0x34 : INC (HL)
tmpByte := memRead(regHL.Value);
inc8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 4;
clockCycles := 10;
end;
$35: begin // OP-Code 0x35 : DEC (HL)
tmpByte := memRead(regHL.Value);
dec8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 4;
clockCycles := 10;
end;
$36: begin // OP-Code 0x36 : LD (HL),n
memWrite(regHL.Value, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$37: begin // OP-Code 0x37 : SCF
regAF.Flag[C] := True;
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$38: begin // OP-Code 0x38 : JR C,d
jmpOffset := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = True) then begin
regPC.Value := regPC.Value + shortint(jmpOffset);
machineCycles := 4;
clockCycles := 8;
end
else begin
machineCycles := 2;
clockCycles := 6;
end;
end;
$39: begin // OP-Code 0x39 : ADD HL,SP
addHL16Bit(regSP.Value);
machineCycles := 5;
clockCycles := 7;
end;
$3A: begin // OP-Code 0x3A : LD A,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regAF.A := memRead(tmpWord.Value);
machineCycles := 4;
clockCycles := 12;
end;
$3B: begin // OP-Code 0x3B : DEC SP
Dec(regSP.Value);
machineCycles := 2;
clockCycles := 4;
end;
$3C: begin // OP-Code 0x3C : INC A
inc8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$3D: begin // OP-Code 0x3D : DEC A
dec8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$3E: begin // OP-Code 0x3E : LD A,n
regAF.A := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$3F: begin // OP-Code 0x3F : CCF
regAF.Flag[H] := regAF.Flag[C];
regAF.Flag[C] := not regAF.Flag[C];
regAF.Flag[N] := False;
machineCycles := 1;
clockCycles := 3;
end;
$40: begin // OP-Code 0x40 : LD B,B
regBC.B := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$41: begin // OP-Code 0x41 : LD B,C
regBC.B := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$42: begin // OP-Code 0x42 : LD B,D
regBC.B := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$43: begin // OP-Code 0x43 : LD B,E
regBC.B := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$44: begin // OP-Code 0x44 : LD B,H
regBC.B := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$45: begin // OP-Code 0x45 : LD B,L
regBC.B := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$46: begin // OP-Code 0x46 : LD B,(HL)
regBC.B := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$47: begin // OP-Code 0x47 : LD B,A
regBC.B := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$48: begin // OP-Code 0x48 : LD C,B
regBC.C := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$49: begin // OP-Code 0x49 : LD C,C
regBC.C := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$4A: begin // OP-Code 0x4A : LD C,D
regBC.C := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$4B: begin // OP-Code 0x4B : LD C,E
regBC.C := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$4C: begin // OP-Code 0x4C : LD C,H
regBC.C := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$4D: begin // OP-Code 0x4D : LD C,L
regBC.C := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$4E: begin // OP-Code 0x4E : LD C,(HL)
regBC.C := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$4F: begin // OP-Code 0x4F : LD C,A
regBC.C := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$50: begin // OP-Code 0x50 : LD D,B
regDE.D := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$51: begin // OP-Code 0x51 : LD D,C
regDE.D := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$52: begin // OP-Code 0x52 : LD D,D
regDE.D := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$53: begin // OP-Code 0x53 : LD D,E
regDE.D := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$54: begin // OP-Code 0x54 : LD D,H
regDE.D := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$55: begin // OP-Code 0x55 : LD D,L
regDE.D := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$56: begin // OP-Code 0x56 : LD D,(HL)
regDE.D := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$57: begin // OP-Code 0x57 : LD D,A
regDE.D := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$58: begin // OP-Code 0x58 : LD E,B
regDE.E := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$59: begin // OP-Code 0x59 : LD E,C
regDE.E := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$5A: begin // OP-Code 0x5A : LD E,D
regDE.E := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$5B: begin // OP-Code 0x5B : LD E,E
regDE.E := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$5C: begin // OP-Code 0x5C : LD E,H
regDE.E := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$5D: begin // OP-Code 0x5D : LD E,L
regDE.E := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$5E: begin // OP-Code 0x5E : LD E,(HL)
regDE.E := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$5F: begin // OP-Code 0x5F : LD E,A
regDE.E := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$60: begin // OP-Code 0x60 : LD H,B
regHL.H := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$61: begin // OP-Code 0x61 : LD H,C
regHL.H := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$62: begin // OP-Code 0x62 : LD H,D
regHL.H := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$63: begin // OP-Code 0x63 : LD H,E
regHL.H := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$64: begin // OP-Code 0x64 : LD H,H
regHL.H := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$65: begin // OP-Code 0x65 : LD H,L
regHL.H := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$66: begin // OP-Code 0x66 : LD H,(HL)
regHL.H := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$67: begin // OP-Code 0x67 : LD H,A
regHL.H := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$68: begin // OP-Code 0x68 : LD L,B
regHL.L := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$69: begin // OP-Code 0x69 : LD L,C
regHL.L := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$6A: begin // OP-Code 0x6A : LD L,D
regHL.L := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$6B: begin // OP-Code 0x6B : LD L,E
regHL.L := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$6C: begin // OP-Code 0x6C : LD L,H
regHL.L := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$6D: begin // OP-Code 0x6D : LD L,L
regHL.L := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$6E: begin // OP-Code 0x6E : LD L,(HL)
regHL.L := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$6F: begin // OP-Code 0x6F : LD L,A
regHL.L := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$70: begin // OP-Code 0x70 : LD (HL),B
memWrite(regHL.Value, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$71: begin // OP-Code 0x71 : LD (HL),C
memWrite(regHL.Value, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$72: begin // OP-Code 0x72 : LD (HL),D
memWrite(regHL.Value, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$73: begin // OP-Code 0x73 : LD (HL),E
memWrite(regHL.Value, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$74: begin // OP-Code 0x74 : LD (HL),H
memWrite(regHL.Value, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$75: begin // OP-Code 0x75 : LD (HL),L
memWrite(regHL.Value, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$76: begin // OP-Code 0x76 : HALT
tmpHALT := True;
machineCycles := 1;
clockCycles := 3;
end;
$77: begin // OP-Code 0x77 : LD (HL),A
memWrite(regHL.Value, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$78: begin // OP-Code 0x78 : LD A,B
regAF.A := regBC.B;
machineCycles := 2;
clockCycles := 4;
end;
$79: begin // OP-Code 0x79 : LD A,C
regAF.A := regBC.C;
machineCycles := 2;
clockCycles := 4;
end;
$7A: begin // OP-Code 0x7A : LD A,D
regAF.A := regDE.D;
machineCycles := 2;
clockCycles := 4;
end;
$7B: begin // OP-Code 0x7B : LD A,E
regAF.A := regDE.E;
machineCycles := 2;
clockCycles := 4;
end;
$7C: begin // OP-Code 0x7C : LD A,H
regAF.A := regHL.H;
machineCycles := 2;
clockCycles := 4;
end;
$7D: begin // OP-Code 0x7D : LD A,L
regAF.A := regHL.L;
machineCycles := 2;
clockCycles := 4;
end;
$7E: begin // OP-Code 0x7E : LD A,(HL)
regAF.A := memRead(regHL.Value);
machineCycles := 2;
clockCycles := 6;
end;
$7F: begin // OP-Code 0x7F : LD A,A
regAF.A := regAF.A;
machineCycles := 2;
clockCycles := 4;
end;
$80: begin // OP-Code 0x80 : ADD A,B
addA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$81: begin // OP-Code 0x81 : ADD A,C
addA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$82: begin // OP-Code 0x82 : ADD A,D
addA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$83: begin // OP-Code 0x83 : ADD A,E
addA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$84: begin // OP-Code 0x84 : ADD A,H
addA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$85: begin // OP-Code 0x85 : ADD A,L
addA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$86: begin // OP-Code 0x86 : ADD A,(HL)
addA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$87: begin // OP-Code 0x87 : ADD A,A
addA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$88: begin // OP-Code 0x88 : ADC A,B
adcA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$89: begin // OP-Code 0x89 : ADC A,C
adcA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$8A: begin // OP-Code 0x8A : ADC A,D
adcA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$8B: begin // OP-Code 0x8B : ADC A,E
adcA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$8C: begin // OP-Code 0x8C : ADC A,H
adcA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$8D: begin // OP-Code 0x8D : ADC A,L
adcA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$8E: begin // OP-Code 0x8E : ADC A,(HL)
adcA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$8F: begin // OP-Code 0x8F : ADC A,A
adcA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$90: begin // OP-Code 0x90 : SUB A,B
subA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$91: begin // OP-Code 0x91 : SUB A,C
subA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$92: begin // OP-Code 0x92 : SUB A,D
subA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$93: begin // OP-Code 0x93 : SUB A,E
subA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$94: begin // OP-Code 0x94 : SUB A,H
subA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$95: begin // OP-Code 0x95 : SUB A,L
subA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$96: begin // OP-Code 0x96 : SUB A,(HL)
subA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$97: begin // OP-Code 0x97 : SUB A,A
subA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$98: begin // OP-Code 0x98 : SBC A,B
sbcA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$99: begin // OP-Code 0x99 : SBC A,C
sbcA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$9A: begin // OP-Code 0x9A : SBC A,D
sbcA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$9B: begin // OP-Code 0x9B : SBC A,E
sbcA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$9C: begin // OP-Code 0x9C : SBC A,H
sbcA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$9D: begin // OP-Code 0x9D : SBC A,L
sbcA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$9E: begin // OP-Code 0x9E : SBC A,(HL)
sbcA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$9F: begin // OP-Code 0x9F : SBC A,A
sbcA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$A0: begin // OP-Code 0xA0 : AND B
andA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$A1: begin // OP-Code 0xA1 : AND C
andA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$A2: begin // OP-Code 0xA2 : AND D
andA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$A3: begin // OP-Code 0xA3 : AND E
andA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$A4: begin // OP-Code 0xA4 : AND H
andA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$A5: begin // OP-Code 0xA5 : AND L
andA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$A6: begin // OP-Code 0xA6 : AND (HL)
andA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$A7: begin // OP-Code 0xA7 : AND A
andA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$A8: begin // OP-Code 0xA8 : XOR B
xorA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$A9: begin // OP-Code 0xA9 : XOR C
xorA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$AA: begin // OP-Code 0xAA : XOR D
xorA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$AB: begin // OP-Code 0xAB : XOR E
xorA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$AC: begin // OP-Code 0xAC : XOR H
xorA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$AD: begin // OP-Code 0xAD : XOR L
xorA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$AE: begin // OP-Code 0xAE : XOR (HL)
xorA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$AF: begin // OP-Code 0xAF : XOR A
xorA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$B0: begin // OP-Code 0xB0 : OR B
orA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$B1: begin // OP-Code 0xB1 : OR C
orA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$B2: begin // OP-Code 0xB2 : OR D
orA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$B3: begin // OP-Code 0xB3 : OR E
orA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$B4: begin // OP-Code 0xB4 : OR H
orA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$B5: begin // OP-Code 0xB5 : OR L
orA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$B6: begin // OP-Code 0xB6 : OR (HL)
orA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$B7: begin // OP-Code 0xB7 : OR A
orA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$B8: begin // OP-Code 0xB8 : CP B
cpA8Bit(regBC.B);
machineCycles := 2;
clockCycles := 4;
end;
$B9: begin // OP-Code 0xB9 : CP C
cpA8Bit(regBC.C);
machineCycles := 2;
clockCycles := 4;
end;
$BA: begin // OP-Code 0xBA : CP D
cpA8Bit(regDE.D);
machineCycles := 2;
clockCycles := 4;
end;
$BB: begin // OP-Code 0xBB : CP E
cpA8Bit(regDE.E);
machineCycles := 2;
clockCycles := 4;
end;
$BC: begin // OP-Code 0xBC : CP H
cpA8Bit(regHL.H);
machineCycles := 2;
clockCycles := 4;
end;
$BD: begin // OP-Code 0xBD : CP L
cpA8Bit(regHL.L);
machineCycles := 2;
clockCycles := 4;
end;
$BE: begin // OP-Code 0xBE : CP (HL)
cpA8Bit(memRead(regHL.Value));
machineCycles := 2;
clockCycles := 6;
end;
$BF: begin // OP-Code 0xBF : CP A
cpA8Bit(regAF.A);
machineCycles := 2;
clockCycles := 4;
end;
$C0: begin // OP-Code 0xC0 : RET NZ
if (regAF.Flag[Z] = False) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$C1: begin // OP-Code 0xC1 : POP BC
pop(regBC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$C2: begin // OP-Code 0xC2 : JP NZ,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = False) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$C3: begin // OP-Code 0xC3 : JP nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end;
$C4: begin // OP-Code 0xC4 : CALL NZ,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = False) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$C5: begin // OP-Code 0xC5 : PUSH BC
push(regBC.Value);
machineCycles := 5;
clockCycles := 11;
end;
$C6: begin // OP-Code 0xC6 : ADD A,n
addA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$C7: begin // OP-Code 0xC7 : RST 00H
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 5;
clockCycles := 11;
end;
$C8: begin // OP-Code 0xC8 : RET Z
if (regAF.Flag[Z] = True) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$C9: begin // OP-Code 0xC9 : RET
pop(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$CA: begin // OP-Code 0xCA : JP Z,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = True) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$CB: begin // OP-Code 0xCB : Prefix 'CB'
execOpCbCodes;
end;
$CC: begin // OP-Code 0xCC : CALL Z,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[Z] = True) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$CD: begin // OP-Code 0xCD : CALL nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end;
$CE: begin // OP-Code 0xCE : ADC A,n
adcA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$CF: begin // OP-Code 0xCF : RST 08H
push(regPC.Value);
regPC.Value := $0008;
machineCycles := 5;
clockCycles := 11;
end;
$D0: begin // OP-Code 0xD0 : RET NC
if (regAF.Flag[C] = False) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$D1: begin // OP-Code 0xD1 : POP DE
pop(regDE.Value);
machineCycles := 3;
clockCycles := 9;
end;
$D2: begin // OP-Code 0xD2 : JP NC,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = False) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$D3: begin // OP-Code 0xD3 : OUT (n),A
ioWrite(regAF.A, memRead(regPC.Value), regAF.A);
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end;
$D4: begin // OP-Code 0xD4 : CALL NC,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = False) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$D5: begin // OP-Code 0xD5 : PUSH DE
push(regDE.Value);
machineCycles := 5;
clockCycles := 11;
end;
$D6: begin // OP-Code 0xD6 : SUB A,n
subA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 4;
end;
$D7: begin // OP-Code 0xD7 : RST 10H
push(regPC.Value);
regPC.Value := $0010;
machineCycles := 5;
clockCycles := 11;
end;
$D8: begin // OP-Code 0xD8 : RET C
if (regAF.Flag[C] = True) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$D9: begin // OP-Code 0xD9 : EXX
tmpWord.Value := regBC.Value;
regBC.Value := regBC_;
regBC_ := tmpWord.Value;
tmpWord.Value := regDE.Value;
regDE.Value := regDE_;
regDE_ := tmpWord.Value;
tmpWord.Value := regHL.Value;
regHL.Value := regHL_;
regHL_ := tmpWord.Value;
machineCycles := 1;
clockCycles := 3;
end;
$DA: begin // OP-Code 0xDA : JP C,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = True) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$DB: begin // OP-Code 0xDB : IN A,(n)
regAF.A := ioRead(regAF.A, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$DC: begin // OP-Code 0xDC : CALL C,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[C] = True) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$DD: begin // OP-Code 0xDD : Prefix 'DD'
execOpDdCodes;
end;
$DE: begin // OP-Code 0xDE : SBC A,n
sbcA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$DF: begin // OP-Code 0xDF : RST 18H
push(regPC.Value);
regPC.Value := $0018;
machineCycles := 5;
clockCycles := 11;
end;
$E0: begin // OP-Code 0xE0 : RET PO
if (regAF.Flag[PV] = False) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$E1: begin // OP-Code 0xE1 : POP HL
pop(regHL.Value);
machineCycles := 3;
clockCycles := 9;
end;
$E2: begin // OP-Code 0xE2 : JP PO,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[PV] = False) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$E3: begin // OP-Code 0xE3 : EX (SP),HL
tmpWord.low := memRead(regSP.Value);
tmpWord.high := memRead(regSP.Value + 1);
memWrite(regSP.Value + 1, regHL.H);
memWrite(regSP.Value, regHL.L);
regHL.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end;
$E4: begin // OP-Code 0xE4 : CALL PO,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[PV] = False) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$E5: begin // OP-Code 0xE5 : PUSH HL
push(regHL.Value);
machineCycles := 5;
clockCycles := 11;
end;
$E6: begin // OP-Code 0xE6 : AND n
andA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$E7: begin // OP-Code 0xE7 : RST 20H
push(regPC.Value);
regPC.Value := $0020;
machineCycles := 5;
clockCycles := 11;
end;
$E8: begin // OP-Code 0xE8 : RET PE
if (regAF.Flag[PV] = True) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$E9: begin // OP-Code 0xE9 : JP (HL)
regPC.Value := regHL.Value;
machineCycles := 1;
clockCycles := 3;
end;
$EA: begin // OP-Code 0xEA : JP PE,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[PV] = True) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$EB: begin // OP-Code 0xEB : EX DE,HL
tmpWord.Value := regDE.Value;
regDE.Value := regHL.Value;
regHL.Value := tmpWord.Value;
machineCycles := 1;
clockCycles := 3;
end;
$EC: begin // OP-Code 0xEC : CALL PE,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[PV] = True) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$ED: begin // OP-Code 0xED : Prefix 'ED'
execOpEdCodes;
end;
$EE: begin // OP-Code 0xEE : XOR n
xorA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$EF: begin // OP-Code 0xEF : RST 28H
push(regPC.Value);
regPC.Value := $0028;
machineCycles := 5;
clockCycles := 11;
end;
$F0: begin // OP-Code 0xF0 : RET P
if (regAF.Flag[S] = False) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$F1: begin // OP-Code 0xF1 : POP AF
pop(regAF.Value);
machineCycles := 3;
clockCycles := 9;
end;
$F2: begin // OP-Code 0xF2 : JP P,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[S] = False) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$F3: begin // OP-Code 0xF3 : DI
IFF1 := False;
IFF2 := False;
machineCycles := 1;
clockCycles := 3;
end;
$F4: begin // OP-Code 0xF4 : CALL P,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[S] = False) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$F5: begin // OP-Code 0xF5 : PUSH AF
push(regAF.Value);
machineCycles := 5;
clockCycles := 11;
end;
$F6: begin // OP-Code 0xF6 : OR n
orA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$F7: begin // OP-Code 0xF7 : RST 30H
push(regPC.Value);
regPC.Value := $0030;
machineCycles := 5;
clockCycles := 11;
end;
$F8: begin // OP-Code 0xF8 : RET M
if (regAF.Flag[S] = True) then begin
pop(regPC.Value);
machineCycles := 4;
clockCycles := 10;
end
else begin
machineCycles := 3;
clockCycles := 5;
end;
end;
$F9: begin // OP-Code 0xF9 : LD SP,HL
regSP.Value := regHL.Value;
machineCycles := 2;
clockCycles := 4;
end;
$FA: begin // OP-Code 0xFA : JP M,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[S] = True) then begin
tmpWord.high := memRead(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 3;
clockCycles := 9;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$FB: begin // OP-Code 0xFB : EI
IFF1 := True;
IFF2 := True;
machineCycles := 1;
clockCycles := 3;
end;
$FC: begin // OP-Code 0xFC : CALL M,nn
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
if (regAF.Flag[S] = True) then begin
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
push(regPC.Value);
regPC.Value := tmpWord.Value;
machineCycles := 6;
clockCycles := 16;
end
else begin
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
end;
$FD: begin // OP-Code 0xFD : Prefix 'FD'
execOpFdCodes;
end;
$FE: begin // OP-Code 0xFE : CP n
cpA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 2;
clockCycles := 6;
end;
$FF: begin // OP-Code 0xFF : RST 38H
push(regPC.Value);
regPC.Value := $0038;
machineCycles := 5;
clockCycles := 11;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpCbCodes;
var
opCode, tmpByte: byte;
begin
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$00: begin // OP-Code 0xCB00 : RLC B
rlc8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$01: begin // OP-Code 0xCB01 : RLC C
rlc8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$02: begin // OP-Code 0xCB02 : RLC D
rlc8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$03: begin // OP-Code 0xCB03 : RLC E
rlc8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$04: begin // OP-Code 0xCB04 : RLC H
rlc8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$05: begin // OP-Code 0xCB05 : RLC L
rlc8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$06: begin // OP-Code 0xCB06 : RLC (HL)
tmpByte := memRead(regHL.Value);
rlc8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$07: begin // OP-Code 0xCB07 : RLC A
rlc8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$08: begin // OP-Code 0xCB08 : RRC B
rrc8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$09: begin // OP-Code 0xCB09 : RRC C
rrc8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$0A: begin // OP-Code 0xCB0A : RRC D
rrc8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$0B: begin // OP-Code 0xCB0B : RRC E
rrc8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$0C: begin // OP-Code 0xCB0C : RRC H
rrc8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$0D: begin // OP-Code 0xCB0D : RRC L
rrc8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$0E: begin // OP-Code 0xCB0E : RRC (HL)
tmpByte := memRead(regHL.Value);
rrc8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$0F: begin // OP-Code 0xCB0F : RRC A
rrc8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$10: begin // OP-Code 0xCB10 : RL B
rl8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$11: begin // OP-Code 0xCB11 : RL C
rl8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$12: begin // OP-Code 0xCB12 : RL D
rl8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$13: begin // OP-Code 0xCB13 : RL E
rl8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$14: begin // OP-Code 0xCB14 : RL H
rl8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$15: begin // OP-Code 0xCB15 : RL L
rl8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$16: begin // OP-Code 0xCB16 : RL (HL)
tmpByte := memRead(regHL.Value);
rl8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$17: begin // OP-Code 0xCB17 : RL A
rl8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$18: begin // OP-Code 0xCB18 : RR B
rr8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$19: begin // OP-Code 0xCB19 : RR C
rr8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$1A: begin // OP-Code 0xCB1A : RR D
rr8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$1B: begin // OP-Code 0xCB1B : RR E
rr8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$1C: begin // OP-Code 0xCB1C : RR H
rr8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$1D: begin // OP-Code 0xCB1D : RR L
rr8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$1E: begin // OP-Code 0xCB1E : RR (HL)
tmpByte := memRead(regHL.Value);
rr8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$1F: begin // OP-Code 0xCB1F : RR A
rr8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$20: begin // OP-Code 0xCB20 : SLA B
sla8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$21: begin // OP-Code 0xCB21 : SLA C
sla8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$22: begin // OP-Code 0xCB22 : SLA D
sla8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$23: begin // OP-Code 0xCB23 : SLA E
sla8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$24: begin // OP-Code 0xCB24 : SLA H
sla8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$25: begin // OP-Code 0xCB25 : SLA L
sla8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$26: begin // OP-Code 0xCB26 : SLA (HL)
tmpByte := memRead(regHL.Value);
sla8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$27: begin // OP-Code 0xCB27 : SLA A
sla8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$28: begin // OP-Code 0xCB28 : SRA B
sra8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$29: begin // OP-Code 0xCB29 : SRA C
sra8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$2A: begin // OP-Code 0xCB2A : SRA D
sra8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$2B: begin // OP-Code 0xCB2B : SRA E
sra8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$2C: begin // OP-Code 0xCB2C : SRA H
sra8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$2D: begin // OP-Code 0xCB2D : SRA L
sra8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$2E: begin // OP-Code 0xCB2E : SRA (HL)
tmpByte := memRead(regHL.Value);
sra8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$2F: begin // OP-Code 0xCB2F : SRA A
sra8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$38: begin // OP-Code 0xCB38 : SRL B
srl8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$39: begin // OP-Code 0xCB39 : SRL C
srl8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$3A: begin // OP-Code 0xCB3A : SRL D
srl8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$3B: begin // OP-Code 0xCB3B : SRL E
srl8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$3C: begin // OP-Code 0xCB3C : SRL H
srl8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$3D: begin // OP-Code 0xCB3D : SRL L
srl8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$3E: begin // OP-Code 0xCB3E : SRL (HL)
tmpByte := memRead(regHL.Value);
srl8Bit(tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$3F: begin // OP-Code 0xCB3F : SRL A
srl8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$40: begin // OP-Code 0xCB40 : BIT 0,B
tstBit(0, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$41: begin // OP-Code 0xCB41 : BIT 0,C
tstBit(0, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$42: begin // OP-Code 0xCB42 : BIT 0,D
tstBit(0, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$43: begin // OP-Code 0xCB43 : BIT 0,E
tstBit(0, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$44: begin // OP-Code 0xCB44 : BIT 0,H
tstBit(0, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$45: begin // OP-Code 0xCB45 : BIT 0,L
tstBit(0, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$46: begin // OP-Code 0xCB46 : BIT 0,(HL)
tstBit(0, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$47: begin // OP-Code 0xCB47 : BIT 0,A
tstBit(0, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$48: begin // OP-Code 0xCB48 : BIT 1,B
tstBit(1, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$49: begin // OP-Code 0xCB49 : BIT 1,C
tstBit(1, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$4A: begin // OP-Code 0xCB4A : BIT 1,D
tstBit(1, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$4B: begin // OP-Code 0xCB4B : BIT 1,E
tstBit(1, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$4C: begin // OP-Code 0xCB4C : BIT 1,H
tstBit(1, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$4D: begin // OP-Code 0xCB4D : BIT 1,L
tstBit(1, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$4E: begin // OP-Code 0xCB4E : BIT 1,(HL)
tstBit(1, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$4F: begin // OP-Code 0xCB4F : BIT 1,A
tstBit(1, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$50: begin // OP-Code 0xCB50 : BIT 2,B
tstBit(2, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$51: begin // OP-Code 0xCB51 : BIT 2,C
tstBit(2, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$52: begin // OP-Code 0xCB52 : BIT 2,D
tstBit(2, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$53: begin // OP-Code 0xCB53 : BIT 2,E
tstBit(2, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$54: begin // OP-Code 0xCB54 : BIT 2,H
tstBit(2, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$55: begin // OP-Code 0xCB55 : BIT 2,L
tstBit(2, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$56: begin // OP-Code 0xCB56 : BIT 2,(HL)
tstBit(2, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$57: begin // OP-Code 0xCB57 : BIT 2,A
tstBit(2, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$58: begin // OP-Code 0xCB58 : BIT 3,B
tstBit(3, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$59: begin // OP-Code 0xCB59 : BIT 3,C
tstBit(3, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$5A: begin // OP-Code 0xCB5A : BIT 3,D
tstBit(3, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$5B: begin // OP-Code 0xCB5B : BIT 3,E
tstBit(3, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$5C: begin // OP-Code 0xCB5C : BIT 3,H
tstBit(3, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$5D: begin // OP-Code 0xCB5D : BIT 3,L
tstBit(3, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$5E: begin // OP-Code 0xCB5E : BIT 3,(HL)
tstBit(3, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$5F: begin // OP-Code 0xCB5F : BIT 3,A
tstBit(3, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$60: begin // OP-Code 0xCB60 : BIT 4,B
tstBit(4, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$61: begin // OP-Code 0xCB61 : BIT 4,C
tstBit(4, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$62: begin // OP-Code 0xCB62 : BIT 4,D
tstBit(4, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$63: begin // OP-Code 0xCB63 : BIT 4,E
tstBit(4, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$64: begin // OP-Code 0xCB64 : BIT 4,H
tstBit(4, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$65: begin // OP-Code 0xCB65 : BIT 4,L
tstBit(4, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$66: begin // OP-Code 0xCB66 : BIT 4,(HL)
tstBit(4, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$67: begin // OP-Code 0xCB67 : BIT 4,A
tstBit(4, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$68: begin // OP-Code 0xCB68 : BIT 5,B
tstBit(5, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$69: begin // OP-Code 0xCB69 : BIT 5,C
tstBit(5, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$6A: begin // OP-Code 0xCB6A : BIT 5,D
tstBit(5, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$6B: begin // OP-Code 0xCB6B : BIT 5,E
tstBit(5, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$6C: begin // OP-Code 0xCB6C : BIT 5,H
tstBit(5, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$6D: begin // OP-Code 0xCB6D : BIT 5,L
tstBit(5, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$6E: begin // OP-Code 0xCB6E : BIT 5,(HL)
tstBit(5, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$6F: begin // OP-Code 0xCB6F : BIT 5,A
tstBit(5, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$70: begin // OP-Code 0xCB70 : BIT 6,B
tstBit(6, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$71: begin // OP-Code 0xCB71 : BIT 6,C
tstBit(6, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$72: begin // OP-Code 0xCB72 : BIT 6,D
tstBit(6, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$73: begin // OP-Code 0xCB73 : BIT 6,E
tstBit(6, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$74: begin // OP-Code 0xCB74 : BIT 6,H
tstBit(6, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$75: begin // OP-Code 0xCB75 : BIT 6,L
tstBit(6, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$76: begin // OP-Code 0xCB76 : BIT 6,(HL)
tstBit(6, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$77: begin // OP-Code 0xCB77 : BIT 6,A
tstBit(6, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$78: begin // OP-Code 0xCB78 : BIT 7,B
tstBit(7, regBC.B);
machineCycles := 2;
clockCycles := 6;
end;
$79: begin // OP-Code 0xCB79 : BIT 7,C
tstBit(7, regBC.C);
machineCycles := 2;
clockCycles := 6;
end;
$7A: begin // OP-Code 0xCB7A : BIT 7,D
tstBit(7, regDE.D);
machineCycles := 2;
clockCycles := 6;
end;
$7B: begin // OP-Code 0xCB7B : BIT 7,E
tstBit(7, regDE.E);
machineCycles := 2;
clockCycles := 6;
end;
$7C: begin // OP-Code 0xCB7C : BIT 7,H
tstBit(7, regHL.H);
machineCycles := 2;
clockCycles := 6;
end;
$7D: begin // OP-Code 0xCB7D : BIT 7,L
tstBit(7, regHL.L);
machineCycles := 2;
clockCycles := 6;
end;
$7E: begin // OP-Code 0xCB7E : BIT 7,(HL)
tstBit(7, memRead(regHL.Value));
machineCycles := 3;
clockCycles := 9;
end;
$7F: begin // OP-Code 0xCB7F : BIT 7,A
tstBit(7, regAF.A);
machineCycles := 2;
clockCycles := 6;
end;
$80: begin // OP-Code 0xCB80 : RES 0,B
resBit(0, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$81: begin // OP-Code 0xCB81 : RES 0,C
resBit(0, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$82: begin // OP-Code 0xCB82 : RES 0,D
resBit(0, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$83: begin // OP-Code 0xCB83 : RES 0,E
resBit(0, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$84: begin // OP-Code 0xCB84 : RES 0,H
resBit(0, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$85: begin // OP-Code 0xCB85 : RES 0,L
resBit(0, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$86: begin // OP-Code 0xCB86 : RES 0,(HL)
tmpByte := memRead(regHL.Value);
resBit(0, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$87: begin // OP-Code 0xCB87 : RES 0,A
resBit(0, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$88: begin // OP-Code 0xCB88 : RES 1,B
resBit(1, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$89: begin // OP-Code 0xCB89 : RES 1,C
resBit(1, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$8A: begin // OP-Code 0xCB8A : RES 1,D
resBit(1, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$8B: begin // OP-Code 0xCB8B : RES 1,E
resBit(1, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$8C: begin // OP-Code 0xCB8C : RES 1,H
resBit(1, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$8D: begin // OP-Code 0xCB8D : RES 1,L
resBit(1, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$8E: begin // OP-Code 0xCB8E : RES 1,(HL)
tmpByte := memRead(regHL.Value);
resBit(1, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$8F: begin // OP-Code 0xCB8F : RES 1,A
resBit(1, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$90: begin // OP-Code 0xCB90 : RES 2,B
resBit(2, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$91: begin // OP-Code 0xCB91 : RES 2,C
resBit(2, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$92: begin // OP-Code 0xCB92 : RES 2,D
resBit(2, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$93: begin // OP-Code 0xCB93 : RES 2,E
resBit(2, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$94: begin // OP-Code 0xCB94 : RES 2,H
resBit(2, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$95: begin // OP-Code 0xCB95 : RES 2,L
resBit(2, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$96: begin // OP-Code 0xCB96 : RES 2,(HL)
tmpByte := memRead(regHL.Value);
resBit(2, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$97: begin // OP-Code 0xCB97 : RES 2,A
resBit(2, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$98: begin // OP-Code 0xCB98 : RES 3,B
resBit(3, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$99: begin // OP-Code 0xCB99 : RES 3,C
resBit(3, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$9A: begin // OP-Code 0xCB9A : RES 3,D
resBit(3, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$9B: begin // OP-Code 0xCB9B : RES 3,E
resBit(3, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$9C: begin // OP-Code 0xCB9C : RES 3,H
resBit(3, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$9D: begin // OP-Code 0xCB9D : RES 3,L
resBit(3, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$9E: begin // OP-Code 0xCB9E : RES 3,(HL)
tmpByte := memRead(regHL.Value);
resBit(3, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$9F: begin // OP-Code 0xCB9F : RES 3,A
resBit(3, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$A0: begin // OP-Code 0xCBA0 : RES 4,B
resBit(4, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$A1: begin // OP-Code 0xCBA1 : RES 4,C
resBit(4, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$A2: begin // OP-Code 0xCBA2 : RES 4,D
resBit(4, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$A3: begin // OP-Code 0xCBA3 : RES 4,E
resBit(4, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$A4: begin // OP-Code 0xCBA4 : RES 4,H
resBit(4, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$A5: begin // OP-Code 0xCBA5 : RES 4,L
resBit(4, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$A6: begin // OP-Code 0xCBA6 : RES 4,(HL)
tmpByte := memRead(regHL.Value);
resBit(4, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$A7: begin // OP-Code 0xCBA7 : RES 4,A
resBit(4, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$A8: begin // OP-Code 0xCBA8 : RES 5,B
resBit(5, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$A9: begin // OP-Code 0xCBA9 : RES 5,C
resBit(5, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$AA: begin // OP-Code 0xCBAA : RES 5,D
resBit(5, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$AB: begin // OP-Code 0xCBAB : RES 5,E
resBit(5, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$AC: begin // OP-Code 0xCBAC : RES 5,H
resBit(5, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$AD: begin // OP-Code 0xCBAD : RES 5,L
resBit(5, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$AE: begin // OP-Code 0xCBAE : RES 5,(HL)
tmpByte := memRead(regHL.Value);
resBit(5, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$AF: begin // OP-Code 0xCBAF : RES 5,A
resBit(5, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$B0: begin // OP-Code 0xCBB0 : RES 6,B
resBit(6, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$B1: begin // OP-Code 0xCBB1 : RES 6,C
resBit(6, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$B2: begin // OP-Code 0xCBB2 : RES 6,D
resBit(6, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$B3: begin // OP-Code 0xCBB3 : RES 6,E
resBit(6, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$B4: begin // OP-Code 0xCBB4 : RES 6,H
resBit(6, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$B5: begin // OP-Code 0xCBB5 : RES 6,L
resBit(6, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$B6: begin // OP-Code 0xCBB6 : RES 6,(HL)
tmpByte := memRead(regHL.Value);
resBit(6, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$B7: begin // OP-Code 0xCBB7 : RES 6,A
resBit(6, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$B8: begin // OP-Code 0xCBB8 : RES 7,B
resBit(7, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$B9: begin // OP-Code 0xCBB9 : RES 7,C
resBit(7, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$BA: begin // OP-Code 0xCBBA : RES 7,D
resBit(7, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$BB: begin // OP-Code 0xCBBB : RES 7,E
resBit(7, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$BC: begin // OP-Code 0xCBBC : RES 7,H
resBit(7, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$BD: begin // OP-Code 0xCBBD : RES 7,L
resBit(7, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$BE: begin // OP-Code 0xCBBE : RES 7,(HL)
tmpByte := memRead(regHL.Value);
resBit(7, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$BF: begin // OP-Code 0xCBBF : RES 7,A
resBit(7, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$C0: begin // OP-Code 0xCBC0 : SET 0,B
setBit(0, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$C1: begin // OP-Code 0xCBC1 : SET 0,C
setBit(0, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$C2: begin // OP-Code 0xCBC2 : SET 0,D
setBit(0, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$C3: begin // OP-Code 0xCBC3 : SET 0,E
setBit(0, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$C4: begin // OP-Code 0xCBC4 : SET 0,H
setBit(0, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$C5: begin // OP-Code 0xCBC5 : SET 0,L
setBit(0, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$C6: begin // OP-Code 0xCBC6 : SET 0,(HL)
tmpByte := memRead(regHL.Value);
setBit(0, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$C7: begin // OP-Code 0xCBC7 : SET 0,A
setBit(0, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$C8: begin // OP-Code 0xCBC8 : SET 1,B
setBit(1, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$C9: begin // OP-Code 0xCBC9 : SET 1,C
setBit(1, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$CA: begin // OP-Code 0xCBCA : SET 1,D
setBit(1, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$CB: begin // OP-Code 0xCBCB : SET 1,E
setBit(1, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$CC: begin // OP-Code 0xCBCC : SET 1,H
setBit(1, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$CD: begin // OP-Code 0xCBCD : SET 1,L
setBit(1, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$CE: begin // OP-Code 0xCBCE : SET 1,(HL)
tmpByte := memRead(regHL.Value);
setBit(1, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$CF: begin // OP-Code 0xCBCF : SET 1,A
setBit(1, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$D0: begin // OP-Code 0xCBD0 : SET 2,B
setBit(2, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$D1: begin // OP-Code 0xCBD1 : SET 2,C
setBit(2, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$D2: begin // OP-Code 0xCBD2 : SET 2,D
setBit(2, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$D3: begin // OP-Code 0xCBD3 : SET 2,E
setBit(2, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$D4: begin // OP-Code 0xCBD4 : SET 2,H
setBit(2, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$D5: begin // OP-Code 0xCBD5 : SET 2,L
setBit(2, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$D6: begin // OP-Code 0xCBD6 : SET 2,(HL)
tmpByte := memRead(regHL.Value);
setBit(2, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$D7: begin // OP-Code 0xCBD7 : SET 2,A
setBit(2, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$D8: begin // OP-Code 0xCBD8 : SET 3,B
setBit(3, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$D9: begin // OP-Code 0xCBD9 : SET 3,C
setBit(3, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$DA: begin // OP-Code 0xCBDA : SET 3,D
setBit(3, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$DB: begin // OP-Code 0xCBDB : SET 3,E
setBit(3, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$DC: begin // OP-Code 0xCBDC : SET 3,H
setBit(3, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$DD: begin // OP-Code 0xCBDD : SET 3,L
setBit(3, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$DE: begin // OP-Code 0xCBDE : SET 3,(HL)
tmpByte := memRead(regHL.Value);
setBit(3, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$DF: begin // OP-Code 0xCBDF : SET 3,A
setBit(3, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$E0: begin // OP-Code 0xCBE0 : SET 4,B
setBit(4, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$E1: begin // OP-Code 0xCBE1 : SET 4,C
setBit(4, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$E2: begin // OP-Code 0xCBE2 : SET 4,D
setBit(4, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$E3: begin // OP-Code 0xCBE3 : SET 4,E
setBit(4, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$E4: begin // OP-Code 0xCBE4 : SET 4,H
setBit(4, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$E5: begin // OP-Code 0xCBE5 : SET 4,L
setBit(4, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$E6: begin // OP-Code 0xCBE6 : SET 4,(HL)
tmpByte := memRead(regHL.Value);
setBit(4, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$E7: begin // OP-Code 0xCBE7 : SET 4,A
setBit(4, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$E8: begin // OP-Code 0xCBE8 : SET 5,B
setBit(5, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$E9: begin // OP-Code 0xCBE9 : SET 5,C
setBit(5, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$EA: begin // OP-Code 0xCBEA : SET 5,D
setBit(5, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$EB: begin // OP-Code 0xCBEB : SET 5,E
setBit(5, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$EC: begin // OP-Code 0xCBEC : SET 5,H
setBit(5, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$ED: begin // OP-Code 0xCBED : SET 5,L
setBit(5, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$EE: begin // OP-Code 0xCBEE : SET 5,(HL)
tmpByte := memRead(regHL.Value);
setBit(5, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$EF: begin // OP-Code 0xCBEF : SET 5,A
setBit(5, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$F0: begin // OP-Code 0xCBF0 : SET 6,B
setBit(6, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$F1: begin // OP-Code 0xCBF1 : SET 6,C
setBit(6, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$F2: begin // OP-Code 0xCBF2 : SET 6,D
setBit(6, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$F3: begin // OP-Code 0xCBF3 : SET 6,E
setBit(6, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$F4: begin // OP-Code 0xCBF4 : SET 6,H
setBit(6, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$F5: begin // OP-Code 0xCBF5 : SET 6,L
setBit(6, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$F6: begin // OP-Code 0xCBF6 : SET 6,(HL)
tmpByte := memRead(regHL.Value);
setBit(6, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$F7: begin // OP-Code 0xCBF7 : SET 6,A
setBit(6, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$F8: begin // OP-Code 0xCBF8 : SET 7,B
setBit(7, regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$F9: begin // OP-Code 0xCBF9 : SET 7,C
setBit(7, regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$FA: begin // OP-Code 0xCBFA : SET 7,D
setBit(7, regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$FB: begin // OP-Code 0xCBFB : SET 7,E
setBit(7, regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$FC: begin // OP-Code 0xCBFC : SET 7,H
setBit(7, regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$FD: begin // OP-Code 0xCBFD : SET 7,L
setBit(7, regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$FE: begin // OP-Code 0xCBFE : SET 7,(HL)
tmpByte := memRead(regHL.Value);
setBit(7, tmpByte);
memWrite(regHL.Value, tmpByte);
machineCycles := 5;
clockCycles := 13;
end;
$FF: begin // OP-Code 0xCBFF : SET 7,A
setBit(7, regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := False; // UFO-Flag loeschen, da TRAP in 2. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 4;
clockCycles := 12;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpDdCodes;
var
opCode, memOffset, tmpByte: byte;
tmpWord: Treg16;
begin
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$09: begin // OP-Code 0xDD09 : ADD IX,BC
addIX16Bit(regBC.Value);
machineCycles := 6;
clockCycles := 10;
end;
$19: begin // OP-Code 0xDD19 : ADD IX,DE
addIX16Bit(regDE.Value);
machineCycles := 6;
clockCycles := 10;
end;
$21: begin // OP-Code 0xDD21 : LD IX,nn
regIX.low := memRead(regPC.Value);
Inc(regPC.Value);
regIX.high := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$22: begin // OP-Code 0xDD22 : LD (nn),IX
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regIX.low);
memWrite(tmpWord.Value + 1, regIX.high);
machineCycles := 7;
clockCycles := 19;
end;
$23: begin // OP-Code 0xDD23 : INC IX
Inc(regIX.Value);
machineCycles := 3;
clockCycles := 7;
end;
$29: begin // OP-Code 0xDD29 : ADD IX,IX
addIX16Bit(regIX.Value);
machineCycles := 6;
clockCycles := 10;
end;
$2A: begin // OP-Code 0xDD2A : LD IX,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regIX.low := memRead(tmpWord.Value);
regIX.high := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$2B: begin // OP-Code 0xDD2B : DEC IX
Dec(regIX.Value);
machineCycles := 3;
clockCycles := 7;
end;
$34: begin // OP-Code 0xDD34 : INC (IX+d)
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.Value := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord.Value);
inc8Bit(tmpByte);
memWrite(tmpWord.Value, tmpByte);
machineCycles := 8;
clockCycles := 18;
end;
$35: begin // OP-Code 0xDD35 : DEC (IX+d)
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.Value := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord.Value);
dec8Bit(tmpByte);
memWrite(tmpWord.Value, tmpByte);
machineCycles := 8;
clockCycles := 18;
end;
$36: begin // OP-Code 0xDD36 : LD (IX+d),n
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpByte := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), tmpByte);
machineCycles := 5;
clockCycles := 15;
end;
$39: begin // OP-Code 0xDD39 : ADD IX,SP
addIX16Bit(regSP.Value);
machineCycles := 6;
clockCycles := 10;
end;
$46: begin // OP-Code 0xDD46 : LD B,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regBC.B := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$4E: begin // OP-Code 0xDD4E : LD C,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regBC.C := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$56: begin // OP-Code 0xDD56 : LD D,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regDE.D := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$5E: begin // OP-Code 0xDD4E : LD E,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regDE.E := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$66: begin // OP-Code 0xDD66 : LD H,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regHL.H := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$6E: begin // OP-Code 0xDD6E : LD L,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regHL.L := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$70: begin // OP-Code 0xDD70 : LD (IX+d),B
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regBC.B);
machineCycles := 7;
clockCycles := 15;
end;
$71: begin // OP-Code 0xDD71 : LD (IX+d),C
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regBC.C);
machineCycles := 7;
clockCycles := 15;
end;
$72: begin // OP-Code 0xDD72 : LD (IX+d),D
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regDE.D);
machineCycles := 7;
clockCycles := 15;
end;
$73: begin // OP-Code 0xDD73 : LD (IX+d),E
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regDE.E);
machineCycles := 7;
clockCycles := 15;
end;
$74: begin // OP-Code 0xDD74 : LD (IX+d),H
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regHL.H);
machineCycles := 7;
clockCycles := 15;
end;
$75: begin // OP-Code 0xDD75 : LD (IX+d),L
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regHL.L);
machineCycles := 7;
clockCycles := 15;
end;
$77: begin // OP-Code 0xDD77 : LD (IX+d),A
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIX.Value + shortint(memOffset), regAF.A);
machineCycles := 7;
clockCycles := 15;
end;
$7E: begin // OP-Code 0xDD7E : LD A,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regAF.A := memRead(regIX.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$86: begin // OP-Code 0xDD86 : ADD A,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
addA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$8E: begin // OP-Code 0xDD8E : ADC A,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
adcA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$96: begin // OP-Code 0xDD96 : SUB A,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
subA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$9E: begin // OP-Code 0xDD9E : SBC A,(IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
sbcA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$A6: begin // OP-Code 0xDDA6 : AND (IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
andA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$AE: begin // OP-Code 0xDDAE : XOR (IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
xorA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$B6: begin // OP-Code 0xDDB6 : OR (IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
orA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$BE: begin // OP-Code 0xDDBE : CP (IX+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
cpA8Bit(memRead(regIX.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$CB: begin // OP-Code 0xDDCB : Prefix 'DDCB'
execOpDdCbCodes;
end;
$E1: begin // OP-Code 0xDDE1 : POP IX
pop(regIX.Value);
machineCycles := 4;
clockCycles := 12;
end;
$E3: begin // OP-Code 0xDDE3 : EX (SP),IX
tmpWord.low := memRead(regSP.Value);
tmpWord.high := memRead(regSP.Value + 1);
memWrite(regSP.Value, regIX.low);
memWrite(regSP.Value + 1, regIX.high);
regIX.Value := tmpWord.Value;
machineCycles := 7;
clockCycles := 19;
end;
$E5: begin // OP-Code 0xDDE5 : PUSH IX
push(regIX.Value);
machineCycles := 6;
clockCycles := 14;
end;
$E9: begin // OP-Code 0xDDE9 : JP (IX)
regPC.Value := regIX.Value;
machineCycles := 2;
clockCycles := 6;
end;
$F9: begin // OP-Code 0xDDF9 : LD SP,IX
regSP.Value := regIX.Value;
machineCycles := 3;
clockCycles := 7;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := False; // UFO-Flag loeschen, da TRAP in 2. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 4;
clockCycles := 12;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpDdCbCodes;
var
opCode, memOffset, tmpByte: byte;
tmpWord: word;
begin
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$06: begin // OP-Code 0xDDCB d 06 : RLC (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rlc8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$0E: begin // OP-Code 0xDDCB d 0E : RRC (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rrc8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$16: begin // OP-Code 0xDDCB d 16 : RL (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rl8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$1E: begin // OP-Code 0xDDCB d 1E : RR (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rr8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$26: begin // OP-Code 0xDDCB d 26 : SLA (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
sla8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$2E: begin // OP-Code 0xDDCB d 2E : SRA (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
sra8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$3E: begin // OP-Code 0xDDCB d 3E : SRL (IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
srl8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$46: begin // OP-Code 0xDDCB d 46 : BIT 0,(IX+d)
tstBit(0, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$4E: begin // OP-Code 0xDDCB d 4E : BIT 1,(IX+d)
tstBit(1, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$56: begin // OP-Code 0xDDCB d 56 : BIT 2,(IX+d)
tstBit(2, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$5E: begin // OP-Code 0xDDCB d 5E : BIT 3,(IX+d)
tstBit(3, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$66: begin // OP-Code 0xDDCB d 66 : BIT 4,(IX+d)
tstBit(4, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$6E: begin // OP-Code 0xDDCB d 6E : BIT 5,(IX+d)
tstBit(5, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$76: begin // OP-Code 0xDDCB d 76 : BIT 6,(IX+d)
tstBit(6, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$7E: begin // OP-Code 0xDDCB d 7E : BIT 7,(IX+d)
tstBit(7, memRead(regIX.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$86: begin // OP-Code 0xDDCB d 86 : RES 0,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(0, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$8E: begin // OP-Code 0xDDCB d 8E : RES 1,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(1, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$96: begin // OP-Code 0xDDCB d 96 : RES 2,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(2, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$9E: begin // OP-Code 0xDDCB d 9E : RES 3,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(3, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$A6: begin // OP-Code 0xDDCB d A6 : RES 4,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(4, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$AE: begin // OP-Code 0xDDCB d AE : RES 5,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(5, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$B6: begin // OP-Code 0xDDCB d B6 : RES 6,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(6, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$BE: begin // OP-Code 0xDDCB d BE : RES 7,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(7, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$C6: begin // OP-Code 0xDDCB d C6 : SET 0,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(0, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$CE: begin // OP-Code 0xDDCB d CE : SET 1,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(1, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$D6: begin // OP-Code 0xDDCB d D6 : SET 2,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(2, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$DE: begin // OP-Code 0xDDCB d DE : SET 3,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(3, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$E6: begin // OP-Code 0xDDCB d E6 : SET 4,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(4, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$EE: begin // OP-Code 0xDDCB d EE : SET 5,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(5, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$F6: begin // OP-Code 0xDDCB d F6 : SET 6,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(6, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$FE: begin // OP-Code 0xDDCB d FE : SET 7,(IX+d)
tmpWord := regIX.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(7, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := True; // UFO-Flag setzen, da TRAP in 3. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 6;
clockCycles := 18;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpFdCodes;
var
opCode, memOffset, tmpByte: byte;
tmpWord: Treg16;
begin
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$09: begin // OP-Code 0xFD09 : ADD IY,BC
addIY16Bit(regBC.Value);
machineCycles := 6;
clockCycles := 10;
end;
$19: begin // OP-Code 0xFD19 : ADD IY,DE
addIY16Bit(regDE.Value);
machineCycles := 6;
clockCycles := 10;
end;
$21: begin // OP-Code 0xFD21 : LD IY,nn
regIY.low := memRead(regPC.Value);
Inc(regPC.Value);
regIY.high := memRead(regPC.Value);
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$22: begin // OP-Code 0xFD22 : LD (nn),IY
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regIY.low);
memWrite(tmpWord.Value + 1, regIY.high);
machineCycles := 7;
clockCycles := 19;
end;
$23: begin // OP-Code 0xFD23 : INC IY
Inc(regIY.Value);
machineCycles := 3;
clockCycles := 7;
end;
$29: begin // OP-Code 0xFD29 : ADD IY,IY
addIY16Bit(regIY.Value);
machineCycles := 6;
clockCycles := 10;
end;
$2A: begin // OP-Code 0xFD2A : LD IY,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regIY.low := memRead(tmpWord.Value);
regIY.high := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$2B: begin // OP-Code 0xFD2B : DEC IY
Dec(regIY.Value);
machineCycles := 3;
clockCycles := 7;
end;
$34: begin // OP-Code 0xFD34 : INC (IY+d)
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.Value := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord.Value);
inc8Bit(tmpByte);
memWrite(tmpWord.Value, tmpByte);
machineCycles := 8;
clockCycles := 18;
end;
$35: begin // OP-Code 0xFD35 : DEC (IY+d)
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.Value := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord.Value);
dec8Bit(tmpByte);
memWrite(tmpWord.Value, tmpByte);
machineCycles := 8;
clockCycles := 18;
end;
$36: begin // OP-Code 0xFD36 : LD (IY+d),n
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
tmpByte := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), tmpByte);
machineCycles := 5;
clockCycles := 15;
end;
$39: begin // OP-Code 0xFD39 : ADD IY,SP
addIY16Bit(regSP.Value);
machineCycles := 6;
clockCycles := 10;
end;
$46: begin // OP-Code 0xFD46 : LD B,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regBC.B := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$4E: begin // OP-Code 0xFD4E : LD C,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regBC.C := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$56: begin // OP-Code 0xFD56 : LD D,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regDE.D := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$5E: begin // OP-Code 0xFD4E : LD E,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regDE.E := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$66: begin // OP-Code 0xFD66 : LD H,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regHL.H := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$6E: begin // OP-Code 0xFD6E : LD L,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regHL.L := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$70: begin // OP-Code 0xFD70 : LD (IY+d),B
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regBC.B);
machineCycles := 7;
clockCycles := 15;
end;
$71: begin // OP-Code 0xFD71 : LD (IY+d),C
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regBC.C);
machineCycles := 7;
clockCycles := 15;
end;
$72: begin // OP-Code 0xFD72 : LD (IY+d),D
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regDE.D);
machineCycles := 7;
clockCycles := 15;
end;
$73: begin // OP-Code 0xFD73 : LD (IY+d),E
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regDE.E);
machineCycles := 7;
clockCycles := 15;
end;
$74: begin // OP-Code 0xFD74 : LD (IY+d),H
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regHL.H);
machineCycles := 7;
clockCycles := 15;
end;
$75: begin // OP-Code 0xFD75 : LD (IY+d),L
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regHL.L);
machineCycles := 7;
clockCycles := 15;
end;
$77: begin // OP-Code 0xFD77 : LD (IY+d),A
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(regIY.Value + shortint(memOffset), regAF.A);
machineCycles := 7;
clockCycles := 15;
end;
$7E: begin // OP-Code 0xFD7E : LD A,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
regAF.A := memRead(regIY.Value + shortint(memOffset));
machineCycles := 6;
clockCycles := 14;
end;
$86: begin // OP-Code 0xFD86 : ADD A,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
addA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$8E: begin // OP-Code 0xFD8E : ADC A,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
adcA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$96: begin // OP-Code 0xFD96 : SUB A,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
subA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$9E: begin // OP-Code 0xFD9E : SBC A,(IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
sbcA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$A6: begin // OP-Code 0xFDA6 : AND (IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
andA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$AE: begin // OP-Code 0xFDAE : XOR (IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
xorA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$B6: begin // OP-Code 0xFDB6 : OR (IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
orA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$BE: begin // OP-Code 0xFDBE : CP (IY+d);
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
cpA8Bit(memRead(regIY.Value + shortint(memOffset)));
machineCycles := 6;
clockCycles := 14;
end;
$CB: begin // OP-Code 0xFDCB : Prefix 'DDCB'
execOpFdCbCodes;
end;
$E1: begin // OP-Code 0xFDE1 : POP IY
pop(regIY.Value);
machineCycles := 4;
clockCycles := 12;
end;
$E3: begin // OP-Code 0xFDE3 : EX (SP),IY
tmpWord.low := memRead(regSP.Value);
tmpWord.high := memRead(regSP.Value + 1);
memWrite(regSP.Value, regIY.low);
memWrite(regSP.Value + 1, regIY.high);
regIY.Value := tmpWord.Value;
machineCycles := 7;
clockCycles := 19;
end;
$E5: begin // OP-Code 0xFDE5 : PUSH IY
push(regIY.Value);
machineCycles := 6;
clockCycles := 14;
end;
$E9: begin // OP-Code 0xFDE9 : JP (IY)
regPC.Value := regIY.Value;
machineCycles := 2;
clockCycles := 6;
end;
$F9: begin // OP-Code 0xFDF9 : LD SP,IY
regSP.Value := regIY.Value;
machineCycles := 3;
clockCycles := 7;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := False; // UFO-Flag loeschen, da TRAP in 2. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 4;
clockCycles := 12;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpFdCbCodes;
var
opCode, memOffset, tmpByte: byte;
tmpWord: word;
begin
memOffset := memRead(regPC.Value);
Inc(regPC.Value);
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$06: begin // OP-Code 0xFDCB d 06 : RLC (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rlc8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$0E: begin // OP-Code 0xFDCB d 0E : RRC (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rrc8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$16: begin // OP-Code 0xFDCB d 16 : RL (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rl8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$1E: begin // OP-Code 0xFDCB d 1E : RR (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
rr8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$26: begin // OP-Code 0xFDCB d 26 : SLA (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
sla8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$2E: begin // OP-Code 0xFDCB d 2E : SRA (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
sra8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$3E: begin // OP-Code 0xFDCB d 3E : SRL (IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
srl8Bit(tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$46: begin // OP-Code 0xFDCB d 46 : BIT 0,(IY+d)
tstBit(0, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$4E: begin // OP-Code 0xFDCB d 4E : BIT 1,(IY+d)
tstBit(1, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$56: begin // OP-Code 0xFDCB d 56 : BIT 2,(IY+d)
tstBit(2, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$5E: begin // OP-Code 0xFDCB d 5E : BIT 3,(IY+d)
tstBit(3, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$66: begin // OP-Code 0xFDCB d 66 : BIT 4,(IY+d)
tstBit(4, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$6E: begin // OP-Code 0xFDCB d 6E : BIT 5,(IY+d)
tstBit(5, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$76: begin // OP-Code 0xFDCB d 76 : BIT 6,(IY+d)
tstBit(6, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$7E: begin // OP-Code 0xFDCB d 7E : BIT 7,(IY+d)
tstBit(7, memRead(regIY.Value + shortint(memOffset)));
machineCycles := 5;
clockCycles := 15;
end;
$86: begin // OP-Code 0xFDCB d 86 : RES 0,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(0, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$8E: begin // OP-Code 0xFDCB d 8E : RES 1,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(1, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$96: begin // OP-Code 0xFDCB d 96 : RES 2,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(2, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$9E: begin // OP-Code 0xFDCB d 9E : RES 3,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(3, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$A6: begin // OP-Code 0xFDCB d A6 : RES 4,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(4, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$AE: begin // OP-Code 0xFDCB d AE : RES 5,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(5, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$B6: begin // OP-Code 0xFDCB d B6 : RES 6,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(6, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$BE: begin // OP-Code 0xFDCB d BE : RES 7,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
resBit(7, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$C6: begin // OP-Code 0xFDCB d C6 : SET 0,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(0, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$CE: begin // OP-Code 0xFDCB d CE : SET 1,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(1, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$D6: begin // OP-Code 0xFDCB d D6 : SET 2,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(2, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$DE: begin // OP-Code 0xFDCB d DE : SET 3,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(3, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$E6: begin // OP-Code 0xFDCB d E6 : SET 4,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(4, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$EE: begin // OP-Code 0xFDCB d EE : SET 5,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(5, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$F6: begin // OP-Code 0xFDCB d F6 : SET 6,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(6, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
$FE: begin // OP-Code 0xFDCB d FE : SET 7,(IY+d)
tmpWord := regIY.Value + shortint(memOffset);
tmpByte := memRead(tmpWord);
setBit(7, tmpByte);
memWrite(tmpWord, tmpByte);
machineCycles := 7;
clockCycles := 19;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := True; // UFO-Flag setzen, da TRAP in 3. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 6;
clockCycles := 18;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
procedure TZ180Cpu.execOpEdCodes;
var
opCode, tmpByte, tmpNibble: byte;
tmpWord: Treg16;
begin
opCode := readOpCode(regPC.Value);
Inc(regPC.Value);
case (opCode) of
$00: begin // OP-Code 0xED00 : IN0 B,(n)
regBC.B := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$01: begin // OP-Code 0xED01 : OUT0 (n),B
ioWrite($00, memRead(regPC.Value), regBC.B);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$04: begin // OP-Code 0xED04 : TST B
tstA8Bit(regBC.B);
machineCycles := 3;
clockCycles := 7;
end;
$08: begin // OP-Code 0xED08 : IN0 C,(n)
regBC.C := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$09: begin // OP-Code 0xED09 : OUT0 (n),C
ioWrite($00, memRead(regPC.Value), regBC.C);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$0C: begin // OP-Code 0xED0C : TST C
tstA8Bit(regBC.C);
machineCycles := 3;
clockCycles := 7;
end;
$10: begin // OP-Code 0xED10 : IN0 D,(n)
regDE.D := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$11: begin // OP-Code 0xED11 : OUT0 (n),D
ioWrite($00, memRead(regPC.Value), regDE.D);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$14: begin // OP-Code 0xED14 : TST D
tstA8Bit(regDE.D);
machineCycles := 3;
clockCycles := 7;
end;
$18: begin // OP-Code 0xED18 : IN0 E,(n)
regDE.E := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$19: begin // OP-Code 0xED19 : OUT0 (n),E
ioWrite($00, memRead(regPC.Value), regDE.E);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$1C: begin // OP-Code 0xED1C : TST E
tstA8Bit(regDE.E);
machineCycles := 3;
clockCycles := 7;
end;
$20: begin // OP-Code 0xED20 : IN0 H,(n)
regHL.H := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$21: begin // OP-Code 0xED21 : OUT0 (n),H
ioWrite($00, memRead(regPC.Value), regHL.H);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$24: begin // OP-Code 0xED24 : TST H
tstA8Bit(regHL.H);
machineCycles := 3;
clockCycles := 7;
end;
$28: begin // OP-Code 0xED28 : IN0 L,(n)
regHL.L := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$29: begin // OP-Code 0xED29 : OUT0 (n),L
ioWrite($00, memRead(regPC.Value), regHL.L);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$2C: begin // OP-Code 0xED2C : TST L
tstA8Bit(regHL.L);
machineCycles := 3;
clockCycles := 7;
end;
$34: begin // OP-Code 0xED34 : TST (HL)
tstA8Bit(memRead(regHL.Value));
machineCycles := 4;
clockCycles := 10;
end;
$38: begin // OP-Code 0xED38 : IN0 A,(n)
regAF.A := inreg8Bit($00, memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$39: begin // OP-Code 0xED39 : OUT0 (n),A
ioWrite($00, memRead(regPC.Value), regAF.A);
Inc(regPC.Value);
machineCycles := 5;
clockCycles := 13;
end;
$3C: begin // OP-Code 0xED3C : TST A
tstA8Bit(regAF.A);
machineCycles := 3;
clockCycles := 7;
end;
$40: begin // OP-Code 0xED40 : IN B,(C)
regBC.B := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$41: begin // OP-Code 0xED41 : OUT (C),B
ioWrite(regBC.B, regBC.C, regBC.B);
machineCycles := 4;
clockCycles := 10;
end;
$42: begin // OP-Code 0xED42 : SBC HL,BC
sbcHL16Bit(regBC.Value);
machineCycles := 6;
clockCycles := 10;
end;
$43: begin // OP-Code 0xED43 : LD (nn),BC
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regBC.C);
memWrite(tmpWord.Value + 1, regBC.B);
machineCycles := 7;
clockCycles := 19;
end;
$44: begin // OP-Code 0xED44 : NEG
regAF.Flag[C] := (regAF.A <> $00); // C is set if Accumulator was not 00H before operation; reset otherwise
regAF.Flag[PV] := (regAF.A = $80); // P/V is set if Accumulator was 80H before operation; reset otherwise
regAF.Flag[H] := ($00 - (regAF.A and $0F) < $00); // H is set if borrow from bit 4; reset otherwise
regAF.A := ($00 - regAF.A);
regAF.Flag[S] := ((regAF.A and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (regAF.A = $00); // Z is set if result is 0; reset otherwise
regAF.Flag[N] := True;
machineCycles := 2;
clockCycles := 6;
end;
$45: begin // OP-Code 0xED45 : RETN
pop(regPC.Value);
IFF1 := IFF2;
machineCycles := 4;
clockCycles := 12;
end;
$46: begin // OP-Code 0xED46 : IM 0
intMode := IM0;
machineCycles := 2;
clockCycles := 6;
end;
$47: begin // OP-Code 0xED47 : LD I,A
regI := regAF.A;
machineCycles := 2;
clockCycles := 6;
end;
$48: begin // OP-Code 0xED48 : IN C,(C)
regBC.C := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$49: begin // OP-Code 0xED49 : OUT (C),C
ioWrite(regBC.B, regBC.C, regBC.C);
machineCycles := 4;
clockCycles := 10;
end;
$4A: begin // OP-Code 0xED4A : ADC HL,BC
adcHL16Bit(regBC.Value);
machineCycles := 6;
clockCycles := 10;
end;
$4B: begin // OP-Code 0xED4B : LD BC,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regBC.C := memRead(tmpWord.Value);
regBC.B := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$4C: begin // OP-Code 0xED4C : MLT BC
//regBC.Value := ((regBC.B * regBC.C) and $FFFF);
regBC.Value := (regBC.B * regBC.C);
machineCycles := 13;
clockCycles := 17;
end;
$4D: begin // OP-Code 0xED4D : RETI
//NOTE: OP-Code 0xED4D : RETI interrupt daisy-chain not implemented
pop(regPC.Value);
machineCycles := 4;
clockCycles := 12;
end;
$4F: begin // OP-Code 0xED4F : LD R,A
regR := regAF.A;
machineCycles := 2;
clockCycles := 6;
end;
$50: begin // OP-Code 0xED50 : IN D,(C)
regDE.D := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$51: begin // OP-Code 0xED51 : OUT (C),D
ioWrite(regBC.B, regBC.C, regDE.D);
machineCycles := 4;
clockCycles := 10;
end;
$52: begin // OP-Code 0xED52 : SBC HL,DE
sbcHL16Bit(regDE.Value);
machineCycles := 6;
clockCycles := 10;
end;
$53: begin // OP-Code 0xED53 : LD (nn),DE
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regDE.E);
memWrite(tmpWord.Value + 1, regDE.D);
machineCycles := 7;
clockCycles := 19;
end;
$56: begin // OP-Code 0xED56 : IM 1
intMode := IM1;
machineCycles := 2;
clockCycles := 6;
end;
$57: begin // OP-Code 0xED57 : LD A,I
regAF.A := regI;
regAF.Flag[S] := ((regI and $80) <> $00); // S is set if I-Register is negative; reset otherwise
regAF.Flag[Z] := (regI = $00); // Z is set if I-Register is zero; reset otherwise
regAF.Flag[PV] := IFF2; // P/V contains contents of IFF2
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 2;
clockCycles := 6;
end;
$58: begin // OP-Code 0xED58 : IN E,(C)
regDE.E := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$59: begin // OP-Code 0xED59 : OUT (C),E
ioWrite(regBC.B, regBC.C, regDE.E);
machineCycles := 4;
clockCycles := 10;
end;
$5A: begin // OP-Code 0xED5A : ADC HL,DE
adcHL16Bit(regDE.Value);
machineCycles := 6;
clockCycles := 10;
end;
$5B: begin // OP-Code 0xED5B : LD DE,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regDE.E := memRead(tmpWord.Value);
regDE.D := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$5C: begin // OP-Code 0xED5C : MLT DE
//regDE.Value := ((regDE.D * regDE.E) and $FFFF);
regDE.Value := (regDE.D * regDE.E);
machineCycles := 13;
clockCycles := 17;
end;
$5E: begin // OP-Code 0xED5E : IM 2
intMode := IM2;
machineCycles := 2;
clockCycles := 6;
end;
$5F: begin // OP-Code 0xED5F : LD A,R
regAF.A := regR;
regAF.Flag[S] := ((regR and $80) <> $00); // S is set if R-Register is negative; reset otherwise
regAF.Flag[Z] := (regR = $00); // Z is set if R-Register is zero; reset otherwise
regAF.Flag[PV] := IFF2; // P/V contains contents of IFF2
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 2;
clockCycles := 6;
end;
$60: begin // OP-Code 0xED60 : IN H,(C)
regHL.H := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$61: begin // OP-Code 0xED61 : OUT (C),H
ioWrite(regBC.B, regBC.C, regHL.H);
machineCycles := 4;
clockCycles := 10;
end;
$62: begin // OP-Code 0xED62 : SBC HL,HL
sbcHL16Bit(regHL.Value);
machineCycles := 6;
clockCycles := 10;
end;
$63: begin // OP-Code 0xED63 : LD (nn),HL
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regHL.L);
memWrite(tmpWord.Value + 1, regHL.H);
machineCycles := 7;
clockCycles := 19;
end;
$64: begin // OP-Code 0xED64 : TST n
tstA8Bit(memRead(regPC.Value));
Inc(regPC.Value);
machineCycles := 3;
clockCycles := 9;
end;
$67: begin // OP-Code 0xED67 : RRD (HL)
tmpByte := memRead(regHL.Value);
tmpNibble := (regAF.A and $0F);
regAF.A := ((regAF.A and $F0) or (tmpByte and $0F));
tmpByte := (((tmpByte shr 4) or (tmpNibble shl 4)) and $FF);
memWrite(regHL.Value, tmpByte);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if (HL) is negative after operation; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if (HL) is zero after operation; reset otherwise
regAF.Flag[PV] := parity[tmpByte]; // P/V is set if parity of (HL) is even after operation; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 8;
clockCycles := 16;
end;
$68: begin // OP-Code 0xED68 : IN L,(C)
regHL.L := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$69: begin // OP-Code 0xED69 : OUT (C),L
ioWrite(regBC.B, regBC.C, regHL.L);
machineCycles := 4;
clockCycles := 10;
end;
$6A: begin // OP-Code 0xED6A : ADC HL,HL
adcHL16Bit(regHL.Value);
machineCycles := 6;
clockCycles := 10;
end;
$6B: begin // OP-Code 0xED6B : LD HL,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regHL.L := memRead(tmpWord.Value);
regHL.H := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$6C: begin // OP-Code 0xED6C : MLT HL
//regHL.Value := ((regHL.H * regHL.L) and $FFFF);
regHL.Value := (regHL.H * regHL.L);
machineCycles := 13;
clockCycles := 17;
end;
$6F: begin // OP-Code 0xED6F : RLD (HL)
tmpByte := memRead(regHL.Value);
tmpNibble := (regAF.A and $0F);
regAF.A := ((regAF.A and $F0) or (tmpByte shr 4));
tmpByte := (((tmpByte shl 4) or tmpNibble) and $FF);
memWrite(regHL.Value, tmpByte);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if (HL) is negative after operation; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if (HL) is zero after operation; reset otherwise
regAF.Flag[PV] := parity[tmpByte]; // P/V is set if parity of (HL) is even after operation; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 8;
clockCycles := 16;
end;
$72: begin // OP-Code 0xED72 : SBC HL,SP
sbcHL16Bit(regSP.Value);
machineCycles := 6;
clockCycles := 10;
end;
$73: begin // OP-Code 0xED73 : LD (nn),SP
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
memWrite(tmpWord.Value, regSP.low);
memWrite(tmpWord.Value + 1, regSP.high);
machineCycles := 7;
clockCycles := 19;
end;
$74: begin // OP-Code 0xED74 : TSTIO n
tmpByte := memRead(regPC.Value);
Inc(regPC.Value);
tmpByte := (tmpByte and ioRead($00, regBC.C));
regAF.Flag[PV] := parity[tmpByte]; // P/V is set if parity is even; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if the result is zero; reset otherwise
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if the result is negative; reset otherwise
regAF.Flag[C] := False;
regAF.Flag[N] := False;
regAF.Flag[H] := True;
machineCycles := 4;
clockCycles := 12;
end;
$76: begin // OP-Code 0xED76 : SLP
tmpSLP := True;
machineCycles := 2;
clockCycles := 8;
end;
$78: begin // OP-Code 0xED78 : IN A,(C)
regAF.A := inreg8Bit(regBC.B, regBC.C);
machineCycles := 3;
clockCycles := 9;
end;
$79: begin // OP-Code 0xED79 : OUT (C),A
ioWrite(regBC.B, regBC.C, regAF.A);
machineCycles := 4;
clockCycles := 10;
end;
$7A: begin // OP-Code 0xED7A : ADC HL,SP
adcHL16Bit(regSP.Value);
machineCycles := 6;
clockCycles := 10;
end;
$7B: begin // OP-Code 0xED7B : LD SP,(nn)
tmpWord.low := memRead(regPC.Value);
Inc(regPC.Value);
tmpWord.high := memRead(regPC.Value);
Inc(regPC.Value);
regSP.low := memRead(tmpWord.Value);
regSP.high := memRead(tmpWord.Value + 1);
machineCycles := 6;
clockCycles := 18;
end;
$7C: begin // OP-Code 0xED7C : MLT SP
//regSP.Value := ((regSP.high * regSP.low) and $FFFF);
regSP.Value := (regSP.high * regSP.low);
machineCycles := 13;
clockCycles := 17;
end;
$83: begin // OP-Code 0xED83 : OTIM
tmpByte := memRead(regHL.Value);
ioWrite($00, regBC.C, tmpByte);
Inc(regHL.Value);
Inc(regBC.C);
Dec(regBC.B);
regAF.Flag[C] := (regBC.B = $FF); // C is set if a borrow occurs after B-l; reset otherwise
regAF.Flag[N] := ((tmpByte and $80) <> $00); // N is set if MSB of memData=1; reset otherwise
regAF.Flag[PV] := parity[regBC.B]; // P/V is set if parity in B is even after B-l; reset otherwise
regAF.Flag[H] := ((regBC.B and $0F) = $0F); // H is set if a borrow from bit 4 of B occurs after B-l; reset otherwise
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B=OO after B-l; reset otherwise
regAF.Flag[S] := ((regBC.B and $80) <> $00); // S is set if B is negative after B-l; reset otherwise
machineCycles := 6;
clockCycles := 14;
end;
$8B: begin // OP-Code 0xED8B : OTDM
tmpByte := memRead(regHL.Value);
ioWrite($00, regBC.C, tmpByte);
Dec(regHL.Value);
Dec(regBC.C);
Dec(regBC.B);
regAF.Flag[C] := (regBC.B = $FF); // C is set if a borrow occurs after B-l; reset otherwise
regAF.Flag[N] := ((tmpByte and $80) <> $00); // N is set if MSB of memData=1; reset otherwise
regAF.Flag[PV] := parity[regBC.B]; // P/V is set if parity in B is even after B-l; reset otherwise
regAF.Flag[H] := ((regBC.B and $0F) = $0F); // H is set if a borrow from bit 4 of B occurs after B-l; reset otherwise
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B=OO after B-l; reset otherwise
regAF.Flag[S] := ((regBC.B and $80) <> $00); // S is set if B is negative after B-l; reset otherwise
machineCycles := 6;
clockCycles := 14;
end;
$93: begin // OP-Code 0xED93 : OTIMR
tmpByte := memRead(regHL.Value);
ioWrite($00, regBC.C, tmpByte);
Inc(regHL.Value);
Inc(regBC.C);
Dec(regBC.B);
regAF.Flag[C] := (regBC.B = $FF); // C is set if a borrow occurs after B-l; reset otherwise
regAF.Flag[N] := ((tmpByte and $80) <> $00); // N is set if MSB of memData=1; reset otherwise
regAF.Flag[PV] := parity[regBC.B]; // P/V is set if parity in B is even after B-l; reset otherwise
regAF.Flag[H] := ((regBC.B and $0F) = $0F); // H is set if a borrow from bit 4 of B occurs after B-l; reset otherwise
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B=OO after B-l; reset otherwise
regAF.Flag[S] := ((regBC.B and $80) <> $00); // S is set if B is negative after B-l; reset otherwise
if (not regAF.Flag[Z]) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 8;
clockCycles := 16;
end
else begin
machineCycles := 6;
clockCycles := 14;
end;
end;
$9B: begin // OP-Code 0xED9B : OTDMR
tmpByte := memRead(regHL.Value);
ioWrite($00, regBC.C, tmpByte);
Dec(regHL.Value);
Dec(regBC.C);
Dec(regBC.B);
regAF.Flag[C] := (regBC.B = $FF); // C is set if a borrow occurs after B-l; reset otherwise
regAF.Flag[N] := ((tmpByte and $80) <> $00); // N is set if MSB of memData=1; reset otherwise
regAF.Flag[PV] := parity[regBC.B]; // P/V is set if parity in B is even after B-l; reset otherwise
regAF.Flag[H] := ((regBC.B and $0F) = $0F); // H is set if a borrow from bit 4 of B occurs after B-l; reset otherwise
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B=OO after B-l; reset otherwise
regAF.Flag[S] := ((regBC.B and $80) <> $00); // S is set if B is negative after B-l; reset otherwise
if (not regAF.Flag[Z]) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 8;
clockCycles := 16;
end
else begin
machineCycles := 6;
clockCycles := 14;
end;
end;
$A0: begin // OP-Code 0xEDA0 : LDI
memWrite(regDE.Value, memRead(regHL.Value));
Inc(regDE.Value);
Inc(regHL.Value);
Dec(regBC.Value);
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 ≠ 0; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 4;
clockCycles := 12;
end;
$A1: begin // OP-Code 0xEDA1 : CPI
tmpByte := memRead(regHL.Value);
regAF.Flag[H] := ((tmpByte and $0F) > (regAF.A and $0F)); // H is set if borrow from bit 4; reset otherwise
tmpByte := ((regAF.A - tmpByte) and $FF);
Inc(regHL.Value);
Dec(regBC.Value);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if A is (HL); reset otherwise
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 is not 0; reset otherwise
regAF.Flag[N] := True;
machineCycles := 6;
clockCycles := 12;
end;
$A2: begin // OP-Code 0xEDA2 : INI
memWrite(regHL.Value, ioRead(regBC.B, regBC.C));
Inc(regHL.Value);
Dec(regBC.B);
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B–1 = 0, reset otherwise
regAF.Flag[N] := True;
machineCycles := 4;
clockCycles := 12;
end;
$A3: begin // OP-Code 0xEDA3 : OUTI
Dec(regBC.B);
ioWrite(regBC.B, regBC.C, memRead(regHL.Value));
Inc(regHL.Value);
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B–1 = 0, reset otherwise
regAF.Flag[N] := True;
machineCycles := 4;
clockCycles := 12;
end;
$A8: begin // OP-Code 0xEDA8 : LDD
memWrite(regDE.Value, memRead(regHL.Value));
Dec(regDE.Value);
Dec(regHL.Value);
Dec(regBC.Value);
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 ≠ 0; reset otherwise
regAF.Flag[H] := False;
regAF.Flag[N] := False;
machineCycles := 4;
clockCycles := 12;
end;
$A9: begin // OP-Code 0xEDA9 : CPD
tmpByte := memRead(regHL.Value);
regAF.Flag[H] := ((tmpByte and $0F) > (regAF.A and $0F)); // H is set if borrow from bit 4; reset otherwise
tmpByte := ((regAF.A - tmpByte) and $FF);
Dec(regHL.Value);
Dec(regBC.Value);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if A is (HL); reset otherwise
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 is not 0; reset otherwise
regAF.Flag[N] := True;
machineCycles := 6;
clockCycles := 12;
end;
$AA: begin // OP-Code 0xEDAA : IND
memWrite(regHL.Value, ioRead(regBC.B, regBC.C));
Dec(regHL.Value);
Dec(regBC.B);
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B–1 = 0, reset otherwise
regAF.Flag[N] := True;
machineCycles := 4;
clockCycles := 12;
end;
$AB: begin // OP-Code 0xEDAB : OUTD
Dec(regBC.B);
ioWrite(regBC.B, regBC.C, memRead(regHL.Value));
Dec(regHL.Value);
regAF.Flag[Z] := (regBC.B = $00); // Z is set if B–1 = 0, reset otherwise
regAF.Flag[N] := True;
machineCycles := 4;
clockCycles := 12;
end;
$B0: begin // OP-Code 0xEDB0 : LDIR
memWrite(regDE.Value, memRead(regHL.Value));
Inc(regDE.Value);
Inc(regHL.Value);
Dec(regBC.Value);
regAF.Flag[PV] := False;
regAF.Flag[H] := False;
regAF.Flag[N] := False;
if (regBC.Value <> $0000) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
$B1: begin // OP-Code 0xEDB1 : CPIR
tmpByte := memRead(regHL.Value);
regAF.Flag[H] := ((tmpByte and $0F) > (regAF.A and $0F)); // H is set if borrow from bit 4; reset otherwise
tmpByte := ((regAF.A - tmpByte) and $FF);
Inc(regHL.Value);
Dec(regBC.Value);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if A is (HL); reset otherwise
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 is not 0; reset otherwise
regAF.Flag[N] := True;
if (regAF.Flag[PV] and not regAF.Flag[Z]) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 8;
clockCycles := 14;
end
else begin
machineCycles := 6;
clockCycles := 12;
end;
end;
$B2: begin // OP-Code 0xEDB2 : INIR
memWrite(regHL.Value, ioRead(regBC.B, regBC.C));
Inc(regHL.Value);
Dec(regBC.B);
regAF.Flag[Z] := True;
regAF.Flag[N] := True;
if (regBC.B <> $00) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
$B3: begin // OP-Code 0xEDB3 : OTIR
Dec(regBC.B);
ioWrite(regBC.B, regBC.C, memRead(regHL.Value));
Inc(regHL.Value);
regAF.Flag[Z] := True;
regAF.Flag[N] := True;
if (regBC.B <> $00) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
$B8: begin // OP-Code 0xEDB8 : LDDR
memWrite(regDE.Value, memRead(regHL.Value));
Dec(regDE.Value);
Dec(regHL.Value);
Dec(regBC.Value);
regAF.Flag[PV] := False;
regAF.Flag[H] := False;
regAF.Flag[N] := False;
if (regBC.Value <> $0000) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
$B9: begin // OP-Code 0xEDB9 : CPDR
tmpByte := memRead(regHL.Value);
regAF.Flag[H] := ((tmpByte and $0F) > (regAF.A and $0F)); // H is set if borrow from bit 4; reset otherwise
tmpByte := ((regAF.A - tmpByte) and $FF);
Dec(regHL.Value);
Dec(regBC.Value);
regAF.Flag[S] := ((tmpByte and $80) <> $00); // S is set if result is negative; reset otherwise
regAF.Flag[Z] := (tmpByte = $00); // Z is set if A is (HL); reset otherwise
regAF.Flag[PV] := (regBC.Value <> $0000); // P/V is set if BC-1 is not 0; reset otherwise
regAF.Flag[N] := True;
if (regAF.Flag[PV] and not regAF.Flag[Z]) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 8;
clockCycles := 14;
end
else begin
machineCycles := 6;
clockCycles := 12;
end;
end;
$BA: begin // OP-Code 0xEDBA : INDR
memWrite(regHL.Value, ioRead(regBC.B, regBC.C));
Dec(regHL.Value);
Dec(regBC.B);
regAF.Flag[Z] := True;
regAF.Flag[N] := True;
if (regBC.B <> $00) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
$BB: begin // OP-Code 0xEDBB : OTDR
Dec(regBC.B);
ioWrite(regBC.B, regBC.C, memRead(regHL.Value));
Dec(regHL.Value);
regAF.Flag[Z] := True;
regAF.Flag[N] := True;
if (regBC.B <> $00) then begin
//regPC.Value := ((regPC.Value - 2) and $FFFF);
Dec(regPC.Value, 2);
machineCycles := 6;
clockCycles := 14;
end
else begin
machineCycles := 4;
clockCycles := 12;
end;
end;
{$ifdef Z180TRAP}
else begin
ioITC.bit[TRAP] := True; // TRAP Flag in ITC-Register setzen
ioITC.bit[UFO] := False; // UFO-Flag loeschen, da TRAP in 2. OP-Code aufgetreten
Dec(regPC.Value); // PC korrigieren
push(regPC.Value);
regPC.Value := $0000;
machineCycles := 4;
clockCycles := 12;
end;
{$endif}
end;
end;
// --------------------------------------------------------------------------------
end.
|
unit ThButton;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics, ExtCtrls,
ThInterfaces, ThCssStyle, ThTextPaint, ThWebControl, ThTag;
type
TThButtonType = ( btSubmit, btReset, btCustom );
//
TThCustomButton = class(TThWebGraphicControl, IThFormInput)
private
FButtonType: TThButtonType;
protected
function ButtonHeight: Integer;
function ButtonWidth: Integer;
procedure Paint; override;
procedure PerformAutoSize; override;
procedure Tag(inTag: TThTag); override;
protected
property AutoSize default true;
property ButtonType: TThButtonType read FButtonType write FButtonType
default btSubmit;
public
constructor Create(AOwner: TComponent); override;
procedure CellTag(inTag: TThTag); override;
//function GetCellStyleAttribute: string; override;
end;
//
TThButton = class(TThCustomButton)
published
property Align;
property AutoSize default true;
property ButtonType;
property Caption;
property Style;
property StyleClass;
property Visible;
public
constructor Create(AOwner: TComponent); override;
end;
const
htThButtonTypes: array[TThButtonType] of string =
( 'submit', 'reset', 'button' );
implementation
{ TThCustomButton }
constructor TThCustomButton.Create(AOwner: TComponent);
begin
inherited;
AutoSize := true;
Style.Border.DefaultBorderPixels := 2;
CtrlStyle.Font.DefaultFontFamily := 'MS Sans Serif';
CtrlStyle.Font.DefaultFontPx := 14;
end;
function TThCustomButton.ButtonWidth: Integer;
begin
if AutoSize then
begin
Result := ThTextWidth(Canvas, Caption);
Result := Result * 140 div 100;
Result := Result + Style.GetBoxWidthMargin;
end else
Result := Width;
end;
function TThCustomButton.ButtonHeight: Integer;
begin
if AutoSize then
begin
Result := ThTextHeight(Canvas, Caption) + 6; //8;
// if Style.Borders.BordersVisible then
// Result := Result + 5;
// else
// Result := Result + 9;
if (Result < 0) then
Result := Height
else
Result := Result + Style.GetBoxHeightMargin;
end else
Result := Height;
end;
procedure TThCustomButton.PerformAutoSize;
begin
Canvas.Font := Font;
SetBounds(Left, Top, ButtonWidth, ButtonHeight);
end;
procedure TThCustomButton.Paint;
var
r: TRect;
begin
r := ClientRect;
if (Parent is TWinControl) then
Canvas.Brush.Color := TPanel(Parent).Color
else
Canvas.Brush.Color := Color;
Canvas.FillRect(r);
Style.UnpadRect(r);
//
Painter.Prepare(Color, CtrlStyle, Canvas, r);
if not ThVisibleColor(CtrlStyle.Color) then
Painter.Color := clBtnFace;
Painter.PaintBackground;
Painter.PaintOutsetBorders;
//
Canvas.Font := Font;
ThPaintText(Canvas, Caption, r, haCenter, vaMiddle);
end;
procedure TThCustomButton.CellTag(inTag: TThTag);
begin
inherited;
Style.Font.ListStyles(inTag.Styles);
Style.Padding.ListStyles(inTag.Styles);
end;
{
function TThCustomButton.GetCellStyleAttribute: string;
begin
with Style do
Result := Font.InlineAttribute + Padding.InlineAttribute;
if Result <> '' then
Result := ' style="' + Result + '"';
end;
}
procedure TThCustomButton.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Element := 'input';
Add('name', Name);
Add('type', htThButtonTypes[ButtonType]);
Add('value', Caption);
AddStyle('width', '100%');
AddStyle('height', '100%');
{
if not AutoSize then
begin
AddStyle('width', Width, 'px');
AddStyle('height', Height, 'px');
end;
}
Style.Border.ListStyles(Styles);
end;
end;
{ TThButton }
constructor TThButton.Create(AOwner: TComponent);
begin
inherited;
FAutoSize := true;
end;
end.
|
{*******************************************************************************
* uFormControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа с формой ввода (TqFFormControl) *
* Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uFormControl;
interface
uses
SysUtils, Classes, Controls, pFIBDatabase, pFIBDataset, pFIBQuery,
FIB, Forms, FIBDatabase;
type
TFormMode = (fmAdd, fmModify, fmInfo, fmClone, fmDelete);
TqFAfterPrepareEvent = procedure(Sender: TObject; Form: TForm; Mode: TFormMode) of object;
TqFDatabaseEvent = procedure(Sender: TObject; Form: TForm; Mode: TFormMode;
Transaction: TFIBTransaction) of object;
TqFFormControl = class(TGraphicControl)
private
FMode: TFormMode;
FControlsParent: TWinControl;
FControlsOwner: TComponent;
FWriteTransaction: TpFIBTransaction;
FReadTransaction: TpFIBTransaction;
FSelectDataset: TpFIBDataSet;
FAddDataset: TpFIBDataSet;
FModifyQuery: TpFIBQuery;
FLastId: Variant;
FWhere: Variant;
FAddCaption: string;
FModifyCaption: string;
FInfoCaption: string;
FAfterPrepare: TqFAfterPrepareEvent;
FDatabaseEventBefore: TqFDatabaseEvent;
FDatabaseEventAfter: TqFDatabaseEvent;
FNewRecordBeforePrepare: TNotifyEvent;
FNewRecordAfterPrepare: TNotifyEvent;
FModifyRecordBeforePrepare: TNotifyEvent;
FModifyRecordAfterPrepare: TNotifyEvent;
FInfoRecordBeforePrepare: TNotifyEvent;
FInfoRecordAfterPrepare: TNotifyEvent;
FAfterRecordAdded: TNotifyEvent;
FCheckWhere: Boolean;
FCloseForm: Boolean;
FShowErrorDialog: Boolean;
FShowDebugInfoInOK: Boolean;
procedure FreeDBObjects;
procedure SetInsertSQL(SQL: TStrings);
function GetInsertSQL: TStrings;
procedure SetSelectSQL(SQL: TStrings);
function GetSelectSQL: TStrings;
procedure SetUpdateSQL(SQL: TStrings);
function GetUpdateSQL: TStrings;
procedure SetDatabase(DB: TpFIBDatabase);
public
IsEmpty: Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
function Prepare(DB: TpFIBDatabase; Mode: TFormMode; Where: Variant;
Additional: Variant): Boolean;
function Check: Boolean;
function Ok: Boolean;
published
property ControlsParent: TWinControl read FControlsParent write FControlsParent;
property ControlsOwner: TComponent read FControlsOwner write FControlsOwner;
property InsertSQL: TStrings read GetInsertSQL write SetInsertSQL;
property UpdateSQL: TStrings read GetUpdateSQL write SetUpdateSQL;
property SelectSQL: TStrings read GetSelectSQL write SetSelectSQL;
property LastId: Variant read FLastId write FLastId; // vallkor write FLastId
property AddCaption: string read FAddCaption write FAddCaption;
property ModifyCaption: string read FModifyCaption write FModifyCaption;
property InfoCaption: string read FInfoCaption write FInfoCaption;
property AfterPrepare: TqFAfterPrepareEvent read FAfterPrepare write FAfterPrepare;
property NewRecordBeforePrepare: TNotifyEvent read FNewRecordBeforePrepare write FNewRecordBeforePrepare;
property NewRecordAfterPrepare: TNotifyEvent read FNewRecordAfterPrepare write FNewRecordAfterPrepare;
property ModifyRecordBeforePrepare: TNotifyEvent read FModifyRecordBeforePrepare write FModifyRecordBeforePrepare;
property ModifyRecordAfterPrepare: TNotifyEvent read FModifyRecordAfterPrepare write FModifyRecordAfterPrepare;
property InfoRecordBeforePrepare: TNotifyEvent read FInfoRecordBeforePrepare write FInfoRecordBeforePrepare;
property InfoRecordAfterPrepare: TNotifyEvent read FInfoRecordAfterPrepare write FInfoRecordAfterPrepare;
property AfterRecordAdded: TNotifyEvent read FAfterRecordAdded write FAfterRecordAdded;
property DatabaseEventBefore: TqFDatabaseEvent read FDatabaseEventBefore write FDatabaseEventBefore;
property DatabaseEventAfter: TqFDatabaseEvent read FDatabaseEventAfter write FDatabaseEventAfter;
property Mode: TFormMode read FMode write FMode;
property CheckWhere: Boolean read FCheckWhere write FCheckWhere;
property CloseForm: Boolean read FCloseForm write FCloseForm;
property ShowErrorDialog: Boolean read FShowErrorDialog write FShowErrorDialog;
property ShowDebugInfoInOk: Boolean read FShowDebugInfoInOk write FShowDebugInfoInOk;
end;
var
Acc_Id_User: Integer;
procedure Register;
{$R *.res}
implementation
uses qFTools, Dialogs, FIBDataSet, FIBQuery, qFStrings, Variants;
function TqFFormControl.Check: Boolean;
begin
Result := qFCheckAll(ControlsOwner, ControlsParent);
end;
// занести информацию в базу
function TqFFormControl.Ok: Boolean;
var
form: TForm;
origSQL, newSQL: string;
begin
// если владелец форма, то запретить автоматическое закрытие
if Owner is TForm then
form := Owner as TForm
else
form := nil;
if FCloseForm and (form <> nil) then form.ModalResult := mrNone;
FLastId := Null;
// если жмем ОК на просмотре - снять блокировку с записи и выйти
if FMode = fmInfo then
begin
if FReadTransaction.Active then FReadTransaction.Commit;
if FCloseForm and (form <> nil) then form.ModalResult := mrOk;
Result := True;
Exit;
end;
result := False;
try
qFAutoSaveIntoRegistry(ControlsOwner, ControlsParent); // vallkor
except
end;
if Check then
begin
result := True;
// добавление в базу новой записи
if (FMode = fmAdd) or (FMode = fmClone) then
try
FAddDataSet.Transaction.StartTransaction;
if Assigned(FDatabaseEventBefore) then
FDatabaseEventBefore(Self, Form, Mode, FAddDataSet.Transaction);
// сохранить оригинальный текст запроса (если вдруг ошибка)
// и заменить параметры значениями
origSQL := FAddDataSet.SelectSQL.Text;
newSQL := qFSubsParams(origSQL, ControlsOwner, ControlsParent);
if (FMode = fmClone) and qFNotEmpty(FWhere) then
newSQL := StringReplace(newSQL, ':where',
qFVariantToString(FWhere), [rfReplaceAll]);
// заменить идентификатор пользоваля
newSQL := StringReplace(newSQL, ':Acc_Id_User',
IntToStr(Acc_Id_User), [rfReplaceAll]);
FAddDataSet.SelectSQL.Text := newSQL;
if ShowDebugInfoInOk then
qFInformDialog('fmAdd/fmClone: SQL=' + #13#10 +
newSQL);
FSelectDataset.Close;
FAddDataSet.Open;
FAddDataSet.FetchAll;
// получить значение добавленного идентификатора, если он есть
if FAddDataSet.FieldCount > 0 then
FLastId := FAddDataSet.Fields[0].Value
else
FLastId := Null;
FWhere := FLastId;
FAddDataSet.Close;
// вернуть оригинальный текст запроса
FAddDataSet.SelectSQL.Text := origSQL;
if Assigned(FDatabaseEventAfter) then
FDatabaseEventAfter(Self, Form, Mode, FAddDataSet.Transaction);
// подтвердить транзакцию, выйти, если владелец - форма
if FAddDataSet.Transaction.InTransaction then FAddDataSet.Transaction.Commit;
if FCloseForm and (form <> nil) then form.ModalResult := mrOk;
if Assigned(FAfterRecordAdded) then
FAfterRecordAdded(Self);
except on e: Exception do
begin
// откатить транзакцию, вернуть исходный текст, показать ошибку
if FAddDataSet.Transaction.Active then
FAddDataSet.Transaction.Rollback;
FAddDataSet.Close;
FAddDataSet.SelectSQL.Text := origSQL;
if ShowErrorDialog then
qFErrorDialog(qFErrorMsg + ': ' + e.Message + '!');
result := False; //vallkor
end;
end
else
{// изменить запись}if FMode = fmModify then
try
FModifyQuery.Transaction.StartTransaction;
if Assigned(FDatabaseEventBefore) then
FDatabaseEventBefore(Self, Form, Mode, FAddDataSet.Transaction);
// сохранить оригинальный текст запроса и заменить параметры
origSQL := FModifyQuery.SQL.Text;
if qFNotEmpty(FWhere) then
begin
newSQL := StringReplace(origSQL, ':where',
qFVariantToString(FWhere), [rfReplaceAll]);
FModifyQuery.SQL.Text := newSQL;
end
else
if FCheckWhere then
Exception.Create(qFCantOk);
newSQL := qFSubsParams(FModifyQuery.SQL.Text, ControlsOwner, ControlsParent);
// заменить идентификатор пользоваля
newSQL := StringReplace(newSQL, ':Acc_Id_User',
IntToStr(Acc_Id_User), [rfReplaceAll]);
FModifyQuery.SQL.Text := newSQL;
if ShowDebugInfoInOk then
qFInformDialog('fmAdd/fmClone: SQL=' + #13#10 +
newSQL);
// снять блокировку
if FReadTransaction.Active then FReadTransaction.Commit;
FModifyQuery.ExecQuery;
// проверка, если долбаные фибы не закрыли датасет
if FModifyQuery.Open then FModifyQuery.Close;
FModifyQuery.SQL.Text := origSQL;
// выполнить дополнительные действия
if Assigned(FDatabaseEventAfter) then
FDatabaseEventAfter(Self, Form, Mode, FAddDataSet.Transaction);
if FModifyQuery.Transaction.InTransaction then FModifyQuery.Transaction.Commit;
if FReadTransaction.Active then FReadTransaction.Commit;
qFAutoSaveIntoRegistry(ControlsOwner, ControlsParent); // vallkor
if FCloseForm and (form <> nil) then form.ModalResult := mrOk;
except on e: Exception do
begin
if FAddDataSet.Transaction.Active then
FModifyQuery.Transaction.Rollback;
// проверка, если долбаные фибы не закрыли датасет
if FModifyQuery.Open then FModifyQuery.Close;
FModifyQuery.SQL.Text := origSQL;
if ShowErrorDialog then
qFErrorDialog(qFErrorMsg + ': ' + e.Message + '!');
// возобновить блокировку
FSelectDataSet.Open;
result := False; //vallkor
end;
end;
end; // vallkor
end;
// подготовить форму
function TqFFormControl.Prepare(DB: TpFIBDatabase; Mode: TFormMode;
Where: Variant; Additional: Variant): Boolean;
var
form: TForm;
begin
Result := True;
// проверить, вдруг это повторное считывание
if (FSelectDataset.Transaction <> nil) and
FSelectDataset.Transaction.InTransaction then
FSelectDataset.Transaction.Rollback;
SetDatabase(DB);
FMode := Mode;
FWhere := Where;
form := nil;
// заменить дополнительные параметры, если не пустые
if (Mode = fmModify) and qFNotEmpty(Additional) then
begin
FModifyQuery.SQL.Text := StringReplace(
FModifyQuery.SQL.Text, ':add', qFVariantToString(Additional),
[rfReplaceAll]);
end;
if ((Mode = fmAdd) or (Mode = fmClone)) and qFNotEmpty(Additional) then
begin
FAddDataSet.SelectSQL.Text := StringReplace(
FAddDataSet.SelectSQL.Text, ':add',
qFVariantToString(Additional), [rfReplaceAll]);
end;
// вызвать дополнительные обработчики, если есть
if (Mode = fmAdd) and Assigned(FNewRecordBeforePrepare) then
FNewRecordBeforePrepare(Self);
if (Mode = fmModify) and Assigned(FModifyRecordBeforePrepare) then
FModifyRecordBeforePrepare(Self);
if (Mode = fmInfo) and Assigned(FInfoRecordBeforePrepare) then
FInfoRecordBeforePrepare(Self);
if (Mode = fmModify) or (Mode = fmInfo) or (Mode = fmClone) then
begin
// заменить параметры еще раз
SelectSQL.Text := qFSubsParams(SelectSQL.Text, ControlsOwner, ControlsParent);
// заменить параметр для ключа его значением
if qFNotEmpty(FWhere) then
with FSelectDataSet do
SelectSQL.Text := StringReplace(SelectSQL.Text, ':where',
qFVariantToString(FWhere), [rfReplaceAll])
else
if FCheckWhere then
begin
qFErrorDialog(qFCantPrepare);
// сбросить блокировку, если что
if (FSelectDataset.Transaction <> nil) and
FSelectDataset.Transaction.InTransaction then
FSelectDataset.Transaction.Rollback;
Exit;
end;
// попробовать получить данные
FSelectDataset.Transaction.StartTransaction;
try
FSelectDataset.Close;
FSelectDataset.Open;
except on e: Exception do
begin
// в случае ошибки посмотреть, не блокировка ли это
// и выдать соответствующее сообщение
if (e is EFIBInterbaseError) and
((e as EFIBInterbaseError).IBErrorCode = 335544345) then
qFErrorDialog(qFLockErrorMsg)
else
qFErrorDialog(qFGetErrorMsg + ': ' + e.Message + '!');
Result := False;
// сбросить блокировку, если что
if (FSelectDataset.Transaction <> nil) and
FSelectDataset.Transaction.InTransaction then
FSelectDataset.Transaction.Rollback;
IsEmpty := True;
Exit;
end;
end;
IsEmpty := FSelectDataset.IsEmpty;
// считать данные в контролы
qFReadData(FSelectDataset, ControlsOwner, ControlsParent);
FSelectDataset.Close;
end;
// если у нас режим просмотра, заблокировать контролы
if Mode = fmInfo then
qFBlock(True, ControlsOwner, ControlsParent);
if Mode = fmAdd then // vallkor
qFAutoLoadFromRegistry(ControlsOwner, ControlsParent);
// установить нужный заголовок у формы
if Owner is TForm then
begin
form := Owner as TForm;
if Mode = fmAdd then form.Caption := FAddCaption;
if (Mode = fmModify) or (Mode = fmClone) then
form.Caption := FModifyCaption;
if Mode = fmInfo then form.Caption := FInfoCaption;
end;
// вызвать дополнительные обработчики, если есть
if (Mode = fmAdd) and Assigned(FNewRecordAfterPrepare) then
FNewRecordAfterPrepare(Self);
if (Mode = fmModify) and Assigned(FModifyRecordAfterPrepare) then
FModifyRecordAfterPrepare(Self);
if (Mode = fmInfo) and Assigned(FInfoRecordAfterPrepare) then
FInfoRecordAfterPrepare(Self);
if Assigned(FAfterPrepare) then
FAfterPrepare(Self, form, Mode);
if form <> nil then form.Repaint;
// стать на первый по TabOrder'у контрол
qFSetFocus(ControlsOwner, ControlsParent);
end;
procedure TqFFormControl.SetInsertSQL(SQL: TStrings);
begin
FAddDataSet.SelectSQL := SQL;
end;
function TqFFormControl.GetInsertSQL: TStrings;
begin
Result := FAddDataSet.SelectSQL;
end;
procedure TqFFormControl.SetSelectSQL(SQL: TStrings);
begin
FSelectDataSet.SelectSQL := SQL;
end;
function TqFFormControl.GetSelectSQL: TStrings;
begin
Result := FSelectDataSet.SelectSQL;
end;
procedure TqFFormControl.SetUpdateSQL(SQL: TStrings);
begin
FModifyQuery.SQL := SQL;
end;
function TqFFormControl.GetUpdateSQL: TStrings;
begin
Result := FModifyQuery.SQL;
end;
procedure TqFFormControl.SetDatabase(DB: TpFIBDatabase);
begin
// на случай повторного считывания данных - чтоб не было ошибки
if FReadTransaction.Active then
FReadTransaction.Rollback;
FReadTransaction.DefaultDatabase := DB;
with FReadTransaction.TRParams do
begin
Add('read_committed');
Add('rec_version');
Add('nowait');
end;
// на случай повторного считывания данных - чтоб не было ошибки
if FWriteTransaction.Active then
FWriteTransaction.Rollback;
FWriteTransaction.DefaultDatabase := DB;
with FWriteTransaction.TRParams do
begin
Add('read_committed');
Add('rec_version');
Add('nowait');
end;
FAddDataSet.Database := FWriteTransaction.DefaultDatabase;
FAddDataSet.Transaction := FWriteTransaction;
FModifyQuery.Database := FWriteTransaction.DefaultDatabase;
FModifyQuery.Transaction := FWriteTransaction;
FSelectDataSet.Database := FReadTransaction.DefaultDatabase;
FSelectDataSet.Transaction := FReadTransaction;
end;
procedure TqFFormControl.FreeDBObjects;
begin
FAddDataset.Free;
FModifyQuery.Free;
FSelectDataset.Free;
FWriteTransaction.Free;
FReadTransaction.Free;
end;
destructor TqFFormControl.Destroy;
begin
FreeDBObjects;
inherited Destroy;
end;
constructor TqFFormControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 60;
Height := 21;
FControlsOwner := AOwner;
FReadTransaction := TpFIBTransaction.Create(nil);
FWriteTransaction := TpFIBTransaction.Create(nil);
FAddDataSet := TpFIBDataset.Create(nil);
FModifyQuery := TpFIBQuery.Create(nil);
FSelectDataSet := TpFIBDataset.Create(nil);
Visible := False;
FCheckWhere := True;
FCloseForm := True;
FShowErrorDialog := True;
FShowDebugInfoInOK := False;
IsEmpty := True;
end;
procedure TqFFormControl.Paint;
begin
inherited;
with Canvas do
begin
Rectangle(0, 0, Width, Height);
Font.Color := $FF0000;
TextOut(1, 3, 'FormControl');
end;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFFormControl]);
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 170652
////////////////////////////////////////////////////////////////////////////////
unit android.provider.ContactsContract_DeletedContacts;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.net.Uri;
type
JContactsContract_DeletedContacts = interface;
JContactsContract_DeletedContactsClass = interface(JObjectClass)
['{D182B873-8737-421F-A4AC-00EA870E0330}']
function _GetCONTENT_URI : JUri; cdecl; // A: $19
function _GetDAYS_KEPT_MILLISECONDS : Int64; cdecl; // A: $19
property CONTENT_URI : JUri read _GetCONTENT_URI; // Landroid/net/Uri; A: $19
property DAYS_KEPT_MILLISECONDS : Int64 read _GetDAYS_KEPT_MILLISECONDS; // J A: $19
end;
[JavaSignature('android/provider/ContactsContract_DeletedContacts')]
JContactsContract_DeletedContacts = interface(JObject)
['{8B3CB96D-405E-4DEA-ABB8-EC414C120E4C}']
end;
TJContactsContract_DeletedContacts = class(TJavaGenericImport<JContactsContract_DeletedContactsClass, JContactsContract_DeletedContacts>)
end;
const
TJContactsContract_DeletedContactsDAYS_KEPT_MILLISECONDS = 2592000000;
implementation
end.
|
unit Chapter02._02_Main;
interface
uses
System.Classes,
System.SysUtils,
System.Math;
procedure Main;
implementation
procedure Main;
var
x, n, i: integer;
sum: int64;
startTime, endTime: TDateTime;
begin
// 数据规模每次增大10倍进行测试
// 有兴趣的同学也可以试验一下数据规模每次增大2倍哦:)
for x := 1 to 9 do
begin
n := Round(Power(10, x));
startTime := Now;
sum := 0;
for i := 0 to n - 1 do
sum := sum + i;
endTime := Now;
WriteLn('sum = ', sum);
WriteLn('10^', x, ' : ', endTime - startTime, ' ms');
WriteLn;
end;
end;
end.
|
unit GBlur2;
interface
uses
Winapi.Windows,
Vcl.Graphics,
Dmitry.Graphics.Types,
uEditorTypes;
type
PRGBTriple = ^TRGBTriple;
TRGBTriple = packed record
B: Byte;
G: Byte;
R: Byte;
end;
type
TRGBArray = array [0 .. 32677] of Winapi.Windows.TRGBTriple; // bitmap element (API windows)
PRGBArray = ^TRGBArray; // type pointer to 3 bytes array
TArPRGBArray = array of PRGBArray;
PRow = ^TRow;
TRow = array [0 .. 32677] of TRGBTriple;
PPRows = ^TPRows;
TPRows = array [0 .. 32677] of PRow;
const
MaxKernelSize = 100;
type
TKernelSize = 1 .. MaxKernelSize;
TKernel = record
Size: TKernelSize;
Weights: array [-MaxKernelSize .. MaxKernelSize] of Single;
end;
// идея заключается в том, что при использовании TKernel мы игнорируем
// Weights (вес), за исключением Weights в диапазоне -Size..Size.
procedure GBlur(TheBitmap: TBitmap; Radius: Double; CallBack: TProgressCallBackProc = nil);
procedure GBlurW(A, B: Integer; TheBitmap: TBitmap; Radius: Double; CallBack: TProgressCallBackProc = nil);
procedure GBlurWX(A, B: Integer; TheBitmap: TBitmap; ScanLines: TArPRGBArray; Radius: Double;
CallBack: TProgressCallBackProc = nil);
implementation
uses
SysUtils;
procedure MakeGaussianKernel(var K: TKernel; Radius: Double;
MaxData, DataGranularity: Double; CallBack: TProgressCallBackProc = nil);
// Делаем K (гауссово зерно) со среднеквадратичным отклонением = radius.
// Для текущего приложения мы устанавливаем переменные MaxData = 255,
// DataGranularity = 1. Теперь в процедуре установим значение
// K.Size так, что при использовании K мы будем игнорировать Weights (вес)
// с наименее возможными значениями. (Малый размер нам на пользу,
// поскольку время выполнения напрямую зависит от
// значения K.Size.)
var
J: Integer;
Temp, Delta: Double;
KernelSize: TKernelSize;
begin
for J := low(K.Weights) to high(K.Weights) do
begin
Temp := J / Radius;
K.Weights[J] := Exp(-Temp * Temp / 2);
end;
// делаем так, чтобы sum(Weights) = 1:
Temp := 0;
for J := low(K.Weights) to high(K.Weights) do
Temp := Temp + K.Weights[J];
for J := low(K.Weights) to high(K.Weights) do
K.Weights[J] := K.Weights[J] / Temp;
// теперь отбрасываем (или делаем отметку "игнорировать"
// для переменной Size) данные, имеющие относительно небольшое значение -
// это важно, в противном случае смазавание происходим с малым радиусом и
// той области, которая "захватывается" большим радиусом...
KernelSize := MaxKernelSize;
Delta := DataGranularity / (2 * MaxData);
Temp := 0;
while (Temp < Delta) and (KernelSize > 1) do
begin
Temp := Temp + 2 * K.Weights[KernelSize];
Dec(KernelSize);
end;
K.Size := KernelSize;
// теперь для корректности возвращаемого результата проводим ту же
// операцию с K.Size, так, чтобы сумма всех данных была равна единице:
Temp := 0;
for J := -K.Size to K.Size do
Temp := Temp + K.Weights[J];
for J := -K.Size to K.Size do
K.Weights[J] := K.Weights[J] / Temp;
end;
function TrimInt(Lower, Upper, TheInteger: Integer): Integer;
begin
if (TheInteger <= Upper) and (TheInteger >= Lower) then
Result := TheInteger
else if TheInteger > Upper then
Result := Upper
else
result := Lower;
end;
function TrimReal(Lower, Upper: Integer; X: Double): Integer;
begin
if (X < Upper) and (X >= Lower) then
Result := Trunc(X)
else if X > Upper then
Result := Upper
else
Result := Lower;
end;
procedure BlurRow(var TheRow: array of TRGBTriple; K: TKernel; P: PRow);
var
J, N: Integer;
Tr, Tg, Tb: Double; // tempRed и др.
W: Double;
begin
for J := 0 to high(TheRow) do
begin
Tb := 0;
Tg := 0;
Tr := 0;
for N := -K.Size to K.Size do
begin
W := K.Weights[N];
// TrimInt задает отступ от края строки...
with TheRow[TrimInt(0, high(TheRow), J - N)] do
begin
Tb := Tb + W * B;
Tg := Tg + W * G;
Tr := Tr + W * R;
end;
end;
with P[J] do
begin
B := TrimReal(0, 255, Tb);
G := TrimReal(0, 255, Tg);
R := TrimReal(0, 255, Tr);
end;
end;
Move(P[0], TheRow[0], ( high(TheRow) + 1) * Sizeof(TRGBTriple));
end;
procedure GBlur(TheBitmap: TBitmap; Radius: Double; CallBack: TProgressCallBackProc = nil);
begin
GBlurW(0, 100, TheBitmap, Radius, CallBack);
end;
procedure GBlurWX(A, B: Integer; TheBitmap: TBitmap; ScanLines: TArPRGBArray; Radius: Double;
CallBack: TProgressCallBackProc = nil);
var
Row, Col: Integer;
TheRows: PPRows;
K: TKernel;
ACol: PRow;
P: PRow;
Terminate: Boolean;
begin
if (TheBitmap.HandleType <> BmDIB) or (TheBitmap.PixelFormat <> pf24Bit) then
raise Exception.Create('GBlur can work only with 24-bit images');
MakeGaussianKernel(K, Radius, 255, 1);
GetMem(TheRows, TheBitmap.Height * SizeOf(PRow));
GetMem(ACol, theBitmap.Height * SizeOf(TRGBTriple));
//запись позиции данных изображения:
for Row := 0 to theBitmap.Height - 1 do
theRows[Row] := PRow(ScanLines[Row]); // theBitmap.Scanline[Row];
// размываем каждую строчку:
P := AllocMem(TheBitmap.Width * SizeOf(TRGBTriple));
for Row := 0 to TheBitmap.Height - 1 do
BlurRow(Slice(TheRows[Row]^, TheBitmap.Width), K, P);
// теперь размываем каждую колонку
ReAllocMem(P, TheBitmap.Height * SizeOf(TRGBTriple));
Terminate := False;
for Col := 0 to TheBitmap.Width - 1 do
begin
// - считываем первую колонку в TRow:
for Row := 0 to TheBitmap.Height - 1 do
ACol[Row] := TheRows[Row][Col];
BlurRow(Slice(ACol^, TheBitmap.Height), K, P);
// теперь помещаем обработанный столбец на свое место в данные изображения:
for Row := 0 to TheBitmap.Height - 1 do
TheRows[Row][Col] := ACol[Row];
if Col mod (TheBitmap.Width div 50) = 0 then
if Assigned(CallBack) then
CallBack(A + Round(Col * B / Thebitmap.Width), Terminate);
if Terminate then
Break;
end;
FreeMem(TheRows);
FreeMem(ACol);
ReAllocMem(P, 0);
end;
procedure GBlurW(A, B: Integer; TheBitmap: TBitmap; Radius: Double; CallBack: TProgressCallBackProc = nil);
var
Row, Col: Integer;
TheRows: PPRows;
K: TKernel;
ACol: PRow;
P: PRow;
Terminate: Boolean;
begin
if (TheBitmap.HandleType <> BmDIB) or (TheBitmap.PixelFormat <> Pf24Bit) then
raise Exception.Create('GBlur может работать только с 24-битными изображениями');
MakeGaussianKernel(K, Radius, 255, 1);
GetMem(TheRows, TheBitmap.Height * SizeOf(PRow));
GetMem(ACol, TheBitmap.Height * SizeOf(TRGBTriple));
// запись позиции данных изображения:
for Row := 0 to TheBitmap.Height - 1 do
TheRows[Row] := TheBitmap.Scanline[Row];
// размываем каждую строчку:
P := AllocMem(TheBitmap.Width * SizeOf(TRGBTriple));
for Row := 0 to TheBitmap.Height - 1 do
BlurRow(Slice(TheRows[Row]^, TheBitmap.Width), K, P);
// теперь размываем каждую колонку
ReAllocMem(P, theBitmap.Height * SizeOf(TRGBTriple));
Terminate:=false;
for Col := 0 to theBitmap.Width - 1 do
begin
//- считываем первую колонку в TRow:
for Row := 0 to theBitmap.Height - 1 do
ACol[Row] := theRows[Row][Col];
BlurRow(Slice(ACol^, theBitmap.Height), K, P);
//теперь помещаем обработанный столбец на свое место в данные изображения:
for Row := 0 to theBitmap.Height - 1 do
theRows[Row][Col] := ACol[Row];
if Col mod (theBitmap.Width div 50)=0 then
if Assigned(CallBack) then CallBack(a+Round(Col*b/thebitmap.Width),Terminate);
if Terminate then break;
end;
FreeMem(theRows);
FreeMem(ACol);
ReAllocMem(P, 0);
end;
end.
|
unit TaxBillPrintForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, RXSpin, ToolEdit, Mask, CurrEdit, Placemnt, Buttons,
uCommonForm,uOilQuery,Ora, uOilStoredProc;
type
TStorageAction = (saLoadSave, saLoad, saSave, saNoAction);
type
TfrmTaxBillPrintForm = class(TCommonForm)
pnlTop: TPanel;
rbUseDefault: TRadioButton;
rbAlwaysAsk: TRadioButton;
pnlBottom: TPanel;
rbEmpty: TRadioButton;
rbOrigOnly: TRadioButton;
rbAll: TRadioButton;
FormStorage: TFormStorage;
Panel1: TPanel;
bbOk: TBitBtn;
rbCopyOnly: TRadioButton;
pnlClient: TPanel;
Label6: TLabel;
sbUpDown: TRxSpinButton;
cbOutputType: TComboBox;
edNumOfCopy: TRxCalcEdit;
deSaveTo: TDirectoryEdit;
chSaveTo: TCheckBox;
Label1: TLabel;
procedure cbOutputTypeChange(Sender: TObject);
procedure rbUseDefaultClick(Sender: TObject);
procedure rbAlwaysAskClick(Sender: TObject);
procedure chSaveToClick(Sender: TObject);
procedure FormStorageRestorePlacement(Sender: TObject);
procedure sbUpDownTopClick(Sender: TObject);
procedure sbUpDownBottomClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FStorage: TStorageAction;
public
procedure EnableComponents(AEnabled: Boolean);
constructor Create(AStorage: TStorageAction = saLoadSave); reintroduce;
end;
var
frmTaxBillPrintForm: TfrmTaxBillPrintForm;
implementation
{$R *.DFM}
procedure TfrmTaxBillPrintForm.cbOutputTypeChange(Sender: TObject);
begin
FormStorage.StoredValues.Items[0].Value := cbOutputType.ItemIndex;
edNumOfCopy.Enabled := cbOutputType.ItemIndex = 1;
sbUpDown.Enabled := cbOutputType.ItemIndex = 1;
chSaveTo.Checked := cbOutputType.ItemIndex = 2;
chSaveToClick(nil);
if (cbOutputType.Itemindex = 0) or
(cbOutputType.Itemindex = 2)
then edNumOfCopy.value := 1;
end;
procedure TfrmTaxBillPrintForm.rbUseDefaultClick(Sender: TObject);
begin
EnableComponents(True);
end;
procedure TfrmTaxBillPrintForm.rbAlwaysAskClick(Sender: TObject);
begin
EnableComponents(False);
end;
procedure TfrmTaxBillPrintForm.EnableComponents(AEnabled:Boolean);
var
i : integer;
begin
for i:= ComponentCount - 1 downto 0 do
if (Components[i] is TControl) then
if ((Components[i] as TControl).Parent = pnlBottom) or
((Components[i] as TControl).Parent = pnlClient)
then
(Components[i] as TControl).Enabled := AEnabled;
end;
procedure TfrmTaxBillPrintForm.chSaveToClick(Sender: TObject);
begin
deSaveTo.Enabled := chSaveTo.Checked;
end;
procedure TfrmTaxBillPrintForm.sbUpDownTopClick(Sender: TObject);
begin
edNumOfCopy.AsInteger := 1 + edNumOfCopy.AsInteger;
end;
procedure TfrmTaxBillPrintForm.sbUpDownBottomClick(Sender: TObject);
begin
if edNumOfCopy.Value>0 then edNumOfCopy.Value := edNumOfCopy.Value - 1;
end;
procedure TfrmTaxBillPrintForm.FormCreate(Sender: TObject);
begin
inherited;
FormStorage.RestoreFormPlacement;
end;
procedure TfrmTaxBillPrintForm.FormStorageRestorePlacement(
Sender: TObject);
begin
if FormStorage.StoredValues[0].Value <> '' then
cbOutputType.ItemIndex := FormStorage.StoredValues[0].Value;
cbOutputTypeChange(nil);
end;
constructor TfrmTaxBillPrintForm.Create(AStorage: TStorageAction = saLoadSave);
begin
inherited Create(Application);
FStorage := AStorage;
FormStorage.Active := (FStorage in [saLoadSave, saLoad]);
end;
procedure TfrmTaxBillPrintForm.FormShow(Sender: TObject);
begin
inherited;
FormStorage.Active := (FStorage in [saLoadSave, saSave]);
end;
end.
|
unit UMainForm;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.OpenGL,
Winapi.OpenGLext,
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.Imaging.jpeg, Vcl.StdCtrls, Vcl.ExtCtrls,
GLSkydome,
GLMirror,
GLScene,
GLObjects,
GLShadowPlane,
GLWin32Viewer,
GLCadencer,
GLTexture, GLParticleFX, GLVectorGeometry,
GLbehaviours, GLKeyboard, GLSpaceText,
GLColor, GLGui, GLMaterial, GLBitmapFont, GLWindows, GLHUDObjects,
GLRenderContextInfo, OpenGLTokens, GLCoordinates, GLCrossPlatform,
GLBaseClasses;
TYPE
TGameStatus = (gsLevelPreview, gsWarmup, gsPlaying, gsLevelWon, gsLevelLost);
TYPE
TForm1 = CLASS(TForm)
GLScene1: TGLScene;
Cadencer: TGLCadencer;
GLSceneViewer1: TGLSceneViewer;
GLCamera: TGLCamera;
CubeMapCamera: TGLCamera;
DCBoard: TGLDummyCube;
GLMaterialLibrary: TGLMaterialLibrary;
DCTable: TGLDummyCube;
Mirror: TGLMirror;
SPTable: TGLShadowplane;
GLDirectOpenGL1: TGLDirectOpenGL;
SelCube: TGLCube;
Timer1: TTimer;
DCInterface: TGLDummyCube;
GLSpaceText1: TGLSpaceText;
GLMemoryViewer1: TGLMemoryViewer;
GLPlane1: TGLPlane;
Panel1: TPanel;
Button2: TButton;
Button1: TButton;
PROCEDURE Button1Click(Sender: TObject);
PROCEDURE GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
PROCEDURE FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; VAR Handled: Boolean);
procedure GLDirectOpenGL1Render(VAR rci: TGLRenderContextInfo);
procedure CadencerProgress(Sender: TObject; CONST deltaTime,
newTime: Double);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure GenerateCubeMap;
public
pickstartx, pickstarty, speedrot: integer;
gameStatus: TGameStatus;
MirrorObj, cubeMapWarnDone: Boolean;
procedure glDraw(VAR rci: TGLRenderContextInfo);
procedure SetObjectMaterial(SceneObject: TGLBaseSceneObject; matindex: integer);
procedure SetBehavioursDamping(rc, rl, rq, sr, sp, st, tc, tl, tq, sx, sy, sz, mass: single);
procedure InitDamion;
procedure InitDamion3D;
function ModifieDamion(aff: boolean): boolean;
procedure selectdamion;
end;
const
Prof = 150;
pas_prof = 30;
TYPE
StructDamion = RECORD
etat: integer;
col: integer;
zeta: integer;
end;
TYPE
glcoord = RECORD
x, y, z: Single;
end;
CONST
TEXTURE_SPEED = 1 / 75;
VAR
Form1: TForm1;
Damion: ARRAY[0..4, 0..4] OF StructDamion;
cursx, cursy: integer;
Tunnels: ARRAY[0..32, 0..32] OF glcoord;
Angle: Single;
Speed: Single;
implementation
{$R *.DFM}
TYPE
TOutLineShader = CLASS(TGLShader)
private
BackgroundColor, LineColor: TColorVector;
OutlineSmooth, lighting: boolean;
OutlineWidth, oldlinewidth: single;
PassCount: Integer;
public
procedure DoApply(VAR rci: TGLRenderContextInfo; Sender: TObject); override;
function DoUnApply(VAR rci: TGLRenderContextInfo): Boolean; override;
end;
VAR
shader1: TOutlineShader;
procedure TOutLineShader.DoApply(VAR rci: TGLRenderContextInfo; Sender: TObject);
begin
PassCount := 1;
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
IF outlineSmooth then
begin
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
END
ELSE
glDisable(GL_LINE_SMOOTH);
glGetFloatv(GL_LINE_WIDTH, @oldlinewidth);
glLineWidth(OutLineWidth);
glPolygonMode(GL_BACK, GL_LINE);
//SetGLPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glCullFace(GL_FRONT);
glDepthFunc(GL_LEQUAL);
glColor3fv(@lineColor);
end;
function TOutLineShader.DoUnApply(VAR rci: TGLRenderContextInfo): Boolean;
begin
CASE PassCount OF
1:
begin
PassCount := 2;
IF lighting then
glEnable(GL_LIGHTING)
ELSE
glColor3fv(@backGroundColor);
glDepthFunc(GL_LESS);
glCullFace(GL_BACK);
//glEnable(GL_BLEND);
// glBlendFunc(GL_SRC_ALPHA,GL_SRC_ALPHA);
//glPolygonMode(GL_Back, GL_Fill);
// SetGLPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
Result := True;
end;
2:
begin
glPopAttrib;
glLineWidth(oldLineWidth);
Result := False;
end;
ELSE
Assert(False);
Result := False;
end;
end;
procedure Tform1.glDraw(VAR rci: TGLRenderContextInfo);
VAR
I, J: Integer;
C, J1, J2: Single;
begin
// GLTunnel FX From Jans Horn www.sulaco.co.za
glClear(GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
glTranslatef(0.0, 0.0, -30.0);
Angle := Angle + speed;
// setup tunnel coordinates
FOR I := 0 TO 24 DO
begin
FOR J := 0 TO 30 DO
begin
Tunnels[I, J].x := (24 - J / 12) * cos(2 * pi / 12 * I) + 2 * sin((Angle + 2 * j) / 24) + cos((Angle + 2 * j)
/ 10) - 2 * sin(Angle / 24) - cos(Angle / 10);
Tunnels[I, J].y := (24 - J / 12) * sin(2 * pi / 12 * I) + 2 * cos((Angle + 2 * j) / 29) + sin((Angle + 2 * j)
/ 14) - 2 * cos(Angle / 29) - sin(Angle / 14);
Tunnels[I, J].z := -(J - 10);
end;
end;
// draw tunnel
FOR J := 0 TO 30 DO
begin
J1 := J / 32 + Angle * TEXTURE_SPEED; // precalculate texture v coords for speed
J2 := (J + 1) / 32 + Angle * TEXTURE_SPEED;
// near the end of the tunnel, fade the effect away
IF J > 24 then
C := 1.0 - (J - 24) / 10
ELSE
C := 1.0;
glColor3f(C, C, C);
GLMaterialLibrary.ApplyMaterial('mat001', rci);
glbegin(GL_QUADS);
FOR I := 0 TO 11 DO
begin
glTexCoord2f((I - 3) / 12, J1); glVertex3f(Tunnels[I, J].X, Tunnels[I, J].Y, Tunnels[I, J].Z);
glTexCoord2f((I - 2) / 12, J1); glVertex3f(Tunnels[I + 1, J].X, Tunnels[I + 1, J].Y, Tunnels[I + 1, J].Z);
glTexCoord2f((I - 2) / 12, J2); glVertex3f(Tunnels[I + 1, J + 1].X, Tunnels[I + 1, J + 1].Y, Tunnels[I + 1, J
+ 1].Z);
glTexCoord2f((I - 3) / 12, J2); glVertex3f(Tunnels[I, J + 1].X, Tunnels[I, J + 1].Y, Tunnels[I, J + 1].Z);
end;
glEnd();
GLMaterialLibrary.UnApplyMaterial(rci);
end;
end;
procedure TForm1.SetObjectMaterial(SceneObject: TGLBaseSceneObject; matindex: integer);
VAR
obj : TGLCustomSceneObject;
begin
IF assigned(sceneobject) AND (matindex >= 0) then
begin
obj := TGLCustomSceneObject(sceneobject);
Obj.Material.MaterialLibrary := GLMaterialLibrary;
obj.Material.Assign(GLMaterialLibrary.Materials[matindex].Material);
end;
end;
//-- GAME CODE -----------------------------------------------------------------
procedure CaseBleu;
begin
IF (cursy > 0) then
damion[cursx, cursy - 1].etat := 1 - Damion[cursx, cursy - 1].etat
ELSE
damion[cursx, 4].etat := 1 - Damion[cursx, 4].etat;
end;
procedure CaseVerte;
begin
IF (cursx < 4) then
damion[cursx + 1, cursy].etat := 1 - Damion[cursx + 1, cursy].etat
ELSE
damion[0, cursy].etat := 1 - Damion[0, cursy].etat;
end;
procedure CaseRouge;
begin
IF (cursy < 4) then
damion[cursx, cursy + 1].etat := 1 - Damion[cursx, cursy + 1].etat
ELSE
damion[cursx, 0].etat := 1 - Damion[cursx, 0].etat;
end;
procedure CaseJaune;
begin
IF (cursx > 0) then
damion[cursx - 1, cursy].etat := 1 - Damion[cursx - 1, cursy].etat
ELSE
damion[4, cursy].etat := 1 - Damion[4, cursy].etat;
end;
function TForm1.ModifieDamion(aff: boolean): boolean;
VAR
i, j, z, c: integer;
begin
damion[cursx, cursy].etat := 1 - damion[cursx, cursy].etat;
CASE damion[cursx, cursy].col OF
0: caseBleu;
1: caseVerte;
2: caseRouge;
3: caseJaune;
4:
begin
casebleu;
caseverte;
caserouge;
casejaune;
end;
end;
z := 0;
WHILE (z < prof) DO
begin
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
IF ((damion[i, j].etat = 1) AND (damion[i, j].zeta <> prof)) then
damion[i, j].zeta := damion[i, j].zeta + pas_prof;
IF ((damion[i, j].etat = 0) AND (damion[i, j].zeta = prof)) then
damion[i, j].zeta := damion[i, j].zeta - pas_prof;
end;
end;
z := z + pas_prof;
end;
IF aff then
begin
c := -1;
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
inc(c);
dcboard.Children[1 + c].Position.y := ((damion[i, j].zeta) / 50);
end;
end;
end;
result := true;
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
IF (damion[i, j].etat = 0) then
begin
result := false;
break;
end;
continue;
end;
IF result = false then break;
end;
end;
procedure TForm1.InitDamion;
VAR
k, cx, cy, i, j: integer;
begin
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
Damion[i, j].etat := 0;
Damion[i, j].zeta := 0;
k := random(5);
damion[i, j].col := k;
end;
end;
cx := random(5);
cy := random(5);
FOR j := 0 TO 4 DO
begin
cursy := j;
FOR i := 0 TO 4 DO
begin
cursx := i;
IF ((cursx <> cx) OR (cursy <> cy)) then modifieDamion(true);
end;
end;
cursx := cx;
cursy := cy;
end;
procedure TForm1.selectdamion;
VAR
tempmaterial: tglmaterial;
begin
Selcube.Position.x := dcboard.Children[1 + (cursx) + (cursy * 5)].Position.x;
Selcube.Position.y := dcboard.Children[1 + (cursx) + (cursy * 5)].Position.y;
Selcube.Position.z := dcboard.Children[1 + (cursx) + (cursy * 5)].Position.z;
tempmaterial := tglmaterial.create(self);
CASE damion[cursx, cursy].col OF
0: tempmaterial.FrontProperties.Diffuse.AsWinColor := clBlue;
1: tempmaterial.FrontProperties.Diffuse.AsWinColor := clGreen;
2: tempmaterial.FrontProperties.Diffuse.AsWinColor := clRed;
3: tempmaterial.FrontProperties.Diffuse.AsWinColor := clyellow;
4: tempmaterial.FrontProperties.Diffuse.AsWinColor := clFuchsia;
end;
tempmaterial.FrontProperties.Diffuse.Alpha := 0.4;
tempmaterial.BackProperties.Diffuse := tempmaterial.FrontProperties.Diffuse;
WITH shader1 DO
begin
CASE (dcboard.Children[1 + (cursx + 1) * (cursy + 1)] AS TGLCube).tag OF
0: BackgroundColor := convertwincolor(clBlue, 0.2);
1: BackgroundColor := convertwincolor(clGreen, 0.2);
2: BackgroundColor := convertwincolor(clRed, 0.2);
3: BackgroundColor := convertwincolor(clyellow, 0.2);
4: BackgroundColor := convertwincolor(clFuchsia, 0.2);
end;
Outlinesmooth := true;
OutLineWidth := 2;
lighting := True;
LineColor := clrWhite;
end;
glmateriallibrary.Materials[7].Shader := NIL;
glmateriallibrary.Materials[7].Material.Assign(tempmaterial);
glmateriallibrary.Materials[7].Shader := shader1;
end;
procedure TForm1.InitDamion3D;
VAR
i, j, n: integer;
AObject: TGLBaseSceneObject;
x, y, z: single;
begin
n := -1;
y := 1.5;
z := 3.0;
speedrot := 6;
FOR j := 0 TO 4 DO
begin
IF j > 0 then z := z - 1.5;
x := -3.0;
FOR i := 0 TO 4 DO
begin
inc(n);
IF i > 0 then x := x + 1.5;
AObject := TGLCube.Create(self);
AObject.Direction.x := 0;
AObject.Direction.y := 1;
AObject.Direction.z := 0;
AObject.up.x := 0;
AObject.up.y := 0;
AObject.up.z := -1;
AObject.Position.x := x;
AObject.Position.y := y;
AObject.Position.z := z;
AObject.Name := 'Cube' + inttostr(n);
AObject.Tag := Damion[i, j].col;
SetObjectMaterial(AObject, 0);
DCBoard.AddChild(AOBject);
end;
end;
GLSceneviewer1.Camera.TargetObject := DCBoard.Children[13];
randomize;
initDamion;
shader1 := TOutLineShader.Create(Self);
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
CASE Damion[i, j].col OF
0: setobjectmaterial(dcboard.Children[1 + i + j * 5], 1);
1: setobjectmaterial(dcboard.Children[1 + i + j * 5], 2);
2: setobjectmaterial(dcboard.Children[1 + i + j * 5], 3);
3: setobjectmaterial(dcboard.Children[1 + i + j * 5], 4);
4: setobjectmaterial(dcboard.Children[1 + i + j * 5], 5);
end;
end;
end;
selectdamion;
// glscene1.SaveToFile('damion.gls');
end;
procedure TForm1.Button1Click(Sender: TObject);
VAR
i, j, n: integer;
begin
randomize;
initDamion;
n := -1;
FOR j := 0 TO 4 DO
begin
FOR i := 0 TO 4 DO
begin
inc(n);
CASE Damion[i, j].col OF
0: setobjectmaterial(dcboard.Children[n + 1], 1);
1: setobjectmaterial(dcboard.Children[n + 1], 2);
2: setobjectmaterial(dcboard.Children[n + 1], 3);
3: setobjectmaterial(dcboard.Children[n + 1], 4);
4: setobjectmaterial(dcboard.Children[n + 1], 5);
end;
end;
end;
Form1.FocusControl(glsceneviewer1);
selectdamion;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
IF (ssRight IN Shift) then
begin
IF GLScene1.CurrentGLCamera.TargetObject <> NIL then
begin
// Rotate around Object
GLScene1.CurrentGLCamera.MoveAroundTarget((y - pickstarty), (x - pickstartx));
end;
end;
PickStartX := x;
PickStartY := y;
glsceneviewer1.Invalidate;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; VAR Handled: Boolean);
begin
GLSceneViewer1.Camera.AdjustDistanceToTarget(Power(1.005, WheelDelta / 120));
end;
procedure TForm1.GLDirectOpenGL1Render(VAR rci: TGLRenderContextInfo);
begin
//glDisable(GL_CULL_FACE);
glDraw(rci);
//glEnable(GL_CULL_FACE);
end;
procedure TForm1.GenerateCubeMap;
//var tmp : tglmaterial;
begin
// Don't do anything if cube maps aren't supported
IF GL_TEXTURE_CUBE_MAP_ARB <> 0 then
begin
IF NOT cubeMapWarnDone then
ShowMessage('Your graphics board does not support cube maps...');
cubeMapWarnDone := True;
Exit;
end;
// Here we generate the new cube map, from CubeMapCamera (a child of the
WITH GLPlane1 DO
begin
GLDirectOpenGL1.Visible := false;
DCInterface.Visible := false;
SPTable.Visible := false;
Visible := False;
glmemoryviewer1.Render;
GLMemoryViewer1.CopyToTexture(material.Texture, 0, 0, 512, 512, 0, 0);
Material.Texture.Disabled := False;
GLDirectOpenGL1.Visible := True;
Visible := True;
SPTable.Visible := True;
DCInterface.Visible := True;
end;
end;
procedure TForm1.SetBehavioursDamping(rc, rl, rq, sr, sp, st, tc, tl, tq, sx, sy, sz, mass: single);
begin
GetOrCreateInertia(DCBoard.Behaviours).RotationDamping.SetDamping(rc, rl, rq);
GetOrCreateInertia(DCBoard).Mass := mass;
GetOrCreateInertia(DCBoard).Turnspeed := st;
GetOrCreateInertia(DCBoard).RollSpeed := sr;
GetOrCreateInertia(DCBoard).PitchSpeed := sp;
GetOrCreateInertia(DCBoard).TranslationDamping.SetDamping(tc, tl, tq);
GetOrCreateInertia(DCBoard).TranslationSpeed.SetVector(sx, sy, sz);
GetOrCreateInertia(DCBoard).DampingEnabled := true;
end;
procedure TForm1.CadencerProgress(Sender: TObject; CONST deltaTime,
newTime: Double);
VAR
mx, my: integer;
begin
IF GameStatus = gsPlaying then
begin
button1.Enabled := false;
IF isKeydown(VK_DOWN) then
IF cursy < 4 then inc(cursy);
IF isKeydown(VK_UP) then
IF cursy > 0 then dec(cursy);
IF isKeydown(VK_LEFT) then
IF cursx > 0 then dec(cursx);
IF isKeydown(VK_RIGHT) then
IF cursx < 4 then inc(cursx);
IF iskeydown(vk_space) then modifiedamion(true);
selectdamion;
END
ELSE
IF GameStatus = gsLevelPreview then
begin
// if behaviour is created, comment the next line (see setbehaviour... in FormCreate)
dcboard.TurnAngle := dcboard.TurnAngle + (10 * deltatime);
//dcboard.TransformationChanged;
//Mirror.TransformationChanged;
GLSpacetext1.TurnAngle := GLSpacetext1.TurnAngle + (-15 * deltatime);
IF ISKeyDown(VK_Space) then Gamestatus := gsPlaying;
end;
IF NOT (mirrorobj) then GenerateCubeMap;
glsceneviewer1.Invalidate;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption := 'Damion : ' + Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]) + ' - ' + inttostr(cursx) + ' - ' +
inttostr(cursy);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Speed := 4;
Angle := 0;
cursx := 0;
cursy := 0;
GameStatus := gsLevelPreview;
InitDamion3d;
Mirrorobj := true;
//SetBehavioursDamping(0,0,0,0,0,10,0,0,0,0,0,0,1);
cadencer.Enabled := true;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
IF mirrorobj then
begin
glplane1.visible := true;
mirror.Visible := false;
mirrorobj := false;
END
ELSE
begin
glplane1.visible := False;
mirror.Visible := True;
mirrorobj := True;
end;
GLSceneViewer1.Invalidate;
end;
END.
|
unit BCEditor.Utils;
interface
uses
Winapi.Windows, System.Math, System.Classes, Vcl.Graphics, System.UITypes, BCEditor.Consts, BCEditor.Types;
function CeilOfIntDiv(ADividend: Cardinal; ADivisor: Word): Word;
function DeleteWhitespace(const AText: string): string;
function GetTabConvertProc(ATabWidth: Integer): TBCEditorTabConvertProc;
function GetTextSize(AHandle: HDC; AText: PChar; ACount: Integer): TSize;
function MessageDialog(const AMessage: string; ADlgType: TMsgDlgType; AButtons: TMsgDlgButtons): Integer;
function MinMax(AValue, AMinValue, AMaxValue: Integer): Integer;
function TextExtent(ACanvas: TCanvas; const AText: string): TSize;
function TextWidth(ACanvas: TCanvas; const AText: string): Integer;
function TextHeight(ACanvas: TCanvas; const AText: string): Integer;
procedure ClearList(var AList: TList);
procedure FreeList(var AList: TList);
implementation
uses
Vcl.Forms, Vcl.Dialogs, System.SysUtils, System.Character;
procedure FreeList(var AList: TList);
begin
ClearList(AList);
if Assigned(AList) then
begin
AList.Free;
AList := nil;
end;
end;
function CeilOfIntDiv(ADividend: Cardinal; ADivisor: Word): Word;
var
LRemainder: Word;
begin
DivMod(ADividend, ADivisor, Result, LRemainder);
if LRemainder > 0 then
Inc(Result);
end;
procedure ClearList(var AList: TList);
var
i: Integer;
begin
if not Assigned(AList) then
Exit;
for i := 0 to AList.Count - 1 do
if Assigned(AList[i]) then
begin
TObject(AList[i]).Free;
AList[i] := nil;
end;
AList.Clear;
end;
function DeleteWhitespace(const AText: string): string;
var
i, j: Integer;
begin
SetLength(Result, Length(AText));
j := 0;
for i := 1 to Length(AText) do
if not AText[i].IsWhiteSpace then
begin
Inc(j);
Result[j] := AText[i];
end;
SetLength(Result, j);
end;
function MessageDialog(const AMessage: string; ADlgType: TMsgDlgType; AButtons: TMsgDlgButtons): Integer;
begin
with CreateMessageDialog(AMessage, ADlgType, AButtons) do
try
HelpContext := 0;
HelpFile := '';
Position := poMainFormCenter;
Result := ShowModal;
finally
Free;
end;
end;
function MinMax(AValue, AMinValue, AMaxValue: Integer): Integer;
begin
AValue := Min(AValue, AMaxValue);
Result := Max(AValue, AMinValue);
end;
function GetHasTabs(ALine: PChar; var ACharsBefore: Integer): Boolean;
begin
Result := False;
ACharsBefore := 0;
if Assigned(ALine) then
begin
while ALine^ <> BCEDITOR_NONE_CHAR do
begin
if ALine^ = BCEDITOR_TAB_CHAR then
Exit(True);
Inc(ACharsBefore);
Inc(ALine);
end;
end
end;
function ConvertTabs(const ALine: string; ATabWidth: Integer; var AHasTabs: Boolean): string;
var
PSource: PChar;
begin
AHasTabs := False;
Result := '';
PSource := PChar(ALine);
while PSource^ <> BCEDITOR_NONE_CHAR do
begin
if PSource^ = BCEDITOR_TAB_CHAR then
begin
AHasTabs := True;
Result := Result + StringOfChar(BCEDITOR_SPACE_CHAR, ATabWidth);
end
else
Result := Result + PSource^;
Inc(PSource);
end;
end;
function GetTabConvertProc(ATabWidth: Integer): TBCEditorTabConvertProc;
begin
Result := TBCEditorTabConvertProc(@ConvertTabs);
end;
function GetTextSize(AHandle: HDC; AText: PChar; ACount: Integer): TSize;
begin
Result.cx := 0;
Result.cy := 0;
GetTextExtentPoint32W(AHandle, AText, ACount, Result);
end;
type
TAccessCanvas = class(TCanvas);
function TextExtent(ACanvas: TCanvas; const AText: string): TSize;
begin
with TAccessCanvas(ACanvas) do
begin
RequiredState([csHandleValid, csFontValid]);
Result := GetTextSize(Handle, PChar(AText), Length(AText));
end;
end;
function TextWidth(ACanvas: TCanvas; const AText: string): Integer;
begin
Result := TextExtent(ACanvas, AText).cx;
end;
function TextHeight(ACanvas: TCanvas; const AText: string): Integer;
begin
Result := TextExtent(ACanvas, AText).cy;
end;
end.
|
unit fTextBlocks;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.UITypes,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.CheckLst,
Vcl.Buttons,
Vcl.ExtCtrls,
uGlobal;
type
TTextBlocksForm = class(TForm)
RichEdit: TRichEdit;
BlockListBox: TCheckListBox;
ApplyBitBtn: TBitBtn;
BitBtn1: TBitBtn;
Label2: TLabel;
EditLeft: TEdit;
EditTop: TEdit;
Label3: TLabel;
EditLineHeight: TEdit;
UpDown1: TUpDown;
ColorButton: TSpeedButton;
ColorPanel: TPanel;
FontButton: TSpeedButton;
Label1: TLabel;
AddButton: TSpeedButton;
DeleteButton: TSpeedButton;
UpButton: TSpeedButton;
DownButton: TSpeedButton;
EditCaption: TEdit;
FontDialog: TFontDialog;
ColorDialog: TColorDialog;
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FloatKeyPress(Sender: TObject; var Key: Char);
procedure IntKeyPress(Sender: TObject; var Key: Char);
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditLeftKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditTopKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditCaptionKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure IntKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure LineHeightChange(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure ApplyBitBtnClick(Sender: TObject);
procedure FontButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure BlockListBoxClick(Sender: TObject);
procedure ColorPanelClick(Sender: TObject);
procedure RichEditChange(Sender: TObject);
procedure BlockListBoxClickCheck(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure UpButtonClick(Sender: TObject);
procedure DownButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
TextData: TTextData;
function DefaultData: TTextData;
procedure UpdateTextLines;
public
procedure ClearTextBlocks;
procedure UpdateRichLines;
procedure ShowData(Sender: TObject);
end;
var
TextBlocksForm: TTextBlocksForm;
const
yIncFactor = 1.65;
//=====================================================================
implementation
//=====================================================================
uses
fMain;
{$R *.dfm}
procedure TTextBlocksForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if ApplyBitBtn.Visible then
begin
case MessageDlg('The current data has been altered.'+
#13#10'To save the change press the Apply Change Button.'+
#13#10'Do you wish to save the alterations ?', mtConfirmation,
[mbYes, mbNo], 0) of
mrYes: CanClose := False;
end;
end;
end;
procedure TTextBlocksForm.FormDestroy(Sender: TObject);
var
i: integer;
begin
for i := 0 to BlocklistBox.Count - 1
do BlockListBox.Items.Objects[i].Free;
RichEdit.Clear;
end;
procedure TTextBlocksForm.FormShow(Sender: TObject);
begin
Caption := GraphFName;
if BlockListBox.Count = 0 then TextData := DefaultData
else
begin
UpdateRichLines;
ColorPanel.Color := RichEdit.DefAttributes.Color;
with BlockListBox do
TextData := TTextDataObject(Items.Objects[ItemIndex]).Data;
with FontDialog.Font, TextData do
begin
Name := FontName;
Size := FontSize;
Style := FontStyle;
Color := ColorPanel.Color;
end;
end;
ShowData(Sender);
end;
procedure TTextBlocksForm.FloatKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['-', '0'..'9', '.', 'e', 'E', #8]) then Key := #0
else if Active then ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
procedure TTextBlocksForm.IntKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['0'..'9', #8]) then Key := #0
else ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
procedure TTextBlocksForm.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_DELETE) or (Key = VK_BACK)
then ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
procedure TTextBlocksForm.EditLeftKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with TextData do
try
xLoc := StrToFloat(EditLeft.Text);
except
if GraphData.Grid.xAxisStyle = asLog then xLoc := 0.1 else xLoc := -0.1;
end;
with BlockListBox do
TTextDataObject(Items.Objects[ItemIndex]).Data.xLoc := TextData.xLoc;
ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
procedure TTextBlocksForm.EditTopKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with TextData do
try
yLoc := StrToFloat(EditTop.Text);
except
if GraphData.Grid.yAxisStyle = asLog then yLoc := 0.1 else yLoc := -0.1;
end;
with BlockListBox do
TTextDataObject(Items.Objects[ItemIndex]).Data.yLoc := TextData.yLoc;
ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
procedure TTextBlocksForm.EditCaptionKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
with BlockListBox do
begin
TTextDataObject(Items.Objects[ItemIndex]).Data.Caption := EditCaption.Text;
Items[ItemIndex] := EditCaption.Text;
end;
end;
procedure TTextBlocksForm.RichEditChange(Sender: TObject);
begin
if Active then
begin
ApplyBitBtn.Visible := (BlockListBox.Count > 0) and
(TTextDataObject(BlockListBox.Items.Objects[BlockListBox.ItemIndex]).
TextLines.Count > 0) and (RichEdit.Lines.Count > 0);
end;
end;
procedure TTextBlocksForm.IntKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Active then
begin
with Sender as TEdit do
try
TextData.yInc := StrToInt(Text);
except
TextData.yInc := round(TextData.FontSize*yIncFactor);
end;
with BlockListBox do
TTextDataObject(Items.Objects[ItemIndex]).Data.yInc := TextData.yInc;
ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
end;
procedure TTextBlocksForm.LineHeightChange(Sender: TObject);
var
k: word;
begin
if Active then
begin
k := 0;
IntKeyUp(Sender, k, []);
end;
end;
procedure TTextBlocksForm.BitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure TTextBlocksForm.ApplyBitBtnClick(Sender: TObject);
begin
UpdateTextLines;
Altered := True;
MainForm.GLViewer.Invalidate;
ApplyBitBtn.Visible := False;
end;
procedure TTextBlocksForm.FontButtonClick(Sender: TObject);
var
Cpos: integer;
i: integer;
begin
if RichEdit.Lines.Count = 0 then RichEdit.Lines.Add('Sample text.');
UpdateTextLines;
Cpos := RichEdit.SelStart;
if FontDialog.Execute then
begin
with TextData, FontDialog.Font do
begin
FontName := Name;
FontStyle := Style;
FontSize := Size;
FontColor := Color;
yInc := round(FontSize*yIncFactor);
ColorPanel.Color := FontColor;
UpDown1.Position := yInc;
end;
with FontDialog,
TTextDataObject(BlockListBox.Items.Objects[BlockListBox.ItemIndex]) do
begin
with Data do
begin
FontName := Font.Name;
FontStyle := Font.Style;
FontSize := Font.Size;
FontColor := Font.Color;
yInc := round(FontSize*yIncFactor);
with RichEdit do if Lines.Count > 0 then
begin
UpdateTextLines;
TextLines.Clear;
for i := 0 to Lines.Count -1
do TextLines.Add(TTextLineObject.Create(Lines[i], FontColor));
Lines.Clear;
with DefAttributes do
begin
Name := FontName;
Style := FontStyle;
Size := FontSize;
Color := FontColor;
end;
for i := 0 to TextLines.Count -1 do
with TTextLineObject(TextLines[i]) do Lines.Add(Text);
end;
end;
end;
RichEdit.SelStart := Cpos;
ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
end;
procedure TTextBlocksForm.AddButtonClick(Sender: TObject);
begin
with BlockListBox do
begin
if Count = 0 then TextData := DefaultData
else TextData := TTextDataObject(Items.Objects[ItemIndex]).Data;
with FontDialog.Font, TextData do
begin
Name := FontName;
Size := FontSize;
Style := FontStyle;
Color := FontColor;
end;
with TextData do Caption := 'Text Block';
AddItem(TextData.Caption, TTextDataObject.Create(TextData));
ItemIndex := Count -1;
Checked[ItemIndex] := True;
RichEdit.Clear;
end;
ShowData(Sender);
EditCaption.SetFocus;
FontButtonClick(Sender);
end;
procedure TTextBlocksForm.BlockListBoxClick(Sender: TObject);
begin
with BlockListBox do
TextData := TTextDataObject(Items.Objects[ItemIndex]).Data;
with FontDialog.Font, TextData do
begin
Name := FontName;
Size := FontSize;
Style := FontStyle;
Color := FontColor;
ColorPanel.Color := Color;
end;
UpdateRichLines;
ShowData(Sender);
end;
procedure TTextBlocksForm.BlockListBoxClickCheck(Sender: TObject);
begin
ApplyBitBtn.Visible := True;
end;
procedure TTextBlocksForm.ColorPanelClick(Sender: TObject);
var
Cpos: integer;
idx: cardinal;
s: string;
begin
with RichEdit do
begin
if Lines.Count = 0 then
begin
Lines.Add('Sample text.');
UpdateTextLines;
SelStart := 1;
end;
Cpos := SelStart;
if ActiveLineNo >= cardinal(Lines.Count) then SelStart := Length(Text) -1;
end;
MainForm.StatusBar.Panels[2].Text := '';
ColorDialog.Color := ColorPanel.Color;
if ColorDialog.Execute then
begin
ColorPanel.Color := ColorDialog.Color;
with RichEdit do
begin
Idx := ActiveLineNo;
s := Lines[Idx];
Lines.Delete(Idx);
SelAttributes.Color := ColorPanel.Color;
Lines.Insert(Idx, s);
end;
end;
RichEdit.SelStart := cPos;
ApplyBitBtn.Visible := RichEdit.Lines.Count > 0;
end;
function TTextBlocksForm.DefaultData: TTextData;
begin
with Result do
begin
Caption := 'Text Block #';
xLoc := 0.0;
yLoc := 0.0;
FontName := 'Tahoma';
FontStyle := [];
FontSize := 12;
FontColor := clBlack;
yInc := round(FontSize*yIncFactor);
end;
end;
procedure TTextBlocksForm.DeleteButtonClick(Sender: TObject);
var
i: integer;
begin
if BlockListBox.Count > 0 then
begin
RichEdit.Clear;
with BlockListBox do
begin
i := ItemIndex;
with Items.Objects[i] as TTextDataObject do Free;
Items.Delete(i);
if i > Count -1 then i := Count -1;
ItemIndex := i;
DeleteButton.Enabled := Count > 0;
end;
if BlockListBox.Count > 0 then BlockListBoxClick(Sender);
ApplyBitBtn.Visible := True;
end;
end;
procedure TTextBlocksForm.DownButtonClick(Sender: TObject);
var
i: integer;
begin
with BlockListBox do
begin
i := ItemIndex;
if i < Count -1 then Items.Move(i, i+1);
ItemIndex := i+1;
end;
BlockListBoxClick(Sender);
end;
procedure TTextBlocksForm.ShowData(Sender: TObject);
var
a: Boolean;
begin
{ if BlockListBox.Count = 0 then disable all except AddButton }
a := Altered;
RichEdit.Color := GraphData.BackColor;
DeleteButton.Enabled := BlockListBox.Count > 0;
UpButton.Enabled := DeleteButton.Enabled and (BlockListBox.Count > 1);
DownButton.Enabled := DeleteButton.Enabled and (BlockListBox.Count > 1);
FontButton.Enabled := DeleteButton.Enabled;
BlockListBox.Enabled := DeleteButton.Enabled;
EditCaption.Enabled := DeleteButton.Enabled;
EditLeft.Enabled := DeleteButton.Enabled;
EditTop.Enabled := DeleteButton.Enabled;
EditLineHeight.Enabled := DeleteButton.Enabled;
upDown1.Enabled := DeleteButton.Enabled;
ColorButton.Enabled := DeleteButton.Enabled;
ColorPanel.Enabled := DeleteButton.Enabled;
RichEdit.Enabled := DeleteButton.Enabled;
ApplyBitBtn.Visible := Active and (Sender.ClassName <> 'TSpeedButton') and
(RichEdit.Lines.Count > 0);
with BlockListBox do if Count > 0 then
begin;
with TTextDataObject(Items.Objects[ItemIndex]).Data do
begin
EditCaption.Text := Caption;
EditLeft.Text := FloatToStrF(xLoc, ffGeneral, 4, 3);
EditTop.Text := FloatToStrF(yLoc, ffGeneral, 4, 3);
EditLineHeight.Text := IntToStr(yInc);
with RichEdit, TTextDataObject(Items.Objects[ItemIndex]) do
if (Lines.Count > 1) and (ActiveLineNo < cardinal(Lines.Count))
then ColorDialog.Color := TTextLineObject(TextLines[ActiveLineNo]).Color;
end;
end;
Altered := a;
end;
procedure TTextBlocksForm.UpButtonClick(Sender: TObject);
var
i: integer;
begin
with BlockListBox do
begin
i := ItemIndex;
if i > 0 then Items.Move(i, i-1);
if i > 1 then ItemIndex := i-1 else ItemIndex := 0;
end;
BlockListBoxClick(Sender);
end;
procedure TTextBlocksForm.UpdateTextLines;
var
i: integer;
begin
with BlockListBox, TTextDataObject(Items.Objects[ItemIndex]) do
begin
for i := 0 to TextLines.Count -1 do
begin
TTextLineObject(TextLines.Items[i]).Free;
end;
TextLines.Clear;
end;
RichEdit.SelStart := 0;
with BlockListBox, TTextDataObject(Items.Objects[ItemIndex]) do
for i := 0 to RichEdit.Lines.Count -1 do
begin
TextLines.Add(TTextLineObject.Create(RichEdit.Lines[i],
RichEdit.SelAttributes.Color));
RichEdit.SelStart := RichEdit.SelStart + Length(RichEdit.Lines[i]) +1;
end;
end;
procedure TTextBlocksForm.UpdateRichLines;
var
i: integer;
begin
with TTextDataObject(BlockListBox.Items.Objects[BlockListBox.ItemIndex]) do
begin
with RichEdit.DefAttributes do
begin
Name := Data.FontName;
Style := Data.FontStyle;
Size := Data.FontSize;
Color := Data.FontColor;
end;
with RichEdit do
begin
Lines.Clear;
for i := 0 to TextLines.Count -1 do
with TTextLineObject(TextLines.Items[i]) do
begin
SelAttributes.Color := Color;
Lines.Add(Text);
end;
end;
end;
end;
procedure TTextBlocksForm.ClearTextBlocks;
var
i: integer;
begin
with BlockListBox do
begin
for i := 0 to Count -1 do Items.Objects[i].Free;
Clear;
end;
RichEdit.Clear;
end;
end.
|
unit XED.SyntaxEnum;
{$Z4}
interface
type
TXED_Syntax_Enum = (
XED_SYNTAX_INVALID,
XED_SYNTAX_XED, ///< XED disassembly syntax
XED_SYNTAX_ATT, ///< ATT SYSV disassembly syntax
XED_SYNTAX_INTEL, ///< Intel disassembly syntax
XED_SYNTAX_LAST);
/// This converts strings to #xed_operand_action_enum_t types.
/// @param s A C-string.
/// @return #xed_operand_action_enum_t
/// @ingroup ENUM
function str2xed_syntax_enum_t(s: PAnsiChar): TXED_Syntax_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_operand_action_enum_t types.
/// @param p An enumeration element of type xed_operand_action_enum_t.
/// @return string
/// @ingroup ENUM
function xed_syntax_enum_t2str(const p: TXED_Syntax_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_operand_action_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_syntax_enum_t_last:TXED_Syntax_Enum;cdecl; external 'xed.dll';
implementation
end.
|
unit MySqlLib;
interface
uses
AccessLib, Uni, Dialogs, BaseServerLib, Classes,Base;
type
MySqlBase = class(TBaseServer)
private
protected
public
UniQueryForShow: TUniQuery;
UniQueryForOp: TUniQuery;
procedure Search(TSQL: string);
function GetItemsFromTable(TSQL, FiledName: string): TStrings;
function GetOneResult(TSQL, FiledName:String): string;
function GetItemsArrFromTable(TSQL: string; Fileds: array of string): TItemsArr;
function ExcuteSql(TSQL:String):Boolean;
constructor Create(PUniConnection: TUniConnection); overload;
destructor Destroy; override;
end;
implementation
function MySqlBase.ExcuteSql(TSQL:String):Boolean;
begin
try
with UniQueryForOP do
begin
Close;
SQL.Clear;
SQL.Add(TSQL);
ExecSQL;
end;
except
ShowErrorMessage('连接数据库出错,请检查'#13'1:网络连接'#13'2:数据库所在地址、端口是否正确');
end;
end;
constructor MySqlBase.Create(PUniConnection: TUniConnection);
begin
inherited Create;
UniQueryForShow := TUniQuery.Create(nil);
UniQueryForShow.Connection := PUniConnection;
UniQueryForOp := TUniQuery.Create(nil);
UniQueryForOp.Connection := PUniConnection;
end;
destructor MySqlBase.Destroy;
begin
try
UniQueryForOp.Close;
UniQueryForOp.Destroy;
UniQueryForShow.Close;
UniQueryForShow.Destroy;
except
ShowErrorMessage('关闭数据库时出错');
end;
end;
procedure MySqlBase.Search(TSQL: string);
begin
try
with UniQueryForShow do
begin
Close;
SQL.Clear;
SQL.Add(TSQL);
ExecSQL;
end;
except
ShowErrorMessage('连接数据库出错,请检查'#13'1:网络连接'#13'2:数据库所在地址、端口是否正确');
end;
end;
function MySqlBase.GetItemsFromTable(TSQL, FiledName: string): TStrings;
var
TS: TStrings;
begin
try
TS := TStringList.Create;
with UniQueryForOp do
begin
Close;
SQL.Clear;
SQL.Add(TSQL);
ExecSQL;
while not Eof do
begin
TS.Add(FieldByName(FiledName).AsString);
Next;
end;
Close;
end;
except
end;
Result := TS;
end;
function MySqlBase.GetOneResult(TSQL, FiledName:String): string;
var
TS: String;
begin
try
with UniQueryForOp do
begin
Close;
SQL.Clear;
SQL.Add(TSQL);
ExecSQL;
while not Eof do
begin
TS := (FieldByName(FiledName).AsString);
Next;
end;
Close;
end;
except
end;
Result := TS;
end;
function MySqlBase.GetItemsArrFromTable(TSQL: string; Fileds: array of string): TItemsArr;
var
ItemsArr: TItemsArr;
I: Integer;
begin
try
SetLength(ItemsArr, Length(Fileds));
for I := 0 to Length(Fileds) - 1 do
ItemsArr[I] := TStringList.Create;
with UniQueryForOp do
begin
Close;
SQL.Clear;
SQL.Add(TSQL);
ExecSQL;
while not Eof do
begin
for I := 0 to Length(Fileds) - 1 do
ItemsArr[I].Add(FieldByName(Fileds[I]).AsString);
Next;
end;
Close;
end;
except
end;
Result := ItemsArr;
end;
end.
|
unit Card.Main;
interface
{-$DEFINE SOLVER}
uses
ECMA.TypedArray, W3C.DOM4, W3C.HTML5, W3C.WebAudio, Card.Framework,
Card.Cards, Card.Confetti;
type
TTopButton = class(TButtonElement);
TCardTargetCanvas = class(TCanvas2DElement)
private
FCardColor: TCardColor;
FPixelRatio: Float;
public
constructor Create(Owner: IHtmlElementOwner; CardColor: TCardColor); overload;
procedure Resize;
procedure Paint;
property CardColor: TCardColor read FCardColor;
end;
TCardTarget = class(TDivElement)
private
FCanvasElement: TCardTargetCanvas;
public
constructor Create(Owner: IHtmlElementOwner; CardColor: TCardColor); overload;
property CanvasElement: TCardTargetCanvas read FCanvasElement;
end;
TPark = class
private
FCards: TArrayOfCard;
protected
procedure UpdatePositions(LargeAdvance: Float); virtual; abstract;
public
constructor Create; virtual;
property Cards: TArrayOfCard read FCards;
property Position: TVector2f;
end;
TPile = class(TPark)
public
procedure UpdatePositions(LargeAdvance: Float); override;
end;
TDeck = class(TPark)
private
FTinyOffsets: array [TCardValue] of Float;
public
constructor Create; override;
procedure UpdatePositions(LargeAdvance: Float); override;
property CardTarget: TCardTarget;
end;
TPiles = array [0..7] of TPile;
TDecks = array [TCardColor] of TDeck;
(*
TModalButton = class(TButtonElement);
TModalContent = class(TDivElement)
private
FHeading: TH1Element;
FButton: TModalButton;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
end;
TModalDialog = class(TDivElement)
private
FContent: TModalContent;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
procedure Show;
procedure Hide;
end;
*)
TMainScreen = class(TDivElement)
private
FBackgroundHeader: TH1Element;
FSolvable: TH5Element;
FButtonNew: TTopButton;
FButtonRetry: TTopButton;
FButtonUndo: TTopButton;
//FButtonSelect: TTopButton;
FButtonFinish: TTopButton;
{$IFDEF SOLVER}
FButtonSolve: TTopButton;
FLabel: TParagraphElement;
{$ENDIF}
FCards: TArrayOfCard;
FCurrentCards: TArrayOfCard;
FCurrentPark: TPark;
FPreviousOldPark: TPark;
FPreviousNewPark: TPark;
FPreviousCards: TArrayOfCard;
FHighlightCard: TCard;
FHintCards: array of TCard;
FPiles: TPiles;
FDecks: TDecks;
FOffset: TVector2f;
FDown: Boolean;
FCardWidth: Float;
FCardHeight: Float;
FCardUnderCursor: TCard;
FLargeAdvance: Float;
FTimeOut: Integer;
//FModalDialog: TModalDialog;
FCurrentSeed: Integer;
FConfetti: TConfetti;
FHashList: array of Integer;
FSeedIndex: Integer;
procedure MouseDownEventHandler(Event: JEvent);
procedure MouseMoveEventHandler(Event: JEvent);
procedure MouseUpEventHandler(Event: JEvent);
procedure TouchStartEventHandler(Event: JEvent);
procedure TouchMoveEventHandler(Event: JEvent);
procedure TouchEndEventHandler(Event: JEvent);
protected
procedure TouchMouseDown(Position: TVector2f);
procedure TouchMouseMove(Position: TVector2f);
procedure TouchMouseUp(Position: TVector2f);
function GetClosestPile: TPark;
function GetDeck: TPark;
function CheckDone: Boolean;
procedure ShowMouseHint;
procedure ResetHintCards;
function LocateTargets(Card: TCard): array of TPark;
function LocateCardUnderCursor(Position: TVector2f): TCard;
function FinishOneCard: Boolean;
{$IFDEF SOLVER}
function GetParkForCard(Card: TCard): TPark;
function GetPilePriority: array of Integer;
function GetPossibleCards(OnlyUseful: Boolean = False): TArrayOfCard;
function GetConcealedHeight(Pile: TPile): Integer;
procedure Solve;
function FindFirstNonConcealed(Pile: TPile): TCard;
function FindFirstNonConcealedIndex(Pile: TPile): Integer;
function UnveilConcealed: Boolean;
function CalculateHash: Integer;
function RandomMove: Boolean;
{$ENDIF}
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
procedure Resize(Event: JEvent);
procedure Shuffle(RandomSeed: Integer = 0);
procedure Retry;
procedure Select;
procedure Undo;
procedure ClearUndo;
procedure Finish;
end;
var
MainScreen: TMainScreen;
implementation
uses
ECMA.Date, WHATWG.Console, W3C.Geometry, W3C.CSSOM, W3C.CSSOMView,
W3C.UIEvents, W3C.TouchEvents, W3C.WebStorage;
const
CWorkingSeeds = [1476865939254, 1476269729858, 1476279959891, 1476284075669,
1476288143993, 1476288349873, 1476288756145, 1476288876115, 1476288966305,
1476289060665, 1476312883639, 1476313825635, 1476314411891, 1476316120917,
1476321342064, 1476321569834, 1476321750585, 1476322931647, 1476322987251,
1476324264739, 1476324353562, 1476324424646, 1476324491202, 1476324724538,
1476324909418, 1476324977202, 1476354545149, 1476354614628, 1476354677709,
1476354748565, 1476354866415, 1476355118645, 1476355206087, 1476360560334,
1476360607758, 1476360705999, 1476360826197, 1476361035381, 1476362732813,
1476362790908, 1476362898852, 1476704659018, 1476704768474, 1476704834522,
1476705123146, 1476705211026, 1476705325106, 1476705362634, 1476705466770,
1476705510682, 1476705708714, 1476865666788, 1476865836591, 1476865849666,
1476866480312, 1476866723283, 1476867192083, 1476867234667, 1476867300548,
1476880882143, 1476881704526, 1476881776466, 1476881792584, 1476881941182,
1476881996070, 1476908135375, 1476908447190, 1476908692430, 1476908712726,
1476908891654, 1476909287087, 1476909314892, 1476909491583, 1476909801151,
1476910789015, 1476911105966, 1476911141126, 1476911456063, 1476911494344,
1476912098112, 1476912186375, 1476912207633, 1476912229910, 1476912274478,
1476912309487, 1476912549062, 1476912574300, 1476912618814, 1476912764312,
1476913144367, 1476913229725, 1477124441663, 1477124528823, 1477124652408,
1477124947711, 1479936899513, 1479936972480, 1479937018459, 1479937086536,
1479937120480, 1479937133005, 1479937275817, 1479937288171, 1479937327712,
1479937365585, 1479937474488, 1479937980632, 1479938162465, 1479938284632,
1479938349827, 1479938392504, 1479938403227, 1479938447480, 1479938731096,
1481292487562, 1481292547946, 1481292737490, 1481292750264, 1481292770389,
1481292794162, 1481293006786, 1481293127642, 1481293239035, 1481293254146,
1483015523385, 1483015574337, 1483015652449, 1483015994921, 1483016019041];
{ TCardTargetCanvas }
constructor TCardTargetCanvas.Create(Owner: IHtmlElementOwner; CardColor: TCardColor);
begin
inherited Create(Owner);
// determine pixel ratio
FPixelRatio := 1;
asm
@FPixelRatio = window.devicePixelRatio || 1;
end;
FCardColor := CardColor;
Resize;
end;
procedure TCardTargetCanvas.Resize;
begin
var R := CanvasElement.getBoundingClientRect;
if (CanvasElement.width <> Round(FPixelRatio * R.width)) or
(CanvasElement.height <> Round(FPixelRatio * R.height)) then
begin
CanvasElement.Width := Round(FPixelRatio * R.width);
CanvasElement.Height := Round(FPixelRatio * R.height);
Paint;
end;
end;
procedure TCardTargetCanvas.Paint;
begin
var Scale := CanvasElement.Width / 13;
Context.setTransform(Scale, 0, 0, Scale, 0, 0);
Context.ClearRect(0, 0, CanvasElement.Width, CanvasElement.Height);
Context.lineWidth := 0.28;
Context.fillStyle := 'rgba(0,0,0,0.15)';
Context.beginPath;
case FCardColor of
ccSpade:
begin
Context.moveTo(5.28, 0);
Context.bezierCurveTo(2.75, 3.61, 0, 5.9, 0, 8.5);
Context.bezierCurveTo(0, 11.1, 3.73, 11.92, 4.64, 9.5);
Context.bezierCurveTo(4.71, 9.32, 4.31, 11.94, 3.62, 13.17);
Context.lineTo(6.93, 13.17);
Context.bezierCurveTo(6.24, 11.94, 5.85, 9.32, 5.92, 9.5);
Context.bezierCurveTo(6.81, 11.91, 10.55, 11.46, 10.55, 8.5);
Context.bezierCurveTo(10.55, 5.55, 7.8, 3.61, 5.28, 0);
end;
ccHeart:
begin
Context.moveTo(6.2, 12.64);
Context.bezierCurveTo(4.09, 9.31, 0, 5.76, 0, 3.61);
Context.bezierCurveTo(0, 1.47, 1.35, 0, 3.03, 0);
Context.bezierCurveTo(4.72, 0, 5.92, 1.88, 6.2, 3.07);
Context.bezierCurveTo(6.48, 1.88, 7.68, 0, 9.36, 0);
Context.bezierCurveTo(11.05, 0, 12.43, 1.45, 12.4, 3.61);
Context.bezierCurveTo(12.36, 5.78, 8.39, 9.22, 6.2, 12.64);
end;
ccClub:
begin
Context.moveTo(6.1, 0);
Context.bezierCurveTo(9.07, 0, 10.02, 2.84, 7.49, 5.67);
Context.bezierCurveTo(10.86, 4.15, 12.85, 6.42, 12.03, 9.02);
Context.bezierCurveTo(11.21, 11.63, 7.53, 11, 6.63, 9.1);
Context.bezierCurveTo(6.3, 10.45, 7.18, 12.04, 7.7, 13.16);
Context.lineTo(4.51, 13.16);
Context.bezierCurveTo(5.03, 12.04, 5.92, 10.45, 5.58, 9.1);
Context.bezierCurveTo(4.69, 11, 1, 11.63, 0.18, 9.02);
Context.bezierCurveTo(-0.64, 6.42, 1.35, 4.15, 4.72, 5.67);
Context.bezierCurveTo(2.19, 2.84, 3.14, 0.01, 6.11, 0);
end;
ccDiamond:
begin
Context.moveTo(5.3, 13.17);
Context.bezierCurveTo(3.88, 10.82, 1.87, 8.53, 0, 6.58);
Context.bezierCurveTo(1.87, 4.63, 3.88, 2.35, 5.3, 0);
Context.bezierCurveTo(6.72, 2.35, 8.73, 4.63, 10.6, 6.58);
Context.bezierCurveTo(8.73, 8.53, 6.72, 10.82, 5.3, 13.17);
end;
end;
Context.closePath;
Context.fill;
end;
{ TCardTarget }
constructor TCardTarget.Create(Owner: IHtmlElementOwner; CardColor: TCardColor);
begin
inherited Create(Owner);
FCanvasElement := TCardTargetCanvas.Create(Self as IHtmlElementOwner, CardColor);
end;
{ TPark }
constructor TPark.Create;
begin
FCards.Clear;
end;
{ TPile }
procedure TPile.UpdatePositions(LargeAdvance: Float);
begin
var Advance := 0.0;
var Index := 1;
var SmallAdvance := 0.5 * LargeAdvance;
var HasLargeAdvance := False;
for var Card in Cards do
begin
Card.Style.left := FloatToStr(Position.X) + 'px';
Card.Style.top := FloatToStr(Position.Y + Advance) + 'px';
Card.Style.zIndex := IntToStr(Index);
Inc(Index);
if Card.IsConcealed then
Advance += SmallAdvance
else
begin
if not HasLargeAdvance then
begin
var MissingCards := (Length(Cards) - Index) + 3;
var Distance := Window.innerHeight - Card.CanvasElement.getBoundingClientRect.Top;
LargeAdvance := Min(LargeAdvance, Distance / MissingCards);
HasLargeAdvance := True;
end;
Advance += LargeAdvance;
end;
end;
end;
{ TDeck }
constructor TDeck.Create;
begin
for var Index := cvA to cvK do
FTinyOffsets[Index] := 0.1 + 0.2 * (Random + Random + Random);
end;
procedure TDeck.UpdatePositions(LargeAdvance: Float);
begin
var Index := 1;
var Offset := 0.0;
for var Card in Cards do
begin
Card.Style.left := FloatToStr(Position.X - Offset) + 'px';
Card.Style.top := FloatToStr(Position.Y - Offset) + 'px';
Card.Style.zIndex := IntToStr(Index);
Offset += FTinyOffsets[Card.Value];
Inc(Index);
end;
end;
(*
{ TModalDialog }
constructor TModalDialog.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FContent := TModalContent.Create(Self as IHtmlElementOwner);
Style.display := 'none';
end;
procedure TModalDialog.Show;
begin
Style.display := 'block';
end;
procedure TModalDialog.Hide;
begin
Style.display := 'none';
end;
{ TModalContent }
constructor TModalContent.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FHeading := TH1Element.Create(Self as IHtmlElementOwner);
FHeading.Text := 'You did it!';
FButton := TModalButton.Create(Self as IHtmlElementOwner);
FButton.Text := 'Retry';
end;
*)
{ TMainScreen }
constructor TMainScreen.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
MainScreen := Self;
DivElement.ID := 'main';
FBackgroundHeader := TH1Element.Create(Self as IHtmlElementOwner);
FBackgroundHeader.Text := 'SOLITAIRE';
FButtonNew := TTopButton.Create(Self as IHtmlElementOwner);
FButtonNew.Text := 'New';
FButtonNew.ButtonElement.addEventListener('click', lambda
Shuffle;
end);
FButtonNew.ButtonElement.addEventListener('touchstart', lambda
Shuffle;
end);
FButtonRetry := TTopButton.Create(Self as IHtmlElementOwner);
FButtonRetry.Text := 'Retry';
FButtonRetry.Style.marginLeft := '0';
FButtonRetry.ButtonElement.addEventListener('click', @Retry);
FButtonRetry.ButtonElement.addEventListener('touchstart', @Retry);
(*
FButtonSelect := TTopButton.Create(Self as IHtmlElementOwner);
FButtonSelect.Text := 'Select';
FButtonSelect.ButtonElement.addEventListener('click', lambda
Select;
end);
FButtonSelect.ButtonElement.addEventListener('touchstart', lambda
Select;
end);
*)
FButtonFinish := TTopButton.Create(Self as IHtmlElementOwner);
FButtonFinish.Text := 'Finish';
FButtonFinish.Style.setProperty('float', 'right');
FButtonFinish.Style.marginLeft := '0';
FButtonFinish.ButtonElement.addEventListener('click', @Finish);
FButtonFinish.ButtonElement.addEventListener('touchstart', @Finish);
{$IFDEF SOLVER}
FButtonSolve := TTopButton.Create(Self as IHtmlElementOwner);
FButtonSolve.Text := 'Solve';
FButtonSolve.Style.setProperty('float', 'right');
FButtonSolve.ButtonElement.addEventListener('click', @Solve);
FButtonSolve.ButtonElement.addEventListener('touchstart', @Solve);
{$ENDIF}
FButtonUndo := TTopButton.Create(Self as IHtmlElementOwner);
FButtonUndo.Text := 'Undo';
FButtonUndo.Style.setProperty('float', 'right');
FButtonUndo.ButtonElement.addEventListener('click', @Undo);
FButtonUndo.ButtonElement.addEventListener('touchstart', @Undo);
{$IFDEF SOLVER}
FLabel := TParagraphElement.Create(Self as IHTMLElementOwner);
FLabel.Style.position := 'fixed';
FLabel.Style.color := '#fff';
FLabel.Style.margin := '0';
FLabel.Style.top := '0';
{$ENDIF}
FSolvable := TH5Element.Create(Self as IHTMLElementOwner);
FSolvable.Text := 'Solvable';
FSolvable.Style.position := 'fixed';
FSolvable.Style.color := 'rgba(0,0,0,0.3)';
FSolvable.Style.margin := '0';
FSolvable.Style.bottom := '0';
FLargeAdvance := 32;
if Variant(LocalStorage.GetItem('SeedIndex')) = null then
begin
LocalStorage.SetItem('SeedIndex', '0');
FSeedIndex := 0;
end
else
FSeedIndex := StrToInt(LocalStorage.GetItem('SeedIndex'));
for var Index := Low(FPiles) to High(FPiles) do
FPiles[Index] := TPile.Create;
for var CardColor in TCardColor do
begin
FDecks[CardColor] := TDeck.Create;
FDecks[CardColor].CardTarget := TCardTarget.Create(Self as IHtmlElementOwner, CardColor);
end;
for var CardColor in TCardColor do
for var CardValue in TCardValue do
begin
var Card := TCard.Create(Self as IHtmlElementOwner, CardColor, CardValue);
Card.TransitionTime := 0.02;
FCards.Add(Card);
end;
// FModalDialog := TModalDialog.Create(Self as IHtmlElementOwner);
FConfetti := TConfetti.Create(Self as IHtmlElementOwner);
FConfetti.CanvasElement.addEventListener('click', lambda
if FConfetti.Rise then
begin
FConfetti.Stop;
Shuffle;
end;
end);
FConfetti.CanvasElement.addEventListener('touchstart', lambda
if FConfetti.Rise then
begin
FConfetti.Stop;
Shuffle;
end;
end);
// add event listeners
Window.addEventListener('resize', @Resize);
DivElement.addEventListener('mousedown', @MouseDownEventHandler);
DivElement.addEventListener('mousemove', @MouseMoveEventHandler);
DivElement.addEventListener('mouseup', @MouseUpEventHandler);
DivElement.addEventListener('touchstart', @TouchStartEventHandler);
DivElement.addEventListener('touchmove', @TouchMoveEventHandler);
DivElement.addEventListener('touchend', @TouchEndEventHandler);
Window.addEventListener('keypress', lambda(Event: JEvent)
var KeyboardEvent := JKeyboardEvent(Event);
case KeyboardEvent.keyCode of
{$IFDEF SOLVER}
115:
Solve;
{$ENDIF}
114:
Shuffle(FCurrentSeed);
110:
Shuffle;
102:
Finish;
117:
Undo;
end;
end);
Resize(nil);
Shuffle;
end;
procedure TMainScreen.Resize(Event: JEvent);
begin
var MinWidth := Min(Window.innerWidth, 4 * Window.innerHeight / 3);
var MinHeight := 3 * MinWidth / 4;
FCardWidth := MinWidth / 9;
FCardHeight := 4 * FCardWidth / 3;
FLargeAdvance := Max(FCardHeight / 5.1, Window.innerHeight / 32);
for var Card in FCards do
begin
Card.Style.width := IntToStr(Round(FCardWidth)) + 'px';
Card.Style.height := IntToStr(Round(FCardHeight)) + 'px';
Card.Resize;
end;
var ButtonRect := FButtonFinish.ButtonElement.getBoundingClientRect;
var X := Window.innerWidth - 0.5 * (Window.innerWidth - MinWidth) - 3 * FCardWidth;
var Y := Max(2 * ButtonRect.top + ButtonRect.height, 0.12 * Window.innerHeight);
for var Deck in FDecks do
begin
Deck.Position := TVector2f.Create(X, Y);
Deck.UpdatePositions(FLargeAdvance);
X -= 1.4 * FCardWidth;
var Style := Deck.CardTarget.Style;
Style.left := IntToStr(Round(Deck.Position.X) - 6) + 'px';
Style.top := IntToStr(Round(Deck.Position.Y) - 6) + 'px';
Style.width := IntToStr(Round(FCardWidth)) + 'px';
Style.height := IntToStr(Round(FCardHeight)) + 'px';
Deck.CardTarget.CanvasElement.Resize;
end;
X := 0.5 * (Window.innerWidth - MinWidth) + 0.1 * FCardWidth;
Y := Y + FCardHeight + ButtonRect.top;
for var Pile in FPiles do
begin
Pile.Position := TVector2f.Create(X, Y);
Pile.UpdatePositions(FLargeAdvance);
X += 1.1 * FCardWidth;
end;
FConfetti.Resize;
end;
procedure TMainScreen.MouseDownEventHandler(Event: JEvent);
begin
TouchMouseDown(TVector2f.Create(
JMouseEvent(Event).clientX,
JMouseEvent(Event).ClientY));
end;
procedure TMainScreen.MouseMoveEventHandler(Event: JEvent);
begin
Window.clearTimeout(FTimeOut);
FTimeOut := Window.setTimeout(lambda
ShowMouseHint;
end, 500);
TouchMouseMove(TVector2f.Create(
JMouseEvent(Event).clientX,
JMouseEvent(Event).ClientY));
end;
procedure TMainScreen.MouseUpEventHandler(Event: JEvent);
begin
TouchMouseUp(TVector2f.Create(
JMouseEvent(Event).clientX,
JMouseEvent(Event).ClientY));
end;
procedure TMainScreen.TouchStartEventHandler(Event: JEvent);
begin
// prevent default handling
Event.preventDefault;
// calculate bounding rectangle
var Touches := JTouchEvent(Event).changedTouches;
TouchMouseDown(TVector2f.Create(Touches[0].pageX, Touches[0].pageY));
end;
procedure TMainScreen.TouchMoveEventHandler(Event: JEvent);
begin
// prevent default handling
Event.preventDefault;
// calculate bounding rectangle
var Touches := JTouchEvent(Event).changedTouches;
TouchMouseMove(TVector2f.Create(Touches[0].pageX, Touches[0].pageY));
end;
procedure TMainScreen.TouchEndEventHandler(Event: JEvent);
begin
// prevent default handling
Event.preventDefault;
// calculate bounding rectangle
var Touches := JTouchEvent(Event).changedTouches;
TouchMouseUp(TVector2f.Create(Touches[0].pageX, Touches[0].pageY));
end;
function Intersect(A, B: JDomRect): Boolean;
begin
Result := not ((A.Left + A.Width < B.Left) or (B.Left + B.Width < A.Left) or
(A.Top + A.Height < B.Top) or (B.Top + B.Height < A.Top));
end;
procedure TMainScreen.TouchMouseDown(Position: TVector2f);
begin
// ignore multitouch
if FDown then
Exit;
// get element under mouse cursor
var CurrentElement := Document.elementFromPoint(Position.X, Position.Y);
// ignore this element
if CurrentElement = DivElement then
Exit;
var Found := False;
for var Pile in FPiles do
begin
var ZCount := 0;
for var Card in Pile.Cards do
begin
// check if the current pile contains the card of choice
if CurrentElement = Card.CanvasElement then
begin
FCurrentPark := Pile;
Found := True;
end;
if Found then
begin
if Card.IsConcealed then
begin
if Pile.Cards[High(Pile.Cards)] = Card then
Card.IsConcealed := False;
ClearUndo;
Exit;
end;
FCurrentCards.Add(Card);
Card.TransitionTime := 0;
Card.Style.zIndex := IntToStr(100 + ZCount);
Inc(ZCount);
end;
end;
if Found then
begin
// remove current cards from pile
for var Card in FCurrentCards do
Pile.Cards.Remove(Card);
break;
end;
end;
if not Found then
begin
for var Deck in FDecks do
begin
if Deck.Cards.Length = 0 then
continue;
var Card := Deck.Cards[High(Deck.Cards)];
// check if the current pile contains the card of choice
if CurrentElement = Card.CanvasElement then
begin
FCurrentPark := Deck;
Found := True;
FCurrentCards.Add(Card);
Card.TransitionTime := 0;
Card.Style.zIndex := IntToStr(100);
// remove current card from deck
Deck.Cards.Remove(Card);
break;
end;
end;
end;
if not Found then
Exit;
var R := FCurrentCards[0].CanvasElement.getBoundingClientRect;
FOffset.X := Position.X - R.Left;
FOffset.Y := Position.Y - R.Top;
FDown := True;
end;
procedure TMainScreen.TouchMouseMove(Position: TVector2f);
procedure ResetHighlighting;
begin
if Assigned(FHighlightCard) then
begin
FHighlightCard.IsHighlighted := False;
FHighlightCard := nil;
end;
end;
begin
if FDown then
begin
var YOffset := 0.0;
for var Card in FCurrentCards do
begin
Card.Style.left := FloatToStr(Position.X - FOffset.X) + 'px';
Card.Style.top := FloatToStr(Position.Y - FOffset.Y + YOffset) + 'px';
YOffset += FLargeAdvance;
end;
var FoundPark := GetClosestPile;
if Assigned(FoundPark) and (FoundPark.Cards.Length > 1) then
begin
if FHighlightCard <> FoundPark.Cards[0] then
begin
ResetHighlighting;
FHighlightCard := FoundPark.Cards[High(FoundPark.Cards)];
FHighlightCard.IsHighlighted := True;
end;
end
else
if Assigned(FHighlightCard) then
begin
FHighlightCard.IsHighlighted := False;
FHighlightCard := nil;
end;
end
else
begin
ResetHintCards;
FCardUnderCursor := LocateCardUnderCursor(Position);
end;
end;
procedure TMainScreen.TouchMouseUp(Position: TVector2f);
procedure Transfer(Park: TPark); overload;
begin
Assert(Assigned(Park));
// eventually store undo information
if Park <> FCurrentPark then
begin
FPreviousCards.Clear;
FPreviousCards.Add(FCurrentCards);
FPreviousOldPark := FCurrentPark;
FPreviousNewPark := Park;
end;
Park.Cards.Add(FCurrentCards);
for var Card in FCurrentCards do
Card.TransitionTime := 0.02;
Park.UpdatePositions(FLargeAdvance);
if Park <> FCurrentPark then
FCurrentPark.UpdatePositions(FLargeAdvance);
FCurrentCards.Clear;
CheckDone;
end;
begin
// ignore multitouch
if not FDown then
Exit;
FDown := False;
if Assigned(FHighlightCard) then
begin
FHighlightCard.IsHighlighted := False;
FHighlightCard := nil;
end;
// ignore if no card is selected
if FCurrentCards.Length = 0 then
Exit;
var FoundPark := GetClosestPile;
// eventually check deck as well
if not Assigned(FoundPark) or (FoundPark = FCurrentPark) then
FoundPark := GetDeck;
// check if a park position could be found
if Assigned(FoundPark) then
Transfer(FoundPark)
else
Transfer(FCurrentPark);
end;
procedure TMainScreen.ResetHintCards;
begin
if FHintCards.Length > 0 then
begin
for var Card in FHintCards do
Card.IsHighlighted := False;
FHintCards.Clear;
end;
end;
procedure TMainScreen.ShowMouseHint;
begin
ResetHintCards;
if Assigned(FCardUnderCursor) then
begin
var Targets := LocateTargets(FCardUnderCursor);
for var Target in Targets do
begin
var Cards := Target.Cards;
if Cards.Length > 0 then
begin
var Card := Cards[High(Cards)];
FHintCards.Add(Card);
Card.IsHighlighted := True;
end;
end;
end;
end;
function TMainScreen.GetClosestPile: TPark;
var
SqrDistance: Float;
begin
Result := nil;
var BottomCard := FCurrentCards[0];
var BR := BottomCard.CanvasElement.getBoundingClientRect;
for var Pile in FPiles do
begin
if Pile.Cards.Length > 0 then
begin
// get top card of the pile
var TopCard := Pile.Cards[High(Pile.Cards)];
// skip pile if not under the cursor
var TR := TopCard.CanvasElement.getBoundingClientRect;
if not Intersect(BR, TR) then
continue;
// skip pile if the top card is an ace
if TopCard.Value = cvA then
continue;
if (BottomCard.Color in [ccClub, ccSpade]) = not (TopCard.Color in [ccClub, ccSpade]) then
if Integer(BottomCard.Value) + 1 = Integer(TopCard.Value) then
begin
// calculate squared card distance
var NewSqrDistance := Sqr(BR.Left - TR.Left) + Sqr(BR.Top - TR.Top);
if (Result = nil) or (NewSqrDistance < SqrDistance) then
begin
Result := Pile;
SqrDistance := NewSqrDistance;
end;
end;
end
else
if BottomCard.Value = cvK then
begin
if not ((BR.Left + BR.Width < Pile.Position.X) or (Pile.Position.X + FCardWidth < BR.Left) or
(BR.Top + BR.Height < Pile.Position.Y) or (Pile.Position.Y + FCardHeight < BR.Top)) then
begin
// calculate squared card distance
var NewSqrDistance := Sqr(BR.Left - Pile.Position.X) +
Sqr(BR.Top - Pile.Position.Y);
if (Result = nil) or (NewSqrDistance < SqrDistance) then
begin
Result := Pile;
SqrDistance := NewSqrDistance;
end;
end;
end;
end;
end;
function TMainScreen.GetDeck: TPark;
begin
Result := nil;
if FCurrentCards.Length = 1 then
begin
var BottomCard := FCurrentCards[0];
var Deck := FDecks[BottomCard.Color];
if Deck.Cards.Length > 0 then
begin
// get top card of the pile
var TopCard := Deck.Cards[High(Deck.Cards)];
// skip pile if the top card is an ace
if Integer(BottomCard.Value) = Integer(TopCard.Value) + 1 then
Exit(Deck);
end
else
if BottomCard.Value = cvA then
Exit(Deck);
end;
end;
procedure TMainScreen.Undo;
begin
if Assigned(FPreviousOldPark) and Assigned(FPreviousNewPark) and
(FPreviousOldPark <> FPreviousNewPark) and (FPreviousCards.Length > 0) then
begin
// ensure the new park position contains the cards
if FPreviousNewPark.Cards.IndexOf(FPreviousCards[0]) < 0 then
exit;
// remove cards from pile
for var Card in FPreviousCards do
FPreviousNewPark.Cards.Remove(Card);
// add cards to previous (old) park position
FPreviousOldPark.Cards.Add(FPreviousCards);
// update card positions
FPreviousOldPark.UpdatePositions(FLargeAdvance);
FPreviousNewPark.UpdatePositions(FLargeAdvance);
ClearUndo;
end;
end;
procedure TMainScreen.ClearUndo;
begin
FPreviousCards.Clear;
FPreviousOldPark := nil;
FPreviousNewPark := nil;
end;
procedure TMainScreen.Shuffle(RandomSeed: Integer = 0);
const
CPileLength : array [0..7] of Integer = (3, 4, 5, 6, 7, 8, 9, 10);
var
Cards: TArrayOfCard;
begin
// clear undo and hash list
ClearUndo;
FHashList.Clear;
// clear all piles all decks
for var Pile in FPiles do
Pile.Cards.Clear;
for var Deck in FDecks do
Deck.Cards.Clear;
// reset card transition time
for var Card in FCards do
Card.TransitionTime := 0;
// specify random seed
if RandomSeed = 0 then
begin
{$IFNDEF SOLVER}
if FSeedIndex < Length(CWorkingSeeds) then
begin
FCurrentSeed := CWorkingSeeds[FSeedIndex];
Inc(FSeedIndex);
LocalStorage.SetItem('SeedIndex', IntToStr(FSeedIndex));
FSolvable.Style.removeProperty('visibility');
end
else
{$ENDIF}
begin
FCurrentSeed := JDate.Now;
FSolvable.Style.visibility := 'hidden';
end;
end;
SetRandSeed(FCurrentSeed);
Console.Log('Random Seed: ' + IntToStr(FCurrentSeed));
{$IFDEF SOLVER}
FLabel.Text := IntToStr(FCurrentSeed);
{$ENDIF}
// shuffle cards
Cards.Clear;
Cards.Add(FCards);
// shuffle cards to piles
while Cards.Length > 0 do
begin
var PileIndex := RandomInt(8);
if FPiles[PileIndex].Cards.Length < CPileLength[PileIndex] then
begin
var Card := Cards[RandomInt(Cards.Length)];
FPiles[PileIndex].Cards.Add(Card);
Card.IsConcealed := FPiles[PileIndex].Cards.Length <= CPileLength[PileIndex] - 3;
Cards.Remove(Card);
end;
end;
// update positions
for var Pile in FPiles do
Pile.UpdatePositions(FLargeAdvance);
// update card transition time
for var Card in FCards do
Card.TransitionTime := 0.02;
end;
procedure TMainScreen.Retry;
begin
Shuffle(FCurrentSeed);
end;
function TMainScreen.FinishOneCard: Boolean;
begin
Result := False;
for var Pile in FPiles do
if Pile.Cards.Length > 0 then
begin
var TopCard := Pile.Cards[High(Pile.Cards)];
var Deck := FDecks[TopCard.Color];
// eventually unveil concealed card
if TopCard.IsConcealed then
TopCard.IsConcealed := False;
if Deck.Cards.Length > 0 then
begin
var BottomCard := FDecks[TopCard.Color].Cards[High(Deck.Cards)];
if Integer(BottomCard.Value) + 1 = Integer(TopCard.Value) then
begin
Deck.Cards.Add(TopCard);
Pile.Cards.Remove(TopCard);
TopCard.TransitionTime := 0.1;
Pile.UpdatePositions(FLargeAdvance);
Deck.UpdatePositions(FLargeAdvance);
Exit(True);
end;
end
else
if TopCard.Value = cvA then
begin
Deck.Cards.Add(TopCard);
Pile.Cards.Remove(TopCard);
TopCard.TransitionTime := 0.1;
Pile.UpdatePositions(FLargeAdvance);
Deck.UpdatePositions(FLargeAdvance);
Exit(True);
end;
end;
end;
function TMainScreen.CheckDone: Boolean;
begin
Result := FCards.Length =
FDecks[ccClub].Cards.Length +
FDecks[ccSpade].Cards.Length +
FDecks[ccDiamond].Cards.Length +
FDecks[ccHeart].Cards.Length;
if Result then
FConfetti.Start;
end;
procedure TMainScreen.Finish;
begin
Window.clearTimeout(FTimeOut);
var Found := FinishOneCard;
if Found then
FTimeOut := Window.setTimeout(Finish, 10)
else
CheckDone;
end;
procedure TMainScreen.Select;
begin
// FModalDialog.Show;
end;
function TMainScreen.LocateCardUnderCursor(Position: TVector2f): TCard;
begin
var CurrentElement := Document.elementFromPoint(Position.X, Position.Y);
// ignore this element
if CurrentElement = DivElement then
Exit;
for var Card in FCards do
if Card.CanvasElement = CurrentElement then
Exit(Card);
end;
function TMainScreen.LocateTargets(Card: TCard): array of TPark;
begin
for var Pile in FPiles do
begin
if Pile.Cards.Length > 0 then
begin
// get top card of the pile
var TopCard := Pile.Cards[High(Pile.Cards)];
// skip pile if the top card is an ace
if TopCard.Value = cvA then
continue;
if (Card.Color in [ccClub, ccSpade]) = not (TopCard.Color in [ccClub, ccSpade]) then
if (Integer(Card.Value) + 1 = Integer(TopCard.Value)) then
Result.Add(Pile);
end
else
if Card.Value = cvK then
Result.Add(Pile);
end;
end;
{$IFDEF SOLVER}
function TMainScreen.GetConcealedHeight(Pile: TPile): Integer;
begin
Result := 0;
for var Card in Pile.Cards do
if Card.IsConcealed then
Inc(Result)
else
Exit;
end;
function TMainScreen.GetPilePriority: array of Integer;
var
Priorities: array [0..7] of Integer;
begin
Priorities[0] := 0;
for var Index := 1 to High(FPiles) do
Priorities[Index] := GetConcealedHeight(FPiles[Index]);
var Height := 0;
while Result.Length < 8 do
begin
for var PriorityIndex := 0 to 7 do
if Priorities[PriorityIndex] = Height then
Result.Add(PriorityIndex);
Inc(Height);
end;
Result.Reverse;
end;
function TMainScreen.FindFirstNonConcealed(Pile: TPile): TCard;
begin
Result := nil;
for var Card in Pile.Cards do
if not Card.IsConcealed then
Exit(Card);
end;
function TMainScreen.FindFirstNonConcealedIndex(Pile: TPile): Integer;
begin
Result := -1;
for var Index := 0 to High(Pile.Cards) do
if not Pile.Cards[Index].IsConcealed then
Exit(Index);
end;
function TMainScreen.UnveilConcealed: Boolean;
begin
Result := False;
var PileIndexes := GetPilePriority;
for var PileIndex in PileIndexes do
begin
var Pile := FPiles[PileIndex];
var Card := FindFirstNonConcealed(Pile);
if Assigned(Card) then
begin
// locate possible targets
var Targets := LocateTargets(Card);
// eventually remove current pile as possible target
if Targets.IndexOf(Pile) >= 0 then
Targets.Remove(Pile);
if Targets.Length > 0 then
begin
var Target := Targets[0];
var CardIndex := FindFirstNonConcealedIndex(Pile);
// security check
Assert(CardIndex >= 0);
while Pile.Cards.Length - CardIndex > 0 do
begin
Target.Cards.Add(Pile.Cards[CardIndex]);
Pile.Cards.Delete(CardIndex);
end;
if CardIndex > 0 then
Pile.Cards[CardIndex - 1].IsConcealed := False;
Targets[0].UpdatePositions(FLargeAdvance);
Pile.UpdatePositions(FLargeAdvance);
ClearUndo;
Exit(True);
end;
end;
end;
end;
function GetCardIndex(Card: TCard; Park: TPark): Integer;
begin
Result := -1;
for var Index := 0 to High(Park.Cards) do
if Park.Cards[Index] = Card then
Exit(Index);
end;
function TMainScreen.GetPossibleCards(OnlyUseful: Boolean = False): TArrayOfCard;
begin
// search possible cards
for var Card in FCards do
begin
if Card.IsConcealed then
continue;
var Targets := LocateTargets(Card);
var CurrentPark := GetParkForCard(Card);
if CurrentPark = nil then
continue;
if (CurrentPark is TDeck) and (Card <> CurrentPark.Cards[High(CurrentPark.Cards)]) then
continue;
if Targets.IndexOf(CurrentPark) >= 0 then
Targets.Remove(CurrentPark);
if Targets.Length > 0 then
begin
var CardIndex := GetCardIndex(Card, CurrentPark);
if OnlyUseful then
begin
// ignore moves from the deck
if CurrentPark is TDeck then
continue;
// ignore bottom card moves
if CardIndex <= 0 then
continue;
// ignore sorted state
var CardBelow := CurrentPark.Cards[CardIndex - 1];
if (CardBelow.Color in [ccClub, ccSpade]) = not (Card.Color in [ccClub, ccSpade])
and (Integer(CardBelow.Value) = Integer(Card.Value) + 1) then
continue;
end;
// ignore moving kings around
if (CardIndex = 0) and (Targets[0].Cards.Length = 0) then
continue;
Result.Add(Card);
end;
end;
end;
function TMainScreen.RandomMove: Boolean;
begin
Result := False;
var PossibleCards := GetPossibleCards(True);
if PossibleCards.Length = 0 then
PossibleCards := GetPossibleCards;
// check if there are any possible cards to move
if PossibleCards.Length = 0 then
Exit(False);
var Card := PossibleCards[RandomInt(PossibleCards.Length)];
// locate possible targets
var Targets := LocateTargets(Card);
var CurrentPark := GetParkForCard(Card);
// eventually remove current pile as possible target
if Targets.IndexOf(CurrentPark) >= 0 then
Targets.Remove(CurrentPark);
if Targets.Length > 0 then
begin
var Target := Targets[RandomInt(Targets.Length)];
var CardIndex := GetCardIndex(Card, CurrentPark);
Assert(CardIndex >= 0);
while CurrentPark.Cards.Length - CardIndex > 0 do
begin
Target.Cards.Add(CurrentPark.Cards[CardIndex]);
CurrentPark.Cards.Delete(CardIndex);
end;
if CardIndex > 0 then
CurrentPark.Cards[CardIndex - 1].IsConcealed := False;
Targets[0].UpdatePositions(FLargeAdvance);
CurrentPark.UpdatePositions(FLargeAdvance);
ClearUndo;
Exit(True);
end;
end;
function TMainScreen.CalculateHash: Integer;
var
Data: array of Integer;
begin
for var Deck in FDecks do
Data.Add(Deck.Cards.Length);
for var Pile in FPiles do
begin
Data.Add(Pile.Cards.Length);
for var Card in Pile.Cards do
Data.Add(4 * Integer(Card.Value) + Integer(Card.Color));
end;
Result := 0;
for var Item in Data do
Result := (Result xor Item) * 16777619;
end;
function TMainScreen.GetParkForCard(Card: TCard): TPark;
begin
Result := nil;
// first check decks
for var Deck in FDecks do
if Deck.Cards.IndexOf(Card) >= 0 then
Exit(Deck);
// next check piles
for var Pile in FPiles do
if Pile.Cards.IndexOf(Card) >= 0 then
Exit(Pile);
end;
procedure TMainScreen.Solve;
begin
Window.clearTimeout(FTimeOut);
//eventually exit if user interacts
if FCurrentCards.Length > 0 then
Exit;
// try to finish a card
var Found := FinishOneCard;
if Found and CheckDone then
Exit;
// try to unveil a concealed card
if not Found then
begin
Found := UnveilConcealed;
if Found then
begin
if CheckDone then
Exit;
var HashValue := CalculateHash;
if FHashList.IndexOf(HashValue) >= 0 then
Found := False
else
FHashList.Add(HashValue);
end;
end;
Randomize;
if not Found then
begin
Found := RandomMove;
if Found then
begin
if CheckDone then
Exit;
var HashValue := CalculateHash;
if FHashList.IndexOf(HashValue) >= 0 then
Found := False
else
FHashList.Add(HashValue);
end;
end;
if Found then
Window.setTimeout(Solve, 10)
else
CheckDone;
end;
{$ENDIF}
end. |
unit algos;
interface
procedure SetDimensions(newP, newM, newN, newLen:word);
function SortLinear:longint;
function Algo_1:longint;
function Algo_2:longint;
function Algo_3:longint;
procedure FormStraightSorted;
procedure FormBackSorted;
procedure FormRandom;
const MAXM=40; MAXN=40; MAXP=20; MAXLEN=20000;
implementation
uses dos;
type TTime=record
hours:word;
mins:word;
secs:word;
hsecs:word;
end;
type TArrType=integer;
PArrType=^TArrType;
TLArray=array [1..MAXLEN] of TArrType;
PLArray=^TLArray;
var M, N, P, Len:word;
A:array [1..MAXP, 1..MAXM, 1..MAXN] of TArrType;
C:PLArray;
procedure FormSorted(straight:boolean);
var i, j, k:word;
dv: integer;
value:TArrType;
begin
if straight = true then begin
value:=1;
dv:=1;
end else begin
value:=M*N;
dv:=-1;
end;
for j:=1 to N do
for i:= 1 to M do begin
for k:= 1 to P do
A[k, i, j]:=value;
value:=value+dv;
end;
if straight = true then value:=1
else value:=Len;
for i:=1 to Len do begin
C^[i]:=value;
value:=value+dv;
end;
end;
procedure SetDimensions(newP, newM, newN, newLen:word);
begin
M:=newM;
N:=newN;
P:=newP;
Len:=newLen;
end;
procedure FormStraightSorted;
begin
FormSorted(true);
end;
procedure FormBackSorted;
begin
FormSorted(false);
end;
procedure FormRandom;
var i, j, k:word;
begin
randomize;
for k:=1 to P do
for i:=1 to M do
for j:=1 to N do
A[k, i, j]:=random(8112);
for i:=1 to Len do C^[i]:=random(8112);
end;
function Algo_1:longint;
var startTime, finTime:TTime;
B:array [1..MAXN*MAXM] of longint;
i, j, k, R, L, x, pos:word;
tmp:TArrType;
begin
with startTime do GetTime(hours, mins, secs, hsecs);
for k:=1 to P do begin
pos:=1;
for j:=1 to N do
for i:=1 to M do begin
B[pos]:=A[k, i, j];
pos:=pos+1;
end;
L:=1; R:=M*N; x:=1;
while L < R do begin
for i:=L to R-1 do
if B[i] > B[i+1] then begin
tmp:=B[i];
B[i]:=B[i+1];
B[i+1]:=tmp;
x:=i;
end;
R:=x;
for i:=R-1 downto L do
if B[i] > B[i+1] then begin
tmp:=B[i];
B[i]:=B[i+1];
B[i+1]:=tmp;
x:=i+1;
end;
L:=x;
end;
pos:=1;
for j:=1 to N do
for i:=1 to M do begin
A[k, i, j]:=B[pos];
pos:=pos+1;
end;
end;
with finTime do GetTime(hours, mins, secs, hsecs);
Algo_1:=((finTime.hours*3600+finTime.mins*60+finTime.secs)*100+finTime.hsecs) -
((startTime.hours*3600+startTime.mins*60+startTime.secs)*100+startTime.hsecs);
end;
function Algo_2:longint;
var startTime, finTime:TTime;
i, k, R, L, x:word;
tmp:TArrType;
begin
with startTime do GetTime(hours, mins, secs, hsecs);
for k:=1 to P do begin
L:=1; R:=M*N; x:=1;
while L < R do begin
for i:=L to R-1 do
if A[k, (i-1)mod(M)+1, (i-1)div(M)+1] > A[k,(i)mod(M)+1, (i)div(M)+1] then begin
tmp:=A[k, (i-1)mod(M)+1, (i-1)div(M)+1];
A[k, (i-1)mod(M)+1, (i-1)div(M)+1]:=A[k,(i)mod(M)+1, (i)div(M)+1];
A[k,(i)mod(M)+1, (i)div(M)+1]:=tmp;
x:=i;
end;
R:=x;
for i:=R-1 downto L do
if A[k, (i-1)mod(M)+1, (i-1)div(M)+1] > A[k,(i)mod(M)+1, (i)div(M)+1] then begin
tmp:=A[k, (i-1)mod(M)+1, (i-1)div(M)+1];
A[k, (i-1)mod(M)+1, (i-1)div(M)+1]:=A[k,(i)mod(M)+1, (i)div(M)+1];
A[k,(i)mod(M)+1, (i)div(M)+1]:=tmp;
x:=i;
end;
L:=x+1;
end;
end;
with finTime do GetTime(hours, mins, secs, hsecs);
Algo_2:=((finTime.hours*3600+finTime.mins*60+finTime.secs)*100+finTime.hsecs) -
((startTime.hours*3600+startTime.mins*60+startTime.secs)*100+startTime.hsecs);
end;
function Algo_3:longint;
var startTime, finTime:TTime;
i, j, k, rI, rJ, lI, lJ, xI, xJ, start, fin:word;
tmp:TArrType;
next:PArrType;
begin
with startTime do GetTime(hours, mins, secs, hsecs);
for k:=1 to P do begin
lI:=1; lJ:=1; rI:=M; rJ:=N; xI:=1; xJ:=1;
while lJ <= rJ do begin
if (lJ = rJ) and (lI >= rI) then break;
for j:=lJ to rJ do begin
start:=1; fin:=M;
if j = lJ then start:=lI;
if j = rJ then fin:=rI-1;
for i:=start to fin do begin
if i < M then next:=@ A[k, i+1, j]
else next:=@ A[k, 1, j+1];
if A[k, i, j] > next^ then begin
tmp:=A[k, i, j];
A[k, i, j]:=next^;
next^:=tmp;
xI:=i;
xJ:=j;
end;
end;
end;
rI:=xI;
rJ:=xJ;
for j:=rJ downto lJ do begin
start:=1; fin:=M;
if j = lJ then start:=lI;
if j = rJ then fin:=rI-1;
for i:=fin downto start do begin
if i < M then next:=@ A[k, i+1, j]
else next:=@ A[k, 1, j+1];
if A[k, i, j] > next^ then begin
tmp:=A[k, i, j];
A[k, i, j]:=next^;
next^:=tmp;
xI:=i;
xJ:=j;
end;
end;
end;
if xI < M then begin
lI:=xI+1;
lJ:=xJ;
end else begin
lI:=1;
lJ:=xJ+1;
end;
end;
end;
with finTime do GetTime(hours, mins, secs, hsecs);
Algo_3:=((finTime.hours*3600+finTime.mins*60+finTime.secs)*100+finTime.hsecs) -
((startTime.hours*3600+startTime.mins*60+startTime.secs)*100+startTime.hsecs);
end;
function SortLinear:longint;
var startTime, finTime:TTime;
L, R, x, i:word;
tmp:TArrType;
begin
with startTime do GetTime(hours, mins, secs, hsecs);
L:=1; R:=Len; x:=1;
while L < R do begin
for i:=L to R-1 do
if C^[i] > C^[i+1] then begin
tmp:=C^[i];
C^[i]:=C^[i+1];
C^[i+1]:=tmp;
x:=i;
end;
R:=x;
for i:=R-1 downto L do
if C^[i] > C^[i+1] then begin
tmp:=C^[i];
C^[i]:=C^[i+1];
C^[i+1]:=tmp;
x:=i;
end;
L:=x+1;
end;
with finTime do GetTime(hours, mins, secs, hsecs);
SortLinear:=((finTime.hours*3600+finTime.mins*60+finTime.secs)*100+finTime.hsecs) -
((startTime.hours*3600+startTime.mins*60+startTime.secs)*100+startTime.hsecs);
end;
begin
new(C);
SetDimensions(1, 1, 1, 1);
FormRandom;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ImgList, ComCtrls, uDebugFunctions;
Const
IMG_CATALOG = 0;
IMG_IMPORT = 1;
IMG_EXPORT = 2;
OPT_CATALOG = 1;
OPT_EXPORT = 2;
OPT_IMPORT = 3;
type
TFrmMain = class(TForm)
Panel1: TPanel;
imgLine: TImage;
imgSelection: TImage;
Label5: TLabel;
Label9: TLabel;
lbOption: TLabel;
lblVersion: TLabel;
Label10: TLabel;
Shape8: TShape;
Panel2: TPanel;
lbImport: TLabel;
lbExport: TLabel;
lbCatalog: TLabel;
imgCatalogSmall: TImage;
imgExport: TImage;
imgImport: TImage;
imgSmall: TImageList;
Shape6: TShape;
pnlMain: TPanel;
pnlSelection: TPanel;
lbSelection: TLabel;
lbPowered: TLabel;
Label8: TLabel;
imgConnection: TImage;
pgSelection: TPageControl;
tsIntro: TTabSheet;
tsCatalog: TTabSheet;
tsExport: TTabSheet;
tsImport: TTabSheet;
imgSearchCatalog: TImage;
lbCatalogSearch: TLabel;
imgComperPrice: TImage;
lbComperDesc: TLabel;
lbPriceComper: TLabel;
Image9: TImage;
lbInventoryUpdate: TLabel;
Label13: TLabel;
imgExpPO: TImage;
lbExpPO: TLabel;
Label2: TLabel;
imgImpotPO: TImage;
lbImpPO: TLabel;
Label15: TLabel;
Image11: TImage;
lbImpEntiry: TLabel;
Label19: TLabel;
Image10: TImage;
lbImpInv: TLabel;
Label17: TLabel;
imgPeachtree: TImage;
lbPeachtree: TLabel;
lbPeachDesc: TLabel;
lbCatalogSearchInfo: TLabel;
imgSysnc: TImage;
lbSyncData: TLabel;
Label4: TLabel;
Image1: TImage;
lbPetCenter: TLabel;
lbPetCenterDetail: TLabel;
lbUser: TLabel;
lbExpirationInfo: TLabel;
lbLicense: TLabel;
lbQuickDesc: TLabel;
lbQuickBooks: TLabel;
Image3: TImage;
Image2: TImage;
LblVendorFile: TLabel;
Label3: TLabel;
procedure lbColumnsMouseLeave(Sender: TObject);
procedure lbColumnsMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Label1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Label1MouseLeave(Sender: TObject);
procedure PersonMouseLeave(Sender: TObject);
procedure PersonMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure lbExpPOMouseLeave(Sender: TObject);
procedure lbExpPOMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Label10Click(Sender: TObject);
procedure lbCatalogMouseEnter(Sender: TObject);
procedure lbCatalogMouseLeave(Sender: TObject);
procedure lbCatalogClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lbPriceComperClick(Sender: TObject);
procedure lbImpPOClick(Sender: TObject);
procedure lbImpEntiryClick(Sender: TObject);
procedure lbImpInvClick(Sender: TObject);
procedure lbExpPOClick(Sender: TObject);
procedure lbInventoryUpdateClick(Sender: TObject);
procedure lbCatalogSearchClick(Sender: TObject);
procedure lbPeachtreeClick(Sender: TObject);
procedure lbSyncDataClick(Sender: TObject);
procedure lbPetCenterClick(Sender: TObject);
procedure lbLicenseClick(Sender: TObject);
procedure lbQuickBooksClick(Sender: TObject);
procedure LblVendorFileClick(Sender: TObject);
private
procedure LoadImage;
procedure HidePanels;
procedure LoadParams;
procedure ShowPanel(Option:Integer);
function ValidateLogin : Boolean;
function ValidateModule(Module : String) : Boolean;
function CallAutoLogin(PW: String): Boolean;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses uWizImportPO, uWizImportCatalog, uFrmServerConnection, uWizImportPerson,
uWizImportInventory, uDMImportExport, uWizExportPO, uFrmInventoryUpdate, ULogin,
uFrmCatalogSearch, uFrmPeachtree, uFrmCatalogSyncData, uWizImportPet,
uUserObj, uMainRetailKeyConst, uMsgBox, uFrmQuickBooks, uWizImportVendorCatalog;
{$R *.dfm}
procedure TFrmMain.lbColumnsMouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := [];
Screen.Cursor := crDefault;
end;
procedure TFrmMain.lbColumnsMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
TLabel(Sender).Font.Style := [fsBold, fsUnderline];
Screen.Cursor := crHandPoint;
end;
procedure TFrmMain.Label1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
TLabel(Sender).Font.Style := [fsBold, fsUnderline];
Screen.Cursor := crHandPoint;
end;
procedure TFrmMain.Label1MouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := [];
Screen.Cursor := crDefault;
end;
procedure TFrmMain.PersonMouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := [];
Screen.Cursor := crDefault;
end;
procedure TFrmMain.PersonMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
TLabel(Sender).Font.Style := [fsBold, fsUnderline];
Screen.Cursor := crHandPoint;
end;
procedure TFrmMain.lbExpPOMouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := [];
Screen.Cursor := crDefault;
end;
procedure TFrmMain.lbExpPOMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
TLabel(Sender).Font.Style := [fsBold, fsUnderline];
Screen.Cursor := crHandPoint;
end;
procedure TFrmMain.Label10Click(Sender: TObject);
begin
with TFrmServerConnection.Create(Self) do
try
Start(1);
finally
Free;
end;
end;
procedure TFrmMain.HidePanels;
begin
pgSelection.ActivePage := tsIntro;
end;
procedure TFrmMain.LoadImage;
begin
imgSmall.GetBitmap(IMG_CATALOG, imgCatalogSmall.Picture.Bitmap);
imgSmall.GetBitmap(IMG_IMPORT, imgImport.Picture.Bitmap);
imgSmall.GetBitmap(IMG_EXPORT, imgExport.Picture.Bitmap);
end;
procedure TFrmMain.ShowPanel(Option: Integer);
begin
HidePanels;
case Option of
OPT_CATALOG : pgSelection.ActivePage := tsCatalog;
OPT_IMPORT : pgSelection.ActivePage := tsImport;
OPT_EXPORT : pgSelection.ActivePage := tsExport;
end;
end;
procedure TFrmMain.lbCatalogMouseEnter(Sender: TObject);
begin
TLabel(Sender).Font.Style := [fsBold];
end;
procedure TFrmMain.lbCatalogMouseLeave(Sender: TObject);
begin
TLabel(Sender).Font.Style := [];
end;
procedure TFrmMain.lbCatalogClick(Sender: TObject);
begin
lbSelection.Caption := TLabel(Sender).Caption;
ShowPanel(TLabel(Sender).Tag);
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
LoadImage;
HidePanels;
LoadParams;
end;
procedure TFrmMain.lbPriceComperClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_CAT_PRICE_COM) then
with TFrmInventoryUpdate.Create(Self) do
try
Start(1);
finally
free;
end;
end;
procedure TFrmMain.lbImpPOClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_IMP_PO) then
with TWizImportPO.Create(Self) do
try
Start;
finally
free;
end;
end;
procedure TFrmMain.lbImpEntiryClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_IMP_ENTITY) then
with TWizImportPerson.Create(Self) do
try
Start;
finally
Free;
end;
end;
procedure TFrmMain.lbImpInvClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_IMP_INV) then
with TWizImportInventory.Create(Self) do
try
Start;
finally
Free;
end;
end;
procedure TFrmMain.lbExpPOClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_EXP_PO) then
with TWizExportPO.Create(Self) do
try
Start;
finally
Free;
end;
end;
procedure TFrmMain.lbInventoryUpdateClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_CAT_INV_UPD) then
with TFrmInventoryUpdate.Create(Self) do
try
Start(2);
finally
Free;
end;
end;
function TFrmMain.ValidateLogin: Boolean;
begin
try
DMImportExport.OpenConnection;
if DMImportExport.FUser.Password = '' then
begin
with TRepLoginFrm.Create(Self) do
try
Result := Start;
lbUser.Caption := DMImportExport.FUser.UserName;
lbExpirationInfo.Visible := False;
if DMImportExport.FSoftwareExpired then
begin
lbExpirationInfo.Visible := True;
lbExpirationInfo.Caption := 'Software expired since ' + FormatDateTime('ddddd', DMImportExport.FSoftwareExpirationDate);
end
else if ((DMImportExport.FSoftwareExpirationDate - 10) < Trunc(Now)) then
begin
lbExpirationInfo.Visible := True;
lbExpirationInfo.Caption := 'Software will expire on ' + FormatDateTime('ddddd', DMImportExport.FSoftwareExpirationDate);
end;
lbLicense.Visible := True;
finally
Free;
end;
end
else
Result := True;
except
on E: Exception do
begin
Result := False;
MsgBox(E.Message, vbCritical + vbOkOnly);
end;
end;
end;
procedure TFrmMain.lbCatalogSearchClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_CAT_SRCH) then
with TFrmCatalogSearch.Create(Self) do
try
Start;
finally
Free;
end;
end;
procedure TFrmMain.lbPeachtreeClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_EXP_PEACHTREE) then
with TFrmPeachtree.Create(self) do
Start;
end;
procedure TFrmMain.lbSyncDataClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_CAT_SYNC) then
with TFrmCatalogSyncData.Create(Self) do
Start;
end;
procedure TFrmMain.lbPetCenterClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_IMP_PET) then
with TWizImportPet.Create(Self) do
try
Start;
finally
Free;
end;
end;
procedure TFrmMain.LoadParams;
begin
if ParamCount > 0 then
begin
if ParamStr(1) = 'PET' then
begin
pgSelection.ActivePage := tsImport;
if (ParamCount > 1) and (ParamStr(2) <> '') then
begin
CallAutoLogin(ParamStr(2));
lbPetCenter.OnClick(Self);
Close;
end;
end;
end;
end;
function TFrmMain.CallAutoLogin(PW: String): Boolean;
begin
if PW <> '' then
begin
with TRepLoginFrm.Create(Self) do
try
Result := AutoLogin(PW);
lbUser.Caption := DMImportExport.FUser.UserName;
finally
Free;
end;
end
else
Result := True;
end;
function TFrmMain.ValidateModule(Module: String): Boolean;
begin
Result := False;
if not DMImportExport.ActiveConnection.AppServer.SoftwareModuleAccess(SOFTWARE_IE, Module) then
begin
MsgBox('You do not have access for this module.', vbInformation + vbOKOnly);
Exit;
end;
Result := True;
end;
procedure TFrmMain.lbLicenseClick(Sender: TObject);
begin
with TFrmServerConnection.Create(Self) do
try
Start(2);
finally
Free;
end;
end;
procedure TFrmMain.lbQuickBooksClick(Sender: TObject);
begin
if ValidateLogin and ValidateModule(SOFTWARE_IE_EXP_QB) then
with TFrmQuickBooks.Create(Self) do
try
Start;
finally
Free;
end;
end;
{ Alex 29/03/2011 }
procedure TFrmMain.LblVendorFileClick(Sender: TObject);
begin
If ( ValidateLogin And ValidateModule( SOFTWARE_IE_IMP_VC ) ) Then Begin
With TWizImportVendorCatalog.Create( Self ) Do Begin
Try
Start;
Finally
Free;
End;
End;
End;
end;
end.
|
unit Demo.TimelineChart.Advanced;
interface
uses
System.Classes, System.SysUtils, Demo.BaseFrame, cfs.GCharts;
type
TDemo_TimelineChart_Advanced = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_TimelineChart_Advanced.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_TIMELINE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Position'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'President'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End')
]);
Chart.Data.AddRow([ 'President', 'George Washington', EncodeDate(1789, 4, 30), EncodeDate(1797, 3, 4) ]);
Chart.Data.AddRow([ 'President', 'John Adams', EncodeDate(1797, 3, 4), EncodeDate(1801, 3, 4) ]);
Chart.Data.AddRow([ 'President', 'Thomas Jefferson', EncodeDate(1801, 3, 4), EncodeDate(1809, 3, 4) ]);
Chart.Data.AddRow([ 'Vice President', 'John Adams', EncodeDate(1789, 4, 21), EncodeDate(1797, 3, 4)]);
Chart.Data.AddRow([ 'Vice President', 'Thomas Jefferson', EncodeDate(1797, 3, 4), EncodeDate(1801, 3, 4)]);
Chart.Data.AddRow([ 'Vice President', 'Aaron Burr', EncodeDate(1801, 3, 4), EncodeDate(1805, 3, 4)]);
Chart.Data.AddRow([ 'Vice President', 'George Clinton', EncodeDate(1805, 3, 4), EncodeDate(1812, 4, 20)]);
Chart.Data.AddRow([ 'Secretary of State', 'John Jay', EncodeDate(1789, 9, 25), EncodeDate(1790, 3, 22)]);
Chart.Data.AddRow([ 'Secretary of State', 'Thomas Jefferson', EncodeDate(1790, 3, 22), EncodeDate(1793, 12, 31)]);
Chart.Data.AddRow([ 'Secretary of State', 'Edmund Randolph', EncodeDate(1794, 1, 2), EncodeDate(1795, 8, 20)]);
Chart.Data.AddRow([ 'Secretary of State', 'Timothy Pickering', EncodeDate(1795, 8, 20), EncodeDate(1800, 5, 12)]);
Chart.Data.AddRow([ 'Secretary of State', 'Charles Lee', EncodeDate(1800, 5, 13), EncodeDate(1800, 6, 5)]);
Chart.Data.AddRow([ 'Secretary of State', 'John Marshall', EncodeDate(1800, 6, 13), EncodeDate(1801, 3, 4)]);
Chart.Data.AddRow([ 'Secretary of State', 'Levi Lincoln', EncodeDate(1801, 3, 5), EncodeDate(1801, 5, 1)]);
Chart.Data.AddRow([ 'Secretary of State', 'James Madison', EncodeDate(1801, 5, 2), EncodeDate(1809, 3, 3)]);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:900px; height:300px; margin:auto;position: absolute;top:0;bottom: 0;left: 0;right: 0;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_TimelineChart_Advanced);
end.
|
unit ExDBGRID;
interface
uses DBGrids, CheckLst, SysUtils, Windows;
function get_column_by_fieldname(tmp:string; grid:TDBGrid) : tColumn;
function GetCountCheckListBox(ListBox : TCheckListBox): integer;
procedure SetPropExcelCell(var MyWs : OleVariant; x : Integer ; y: Integer; iInteriorColor: integer; iHorizontalAlignment: integer);
procedure SetPropExcelFontSize(var MyWs: OleVariant; x1: Integer ; y1: Integer; x2: integer; y2: integer; SFontSize: string);
procedure MergeExcelCells(var MyWs : OleVariant; x1,y1,x2,y2 : integer);
procedure upoTryStrToCurr(var S: string);
function CellName(a, b: Integer): string;
function ufoTryStrToInt(const S: string): Boolean;
function ufoTryStrToCurr(const S: string): Boolean;
function GetComputerNetName: string;
function GetUserFromWindows: string;
implementation
uses Excel97;
function get_column_by_fieldname(tmp:string; grid:TDBGrid) : tColumn;
var
i:integer;
begin
for i:=0 to grid.Columns.count-1 do begin
if tmp = grid.Columns[i].FieldName then begin
result := grid.Columns[i];
break;
end;
end;
end;
function GetCountCheckListBox(ListBox : TCheckListBox): integer;
var
i : integer;
iCount_Check : integer;
begin
iCount_Check := 0;
for i := 0 to ListBox.Count-1 do if ListBox.Checked[i] then inc(iCount_Check);
result := iCount_Check;
end;
function CellName(a, b: Integer): string;
begin
if a <= 26 then Result := chr(a + $40)
else Result := chr((a - 27) div 26 + $41) + chr((a - 1) mod 26 + $41);
Result := Result + IntToStr(b);
end;
function ufoTryStrToInt(const S: string): Boolean;
var
ISignType : integer;
bVal : boolean;
begin
if length(trim(S)) <> 0 then bVal := TryStrToInt(S,ISignType) else bVal := true;
Result := bVal;
end;
function ufoTryStrToCurr(const S: string): Boolean;
var
NSignCurr : Currency;
bVal : boolean;
begin
if length(trim(S)) <> 0 then bVal := TryStrToCurr(S,NSignCurr) else bVal := true;
Result := bVal;
end;
{
Детальный анализ символьного выражения типа Currency
Обычно вызывается после ufoTryStrToCurr
}
procedure upoTryStrToCurr(var S: string);
var
CountNotDigit : integer;
iCkl : integer;
Coma : char;
begin
CountNotDigit := 0;
for iCkl := 1 to length(S) do begin
if not (S[iCkl] in ['0'..'9']) then begin
inc(CountNotDigit);
Coma := S[iCkl];
end;
end;
if (CountNotDigit = 1) and (Coma in [',','.']) then begin
if Coma = ',' then S := StringReplace(S,',','.',[])
else if Coma = '.' then S := StringReplace(S,'.',',',[])
end;
end;
{ Форматирование ячейки }
procedure SetPropExcelCell(var MyWs: OleVariant; x : Integer ; y: Integer; iInteriorColor: integer; iHorizontalAlignment: integer);
var
cell : OleVariant;
begin
cell := MyWS.Range[CellName(x,y) + ':' + CellName(x,y)];
cell.Borders.LineStyle := xlContinuous;
cell.HorizontalAlignment := iHorizontalAlignment;
cell.VerticalAlignment := xlTop;
cell.Interior.ColorIndex := iInteriorColor;
//cell.WrapText := true;
end;
procedure SetPropExcelFontSize(var MyWs: OleVariant; x1: Integer ; y1: Integer; x2: integer; y2: integer; SFontSize: string);
var
cells : OleVariant;
begin
cells := MyWS.Range[CellName(x1,y1) + ':' + CellName(x2,y2)];
cells.Select;
cells.Font.Size := SFontSize;
cells.Select;
end;
{ Объединений ячеек }
procedure MergeExcelCells(var MyWs : OleVariant; x1,y1,x2,y2 : integer);
var
Cells : OleVariant;
begin
Cells := MyWS.Range[CellName(x1,y1) + ':' + CellName(x2,y2)];
Cells.Select;
Cells.Merge;
end;
function GetComputerNetName: string;
var
buffer: array[0..255] of char;
size: dword;
begin
size := 256;
if GetComputerName(buffer, size)
then Result := buffer
else Result := ''
end;
function GetUserFromWindows: string;
var
UserName : string;
UserNameLen : Dword;
begin
UserNameLen := 255;
SetLength(userName, UserNameLen);
if GetUserName(PChar(UserName), UserNameLen)
then Result := Copy(UserName,1,UserNameLen - 1)
else Result := 'Unknown';
end;
end.
|
unit GLDScaleParamsFrame;
interface
uses
Classes, Controls, Forms, ComCtrls, StdCtrls, GL,
GLDTypes, GLDSystem, GLDUpDown;
type
TGLDScaleParamsFrame = class(TFrame)
GB_Scale: TGroupBox;
L_ScaleX: TLabel;
L_ScaleY: TLabel;
L_ScaleZ: TLabel;
E_ScaleX: TEdit;
E_ScaleY: TEdit;
E_ScaleZ: TEdit;
UD_ScaleX: TGLDUpDown;
UD_ScaleY: TGLDUpDown;
UD_ScaleZ: TGLDUpDown;
procedure ValueChangeUD(Sender: TObject);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HaveScale: GLboolean;
function GetParams: TGLDScaleParams;
procedure SetParams(const Params: TGLDScaleParams);
procedure SetParamsFrom(Source: TObject);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
implementation
{$R *.dfm}
uses
SysUtils, GLDX, GLDModify;
function TGLDScaleParamsFrame.HaveScale: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedModify) and
(FDrawer.EditedModify is TGLDScale) then
Result := True;
end;
function TGLDScaleParamsFrame.GetParams: TGLDScaleParams;
begin
Result := GLDXScaleParams(
UD_ScaleX.Position, UD_ScaleY.Position, UD_ScaleZ.Position);
end;
procedure TGLDScaleParamsFrame.SetParams(const Params: TGLDScaleParams);
begin
UD_ScaleX.Position := Params.ScaleX;
UD_ScaleY.Position := Params.ScaleY;
UD_ScaleZ.Position := Params.ScaleZ;
end;
procedure TGLDScaleParamsFrame.SetParamsFrom(Source: TObject);
begin
if Assigned(Source) and (Source is TGLDScale) then
SetParams(TGLDScale(Source).Params);
end;
procedure TGLDScaleParamsFrame.ApplyParams;
begin
if HaveScale then
TGLDScale(FDrawer.EditedModify).Params := GetParams;
end;
procedure TGLDScaleParamsFrame.ValueChangeUD(Sender: TObject);
begin
if HaveScale then
with TGLDScale(FDrawer.EditedModify) do
if Sender = UD_ScaleX then
ScaleX := UD_ScaleX.Position else
if Sender = UD_ScaleY then
ScaleY := UD_ScaleY.Position else
if Sender = UD_ScaleZ then
ScaleZ := UD_ScaleZ.Position;
end;
procedure TGLDScaleParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDScaleParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDScaleParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
if Assigned(FDrawer) then
SetParamsFrom(FDrawer.EditedModify);
end;
end.
|
unit fre_db_interface;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> 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.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage UTF8}
{$modeswitch nestedprocvars}
{$modeswitch advancedrecords}
{$interfaces corba}
//TFRE_DB_String is a AnsiString with CodePage(UTF8)
//TODO: Testsuite MAtrix for DERIVED COLLECTION FILTERS
interface
uses
Classes, SysUtils, FRE_SYSTEM,FOS_TOOL_INTERFACES,FOS_INTERLOCKED,
FOS_REDBLACKTREE_GEN,FRE_APS_INTERFACE,contnrs,fpjson,math,fre_process
{$ifdef UNIX}
,BaseUnix
{$endif}
;
type
TFRE_DB_Compresslevel = (db_CLEV_NONE,db_CLEV_FAST,db_CLEV_MAX);
TFRE_DB_GUID = FRE_SYSTEM.TFRE_DB_GUID;
TFOS_MAC_ADDR = FRE_SYSTEM.TFOS_MAC_ADDR;
var
//@ Precalculated GUIDS per DB THREAD & MainThread
GFRE_DB_MAXGUID_RESERVE_BLOCK : Integer = 10000;
//@ Compression Preset for Backup of Objects
GCFG_DB_BACKUP_COMPRESSLEVEL : TFRE_DB_Compresslevel = db_CLEV_MAX;
//@ Number of concurrent Database Backend Threads
GCFG_DB_BACKEND_THREAD_CNT : Integer = 1;
GCFG_RANDOM_BYTES_DEVICE : String = '/dev/random';
GCFG_SESSION_UNBOUND_TO : Integer = 600; //if this value is too low some browsers will be stuck in an endless loop
type
TFRE_DB_SESSION_ID = TFRE_DB_GUID_String;
var
cFRE_DB_LOGIN_APP_UID :TFRE_DB_Guid;
cFRE_DB_LOGIN_APP :TObject;
type
TFRE_DB_SIZE_TYPE = integer;
Int16 = Smallint;
Int32 = Longint;
UInt16 = word;
UInt32 = longword;
TFRE_DB_String = type AnsiString(CP_UTF8);
PFRE_DB_String = ^TFRE_DB_String;
TFRE_DB_RawByteString = RawByteString;
PNativeUint = ^NativeUint;
PNativeInt = ^NativeInt;
IFRE_DB_RIGHT = TFRE_DB_String; {a right is a string key}
TFRE_DB_ConstArray = Array of TVarRec;
TFRE_DB_LOGCATEGORY = (dblc_NONE,dblc_PERSISTANCE,dblc_PERSISTANCE_NOTIFY,dblc_DB,dblc_MEMORY,dblc_REFERENCES,dblc_EXCEPTION,dblc_SERVER,dblc_HTTP_REQ,dblc_HTTP_RES,dblc_WEBSOCK,dblc_APPLICATION,
dblc_SESSION,dblc_FLEXCOM,dblc_SERVER_DATA,dblc_WS_JSON,dblc_FLEX_IO,dblc_APSCOMM,dblc_HTTP_ZIP,dblc_HTTP_CACHE,dblc_STREAMING,dblc_QUERY,dblc_DBTDM,dblc_DBTDMRM);
TFRE_DB_Errortype_EC = (edb_OK,edb_ERROR,edb_ACCESS,edb_RESERVED,edb_NOT_FOUND,edb_DB_NO_SYSTEM,edb_EXISTS,edb_INTERNAL,edb_ALREADY_CONNECTED,edb_NOT_CONNECTED,edb_MISMATCH,edb_ILLEGALCONVERSION,edb_INDEXOUTOFBOUNDS,edb_STRING2TYPEFAILED,edb_OBJECT_REFERENCED,edb_INVALID_PARAMS,edb_UNSUPPORTED,edb_NO_CHANGE,edb_PERSISTANCE_ERROR);
TFRE_DB_FILTERTYPE = (dbf_TEXT,dbf_SIGNED,dbf_UNSIGNED,dbf_DATETIME,dbf_BOOLEAN,dbf_CURRENCY,dbf_REAL64,dbf_GUID,dbf_SCHEME,dbf_RIGHT,dbf_EMPTY);
TFRE_DB_STR_FILTERTYPE = (dbft_EXACT,dbft_PART,dbft_STARTPART,dbft_ENDPART,dbft_EXACTVALUEINARRAY); { currently only the first value of the filter is used in this modes }
TFRE_DB_NUM_FILTERTYPE = (dbnf_EXACT,dbnf_LESSER,dbnf_LESSER_EQ,dbnf_GREATER,dbnf_GREATER_EQ,dbnf_IN_RANGE_EX_BOUNDS,dbnf_IN_RANGE_WITH_BOUNDS,dbnf_AllValuesFromFilter,dbnf_OneValueFromFilter,dbnf_NoValueInFilter);
TFRE_DB_SchemeType = (dbst_INVALID,dbst_System,dbst_Extension,dbst_DB);
TFRE_DB_COMMANDTYPE = (fct_SyncRequest,fct_SyncReply,fct_AsyncRequest,fct_Error);
TFRE_DB_SUBSEC_DISPLAY_TYPE = (sec_dt_tab,sec_dt_vertical,sec_dt_hiddentab);
TFRE_DB_CHOOSER_DH = (dh_chooser_radio,dh_chooser_check,dh_chooser_combo);
TFRE_DB_STANDARD_RIGHT = (sr_BAD,sr_STORE,sr_UPDATE,sr_DELETE,sr_FETCH); //DB CORE RIGHTS
TFRE_DB_STANDARD_RIGHT_SET = set of TFRE_DB_STANDARD_RIGHT;
TFRE_DB_STANDARD_COLL = (coll_NONE,coll_USER,coll_GROUP,coll_DOMAIN,coll_WFACTION);
TFRE_DB_NameType = String[63]; // Type for named objects (not data of the DB / no unicode and fixed length)
{ TFRE_DB_Errortype }
TFRE_DB_Errortype = record
Code : TFRE_DB_Errortype_EC;
Msg : String;
Lineinfo : String;
procedure SetIt(const ecode : TFRE_DB_Errortype_EC ; const message : string ; const lineinf:string='');
function AsString:string;
end;
EFRE_DB_Exception=class(EFRE_Exception)
ErrorType : TFRE_DB_Errortype;
LineInfo : String;
constructor Create(const msg : TFRE_DB_String);
constructor Create(const et:TFRE_DB_Errortype_EC;msg:TFRE_DB_String='');
constructor Create(const et:TFRE_DB_Errortype_EC;msg:TFRE_DB_String;params:array of const);
end;
EFRE_DB_PL_Exception=class(EFRE_DB_Exception)
end;
TFRE_DB_FIELDTYPE = (fdbft_NotFound,fdbft_GUID,fdbft_Byte,fdbft_Int16,fdbft_UInt16,fdbft_Int32,fdbft_UInt32,fdbft_Int64,fdbft_UInt64,fdbft_Real32,fdbft_Real64,fdbft_Currency,fdbft_String,fdbft_Boolean,fdbft_DateTimeUTC,fdbft_Stream,fdbft_Object,fdbft_ObjLink);
TFRE_DB_INDEX_TYPE = (fdbit_Unsupported,fdbit_Unsigned,fdbit_Signed,fdbit_Real,fdbit_Text,fdbit_SpecialValue);
TFRE_DB_DISPLAY_TYPE = (dt_string,dt_date,dt_number,dt_number_pb,dt_currency,dt_icon,dt_boolean,dt_description);
TFRE_DB_MESSAGE_TYPE = (fdbmt_error,fdbmt_warning,fdbmt_info,fdbmt_confirm,fdbmt_wait);
TFRE_DB_FIELDTYPE_Array = Array of TFRE_DB_FIELDTYPE;
TFRE_DB_DISPLAY_TYPE_Array = Array of TFRE_DB_DISPLAY_TYPE;
TFRE_DB_Fieldproperty = (fp_Required,fp_Multivalues,fp_PasswordField,fp_AddConfirmation,fp_Min,fp_Max);
TFRE_DB_Fieldproperties = set of TFRE_DB_Fieldproperty;
TFRE_DB_FieldDepVisibility = (fdv_visible,fdv_hidden,fdv_none);
TFRE_DB_FieldDepEnabledState= (fdes_enabled,fdes_disabled,fdes_none);
const
CFRE_DB_FIELDDEPVISIBILITY : Array[TFRE_DB_FieldDepVisibility] of String = ('VISIBLE','HIDDEN','NONE');
CFRE_DB_FIELDDEPENABLEDSTATE : Array[TFRE_DB_FieldDepEnabledState] of String = ('ENABLED','DISABLED','NONE');
CFRE_DB_FIELDTYPE : Array[TFRE_DB_FIELDTYPE] of String = ('UNSET','GUID','BYTE','INT16','UINT16','INT32','UINT32','INT64','UINT64','REAL32','REAL64','CURRENCY','STRING','BOOLEAN','DATE','STREAM','OBJECT','OBJECTLINK');
CFRE_DB_FIELDTYPE_SHORT : Array[TFRE_DB_FIELDTYPE] of String = ( '-', 'G', 'U1', 'I2', 'U2', 'S4', 'U4', 'I8', 'U8', 'R4', 'R8', 'CU', 'SS', 'BO', 'DT', 'ST', 'OB', 'LK');
CFRE_DB_INDEX_TYPE : Array[TFRE_DB_INDEX_TYPE] of String = ('UNSUPPORTED','UNSIGNED','SIGNED','REAL','TEXT','SPECIAL');
CFRE_DB_STANDARD_RIGHT : Array[TFRE_DB_STANDARD_RIGHT] of String = ('BAD','STORE','UPDATE','DELETE','FETCH');
CFRE_DB_STANDARD_RIGHT_SHORT : Array[TFRE_DB_STANDARD_RIGHT] of String = ('B','S','U','D','F');
CFRE_DB_Errortype : Array[TFRE_DB_Errortype_EC] of String = ('OK','ERROR','ACCESS PROHIBITED','RESERVED','NOT FOUND','SYSTEM DB NOT FOUND','EXISTS','INTERNAL','ALREADY CONNECTED','NOT CONNECTED','MISMATCH','ILLEGALCONVERSION','INDEXOUTOFBOUNDS','STRING2TYPEFAILED','OBJECT IS REFERENCED','INVALID PARAMETERS','UNSUPPORTED','NO CHANGE','PERSISTANCE ERROR');
CFRE_DB_FILTERTYPE : Array[TFRE_DB_FILTERTYPE] of String = ('T','S','U','D','B','C','R','G','X','Z','E');
CFRE_DB_STR_FILTERTYPE : Array[TFRE_DB_STR_FILTERTYPE] of String = ('EX','PA','SP','EP','EXVA');
CFRE_DB_NUM_FILTERTYPE : Array[TFRE_DB_NUM_FILTERTYPE] of String = ('EX','LE','LEQ','GT','GEQ','REXB','RWIB','AVFF','OVFV','NVFF');
CFRE_DB_LOGCATEGORY : Array[TFRE_DB_LOGCATEGORY] of String = ('-','PL','PL EV','DB','MEMORY','REFLINKS','EXCEPT','SERVER','>HTTP','<HTTP','WEBSOCK','APP','SESSION','FLEXCOM','SRV DATA','WS/JSON','FC/IO','APSCOMM','HTTP ZIP','HTTP CACHE','STREAM','QUERY','DBTDM','TDMRM');
CFRE_DB_LOGCATEGORY_INI_IDENT : Array[TFRE_DB_LOGCATEGORY] of String = ('NONE','PERSISTANCE','PERSISTANCE_NOTIFY','DB','MEMORY','REFERENCES','EXCEPTION','SERVER','HTTP_REQ','HTTP_RES','WEBSOCK','APPLICATION','SESSION','FLEXCOM','SERVER_DATA','WS_JSON','FLEX_IO','APSCOMM','HTTP_ZIP','HTTP_CACHE','STREAMING','QUERY','DBTM','TDMRM');
CFRE_DB_COMMANDTYPE : Array[TFRE_DB_COMMANDTYPE] of String = ('S','SR','AR','E');
CFRE_DB_DISPLAY_TYPE : Array[TFRE_DB_DISPLAY_TYPE] of string = ('STR','DAT','NUM','PRG','CUR','ICO','BOO','DES');
CFRE_DB_MESSAGE_TYPE : array [TFRE_DB_MESSAGE_TYPE] of string = ('msg_error','msg_warning','msg_info','msg_confirm','msg_wait');
CFRE_DB_SUBSEC_DISPLAY_TYPE : array [TFRE_DB_SUBSEC_DISPLAY_TYPE] of string = ('sec_dt_tab','sec_dt_vertical','sec_dt_hiddentab');
CFRE_DB_SYS_DOMAIN_NAME = 'SYSTEM';
cFRE_DB_STKEY = '#ST#';
cFRE_DB_ST_ETAG = '#ETG#';
cFRE_DB_SYS_NOCHANGE_VAL_STR = '*$NOCHANGE*'; { used to indicate a DONT CHANGE THE FIELD in translating from JSON <-> DBO }
cFRE_DB_SYS_CLEAR_VAL_STR = '*$CLEAR*'; { used to indicate a CLEAR FIELD in translating from JSON <-> DBO }
cFRE_DB_SYS_T_LMO_TRANSID = '*$_LMOTID*'; { used in the persistence layer to mark the last id that modified the object }
cFRE_DB_SYS_PLUGIN_CONTAINER = '_$PLG';
cFRE_DB_SYS_STAT_METHODPOINTER = '*$_SMP*'; { used to call a stattransformation }
cFRE_DB_DIFFUP_SUBOBJ_EXISTS = '*$SUX*'; { sub object exists }
cFRE_DB_IGNORE_SYS_FIELD_NAMES : Array [0..0] of TFRE_DB_NameType = (cFRE_DB_SYS_T_LMO_TRANSID); { System fields in the Object, ignored on object compare, WARNING these must be uppercase(!) , do NOT add cFRE_DB_SYS_PLUGIN_CONTAINER (it must be compared) }
cFRE_DB_CLN_CHILD_CNT = '_children_count_';
cFRE_DB_CLN_CHILD_FLD = 'children';
cFRE_DB_CLN_CHILD_FLG = 'UNCHECKED';
CFRE_DB_EPSILON_DBL = 2.2204460492503131e-016; { Epsiolon for Double Compare (Zero / boolean) }
CFRE_DB_EPSILON_SGL = 1.192092896e-07; { Epsiolon for Single Compare (Zero / boolean) }
CFRE_DB_SIZE_ENCODING_SIZE = Sizeof(TFRE_DB_SIZE_TYPE);
CFRE_DB_NullGUID : TFRE_DB_GUID = ( D : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) );
CFRE_DB_MaxGUID : TFRE_DB_GUID = ( D : ($FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF ) );
cFOS_IID_COLLECTION = 'ID_COL';
cFOS_IID_DERIVED_COLL = 'ID_CDC';
cFOS_IID_SCHEME_COLL = 'ID_CSC';
cFOS_WF_GROUPS_DC = 'WF_GROUPS_DC';
CFOS_WF_DATA_COLLECTION = 'WF_DATA';
cFOS_RADIAL_SITEMAP_SCALE = 0.8;
cFRE_DB_MAX_CLIENT_CONTINUATIONS = 500;
type
{ TFRE_DB_Stream }
TFRE_DB_Stream = class(TMemoryStream)
public
destructor Destroy;override;
function AsRawByteString : TFRE_DB_RawByteString;
procedure SetFromRawByteString (const rb_string : TFRE_DB_RawByteString);
function CalcETag : ShortString;
end;
PFRE_DB_GUID = ^TFRE_DB_GUID;
TFRE_DB_GUIDArray = Array of TFRE_DB_Guid;
PFRE_DB_GUIDArray = ^TFRE_DB_GUIDArray;
TFRE_DB_ByteArray = Array of Byte;
PFRE_DB_ByteArray = ^TFRE_DB_ByteArray;
TFRE_DB_Int16Array = Array of Int16;
PFRE_DB_Int16Array = ^TFRE_DB_Int16Array;
TFRE_DB_UInt16Array = Array of UInt16;
PFRE_DB_UInt16Array = ^TFRE_DB_UInt16Array;
TFRE_DB_Int32Array = Array of Int32;
PFRE_DB_Int32Array = ^TFRE_DB_Int32Array;
TFRE_DB_UInt32Array = Array of UInt32;
PFRE_DB_UInt32Array = ^TFRE_DB_UInt32Array;
TFRE_DB_Int64Array = Array of Int64;
PFRE_DB_Int64Array = ^TFRE_DB_Int64Array;
TFRE_DB_UInt64Array = Array of UInt64;
PFRE_DB_UInt64Array = ^TFRE_DB_UInt64Array;
TFRE_DB_Real32Array = Array of Single;
PFRE_DB_Real32Array = ^TFRE_DB_Real32Array;
TFRE_DB_Real64Array = Array of Double;
PFRE_DB_Real64Array = ^TFRE_DB_Real64Array;
TFRE_DB_CurrencyArray = Array of Currency;
PFRE_DB_CurrencyArray = ^TFRE_DB_CurrencyArray;
TFRE_DB_StringArray = Array of TFRE_DB_String;
PFRE_DB_StringArray = ^TFRE_DB_StringArray;
TFRE_DB_BoolArray = Array of Boolean;
PFRE_DB_BoolArray = ^TFRE_DB_BoolArray;
TFRE_DB_DateTimeArray = Array of TFRE_DB_DateTime64;
PFRE_DB_DateTimeArray = ^TFRE_DB_DateTimeArray;
TFRE_DB_StreamArray = Array of TFRE_DB_Stream;
PFRE_DB_StreamArray = ^TFRE_DB_StreamArray;
TFRE_DB_ObjLinkArray = Array of TFRE_DB_Guid;
PFRE_DB_ObjLinkArray = ^TFRE_DB_ObjLinkArray;
PFRE_DB_NameType = ^TFRE_DB_NameType;
TFRE_DB_NameTypeRL = string[129]; // SCHEMENAME(64 + < + FIELDNAME(64) = 129 Byte (InboundLink)
// FIELDNAME(64) + > + SCHEMENAME(64) = 129 Byte (Outboundlink)
TFRE_DB_TransStepId = String[80]; // Nametype+/+number
TFRE_DB_NameTypeArray = Array of TFRE_DB_NameType;
TFRE_DB_NameTypeRLArray = Array of TFRE_DB_NameTypeRL;
TFRE_DB_NameTypeRLArrayArray = Array of TFRE_DB_NameTypeRLArray;
TFRE_DB_MimeTypeStr = string[100];
TFRE_DB_CountedGuid=record
link : TFRE_DB_Guid;
count : NativeInt;
end;
TFRE_DB_ReferencesByField=record
fieldname : TFRE_DB_NameType;
schemename : TFRE_DB_NameType;
linked_uid : TFRE_DB_GUID;
end;
{ TFRE_DB_INDEX_DEF }
TFRE_DB_INDEX_DEF=record
IndexClass : Shortstring;
IndexName : TFRE_DB_NameType;
FieldName : TFRE_DB_NameType;
FieldType : TFRE_DB_FIELDTYPE;
Unique : boolean;
AllowNulls : boolean;
UniqueNull : boolean;
IgnoreCase : boolean;
DomainIndex : boolean;
function IndexDescription : TFRE_DB_String;
function IndexDescriptionShort : TFRE_DB_String;
end;
TFRE_DB_INDEX_DEF_ARRAY=array of TFRE_DB_INDEX_DEF;
TFRE_DB_Mimetype=record
extension : string[32];
mimetype : TFRE_DB_MimeTypeStr;
end;
TFRE_DB_ObjectReferences = array of TFRE_DB_ReferencesByField;
TFRE_DB_CountedGuidArray = array of TFRE_DB_CountedGuid;
TFRE_DB_CONTENT_DESC = class;
TFRE_DB_SERVER_FUNC_DESC = class;
IFRE_DB_Object = interface;
IFRE_DB_Usersession = interface;
IFRE_DB_APPLICATION = interface;
IFRE_DB_CONNECTION = interface;
IFRE_DB_ClientFieldValidator = interface;
IFRE_DB_ObjectArray = Array of IFRE_DB_Object;
PFRE_DB_ObjectArray = ^IFRE_DB_ObjectArray;
IFRE_DB_ClientFieldValidatorArray = Array of IFRE_DB_ClientFieldValidator;
IFRE_DB_BASE = interface
procedure Finalize ;
function Implementor : TObject;
function Implementor_HC : TObject;
end;
IFRE_DB_UID_BASE = interface(IFRE_DB_BASE)
function UID : TFRE_DB_GUID;
function DomainID : TFRE_DB_GUID;
end;
IFRE_DB_COMMON = interface (IFRE_DB_BASE)
function Supports (const InterfaceSpec:ShortString ; out Intf) : Boolean;
function Supports (const InterfaceSpec:ShortString) : Boolean;
procedure IntfCast (const InterfaceSpec:ShortString ; out Intf) ; // IntfCast throws an Exception if not succesful
end;
IFRE_DB_INVOKEABLE = interface(IFRE_DB_COMMON)
function MethodExists (const name:Shortstring):Boolean;
end;
TFRE_DB_OBJECT_PLUGIN_CLASS = class of TFRE_DB_OBJECT_PLUGIN_BASE;
IFRE_DB_TEXT = interface;
{ IFRE_DB_Field }
IFRE_DB_Field = interface(IFRE_DB_BASE)
//private // ? - only for info, as interfaces dont support private methods
{utility functions}
function CloneToNewStreamable : IFRE_DB_Field; { This creates a lightweight "streamable field" copy with only certain supported function (fieldvalues,type, but no parentobject etc support }
function CloneToNewStreamableObj : IFRE_DB_Object; { encode the data as object }
function RemoveObjectLinkByUID(const to_remove_uid : TFRE_DB_GUID):boolean;
function GetAsGUID : TFRE_DB_GUID;
function GetAsByte : Byte;
function GetAsInt16 : Smallint;
function GetAsInt32 : longint;
function GetAsInt64 : int64;
function GetAsSingle : Single;
function GetAsDouble : Double;
function GetAsUInt16 : Word;
function GetAsUInt32 : longword;
function GetAsUInt64 : uint64;
function GetAsCurrency : Currency;
function GetAsDateTime : TFRE_DB_DateTime64;
function GetAsDateTimeUTC : TFRE_DB_DateTime64;
function GetAsString : TFRE_DB_String;
function GetAsBoolean : Boolean;
function GetAsObject : IFRE_DB_Object;
function GetAsStream : TFRE_DB_Stream;
function GetAsObjectLink : TFRE_DB_GUID;
procedure SetAsByte (const AValue: Byte);
procedure SetAsInt16 (const AValue: Smallint);
procedure SetAsInt32 (const AValue: longint);
procedure SetAsInt64 (const AValue: int64);
procedure SetAsUInt16 (const AValue: Word);
procedure SetAsUInt32 (const AValue: longword);
procedure SetAsUInt64 (const AValue: uint64);
procedure SetAsSingle (const AValue: Single);
procedure SetAsDouble (const AValue: Double);
procedure SetAsCurrency (const AValue: Currency);
procedure SetAsDateTime (const AValue: TFRE_DB_Datetime64);
procedure SetAsDateTimeUTC (const AValue: TFRE_DB_Datetime64);
procedure SetAsGUID (const AValue: TFRE_DB_GUID);
procedure SetAsObject (const AValue: IFRE_DB_Object); //
procedure SetAsStream (const AValue: TFRE_DB_Stream);
procedure SetAsString (const AValue: TFRE_DB_String); //
procedure SetAsBoolean (const AValue: Boolean);//
procedure SetAsObjectLink (const AValue: TFRE_DB_GUID);
function GetAsGUIDArray : TFRE_DB_GUIDArray; //
function GetAsByteArray : TFRE_DB_ByteArray; //
function GetAsInt16Array : TFRE_DB_Int16Array; //
function GetAsInt32Array : TFRE_DB_Int32Array; //
function GetAsInt64Array : TFRE_DB_Int64Array; //
function GetAsUInt16Array : TFRE_DB_UInt16Array; //
function GetAsUInt32Array : TFRE_DB_UInt32Array; //
function GetAsUInt64Array : TFRE_DB_UInt64Array; //
function GetAsSingleArray : TFRE_DB_Real32Array; //
function GetAsDoubleArray : TFRE_DB_Real64Array; //
function GetAsDateTimeArray : TFRE_DB_DateTimeArray; //
function GetAsDateTimeArrayUTC : TFRE_DB_DateTimeArray; //
function GetAsCurrencyArray : TFRE_DB_CurrencyArray; //
function GetAsStringArray : TFRE_DB_StringArray; //
function GetAsStreamArray : TFRE_DB_StreamArray; //
function GetAsBooleanArray : TFRE_DB_BoolArray; //
function GetAsObjectArray : IFRE_DB_ObjectArray; //
function GetAsObjectLinkArray : TFRE_DB_ObjLinkArray;//
procedure ReverseObjectArray ;
function GetAsGUIDList (idx: Integer): TFRE_DB_GUID;
function GetAsByteList (idx: Integer): Byte;
function GetAsInt16List (idx: Integer): Smallint;
function GetAsInt32List (idx: Integer): longint;
function GetAsInt64List (idx: Integer): int64;
function GetAsUInt16List (idx: Integer): Word;
function GetAsUInt32List (idx: Integer): longword;
function GetAsUInt64List (idx: Integer): uint64;
function GetAsSingleList (idx: Integer): Single;
function GetAsDoubleList (idx: Integer): Double;
function GetAsDateTimeList (idx: Integer): TFRE_DB_DateTime64;
function GetAsDateTimeListUTC (idx: Integer): TFRE_DB_DateTime64;
function GetAsCurrencyList (idx: Integer): Currency;
function GetAsStringList (idx: Integer): TFRE_DB_String;
function GetAsStreamList (idx: Integer): TFRE_DB_Stream;
function GetAsBooleanList (idx: Integer): Boolean;
function GetAsObjectList (idx: Integer): IFRE_DB_Object;
function GetAsObjectLinkList (idx: Integer): TFRE_DB_GUID;
procedure SetAsByteArray (const AValue: TFRE_DB_ByteArray);
procedure SetAsInt16Array (const AValue: TFRE_DB_Int16Array);
procedure SetAsInt32Array (const AValue: TFRE_DB_Int32Array);
procedure SetAsInt64Array (const AValue: TFRE_DB_Int64Array);
procedure SetAsSingleArray (const AValue: TFRE_DB_Real32Array);
procedure SetAsUInt16Array (const AValue: TFRE_DB_UInt16Array);
procedure SetAsUInt32Array (const AValue: TFRE_DB_UInt32Array);
procedure SetAsUInt64Array (const AValue: TFRE_DB_UInt64Array);
procedure SetAsCurrencyArray (const AValue: TFRE_DB_CurrencyArray);
procedure SetAsDateTimeArray (const AValue: TFRE_DB_DateTimeArray);
procedure SetAsDateTimeArrayUTC (const AValue: TFRE_DB_DateTimeArray);
procedure SetAsDoubleArray (const AValue: TFRE_DB_Real64Array);
procedure SetAsGUIDArray (const AValue: TFRE_DB_GUIDArray);
procedure SetAsObjectArray (const AValue: IFRE_DB_ObjectArray);
procedure SetAsStreamArray (const AValue: TFRE_DB_StreamArray);
procedure SetAsStringArray (const AValue: TFRE_DB_StringArray);
procedure SetAsBooleanArray (const AValue: TFRE_DB_BoolArray);
procedure SetAsObjectLinkArray (const Avalue: TFRE_DB_ObjLinkArray);
procedure SetAsByteList (idx: Integer; const AValue: Byte);
procedure SetAsDateTimeUTCList (idx: Integer; const AValue: TFRE_DB_DateTime64);
procedure SetAsInt16List (idx: Integer; const AValue: Smallint);
procedure SetAsInt32List (idx: Integer; const AValue: longint);
procedure SetAsInt64List (idx: Integer; const AValue: int64);
procedure SetAsSingleList (idx: Integer; const AValue: Single);
procedure SetAsUInt16List (idx: Integer; const AValue: Word);
procedure SetAsUInt32List (idx: Integer; const AValue: longword);
procedure SetAsUInt64List (idx: Integer; const AValue: uint64);
procedure SetAsCurrencyList (idx: Integer; const AValue: Currency);
procedure SetAsDateTimeList (idx: Integer; const AValue: TFRE_DB_Datetime64);
procedure SetAsDateTimeListUTC (idx: Integer; const AValue: TFRE_DB_Datetime64);
procedure SetAsDoubleList (idx: Integer; const AValue: Double);
procedure SetAsGUIDList (idx: Integer; const AValue: TFRE_DB_GUID);
procedure SetAsObjectList (idx: Integer; const AValue: IFRE_DB_Object);
procedure SetAsStreamList (idx: Integer; const AValue: TFRE_DB_Stream);
procedure SetAsStringList (idx: Integer; const AValue: TFRE_DB_String);
procedure SetAsBooleanList (idx: Integer; const AValue: Boolean);
procedure SetAsObjectLinkList (idx: Integer; const AValue: TFRE_DB_GUID);
function AsObjectArrayJSONString: TFRE_DB_String; { Deliver an Object Field, or a TFRE_DB_OBJECTLIST as plain JSON Array}
function AsPlugin (const plugclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; out plugin):boolean;
//public info
function FieldType : TFRE_DB_FIELDTYPE;
function FieldTypeAsString : TFRE_DB_String;
function ValueCount : NativeInt; { delivers the count or if fake object list as subobject the faked count}
function ValueCountReal : NativeInt; { delivers 1 if object }
function IsUIDField : boolean;
function IsDomainIDField : boolean;
function IsSystemField : boolean;
function IsObjectField : boolean;
function IsSchemeField : boolean;
function IsObjectArray : boolean;
property AsGUID : TFRE_DB_GUID read GetAsGUID write SetAsGUID;
property AsByte : Byte read GetAsByte write SetAsByte;
property AsInt16 : Smallint read GetAsInt16 write SetAsInt16;
property AsUInt16 : Word read GetAsUInt16 write SetAsUInt16;
property AsInt32 : longint read GetAsInt32 write SetAsInt32;
property AsUInt32 : longword read GetAsUInt32 write SetAsUInt32;
property AsInt64 : int64 read GetAsInt64 write SetAsInt64;
property AsUInt64 : uint64 read GetAsUInt64 write SetAsUInt64;
property AsReal32 : Single read GetAsSingle write SetAsSingle;
property AsReal64 : Double read GetAsDouble write SetAsDouble;
property AsCurrency : Currency read GetAsCurrency write SetAsCurrency;
property AsString : TFRE_DB_String read GetAsString write SetAsString;
property AsBoolean : Boolean read GetAsBoolean write SetAsBoolean;
property AsDateTime : TFRE_DB_DateTime64 read GetAsDateTime write SetAsDateTime;
property AsDateTimeUTC : TFRE_DB_DateTime64 read GetAsDateTimeUTC write SetAsDateTimeUTC;
property AsStream : TFRE_DB_Stream read GetAsStream write SetAsStream; // Stores only reference to stream;
property AsObject : IFRE_DB_Object read GetAsObject write SetAsObject;
property AsObjectLink : TFRE_DB_GUID read GetAsObjectLink write SetAsObjectLink;
property AsGUIDArr : TFRE_DB_GUIDArray read GetAsGUIDArray write SetAsGUIDArray;
property AsByteArr : TFRE_DB_ByteArray read GetAsByteArray write SetAsByteArray;
property AsInt16Arr : TFRE_DB_Int16Array read GetAsInt16Array write SetAsInt16Array;
property AsUInt16Arr : TFRE_DB_UInt16Array read GetAsUInt16Array write SetAsUInt16Array;
property AsInt32Arr : TFRE_DB_Int32Array read GetAsInt32Array write SetAsInt32Array;
property AsUInt32Arr : TFRE_DB_UInt32Array read GetAsUInt32Array write SetAsUInt32Array;
property AsInt64Arr : TFRE_DB_Int64Array read GetAsInt64Array write SetAsInt64Array;
property AsUInt64Arr : TFRE_DB_UInt64Array read GetAsUInt64Array write SetAsUInt64Array;
property AsReal32Arr : TFRE_DB_Real32Array read GetAsSingleArray write SetAsSingleArray;
property AsReal64Arr : TFRE_DB_Real64Array read GetAsDoubleArray write SetAsDoubleArray;
property AsCurrencyArr : TFRE_DB_CurrencyArray read GetAsCurrencyArray write SetAsCurrencyArray;
property AsStringArr : TFRE_DB_StringArray read GetAsStringArray write SetAsStringArray;
property AsBooleanArr : TFRE_DB_BoolArray read GetAsBooleanArray write SetAsBooleanArray;
property AsDateTimeArr : TFRE_DB_DateTimeArray read GetAsDateTimeArray write SetAsDateTimeArray;
property AsDateTimeUTCArr : TFRE_DB_DateTimeArray read GetAsDateTimeArrayUTC write SetAsDateTimeArrayUTC;
property AsStreamArr : TFRE_DB_StreamArray read GetAsStreamArray write SetAsStreamArray; // Stores only reference to stream;
property AsObjectArr : IFRE_DB_ObjectArray read GetAsObjectArray write SetAsObjectArray;
property AsObjectLinkArray : TFRE_DB_ObjLinkArray read GetAsObjectLinkArray write SetAsObjectLinkArray;
//property AsObjectLinkArrayObjects : IFRE_DB_ObjectArray read GetAsObjectLinkArrayObj write SetAsObjectLinkArrayObj;
property AsGUIDItem [idx:Integer] : TFRE_DB_GUID read GetAsGUIDList write SetAsGUIDList;
property AsByteItem [idx:Integer] : Byte read GetAsByteList write SetAsByteList;
property AsInt16Item [idx:Integer] : Smallint read GetAsInt16List write SetAsInt16List;
property AsUInt16Item [idx:Integer] : Word read GetAsUInt16List write SetAsUInt16List;
property AsInt32Item [idx:Integer] : longint read GetAsInt32List write SetAsInt32List;
property AsUInt32Item [idx:Integer] : longword read GetAsUInt32List write SetAsUInt32List;
property AsInt64Item [idx:Integer] : int64 read GetAsInt64List write SetAsInt64List;
property AsUInt64Item [idx:Integer] : uint64 read GetAsUInt64List write SetAsUInt64List;
property AsReal32Item [idx:Integer] : Single read GetAsSingleList write SetAsSingleList;
property AsReal64Item [idx:Integer] : Double read GetAsDoubleList write SetAsDoubleList;
property AsCurrencyItem [idx:Integer] : Currency read GetAsCurrencyList write SetAsCurrencyList;
property AsStringItem [idx:Integer] : TFRE_DB_String read GetAsStringList write SetAsStringList;
property AsBooleanItem [idx:Integer] : Boolean read GetAsBooleanList write SetAsBooleanList;
property AsDateTimeItem [idx:Integer] : TFRE_DB_DateTime64 read GetAsDateTimeList write SetAsDateTimeList;
property AsDateTimeUTCItem [idx:Integer] : TFRE_DB_DateTime64 read GetAsDateTimeListUTC write SetAsDateTimeListUTC;
property AsStreamItem [idx:Integer] : TFRE_DB_Stream read GetAsStreamList write SetAsStreamList; // Stores only reference to stream;
property AsObjectItem [idx:Integer] : IFRE_DB_Object read GetAsObjectList write SetAsObjectList;
property AsObjectLinkItem [idx:Integer] : TFRE_DB_GUID read GetAsObjectLinkList write SetAsObjectLinkList;
procedure CloneFromField (const Field:IFRE_DB_FIELD);
function CheckOutObject : IFRE_DB_Object;
function CheckOutObjectArray : IFRE_DB_ObjectArray;
function CheckOutObjectArrayItem (const idx : NAtiveInt): IFRE_DB_Object;
procedure Add2ArrayFromField (const sourcefield:IFRE_DB_Field);
procedure AddGuid (const value : TFRE_DB_GUID);
procedure AddByte (const value : Byte);
procedure AddInt16 (const value : SmallInt);
procedure AddUInt16 (const value : Word);
procedure AddInt32 (const value : longint);
procedure AddUInt32 (const value : longword);
procedure AddInt64 (const value : Int64);
procedure AddUInt64 (const value : UInt64);
procedure AddReal32 (const value : single);
procedure AddReal64 (const value : double);
procedure AddCurrency (const value : Currency);
procedure AddString (const value : TFRE_DB_String);
procedure AddBoolean (const value : Boolean);
procedure AddDateTime (const value : TFRE_DB_DateTime64);
procedure AddDateTimeUTC (const value : TFRE_DB_DateTime64);
procedure AddStream (const value : TFRE_DB_Stream);
procedure AddObject (const value : IFRE_DB_Object);
procedure AddObjectLink (const value : TFRE_DB_GUID);
procedure RemoveGuid (const idx : integer);
procedure RemoveByte (const idx : integer);
procedure RemoveInt16 (const idx : integer);
procedure RemoveUInt16 (const idx : integer);
procedure RemoveInt32 (const idx : integer);
procedure RemoveUInt32 (const idx : integer);
procedure RemoveInt64 (const idx : integer);
procedure RemoveUInt64 (const idx : integer);
procedure RemoveReal32 (const idx : integer);
procedure RemoveReal64 (const idx : integer);
procedure RemoveCurrency (const idx : integer);
procedure RemoveString (const idx : integer);
procedure RemoveBoolean (const idx : integer);
procedure RemoveDateTimeUTC (const idx : integer);
procedure RemoveStream (const idx : integer);
procedure RemoveObject (const idx : integer);
procedure RemoveObjectLink (const idx : integer);
procedure SetAsEmptyStringArray ;
procedure Stream2String (var raw_string:TFRE_DB_RawByteString);
function AsStringDump : TFRE_DB_String;
function FieldName : TFRE_DB_NameType;
procedure Clear (const dont_free_streams_and_objects:boolean=false);
procedure RemoveIndex (const idx:integer);
procedure IntfCast (const InterfaceSpec:ShortString ; out Intf) ; // Interpret as Object and then -> IntfCast throws an Exception if not succesful
function AsDBText :IFRE_DB_TEXT;
function IsEmptyArray : boolean;
function ParentObject : IFRE_DB_Object;
function GetUpdateObjectUIDPath : TFRE_DB_GUIDArray; { This is only set in case of a "clone" stream field (standalone field only) }
function GetInCollectionArrayUSL : TFRE_DB_StringArray; { This is only set in case of a "clone" stream field (standalone field only) }
function GetUpdateObjSchemePath : TFRE_DB_StringArray; { This is only set in case of a "clone" stream field (standalone field only) }
function GetUpdateObjFieldPath : TFRE_DB_StringArray; { This is only set in case of a "clone" stream field (standalone field only) }
function IsSpecialClearMarked : Boolean; { if a string field and has special clear string mark set => true (usefull for json web interface) }
function ConvAsSignedArray : TFRE_DB_Int64Array; { for filtering purposes }
function ConvAsUnsignedArray : TFRE_DB_UInt64Array; { for filtering purposes }
function ConvAsCurrencyArray : TFRE_DB_CurrencyArray; { for filtering purposes }
function ConvAsReal64Array : TFRE_DB_Real64Array; { for filtering purposes }
function GetFieldPath : TFRE_DB_StringArray;
function GetFieldPathAsString : TFRE_DB_String;
end;
IFRE_DB_SCHEMEOBJECT = interface;
IFRE_DB_Enum = interface;
IFRE_DB_COLLECTION = interface;
IFRE_DB_FieldSchemeDefinition = interface;
IFRE_DB_DOMAIN = interface;
IFRE_DB_USER_RIGHT_TOKEN = interface;
TFRE_DB_ObjCompareEventType = (cev_FieldDeleted,cev_FieldAdded,cev_FieldChanged);
TObjectNestedIterator = procedure (const obj : TObject) is nested;
TObjectNestedDataIterator = procedure (const obj : TObject ; const data : Pointer) is nested;
IFRE_DB_FieldIterator = procedure (const obj : IFRE_DB_Field) is nested;
IFRE_DB_FieldIteratorBrk = function (const obj : IFRE_DB_Field):boolean is nested;
IFRE_DB_Obj_Iterator = procedure (const obj : IFRE_DB_Object) is nested;
IFRE_DB_Obj_NameIterator = procedure (const fieldname : TFRE_DB_NameType ; const obj : IFRE_DB_Object) is nested;
IFRE_DB_ObjectIteratorBrk = procedure (const obj:IFRE_DB_Object; var halt:boolean) is nested;
IFRE_DB_ObjectIteratorBrkProgress = procedure (const obj:IFRE_DB_Object; var halt:boolean ; const current,max : NativeInt) is nested;
IFRE_DB_UpdateChange_Iterator = procedure (const is_child_update : boolean ; const update_obj : IFRE_DB_Object ; const update_type :TFRE_DB_ObjCompareEventType ;const new_field, old_field: IFRE_DB_Field) is nested;
IFRE_DB_ObjUid_IteratorBreak = procedure (const uid : TFRE_DB_GUID ; var halt : boolean) is nested;
IFRE_DB_Scheme_Iterator = procedure (const obj : IFRE_DB_SchemeObject) is nested;
IFRE_DB_SchemeFieldDefIterator = procedure (const obj : IFRE_DB_FieldSchemeDefinition) is nested;
IFRE_DB_Enum_Iterator = procedure (const obj : IFRE_DB_Enum) is nested;
IFRE_DB_ClientFieldValidator_Iterator = procedure (const obj : IFRE_DB_ClientFieldValidator) is nested;
IFRE_DB_Coll_Iterator = procedure (const coll: IFRE_DB_COLLECTION) is nested;
IFRE_DB_Domain_Iterator = procedure (const obj : IFRE_DB_Domain) is nested;
TFRE_DB_StreamingCallback = procedure (const uid,fieldname: TFRE_DB_String ; const stream:TFRE_DB_Stream) is nested;
TFRE_DB_PhaseProgressCallback = procedure (const phase,detail,header : shortstring ; const cnt,max: integer) is nested;
TFRE_DB_SimpleLineCallback = procedure (const line:string) is nested;
TFRE_DB_Guid_Iterator = procedure (const obj:TFRE_DB_GUID) is nested;
TFRE_DB_ObjectEx = class;
TFRE_DB_RIF_RESULT = class;
TFRE_DB_ObjectClassEx = class of TFRE_DB_ObjectEx;
TFRE_DB_BaseClass = class of TFRE_DB_Base;
TFRE_DB_ObjectClassExArray = Array of TFRE_DB_ObjectClassEx;
TFRE_DB_FIELD_EXPRESSION = function(const field:IFRE_DB_Field):boolean is nested;
IFRE_DB_InvokeMethod = function (const Input:IFRE_DB_Object):IFRE_DB_Object;
IFRE_DB_InvokeMethodCallbackObjectEx = function (const obj: TFRE_DB_ObjectEx ; const Input:IFRE_DB_Object):IFRE_DB_Object;
IFRE_DB_InvokeInstanceMethod = function (const Input:IFRE_DB_Object):IFRE_DB_Object of object;
IFRE_DB_WebInstanceMethod = function (const Input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession ; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object of object;
IFRE_DB_InvokeClassMethod = function (const Input:IFRE_DB_Object):IFRE_DB_Object of object;
IFRE_DB_WebClassMethod = function (const Input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession ; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object of object;
IFRE_DB_RemInstanceMethod = procedure (const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE) of object;
IFRE_DB_WebTimerMethod = procedure (const ses: IFRE_DB_Usersession) of object;
IFRE_DB_SessionDataCallback = procedure (const ses: IFRE_DB_UserSession ; const data : IFRE_DB_Object) of object;
IFRE_DB_CS_CALLBACK = procedure (const Input:IFRE_DB_Object) of Object;
IFRE_DB_InvokeProcedure = procedure (const Input:IFRE_DB_Object) of Object;
TFRE_DB_RIF_Method = function (const running_context : TObject): TFRE_DB_RIF_RESULT of object;
TFRE_DB_Object_Properties = (fop_SYSTEM,fop_READ_ONLY,fop_VOLATILE,fop_STORED_IMMUTABLE,fop_IN_SYSTEM_DB); { fop_SYSTEM=static/read only, fop_IN_SYSTEM_DB = from System DB masterdata}
TFRE_DB_Object_PropertySet = set of TFRE_DB_Object_Properties;
TFRE_InputGroupDefType=(igd_Bad,igd_Field,igd_UsedGroup,igd_UsedSubGroup,igd_BlockGroup);
TFRE_DB_SESSIONSTATE =(sta_BAD,sta_ActiveNew,sta_ReUsed);
R_Depfieldfield = record
depFieldName : TFRE_DB_NameType;
disablesField : Boolean;
end;
R_EnumDepfieldfield = record
depFieldName : TFRE_DB_NameType;
enumValue : String;
visible : TFRE_DB_FieldDepVisibility;
enabledState : TFRE_DB_FieldDepEnabledState;
capTransKey : String;
valKey : String;
valParams : IFRE_DB_Object;
end;
TFRE_DB_Depfielditerator = procedure (const depfield : R_Depfieldfield) is nested;
TFRE_DB_EnumDepfielditerator = procedure (const depfield : R_EnumDepfieldfield) is nested;
//IFRE_DB_EXTENSION_GRP loosely groups the necessary
//DB Apps Registery Functions and extension functions, plus dependencies
//to prepare and query db extensions on startup
IFRE_DB_EXTENSION_GRP = interface
function GetExtensionName : TFRE_DB_String;
procedure RegisterExtensionAndDependencies ;
procedure InitializeDatabaseForExtension (const db_name : string ; const user,pass:string);
procedure RemoveForExtension (const db_name : string ; const user,pass:string);
procedure GenerateTestdataForExtension (const db_name : string ; const user,pass:string);
procedure DoUnitTestforExtension (const db_name : string ; const user,pass:string);
end;
TFRE_DB_Usersession = class;
TFRE_DB_OBJECT_PLUGIN_BASE = class;
IFRE_DB_EXTENSION_Iterator = procedure (const ext:IFRE_DB_EXTENSION_GRP) is nested;
IFRE_DB_EXTENSION_RegisterCB = procedure ;
IFRE_DB_EXTENSION_INITDB_CB = procedure (const dbname :string; const user,pass:string);
IFRE_DB_EXTENSION_REMOVE_CB = procedure (const dbname :string; const user,pass:string);
IFRE_DB_PLUGIN_ITERATOR = procedure (const plugin : TFRE_DB_OBJECT_PLUGIN_BASE) is nested;
TFRE_DB_COMMAND_STATUS = (cdcs_OK,cdcs_TIMEOUT,cdcs_ERROR);
TFRE_DB_SessionIterator = procedure (const session : TFRE_DB_UserSession ; var halt : boolean) is nested ;
TFRE_DB_CONT_HANDLER = procedure(const DATA : IFRE_DB_Object ; const status:TFRE_DB_COMMAND_STATUS ; const error_txt:string) of object;
{ IFRE_DB_NetServer }
IFRE_DB_NetServer=interface
function ExistsUserSessionForUserLocked (const username:string;out other_session:TFRE_DB_UserSession):boolean;
function ExistsUserSessionForKeyLocked (const key :string;out other_session:TFRE_DB_UserSession):boolean;
function FetchPublisherSessionLocked (const rcall,rmeth:TFRE_DB_NameType;out ses : TFRE_DB_UserSession ; out right:TFRE_DB_String):boolean;
function FetchPublisherSessionLockedMachine (const machineid: TFRE_DB_GUID ; const rcall,rmeth:TFRE_DB_NameType;out ses : TFRE_DB_UserSession ; out right:TFRE_DB_String):boolean;
function FetchPublisherSessionLockedMachineMac (const machine_mac: TFRE_DB_NameType ; const rcall,rmeth:TFRE_DB_NameType;out ses : TFRE_DB_UserSession ; out right:TFRE_DB_String):boolean;
function FetchSessionByIdLocked (const sesid : TFRE_DB_SESSION_ID ; var ses : TFRE_DB_UserSession):boolean;
procedure ForAllSessionsLocked (const iterator : TFRE_DB_SessionIterator ; var halt : boolean); // If halt, then the dir and the session remain locked!
function GetImpersonatedDatabaseConnection (const dbname,username,pass:TFRE_DB_String ; out dbs:IFRE_DB_CONNECTION ; const allowed_classes : TFRE_DB_StringArray):TFRE_DB_Errortype;
function GetDBWithServerRights (const dbname:TFRE_DB_String ; out dbs:IFRE_DB_CONNECTION):TFRE_DB_Errortype;
function CheckUserNamePW (username,pass:TFRE_DB_String ; const allowed_classes : TFRE_DB_StringArray) : TFRE_DB_Errortype;
function SendDelegatedContentToClient (sessionID : TFRE_DB_SESSION_ID ; const content : TFRE_DB_CONTENT_DESC):boolean; { Send content in behalf of session }
function SubscribeGlobalEvent (const sessionID : TFRE_DB_SESSION_ID ; const ev_name: TFRE_DB_NameType):boolean;
function UnsubscribeGlobalEvent (const sessionID : TFRE_DB_SESSION_ID ; const ev_name: TFRE_DB_NameType):boolean;
function PublishGlobalEvent (const ev_name: TFRE_DB_NameType; const ev_data: IFRE_DB_Object):boolean;
end;
IFRE_FLEX_CLIENT=interface
function SendServerCommand (const InvokeClass,InvokeMethod : String;const uidpath:Array of TFRE_DB_GUID;const DATA: IFRE_DB_Object;const ContinuationCB : TFRE_DB_CONT_HANDLER=nil;const timeout:integer=5000) : boolean;
function AnswerSyncCommand (const command_id : QWord ; const data : IFRE_DB_Object) : boolean;
function AnswerSyncError (const command_id : QWord ; const error : TFRE_DB_String) : boolean;
end;
{ IFRE_DB_EXTENSION_MNGR }
IFRE_DB_SYS_CONNECTION = interface;
IFRE_DB_EXTENSION_MNGR = interface
function GetExtensionList : IFOS_STRINGS;
procedure RegisterExtensions4DB (const list: IFOS_STRINGS);
procedure InitDatabase4Extensions (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure GenerateTestData4Exts (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure GenerateUnitTestsdata (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure Remove4Extensions (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure RegisterNewExtension (const extension_name : String ; const MetaRegistrationFunction : IFRE_DB_EXTENSION_RegisterCB ; const MetaRegisterInitDBFunction : IFRE_DB_EXTENSION_INITDB_CB; const MetaRegisterRemoveFunction : IFRE_DB_EXTENSION_REMOVE_CB ; const MetaGentestdata : IFRE_DB_EXTENSION_INITDB_CB = nil ; const MetaGenUnitTest : IFRE_DB_EXTENSION_INITDB_CB = nil);
procedure Finalize ;
end;
{ IFRE_DB_Object }
TFRE_DB_STATUS_PLUGIN = class;
IFRE_DB_Object = interface(IFRE_DB_INVOKEABLE)
['IFREDBO']
function _InternalDecodeAsField : IFRE_DB_Field; { create a streaming only lightweight field from the encoding object }
procedure _InternalSetMediator (const mediator : TFRE_DB_ObjectEx);
procedure ForAllPlugins (const plugin_iterator : IFRE_DB_PLUGIN_ITERATOR);
function HasPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS): boolean; { delivers the internal reference of the plugin, if avail, dont free it (!) }
function HasPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; out plugin): boolean; { delivers the internal reference of the plugin, if avail, dont free it (!) }
procedure GetPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; out plugin); { delivers the internal reference of the plugin, if avail, dont free it (!), raises exception if not attached }
function GetStatusPlugin : TFRE_DB_STATUS_PLUGIN;
function AttachPlugin (const plugin : TFRE_DB_OBJECT_PLUGIN_BASE ; const raise_if_existing : boolean=true) : Boolean; { sets a plugin instance of the specified class }
function RemovePlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; const raise_if_not_existing : boolean=true) : Boolean;
function GetUCTHashed : Shortstring;
function UIDP : PByte;
function PUID : PFRE_DB_Guid;
function ObjectRoot : IFRE_DB_Object; // = the last parent with no parent
function GetScheme (const raise_non_existing:boolean=false): IFRE_DB_SchemeObject;
function GetAsJSON (const without_reserved_fields:boolean=false;const full_dump:boolean=false;const stream_cb:TFRE_DB_StreamingCallback=nil): TJSONData;
function GetAsJSONString (const without_reserved_fields:boolean=false;const full_dump:boolean=false;const stream_cb:TFRE_DB_StreamingCallback=nil;const pretty:boolean=true):TFRE_DB_String;
function CloneToNewObject (const create_new_uids:boolean=false): IFRE_DB_Object;
procedure ForAllFields (const iter:IFRE_DB_FieldIterator;const without_system_fields:boolean=false);
procedure ForAllFieldsBreak (const iter:IFRE_DB_FieldIteratorBrk;const without_system_fields:boolean=false);
procedure ForAllObjects (const iter:IFRE_DB_Obj_Iterator);
procedure ForAllObjectsBreak (const iter:IFRE_DB_ObjectIteratorBrk);
procedure ForAllObjectsFieldName (const iter:IFRE_DB_Obj_NameIterator);
function GetDescriptionID (const full_uid_path : boolean=true): String;
function UID : TFRE_DB_GUID;
procedure SetUID (const newuid:TFRE_DB_GUID);
function UCT : TFRE_DB_String;
procedure SetUCT (const tag : TFRE_DB_String);
function DomainID : TFRE_DB_GUID;
procedure SetDomainID (const domid:TFRE_DB_GUID);
function UID_String : TFRE_DB_GUID_String;
function NeededSize : TFRE_DB_SIZE_TYPE;
function Parent : IFRE_DB_Object;
function ParentField : IFRE_DB_FIELD;
function AsString :TFRE_DB_String;
function Field (const name:TFRE_DB_NameType):IFRE_DB_FIELD;
function FieldOnlyExistingObj (const name:TFRE_DB_NameType):IFRE_DB_Object;
function FieldOnlyExistingObject (const name:TFRE_DB_NameType; var obj:IFRE_DB_Object):boolean;
function FieldOnlyExistingObjAs (const name:TFRE_DB_NameType; const classref : TFRE_DB_BaseClass ; var outobj) : boolean;
function FieldOnlyExisting (const name:TFRE_DB_NameType;var fld:IFRE_DB_FIELD):boolean;
function FieldOnlyExistingUID (const name:TFRE_DB_NameType;const def : PFRE_DB_GUID=nil):TFRE_DB_GUID;
function FieldOnlyExistingByte (const name:TFRE_DB_NameType;const def : Byte=0):Byte;
function FieldOnlyExistingInt16 (const name:TFRE_DB_NameType;const def : Int16=-1):Int16;
function FieldOnlyExistingUInt16 (const name:TFRE_DB_NameType;const def : UInt16=0):UInt16;
function FieldOnlyExistingInt32 (const name:TFRE_DB_NameType;const def : Int32=-1):Int32;
function FieldOnlyExistingUInt32 (const name:TFRE_DB_NameType;const def : UInt32=0):UInt32;
function FieldOnlyExistingInt64 (const name:TFRE_DB_NameType;const def : Int64=-1):Int64;
function FieldOnlyExistingUInt64 (const name:TFRE_DB_NameType;const def : UInt64=0):UInt64;
function FieldOnlyExistingReal32 (const name:TFRE_DB_NameType;const def : Single=-1):Single;
function FieldOnlyExistingReal64 (const name:TFRE_DB_NameType;const def : Double=-1):Double;
function FieldOnlyExistingCurrency (const name:TFRE_DB_NameType;const def : Currency=0):Currency;
function FieldOnlyExistingString (const name:TFRE_DB_NameType;const def : String=''):String;
function FieldOnlyExistingBoolean (const name:TFRE_DB_NameType;const def : Boolean=false):Boolean;
function FieldPath (const name:TFRE_DB_String;const dont_raise_ex:boolean=false):IFRE_DB_FIELD;
function FieldPathCreate (const name:TFRE_DB_String):IFRE_DB_FIELD;
function FieldPathExists (const name:TFRE_DB_String):Boolean;
function FieldPathExists (const name: TFRE_DB_String;out fld:IFRE_DB_Field): Boolean;
function FieldPathExistsAndNotMarkedClear (const name:TFRE_DB_String):Boolean;
function FieldPathExistsAndNotMarkedClear (const name: TFRE_DB_String;out fld:IFRE_DB_Field): Boolean;
function FieldPathListFormat (const field_list:TFRE_DB_NameTypeArray;const formats : TFRE_DB_String;const empty_val: TFRE_DB_String) : TFRE_DB_String;
function FieldCount (const without_system_fields:boolean): SizeInt;
function DeleteField (const name:TFRE_DB_String):Boolean;
procedure ClearAllFields ;
procedure ClearAllFieldsExcept (const fieldnames : array of TFRE_DB_NameType);
function FieldExists (const name:TFRE_DB_String):boolean;
function FieldExistsAndNotMarkedClear (const name:TFRE_DB_String):boolean;
procedure DumpToStrings (const strings:TStrings;indent:integer=2);
function DumpToString (indent:integer=2;const dump_length_max:Integer=0):TFRE_DB_String;
function GetFormattedDisplay : TFRE_DB_String;
function FormattedDisplayAvailable : boolean;
function SubFormattedDisplayAvailable : boolean;
function GetSubFormattedDisplay (indent:integer=4):TFRE_DB_String;
function SchemeClass : TFRE_DB_NameType;
function IsA (const schemename : shortstring):Boolean;
function IsA (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX) : Boolean;
function IsA (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX ; out obj ) : Boolean;
procedure AsClass (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX ; out obj );
function IsObjectRoot : Boolean;
function IsPluginContainer : Boolean;
function IsPlugin : Boolean;
procedure SaveToFile (const filename:TFRE_DB_String);
procedure SaveToFileHandle (const handle : THandle);
function ReferencesObjectsFromData : Boolean;
function GetFieldListFilter (const field_type:TFRE_DB_FIELDTYPE):TFRE_DB_StringArray;
function GetUIDPath :TFRE_DB_StringArray; { Top Down Path of UIDS StringValues }
function GetUIDPathUA :TFRE_DB_GUIDArray; { Top Down Path of UIDS Values }
function GetFieldValuePathString (const fieldname:TFRE_DB_NameType):TFRE_DB_StringArray; { Top Down Path of Field Values }
function Invoke (const method:TFRE_DB_String;const input:IFRE_DB_Object ; const ses : IFRE_DB_Usersession ; const app : IFRE_DB_APPLICATION ; const conn : IFRE_DB_CONNECTION):IFRE_DB_Object;
function Mediator : TFRE_DB_ObjectEx;
procedure Set_ReadOnly ;
procedure CopyField (const obj:IFRE_DB_Object;const field_name:String);
procedure CopyToMemory (memory : Pointer);
function ForAllObjectsBreakHierarchic (const iter:IFRE_DB_ObjectIteratorBrk):boolean; // includes root object (self)
function FetchObjByUID (const childuid:TFRE_DB_GUID ; var obj : IFRE_DB_Object):boolean;
function FetchObjWithStringFieldValue (const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; var obj: IFRE_DB_Object; ClassnameToMatch: ShortString=''): boolean;
function FetchObjWithStringFieldValueAs (const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; const exclasstyp : TFRE_DB_ObjectClassEx ; var obj): boolean;
procedure SetAllSimpleObjectFieldsFromObject (const source_object : IFRE_DB_Object); // only first level, no uid, domid, obj, objlink fields
function CloneToNewObjectWithoutSubobjects (const generate_new_uids: boolean=false): IFRE_DB_Object;
procedure CheckoutFromObject ;
procedure SetGenericUCTTags (const check_unique_tagging : boolean=false);
function GetDesc : IFRE_DB_TEXT;
procedure SetDesc (const AValue: IFRE_DB_TEXT);
function GetName : TFRE_DB_String;
procedure SetName (const AValue: TFRE_DB_String);
property ObjectName : TFRE_DB_String read GetName write SetName;
property Description : IFRE_DB_TEXT read GetDesc write SetDesc;
end;
TFRE_DB_TEXT_SUBTYPE=(tst_Short,tst_Long,tst_Hint,tst_Key);
IFRE_DB_TEXT=interface(IFRE_DB_COMMON)
['IFREDBTXT']
function GetHint: TFRE_DB_String;
function GetLong: TFRE_DB_String;
function Getshort: TFRE_DB_String;
function GetTKey: TFRE_DB_String;
procedure SetHint(const AValue: TFRE_DB_String);
procedure Setlong(const AValue: TFRE_DB_String);
procedure ClearLong;
procedure ClearShort;
procedure ClearHint;
procedure SetShort(const AValue: TFRE_DB_String);
procedure SetTKey(const AValue: TFRE_DB_String);
property LongText : TFRE_DB_String read GetLong write Setlong;
property ShortText : TFRE_DB_String read Getshort write SetShort;
property Hint : TFRE_DB_String read GetHint write SetHint;
property TranslationKey : TFRE_DB_String read GetTKey write SetTKey;
procedure SetupText (const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
end;
{ IFRE_DB_COLLECTION }
IFRE_DB_COLLECTION=interface(IFRE_DB_COMMON)
[cFOS_IID_COLLECTION]
function UID : TFRE_DB_GUID;
function ExistsInCollection (const ouid:TFRE_DB_GUID ; const has_fetch_rights : boolean=true):boolean;
procedure ForAll (const func:IFRE_DB_Obj_Iterator);
procedure ForAllBreak (const func:IFRE_DB_ObjectIteratorBrk ; var halt : boolean);
function Remove (const ouid:TFRE_DB_GUID):TFRE_DB_Errortype;
function Store (const new_obj:IFRE_DB_Object):TFRE_DB_Errortype;
function Update (const dbo:IFRE_DB_Object):TFRE_DB_Errortype;
function Fetch (const ouid:TFRE_DB_GUID;out dbo:IFRE_DB_Object): boolean; deprecated ; { deprectated naming }
function FetchInCollection (const ouid:TFRE_DB_GUID;out dbo:IFRE_DB_Object): boolean;
function CollectionName (const unique:boolean=false): TFRE_DB_NameType;
function ItemCount : Int64;
function Count : Int64; deprecated ; { replaced by ItemCount }
function First : IFRE_DB_Object;
function Last : IFRE_DB_Object;
function GetItem (const num:uint64):IFRE_DB_Object;
procedure ClearCollection ; { clear with respect to userid }
function DefineIndexOnField (const FieldName : TFRE_DB_NameType;const FieldType:TFRE_DB_FIELDTYPE;const unique:boolean; const ignore_content_case:boolean=false;const index_name:TFRE_DB_NameType='def' ; const allow_null_value : boolean=true ; const unique_null_values : boolean=false ; const is_a_domain_index : boolean=false):TFRE_DB_Errortype;
function DefineIndexOnField (const IndexDef : TFRE_DB_INDEX_DEF):TFRE_DB_Errortype;
function GetIndexDefinition (const index_name : TFRE_DB_NameType):TFRE_DB_INDEX_DEF;
function DropIndex (const index_name : TFRE_DB_NameType):TFRE_DB_Errortype;
function IndexExists (const index_name:TFRE_DB_NameType):boolean;
function ExistsIndexed (const query_value : TFRE_DB_String ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def'):Boolean; deprecated ; // for the string fieldtype
function ExistsIndexedFieldval (const fld : IFRE_DB_Field ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; { preferred } // for all supported field types
function ExistsIndexedText (const query_value : TFRE_DB_String ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; // for the string fieldtype
function ExistsIndexedSigned (const query_value : int64 ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; // for the signed fieldtypes
function ExistsIndexedUnsigned (const query_value : UInt64 ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; // for the unsigned fieldtypes
function ExistsIndexedReal (const query_value : Double ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; // for the floating point fieldtypes
function GetIndexedObj (const query_value : TFRE_DB_String ; out obj : IFRE_DB_Object ; const index_name:TFRE_DB_NameType='def'):boolean; deprecated; // for the string fieldtype
function GetIndexedObjFieldval (const fld : IFRE_DB_Field ; out obj : IFRE_DB_Object ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; { preferred }
function GetIndexedObjGuid (const query_value : TFRE_DB_GUID ; out obj : IFRE_DB_Object ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjText (const query_value : TFRE_DB_String ; out obj : IFRE_DB_Object ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjSigned (const query_value : int64 ; out obj : IFRE_DB_Object ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjUnsigned (const query_value : Uint64 ; out obj : IFRE_DB_Object ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjReal (const query_value : Double ; out obj : IFRE_DB_Object ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjsFieldval (const fld : IFRE_DB_Field ; out obj : IFRE_DB_ObjectArray ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; { preferred }
function GetIndexedObjsGuid (const query_value : TFRE_DB_GUID ; out obj : IFRE_DB_ObjectArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjsText (const query_value : TFRE_DB_String ; out obj : IFRE_DB_ObjectArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjsSigned (const query_value : int64 ; out obj : IFRE_DB_ObjectArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjsUnsigned (const query_value : Uint64 ; out obj : IFRE_DB_ObjectArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedObjsReal (const query_value : Double ; out obj : IFRE_DB_ObjectArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUID (const query_value : TFRE_DB_String ; out fuid : TFRE_DB_GUID ; const index_name:TFRE_DB_NameType='def'):boolean; deprecated;
function GetIndexedUIDFieldval (const fld : IFRE_DB_Field ; out fuid : TFRE_DB_GUID ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; { preferred }
function GetIndexedUIDText (const query_value : TFRE_DB_String ; out fuid : TFRE_DB_GUID ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDSigned (const query_value : int64 ; out fuid : TFRE_DB_GUID ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDUnsigned (const query_value : Uint64 ; out fuid : TFRE_DB_GUID ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDReal (const query_value : Double ; out fuid : TFRE_DB_GUID ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDsFieldval (const fld : IFRE_DB_Field ; out fuids : TFRE_DB_GUIDArray ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt; { preferred }
function GetIndexedUIDsText (const query_value : TFRE_DB_String ; out fuids : TFRE_DB_GUIDArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDsSigned (const query_value : int64 ; out fuids : TFRE_DB_GUIDArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDsUnsigned (const query_value : Uint64 ; out fuids : TFRE_DB_GUIDArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function GetIndexedUIDsReal (const query_value : Double ; out fuids : TFRE_DB_GUIDArray ; const val_is_null : boolean=false ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function RemoveIndexedFieldval (const fld : IFRE_DB_Field ; const index_name:TFRE_DB_NameType='def' ; const domain_uid_string : TFRE_DB_GUID_String = '') : NativeInt; { preferred }
function RemoveIndexedText (const query_value : TFRE_DB_String ; const index_name:TFRE_DB_NameType='def' ; const val_is_null : boolean = false ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function RemoveIndexedSigned (const query_value : int64 ; const index_name:TFRE_DB_NameType='def' ; const val_is_null : boolean = false ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function RemoveIndexedUnsigned (const query_value : QWord ; const index_name:TFRE_DB_NameType='def' ; const val_is_null : boolean = false ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
function RemoveIndexedReal (const query_value : Double ; const index_name:TFRE_DB_NameType='def' ; const val_is_null : boolean = false ; const domain_uid_string : TFRE_DB_GUID_String = ''):NativeInt;
procedure GetAllUids (var uids:TFRE_DB_GUIDArray);
procedure GetAllObjs (out objs:IFRE_DB_ObjectArray);
procedure ForAllIndexed (const func : IFRE_DB_ObjectIteratorBrk ; var halt : boolean ; const index_name:TFRE_DB_NameType='def';const ascending:boolean=true; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexedFieldvalRange (const min_field,max_field : IFRE_DB_Field ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt : boolean ; const index_name:TFRE_DB_NameType='def';const ascending:boolean=true; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexedSignedRange (const min_value,max_value : int64 ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt:boolean ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexedUnsignedRange (const min_value,max_value : QWord ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt:boolean ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexedTextRange (const min_value,max_value : TFRE_DB_String ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt:boolean ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexedRealRange (const min_value,max_value : Double ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt:boolean ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const min_is_null : boolean = false ; const max_is_max : boolean = false ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
procedure ForAllIndexPrefixString (const prefix : TFRE_DB_String ; const iterator : IFRE_DB_ObjectIteratorBrk ; var halt:boolean ; const index_name : TFRE_DB_NameType ; const ascending: boolean = true ; const max_count : NativeInt=0 ; skipfirst : NativeInt=0 ; const domain_uid_string : TFRE_DB_GUID_String = '');
function IsVolatile : Boolean;
end;
IFRE_DB_TRANSFORMOBJECT = interface;
TFRE_DB_TRANS_COLL_FILTER_KEY = string[31];
TFRE_DB_CACHE_DATA_KEY = shortstring;
{ TFRE_DB_TRANS_COLL_DATA_KEY }
TFRE_DB_TRANS_COLL_DATA_KEY = record
CollName : TFRE_DB_NameType;
DC_Name : TFRE_DB_NameType;
orderkey : TFRE_DB_Nametype;
filterkey : TFRE_DB_TRANS_COLL_FILTER_KEY;
FSealed : Boolean;
procedure Seal;
function IsSealed : Boolean;
function GetFullKeyString : TFRE_DB_CACHE_DATA_KEY; { includes filterkey, full spec of cached data }
function GetOrderKeyPart : TFRE_DB_CACHE_DATA_KEY; { includes ordering upon basedata }
function GetBaseDataKey : TFRE_DB_CACHE_DATA_KEY; { includes only basedata identification }
end;
{ TFRE_DB_SESSION_DC_RANGE_MGR_KEY }
TFRE_DB_SESSION_DC_RANGE_MGR_KEY = record
SessionID : TFRE_DB_SESSION_ID;
DataKey : TFRE_DB_TRANS_COLL_DATA_KEY;
Parenthash : TFRE_DB_NameTypeRL;
procedure Setup4QryId (const sid : TFRE_DB_SESSION_ID ; const ok : TFRE_DB_TRANS_COLL_DATA_KEY ; const fk : TFRE_DB_TRANS_COLL_FILTER_KEY ; const pp : TFRE_DB_String); { coming from a query spec, check that the rm fits the query}
function GetRmKeyAsString : TFRE_DB_CACHE_DATA_KEY; { sessionid@derivedcollection/parenthash }
function GetFullKeyString : TFRE_DB_CACHE_DATA_KEY; { sessionid@parentcollection/derivedcollection/reflinkspec/orderhash/filterhash }
procedure SetupFromQryID (qryid : TFRE_DB_CACHE_DATA_KEY);
end;
//TFRE_DB_DC_STRINGFIELDKEY_LIST = array of TFRE_DB_DC_STRINGFIELDKEY;
TFRE_DB_CHART_TYPE = (fdbct_pie,fdbct_column,fdbct_line);
TFRE_DB_LIVE_CHART_TYPE = (fdblct_line,fdblct_sampledline,fdblct_column);
TFRE_COLLECTION_DISPLAY_TYPE = (cdt_Invalid,cdt_Listview,cdt_Chooser);
TFRE_COLLECTION_GRID_DISPLAY_FLAG = (cdgf_ShowSearchbox,cdgf_Editable,cdgf_ColumnResizeable,cdgf_ColumnHideable,cdgf_ColumnDragable,cdgf_Details,cdgf_Children,cdgf_Multiselect);
TFRE_COLLECTION_TREE_DISPLAY_FLAG = (cdtf_None);
TFRE_COLLECTION_GRID_DISPLAY_FLAGS = set of TFRE_COLLECTION_GRID_DISPLAY_FLAG;
TFRE_COLLECTION_TREE_DISPLAY_FLAGS = set of TFRE_COLLECTION_TREE_DISPLAY_FLAG;
IFRE_DB_TRANSDATA_CHANGE_NOTIFIER = interface
end;
TFRE_DB_DC_FILTER_DEFINITION_BASE = class;
TFRE_DB_DC_ORDER_DEFINITION_BASE = class;
IFRE_DB_SIMPLE_TRANSFORM = interface;
{ IFRE_DB_DERIVED_COLLECTION }
IFRE_DB_DERIVED_COLLECTION=interface
[cFOS_IID_DERIVED_COLL]
function UID : TFRE_DB_GUID;
function Implementor : TObject;
function ItemCount : Int64;
function First : IFRE_DB_Object;
function Last : IFRE_DB_Object;
function FetchIndexed (const idx:NativeInt) : IFRE_DB_Object;
function FetchInDerived (const ouid:TFRE_DB_GUID;out dbo:IFRE_DB_Object): boolean; { honors rights and serverside filters, delivers the transformed(!) object !!}
procedure ForAllDerived (const func:IFRE_DB_Obj_Iterator); { honors rights and serverside filters, delivers the transformed(!) object !!}
function CollectionName (const unique:boolean=false): TFRE_DB_NameType;
function GetCollectionTransformKey : TFRE_DB_NameTypeRL; { deliver a key which identifies transformed data depending on ParentCollection and Transformation}
procedure BindSession (const session : TFRE_DB_UserSession);
procedure SetDefaultOrderField (const field_name:TFRE_DB_String ; const ascending : boolean);
procedure RemoveAllFilterFields ;
procedure RemoveAllFiltersPrefix (const prefix:string);
procedure SetDeriveParent (const coll:IFRE_DB_COLLECTION; const idField: String='uid');
procedure SetDeriveTransformation (const tob:IFRE_DB_SIMPLE_TRANSFORM);
function GetDeriveTransformation : IFRE_DB_SIMPLE_TRANSFORM;
//{
// This Type is only usefull as a Detail/Dependend Grid, as it needs a input Dependency Object
// Deliver all Objects which are pointed to by the input "Dependency" object,
// or all Objects which point to the the input "Dependency" object,
// via a schemelinkdefinition chain : Outbound ['TFRE_DB_SCHEME>DOMAINDILINK', ... ] or Inbound (common) ['TFRE_DB_USER<DOMAINIDLINK']
//}
procedure SetUseDependencyAsUidFilter (const field_to_filter : TFRE_DB_NameType ; const negate : boolean=false ; const dependency_reference : string = 'uids');
procedure SetDisplayType (const CollectionDisplayType : TFRE_COLLECTION_DISPLAY_TYPE ; const Flags:TFRE_COLLECTION_GRID_DISPLAY_FLAGS;const title:TFRE_DB_String;const item_menu_func: TFRE_DB_SERVER_FUNC_DESC=nil;const item_details_func: TFRE_DB_SERVER_FUNC_DESC=nil; const grid_item_notification: TFRE_DB_SERVER_FUNC_DESC=nil; const tree_menu_func: TFRE_DB_SERVER_FUNC_DESC=nil; const drop_func: TFRE_DB_SERVER_FUNC_DESC=nil; const drag_func: TFRE_DB_SERVER_FUNC_DESC=nil);
procedure SetParentToChildLinkField (const fieldname : TFRE_DB_NameTypeRL); { Define a Child/Parent Parent/Child relation via Reflinks syntax is FROMFIELD>TOSCHEME or FROMSCHEME<FROMFIELD, the scheme could be empty }
procedure SetParentToChildLinkField (const fieldname : TFRE_DB_NameTypeRL ; const skipclasses : Array of TFRE_DB_NameType);
procedure SetParentToChildLinkField (const fieldname : TFRE_DB_NameTypeRL ; const skipclasses : Array of TFRE_DB_NameType ; const filterclasses : Array of TFRE_DB_NameType);
procedure SetParentToChildLinkField (const fieldname : TFRE_DB_NameTypeRL ; const skipclasses : Array of TFRE_DB_NameType ; const filterclasses : Array of TFRE_DB_NameType ; const stop_on_explicit_leave_classes : Array of TFRE_DB_NameType);
function GetDisplayDescription : TFRE_DB_CONTENT_DESC;
function GetStoreDescription : TFRE_DB_CONTENT_DESC;
function getDescriptionStoreId : String;
procedure AddSelectionDependencyEvent (const derived_collection_name : TFRE_DB_NameType ; const ReferenceID :TFRE_DB_NameType='uids'); {On selection change a dependency "filter" object is generated and sent to the derived collection}
procedure RefreshClientviewManually ; { do last WEB query again, respect changed filters ... }
//@ Set a String Filter, which can be used before or after the transformation
//@ filterkey = ID of the Filter / field_name : on which field the filter works / filtertype: how the filter works
//function AddUIDFieldFilter (const filter_key,field_name:TFRE_DB_String;const values:array of TFRE_DB_GUID ;const number_compare_type : TFRE_DB_NUM_FILTERTYPE):TFRE_DB_Errortype;
//function RemoveFilter (const filter_key :TFRE_DB_String):TFRE_DB_Errortype;
function Filters : TFRE_DB_DC_FILTER_DEFINITION_BASE;
function Orders : TFRE_DB_DC_ORDER_DEFINITION_BASE;
procedure Finalize ;
end;
IFRE_DB_SCHEME_COLLECTION=interface(IFRE_DB_COLLECTION)
[cFOS_IID_SCHEME_COLL]
end;
IFRE_DB_TRANSFORMOBJECT = interface(IFRE_DB_BASE)
['IFDBTO']
end;
IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION = procedure (const ut : IFRE_DB_USER_RIGHT_TOKEN ; const transformed_object : IFRE_DB_Object ; const session_data : IFRE_DB_Object;const langres: array of TFRE_DB_String) of object;
IFRE_DB_QUERY_SELECTOR_FUNCTION = procedure (const ref_objects: IFRE_DB_ObjectArray; const input_object,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray) of object;
IFRE_DB_QUERY_SELECTOR_FUNCTION_NESTED = procedure (const ref_objects: IFRE_DB_ObjectArray; const input_object,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray) is nested;
IFRE_DB_OBJECT_SIMPLE_CALLBACK = procedure (const input, output : IFRE_DB_Object;const langres: TFRE_DB_StringArray) of object;
IFRE_DB_OBJECT_SIMPLE_CALLBACK_NESTED = procedure (const input, output : IFRE_DB_Object;const langres: TFRE_DB_StringArray) is nested;
IFRE_DB_SIMPLE_TRANSFORM=interface(IFRE_DB_TRANSFORMOBJECT)
['IFDBST']
procedure SetSimpleFuncTransformNested (const callback : IFRE_DB_OBJECT_SIMPLE_CALLBACK_NESTED;const langres: array of TFRE_DB_String); { may also be used for static methods (non object methods) }
procedure SetSimpleFuncTransformNested (const callback : IFRE_DB_OBJECT_SIMPLE_CALLBACK_NESTED;const langres: TFRE_DB_StringArray); { may also be used for static methods (non object methods) }
procedure SetSimpleFuncTransform (const callback : IFRE_DB_OBJECT_SIMPLE_CALLBACK;const langres: array of TFRE_DB_String);
procedure SetSimpleFuncTransform (const callback : IFRE_DB_OBJECT_SIMPLE_CALLBACK;const langres: TFRE_DB_StringArray);
procedure AddCollectorscheme (const format:TFRE_DB_String;const in_fieldlist:TFRE_DB_NameTypeArray;const out_field:TFRE_DB_String;const output_title:TFRE_DB_String='';const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const fieldSize: Integer=1;const hide_in_output : boolean=false);
procedure AddFulltextFilterOnTransformed (const fieldlist:array of TFRE_DB_NameType); { takes the text rep of the fields (asstring), concatenates them into 'FTX_SEARCH' }
procedure AddOutputFieldUntransformed (const fieldname:TFRE_DB_String;const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const iconID:String='';const openIconID:String='';const tooltipID:String='');
procedure AddOneToOnescheme (const fieldname:TFRE_DB_String;const out_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const showEnumCaption:Boolean=true; const fieldSize: Integer=1;const iconID:String='';const openIconID:String='';const default_value:TFRE_DB_String='';const filterValues:TFRE_DB_StringArray=nil;const tooltipID:String='';const hide_in_output : boolean=false);
procedure AddPluginField (const Pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; const pluginfieldname : TFRE_DB_NameType; const out_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const showEnumCaption:Boolean=true;const fieldSize: Integer=1;const iconID:String='';const openIconID:String='';const default_value:TFRE_DB_String='';const filterValues: TFRE_DB_StringArray=nil;const tooltipID:String=''; const hide_in_output : boolean=false);
procedure AddStatisticToOnescheme (const fieldname:TFRE_DB_String;const out_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const display:Boolean=true;const fieldSize: Integer=1;const default_value:TFRE_DB_String='');
procedure AddMultiToOnescheme (const in_fieldlist:TFRE_DB_NameTypeArray;const out_field:TFRE_DB_String;const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const iconID:String='';const openIconID:String='';const default_value:TFRE_DB_String='';const tooltipID:String='';const hide_in_output : boolean=false);
procedure AddProgressTransform (const valuefield:TFRE_DB_String;const out_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const textfield:TFRE_DB_String='';const out_text:TFRE_DB_String='';const maxValue:Single=100;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1);
procedure AddConstString (const out_field,value:TFRE_DB_String;const display: Boolean=false;const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const hide_in_output : boolean=false);
procedure AddDBTextToOne (const fieldname:TFRE_DB_String;const which_text : TFRE_DB_TEXT_SUBTYPE ; const out_field:TFRE_DB_String;const output_title:TFRE_DB_String='';const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const hide_in_output : boolean=false);
procedure AddDomainName (const out_field:TFRE_DB_String='domainname';const output_title:TFRE_DB_String='';const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const filterValues: TFRE_DB_StringArray=nil;const hide_in_output : boolean=false);
procedure AddMatchingReferencedField (const ref_field_chain: array of TFRE_DB_NameTypeRL ; const target_field:TFRE_DB_String;const output_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const display:Boolean=true;const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const iconID:String='';const default_value:TFRE_DB_String='';const filterValues:TFRE_DB_StringArray=nil;const tooltipID:String=''; const hide_in_output : boolean=false; const linkFieldName:TFRE_DB_NameType='uid'; const allow_derived_classes : boolean=true);
procedure AddMatchingReferencedField (const ref_field : TFRE_DB_NameTypeRL ; const target_field:TFRE_DB_String;const output_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const display:Boolean=true;const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const iconID:String='';const default_value:TFRE_DB_String='';const filterValues:TFRE_DB_StringArray=nil;const tooltipID:String=''; const hide_in_output : boolean=false; const linkFieldName:TFRE_DB_NameType='uid'; const allow_derived_classes : boolean=true);
procedure AddMatchingReferencedFieldArray (const ref_field_chain: array of TFRE_DB_NameTypeRL;const target_field:TFRE_DB_String;const output_field:TFRE_DB_String='';const output_title:TFRE_DB_String='';const display:Boolean=true;const gui_display_type:TFRE_DB_DISPLAY_TYPE=dt_string;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const iconID:String='';const default_value:TFRE_DB_String='';const filterValues:TFRE_DB_StringArray=nil;const tooltipID:String='';const hide_in_output : boolean=false; const linkFieldName:TFRE_DB_NameType='uid'; const allow_derived_classes : boolean=true);
procedure AddMatchingReferencedObjPlugin (const ref_field_chain: array of TFRE_DB_NameTypeRL;const pluginclass :TFRE_DB_OBJECT_PLUGIN_CLASS ; const output_field:TFRE_DB_String=''; const allow_derived_classes : boolean=true);
procedure AddReferencedFieldQuery (const func : IFRE_DB_QUERY_SELECTOR_FUNCTION;const ref_field_chain: array of TFRE_DB_NameTypeRL ; const output_fields:array of TFRE_DB_String;const output_titles:array of TFRE_DB_String;const langres: array of TFRE_DB_String;const gui_display_type:array of TFRE_DB_DISPLAY_TYPE;const display:Boolean=true;const sortable:Boolean=false; const filterable:Boolean=false;const fieldSize: Integer=1;const hide_in_output: boolean=false; const allow_derived_classes : boolean=true);
procedure SetFinalRightTransformFunction (const func : IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION;const langres: array of TFRE_DB_String); { set a function that changes the object after, transfrom, order, and filter as last step before data deliverance }
procedure GetFinalRightTransformFunction (out func : IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION;out langres: TFRE_DB_StringArray);
end;
{ IFRE_DB_FieldSchemeDefinition }
IFRE_DB_FieldSchemeDefinition=interface //(IFRE_DB_BASE)
['IFDBFSD']
function GetFieldName : TFRE_DB_NameType;
function GetFieldType : TFRE_DB_FIELDTYPE;
function GetHasMin : Boolean;
function GetHasMax : Boolean;
function GetMaxValue : Int64;
function GetMinValue : Int64;
function GetSubSchemeName : TFRE_DB_NameType;
function GetMultiValues : Boolean;
function GetRequired : Boolean;
function GetValidator (var validator: IFRE_DB_ClientFieldValidator):boolean;
function getValidatorParams : IFRE_DB_Object;
function GetEnum (var enum : IFRE_DB_Enum) : boolean;
procedure SetHasMin (AValue: Boolean);
procedure SetHasMax (AValue: Boolean);
procedure SetMultiValues (AValue: Boolean);
procedure SetRequired (AValue: Boolean);
function GetIsPass : Boolean;
function GetAddConfirm : Boolean;
function GetFieldProperties : TFRE_DB_FieldProperties;
procedure SetFieldProperties (AValue: TFRE_DB_FieldProperties);
function SetupFieldDef (const is_required:boolean;const is_multivalue:boolean=false;const enum_key:TFRE_DB_NameType='';const validator_key:TFRE_DB_NameType='';const is_pass:Boolean=false; const add_confirm:Boolean=false ; const validator_params : IFRE_DB_Object=nil):IFRE_DB_FieldSchemeDefinition;
function SetupFieldDefNum (const is_required:boolean;const min_value:Int64;const max_value:Int64):IFRE_DB_FieldSchemeDefinition;
function SetupFieldDefNumMin(const is_required:boolean;const min_value:Int64):IFRE_DB_FieldSchemeDefinition;
function SetupFieldDefNumMax(const is_required:boolean;const max_value:Int64):IFRE_DB_FieldSchemeDefinition;
procedure addDepField (const fieldName: TFRE_DB_String;const disablesField: Boolean=true);
procedure addEnumDepField (const fieldName: TFRE_DB_String;const enumValue:String;const visible:TFRE_DB_FieldDepVisibility=fdv_none;const enabledState:TFRE_DB_FieldDepEnabledState=fdes_none;const cap_trans_key: String='';const validator_key:TFRE_DB_NameType='';const validator_params: IFRE_DB_Object=nil);
property FieldName :TFRE_DB_NameType read GetFieldName;
property FieldType :TFRE_DB_FIELDTYPE read GetFieldType;
property SubschemeName :TFRE_DB_NameType read GetSubSchemeName;
function GetSubScheme :IFRE_DB_SchemeObject;
property Required :Boolean read GetRequired write SetRequired;
property MultiValues :Boolean read GetMultiValues write SetMultiValues;
property hasMin :Boolean read GetHasMin write SetHasMin;
property hasMax :Boolean read GetHasMax write SetHasMax;
function ValidateField (const field_to_check:IFRE_DB_FIELD;const raise_exception:boolean=true):boolean;
procedure ForAllDepfields (const depfielditerator : TFRE_DB_Depfielditerator);
procedure ForAllEnumDepfields(const depfielditerator : TFRE_DB_EnumDepfielditerator);
property FieldProperties :TFRE_DB_FieldProperties read GetFieldProperties write SetFieldProperties;
property minValue :Int64 read GetMinValue;
property maxValue :Int64 read GetMaxValue;
property IsPass :Boolean read GetIsPass;
property AddConfirm :Boolean read GetAddConfirm;
end;
IFRE_DB_NAMED_OBJECT_PLAIN = interface(IFRE_DB_UID_BASE)
['IFDBNO']
function GetDesc : IFRE_DB_TEXT;
procedure SetDesc (const AValue: IFRE_DB_TEXT);
function GetName : TFRE_DB_String;
procedure SetName (const AValue: TFRE_DB_String);
property ObjectName : TFRE_DB_String read GetName write SetName;
property Description : IFRE_DB_TEXT read GetDesc write SetDesc;
end;
IFRE_DB_Enum=interface(IFRE_DB_NAMED_OBJECT_PLAIN)
['IFDBE']
function Setup (const infoText: IFRE_DB_TEXT): IFRE_DB_Enum;
procedure addEntry (const value:TFRE_DB_String;const cap_trans_key: TFRE_DB_String);
function getEntries :IFRE_DB_ObjectArray;
function getCaptions(const conn: IFRE_DB_CONNECTION):TFRE_DB_StringArray;
function getCaption (const conn: IFRE_DB_CONNECTION; const value: TFRE_DB_String):TFRE_DB_String;
function CheckField (const field_to_check:IFRE_DB_FIELD;const raise_exception:boolean):boolean;
end;
{ IFRE_DB_COMMAND }
IFRE_DB_COMMAND = interface;
TFRE_DB_CMD_Request = procedure(const sender:TObject; const CMD : IFRE_DB_COMMAND) of object;
IFRE_DB_COMMAND_REQUEST_ANSWER_SC = interface(IFRE_DB_BASE)
['IFDBCRASC']
procedure Send_ServerClient (const dbc : IFRE_DB_COMMAND);
procedure DeactivateSessionBinding (const from_session : boolean=false);
procedure UpdateSessionBinding (const new_session : TObject);
function GetInfoForSessionDesc : String;
function GetChannel : IFRE_APSC_CHANNEL;
end;
IFRE_DB_COMMAND=interface(IFRE_DB_BASE)
['IFDBCMD']
function GetBinDataKey: string;
function GetCommandID : UInt64;
function GetCType : TFRE_DB_COMMANDTYPE;
function GetEText : TFRE_DB_String;
function GetFatalClose : Boolean;
function GetChangeSessionKey : TFRE_DB_SESSION_ID;
procedure SetBinDataKey (AValue: string);
procedure SetChangeSessionKey (AValue: TFRE_DB_SESSION_ID);
procedure SetFatalClose (AValue: Boolean);
procedure SetEText (AValue: TFRE_DB_String);
procedure SetAnswerInterface (const answer_interface : IFRE_DB_COMMAND_REQUEST_ANSWER_SC); //
function GetAnswerInterface :IFRE_DB_COMMAND_REQUEST_ANSWER_SC;
procedure SetCType (AValue: TFRE_DB_COMMANDTYPE);
function GetData : IFRE_DB_Object;
//procedure SetIfCmd (AValue: Boolean);
function GetUidPath : TFRE_DB_GUIDArray;
//function GetIfCmd : Boolean;
procedure SetUidPath (AValue: TFRE_DB_GUIDArray);
function GetIsAnswer : Boolean;
function GetIsClient : Boolean;
procedure SetCommandID (const AValue: UInt64);
procedure SetData (const AValue: IFRE_DB_Object);
function GetInvokeClass : String;
function GetInvokeMethod : String;
procedure SetInvokeClass (AValue: String);
procedure SetInvokeMethod (AValue: String);
procedure SetIsAnswer (const AValue: Boolean);
procedure SetIsClient (const AValue: Boolean);
function NeededSize : TFRE_DB_SIZE_TYPE;
procedure CopyToMemory (memory : Pointer);
property Answer : Boolean read GetIsAnswer write SetIsAnswer;
property ClientCommand : Boolean read GetIsClient write SetIsClient;
function CheckoutData : IFRE_DB_Object;
//function AsJSONString : TFRE_DB_RawByteString;
function AsDBODump : TFRE_DB_RawByteString;
//public
property CommandID : UInt64 read GetCommandID write SetCommandID;
property InvokeClass : String read GetInvokeClass write SetInvokeClass;
property InvokeMethod : String read GetInvokeMethod write SetInvokeMethod;
property Data : IFRE_DB_Object read GetData write SetData;
property UidPath : TFRE_DB_GUIDArray read GetUidPath write SetUidPath;
property CommandType : TFRE_DB_COMMANDTYPE read GetCType write SetCType;
property ErrorText : TFRE_DB_String read GetEText write SetEText;
property FatalClose : Boolean read GetFatalClose write SetFatalClose;
property ChangeSession : TFRE_DB_SESSION_ID read GetChangeSessionKey write SetChangeSessionKey;
property BinaryDataKey : string read GetBinDataKey write SetBinDataKey;
end;
{ IFRE_DB_ROLE }
IFRE_DB_ROLE = interface(IFRE_DB_NAMED_OBJECT_PLAIN)
['IFDBRIGR']
function GetDomain (const conn : IFRE_DB_CONNECTION): TFRE_DB_NameType;
procedure AddRight (const right : IFRE_DB_RIGHT);
function GetIsInternal : Boolean;
function GetIsDisabled : Boolean;
function GetRightNames : TFRE_DB_StringArray;
procedure AddRightsFromRole (const role : IFRE_DB_ROLE);
procedure SetIsInternal (AValue: Boolean);
procedure SetIsDisabled (AValue: Boolean);
property isInternal : Boolean read GetIsInternal write SetIsInternal; { This role is used internally, and should not be or specially be presented to the user }
property isDisabled : Boolean read GetIsDisabled write SetIsDisabled; { This role is disabled,for users where the userdomain=the role domain
after a new instatiation of a user right token, the user gets not the rights of this role }
end;
IFRE_DB_USER=interface;
{ IFRE_DB_USER_RIGHT_TOKEN }
IFRE_DB_USER_RIGHT_TOKEN=interface
function Implementor : TObject;
function GetSysDomainID : TFRE_DB_GUID;
function GetMyDomainID (const sysadmin2defaultdomain : boolean=false): TFRE_DB_GUID;
function GetDefaultDomainID : TFRE_DB_GUID;
function GetDomainID (const domainname:TFRE_DB_NameType):TFRE_DB_GUID;
function GetDomainNameByUid (const domainid:TFRE_DB_GUID):TFRE_DB_NameType;
function GetUserGroupIDS : TFRE_DB_GUIDArray;
function GetUserUID : TFRE_DB_GUID;
function GetUserUIDP : PFRE_DB_GUID;
function GetDomainLoginKey : TFRE_DB_String;
function CheckStdRightAndCondFinalize (const dbi : IFRE_DB_Object ; const sr : TFRE_DB_STANDARD_RIGHT ; const without_right_check: boolean=false;const cond_finalize:boolean=true) : TFRE_DB_Errortype;
function CheckStdRightSetUIDAndClass (const obj_uid, obj_domuid: TFRE_DB_GUID; const check_classname: ShortString; const sr: TFRE_DB_STANDARD_RIGHT_SET): TFRE_DB_Errortype;
function CheckGenRightSetUIDAndClass (const obj_uid, obj_domuid: TFRE_DB_GUID; const check_classname: ShortString; const sr: TFRE_DB_StringArray): TFRE_DB_Errortype;
{ Safe case, use for single domain use cases }
function CheckClassRight4MyDomain (const right_name:TFRE_DB_String;const classtyp: TClass):boolean; { and systemuser and systemdomain}
{ Many domain case, add additional checks for the specific domain }
function CheckClassRight4AnyDomain (const right_name:TFRE_DB_String;const classtyp: TClass):boolean;
function CheckClassRight4Domain (const right_name:TFRE_DB_String;const classtyp: TClass;const domainKey:TFRE_DB_String=''):boolean;
function GetDomainsForRight (const right_name:TFRE_DB_String): TFRE_DB_GUIDArray;
function GetDomainsForClassRight (const right_name:TFRE_DB_String;const classtyp: TClass): TFRE_DB_GUIDArray;
{ Stdrights Many domain case, add additional checks for the specific domain }
function CheckClassRight4MyDomain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass):boolean;
function CheckClassRight4AnyDomain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass):boolean;
//function CheckClassRight4Domain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass;const domainKey:TFRE_DB_String=''):boolean; { specific domain }
//function CheckClassRight4DomainId (const right_name: TFRE_DB_String; const classtyp: TClass; const domain: TFRE_DB_GUID): boolean;
//function CheckClassRight4DomainId (const std_right: TFRE_DB_STANDARD_RIGHT; const classtyp: TClass; const domain: TFRE_DB_GUID): boolean;
function CheckClassRight4Domain (const std_right : TFRE_DB_STANDARD_RIGHT ; const classtyp : TClass ; const domainKey:TFRE_DB_String=''):boolean; { specific domain }
function CheckClassRight4Domain (const std_right : TFRE_DB_STANDARD_RIGHT ; const rclassname: ShortString ; const domainKey:TFRE_DB_String=''):boolean; { specific domain }
function CheckClassRight4DomainId (const right_name: TFRE_DB_String ; const classtyp : TClass ; const domain: TFRE_DB_GUID): boolean;
function CheckClassRight4DomainId (const right_name: TFRE_DB_String ; const rclassname: ShortString ; const domain: TFRE_DB_GUID): boolean;
function CheckClassRight4DomainId (const std_right : TFRE_DB_STANDARD_RIGHT ; const classtyp : TClass ; const domain: TFRE_DB_GUID): boolean;
function CheckClassRight4DomainId (const std_right : TFRE_DB_STANDARD_RIGHT ; const rclassname: ShortString ; const domain: TFRE_DB_GUID): boolean;
function GetDomainsForClassRight (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass): TFRE_DB_GUIDArray;
function GetDomainNamesForClassRight (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass): TFRE_DB_StringArray;
function CheckObjectRight (const right_name : TFRE_DB_String ; const uid : TFRE_DB_GUID ):boolean;
function CheckObjectRight (const std_right : TFRE_DB_STANDARD_RIGHT ; const uid : TFRE_DB_GUID ):boolean; // New is senseless
//function User : IFRE_DB_USER;
function GetUniqueTokenKey : TFRE_DB_NameType;
function GetFullUserLogin : TFRE_DB_String;
procedure GetUserDetails (out fulluserlogin,firstname,lastname,description : TFRE_DB_String);
function DumpUserRights : TFRE_DB_String;
function CloneToNewUserToken : IFRE_DB_USER_RIGHT_TOKEN;
procedure Finalize ;
end;
{ IFRE_DB_USER }
IFRE_DB_USER=interface(IFRE_DB_UID_BASE)
['IFDBUSER']
function GetFirstName: TFRE_DB_String;
function GetIsInternal: Boolean;
function GetLastName: TFRE_DB_String;
function GetLogin: TFRE_DB_String;
//function GetDomain (const conn:IFRE_DB_CONNECTION): TFRE_DB_NameType;
function GetLoginAtDomain (conn : IFRE_DB_SYS_CONNECTION):TFRE_DB_NameType;
function GetDomainIDLink: TFRE_DB_GUID;
function GetUserGroupIDS: TFRE_DB_ObjLinkArray;
procedure SetFirstName(const AValue: TFRE_DB_String);
procedure SetIsInternal(AValue: Boolean);
procedure SetLastName(const AValue: TFRE_DB_String);
procedure Setlogin(const AValue: TFRE_DB_String);
property Login :TFRE_DB_String read GetLogin write Setlogin;
property Firstname :TFRE_DB_String read GetFirstName write SetFirstName;
property Lastname :TFRE_DB_String read GetLastName write SetLastName;
property isInternal :Boolean read GetIsInternal write SetIsInternal;
procedure SetPassword (const pw:TFRE_DB_String);
function Checkpassword (const pw:TFRE_DB_String):boolean;
end;
{ IFRE_DB_DOMAIN }
IFRE_DB_DOMAIN=interface(IFRE_DB_BASE)
['IFDBUSERDOMAIN']
function Domainkey : TFRE_DB_GUID_String;
function Domainname (const unique:boolean=false) : TFRE_DB_NameType;
function GetIsInternal : Boolean;
function GetSuspended : Boolean;
function GetIsDefaultDomain : boolean;
procedure SetIsDefaultDomain (AValue: boolean);
procedure SetIsInternal (AValue: Boolean);
procedure SetSuspended (AValue: Boolean);
function UID : TFRE_DB_GUID;
property isInternal :Boolean read GetIsInternal write SetIsInternal;
property Suspended :Boolean read GetSuspended write SetSuspended;
property IsDefaultDomain : boolean read GetIsDefaultDomain write SetIsDefaultDomain;
end;
{ IFRE_DB_GROUP }
IFRE_DB_GROUP=interface(IFRE_DB_NAMED_OBJECT_PLAIN)
['IFDBUSERGRP']
function GetDomain (const conn :IFRE_DB_CONNECTION): TFRE_DB_NameType;
function DomainID : TFRE_DB_GUID;
function GetIsInternal : Boolean;
function GetIsDelegation : Boolean;
function GetIsProtected : Boolean;
function GetIsDisabled : Boolean;
procedure SetIsInternal (AValue: Boolean);
procedure SetIsProtected (AValue: Boolean);
procedure SetIsDelegation (AValue: Boolean);
procedure SetIsDisabled (AValue: Boolean);
property isProtected :Boolean read GetIsProtected write SetIsProtected;
property isInternal :Boolean read GetIsInternal write SetIsInternal; { should not be shown in to the User, because the Group is not directly usable for the user }
property isDelegation :Boolean read GetIsDelegation write SetIsDelegation; { group is used as delegation of other groups }
property isDisabled :Boolean read GetIsDisabled write SetIsDisabled; { This group is disabled for users where the userdomain=the group domain ,after a new instatiation of a right token, the user gets not the roles of this group }
end;
IFRE_DB_ClientFieldValidator = interface(IFRE_DB_NAMED_OBJECT_PLAIN)
['IFDBCV']
function getRegExp :TFRE_DB_String;
function getInfoText :IFRE_DB_TEXT;
function getHelpTextKey :TFRE_DB_String;
function getAllowedChars :TFRE_DB_String;
function getReplaceRegExp :TFRE_DB_String;
function getReplaceValue :TFRE_DB_String;
function Setup (const regExp:TFRE_DB_String; const infoText: IFRE_DB_TEXT; const help_trans_key: TFRE_DB_String=''; const allowedChars:TFRE_DB_String=''; const replaceRegExp: TFRE_DB_String=''; const replaceValue: TFRE_DB_String=''): IFRE_DB_ClientFieldValidator;
end;
IFRE_DB_InputGroupSchemeDefinition = interface;
{ IFRE_DB_SCHEMEOBJECT }
IFRE_DB_SCHEMEOBJECT=interface
['IFDBSO']
function Implementor :TObject;
function GetExplanation :TFRE_DB_String;
procedure SetExplanation (AValue: TFRE_DB_String);
function GetAll_WEB_Methods :TFRE_DB_StringArray;
function MethodExists (const name:TFRE_DB_String):boolean;
function AddSchemeField (const newfieldname :TFRE_DB_NameType ; const newfieldtype:TFRE_DB_FIELDTYPE ):IFRE_DB_FieldSchemeDefinition;
function AddSchemeFieldSubscheme (const newfieldname :TFRE_DB_NameType ; const sub_scheme:TFRE_DB_NameType):IFRE_DB_FieldSchemeDefinition;
function GetSchemeField (const fieldname :TFRE_DB_NameType ; var fieldschemedef:IFRE_DB_FieldSchemeDefinition): boolean;
function GetSchemeField (const fieldname :TFRE_DB_NameType): IFRE_DB_FieldSchemeDefinition;
function IsA (const schemename :shortstring):Boolean;
procedure SetSimpleSysDisplayField (const field_name :TFRE_DB_String);
procedure SetSysDisplayField (const field_names :TFRE_DB_NameTypeArray;const format:TFRE_DB_String);
function GetFormattedDisplay (const obj : IFRE_DB_Object):TFRE_DB_String;
function FormattedDisplayAvailable (const obj : IFRE_DB_Object):boolean;
function DefinedSchemeName : TFRE_DB_String;
procedure Strict (const only_defined_fields:boolean);
procedure SetParentSchemeByName (const parentschemename:TFRE_DB_String);
function GetParentScheme :IFRE_DB_SchemeObject;
function GetParentSchemeName :TFRE_DB_String;
procedure SetObjectFieldsWithScheme (const Raw_Object: IFRE_DB_OBject; const Update_Object: IFRE_DB_Object;const new_object:boolean;const DBConnection:IFRE_DB_CONNECTION;const schemeType: TFRE_DB_String='');
//@ Defines new InputGroup, to use with IMI_CONTENT
function AddInputGroup (const id: TFRE_DB_String): IFRE_DB_InputGroupSchemeDefinition;
function ReplaceInputGroup (const id: TFRE_DB_String): IFRE_DB_InputGroupSchemeDefinition;
function GetInputGroup (const id: TFRE_DB_String): IFRE_DB_InputGroupSchemeDefinition;
function HasInputGroup (const id: TFRE_DB_String; out igroup:IFRE_DB_InputGroupSchemeDefinition): Boolean;
procedure SetOverlayRights4UserClass (const Userclass:TFRE_DB_NameType ; const right_set : TFRE_DB_STANDARD_RIGHT_SET);
function GetOverlayRights4UserClass (const UserClass:TFRE_DB_NameType ; out right_set : TFRE_DB_STANDARD_RIGHT_SET):boolean;
function GetSchemeType : TFRE_DB_SchemeType;
function ValidateObject (const dbo : IFRE_DB_Object;const raise_errors:boolean=true):boolean;
function InvokeMethod_UID (const suid : TFRE_DB_GUID;const methodname:TFRE_DB_String;var input:IFRE_DB_Object;const connection:IFRE_DB_CONNECTION):IFRE_DB_Object;
procedure ForAllFieldSchemeDefinitions (const iterator:IFRE_DB_SchemeFieldDefIterator);
property Explanation:TFRE_DB_String read GetExplanation write SetExplanation;
end;
IFRE_DB_SCHEMEOBJECTArray = array of IFRE_DB_SCHEMEOBJECT;
TFRE_DB_TRANSACTION_TYPE=(dbt_Implicit_RD,dbt_Implicit_WR,dbt_OLTP_RD,dbt_OLTP_WR,dbt_OLAP_RD);
IFRE_DB_TRANSACTION=interface
function GetType : boolean;
procedure Rollback;
procedure Commit;
end;
// Abstraction of a Collection in the Persistance Layer
// Manages Object Storage
// -
// Every Object has to be in one collection to be storeable
// Objects can be in more than one Collection
// Objects stored in temporary collections do not feature referential integrity management
// Subobjects can be stored in collections too
//
// Every object store originates in the collection, but also checks for other collections
//
// Every Persistance Collection manages indexes for data
IFRE_DB_PERSISTANCE_LAYER=interface;
TFRE_DB_PERSISTANCE_COLLECTION_BASE=class
function CollectionName (const unique:boolean=false):TFRE_DB_NameType;virtual;abstract;
function GetPersLayer : IFRE_DB_PERSISTANCE_LAYER;virtual;abstract;
function Count : Int64;virtual;abstract;
function IsVolatile : boolean;virtual;abstract;
end;
{ IFRE_DB_PERSISTANCE_COLLECTION }
TFRE_DB_PERSISTANCE_COLLECTION_ARRAY = array of TFRE_DB_PERSISTANCE_COLLECTION_BASE;
{ IFRE_DB_PERSISTANCE_LAYER }
IFRE_DB_DBChangedNotificationBlock = interface; { sending a bulk change from an transaction }
IFRE_DB_DBChangedNotification = interface; { recording changes in the transaction }
IFRE_DB_PERSISTANCE_LAYER=interface
procedure DEBUG_DisconnectLayer (const db:TFRE_DB_String);
procedure DEBUG_InternalFunction (const func:NativeInt);
procedure WT_StoreCollectionPersistent (const coll:TFRE_DB_PERSISTANCE_COLLECTION_BASE);
procedure WT_StoreObjectPersistent (const obj: IFRE_DB_Object);
procedure WT_DeleteCollectionPersistent (const collname : TFRE_DB_NameType);
procedure WT_DeleteObjectPersistent (const iobj:IFRE_DB_Object);
procedure WT_TransactionID (const number:qword);
function FDB_GetObjectCount (const coll:boolean; const SchemesFilter:TFRE_DB_StringArray=nil): Integer;
procedure FDB_ForAllObjects (const cb:IFRE_DB_ObjectIteratorBrk; const SchemesFilter:TFRE_DB_StringArray=nil);
procedure FDB_ForAllColls (const cb:IFRE_DB_Obj_Iterator);
function FDB_GetAllCollsNames :TFRE_DB_NameTypeArray;
procedure FDB_PrepareDBRestore (const phase:integer ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String);
procedure FDB_SendObject (const obj:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String);
procedure FDB_SendCollection (const obj:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String);
function FDB_TryGetIndexStream (const collname : TFRE_DB_NameType ; const ix_name : TFRE_DB_Nametype ; out stream : TStream):boolean;
function GetConnectedDB : TFRE_DB_NameType;
function Connect (const db_name:TFRE_DB_String ; out db_layer : IFRE_DB_PERSISTANCE_LAYER ; const NotifIF : IFRE_DB_DBChangedNotificationBlock=nil) : TFRE_DB_Errortype;
function Disconnect : TFRE_DB_Errortype;
function DatabaseList : IFOS_STRINGS;
function DatabaseExists (const dbname:TFRE_DB_String):Boolean;
function CreateDatabase (const dbname:TFRE_DB_String ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype;
function DeleteDatabase (const dbname:TFRE_DB_String ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype;
function DeployDatabaseScheme (const scheme:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype;
function GetDatabaseScheme (out scheme:IFRE_DB_Object):TFRE_DB_Errortype;
procedure Finalize ;
function GetReferences (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ; const field_exact_filter : TFRE_DB_NameType ; const exact_filter_and_derived_classes : boolean):TFRE_DB_GUIDArray;
function GetReferencesCount (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ; const field_exact_filter : TFRE_DB_NameType ; const exact_filter_and_derived_classes : boolean):NativeInt;
function GetReferencesDetailed (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ; const field_exact_filter : TFRE_DB_NameType ; const exact_filter_and_derived_classes : boolean):TFRE_DB_ObjectReferences;
procedure ExpandReferences (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : TFRE_DB_GUIDArray ; const allow_derived_classes : boolean); { works over a reflink chain, with a starting object list }
function ExpandReferencesCount (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; const allow_derived_classes : boolean) : NativeInt; { works over a reflink chain, with a starting object list }
procedure FetchExpandReferences (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : IFRE_DB_ObjectArray ; const allow_derived_classes : boolean); { works over a reflink chain, with a starting object list }
function StartTransaction (const typ:TFRE_DB_TRANSACTION_TYPE ; const ID:TFRE_DB_NameType) : TFRE_DB_Errortype;
function Commit : boolean;
procedure RollBack ;
function RebuildUserToken (const user_uid : TFRE_DB_GUID):IFRE_DB_USER_RIGHT_TOKEN;
function ObjectExists (const obj_uid : TFRE_DB_GUID) : boolean; { returns the state, without checking fetch rights, because creating an object with a forged uid would show that an object with that uid exists anyway}
function Fetch (const user_context : PFRE_DB_GUID ; const ouid : TFRE_DB_GUID ; out dbo:IFRE_DB_Object):TFRE_DB_Errortype;
function BulkFetch (const user_context : PFRE_DB_GUID ; const obj_uids : TFRE_DB_GUIDArray ; out objects : IFRE_DB_ObjectArray):TFRE_DB_Errortype;
function DeleteObject (const user_context : PFRE_DB_GUID ; const obj_uid : TFRE_DB_GUID ; const collection_name: TFRE_DB_NameType = ''):TFRE_DB_TransStepId;
function StoreOrUpdateObject (const user_context : PFRE_DB_GUID ; const obj : IFRE_DB_Object ; const collection_name : TFRE_DB_NameType ; const store : boolean) : TFRE_DB_TransStepId;
{ Differential Bulk Update Interface }
function DifferentialBulkUpdate (const user_context : PFRE_DB_GUID ; const transport_obj : IFRE_DB_Object) : TFRE_DB_Errortype;
{ Collection Interface }
function CollectionExistCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : Boolean;
function CollectionNewCollection (const coll_name: TFRE_DB_NameType ; const volatile_in_memory: boolean ; const user_context : PFRE_DB_GUID): TFRE_DB_TransStepId;
function CollectionDeleteCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : TFRE_DB_TransStepId;
function CollectionDefineIndexOnField (const user_context : PFRE_DB_GUID; const coll_name: TFRE_DB_NameType ; const FieldName : TFRE_DB_NameType ; const FieldType : TFRE_DB_FIELDTYPE ; const unique : boolean;
const ignore_content_case: boolean ; const index_name : TFRE_DB_NameType ; const allow_null_value : boolean=true ; const unique_null_values: boolean=false ; const is_a_domain_index: boolean = false): TFRE_DB_TransStepId;
function CollectionGetIndexDefinition (const coll_name: TFRE_DB_NameType ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID):TFRE_DB_INDEX_DEF;
function CollectionDropIndex (const coll_name: TFRE_DB_NameType ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID):TFRE_DB_TransStepId;
function CollectionGetAllIndexNames (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : TFRE_DB_NameTypeArray;
function CollectionExistsInCollection (const coll_name: TFRE_DB_NameType ; const check_uid: TFRE_DB_GUID ; const and_has_fetch_rights: boolean ; const user_context : PFRE_DB_GUID): boolean;
function CollectionFetchInCollection (const coll_name: TFRE_DB_NameType ; const check_uid: TFRE_DB_GUID ; out dbo:IFRE_DB_Object ; const user_context : PFRE_DB_GUID):TFRE_DB_Errortype;
function CollectionBulkFetch (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID): IFRE_DB_ObjectArray;
function CollectionBulkFetchUIDS (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID): TFRE_DB_GUIDArray;
procedure CollectionClearCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID);
function CollectionIndexExists (const coll_name: TFRE_DB_NameType ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID):Boolean;
function CollectionGetIndexedValueCount (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : NativeInt;
function CollectionGetIndexedObjsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; out objs : IFRE_DB_ObjectArray ; const index_must_be_full_unique : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : NativeInt;
function CollectionGetIndexedUidsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; out objs : TFRE_DB_GUIDArray ; const index_must_be_full_unique : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : NativeInt;
function CollectionRemoveIndexedUidsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : NativeInt;
function CollectionGetIndexedObjsRange (const coll_name: TFRE_DB_NameType ; const min,max : IFRE_DB_Object ; const ascending: boolean ; const max_count,skipfirst : NativeInt ; out objs : IFRE_DB_ObjectArray ; const min_val_is_a_prefix : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID) : NativeInt;
function CollectionGetFirstLastIdxCnt (const coll_name: TFRE_DB_NameType ; const idx : Nativeint ; out obj : IFRE_DB_Object ; const user_context : PFRE_DB_GUID) : NativeInt;
procedure SyncSnapshot ;
function ForceRestoreIfNeeded :boolean;
function GetNotificationRecordIF : IFRE_DB_DBChangedNotification; { to record changes }
end;
IFRE_DB_DBChangedNotification = interface
procedure StartNotificationBlock (const key : TFRE_DB_TransStepId);
procedure FinishNotificationBlock(out block : IFRE_DB_Object);
procedure SendNotificationBlock (const block : IFRE_DB_Object);
procedure CollectionCreated (const coll_name: TFRE_DB_NameType ; const in_memory_only: boolean ; const tsid : TFRE_DB_TransStepId);
procedure CollectionDeleted (const coll_name: TFRE_DB_NameType ; const tsid : TFRE_DB_TransStepId) ;
procedure IndexDefinedOnField (const coll_name: TFRE_DB_NameType ; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE;
const unique: boolean; const ignore_content_case: boolean;
const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean ; const tsid : TFRE_DB_TransStepId);
procedure IndexDroppedOnField (const coll_name: TFRE_DB_NameType ; const index_name: TFRE_DB_NameType ; const tsid : TFRE_DB_TransStepId);
procedure ObjectStored (const coll_name: TFRE_DB_NameType ; const obj : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure ObjectDeleted (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure ObjectUpdated (const obj : IFRE_DB_Object ; const colls:TFRE_DB_StringArray ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure DifferentiallUpdStarts (const obj_uid : IFRE_DB_Object; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldDelete (const old_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldAdd (const new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldChange (const old_field,new_field : IFRE_DB_Field; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure DifferentiallUpdEnds (const obj_uid : TFRE_DB_GUID; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure ObjectRemoved (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object ; const is_a_full_delete : boolean ; const tsid : TFRE_DB_TransStepId);
procedure SetupOutboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure SetupInboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure InboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure OutboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure FinalizeNotif ;
end;
IFRE_DB_DBChangedNotificationBlock=interface
procedure SendNotificationBlock (const block : IFRE_DB_Object); { encapsulate a block of changes from a transaction }
function Implementor : Tobject;
end;
IFRE_DB_DBChangedNotificationConnection = interface { handle metadata changes }
procedure CollectionCreated (const coll_name: TFRE_DB_NameType ; const in_memory_only: boolean ; const tsid : TFRE_DB_TransStepId) ;
procedure CollectionDeleted (const coll_name: TFRE_DB_NameType ; const tsid : TFRE_DB_TransStepId) ;
procedure IndexDefinedOnField (const coll_name: TFRE_DB_NameType ; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean;
const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean ;
const tsid : TFRE_DB_TransStepId);
procedure IndexDroppedOnField (const coll_name: TFRE_DB_NameType ; const index_name: TFRE_DB_NameType ; const tsid : TFRE_DB_TransStepId);
end;
IFRE_DB_DBChangedNotificationSession = interface
procedure DifferentiallUpdStarts (const obj_uid : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldDelete (const old_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldAdd (const new_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldChange (const old_field,new_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure DifferentiallUpdEnds (const obj_uid : TFRE_DB_GUID ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure ObjectDeleted (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure ObjectUpdated (const obj : IFRE_DB_Object ; const colls:TFRE_DB_StringArray ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure SetupInboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure InboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
end;
TFRE_DB_APPLICATION = Class;
TFRE_DB_APPLICATION_MODULE = class;
TFRE_DB_APPLICATIONCLASS = Class of TFRE_DB_APPLICATION;
TFRE_DB_APPLICATION_MODULE_CLASS = class of TFRE_DB_APPLICATION_MODULE;
IFRE_DB_APPLICATION_ARRAY = array of IFRE_DB_APPLICATION;
TFRE_DB_APPLICATION_ARRAY = array of TFRE_DB_APPLICATION;
TFRE_DB_MODULE_CLASS_ARRAY = array of TFRE_DB_APPLICATION_MODULE_CLASS;
{ IFRE_DB_CONNECTION }
IFRE_DB_CONNECTION=interface(IFRE_DB_BASE)
['IFDB_CONN']
procedure BindUserSession (const session : IFRE_DB_Usersession);
procedure ClearUserSessionBinding ;
function GetDatabaseName : TFRE_DB_String;
function Connect (const db,user,pass:TFRE_DB_String ; const wants_notifications:boolean=false):TFRE_DB_Errortype;
function CollectionExists (const name:TFRE_DB_NameType):boolean;
function DeleteCollection (const name:TFRE_DB_NameType):TFRE_DB_Errortype;
function Delete (const ouid: TFRE_DB_GUID): TFRE_DB_Errortype;
function Fetch (const ouid:TFRE_DB_GUID;out dbo:IFRE_DB_Object) : TFRE_DB_Errortype;
function FetchAs (const ouid:TFRE_DB_GUID;const classref : TFRE_DB_BaseClass ; var outobj) : TFRE_DB_Errortype;
function FetchAsIntf (const ouid:TFRE_DB_GUID;const IntfSpec:ShortString; out Intf) : TFRE_DB_Errortype;
function Update (const dbo:IFRE_DB_OBJECT) : TFRE_DB_Errortype;
function BulkFetch (const uids:TFRE_DB_GUIDArray;out dbos:IFRE_DB_ObjectArray) : TFRE_DB_Errortype; { uids must be from one db }
function GetCollection (const collection_name: TFRE_DB_NameType) : IFRE_DB_COLLECTION;
function CreateCollection (const collection_name: TFRE_DB_NameType;const in_memory:boolean=false) : IFRE_DB_COLLECTION;
function CreateDerivedCollection (const collection_name: TFRE_DB_NameType): IFRE_DB_DERIVED_COLLECTION;
function GetDatabaseObjectCount (const Schemes:TFRE_DB_StringArray=nil):NativeInt;
procedure ForAllDatabaseObjectsDo (const dbo:IFRE_DB_ObjectIteratorBrkProgress ; const Schemes:TFRE_DB_StringArray=nil); { Warning may take some time, delivers a clone }
procedure ForAllColls (const iterator:IFRE_DB_Coll_Iterator) ;
procedure ForAllSchemes (const iterator:IFRE_DB_Scheme_Iterator) ;
procedure ForAllEnums (const iterator:IFRE_DB_Enum_Iterator) ;
procedure ForAllClientFieldValidators (const iterator:IFRE_DB_ClientFieldValidator_Iterator) ;
function InvokeMethod (const class_name,method_name:TFRE_DB_String;const uid_path:TFRE_DB_GUIDArray;var input:IFRE_DB_Object;const session:TFRE_DB_UserSession):IFRE_DB_Object;
procedure ExpandReferences (ObjectList : TFRE_DB_GUIDArray ; ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : TFRE_DB_GUIDArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list }
function ExpandReferencesCount (ObjectList : TFRE_DB_GUIDArray ; ref_constraints : TFRE_DB_NameTypeRLArray ; const allow_derived_classes : boolean=true) : NativeInt; { works over a reflink chain, with a starting object list }
procedure FetchExpandReferences (ObjectList : TFRE_DB_GUIDArray ; ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : IFRE_DB_ObjectArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list }
procedure ExpandReferences (ObjectList : Array of TFRE_DB_GUID ; ref_constraints : Array of TFRE_DB_NameType ; out expanded_refs : TFRE_DB_GUIDArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list }
function ExpandReferencesCount (ObjectList : Array of TFRE_DB_GUID ; ref_constraints : Array of TFRE_DB_NameType ; const allow_derived_classes : boolean=true) : NativeInt; { works over a reflink chain, with a starting object list }
procedure FetchExpandReferences (ObjectList : Array of TFRE_DB_GUID ; ref_constraints : Array of TFRE_DB_NameType ; out expanded_refs : IFRE_DB_ObjectArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list }
function IsReferenced (const obj_uid:TFRE_DB_GUID; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const allow_derived_classes : boolean=true):Boolean;
function ReferencesObjects (const obj_uid:TFRE_DB_GUID; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const allow_derived_classes : boolean=true):Boolean;
function GetReferences (const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=true):TFRE_DB_GUIDArray;
function GetReferencesCount (const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=true):NativeInt;
function GetReferencesDetailed (const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=true):TFRE_DB_ObjectReferences;
function FetchUserSessionData (var SessionData: IFRE_DB_OBJECT):boolean;
function StoreUserSessionData (var session_data:IFRE_DB_Object):TFRE_DB_Errortype;
procedure OverviewDump (const cb : TFRE_DB_SimpleLineCallback);
function DifferentialBulkUpdate (const transport_obj : IFRE_DB_Object) : TFRE_DB_Errortype;
function SYS : IFRE_DB_SYS_CONNECTION;
function FetchApplications (var apps : IFRE_DB_APPLICATION_ARRAY; var loginapp: IFRE_DB_APPLICATION; const interactive_session : boolean) : TFRE_DB_Errortype; // with user rights, interactive session are not filtered by appfilter
function FetchTranslateableTextOBJ (const translation_key:TFRE_DB_String; var textObj: IFRE_DB_TEXT):Boolean; // Warning: finalize the TEXTOBJ!
function FetchTranslateableTextShort (const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchTranslateableTextLong (const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchTranslateableTextHint (const translation_key:TFRE_DB_String):TFRE_DB_String;
function AdmGetTextResourcesCollection :IFRE_DB_COLLECTION; { Pre defined Special Collection from the System DB }
function AdmGetUserCollection :IFRE_DB_COLLECTION;
function AdmGetRoleCollection :IFRE_DB_COLLECTION;
function AdmGetGroupCollection :IFRE_DB_COLLECTION;
function AdmGetDomainCollection :IFRE_DB_COLLECTION;
function AdmGetAuditCollection :IFRE_DB_COLLECTION;
function AdmGetWorkFlowCollection :IFRE_DB_COLLECTION;
function AdmGetWorkFlowSchemeCollection :IFRE_DB_COLLECTION;
function AdmGetWorkFlowMethCollection :IFRE_DB_COLLECTION;
function AdmGetNotificationCollection :IFRE_DB_COLLECTION;
function AdmGetApplicationConfigCollection:IFRE_DB_COLLECTION;
function GetNotesCollection :IFRE_DB_COLLECTION; { Pre Defined special collection }
function GetMachinesCollection :IFRE_DB_COLLECTION;
function GetJobsCollection :IFRE_DB_COLLECTION;
function GetSysDomainUID :TFRE_DB_GUID;
function GetDefaultDomainUID :TFRE_DB_GUID;
function URT (const cone:boolean=false) : IFRE_DB_USER_RIGHT_TOKEN; { get userright token reference or value }
function AddDomain (const domainname:TFRE_DB_NameType;const txt,txt_short:TFRE_DB_String):TFRE_DB_Errortype;
procedure DrawScheme (const datastream:TStream; const classfile:string);
function BackupDatabase2DBO (const sysdba_user, sysdba_pw_hash: TFRE_DB_String; out DBB_OBJ: IFRE_DB_Object): TFRE_DB_Errortype;
function GetFeatureStatus (const feature_name : TFRE_DB_NameType):boolean;
function SetFeatureStatus (const feature_name : TFRE_DB_NameType; const enable:boolean):TFRE_DB_Errortype;
function GetAllEnabledDBFeatures : IFOS_STRINGS;
end;
{ IFRE_DB_SYS_CONNECTION }
IFRE_DB_SYS_CONNECTION=interface(IFRE_DB_BASE)
['IFDB_SYS_CONN']
//function GetNotif : IFRE_DB_DBChangedNotification; { get the notif of an impersonated (cloned) connection}
function GetClassesVersionDirectory : IFRE_DB_Object;
function StoreClassesVersionDirectory(const version_dbo : IFRE_DB_Object) : TFRE_DB_Errortype;
function DelClassesVersionDirectory : TFRE_DB_Errortype;
function Connect (const loginatdomain,pass:TFRE_DB_String ; const wants_notifications : boolean=false):TFRE_DB_Errortype;
function CheckLogin (const loginatdomain,pass:TFRE_DB_String;const allowed_classes : TFRE_DB_StringArray):TFRE_DB_Errortype;
function AddUser (const login:TFRE_DB_String; const domainUID: TFRE_DB_GUID;const password,first_name,last_name:TFRE_DB_String;const image : TFRE_DB_Stream=nil; const imagetype : String='';const is_internal:Boolean=false;const long_desc : TFRE_DB_String='' ; const short_desc : TFRE_DB_String='' ; const userclass : TFRE_DB_STRING=''):TFRE_DB_Errortype;
function UserExists (const login:TFRE_DB_String; const domainUID: TFRE_DB_GUID):boolean;
function DeleteUser (const login:TFRE_DB_String; const domainUID: TFRE_DB_GUID):TFRE_DB_Errortype;
function DeleteUserById (const user_id:TFRE_DB_GUID):TFRE_DB_Errortype;
function FetchUser (const login:TFRE_DB_String; const domainUID: TFRE_DB_GUID;out user:IFRE_DB_USER):TFRE_DB_Errortype;
function FetchUserById (const user_id:TFRE_DB_GUID; out user: IFRE_DB_USER):TFRE_DB_Errortype;
function FetchGroup (const group:TFRE_DB_String; const domainUID: TFRE_DB_GUID;out ug: IFRE_DB_GROUP):TFRE_DB_Errortype;
function FetchGroupById (const group_id:TFRE_DB_GUID;out ug: IFRE_DB_GROUP):TFRE_DB_Errortype;
function ModifyGroupById (const group_id:TFRE_DB_GUID; const groupname : TFRE_DB_NameType; const txt:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR;const txt_short:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR):TFRE_DB_Errortype;
function ModifyGroup (const group:TFRE_DB_NameType; const domain_id:TFRE_DB_GUID; const groupname : TFRE_DB_NameType; const txt:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR;const txt_short:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR):TFRE_DB_Errortype;
function FetchRole (const rolename:TFRE_DB_String;const domainUID: TFRE_DB_GUID;out role: IFRE_DB_ROLE):TFRE_DB_Errortype;
function FetchRoleById (const role_id:TFRE_DB_GUID;out role: IFRE_DB_ROLE):TFRE_DB_Errortype;
function ModifyRoleById (const role_id:TFRE_DB_GUID; const rolename : TFRE_DB_NameType; const txt:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR;const txt_short:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR):TFRE_DB_Errortype;
function ModifyRole (const role:TFRE_DB_NameType; const domain_id:TFRE_DB_GUID; const rolename : TFRE_DB_NameType; const txt:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR;const txt_short:TFRE_DB_String=cFRE_DB_SYS_NOCHANGE_VAL_STR):TFRE_DB_Errortype;
function FetchDomainById (const domain_id:TFRE_DB_GUID;out domain: IFRE_DB_DOMAIN):TFRE_DB_Errortype;
function FetchDomainNameById (const domain_id:TFRE_DB_GUID):TFRE_DB_NameType;
function FetchDomainUIDbyName (const name :TFRE_DB_NameType; out domain_uid:TFRE_DB_GUID):boolean;
function ModifyDomainById (const domain_id:TFRE_DB_GUID; const domainname : TFRE_DB_NameType; const txt,txt_short:TFRE_DB_String):TFRE_DB_Errortype; { use special value "*$NOCHANGE$*" for unchanged webfields }
function DeleteDomainById (const domain_id:TFRE_DB_GUID):TFRE_DB_Errortype;
function FetchTranslateableText (const translation_key:TFRE_DB_String; out textObj: IFRE_DB_TEXT):Boolean;//don't finalize the object
function NewRole (const rolename,txt,txt_short:TFRE_DB_String;const is_internal:Boolean; out role :IFRE_DB_ROLE):TFRE_DB_Errortype;
function NewGroup (const groupname,txt,txt_short:TFRE_DB_String;const is_protected:Boolean; const is_internal:Boolean; const is_delegation:Boolean; out user_group:IFRE_DB_GROUP):TFRE_DB_Errortype;
function AddGroup (const groupname,txt,txt_short:TFRE_DB_String;const domainUID:TFRE_DB_GUID; const is_protected:Boolean=false; const is_internal:Boolean=false; const is_delegation:Boolean=false):TFRE_DB_Errortype;
function AddRole (const rolename,txt,txt_short:TFRE_DB_String;const domainUID:TFRE_DB_GUID; const is_internal:Boolean=false):TFRE_DB_Errortype;
function AddRolesToGroupById (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const role_ids: TFRE_DB_GUIDArray):TFRE_DB_Errortype;
function AddRolesToGroup (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const roles: TFRE_DB_StringArray):TFRE_DB_Errortype;
function AddSysRolesToGroup (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const roles: TFRE_DB_StringArray):TFRE_DB_Errortype;
function RemoveAllRolesFromGroup (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID): TFRE_DB_Errortype;
function RemoveRoleFromAllGroups (const role:TFRE_DB_String;const domainUID: TFRE_DB_GUID): TFRE_DB_Errortype;
function RemoveRolesFromGroup (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const roles: TFRE_DB_StringArray; const ignore_not_set:boolean): TFRE_DB_Errortype; //TODO: Remove Ignorenotset
function RemoveRolesFromGroupById (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const role_ids: TFRE_DB_GUIDArray; const ignore_not_set:boolean): TFRE_DB_Errortype; //TODO: Remove Ignorenotset
function AddGroupsToGroupById (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const group_ids: TFRE_DB_GUIDArray):TFRE_DB_Errortype;
function RemoveGroupsFromGroupById (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const group_ids: TFRE_DB_GUIDArray; const ignore_not_set:boolean): TFRE_DB_Errortype; //TODO: Remove Ignorenotset
function AddRoleRightsToRole (const rolename:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const roles: TFRE_DB_StringArray):TFRE_DB_Errortype;
function RemoveRoleRightsFromRole (const rolename:TFRE_DB_String;const domainUID: TFRE_DB_GUID;const roles: TFRE_DB_StringArray):TFRE_DB_Errortype;
function RemoveRightsFromRole (const rolename:TFRE_DB_String;const rights:TFRE_DB_StringArray; const domainUID: TFRE_DB_GUID):TFRE_DB_Errortype;
function ModifyUserGroupsById (const user_id:TFRE_DB_GUID; const user_group_ids:TFRE_DB_GUIDArray; const keep_existing_groups:boolean=false):TFRE_DB_Errortype;
function RemoveUserGroupsById (const user_id:TFRE_DB_GUID; const user_group_ids:TFRE_DB_GUIDArray):TFRE_DB_Errortype;
function RoleExists (const role:TFRE_DB_String;const domainUID: TFRE_DB_GUID):boolean;
function GroupExists (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID):boolean;
function DeleteGroup (const group:TFRE_DB_String;const domainUID: TFRE_DB_GUID):TFRE_DB_Errortype;
function DeleteGroupById (const group_id:TFRE_DB_GUID):TFRE_DB_Errortype;
function DeleteRole (const role:TFRE_DB_String;const domainUID: TFRE_DB_GUID):TFRE_DB_Errortype;
function DomainExists (const domainname:TFRE_DB_NameType):boolean;
function DomainID (const domainname:TFRE_DB_NameType):TFRE_DB_GUID;
function DeleteDomain (const domainname:TFRE_DB_Nametype):TFRE_DB_Errortype;
procedure ForAllDomains (const func:IFRE_DB_Domain_Iterator);
function FetchAllDomainUids : TFRE_DB_GUIDArray;
function StoreRole (var role:IFRE_DB_ROLE; const domainUID : TFRE_DB_GUID ):TFRE_DB_Errortype;
function StoreGroup (var group:IFRE_DB_GROUP;const domainUID: TFRE_DB_GUID): TFRE_DB_Errortype;
function UpdateGroup (var group:IFRE_DB_GROUP): TFRE_DB_Errortype;
function UpdateRole (var role:IFRE_DB_ROLE): TFRE_DB_Errortype;
function UpdateDomain (var domain:IFRE_DB_DOMAIN): TFRE_DB_Errortype;
function UpdateUser (var user:IFRE_DB_USER): TFRE_DB_Errortype;
function StoreTranslateableText (const txt :IFRE_DB_TEXT) :TFRE_DB_Errortype;
function UpdateTranslateableText (const txt :IFRE_DB_TEXT) :TFRE_DB_Errortype;
function DeleteTranslateableText (const key :TFRE_DB_String) :TFRE_DB_Errortype;
function BackupDatabaseReadable (const sys,adb : TStream;const progress : TFRE_DB_PhaseProgressCallback; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype;
function RestoreDatabaseReadable (const sys,adb : TStream;const db_name:string;const progress : TFRE_DB_PhaseProgressCallback; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype;
procedure StartTransaction (const trans_id: TFRE_DB_NameType ; const trans_type : TFRE_DB_TRANSACTION_TYPE);
procedure Commit ;
procedure DrawScheme (const datastream:TStream; const classfile:string);
function GetDatabaseObjectCount (const Schemes:TFRE_DB_StringArray=nil):NativeInt;
procedure ForAllDatabaseObjectsDo (const dbo:IFRE_DB_ObjectIteratorBrkProgress ; const Schemes:TFRE_DB_StringArray=nil ); { Warning may take some time, delivers a clone }
function CheckClassRight4MyDomain (const right_name:TFRE_DB_String;const classtyp: TClass):boolean;
function CheckClassRight4MyDomain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass):boolean;
function CheckClassRight4AnyDomain (const right_name:TFRE_DB_String;const classtyp: TClass):boolean;
function CheckClassRight4Domain (const right_name:TFRE_DB_String;const classtyp: TClass;const domainKey:TFRE_DB_String):boolean;
function CheckClassRight4DomainId (const right_name:TFRE_DB_String;const classtyp: TClass;const domain:TFRE_DB_GUID):boolean;
function CheckClassRight4DomainId (const right_name:TFRE_DB_String;const rclassname: ShortString;const domain: TFRE_DB_GUID): boolean;
function GetDomainsForClassRight (const right_name:TFRE_DB_String;const classtyp: TClass): TFRE_DB_GUIDArray;
function CheckClassRight4AnyDomain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass):boolean;
function CheckClassRight4AnyDomain (const std_right:TFRE_DB_STANDARD_RIGHT;const rclassname: ShortString):boolean;
function CheckClassRight4Domain (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass;const domainKey:TFRE_DB_String):boolean;
function CheckClassRight4DomainId (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass;const domain:TFRE_DB_GUID):boolean;
function CheckClassRight4DomainId (const std_right:TFRE_DB_STANDARD_RIGHT;const rclassname: ShortString;const domain:TFRE_DB_GUID):boolean;
function GetDomainsForClassRight (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass): TFRE_DB_GUIDArray;
function GetDomainsForClassRight (const std_right:TFRE_DB_STANDARD_RIGHT;const rclassname: ShortString): TFRE_DB_GUIDArray;
function GetDomainNamesForClassRight (const std_right:TFRE_DB_STANDARD_RIGHT;const classtyp: TClass): TFRE_DB_StringArray;
function CheckObjectRight (const right_name : TFRE_DB_String ; const uid : TFRE_DB_GUID ):boolean;
function CheckObjectRight (const std_right : TFRE_DB_STANDARD_RIGHT ; const uid : TFRE_DB_GUID ):boolean; // New is sensless
//function IsCurrentUserSystemAdmin :boolean;
function SuspendContinueDomainById (const domain_id:TFRE_DB_GUID; const suspend : boolean):TFRE_DB_Errortype;
function IsDomainSuspended (const domainname:TFRE_DB_NameType):boolean; {delivers true if the domain exists and is suspended, otherwise false}
function DumpUserRights :TFRE_DB_String;
function GetSysDomainUID :TFRE_DB_GUID;
function GetDefaultDomainUID : TFRE_DB_GUID;
function GetCurrentUserTokenClone : IFRE_DB_USER_RIGHT_TOKEN;
function GetCurrentUserTokenRef : IFRE_DB_USER_RIGHT_TOKEN;
procedure RefreshUserRights ;
end;
TFRE_DB_CONTENT_DESC_ARRAY = array of TFRE_DB_CONTENT_DESC;
IFRE_DB_APPLICATION=interface(IFRE_DB_COMMON)
['IFDBAPP']
// function GetDescription (conn : IFRE_DB_CONNECTION): IFRE_DB_TEXT;
function UID : TFRE_DB_GUID;
function ShowInApplicationChooser (const session:IFRE_DB_UserSession): Boolean;
function IsConfigurationApp : Boolean;
function FetchAppTextShort (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextLong (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextHint (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextFull (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;
function AppClassName : ShortString;
function AsObject : IFRE_DB_Object;
function GetCaption (const ses : IFRE_DB_Usersession): TFRE_DB_String;
function GetIcon : TFRE_DB_String;
function IsMultiDomainApp : Boolean;
function FetchOrInitFeederMachine (const ses: IFRE_DB_Usersession ; const configmachinedata : IFRE_DB_Object ; out machine_uid : TFRE_DB_GUID ; out BoundMachineName,BoundMachineMac : TFRE_DB_String):boolean; { true if this app configures machines,datacenters and results the binding }
end;
IFRE_DB_APPLICATION_MODULE=interface
['IFDBAPPM']
function GetImplementorsClass : TClass;
function GetToolbarMenu (const ses : IFRE_DB_Usersession): TFRE_DB_CONTENT_DESC;
function GetModuleTitle (const ses : IFRE_DB_Usersession): TFRE_DB_String;
function ShowInSession (const ses : IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const app: IFRE_DB_APPLICATION): Boolean;
function GetModuleClassName : Shortstring;
function GetSitemapIconFilename : TFRE_DB_String;
function AsObject : IFRE_DB_Object;
end;
{ TFOS_BASE }
TFOS_BASE = class(TObject)
public
constructor Create ; virtual;
function Implementor : TObject;virtual;
function Implementor_HC : TObject;virtual;
function GetImplementorsClass : TClass;
end;
{ TFRE_DB_Base }
{$M+}
TFRE_DB_Base = class(TFOS_Base)
private
class procedure _InstallDBObjects4Domain (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID);
protected
FMediatorExtention : TFRE_DB_ObjectEx;
function Implementor_HC : TObject;override;
function Debug_ID : TFRE_DB_String;virtual;
public
class procedure VersionInstallationCheck (const currentVersionId,newVersionId: TFRE_DB_NameType);
class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); virtual;
{install methods for system db}
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); virtual;
class procedure InstallDBObjects4Domain (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure InstallDBObjects4SysDomain (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
{install methods for user db}
class procedure InstallUserDBObjects (const conn:IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); virtual;
class procedure InstallUserDBObjects4Domain (const conn:IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure InstallUserDBObjects4SysDomain(const conn:IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure RemoveDBObjects (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType); virtual;
class procedure RemoveDBObjects4Domain (const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
function GetSystemSchemeByName (const schemename:TFRE_DB_String; var scheme: IFRE_DB_SchemeObject): Boolean;
function GetSystemScheme (const schemename:TClass; var scheme: IFRE_DB_SchemeObject): Boolean;
class function GetStdObjectRightName (const std_right: TFRE_DB_STANDARD_RIGHT;const uid : TFRE_DB_GUID):TFRE_DB_String;
class function GetObjectRightName (const right: TFRE_DB_NameType ; const uid : TFRE_DB_GUID):TFRE_DB_String;
class function _GetClassRight (const right: TFRE_DB_NameType): IFRE_DB_RIGHT;
class function GetRight4Domain (const right: TFRE_DB_NameType; const domainUID:TFRE_DB_GUID): IFRE_DB_RIGHT;
class function GetClassRightName (const rclassname:ShortString ; const right: TFRE_DB_NameType): TFRE_DB_String;
class function GetClassRightName (const right: TFRE_DB_NameType): TFRE_DB_String;
class function GetClassRightNameSR (const rclassname:ShortString ; const sright: TFRE_DB_STANDARD_RIGHT): TFRE_DB_String;
class function GetClassRightNameUpdate : TFRE_DB_String;
class function GetClassRightNameDelete : TFRE_DB_String;
class function GetClassRightNameStore : TFRE_DB_String;
class function GetClassRightNameFetch : TFRE_DB_String;
class function CreateClassRole (const rolename: TFRE_DB_String; const short_desc, long_desc: TFRE_DB_String): IFRE_DB_ROLE;
class function GetClassRoleName (const rolename: TFRE_DB_String): TFRE_DB_String;
class function GetClassRoleNameUpdate : TFRE_DB_String;
class function GetClassRoleNameDelete : TFRE_DB_String;
class function GetClassRoleNameStore : TFRE_DB_String;
class function GetClassRoleNameFetch : TFRE_DB_String;
class function GetClassStdRoles (const store:boolean=true; const update:boolean=true; const delete:boolean=true; const fetch:boolean=true): TFRE_DB_StringArray;
procedure __SetMediator (const med : TFRE_DB_ObjectEx);
class function CheckGetRIFMethodInstance (const rifmethod:TFRE_DB_RIF_Method ; out rclassname,rmethodname : ShortString ; out obj : IFRE_DB_Object):boolean;
class function Get_DBI_InstanceMethods : TFRE_DB_StringArray;
class function Get_DBI_RemoteMethods : TFRE_DB_StringArray; //Feeder Instance Methods (Singletons / Usescase : Remote Control Interfaces on the feeder )
class function Get_DBI_RIFMethods : TFRE_DB_StringArray; //Feeder Instance Methods (Singletons / Usescase : Remote Control Interfaces on a ObjectExClass)
class function Get_DBI_ClassMethods : TFRE_DB_StringArray;
class function ClassMethodExists (const name:Shortstring) : Boolean; // new
class function Invoke_DBIMC_Method (const name:TFRE_DB_String;const input:IFRE_DB_Object;const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION) : IFRE_DB_Object;
function Invoke_DBIMI_Method (const name:TFRE_DB_String;const input:IFRE_DB_Object;const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION) : IFRE_DB_Object;
procedure Invoke_DBREM_Method (const rmethodname : TFRE_DB_NameType ; const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE);
function Invoke_DBRIF_Method (const rmethodname: TFRE_DB_NameType; const run_ctx: TObject; const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE): IFRE_DB_Object;
function IMI_MethodExists (const name:TFRE_DB_String) : boolean;
function MethodExists (const name:Shortstring) : Boolean; // new
function Supports (const InterfaceSpec:ShortString ; out Intf) : boolean;
function Supports (const InterfaceSpec:ShortString) : boolean;
procedure IntfCast (const InterfaceSpec:ShortString ; out Intf) ; // IntfCast throws an Exception if not succesful
//Utility Shortcuts
function CSFT (const server_function_name : string ; const obj:IFRE_DB_Object=nil):TFRE_DB_SERVER_FUNC_DESC;
function CSF (const invoke_method : IFRE_DB_InvokeInstanceMethod):TFRE_DB_SERVER_FUNC_DESC;
function CWSF (const invoke_method : IFRE_DB_WebInstanceMethod):TFRE_DB_SERVER_FUNC_DESC;
function CSCF (const serv_classname,server_function_name : string ; const param1 : string=''; const value1 : string=''):TFRE_DB_SERVER_FUNC_DESC;
end;
{$M-}
// This is the TFRE_DB_ObjectEx mediator Class for all Code that has no direct access to TFRE_DB_Object Class
{ TFRE_DB_ObjectEx }
TFRE_DB_ObjectEx=class(TFRE_DB_Base, IFRE_DB_Object)
private
FImplementor : IFRE_DB_Object; // Must support DBO Interface
protected
function Debug_ID : TFRE_DB_String ;override;
procedure InternalSetup ; virtual;
procedure InternalFinalize ; virtual;
procedure _InternalSetMediator (const mediator : TFRE_DB_ObjectEx);
function _InternalDecodeAsField : IFRE_DB_Field; { create a streaming only lightweight field from the encoding object }
public
function GetDescriptionID (const full_uid_path : boolean=true): String;
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
function Invoke (const method:TFRE_DB_String;const input:IFRE_DB_Object ; const ses : IFRE_DB_Usersession ; const app : IFRE_DB_APPLICATION ; const conn : IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
constructor Create ; { Scheme must not be registered }
constructor CreateForDB ; { Scheme must be registered }
constructor CreateBound (const dbo:IFRE_DB_Object);
destructor Destroy ;override;
destructor DestroyFromBackingDBO ;
procedure FreeFromBackingDBO ;virtual;
procedure Free ;
function GetUCTHashed : Shortstring;
//Interface - Compatibility Block
{if it's a named object support this }
function GetDesc : IFRE_DB_TEXT; {}
procedure SetDesc (const AValue: IFRE_DB_TEXT);
function GetName : TFRE_DB_String;
procedure SetName (const AValue: TFRE_DB_String);
property ObjectName : TFRE_DB_String read GetName write SetName;
property Description : IFRE_DB_TEXT read GetDesc write SetDesc;
function UIDP : PByte;
function PUID : PFRE_DB_Guid;
function ObjectRoot : IFRE_DB_Object; // = the last parent with no parent
procedure ForAllFields (const iter:IFRE_DB_FieldIterator;const without_system_fields:boolean=false);
procedure ForAllFieldsBreak (const iter:IFRE_DB_FieldIteratorBrk;const without_system_fields:boolean=false);
procedure ForAllObjects (const iter:IFRE_DB_Obj_Iterator);
procedure ForAllObjectsBreak (const iter:IFRE_DB_ObjectIteratorBrk);
procedure ForAllObjectsFieldName (const iter:IFRE_DB_Obj_NameIterator);
function UID : TFRE_DB_GUID;
function UCT : TFRE_DB_String;
procedure SetUCT (const tag : TFRE_DB_String);
procedure SetUID (const guid:TFRE_DB_GUID);
function UID_String : TFRE_DB_GUID_String;
function DomainID : TFRE_DB_GUID;
procedure SetDomainID (const domid:TFRE_DB_GUID);
function Parent : IFRE_DB_Object;
function ParentField : IFRE_DB_FIELD;
function AsString : TFRE_DB_String;
function Field (const name:TFRE_DB_NameType):IFRE_DB_FIELD;
function FieldOnlyExistingObj (const name:TFRE_DB_NameType):IFRE_DB_Object;
function FieldOnlyExistingObject (const name:TFRE_DB_NameType; var obj:IFRE_DB_Object):boolean;
function FieldOnlyExistingObjAs (const name:TFRE_DB_NameType; const classref : TFRE_DB_BaseClass ; var outobj) : boolean;
function FieldOnlyExisting (const name:TFRE_DB_NameType;var fld:IFRE_DB_FIELD):boolean;
function FieldOnlyExistingUID (const name:TFRE_DB_NameType;const def : PFRE_DB_GUID=nil):TFRE_DB_GUID;
function FieldOnlyExistingByte (const name:TFRE_DB_NameType;const def : Byte=0):Byte;
function FieldOnlyExistingInt16 (const name:TFRE_DB_NameType;const def : Int16=-1):Int16;
function FieldOnlyExistingUInt16 (const name:TFRE_DB_NameType;const def : UInt16=0):UInt16;
function FieldOnlyExistingInt32 (const name:TFRE_DB_NameType;const def : Int32=-1):Int32;
function FieldOnlyExistingUInt32 (const name:TFRE_DB_NameType;const def : UInt32=0):UInt32;
function FieldOnlyExistingInt64 (const name:TFRE_DB_NameType;const def : Int64=-1):Int64;
function FieldOnlyExistingUInt64 (const name:TFRE_DB_NameType;const def : UInt64=0):UInt64;
function FieldOnlyExistingReal32 (const name:TFRE_DB_NameType;const def : Single=-1):Single;
function FieldOnlyExistingReal64 (const name:TFRE_DB_NameType;const def : Double=-1):Double;
function FieldOnlyExistingCurrency (const name:TFRE_DB_NameType;const def : Currency=0):Currency;
function FieldOnlyExistingString (const name:TFRE_DB_NameType;const def : String=''):String;
function FieldOnlyExistingBoolean (const name:TFRE_DB_NameType;const def : Boolean=false):Boolean;
function FieldPath (const name:TFRE_DB_String;const dont_raise_ex:boolean=false):IFRE_DB_FIELD;
function FieldPathCreate (const name:TFRE_DB_String):IFRE_DB_FIELD;
function FieldPathExists (const name:TFRE_DB_String):Boolean;
function FieldPathExists (const name: TFRE_DB_String;out fld:IFRE_DB_Field): Boolean;
function FieldPathExistsAndNotMarkedClear (const name:TFRE_DB_String):Boolean;
function FieldPathExistsAndNotMarkedClear (const name: TFRE_DB_String;out fld:IFRE_DB_Field): Boolean;
function FieldPathListFormat (const field_list:TFRE_DB_NameTypeArray;const formats : TFRE_DB_String;const empty_val: TFRE_DB_String) : TFRE_DB_String;
function FieldCount (const without_system_fields:boolean): SizeInt;
function DeleteField (const name:TFRE_DB_String):Boolean;
procedure ClearAllFields ;
procedure ClearAllFieldsExcept (const fieldnames : array of TFRE_DB_NameType);
function FieldExists (const name:TFRE_DB_String):boolean;
function FieldExistsAndNotMarkedClear (const name:TFRE_DB_String):boolean;
procedure DumpToStrings (const strings:TStrings;indent:integer=0);
function DumpToString (indent:integer=2;const dump_length_max:Integer=0):TFRE_DB_String;
function GetFormattedDisplay : TFRE_DB_String;
function FormattedDisplayAvailable : boolean; virtual;
function SubFormattedDisplayAvailable : boolean; virtual;
function GetSubFormattedDisplay (indent:integer=4):TFRE_DB_String;virtual;
function SchemeClass : TFRE_DB_NameType; virtual;
function IsA (const schemename:shortstring):Boolean;
function IsA (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX) : Boolean;
function IsA (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX ; out obj ) : Boolean;
procedure AsClass (const IsSchemeclass : TFRE_DB_OBJECTCLASSEX ; out obj );
function IsObjectRoot : Boolean;
function IsPluginContainer : Boolean;
function IsPlugin : Boolean;
procedure SaveToFile (const filename:TFRE_DB_String);
procedure SaveToFileHandle (const handle : THandle);
function ReferencesObjectsFromData : Boolean;
function ForAllObjectsBreakHierarchic (const iter:IFRE_DB_ObjectIteratorBrk):boolean; // includes root object (self)
function FetchObjByUID (const childuid:TFRE_DB_GUID ; var obj : IFRE_DB_Object):boolean;
function FetchObjWithStringFieldValue (const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; var obj: IFRE_DB_Object; ClassnameToMatch: ShortString=''): boolean;
function FetchObjWithStringFieldValueAs (const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; const exclasstyp : TFRE_DB_ObjectClassEx ; var obj): boolean;
procedure SetAllSimpleObjectFieldsFromObject (const source_object : IFRE_DB_Object); // only first level, no uid, domid, obj, objlink fields
function GetFieldListFilter (const field_type:TFRE_DB_FIELDTYPE):TFRE_DB_StringArray;
function GetUIDPath :TFRE_DB_StringArray;
function GetUIDPathUA :TFRE_DB_GUIDArray;
function GetFieldValuePathString (const fieldname:TFRE_DB_NameType):TFRE_DB_StringArray; { Top Down Path of Field Values }
function Implementor : TObject;override;
function Implementor_HC : TObject;override;
function Supports (const InterfaceSpec:ShortString ; out Intf) : boolean;
function Supports (const InterfaceSpec:ShortString) : boolean;
procedure IntfCast (const InterfaceSpec:ShortString ; out Intf) ; // IntfCast throws an Exception if not succesful
function IntfCast (const InterfaceSpec:ShortString) : Pointer ; // IntfCast throws an Exception if not succesful
function GetScheme (const raise_non_existing:boolean=false): IFRE_DB_SchemeObject;
procedure Finalize ;
function GetAsJSON (const without_uid: boolean=false;const full_dump:boolean=false;const stream_cb:TFRE_DB_StreamingCallback=nil): TJSONData;
function GetAsJSONString (const without_reserved_fields:boolean=false;const full_dump:boolean=false;const stream_cb:TFRE_DB_StreamingCallback=nil;const pretty:boolean=false):TFRE_DB_String;
function CloneToNewObject (const generate_new_uids:boolean=false): IFRE_DB_Object;
function Mediator : TFRE_DB_ObjectEx;
function NeededSize : TFRE_DB_SIZE_TYPE;
procedure Set_ReadOnly ;
procedure CopyField (const obj:IFRE_DB_Object;const field_name:String);
class function NewOperation (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_GUID;
procedure CopyToMemory (memory : Pointer);
function GetInstanceRight (const right: TFRE_DB_NameType): IFRE_DB_RIGHT;
class procedure StoreTranslateableText (const conn: IFRE_DB_SYS_CONNECTION; const key: TFRE_DB_NameType; const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
class procedure DeleteTranslateableText (const conn: IFRE_DB_SYS_CONNECTION; const key: TFRE_DB_NameType);
class function GetTranslateableTextKey (const key: TFRE_DB_NameType):TFRE_DB_String;
class function GetTranslateableTextShort (const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType):TFRE_DB_String;
class function GetTranslateableTextLong (const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType):TFRE_DB_String;
class function GetTranslateableTextHint (const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType):TFRE_DB_String;
function CloneToNewObjectWithoutSubobjects (const generate_new_uids: boolean=false): IFRE_DB_Object;
//procedure SetPluginContainerTag (const tagvalue : TFRE_DB_String ; const tagfield : TFRE_DB_NameType='UCT');
//function GetPluginContainerTag (const tagfield : TFRE_DB_NameType='UCT'):TFRE_DB_String;
procedure SetGenericUCTTags (const check_unique_tagging : boolean=false); { setup missing UCT Tags (DBTEXT Subobjects) }
function HasPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS): boolean;
function HasPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; out plugin): boolean; { delivers the internal reference of the plugin, if avail, dont free it (!) }
procedure GetPlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; out plugin); { delivers the internal reference of the plugin, if avail, dont free it (!), raises exception if not attached }
function GetStatusPlugin : TFRE_DB_STATUS_PLUGIN;
function AttachPlugin (const plugin : TFRE_DB_OBJECT_PLUGIN_BASE ; const raise_if_existing : boolean=true) : Boolean; { sets a plugin instance of the specified class }
procedure ForAllPlugins (const plugin_iterator : IFRE_DB_PLUGIN_ITERATOR);
function RemovePlugin (const pluginclass : TFRE_DB_OBJECT_PLUGIN_CLASS ; const raise_if_not_existing : boolean=true) : Boolean;
procedure CheckoutFromObject ;
published
function WEB_SaveOperation (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_DeleteOperation (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
class function WBC_NewOperation (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_NoteLoad (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_NoteSave (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_NoteStartEdit (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_NoteStopEdit (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
//Interface - Compatibility Block End
end;
{ TFRE_DB_USER }
TFRE_DB_USER=class(TFRE_DB_ObjectEx,IFRE_DB_USER)
private
function GetLoginAtDomain (conn: IFRE_DB_SYS_CONNECTION): TFRE_DB_NameType;
function GetFirstName :TFRE_DB_String;
function GetIsInternal :Boolean;
function GetLastName :TFRE_DB_String;
function GetLogin :TFRE_DB_String;
function GetUserclass :TFRE_DB_String;
procedure SetFirstName (const AValue: TFRE_DB_String);
procedure SetGIDA (AValue: TFRE_DB_ObjLinkArray);
procedure SetIsInternal (AValue: Boolean);
procedure SetLastName (const AValue: TFRE_DB_String);
procedure Setlogin (const AValue: TFRE_DB_String);
procedure SetDomainIDLink (AValue: TFRE_DB_GUID);
procedure SetUserclass (AValue: TFRE_DB_String);
procedure _UpdateDomainLoginKey;
public
function GetDomainIDLink :TFRE_DB_GUID;
function GetUserGroupIDS : TFRE_DB_ObjLinkArray;
function SubFormattedDisplayAvailable :boolean; override;
function GetSubFormattedDisplay (indent: integer=4): TFRE_DB_String; override;
procedure SetImage (const image_stream: TFRE_DB_Stream; const streamtype: string ; const etag : string);
procedure InitData (const nlogin,nfirst,nlast,npasswd:TFRE_DB_String;const userdomainid:TFRE_DB_GUID;const is_internal:Boolean;const long_desc,short_desc:TFRE_DB_String);
property Login :TFRE_DB_String read GetLogin write Setlogin;
property Firstname :TFRE_DB_String read GetFirstName write SetFirstName;
property Lastname :TFRE_DB_String read GetLastName write SetLastName;
property UserGroupIDs :TFRE_DB_ObjLinkArray read GetUserGroupIDS write SetGIDA;
procedure SetPassword (const pw:TFRE_DB_String);
function Checkpassword (const pw:TFRE_DB_String):boolean;
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class function GetDomainLoginKey (const loginpart : TFRE_DB_String; const domain_id : TFRE_DB_GUID) : TFRE_DB_String;
function DomainLoginKey :TFRE_DB_String;
class procedure InstallDBObjects (const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallDBObjects4Domain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
property isInternal :Boolean read GetIsInternal write SetIsInternal;
property Userclass :TFRE_DB_String read GetUserclass write SetUserclass; { Every User has one defined class WEBUSER, FEEDER, (MIGHTYFEEDER), right checks can be OVERLAYED by the CLASS and the special class ALL }
published
class function WBC_NewUserOperation (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
function WEB_SaveOperation (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
end;
{ TFRE_DB_DOMAIN }
TFRE_DB_DOMAIN=class(TFRE_DB_ObjectEx,IFRE_DB_DOMAIN)
private
function IFRE_DB_DOMAIN.GetDesc = GetDescI;
function IFRE_DB_DOMAIN.SetDesc = SetDescI;
function GetIsDefaultDomain : boolean;
function GetIsInternal : Boolean;
procedure SetIsDefaultDomain (AValue: boolean);
procedure SetIsInternal (AValue: Boolean);
function GetSuspended : boolean;
procedure SetSuspended (AValue: boolean);
public
class procedure InstallDBObjects (const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
function Domainname (const unique:boolean=false) : TFRE_DB_NameType;
function Domainkey : TFRE_DB_GUID_String;
property isInternal : Boolean read GetIsInternal write SetIsInternal;
property Suspended : boolean read GetSuspended write SetSuspended;
property IsDefaultDomain : boolean read GetIsDefaultDomain write SetIsDefaultDomain;
end;
{ TFRE_DB_GROUP }
TFRE_DB_GROUP=class(TFRE_DB_ObjectEx,IFRE_DB_GROUP)
private
function GetIsInternal : Boolean;
function GetIsDelegation : Boolean;
function GetIsDisabled : Boolean;
function GetIsProtected : Boolean;
function GetRoleIDs : TFRE_DB_ObjLinkArray;
function GetGroupIDs : TFRE_DB_ObjLinkArray;
function IFRE_DB_GROUP.GetDesc = GetDescI;
function IFRE_DB_GROUP.SetDesc = SetDescI;
procedure SetIsInternal (AValue: Boolean);
procedure SetIsDelegation (AValue: Boolean);
procedure SetIsProtected (AValue: Boolean);
procedure SetIsDisabled (AValue: Boolean);
procedure SetRoleIDs (AValue: TFRE_DB_ObjLinkArray);
procedure SetGroupIDs (AValue: TFRE_DB_ObjLinkArray);
public
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class function GetDomainGroupKey (const grouppart : TFRE_DB_String; const domain_id : TFRE_DB_GUID) : TFRE_DB_String;
class procedure InstallDBObjects (const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallDBObjects4Domain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
class procedure InstallDBObjects4SysDomain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
function GetDomainIDLink : TFRE_DB_GUID;
procedure SetDomainIDLink (AValue: TFRE_DB_GUID);
procedure UpdateDomainGroupKey ;
function GetDomain (const conn :IFRE_DB_CONNECTION): TFRE_DB_NameType;
function SubFormattedDisplayAvailable : boolean; override;
function GetSubFormattedDisplay (indent: integer=4): TFRE_DB_String; override;
property RoleIDs :TFRE_DB_ObjLinkArray read GetRoleIDs write SetRoleIDs;
property GroupIDs :TFRE_DB_ObjLinkArray read GetGroupIDs write SetGroupIDs;
property isProtected :Boolean read GetIsProtected write SetIsProtected;
property isInternal :Boolean read GetIsInternal write SetIsInternal;
property isDelegation :Boolean read GetIsDelegation write SetIsDelegation;
property isDisabled :Boolean read GetIsDisabled write SetIsDisabled;
end;
{ TFRE_DB_ROLE }
TFRE_DB_ROLE=class(TFRE_DB_ObjectEx,IFRE_DB_ROLE)
private
function IFRE_DB_ROLE.GetDesc = GetDescI;
function IFRE_DB_ROLE.SetDesc = SetDescI;
function GetDomain (const conn :IFRE_DB_CONNECTION): TFRE_DB_NameType;
function GetDomainIDLink : TFRE_DB_GUID;
function GetIsInternal : Boolean;
function GetIsDisabled : Boolean;
procedure SetIsInternal (AValue: Boolean);
procedure SetIsDisabled (AValue: Boolean);
public
class procedure InstallDBObjects (const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallDBObjects4Domain (const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
class procedure InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID); override;
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
class function GetDomainRoleKey (const rolepart : TFRE_DB_String; const domain_id : TFRE_DB_GUID) : TFRE_DB_String;
procedure SetDomainIDLink (AValue: TFRE_DB_GUID);
procedure UpdateDomainRoleKey;
procedure AddRight (const right : IFRE_DB_RIGHT);
function SubFormattedDisplayAvailable : boolean; override;
function GetSubFormattedDisplay (indent: integer=4): TFRE_DB_String; override;
function GetRightNames :TFRE_DB_StringArray;
procedure AddRightsFromRole (const role : IFRE_DB_ROLE);
procedure RemoveRightsOfRole (const role : IFRE_DB_ROLE);
procedure RemoveRights (const rights : TFRE_DB_StringArray);
property isInternal : Boolean read GetIsInternal write SetIsInternal;
property isDisabled : Boolean read GetIsDisabled write SetIsDisabled;
end;
{ TFRE_DB_WeakObjectEx }
TFRE_DB_WeakObjectEx=class(TFRE_DB_ObjectEx)
private
FWeakClassname : ShortString;
public
constructor Create(const weakclname : Shortstring);
function CloneInstance : TFRE_DB_WeakObjectEx;
function SchemeClass: TFRE_DB_NameType; override;
end;
{ TFRE_DB_OBJECT_PLUGIN_BASE }
TFRE_DB_OBJECT_PLUGIN_BASE=class(TFRE_DB_ObjectEx)
private
protected
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function EnhancesGridRenderingTransform : Boolean; virtual;
class function EnhancesGridRenderingPreClientSend : Boolean; virtual;
class function EnhancesFormRendering : Boolean; virtual;
procedure TransformGridEntryClientSend (const ut : IFRE_DB_USER_RIGHT_TOKEN ; const transformed_object : IFRE_DB_Object ; const session_data : IFRE_DB_Object;const langres: array of TFRE_DB_String); virtual ; abstract;
procedure TransformGridEntry (const transformed_object : IFRE_DB_Object); virtual ; abstract;
procedure RenderFormEntry (const formdesc : TFRE_DB_CONTENT_DESC ; const entry : IFRE_DB_Object ; const pre_render : boolean); virtual ; abstract;
function CloneToNewPlugin : TFRE_DB_OBJECT_PLUGIN_BASE;
function MyObj : IFRE_DB_Object;
published
end;
{ TFRE_DB_STATUS_PLUGIN }
TFRE_DB_STATUS_PLUGIN=class(TFRE_DB_OBJECT_PLUGIN_BASE)
protected
procedure InternalSetup ; override;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function GetStateFieldForDiffSync : IFRE_DB_Field; { the DiffSync algo is field based, we need the field internally to mark objects as deleted }
procedure lock ;
procedure unlock ;
function isLocked : Boolean; virtual; { obj is lock and should not be modified until it is unlocked }
procedure setApplyConfirmedConfig ; { signal to apply the configuration 2 physical object }
procedure setConfigIsApplied ; { this gets set when the feeder reads the physical object back }
//obj state: planned, modified, deleted or stable
procedure setPlanned ; //obj is new and has to be confirmed
procedure setModified ; //obj is modified by user and has to be confirmed
procedure setDeleted ; //obj no longer exists in real world
procedure setStable ; //config and real world are the same
procedure setPhysicalExisting ; { set by feeder to see if an object was created physical }
function getStatusText : TFRE_DB_String;
function isModifiedOrPlanned : Boolean;
function isLockedOrDeleted : Boolean;
function isPlanned : Boolean;
function isModified : Boolean;
function isDeleted : Boolean;
function isPhysicalExisting : boolean;
end;
{ TFRE_DB_RIF_RESULT }
TFRE_DB_RIF_RESULT=class(TFRE_DB_ObjectEx)
private
function GetChildPid: int32;
function GetErrorcode: Int32;
function GetErrorText: TFRE_DB_String;
function GetJobKey: TFRE_DB_String;
function GetJobUid: TFRE_DB_GUID;
function GetTransferStatus: TFRE_DB_COMMAND_STATUS;
procedure SetChildPid(AValue: int32);
procedure SetErrorcode(AValue: Int32);
procedure SetErrorText(AValue: TFRE_DB_String);
procedure SetJobKey(AValue: TFRE_DB_String);
procedure SetJobUid(AValue: TFRE_DB_GUID);
procedure SetTransferStatus(AValue: TFRE_DB_COMMAND_STATUS);
public
function GetTransferStatusString : TFRE_DB_String;
property Transferstatus :TFRE_DB_COMMAND_STATUS read GetTransferStatus write SetTransferStatus;
property ErrorCode :Int32 read GetErrorcode write SetErrorcode;
property ChildPid :int32 read GetChildPid write SetChildPid;
property ErrorText :TFRE_DB_String read GetErrorText write SetErrorText;
property JobKey :TFRE_DB_String read GetJobKey write SetJobKey;
property JobUID :TFRE_DB_GUID read GetJobUid write SetJobUid;
end;
TFRE_DB_TRANSFORM_UTIL_DATA_BASE=class
function GetObj : IFRE_DB_Object;virtual;abstract;
function PreTransformedScheme : Shortstring;virtual;abstract;
end;
{ TFRE_DB_FILTER_BASE }
TFRE_DB_FILTER_BASE=class
protected
FKey : TFRE_DB_NameType;
FFieldname : TFRE_DB_NameType;
FNegate : Boolean;
FAllowNull : Boolean;
FOnlyRootNodes : Boolean;
FDBName : TFRE_DB_NameType;
public
function GetKeyName : TFRE_DB_NameType; { get a reproducable unique key, depending on the filter field, values and settings}
function GetDefinitionKey : TFRE_DB_NameType;virtual;abstract; { return true if the filter hits }
function CheckFilterMiss (const ud : TFRE_DB_TRANSFORM_UTIL_DATA_BASE ; var flt_errors : Int64):boolean;virtual;abstract; { return TRUE, when the filter misses the value (!) }
constructor Create (const key : TFRE_DB_NameType);
function Clone : TFRE_DB_FILTER_BASE;virtual; abstract;
function IsARootNodeOnlyFilter : Boolean;
end;
{ TFRE_DB_TRANS_COLL_DATA_BASE }
//TFRE_DB_TRANS_RESULT_BASE = class
//public
// procedure LockOrder ; virtual; abstract;
// procedure UnlockOrder ; virtual; abstract;
// //function GetFullKey : TFRE_DB_TRANS_COLL_DATA_KEY; virtual ; abstract;
//end;
{ TFRE_DB_DC_FILTER_DEFINITION_BASE }
TFRE_DB_DC_FILTER_DEFINITION_BASE = class { a filter filters out the specified values, so that the filtered values are not in the result datatest }
procedure AddStringFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalue : TFRE_DB_String ; const stringfiltertype : TFRE_DB_STR_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddSignedFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of Int64 ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddUnsignedFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of Uint64 ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddCurrencyFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of Currency ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddReal64FieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of Double ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddDatetimeFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of TFRE_DB_DateTime64 ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddBooleanFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalue : boolean ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddUIDFieldFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of TFRE_DB_GUID ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddRootNodeFilter (const key,fieldname:TFRE_DB_NameType ; filtervalues : Array of TFRE_DB_GUID ; const numfiltertype : TFRE_DB_NUM_FILTERTYPE ; const negate:boolean=true ; const include_null_values : boolean=false);virtual;abstract;
procedure AddSchemeObjectFilter (const key: TFRE_DB_NameType ; filtervalues : Array of TFRE_DB_String ; const negate:boolean=true );virtual;abstract;
procedure AddStdRightObjectFilter (const key: TFRE_DB_NameType ; stdrightset : TFRE_DB_STANDARD_RIGHT_SET ; const usertoken : IFRE_DB_USER_RIGHT_TOKEN ; const negate:boolean=true; const ignoreField:TFRE_DB_NameType=''; const ignoreValue:TFRE_DB_String='');virtual;abstract;
procedure AddStdClassRightFilter (const key: TFRE_DB_NameType ; domainidfield, objuidfield, schemeclassfield: TFRE_DB_NameType; schemeclass: TFRE_DB_NameType; stdrightset: TFRE_DB_STANDARD_RIGHT_SET; const usertoken: IFRE_DB_USER_RIGHT_TOKEN; const negate: boolean=true; const ignoreField:TFRE_DB_NameType=''; const ignoreValue:TFRE_DB_String=''); virtual;abstract;
procedure AddObjectRightFilter (const key: TFRE_DB_NameType ; rightset : Array of TFRE_DB_String ; const usertoken : IFRE_DB_USER_RIGHT_TOKEN ; const negate:boolean=true; const ignoreField:TFRE_DB_NameType=''; const ignoreValue:TFRE_DB_String='');virtual;abstract;
procedure AddClassRightFilter (const key: TFRE_DB_NameType ; domainidfield, objuidfield, schemeclassfield: TFRE_DB_NameType; schemeclass: TFRE_DB_NameType; rightset: Array of TFRE_DB_String; const usertoken: IFRE_DB_USER_RIGHT_TOKEN; const negate: boolean=true; const ignoreField:TFRE_DB_NameType=''; const ignoreValue:TFRE_DB_String=''); virtual;abstract;
procedure AddChildFilter (const key: TFRE_DB_NameType); virtual ; abstract; { Filters Childs out => Only Root nodes PP must be empty, internal (!) do not USE }
procedure AddParentFilter (const key: TFRE_DB_NameType ; const allowed_parent_path : TFRE_DB_String); virtual ; abstract ; { Child Query Filter, filter all Nodes which have not the corresponding PP, internal (!), do not USE }
function RemoveFilter (const key: TFRE_DB_NameType):boolean;virtual;abstract;
function FilterExists (const key: TFRE_DB_NameType):boolean;virtual;abstract;
procedure RemoveAllFilters ;virtual;abstract;
procedure RemoveAllFiltersPrefix (const key_prefix: TFRE_DB_NameType);virtual;abstract;
end;
TFRE_DB_DC_ORDER_DEFINITION_BASE = class { defines a globally stored ordered and transformed set of dbo's}
public
procedure ClearOrders ; virtual ; abstract;
procedure AddOrderDef (const orderfield_name : TFRE_DB_NameType ; const ascending : boolean ; const case_insensitive : boolean); virtual ; abstract;
function OrderCount : NativeInt; virtual ; abstract;
procedure AssignFrom (const orderdef : TFRE_DB_DC_ORDER_DEFINITION_BASE); virtual; abstract;
function HasOrders : boolean;virtual;abstract;
end;
{ TFRE_DB_QUERY_DEF }
TFRE_DB_QUERY_DEF=record
StartIdx : Int32;
EndIndex : Int32;
SessionID : TFRE_DB_SESSION_ID;
DerivedCollName : TFRE_DB_NameTypeRL;
ParentName : TFRE_DB_NameTypeRL;
DBName : TFRE_DB_NameType;
UserTokenRef : IFRE_DB_USER_RIGHT_TOKEN;
FilterDefStaticRef : TFRE_DB_DC_FILTER_DEFINITION_BASE;
FilterDefDynamicRef : TFRE_DB_DC_FILTER_DEFINITION_BASE;
FilterDefDependencyRef : TFRE_DB_DC_FILTER_DEFINITION_BASE;
OrderDefRef : TFRE_DB_DC_ORDER_DEFINITION_BASE;
ParentPath : TFRE_DB_String;
ParentChildSpec : TFRE_DB_NameTypeRL;
ParentChildScheme : TFRE_DB_NameType;
ParentChildField : TFRE_DB_NameType;
ParentLinksChild : Boolean ;
ParentChildSkipSchemes : TFRE_DB_NameTypeArray;
ParentChildFilterClasses : TFRE_DB_NameTypeArray;
ParentChildStopOnLeaves : TFRE_DB_NameTypeArray;
DependencyRefIds : TFRE_DB_StringArray;
DepRefConstraints : TFRE_DB_NameTypeRLArrayArray;
DepRefNegate : Boolean;
DepFilterUids : Array of TFRE_DB_GUIDArray;
FullTextFilter : String;
OnlyOneUID : TFRE_DB_GUID;
function GetReflinkSpec (const upper_refid : TFRE_DB_NameType):TFRE_DB_NameTypeRLArray;
function GetReflinkStartValues (const upper_refid : TFRE_DB_NameType):TFRE_DB_GUIDArray; { start values for the RL expansion }
end;
{ TFRE_DB_QUERY_BASE }
TFRE_DB_QUERY_BASE=class
function GetReqID : Qword; virtual; abstract;
function GetQueryID : TFRE_DB_SESSION_DC_RANGE_MGR_KEY; virtual; abstract;
function GetTransfrom : IFRE_DB_SIMPLE_TRANSFORM; virtual;abstract;
function GetTotalCount : NativeInt; virtual ; abstract;
function GetResultData : IFRE_DB_ObjectArray; virtual ; abstract;
function ExecuteQuery (const iterator : IFRE_DB_Obj_Iterator ; const dc : IFRE_DB_DERIVED_COLLECTION):NativeInt;virtual;abstract;
procedure ExecutePointQuery (const iterator : IFRE_DB_Obj_Iterator);virtual;abstract;
procedure CaptureStartTime ; virtual ; abstract;
function CaptureEndTime : NativeInt; virtual ; abstract;
end;
{ TFRE_DB_TRANSDATA_MANAGER_BASE }
TFRE_DB_TRANSDATA_MANAGER_BASE=class
public
function FormQueryID (const session_id : TFRE_DB_String ; const dc_name : TFRE_DB_NameTypeRL):TFRE_DB_NameType; virtual; abstract;
function GenerateQueryFromQryDef (const qry_def : TFRE_DB_QUERY_DEF):TFRE_DB_QUERY_BASE; virtual ; abstract;
function GetNewOrderDefinition : TFRE_DB_DC_ORDER_DEFINITION_BASE; virtual ; abstract;
function GetNewFilterDefinition (const filter_db_name : TFRE_DB_NameType): TFRE_DB_DC_FILTER_DEFINITION_BASE; virtual; abstract;
procedure cs_RemoveQueryRange (const qry_id: TFRE_DB_CACHE_DATA_KEY; const start_idx,end_index : NativeInt); virtual; abstract;
procedure cs_DropAllQueryRanges (const qry_id: TFRE_DB_CACHE_DATA_KEY ; const whole_session: boolean); virtual; abstract; { is a sessionid only }
procedure cs_InboundNotificationBlock (const dbname: TFRE_DB_NameType ; const block : IFRE_DB_Object); virtual; abstract;
procedure cs_InvokeQry (const qry: TFRE_DB_QUERY_BASE ; const transform: IFRE_DB_SIMPLE_TRANSFORM; const return_cg: IFRE_APSC_CHANNEL_GROUP;const ReqID : Qword ; const sync_event : IFOS_E); virtual ; abstract;
end;
{ TFRE_DB_NOTE }
TFRE_DB_NOTE=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_NOTIFICATION }
TFRE_DB_NOTIFICATION=class(TFRE_DB_ObjectEx)
public
procedure setMenuFunc (const menuFunc: TFRE_DB_NameType; const objGuid: TFRE_DB_GUID);
function getMenu (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_APPLICATION_CONFIG }
TFRE_DB_APPLICATION_CONFIG=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_AUDIT_ENTRY }
TFRE_DB_AUDIT_ENTRY=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_WORKFLOW_ACTION }
TFRE_DB_WORKFLOW_ACTION=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_WORKFLOW_BASE }
TFRE_DB_WORKFLOW_BASE=class(TFRE_DB_ObjectEx)
private
function _hasFailedChild (const conn: IFRE_DB_CONNECTION): Boolean;
procedure update (const conn: IFRE_DB_CONNECTION);
public
function getState : UInt32;
procedure setState (const conn: IFRE_DB_CONNECTION; const state: UInt32); virtual;
end;
{ TFRE_DB_WORKFLOW }
TFRE_DB_WORKFLOW=class(TFRE_DB_WORKFLOW_BASE)
private
procedure _init (const conn: IFRE_DB_CONNECTION);
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure setState (const conn: IFRE_DB_CONNECTION; const state: UInt32); virtual;
procedure start (const conn: IFRE_DB_CONNECTION);
end;
{ TFRE_DB_WORKFLOW_STEP }
TFRE_DB_WORKFLOW_STEP=class(TFRE_DB_WORKFLOW_BASE)
private
function getAction : TFRE_DB_GUID;
function getIsErrorStep: Boolean;
function getStepId : UInt32;
procedure setAction (AValue: TFRE_DB_GUID);
procedure setIsErrorStep(AValue: Boolean);
procedure setStepId (AValue: UInt32);
published
function WEB_Done (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
function WEB_NotificationMenu (const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
procedure setState (const conn: IFRE_DB_CONNECTION; const state: UInt32); override;
property isErrorStep : Boolean read getIsErrorStep write setIsErrorStep;
property action : TFRE_DB_GUID read getAction write setAction;
property stepId : UInt32 read getStepId write setStepId;
end;
{ TFRE_DB_WORKFLOW_DATA }
TFRE_DB_WORKFLOW_DATA=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure InstallUserDBObjects (const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_UNCONFIGURED_MACHINE }
TFRE_DB_UNCONFIGURED_MACHINE=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_JOB }
TFRE_SignalStatus = (statusUnknown, statusOK, statusWarning, statusFailure);// deprecated KILL
TFRE_JobState = (jobStateUnknown,jobStateToRun,jobStateImmediateStart,jobStateRunning,jobStateDone,jobStateFailed);
const
CFRE_SignalStatus : Array[TFRE_SignalStatus] of string = ('UNKNOWN', 'OK', 'WARNING', 'FAILURE'); // deprecated KILL
type
TFRE_DB_JOBREPORTPLUGIN = class;
{ Known Job Progress Keys
('ZCRADDFS',[fs_dir,fs_special],'Added Filesystem '+fs_dir+' '+fs_special)
('ZFSADDDS',[ds_name],'Added Dataset '+ds_name)
('FBZCREATEDS',[dsname],'FBZ: Created dataset '+dsname)
('FBZCLONEDS',[dsname,snapshot_name],'FBZ: Cloned dataset '+snapshot_name+' '+dsname)
('FBZINSTALLSTART',[zone_caption,zone_dataset],'Installing Zone '+zone_caption+' '+zone_dataset,65)
('ZCFGSAVEFAIL',[master_dspath+'/zones/'+zone_name],'Error saving zone configuration file:'+master_dspath+'/zones/'+zone_name)
('ZCFGSAVEOK''Zonecfg saved to zone dbo file',30)
('ZINSTALLED','Zonestate set to INSTALLED',90)
('ZCRZNAM',[czonename],'Assigned zonename '+czonename+',15')
('ZCRADDD','Done adding datasets',20)
('ZCRZSVD','Zonecfg saved in System',25)
('ZCRCFGD','Zonestate set to CONFIGURED',40)
('MIWIPE',cmd,'superwipe [%s]',[cmd],0)
('MICRPOOL','syspool data read, creating pool',0)
('MICPOOLD','syspool created',10)
('MICRDUMP','creating dump volume [%s]',[cmd],20);
('MIADMP',cmd,'activating dump device [%s]',[cmd],25)
('MICROPT',cmd,'create opt [%s]',[cmd],30)
('MIINOPT',cmd,'install opt [%s]',[cmd],35)
('MICRVAR',cmd,'create var [%s]',[cmd],40)
('MIIVAR',cmd,'install var [%s]',[cmd],45)
('MISMT',cmd,'set mountpoint legacy /var /opt [%s]',[cmd],50)
('MIMIN',cmd,'mount install directory [%s]',[cmd],60)
('MIPDS',cmd,'prepare dataset structure',70)
('MINTMPL',template,'install template [%s]',[template],90)
('MIIND','base install done',100)
('JERR',e.Message,'Job failed due to exception '+e.Message,100);
}
{
JOB UIDS are stable per definition, jobs are saved to the disk
JOBs therefor dont need UCT Tags
Jobkey : Unique ID, Only one Job of this key might run at a time
}
TFRE_DB_JOB = class (TFRE_DB_ObjectEx)
private
const
CFRE_JobState : Array[TFRE_JobState] of string = ('UNKNOWN','TORUN','IMMEDIATESTART','RUNNING','DONE','FAILED');
function GetDontStartJob : Boolean;
function GetJobLink: TFRE_DB_Guid;
function GetRunningMachine: TFRE_DB_Guid;
function GetConfig : IFRE_DB_Object; { the config should be cleared, when syncing running jobs }
procedure SetConfig (AValue: IFRE_DB_Object);
procedure SetDontStartJob (AValue: Boolean);
function GetJobFilename : string;
procedure GetJobRemoteSSH ;
procedure SetJobLink (AValue: TFRE_DB_Guid);
procedure SetRunningMachine (AValue: TFRE_DB_Guid);
protected
procedure InternalSetup ; override;
procedure SetStatus (const status : TFRE_SignalStatus; const statussummary : string);
procedure SetDetailStatus (const detail : IFRE_DB_Object; const status : TFRE_SignalStatus; const statussummary : string);
procedure SetMaxAllowedTime (const time_s : NativeInt);
procedure SetJobStateAndDeleteFile (const value:TFRE_JobState);
public
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
function GetTransferFilename : TFRE_DB_String;
procedure SetTransferTimeStamp ;
procedure SaveJobToTransferred ;
procedure RemoveJobFromTransferred ;
procedure Do_the_Job ; { startroutine in safejob binary context }
procedure CheckNotRunningAndBinaryExists ;
function StartAsyncProcess (out childpid : integer; const config_mode : boolean=false):integer; { startroutine in starter context }
procedure SetJobRemoteSSH (const user : string; const host : string; const keyfilename : string ; const port : integer); { prepare to run the job through a ssh session on a "remote" remote system}
procedure ExecuteJob ; virtual;
function JobKey : string;
procedure SetJobkeyDescription (const newjobkey : string; const jdescription: string);
procedure SaveJobToFile ;
procedure DeleteJobFile ;
procedure SetJobStateandSave (const value:TFRE_JobState);
function GetJobState :TFRE_JobState;
procedure SetPid (const value : QWord);
function GetPid : QWord;
procedure ClearPid ;
procedure SetProgress (const percent:single);
procedure AddProgressLog (const key,msg: string ; const percent:single=-1);
procedure AddProgressLog (const key : string ; const stringparams:array of String ; const msg: string ; const percent:single=-1);
procedure AddProgressLog (const key : string ; const stringparams:array of String ; const msg: string ; const msg_params : array of const; const percent:single=-1);
procedure SetCurrentStateOnly (const key : string ; const msg: string ; const percent:single=-1);
procedure ManualStart (const only_safe_the_definition : boolean ; const config_mode : boolean=false);
procedure SetRecurrence (const rec : String);
function GetReport : TFRE_DB_JobReportPlugin;
function GetPidLockFilename : string;
class function GetJobBaseFilename (const state : TFRE_JobState; const vjobkey:string):string;
class function GetJobBaseDirectory (const state : TFRE_JobState):string;
procedure ClearConfig ;
property JobConfig : IFRE_DB_Object read GetConfig write SetConfig;
property DontStartImmediateJob : Boolean read GetDontStartJob write SetDontStartJob; { do not start the Jon on RIF_Start, job gets manually started, only definition is saved }
property JobObjectLink : TFRE_DB_Guid read GetJobLink write SetJobLink;
property RunningOnMachineId : TFRE_DB_Guid read GetRunningMachine write SetRunningMachine; { Only Set to the machineid if the job is running - INDEX }
procedure ClearRunningOnMachine ;
published
function RIF_Start (const runnning_ctx : TObject) : TFRE_DB_RIF_RESULT;
function RIF_Kill (const runnning_ctx : TObject) : TFRE_DB_RIF_RESULT;
function RIF_CreateJobDescription (const runnning_ctx : TObject) : IFRE_DB_Object; { "cron" like jobs }
function RIF_DeleteJobDescription (const runnning_ctx : TObject) : IFRE_DB_Object;
function RIF_GetAllJobDescriptions (const runnning_ctx : TObject) : IFRE_DB_Object; { "" }
end;
{ TFRE_DB_JOBREPORTPLUGIN }
TFRE_DB_JOBREPORTPLUGIN = class (TFRE_DB_STATUS_PLUGIN)
public
procedure SetProgress (const percent:single);
procedure AddProgressLog (const key,msg:string ; const stringparams : array of string); { Logkey (Translatable) - Msg (native) }
procedure SetCurrentState (const key,msg:string ; const stringparams : array of string); { Logkey (Translatable) - Msg (native) }
function HasStartTime :Boolean;
function HasEndTime :Boolean;
function GetStartTime (const utc:boolean=false): TFRE_DB_DateTime64;
function GetEndTime (const utc:boolean=false): TFRE_DB_DateTime64;
procedure SetStartTimeUTC (const dt : TFRE_DB_DateTime64);
procedure SetEndTimeUTC (const dt : TFRE_DB_DateTime64);
function GetCurProgressValue : Single;
function GetCurProgressTransKey : TFRE_DB_String;
function GetCurProgressStringParams : TFRE_DB_StringArray;
function GetCurrentProgressMsg : TFRE_DB_String;
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
{ TFRE_DB_TIMERTEST_JOB }
TFRE_DB_TIMERTEST_JOB=class(TFRE_DB_JOB)
protected
procedure InternalSetup ; override;
class procedure RegisterSystemScheme (const scheme : IFRE_DB_SCHEMEOBJECT); override;
public
procedure SetTimeout (const value:integer);
procedure ExecuteJob ; override;
end;
TFRE_DB_APPLICATION_MODULE_ITERATOR = procedure(const module : IFRE_DB_APPLICATION_MODULE;const modul_order:NativeInt) is nested;
{ TFRE_DB_APPLICATION}
TFRE_DB_APPLICATION = class (TFRE_DB_ObjectEx,IFRE_DB_APPLICATION) // Requires Named Object as Implementor
private
function GetSitemapMainiconFilename : string;
function GetSitemapMainiconSubpath : string;
procedure SetDescTranslationKey (const AValue: TFRE_DB_String);
function GetDescTranslationKey : TFRE_DB_String;
procedure SessionInitialize (const session : TFRE_DB_UserSession);virtual;
procedure SessionFinalize (const session : TFRE_DB_UserSession);virtual;
procedure SessionPromotion (const session : TFRE_DB_UserSession);virtual;
procedure SetSitemapMainiconFilename (AValue: string);
procedure SetSitemapMainiconSubpath (AValue: string);
protected
function IsContentUpdateVisible (const session : IFRE_DB_UserSession; const update_content_id:string):Boolean;
procedure InternalSetup ; override;
procedure SetupApplicationStructure ; virtual;
procedure AddApplicationModule (const module:TFRE_DB_APPLICATION_MODULE ; const sitemap_key : string='' ; const icon_path : string='');
function DelegateInvoke (const modulename:TFRE_DB_String;const methname:string;const input : IFRE_DB_Object):IFRE_DB_Object;
function IFRE_DB_APPLICATION.ObjectName = ObjectNameI;
procedure MySessionInitialize (const session: TFRE_DB_UserSession); virtual;
procedure MySessionPromotion (const session: TFRE_DB_UserSession); virtual;
procedure MySessionFinalize (const session: TFRE_DB_UserSession); virtual;
procedure MyServerInitialize (const admin_dbc : IFRE_DB_CONNECTION);virtual;
procedure MyUpdateSitemap (const session: TFRE_DB_UserSession);virtual;
procedure MyServerFinalize ;
function FetchOrInitFeederMachine (const ses: IFRE_DB_Usersession ; const configmachinedata : IFRE_DB_Object ; out machine_uid : TFRE_DB_GUID ; out BoundMachineName,BoundMachineMac : TFRE_DB_String):boolean; virtual;{ true if this app configures machines,datacenters and results the binding }
public
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class procedure EnableFeature4Domain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure EnableFeature4SysDomain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure DisableFeature4Domain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure DisableFeature4SysDomain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
procedure ForAllAppModules (const module_iterator:TFRE_DB_APPLICATION_MODULE_ITERATOR);
procedure ServerInitialize (const admin_dbc : IFRE_DB_CONNECTION);
procedure ServerFinalize (const admin_dbc : IFRE_DB_CONNECTION); // NOT IMPLEMENTED
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
procedure Finalize ;
procedure InitApp (const descr_translation_key:TFRE_DB_String; const icon: TFRE_DB_String='');virtual;
function AsObject : IFRE_DB_Object;
function AppClassName : ShortString;
function IsMultiDomainApp : Boolean; virtual;
function GetCaption (const ses : IFRE_DB_Usersession): TFRE_DB_String;
function GetIcon : TFRE_DB_String;
procedure AddAppToSiteMap (const session:IFRE_DB_UserSession ; const parent_entry : TFRE_DB_CONTENT_DESC);
function ShowInApplicationChooser (const session:IFRE_DB_UserSession): Boolean;virtual;
function IsConfigurationApp : Boolean;virtual;
function _FetchAppText (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;// FINALIZE THE OBJECT
function FetchAppTextShort (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextLong (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextHint (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchAppTextFull (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;// FINALIZE THE OBJECT
class procedure CreateAppText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
class procedure DeleteAppText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String);
class procedure UpdateAppText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
class function StdSidebarCaptionKey : TFRE_DB_String;
class function StdSitemapCaptionKey : TFRE_DB_String;
property SiteMapIconSubPath : string read GetSitemapMainiconSubpath write SetSitemapMainiconSubpath;
property SiteMapMainIconFilename : string read GetSitemapMainiconFilename write SetSitemapMainiconFilename;
published
function WEB_Content (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_OnUIChange (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
end;
{ TFRE_DB_APPLICATION_MODULE }
TFRE_DB_APPLICATION_MODULE = class (TFRE_DB_ObjectEx,IFRE_DB_APPLICATION_MODULE)
private
procedure SetSitemapIconFilename (AValue: TFRE_DB_String);
function GetSitemapIconFilename : TFRE_DB_String;
protected
procedure InternalSetup ; override;
procedure SetupAppModuleStructure ;virtual;
procedure AddApplicationModule (const module:TFRE_DB_APPLICATION_MODULE);
procedure InitModuleDesc (const descr_translation_key:TFRE_DB_String);virtual; deprecated ; { use the std translation keys }
function IFRE_DB_APPLICATION_MODULE.ObjectName = GetName;
function IFRE_DB_APPLICATION_MODULE.DEscription = GetDesc;
procedure MyServerInitializeModule (const admin_dbc : IFRE_DB_CONNECTION); virtual;
procedure CheckClassVisibility4AnyDomain(const session : IFRE_DB_UserSession);virtual;
procedure CheckClassVisibility4MyDomain (const session : IFRE_DB_UserSession);virtual;
public
class procedure EnableFeature4Domain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure EnableFeature4SysDomain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure DisableFeature4Domain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure DisableFeature4SysDomain (const conn:IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID : TFRE_DB_GUID); virtual;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
class function StdSitemapModuleTitleKey : TFRE_DB_String;
class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override;
procedure ForAllAppModules (const module_iterator:TFRE_DB_APPLICATION_MODULE_ITERATOR);
procedure MySessionInitializeModule (const session : TFRE_DB_UserSession);virtual;
procedure MySessionPromotionModule (const session: TFRE_DB_UserSession); virtual;
procedure MySessionFinalizeModule (const session : TFRE_DB_UserSession);virtual;
function ShowInSession (const ses : IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const app: IFRE_DB_APPLICATION): Boolean; virtual;
function GetEmbeddingApp : TFRE_DB_APPLICATION;
function _FetchAppText (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;
function GetToolbarMenu (const ses : IFRE_DB_Usersession): TFRE_DB_CONTENT_DESC; virtual;
function GetDependencyFiltervalues (const input:IFRE_DB_Object; const dependencyfield:string): TFRE_DB_StringArray;
procedure SetDescrTranslationKey (const val:TFRE_DB_String); deprecated;
function GetDescrTranslationKey :TFRE_DB_String; deprecated;
function GetModuleTitle (const ses : IFRE_DB_Usersession): TFRE_DB_String;
function GetModuleClassName : Shortstring;
function AsObject : IFRE_DB_Object;
function IsContentUpdateVisible (const session: IFRE_DB_UserSession; const update_content_id:string):Boolean;
function _FetchModuleText (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;// FINALIZE THE OBJECT
function FetchModuleTextShort (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchModuleTextLong (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchModuleTextHint (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):TFRE_DB_String;
function FetchModuleTextFull (const session:IFRE_DB_UserSession;const translation_key:TFRE_DB_String):IFRE_DB_TEXT;// FINALIZE THE OBJECT
class procedure CreateModuleText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
class procedure DeleteModuleText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String);
class procedure UpdateModuleText (const conn: IFRE_DB_SYS_CONNECTION;const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String='');
property SitemapIconFilename :TFRE_DB_String read GetsitemapIconFilename write SetSitemapIconFilename;
published
function WEB_Content (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
function WEB_OnUIChange (const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;
end;
// Describes a basic content Element
// The content has an contentID and uses as Internal representation a (temporary/non saved) DBO
{ TFRE_DB_CONTENT_DESC }
TFRE_DB_CONTENT_DESC = class(TFRE_DB_ObjectEx)
private
function GetContentId : TFRE_DB_String;
function GetUpdateId : TFRE_DB_String;
function GetWindowCaption : TFRE_DB_String;
procedure SetContentId (AValue: TFRE_DB_String);
procedure SetUpdateId (AValue: TFRE_DB_String);
procedure SetWindowCaption(AValue: TFRE_DB_String);
published
// An id to indentify the content
property contentId : TFRE_DB_String read GetContentId write SetContentId;
// This content should update an content with contentID (don't forget to set a new(the same) contentID again! (updateID is only for special cases, as if updateID is unset contentID is used in update case)
property updateId : TFRE_DB_String read GetUpdateId write SetUpdateId;
property windowCaption: TFRE_DB_String read GetWindowCaption write SetWindowCaption;
end;
{ TFRE_DB_UPDATE_STORE_DESC }
TFRE_DB_UPDATE_STORE_DESC = class(TFRE_DB_CONTENT_DESC) { the positions must be set correctly (!!!) }
public
//@ Describes an update of a store.
function Describe (const storeId:String ; const storeid_dc:string=''):TFRE_DB_UPDATE_STORE_DESC;
//@ Adds an updated entry and moves it to a new Position.
procedure addUpdatedEntry (const entry: IFRE_DB_Object ; const old_position,new_position: Int64 ; const absolutecount: Int64);
//@ Adds the id of a deleted entry.
procedure addDeletedEntry (const entryId: String ; const position: Int64 ; const absolutecount: Int64);
//@ Adds a new entry.
//@ parentId is only useful for tree grids. If not parentId is given the new item is added as root item.
//@ use nextItemId = '' to insert the new item at the end of the query.
procedure addNewEntry (const entry: IFRE_DB_Object; const position: Int64 ; const absolutecount: Int64);
//@ Sets the new total count.
procedure setTotalCount (const count: Integer);
procedure ForAllUpdated (const obcb : IFRE_DB_Obj_Iterator);
procedure ForAllInserted (const obcb : IFRE_DB_Obj_Iterator);
function GetStoreID : TFRE_DB_NameType;
function GetStoreID_DC : TFRE_DB_NameType; { get only the derived collection part of the storeid }
function hasChanges : Boolean;
end;
{ TFRE_DB_NIL_DESC }
//@ Describes "No Reply". E.g. User answers no to a confirm deletion dialog.
TFRE_DB_NIL_DESC = class(TFRE_DB_CONTENT_DESC)
public class
var NILInstances : NativeInt;
public
constructor Create ;
procedure Free ;
destructor Destroy ; override;
destructor DestroySingleton ;
procedure FreeFromBackingDBO ; override;
end;
//@ This suppresses the sync answer to the client, a Sync answer should be sent in time by another method
{ TFRE_DB_SUPPRESS_ANSWER_DESC }
TFRE_DB_SUPPRESS_ANSWER_DESC=class(TFRE_DB_ObjectEx)
public class
var NILInstances : NativeInt;
constructor Create ;
procedure Free ;
destructor Destroy ;override;
destructor DestroySingleton ;
procedure FreeFromBackingDBO ; override;
end;
{ TFRE_DB_PARAM_DESC }
TFRE_DB_PARAM_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a single parameter for a parameterizable content.
function Describe (const key,value: string):TFRE_DB_PARAM_DESC;
//@ Describes a single parameter with multiple values for a parameterizable content.
function Describe (const key:String;const value:TFRE_DB_StringArray):TFRE_DB_PARAM_DESC;
end;
{ TFRE_DB_SERVER_FUNC_DESC }
TFRE_DB_SERVER_FUNC_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a server function of a known object.
function Describe (const obj: IFRE_DB_Object; const func: String):TFRE_DB_SERVER_FUNC_DESC;
//@ Describes a server function of a known object.
function Describe (const oschemeclass: String;const ouid :TFRE_DB_GUID; const func: String):TFRE_DB_SERVER_FUNC_DESC;
function Describe (const oschemeclass: String;const uidpath:TFRE_DB_StringArray; const func: String):TFRE_DB_SERVER_FUNC_DESC;
//@ Describes a server class function of the given schemeclass (e.g. new operations) or
//@ a server function of an unknown object of the given schemeclass (e.g. menu function of a grid entry).
function Describe (const oschemeclass: String; const func: String):TFRE_DB_SERVER_FUNC_DESC;
function InternalInvoke (const session: TFRE_DB_UserSession): IFRE_DB_Object;
function InternalInvokeDI (const session: TFRE_DB_UserSession ; const input : IFRE_DB_OBJECT): IFRE_DB_Object;
//@ Internally invokes a server function, on a given session
function AddParam : TFRE_DB_PARAM_DESC;
//@ Creates a new parameter and adds it to the parameterizable content.
function hasParam : Boolean;
end;
{ TFRE_DB_MESSAGE_DESC }
TFRE_DB_MESSAGE_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a message of the given type (error, info or confirm).
//@ The server function will be called after the user clicks a button.
//@ For confirm dialogs the server function is required.
//@ For wait dialogs an abort button will be displayed if a server function is given and a progressBar will be displayed if the progressBarId is specified.
function Describe (const caption,msg: String;const msgType:TFRE_DB_MESSAGE_TYPE;const serverFunc:TFRE_DB_SERVER_FUNC_DESC=nil;const progressBarId: String=''): TFRE_DB_MESSAGE_DESC;
end;
{ TFRE_DB_OPEN_NEW_LOCATION_DESC }
TFRE_DB_OPEN_NEW_LOCATION_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a new browser window.
function Describe (const url: String; const inNewWindow: Boolean=true): TFRE_DB_OPEN_NEW_LOCATION_DESC;
end;
{ TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC }
TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC = class(TFRE_DB_CONTENT_DESC)
//@ Describes an update of a progress indicator within a message dialog.
function Describe (const progressBarId: String; const percentage: Real): TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC;
end;
{ TFRE_DB_EDITOR_DATA_DESC }
TFRE_DB_EDITOR_DATA_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the data for an editor.
function Describe (const value: String): TFRE_DB_EDITOR_DATA_DESC;
end;
{ TFRE_DB_REFRESH_STORE_DESC }
TFRE_DB_REFRESH_STORE_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a refresh action. E.g. after an add opertion.
function Describe (const storeId: String): TFRE_DB_REFRESH_STORE_DESC;
end;
{ TFRE_DB_CLOSE_DIALOG_DESC }
TFRE_DB_CLOSE_DIALOG_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a refresh action. E.g. after an add opertion.
function Describe (): TFRE_DB_CLOSE_DIALOG_DESC;
end;
TFRE_DB_MENU_DESC = class;
{ TFRE_DB_SECTION_DESC }
TFRE_DB_SECTION_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const title :String; const ord:Int16; const sectionId:String; const size:Integer): TFRE_DB_SECTION_DESC;
public
//@ Describes a single section of the subsections description.
//@ The contentFunc is used to get the content description of the section.
//@ The ord parameter can be used to sort the sections.
function Describe (const contentFunc:TFRE_DB_SERVER_FUNC_DESC;const title :String; const ord:Int16; const sectionId:String=''; const size:Integer=-1): TFRE_DB_SECTION_DESC;
//@ Used by the framework.
//@ DO NO USE.
function _internalDescribe (const content:TFRE_DB_CONTENT_DESC;const title :String; const ord:Int16; const sectionId:String=''; const size:Integer=-1): TFRE_DB_SECTION_DESC;
//@ Sets the section as the active one.
//@ Only usefull in case of display type sec_dt_tab
procedure SetActive (const active: Boolean);
//@ Sets the menu of the section. Will be displayed like a file menu in a desktop application.
procedure SetMenu (const menu: TFRE_DB_MENU_DESC);
end;
{ TFRE_DB_SUBSECTIONS_DESC }
TFRE_DB_SUBSECTIONS_DESC = class(TFRE_DB_CONTENT_DESC)
private
fnoActiveSectionSet: Boolean;
factiveSectionOrd : Integer;
procedure SetActiveSectionUID (const sectionUID: String);
procedure SectionDescribed (const sectionUID: String; const ord,size: Integer);
public
constructor Create ;
//@ Describes a collection of content which is displayed either as tabs or vertical arranged with resize handlers.
function Describe (const displayType: TFRE_DB_SUBSEC_DISPLAY_TYPE=sec_dt_tab): TFRE_DB_SUBSECTIONS_DESC;
//@ The serverFunction will be called on an ui change. In this case tab change if the display type is sec_dt_tab.
//@ FIXXME - finish implementation.
procedure OnUIChange (const serverFunc: TFRE_DB_SERVER_FUNC_DESC);
//@ Creates a new section and adds it.
//@ The size parameter is only useful for the display type sec_dt_vertical.
function AddSection : TFRE_DB_SECTION_DESC;
//@ Set the section with the given id as active section.
procedure SetActiveSection (const sectionId: String);
end;
{ TFRE_DB_MENU_ENTRY_DESC }
TFRE_DB_MENU_ENTRY_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const caption,icon:String; const disabled:Boolean; const descr: String):TFRE_DB_MENU_ENTRY_DESC;
public
//@ Describes a menu entry. See also TFRE_DB_MENU_DESC and TFRE_DB_SUBMENU_DESC.
//@ descr parameter should not be used for the main entries of a toolbarmenu
function Describe (const caption,icon:String; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const disabled:Boolean=false; const id:String=''; const descr:String=''):TFRE_DB_MENU_ENTRY_DESC;
function DescribeDownload (const caption,icon:String; const downloadId: String; const disabled:Boolean=false; const descr:String=''):TFRE_DB_MENU_ENTRY_DESC;
end;
TFRE_DB_SUBMENU_DESC = class;
{ TFRE_DB_MENU_DESC }
TFRE_DB_MENU_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a menu.
function Describe : TFRE_DB_MENU_DESC;
//@ Creates a new menu entry description and adds it.
function AddEntry : TFRE_DB_MENU_ENTRY_DESC;
//@ Creates a new sub menu description and adds it.
function AddMenu : TFRE_DB_SUBMENU_DESC;
end;
{ TFRE_DB_SUBMENU }
TFRE_DB_SUBMENU_DESC = class(TFRE_DB_MENU_DESC)
public
//@ Describes a sub menu. See TFRE_DB_MENU_DESC.
function Describe (const caption,icon: String; const disabled:Boolean=false; const id:String=''):TFRE_DB_SUBMENU_DESC;
end;
{ TFRE_DB_RESTORE_UI_DESC }
TFRE_DB_RESTORE_UI_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a client side function which should be called.
//@ baseContainerId: Start point of the sectionIds path. Can be a section description or a layout description or 'FirmOSViewport' to start at the top.
function Describe (const baseContainerId: String; const sectionIds: TFRE_DB_StringArray): TFRE_DB_RESTORE_UI_DESC;
end;
{ TFRE_DB_UPDATE_FORM_DESC }
TFRE_DB_UPDATE_FORM_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes an update of a form dbo. All Forms including the given updateObj will be updated.
//@ updateObj has to hold all changes (added, modified and deleted fields (delta object))
function DescribeDBO (const updateObj:IFRE_DB_Object):TFRE_DB_UPDATE_FORM_DESC;
//@ Describes an update of a form. The form with the given id will be updated be the given object.
function Describe (const formId: String; const updateObj:IFRE_DB_Object):TFRE_DB_UPDATE_FORM_DESC;
//@ Describes an update of a form. The form with the given id will be updated be the given object.
function DescribeReset (const formId: String):TFRE_DB_UPDATE_FORM_DESC;
end;
{ TFRE_DB_SITEMAP_ENTRY_DESC }
TFRE_DB_SITEMAP_ENTRY_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a sitemap entry.
//@ Top level entries are arranged automatically. Therefore parameters x and y are ignored for top level entries.
function Describe (const caption,icon:String; const restoreUIFunc: TFRE_DB_RESTORE_UI_DESC; const x,y:Integer; const id:String=''; const newsCount:Integer=0; const disabled:Boolean=false; const scale:Single=1): TFRE_DB_SITEMAP_ENTRY_DESC;
//@ Creates a new sitemap entry description and adds it.
function AddEntry : TFRE_DB_SITEMAP_ENTRY_DESC;
end;
{ TFRE_DB_SVG_DEF_ELEM_ATTR_DESC }
TFRE_DB_SVG_DEF_ELEM_ATTR_DESC = class(TFRE_DB_CONTENT_DESC)
//@ Describes an attribute of a SVG definitions element.
function Describe (const name,value:String): TFRE_DB_SVG_DEF_ELEM_ATTR_DESC;
end;
{ TFRE_DB_SVG_DEF_ELEM_DESC }
TFRE_DB_SVG_DEF_ELEM_DESC = class(TFRE_DB_CONTENT_DESC)
//@ Describes a SVG definitions element. E.g. linearGradient.
function Describe (const tagName:String): TFRE_DB_SVG_DEF_ELEM_DESC;
//@ Adds a sub element. E.g. a 'stop' element to a 'linearGradiant'
function AddElement :TFRE_DB_SVG_DEF_ELEM_DESC;
//@ Adds an attribute.
function AddAttribute :TFRE_DB_SVG_DEF_ELEM_ATTR_DESC;
end;
TFRE_DB_SVG_DEF_ELEM_DESC_ARRAY = array of TFRE_DB_SVG_DEF_ELEM_DESC;
{ TFRE_DB_SITEMAP_DESC }
TFRE_DB_SITEMAP_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a sitemap/structure of the application.
function Describe (const svgDefs: TFRE_DB_SVG_DEF_ELEM_DESC_ARRAY=nil): TFRE_DB_SITEMAP_DESC;
//@ Creates a new sitemap entry description and adds it.
function AddEntry : TFRE_DB_SITEMAP_ENTRY_DESC;
end;
{ TFRE_DB_STORE_DATA_DESC }
TFRE_DB_STORE_DATA_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the result of store data request. (e.g. grid, chart...)
function Describe (const totalCount: Int32): TFRE_DB_STORE_DATA_DESC;
//@ Adds an entry to the result.
procedure addEntry (const entry: IFRE_DB_Object);
end;
TFRE_DB_SERVER_FUNC_DESC_ARRAY = Array of TFRE_DB_SERVER_FUNC_DESC;
TFRE_DB_DESCRIPTION_CLASS = class of TFRE_DB_CONTENT_DESC;
IFRE_DB=interface
procedure GenerateAnObjChangeList (const first_obj, second_obj: IFRE_DB_Object ; const InsertCB,DeleteCB : IFRE_DB_Obj_Iterator ; const UpdateCB : IFRE_DB_UpdateChange_Iterator);
procedure GenerateAnObjChangeListTagField (const tagfieldname : TFRE_DB_NameType ; const first_obj, second_obj: IFRE_DB_Object ; const InsertCB,DeleteCB : IFRE_DB_Obj_Iterator ; const UpdateCB : IFRE_DB_UpdateChange_Iterator);
function CompareObjectsEqual (const first_obj, second_obj: IFRE_DB_Object) :Boolean; { true if equal }
function CompareObjectsEqualByTagfield (const tagfield : TFRE_DB_NameType ; const first_obj, second_obj: IFRE_DB_Object) :Boolean; { true if equal }
function DumpObjectDifferences (const first_obj, second_obj: IFRE_DB_Object; out difference_list : IFOS_STRINGS):boolean;
function NewDBCommand : IFRE_DB_COMMAND;
function FetchApplications (var apps : IFRE_DB_APPLICATION_ARRAY; var loginapp: IFRE_DB_APPLICATION):TFRE_DB_Errortype;
function GetFormatSettings : TFormatSettings;
function GetLocalZone : TFRE_DB_String;
procedure SetFormatSettings (const AValue: TFormatSettings);
procedure SetLocalZone (const AValue: TFRE_DB_String);
function LocalTimeToUTCDB64 (const ADateTime64: TFRE_DB_DateTime64) : TFRE_DB_DateTime64;
function UTCToLocalTimeDB64 (const ADateTime64: TFRE_DB_DateTime64) : TFRE_DB_DateTime64;
function NewText (const key,txt,txt_short:TFRE_DB_String;const hint:TFRE_DB_String=''):IFRE_DB_TEXT;
function NewRole (const rolename,txt,txt_short:TFRE_DB_String;const is_internal:Boolean=false):IFRE_DB_ROLE;
function NewGroup (const groupname,txt,txt_short:TFRE_DB_String;const is_protected:Boolean=false;const is_internal:Boolean=false):IFRE_DB_GROUP;
function NewClientFieldValidator (const name: TFRE_DB_String) : IFRE_DB_ClientFieldValidator;
function NewEnum (const name: TFRE_DB_String) : IFRE_DB_Enum;
function RegisterSysClientFieldValidator (const val : IFRE_DB_ClientFieldValidator):TFRE_DB_Errortype;
function RegisterSysEnum (const enu : IFRE_DB_Enum):TFRE_DB_Errortype;
function GetSystemSchemeByName (const schemename:TFRE_DB_NameType; var scheme: IFRE_DB_SchemeObject ; const dont_raise : boolean=false): Boolean;
function GetSystemScheme (const schemename:TClass; var scheme: IFRE_DB_SchemeObject ; const dont_raise : boolean=false): Boolean;
function GetSystemEnum (const name:TFRE_DB_NameType ; out enum : IFRE_DB_Enum ; const dont_raise : boolean=false):boolean;
function GetSystemClientFieldValidator (const name:TFRE_DB_NameType ; out clf : IFRE_DB_ClientFieldValidator ; const dont_raise : boolean=false):boolean;
function GetClassesDerivedFrom (const SchemeClass : ShortString) : TFRE_DB_ObjectClassExArray;
function GetSchemesDerivedFrom (const SchemeClass : ShortString) : IFRE_DB_SCHEMEOBJECTArray;
function GetObjectClassEx (const ClName:ShortString) : TFRE_DB_OBJECTCLASSEX;
function NewObjectIntf (const InterfaceSpec:ShortString;out Intf;const mediator : TFRE_DB_ObjectEx=nil;const fail_on_non_existent:boolean=true) : Boolean;
function NewObject : IFRE_DB_Object;
function NewObjectScheme (const Scheme : TClass): IFRE_DB_Object;
function NewObjectSchemeByName (const Scheme : TFRE_DB_NameType): IFRE_DB_Object;
function AnonObject2Interface (const Data : Pointer):IFRE_DB_Object;
function CreateFromFile (const filename:TFRE_DB_String):IFRE_DB_Object;
function CreateFromMemory (memory : Pointer):IFRE_DB_Object;
function CreateFromString (const AValue:TFRE_DB_String):IFRE_DB_Object;
function CreateFromJSONString (const AValue:TFRE_DB_String):IFRE_DB_Object;
function NewConnection (const direct : boolean = true): IFRE_DB_CONNECTION;
function NewSysOnlyConnection : IFRE_DB_SYS_CONNECTION; // always direct=embedded
function DatabaseList (const user:TFRE_DB_String='';const pass:TFRE_DB_String=''): IFOS_STRINGS;
procedure DBInitializeAllExClasses (const conn:IFRE_DB_CONNECTION);
procedure DBInitializeAllSystemClasses (const conn:IFRE_DB_CONNECTION); // not impemented by now (no initializable sys classes, keep count low)
function StringArray2String (const A:TFRE_DB_StringArray):TFRE_DB_String;
function GuidArray2SString (const A:TFRE_DB_GUIDArray):TFRE_DB_String;
function StringArray2GuidArray (const A:TFRE_DB_StringArray):TFRE_DB_GUIDArray;
function CountedObjLinks2String (const A:TFRE_DB_CountedGuidArray):TFRE_DB_String;
function IsAClassOrDerived (const classname:shortstring ; const classtype : TFRE_DB_ObjectClassEx):boolean;
function CreateText (const translation_key:TFRE_DB_String;const short_text:TFRE_DB_String;const long_text:TFRE_DB_String='';const hint_text:TFRE_DB_String=''):IFRE_DB_TEXT;
function JSONObject2Object (const json_string: string; const fieldtype_fixed_string: boolean=true): IFRE_DB_Object;
procedure RegisterObjectClassEx (const ExtensionObject : TFRE_DB_OBJECTCLASSEX);
procedure RegisterFeature (const featurename : TFRE_DB_NameType); { Introduce a possible feature }
function GetFeatureList : IFOS_STRINGS; { get possible features }
function IsFeatureRegistered (const featurename : TFRE_DB_NameType):Boolean;
procedure LogDebug (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogInfo (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogEmergency (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogWarning (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogError (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogNotice (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString;const param:array of const);
procedure LogDebug (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogInfo (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogEmergency (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogWarning (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogError (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogNotice (const category:TFRE_DB_LOGCATEGORY;const msg:ShortString);
procedure LogDebugIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
procedure LogInfoIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
procedure LogWarningIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
procedure LogErrorIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
procedure LogNoticeIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
procedure LogEmergencyIf (const category:TFRE_DB_LOGCATEGORY;const logcallback : TFRE_SimpleCallbackNested);
function Get_A_Guid : TFRE_DB_GUID;
function Get_A_Guid_HEX : Ansistring;
property LocalZone : TFRE_DB_String read GetLocalZone write SetLocalZone;
property StringFormatSettings : TFormatSettings read GetFormatSettings write SetFormatSettings;
function NetServ : IFRE_DB_NetServer;
end;
//OFRE_InputFieldDef4Group = record
// typ : TFRE_InputGroupDefType;
// field : TFRE_DB_NameType;
// scheme : string[255]; //path
// collapsible,
// collapsed,
// required,
// chooser_add_empty,
// hideSingle,
// disabled,
// hidden : Boolean;
// caption_key : TFRE_DB_NameType;
// group : TFRE_DB_NameType;
// prefix : TFRE_DB_NameType;
// datacollection : TFRE_DB_NameType;
// standardcoll : TFRE_DB_STANDARD_COLL;
// chooser_type : TFRE_DB_CHOOSER_DH;
// std_right : Char; //TFRE_DB_STANDARD_RIGHT;
// right_class : TFRE_DB_NameType;
// fieldschemdef : IFRE_DB_FieldSchemeDefinition; // points to
//end;
//
//
//PFRE_InputFieldDef4Group = ^OFRE_InputFieldDef4Group;
//PFRE_InputFieldDef4GroupArr = Array of PFRE_InputFieldDef4Group;
TFRE_DB_InputGroupFieldProperty = (gfp_Required,gfp_CollectionIsDerived,gfp_HideSingle,gfp_Hidden,gfp_ChooserAddEmptyValue,gfp_Disabled,gfp_Collapsible,gfp_Collapsed);
TFRE_DB_InputGroupFieldproperties = set of TFRE_DB_InputGroupFieldProperty;
IFRE_DB_FieldDef4Group=interface
function GetType : TFRE_InputGroupDefType;
function GetGroup : TFRE_DB_NameType;
function GetPrefix : TFRE_DB_String;
function GetIndentEC : Boolean;
function GetBlockElemSizes : TFRE_DB_Int32Array;
function GetScheme : TFRE_DB_String;
function GetStdRight : TFRE_DB_STANDARD_RIGHT; // FREDB_String2StdRightShort(obj^.std_right)
function GetRightClass : Shortstring;
function GetDatacollection : TFRE_DB_NameType;
function GetRequired : Boolean;
function GetCollectionIsDerived : Boolean;
function GetHideSingle : Boolean;
function GetHidden : Boolean;
function GetChooserAddEmptyValue : Boolean;
function GetDisabled : Boolean;
function GetCollapsible : Boolean;
function GetCollapsed : Boolean;
function GetStandardCollection : TFRE_DB_STANDARD_COLL;
function GetCaptionKey : TFRE_DB_NameType;
function GetfieldName : TFRE_DB_NameType;
function GetDefault : String;
function GetValidator (var validator: IFRE_DB_ClientFieldValidator):Boolean;
function GetValidatorParams : IFRE_DB_Object;
function GetChooserType : TFRE_DB_CHOOSER_DH;
function FieldSchemeDefinition : IFRE_DB_FieldSchemeDefinition;
end;
IFRE_DB_FieldDef4GroupArr = array of IFRE_DB_FieldDef4Group;
{ IFRE_DB_InputGroupSchemeDefinition }
IFRE_DB_InputGroupSchemeDefinition=interface
function GetCaptionKey : TFRE_DB_NameType;
function Setup (const caption: TFRE_DB_String):IFRE_DB_InputGroupSchemeDefinition;
function GetParentScheme : IFRE_DB_SchemeObject;
procedure AddInput (const schemefield: TFRE_DB_String; const cap_trans_key: TFRE_DB_String=''; const disabled: Boolean=false;const hidden:Boolean=false; const default_value:String=''; const field_backing_collection: TFRE_DB_String='';const fbCollectionsIsDerivedCollection:Boolean=false; const chooser_type:TFRE_DB_CHOOSER_DH=dh_chooser_combo; const standard_coll: TFRE_DB_STANDARD_COLL=coll_NONE; const chooserAddEmptyForRequired: Boolean=false; const validator_key:TFRE_DB_NameType=''; const validator_params : IFRE_DB_Object=nil);
procedure AddDomainChooser (const schemefield: TFRE_DB_String; const std_right:TFRE_DB_STANDARD_RIGHT; const rightClasstype: TClass; const hideSingle: Boolean; const cap_trans_key: TFRE_DB_String='');
procedure UseInputGroup (const scheme,group: TFRE_DB_String; const addPrefix: TFRE_DB_String='';const as_gui_subgroup:boolean=false ; const collapsible:Boolean=false;const collapsed:Boolean=false);
procedure UseInputGroupAsBlock (const scheme,group: TFRE_DB_String; const addPrefix: TFRE_DB_String='';const indentEmptyCaption: Boolean=true;const blockElemSizes: TFRE_DB_Int32Array=nil);
property CaptionKey : TFRE_DB_NameType read GetCaptionKey;
function GroupFields : IFRE_DB_FieldDef4GroupArr;
end;
TFRE_DB_OnCheckUserNamePassword = function (username,pass:TFRE_DB_String) : TFRE_DB_Errortype of object;
TFRE_DB_OnGetImpersonatedConnection = function (const db,username,pass:TFRE_DB_String;out conn : IFRE_DB_CONNECTION):TFRE_DB_Errortype of object;
TFRE_DB_OnRestoreDefaultConnection = function (out username:TFRE_DB_String;out conn : IFRE_DB_CONNECTION):TFRE_DB_Errortype of object;
TFRE_DB_OnExistsUserSessionForKey = function (const key:string;out other_session:TFRE_DB_UserSession):boolean of object;
TFRE_DB_OnFetchPublisherSession = function (const rcall,rmeth:TFRE_DB_NameType;out ses:TFRE_DB_UserSession ; out right:TFRE_DB_String):boolean of object;
TFRE_DB_OnFetchSessionByID = function (const sessionid : TFRE_DB_SESSION_ID ; var session : TFRE_DB_Usersession):boolean of object;
TFRE_DB_PromoteResult = (pr_OK,pr_Failed,pr_Takeover,pr_TakeoverPrepared);
{ TFRE_DB_UserSession }
TFRE_DB_EVENT_METHOD_ENC=class
public
method : IFRE_DB_InvokeClassMethod;
params : IFRE_DB_Object;
end;
TFRE_DB_GenericCBMethod = procedure() of object;
TFRE_DB_RemoteCB = procedure(const ses : IFRE_DB_UserSession ; const data : IFRE_DB_Object ; const status : TFRE_DB_COMMAND_STATUS ; const original_command_id : Qword ; const opaquedata : IFRE_DB_Object) of object;
TFRE_DB_RemoteCB_RIF = procedure(const ses : IFRE_DB_UserSession ; const rif_result : TFRE_DB_RIF_RESULT ; const original_command_id : Qword ; const opaquedata : IFRE_DB_Object) of object;
IECF_SystemConfiguration=interface
function HasFeature (const feature_name:TFRE_DB_NameType):Boolean;
function GetSystemMAC : TFOS_MAC_ADDR; { should be provisioningmac }
function IsSystemManaged : Boolean; { True = MOS Managed Machine / false = one DC,one Machine}
function IsConfigurationMode : Boolean; { True = the system is in configuration mode }
end;
{ IFRE_DB_UserSession }
IFRE_DB_UserSession=interface
function GetSessionID : TFRE_DB_SESSION_ID;
function GetSessionState : TFRE_DB_SESSIONSTATE;
function GetSessionAppData (const app_key:TFRE_DB_String):IFRE_DB_Object;
function GetSessionModuleData (const mod_key:TFRE_DB_String):IFRE_DB_Object;
function GetSessionGlobalData :IFRE_DB_Object;
function NewDerivedCollection (dcname:TFRE_DB_NameType):IFRE_DB_DERIVED_COLLECTION; // Session DC
function FetchDerivedCollection (dcname:TFRE_DB_NameType):IFRE_DB_DERIVED_COLLECTION;
function GetDBConnection :IFRE_DB_CONNECTION;
function GetSessionChannelGroup : IFRE_APSC_CHANNEL_GROUP;
function GetSessionAppArray : IFRE_DB_APPLICATION_ARRAY;
function LoggedIn : Boolean;
procedure Logout ;
function Promote (const user_name,password:TFRE_DB_String;var promotion_status:TFRE_DB_String; force_new_session_data : boolean ; const session_takeover : boolean ; const auto_promote : boolean=false ; const allowed_user_classes: array of TFRE_DB_String) : TFRE_DB_PromoteResult; // Promote USER to another USER
procedure SendServerClientRequest (const description : TFRE_DB_CONTENT_DESC;const session_id:TFRE_DB_SESSION_ID='');
procedure SendServerClientAnswer (const description : TFRE_DB_CONTENT_DESC;const answer_id : Qword);
//Send a Server Client Message in behalv of another session (think about security)
// ses.SendDelegatedEventToSession(sessionID,SF,input.CloneToNewObject());
//Invoke a Method that another Session provides via Register, in the context of that session (feeder session)
function GetMachineUidByName (const mname : TFRE_DB_String ; out machuid : TFRE_DB_GUID):boolean;
function GetMachineUidByMac (const mac : TFOS_MAC_ADDR ; out machuid : TFRE_DB_GUID):boolean;
function InvokeRemoteRequest (const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
function InvokeRemoteRequestMachine (const machineid : TFRE_DB_GUID ; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
function InvokeRemoteRequestMachineMac (const machine_mac : TFRE_DB_NameType ; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
function InvokeRemoteInterface (const machineid : TFRE_DB_GUID ; const RIFMethod:TFRE_DB_RIF_Method; const CompletionCallback: TFRE_DB_RemoteCB_RIF ; const opaquedata: IFRE_DB_Object=nil) : TFRE_DB_Errortype;
function InternalSessInvokeMethod (const class_name,method_name:string;const uid_path:TFRE_DB_GUIDArray;var input:IFRE_DB_Object):IFRE_DB_Object;
function RegisterTaskMethod (const TaskMethod:IFRE_DB_WebTimerMethod ; const invocation_interval : integer ; const id :TFRE_APSC_ID='TIMER') : boolean;
function RemoveTaskMethod (const id:string='TIMER'):boolean;
function GetCurrentRequestID : QWord; { warning this is a side effect }
function SysConfig :IECF_SystemConfiguration;
procedure ClearUpdatable ;
procedure RegisterUpdatableContent (const contentId: String);
procedure UnregisterUpdatableContent (const contentId: String);
procedure RegisterUpdatableDBO (const UID_id: TFRE_DB_GUID);
procedure UnregisterUpdatableDBO (const UID_id: TFRE_DB_GUID);
procedure RegisterDBOChangeCB (const UID_id: TFRE_DB_GUID; const callback: TFRE_DB_SERVER_FUNC_DESC; const contentId: TFRE_DB_String);
procedure UnregisterDBOChangeCB (const contentId: TFRE_DB_String);
function getDBOChangeCBs (const UID_id: TFRE_DB_GUID):IFRE_DB_Object;
function IsUpdatableContentVisible (const contentId: String): Boolean;
function IsDBOUpdatable (const UID_id: TFRE_DB_GUID):boolean;
function IsInteractiveSession : Boolean;
function GetDownLoadLink4StreamField (const obj_uid: TFRE_DB_GUID; const fieldname: TFRE_DB_NameType; const is_attachment: boolean; mime_type: string; file_name: string ; force_url_etag : string=''): String; { Make a DBO Stream Field Downloadable in a Session context }
function GetUserName : String;
function GetDomain : TFRE_DB_String; { domainname of logged in user }
function GetDomainUID : TFRE_DB_GUID; { domain id of logged in user }
function GetDomainUID_String : TFRE_DB_GUID_String; { domain id as string of logged in user }
procedure InboundNotificationBlock (const block: IFRE_DB_Object); { Here comes an Inbound Notification block from the network/pl layer}
function GetSyncWaitEvent (out e:IFOS_E):boolean;
function SubscribeGlobalEvent (const ev_name : TFRE_DB_NameType ; const event_callback : IFRE_DB_SessionDataCallback) : boolean; { true= first register, false= update }
procedure UnsubscribeGlobalEvent (const ev_name : TFRE_DB_NameType);
procedure PublishGlobalEvent (const ev_name : TFRE_DB_NameType ; const ev_data : IFRE_DB_Object);
procedure PublishGlobalEventText (const ev_name : TFRE_DB_NameType ; const ev_data : Shortstring);
end;
TFRE_DB_RemoteReqSpec = record
classname : TFRE_DB_NameType;
methodname : TFRE_DB_NameType;
invokationright : TFRE_DB_String;
end;
TFRE_DB_RemoteReqSpecArray = array of TFRE_DB_RemoteReqSpec;
{ TFRE_DB_RemoteSessionInvokeEncapsulation }
TFRE_DB_RemoteSessionInvokeEncapsulation=class
private
Fclassname, Fmethodname : TFRE_DB_NameType;
Finput : IFRE_DB_Object;
FSyncCallback : TFRE_DB_GenericCBMethod;
Fopaquedata : IFRE_DB_Object;
FsessionID : TFRE_DB_SESSION_ID;
FOCid : QWord;
FIsRifCB : Boolean;
public
constructor Create(const rclassname, rmethodname: TFRE_DB_NameType ; const ocid : QWord ; const SessionID: TFRE_DB_SESSION_ID; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_GenericCBMethod; const opaquedata: IFRE_DB_Object ; const is_rif_cb : boolean);
end;
{ TFRE_DB_RemoteSessionAnswerEncapsulation }
TFRE_DB_RemoteSessionAnswerEncapsulation=class
private
FData : IFRE_DB_Object;
FStatus : TFRE_DB_COMMAND_STATUS;
Fopaquedata : IFRE_DB_Object;
FOCid : Qword;
FContmethod : TFRE_DB_GenericCBMethod;
FIsRifCB : Boolean;
FSesID : TFRE_DB_SESSION_ID;
public
constructor Create (const data : IFRE_DB_Object ; const status : TFRE_DB_COMMAND_STATUS ; const original_command_id : Qword ; const opaquedata : IFRE_DB_Object ; Contmethod : TFRE_DB_GenericCBMethod ; const isRifcb : Boolean ; const SesID : TFRE_DB_String);
procedure DispatchAnswer (const ses : IFRE_DB_UserSession);
end;
TFRE_DB_Usersession_COR=class
procedure Execute(const session : TFRE_DB_Usersession);virtual;abstract;
end;
{ TFRE_DB_SESSION_UPO }
TFRE_DB_SESSION_UPO = class
private
FStoreList : TFPHashObjectList;
FSessid : TFRE_DB_SESSION_ID;
function GetUpdateStore (const store_id,store_id_dc: shortstring): TFRE_DB_UPDATE_STORE_DESC;
public
constructor Create (const session_id : TFRE_DB_NameType);
destructor Destroy ; override;
procedure AddStoreUpdate (const store_id,store_id_dc: TFRE_DB_String; const upo: IFRE_DB_Object ; const oldpos,newpos,abscount : NativeInt);
procedure AddStoreInsert (const store_id,store_id_dc: TFRE_DB_String; const upo: IFRE_DB_Object ; const position,abscount : NativeInt);
procedure AddStoreDelete (const store_id,store_id_dc: TFRE_DB_String; const id: TFRE_DB_String ; const position,abscount : NativeInt);
procedure DispatchAllNotifications (const session:TFRE_DB_UserSession);
procedure cs_SendUpdatesToSession ;
end;
TFRE_DB_UserSession = class(TObject,IFRE_DB_Usersession,IFRE_DB_DBChangedNotificationSession,IECF_SystemConfiguration)
private type
TDiffFieldUpdateMode=(mode_df_add,mode_df_del,mode_df_change);
TDispatch_Continuation = record
CID : Qword;
ORIG_CID : Qword;
Contmethod : TFRE_DB_GenericCBMethod;
IsRif : Boolean;
ExpiredAt : TFRE_DB_DateTime64;
SesID : TFRE_DB_String;
opData : IFRE_DB_Object;
end;
private class var
FContinuationArray : Array [0..cFRE_DB_MAX_CLIENT_CONTINUATIONS] of TDispatch_Continuation;
FContinuationLock : IFOS_LOCK;
FGlobalDebugLock : IFOS_LOCK;
FMyReqID : NativeUint;
private
FSessionLock : IFOS_LOCK;
FTakeoverPrepared : String;
FSessionTerminationTO : NativeInt;
FBoundThreadID : TThreadID;
FModuleInitialized : TFPHashList;
var
FOnWorkCommands : TNotifyEvent;
FUserName : TFRE_DB_String;
FSessionID : TFRE_DB_SESSION_ID;
FDefaultApp : TFRE_DB_String;
FSessionData : IFRE_DB_Object;
FBinaryInputs : IFRE_DB_Object; { per key requestable of Binary Input which get's sent seperated from the data }
FUpdateableDBOS : IFRE_DB_Object;
FServerFuncDBOS : IFRE_DB_Object;
FGlobalEventCallbacks : IFRE_DB_Object;
FDifferentialUpdates : IFRE_DB_Object;
FUpdateableContent : IFRE_DB_Object;
FTimers : TList;
FRemoteRequestSet : TFRE_DB_RemoteReqSpecArray;
FCurrentReqID : QWord; // Current ReqID that is beeing processed (from client)
FDefaultUID : TFRE_DB_GUIDArray;
FDBConnection : IFRE_DB_CONNECTION;
FPromoted : Boolean;
FAppArray : Array of IFRE_DB_APPLICATION;
FLoginApp : IFRE_DB_APPLICATION;
FDC_Array : Array of IFRE_DB_DERIVED_COLLECTION;
FcurrentApp : TFRE_DB_String;
FConnDesc : String;
FBoundSession_RA_SC : IFRE_DB_COMMAND_REQUEST_ANSWER_SC;
FSessionCG : IFRE_APSC_CHANNEL_GROUP;
FIsInteractive : Boolean;
FBindState : TFRE_DB_SESSIONSTATE;
FBoundMachineUid : TFRE_DB_Guid;
FBoundMachineMac,
FBoundMachineName : TFRE_DB_String;
FSyncWaitE : IFOS_E;
procedure SetOnWorkCommands (AValue: TNotifyEvent);
procedure _FixupDCName (var dcname:TFRE_DB_NameType);
function SearchSessionDC (dc_name:TFRE_DB_String;out dc:IFRE_DB_DERIVED_COLLECTION):boolean;
procedure _FetchAppsFromDB ;
procedure _InitApps ;
procedure _ReinitializeApps ;
procedure AddSyncContinuationEntry (const request_id,original_req_id:Qword ; const for_session_id : String ; const callback : TFRE_DB_GenericCBMethod ; const is_rif : boolean ; const expire_in : NativeUint ; const opaquedata : IFRE_DB_Object);
procedure INT_TimerCallBack (const timer : IFRE_APSC_TIMER ; const flag1,flag2 : boolean);
procedure RemoveAllTimers ;
function HasFeature (const feature_name:TFRE_DB_NameType):Boolean;
function GetSystemMAC :TFOS_MAC_ADDR; { should be provisioningmac }
function IsSystemManaged :Boolean; { True = MOS Managed Machine / false = one DC,one Machine}
function IsConfigurationMode :Boolean; { True = the system is in configuration mode }
public
function FetchStreamDBO_OTCU (const uid:TFRE_DB_GUID ; var end_field : TFRE_DB_NameTypeRL ; var lcontent : TFRE_DB_RawByteString ; var content_type : TFRE_DB_String ; var etag : TFRE_DB_String) : Boolean; // Other Thread Context Unsafe
class procedure HandleContinuationTimeouts(const onfetch: TFRE_DB_OnFetchSessionByID);
procedure LockSession ;
procedure UnlockSession ;
class destructor destroyit ;
class constructor createit ;
procedure SetSessionState (const sstate : TFRE_DB_SESSIONSTATE);
function GetSessionState : TFRE_DB_SESSIONSTATE;
function GetCurrentRequestID : QWord;
function CheckUnboundSessionForPurge : boolean;
constructor Create (const cg : IFRE_APSC_CHANNEL_GROUP;const user_name, password: TFRE_DB_String; const default_app: TFRE_DB_String; const default_uid_path: TFRE_DB_GUIDArray; conn: IFRE_DB_CONNECTION; const interactive_session: boolean);
destructor Destroy ;override;
procedure StoreSessionData ;
function SearchSessionApp (const app_key:TFRE_DB_String ; out app:TFRE_DB_APPLICATION ; out idx:integer):boolean;
procedure InboundNotificationBlock (const block: IFRE_DB_Object); { Here comes an Inbound Notification block from the network/pl layer}
procedure COR_InboundNotifyBlock (const data : Pointer);
function SearchSessionAppUID (const app_uid:TFRE_DB_GUID;out app:IFRE_DB_Object):boolean;
function SearchSessionDCUID (const dc_uid:TFRE_DB_GUID;out dc:IFRE_DB_DERIVED_COLLECTION):boolean;
procedure RemSessionAppAndFinialize(const app_key:TFRE_DB_String);
procedure RemoveAllAppsAndFinalize ;
procedure SetCurrentApp (const app_key:TFRE_DB_String);
procedure Input_FRE_DB_Command (const cmd :IFRE_DB_COMMAND); // Here Comes the command in ..
class
procedure CLS_ForceInvalidSessionReload (rac :IFRE_DB_COMMAND_REQUEST_ANSWER_SC ; const cmd :IFRE_DB_COMMAND); // Here Comes the command in ..
function InternalSessInvokeMethod (const class_name,method_name:string;const uid_path:TFRE_DB_GUIDArray;var input:IFRE_DB_Object):IFRE_DB_Object;
function SetupSyncWaitDataEvent : IFOS_E;
function GetSyncWaitEvent (out e:IFOS_E):boolean;
procedure FinalizeSyncWaitEvent ;
function InternalSessInvokeMethod (const app:IFRE_DB_APPLICATION;const method_name:string;const input:IFRE_DB_Object):IFRE_DB_Object;
function Promote (const user_name,password:TFRE_DB_String;var promotion_status:TFRE_DB_String; force_new_session_data : boolean ; const session_takeover : boolean ; const auto_promote : boolean ; const allowed_user_classes : array of TFRE_DB_String) : TFRE_DB_PromoteResult; // Promote USER to another USER
procedure COR_InitiateTakeOver (const data : Pointer); // In old session binding
procedure COR_FinalizeTakeOver (const data : Pointer); // In new session binding
procedure AutoPromote (const NEW_RASC:IFRE_DB_COMMAND_REQUEST_ANSWER_SC;const conn_desc:String);
procedure Logout ;
function LoggedIn : Boolean;
function QuerySessionDestroy : Boolean;
function GetSessionID : TFRE_DB_SESSION_ID;
function GetSessionAppData (const app_key:TFRE_DB_String):IFRE_DB_Object;
function GetSessionModuleData (const mod_key:TFRE_DB_String):IFRE_DB_Object;
function GetSessionGlobalData :IFRE_DB_Object;
function NewDerivedCollection (dcname:TFRE_DB_NameType):IFRE_DB_DERIVED_COLLECTION;
function HasDerivedCollection (dcname:TFRE_DB_NameType):Boolean;
function FetchDerivedCollection (dcname:TFRE_DB_NameType):IFRE_DB_DERIVED_COLLECTION;
procedure FinishDerivedCollections ;
function GetUsername : String;
function GetClientDetails : String;
procedure SetClientDetails (const net_conn_desc:String);
function GetTakeOverKey : String;
function GetSessionAppArray : IFRE_DB_APPLICATION_ARRAY;
function GetModuleInitialized (const modulename:ShortString):Boolean;
function SetModuleInitialized (const modulename:ShortString):Boolean;
function FetchOrInitFeederMachines (const configmachinedata: IFRE_DB_Object): TFRE_DB_GUID; { Initialize or deliver Machine Objects in the Session DB }
function GetMachineUidByName (const mname : TFRE_DB_String ; out machuid : TFRE_DB_GUID):boolean;
function GetMachineUidByMac (const mac : TFOS_MAC_ADDR ; out machuid : TFRE_DB_GUID):boolean;
procedure SetServerClientInterface (const sc_interface: IFRE_DB_COMMAND_REQUEST_ANSWER_SC);
procedure ClearServerClientInterface ;
function GetClientServerInterface (out sc : IFRE_DB_COMMAND_REQUEST_ANSWER_SC):boolean;
procedure ClearUpdatable ;
procedure RegisterUpdatableContent (const contentId: String);
procedure UnregisterUpdatableContent (const contentId: String);
function IsUpdatableContentVisible (const contentId: String): Boolean;
procedure RegisterUpdatableDBO (const UID_id: TFRE_DB_GUID);
procedure UnregisterUpdatableDBO (const UID_id: TFRE_DB_GUID);
function IsDBOUpdatable (const UID_id: TFRE_DB_GUID):boolean;
procedure RegisterDBOChangeCB (const UID_id: TFRE_DB_GUID; const callback: TFRE_DB_SERVER_FUNC_DESC; const cbGroupId: TFRE_DB_String);
procedure UnregisterDBOChangeCB (const cbGroupId: TFRE_DB_String);
function getDBOChangeCBs (const UID_id: TFRE_DB_GUID):IFRE_DB_Object;
procedure SendServerClientRequest (const description : TFRE_DB_CONTENT_DESC;const session_id:TFRE_DB_SESSION_ID=''); // Currently no continuation, and answer processing is implemented, is an Async request
procedure SendServerClientAnswer (const description : TFRE_DB_CONTENT_DESC;const answer_id : Qword);
procedure SendServerClientCMD (const cmd : IFRE_DB_COMMAND);
function GetSessionChannelManager : IFRE_APSC_CHANNEL_MANAGER;
function GetSessionChannelGroup : IFRE_APSC_CHANNEL_GROUP;
//Invoke a Method that another Session provides via Register
function InvokeRemoteRequest (const rclassname,rmethodname:TFRE_DB_NameType;const input : IFRE_DB_Object ; const SyncCallback : TFRE_DB_RemoteCB ; const opaquedata : IFRE_DB_Object):TFRE_DB_Errortype;
function InvokeRemoteRequestMachine (const machineid : TFRE_DB_GUID ; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
function InvokeRemoteRequestMachineMac (const machine_mac : TFRE_DB_NameType ; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
function InvokeRemoteInterface (const machineid : TFRE_DB_GUID ; const RIFMethod:TFRE_DB_RIF_Method; const CompletionCallback: TFRE_DB_RemoteCB_RIF ; const opaquedata: IFRE_DB_Object=nil) : TFRE_DB_Errortype;
procedure InvokeRemReqCoRoutine (const data : Pointer);
procedure AnswerRemReqCoRoutine (const data : Pointer);
procedure COR_SendContentOnBehalf (const data : Pointer);
procedure COR_ExecuteSessionCmd (const data : Pointer);
function ProcessQryToDescription (const qry : TFRE_DB_QUERY_BASE):TFRE_DB_STORE_DATA_DESC;
procedure COR_AnswerGridData (const qry : TFRE_DB_QUERY_BASE);
procedure COR_SendStoreUpdates (const data : TFRE_DB_SESSION_UPO);
procedure FinalRightTransform (const transformed_filtered_cloned_obj:IFRE_DB_Object ; const frt : IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION ; const langres : TFRE_DB_StringArray);
function DispatchCoroutine (const coroutine : TFRE_APSC_CoRoutine;const data : Pointer):boolean; // Call a Coroutine in this sessions thread context
//Enable a session to "Publish" Remote Methods, overrides previous set
function RegisterRemoteRequestSet (const requests : TFRE_DB_RemoteReqSpecArray):TFRE_DB_Errortype;
function RegisterTaskMethod (const TaskMethod:IFRE_DB_WebTimerMethod ; const invocation_interval : integer ; const id :TFRE_APSC_ID='TIMER') : boolean;
function RemoveTaskMethod (const id:string):boolean;
function IsInteractiveSession : Boolean;
function GetDBConnection : IFRE_DB_CONNECTION;
function GetDomain : TFRE_DB_String; { doaminname of logged in user }
function GetDomainUID : TFRE_DB_GUID; { doamin id of logged in user }
function GetDomainUID_String : TFRE_DB_GUID_String; { doamin id as string of logged in user }
function GetLoginUserAsCollKey : TFRE_DB_NameType; { use this if you need per user(session) distinct collections }
function GetPublishedRemoteMeths : TFRE_DB_RemoteReqSpecArray;
function GetDownLoadLink4StreamField (const obj_uid: TFRE_DB_GUID; const fieldname: TFRE_DB_NameType; const is_attachment: boolean; mime_type: string; file_name: string ; force_url_etag : string=''): String; { Make a DBO Stream Field Downloadable in a Session context }
{ Notification interface function, the notification interface gets an update block pushed from the net/pl layer }
procedure DifferentiallUpdStarts (const obj : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure DifferentiallUpdEnds (const obj_uid : TFRE_DB_GUID ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldDelete (const old_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldAdd (const new_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FieldChange (const old_field,new_field : IFRE_DB_Field ; const tsid : TFRE_DB_TransStepId); { DIFFERENTIAL STATE}
procedure FinalizeNotif ;
procedure ObjectDeleted (const coll_names: TFRE_DB_NameTypeArray ; const obj : IFRE_DB_Object ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure ObjectUpdated (const upobj : IFRE_DB_Object ; const colls:TFRE_DB_StringArray ; const tsid : TFRE_DB_TransStepId); { FULL STATE }
procedure SetupInboundRefLink (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
procedure InboundReflinkDropped (const from_obj: IFRE_DB_Object ; const to_obj: IFRE_DB_Object ; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
{Helper}
procedure HandleDiffField (const mode : TDiffFieldUpdateMode ; const fld : IFRE_DB_Field);
function BoundMachineUID : TFRE_DB_GUID;
function BoundMachineMac : TFRE_DB_NameType;
function SysConfig :IECF_SystemConfiguration;
procedure DoGlobalEvent (const ev_name : TFRE_DB_NameType ; const ev_data : IFRE_DB_Object);
function SubscribeGlobalEvent (const ev_name : TFRE_DB_NameType ; const event_callback : IFRE_DB_SessionDataCallback):boolean; { true= first register, false= update}
procedure UnsubscribeGlobalEvent (const ev_name : TFRE_DB_NameType);
procedure PublishGlobalEvent (const ev_name : TFRE_DB_NameType ; const ev_data : IFRE_DB_Object);
procedure PublishGlobalEventText (const ev_name : TFRE_DB_NameType ; const ev_data : Shortstring);
end;
TFRE_DB_FetchSessionCB = function(const back_channel: IFRE_DB_COMMAND_REQUEST_ANSWER_SC; out session : TFRE_DB_UserSession;const old_session_id:string;const interactive_session:boolean):boolean of object;
TFRE_DB_SessionCB = procedure(const sender : TObject; const session : TFRE_DB_UserSession) of object;
const
cFRE_GUID_DATA_MODE = $DA;
cFRE_GUID_SYS_MODE = $CC;
cFRE_GUID_NONU_MODE = $11;
type
PGUID_Access = ^TFRE_DB_GUID_Access;
TFRE_DB_RANDOM_PW_MODE = (rpm_OnlyChars,rpm_OnlyDigits,rpm_DigitsCharsMixed,rpm_ExtendedPasswordChars);
function FieldtypeShortString2Fieldtype (const fts: TFRE_DB_String): TFRE_DB_FIELDTYPE;
procedure CheckDbResult (const res:TFRE_DB_Errortype;const error_string : TFRE_DB_String ='' ; const tolerate_no_change : boolean=true);
procedure CheckDbResultFmt (const res:TFRE_DB_Errortype;const error_string : TFRE_DB_String ='' ; const params:array of const ; const tolerate_no_change : boolean=true );
function FREDB_GetRandomChars (const len:NativeInt ; const randommode : TFRE_DB_RANDOM_PW_MODE=rpm_ExtendedPasswordChars):string;
procedure FREDB_LoadMimetypes (const filename:string);
function FREDB_Filename2MimeType (const filename:string):TFRE_DB_MimeTypeStr;
function FREDB_FindStringIndexInArray (const text:TFRE_DB_String;const strings:TFRE_DB_StringArray):integer;
function FREDB_CombineString (const strings: TFRE_DB_StringArray; const sep: TFRE_DB_String): TFRE_DB_String;
function FREDB_CombineNametypes (const strings: TFRE_DB_NameTypeArray; const sep: TFRE_DB_String): TFRE_DB_String;
procedure FREDB_SeperateString (const value,sep : TFRE_DB_String; var Strings: TFRE_DB_StringArray); //TODO UNICODE
function FREDB_DBNameType_Compare (const S1, S2: TFRE_DB_NameType): NativeInt;
function FREDB_DBString_Compare (const S1, S2: TFRE_DB_String): NativeInt;
function FREDB_DBint64_Compare (const S1, S2: int64): NativeInt;
function FREDB_DBuint64_Compare (const S1, S2: uint64): NativeInt;
function FREDB_FieldtypeShortString2Fieldtype (const fts: TFRE_DB_String): TFRE_DB_FIELDTYPE;
function FREDB_FieldDepVisString2FieldDepVis (const fts: TFRE_DB_String): TFRE_DB_FieldDepVisibility;
function FREDB_FieldDepESString2FieldDepES (const fts: TFRE_DB_String): TFRE_DB_FieldDepEnabledState;
function FREDB_FilterTypeString2Filtertype (const fts: TFRE_DB_String): TFRE_DB_FILTERTYPE;
function FREDB_Bool2String (const bool:boolean):String;
function FREDB_EncodeTranslatableWithParams (const translation_key:TFRE_DB_String ; params : array of const):TFRE_DB_String;
function FREDB_TranslatableHasParams (var translation_key:TFRE_DB_String ; var params : TFRE_DB_StringArray):boolean;
procedure FREDB_DecodeVarRecParams (const params : TFRE_DB_StringArray ; var vaparams : TFRE_DB_ConstArray);
procedure FREDB_FinalizeVarRecParams (const vaparams : TFRE_DB_ConstArray);
procedure FREDB_FinalizeObjectArray (var obja : IFRE_DB_ObjectArray);
function FREDB_G2H (const uid : TFRE_DB_GUID):ShortString; { deprecated, use guid AR function .AsHexString}
function FREDB_H2G (const uidstr : shortstring):TFRE_DB_GUID;
function FREDB_G2SB (const uid : TFRE_DB_GUID):ShortString; { uid to binary shortstring }
function FREDB_SB2G (const uid_sb : ShortString):TFRE_DB_GUID; { binary shortstring to uid}
function FREDB_ExtractUidsfromRightArray (const str:TFRE_DB_StringArray;const rightname:TFRE_DB_STRING):TFRE_DB_GUIDArray;
function FREDB_H2GArray (const str:string):TFRE_DB_GUIDArray;
function FREDB_H2GArray (const str:TFRE_DB_String):TFRE_DB_GUIDArray;
function FREDB_String2Bool (const str:string):boolean;
function FREDB_SplitRefLinkDescription (key_description : TFRE_DB_NameTypeRL ; out rl_field,rl_scheme : TFRE_DB_NameTypeRL):boolean; { True if outbound RL}
function FREDB_SplitRefLinkDescriptionEx (key_description : TFRE_DB_NameTypeRL ; out rl_field,rl_scheme : TFRE_DB_NameTypeRL ; out recursive : boolean):boolean; { True if outbound RL}
function FREDB_String2NativeInt (const str:String):NativeInt;
function FREDB_String2NativeUInt (const str:String):NativeUint;
function FREDB_NumFilterType2String (const nft:TFRE_DB_NUM_FILTERTYPE):String;
function FREDB_String2NumfilterType (const str:string):TFRE_DB_NUM_FILTERTYPE;
function FREDB_String2StrFilterType (const str:string):TFRE_DB_STR_FILTERTYPE;
function FREDB_StrFilterType2String (const sft:TFRE_DB_STR_FILTERTYPE):String;
function FREDB_String2StdRightShort (const c:Char):TFRE_DB_STANDARD_RIGHT;
function FREDB_Guids_Same (const d1, d2 : TFRE_DB_GUID):boolean;
function FREDB_Guids_Compare (const d1, d2 : TFRE_DB_GUID):NativeInt; // 0=Same 1 = d2>d1 -1 = d1>d2
function FREDB_Guid_ArraysSame (const arr1,arr2: TFRE_DB_GUIDArray):boolean;
function FREDB_GuidArray2String (const arr: TFRE_DB_GUIDArray):String;
function FREDB_CheckGuidsUnique (const arr: TFRE_DB_GUIDArray):boolean;
function FREDB_GuidList2Counted (const arr: TFRE_DB_GUIDArray; const stop_on_first_double: boolean=false): TFRE_DB_CountedGuidArray;
function FREDB_ObjectToPtrUInt (const obj : TObject):PtrUInt; inline;
function FREDB_PtrUIntToObject (const obj : PtrUInt):TObject; inline;
procedure FREDB_BinaryKey2ByteArray (const key : PByte ; const k_len : NativeInt ; var bytearr : TFRE_DB_ByteArray);
function FREDB_GetIndexTypeForFieldType (const fld_type : TFRE_DB_FIELDTYPE) : TFRE_DB_INDEX_TYPE;
function FREDB_GetIndexTypeFromObjectEncoding (const obj_enc : IFRE_DB_Object) : TFRE_DB_INDEX_TYPE;
function FREDB_GetIndexFldValFromObjectEncoding (const obj_enc : IFRE_DB_Object) : IFRE_DB_Field; { nil, if NULL Value qry !}
function FREDB_GetDomainIDFldValFromObjectEncoding (const obj_enc : IFRE_DB_Object) : IFRE_DB_Field;
procedure FREDB_SetUserDomIDFldValForObjectEncoding (const obj_enc : IFRE_DB_Object ; ut : IFRE_DB_USER_RIGHT_TOKEN);
function FREDB_NewIndexFldValForObjectEncoding (const fld : IFRE_DB_Field ; const domaid_uid_String : TFRE_DB_GUID_String):IFRE_DB_Object;
function FREDB_GetGlobalTextKey (const key: String): String;
function FREDB_getThemedResource (const id: String): String;
function FREDB_RightSetString2RightSet (const rightstr:ShortString):TFRE_DB_STANDARD_RIGHT_SET;
function FREDB_StringInArray (const src:string;const arr:TFRE_DB_StringArray):boolean;
function FREDB_StringInNametypeArray (const src:string;const arr:TFRE_DB_NameTypeArray):boolean;
function FREDB_StringArray2Upper (const sa : TFRE_DB_StringArray):TFRE_DB_StringArray;
function FREDB_NametypeArray2Upper (const sa : TFRE_DB_NameTypeArray):TFRE_DB_NameTypeArray;
function FREDB_StringArray2Lower (const sa : TFRE_DB_StringArray):TFRE_DB_StringArray;
function FREDB_StringArray2NametypeArray (const sa : TFRE_DB_StringArray):TFRE_DB_NameTypeArray;
function FREDB_StringArray2NametypeRLArray (const sa : TFRE_DB_StringArray):TFRE_DB_NameTypeRLArray;
function FREDB_StringArrayOpen2StringArray (const sa : array of TFRE_DB_String):TFRE_DB_StringArray;
function FREDB_ClassArray2StringArray (const sa : array of TClass):TFRE_DB_StringArray;
function FREDB_NametypeArray2StringArray (const sa : TFRE_DB_NameTypeArray):TFRE_DB_StringArray;
function FREDB_NametypeArrayOpen2NametypeArray (const sa : array of TFRE_DB_NameType):TFRE_DB_NameTypeArray;
function FREDB_StringArray2UidArray (const sa : array of TFRE_DB_String):TFRE_DB_GUIDArray;
function FREDB_GuidArrayOpen2GuidArray (const ga : array of TFRE_DB_GUID):TFRE_DB_GUIDArray;
function FREDB_NumFld2Int64Array (const fld : IFRE_DB_Field ; var a : TFRE_DB_Int64Array): boolean;
function FREDB_NumFld2UInt64Array (const fld : IFRE_DB_Field ; var a : TFRE_DB_UInt64Array): boolean;
function FREDB_StringInArrayIdx (const src:string;const arr:TFRE_DB_StringArray):NativeInt;
function FREDB_StringInNametypeArrayIdx (const src:string;const arr:TFRE_DB_NameTypeArray):NativeInt;
function FREDB_PrefixStringInArray (const pfx:string;const arr:TFRE_DB_StringArray):boolean;
procedure FREDB_ConcatStringArrays (var TargetArr:TFRE_DB_StringArray;const add_array:TFRE_DB_StringArray);
procedure FREDB_ConcatGUIDArrays (var TargetArr:TFRE_DB_GuidArray;const add_array:TFRE_DB_GuidArray);
procedure FREDB_ConcatReferenceArrays (var TargetArr:TFRE_DB_ObjectReferences ; const add_array : TFRE_DB_ObjectReferences);
function FREDB_GuidInArray (const check:TFRE_DB_GUID;const arr:TFRE_DB_GUIDArray):NativeInt;
function FREDB_GuidInObjArray (const check:TFRE_DB_GUID;const arr:IFRE_DB_ObjectArray):NativeInt;
function FREDB_FindNthGuidIdx (n:integer;const guid:TFRE_DB_GUID;const arr:TFRE_DB_GUIDArray):integer;inline;
function FREDB_CheckAllStringFieldsEmptyInObject (const obj:IFRE_DB_Object):boolean;
function FREDB_RemoveIdxFomObjectArray (const arr:IFRE_DB_ObjectArray ; const idx : NativeInt):IFRE_DB_ObjectArray;
function FREDB_InsertAtIdxToObjectArray (const arr:IFRE_DB_ObjectArray ; var at_idx : NativeInt ; const new_obj : IFRE_DB_Object ; const before : boolean):IFRE_DB_ObjectArray;
function FREDB_String2DBDisplayType (const fts: string): TFRE_DB_DISPLAY_TYPE;
procedure FREDB_SiteMap_AddEntry (const SiteMapData : IFRE_DB_Object ; const key:string;const caption : String ; const icon : String ; InterAppLink : TFRE_DB_StringArray ;const x,y : integer; const newsCount:Integer=0; const scale:Single=1; const enabled:Boolean=true); //obsolete
procedure FREDB_SiteMap_AddRadialEntry (const SiteMapData : IFRE_DB_Object ; const key:string;const caption : String ; const icon : String ; InterAppLink : String; const newsCount:Integer=0; const enabled:Boolean=true);
procedure FREDB_SiteMap_RadialAutoposition (const SiteMapData : IFRE_DB_Object; rootangle:integer=0);
procedure FREDB_SiteMap_DisableEntry (const SiteMapData : IFRE_DB_Object ; const key:string);
function FREDB_GuidArray2StringStream (const arr:TFRE_DB_GUIDArray):String; { Caution ! - used in streaming}
function FREDB_StreamString2GuidArray (str:string):TFRE_DB_GUIDArray; { Caution ! - used in streaming, must be in format of FREDB_GuidArray2String}
procedure FREDB_SplitLocalatDomain (const localatdomain: TFRE_DB_String; var localpart, domainpart: TFRE_DB_String);
function FREDB_GetDboAsBufferLen (const dbo: IFRE_DB_Object; var mem: Pointer): UInt32;
procedure FREDB_SetStringFromExistingFieldPathOrNoChange(const obj:IFRE_DB_Object ; const fieldpath:string ; var string_fld : TFRE_DB_String); { }
function FREDB_HCV (const txt : TFRE_DB_String):TFRE_DB_String; { replace cFRE_DB_SYS_CLEAR_VAL_STR with '' use for new operation/web }
function FREDB_IniLogCategory2LogCategory (const ini_logcategory: string) : TFRE_DB_LOGCATEGORY;
// This function should replace all character which should not a appear in an ECMA Script (JS) string type to an escaped version,
// as additional feature it replaces CR with a <br> tag, which is useful in formatting HTML
function FREDB_String2EscapedJSString (const input_string:TFRE_DB_String;const replace_cr_with_br:boolean=false) : TFRE_DB_String;
procedure FREDB_ApplyNotificationBlockToNotifIF (const block: IFRE_DB_Object ; const deploy_if : IFRE_DB_DBChangedNotification ; var layer : TFRE_DB_NameType); { full block used in transaction, and in TransDM }
procedure FREDB_ApplyNotificationBlockToNotifIF_Connection (const block: IFRE_DB_Object ; const deploy_if : IFRE_DB_DBChangedNotificationConnection);
procedure FREDB_ApplyNotificationBlockToNotifIF_Session (const block: IFRE_DB_Object ; const deploy_if : IFRE_DB_DBChangedNotificationSession);
//function FREDB_PP_ObjectInParentPath (const obj : IFRE_DB_Object ; const pp : TFRE_DB_String): boolean;
//procedure FREDB_PP_AddParentPathToObj (const obj : IFRE_DB_Object ; const pp : TFRE_DB_String);
function FREDB_PP_ExtendParentPath (const uid : TFRE_DB_GUID ; const pp :TFRE_DB_String):TFRE_DB_String;
function FREDB_CreateIndexDefFromObject (const ix_def_o : IFRE_DB_Object): TFRE_DB_INDEX_DEF;
function FREDB_CreateIndexDefArrayFromObject (const ix_def_ao : IFRE_DB_Object): TFRE_DB_INDEX_DEF_ARRAY;
function FREDB_CheckMacAddress (const mac:ShortString):boolean;
function FREDB_CompareReflinkSpecs (r1,r2 : TFRE_DB_NameTypeRL ; const strict : boolean=false):boolean;
function FREDB_CompareReflinkSpec2Arr (const key_descr: TFRE_DB_NameTypeRL; const rla: TFRE_DB_NameTypeRLArray): boolean;
function FREDB_TransformException2ec (const e:exception;const lineinfo:shortstring):TFRE_DB_Errortype;inline;
procedure FREDB_ShellExpandFixUserPath (var path_var:string); { handle ~ and $ expansion of specified directories }
procedure FREDB_StringWrite2Stream (const msg:TFRE_DB_String ; const str : TStream);
function FREDB_ReadJSONEncodedObject (const str : TStream):IFRE_DB_Object;
procedure FREDB_DumpDboEx (dbo : IFRE_DB_Object ; const form : TFRE_DBO_DUMP_FORMAT ; const filename : string);
function FREDB_ApplyChangesFromTaggedUniqueObjectToObject (const to_update_object : IFRE_DB_Object ; const source_object : IFRE_DB_Object ; const ignore_fields : TFRE_DB_NameTypeArray; const unique_tag_field_name : TFRE_DB_NameType='UCT'; const dry_run : boolean=false ; const record_changes : IFOS_STRINGS=nil ; const dont_delete_plugin_deleted : boolean=true):NativeInt; { report changecount }
function FREDB_IsFieldNameInIgnoreList (const fn : TFRE_DB_NameType):boolean;
function FREDB_CheckUniqueTags (const obj : IFRE_DB_Object ; skip_root : boolean=true ; const raise_ex : boolean=true ; const dump_tags : boolean=false):boolean;
procedure FREDB_CheckFieldnameLength (const fn : string); { check if a string is too long to be (unique) used as a Fieldname TFRE_DB_Nametype }
function FREDB_GetPoolNameFromDatasetorDirectory (const ds_or_dir : string):String;
operator= (e1 : TFRE_DB_Errortype ; e2 : TFRE_DB_Errortype_EC) b : boolean;
operator= (e1 : TFRE_DB_Errortype_EC; e2 : TFRE_DB_Errortype) b : boolean;
operator:= (e1 : TFRE_DB_Errortype) r : TFRE_DB_Errortype_EC;
operator:= (e1 : TFRE_DB_Errortype_EC) r : TFRE_DB_Errortype;
operator:= (o1 : Array of TFRE_DB_String) b :TFRE_DB_StringArray;
operator:= (o1 : Array of TFRE_DB_NameType) b :TFRE_DB_NameTypeArray;
operator:= (o1 : Array of TFRE_DB_GUID) b : TFRE_DB_GUIDArray;
type
TAddAppToSiteMap_Callback = procedure (const app : TFRE_DB_APPLICATION ; const session: TFRE_DB_UserSession; const parent_entry: TFRE_DB_CONTENT_DESC);
var
GFRE_DBI : IFRE_DB;
GFRE_DBI_REG_EXTMGR : IFRE_DB_EXTENSION_MNGR;
GFRE_DB_NIL_DESC : TFRE_DB_NIL_DESC;
GFRE_DB_SUPPRESS_SYNC_ANSWER : TFRE_DB_SUPPRESS_ANSWER_DESC;
GFRE_DB_MIME_TYPES : Array of TFRE_DB_Mimetype;
GFRE_DB_TCDM : TFRE_DB_TRANSDATA_MANAGER_BASE;
G_LiveStatLock : IFOS_LOCK;
G_LiveStats : IFRE_DB_Object;
G_LiveFeeding : Boolean;
implementation
function FREDB_CreateIndexDefFromObject (const ix_def_o : IFRE_DB_Object): TFRE_DB_INDEX_DEF;
begin
result := Default(TFRE_DB_INDEX_DEF);
with result do
begin
IndexClass := ix_def_o.Field('IX_CLASS').AsString;
IndexName := ix_def_o.Field('IX_NAM').AsString;
FieldName := ix_def_o.Field('IX_FN').AsString;
FieldType := FREDB_FieldtypeShortString2Fieldtype(ix_def_o.Field('IX_FT').AsString);
Unique := ix_def_o.Field('IX_UNQ').AsBoolean;
AllowNulls := ix_def_o.Field('IX_ANULL').AsBoolean;
UniqueNull := ix_def_o.Field('IX_UNQN').AsBoolean;
if ix_def_o.FieldExists('IXT_CSENS') then
IgnoreCase := ix_def_o.Field('IXT_CSENS').AsBoolean
else
IgnoreCase := false;
end;
end;
function FREDB_CreateIndexDefArrayFromObject (const ix_def_ao : IFRE_DB_Object): TFRE_DB_INDEX_DEF_ARRAY;
var nta : TFRE_DB_NameTypeArray;
i : NativeInt;
ido : IFRE_DB_Object;
begin
nta := FREDB_StringArray2NametypeArray(ix_def_ao.Field('IndexNames').AsStringArr);
SetLength(result,Length(nta));
for i:=0 to high(nta) do
begin
ido := ix_def_ao.Field('ID_'+nta[i]).AsObject;
result[i] := FREDB_CreateIndexDefFromObject(ido);
end;
end;
function FREDB_CheckMacAddress(const mac: ShortString): boolean;
var conv : ShortString;
bytes : string;
binv : Qword;
len : NativeInt;
begin
if length(mac)<>17 then
exit(false);
conv := StringReplace(mac,':','',[rfReplaceAll]);
if Length(conv)<>12 then
exit(false);
len := HexToBin(@conv[1],@binv,6);
result := len=6;
end;
function FREDB_CompareReflinkSpecs(r1,r2 : TFRE_DB_NameTypeRL ; const strict : boolean=false):boolean;
var f1,s1,f2,s2 : TFRE_DB_NameType;
rc1,rc2,d1,d2 : boolean;
begin
if strict then
exit(uppercase(r1)=uppercase(r2));
d1 := FREDB_SplitRefLinkDescriptionEx(r1,f1,s1,rc1);
d2 := FREDB_SplitRefLinkDescriptionEx(r2,f2,s2,rc2);
if d1<>d2 then
exit(false);
{ direction is same }
if f1<>f2 then
exit(false);
result := true; // Schemes must not match, fields must
end;
function FREDB_CompareReflinkSpec2Arr(const key_descr: TFRE_DB_NameTypeRL; const rla: TFRE_DB_NameTypeRLArray): boolean;
var
i: NativeInt;
begin
result := false;
for i := 0 to high(rla) do
begin
if FREDB_CompareReflinkSpecs(key_descr,rla[i],false) then
begin
result := true;
break;
end
end;
end;
function FREDB_GetRandomChars(const len: NativeInt; const randommode: TFRE_DB_RANDOM_PW_MODE): string;
const only_chars ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
only_digits='0123456789';
mixed ='abc1def7ghi0jklmnopqr3stuvw6xyzABCD4EFG8HIJKLMNOP2QRSTUVWX5YZ9';
extended ='abc1def7g&hi0j#klmno*pqr3stuvw6xyzABC-D4EFG8HI@JKLM+NOP2QRST$UVWX(5YZ)9';
var src : string;
i : integer;
l : integer;
k : byte;
begin
result:='';
case randommode of
rpm_OnlyChars: src := only_chars;
rpm_OnlyDigits: src := only_digits;
rpm_DigitsCharsMixed: src := mixed;
rpm_ExtendedPasswordChars: src := extended;
end;
l := High(src);
for i:=1 to len do
begin
k := random(l)+1;
result := result + src[k];
end;
end;
procedure FREDB_LoadMimetypes(const filename: string);
var cnt : NativeInt;
procedure add(const ext,mt:string);
begin
with GFRE_DB_MIME_TYPES[cnt] do
begin
extension := ext;
mimetype := mt;
end;
inc(cnt);
end;
begin
if filename<>'' then
begin
//TODO PARSE apache MIMETYPEFILE
abort;
end
else
begin
SetLength(GFRE_DB_MIME_TYPES,16);
cnt := 0;
add('js','application/javascript');
add('html','text/html');
add('css','text/css');
add('gif','image/gif');
add('jpg','image/jpeg');
add('png','image/png');
add('tiff','image/tiff');
add('txt','text/plain');
add('svg','image/svg+xml');
add('swf','application/x-shockwave-flash');
add('woff','application/font-woff');
add('ttf','application/octet-stream');
add('otf','font/opentype');
add('eot','application/vnd.ms-fontobject');
add('zip','application/zip');
add('pdf','application/pdf');
end;
end;
function FREDB_Filename2MimeType(const filename: string): TFRE_DB_MimeTypeStr;
var
i : NativeInt;
ext : string;
begin
ext := Copy(lowercase(ExtractFileExt(filename)),2,maxint);
for i := 0 to high(GFRE_DB_MIME_TYPES) do
begin
if GFRE_DB_MIME_TYPES[i].extension = ext then
exit(GFRE_DB_MIME_TYPES[i].mimetype);
end;
result := 'application/octet-stream';
end;
function FREDB_FindStringIndexInArray(const text: TFRE_DB_String; const strings: TFRE_DB_StringArray): integer;
var i: Integer;
begin
result := -1;
for i:=0 to high(strings) do begin
if text=strings[i] then exit(i);
end;
end;
function FREDB_CombineString(const strings: TFRE_DB_StringArray; const sep: TFRE_DB_String): TFRE_DB_String;
var i:integer;
begin
result := '';
for i:=0 to high(strings)-1 do begin
result := result+strings[i]+sep;
end;
if High(strings)>=0 then begin
result := result + strings[high(strings)];
end;
end;
function FREDB_CombineNametypes(const strings: TFRE_DB_NameTypeArray; const sep: TFRE_DB_String): TFRE_DB_String;
var i:integer;
begin
result := '';
for i:=0 to high(strings)-1 do begin
result := result+strings[i]+sep;
end;
if High(strings)>=0 then begin
result := result + strings[high(strings)];
end;
end;
procedure FREDB_SeperateString(const value, sep: TFRE_DB_String; var Strings: TFRE_DB_StringArray);
var SepLen : Integer;
F, P : PChar;
Index : Integer;
UniString : AnsiString;
begin
if Value = '' then exit;
if Sep = '' then begin
SetLength(Strings, 1);
Strings[0] := Value;
Exit;
end;
SepLen := Length(Sep);
Index := 0;
P := PChar(@Value[1]);
while P^ <> #0 do begin
F := P;
P := StrPos(P, PChar(@Sep[1]));
if P = nil then P := StrEnd(F);
if Index >= length(Strings) then SetLength(Strings, length(strings)+10);
SetString(UniString, F, P - F);
Strings[Index] := UniString;
Inc(Index);
if P^ <> #0 then Inc(P, SepLen);
end;
if Index < length(strings) then begin
SetLength(Strings, Index);
end;
end;
function FREDB_DBNameType_Compare(const S1, S2: TFRE_DB_NameType): NativeInt;
begin
result := Default_RB_String_Compare(s1,s2);
end;
function FREDB_DBString_Compare(const S1, S2: TFRE_DB_String): NativeInt; // TODO:UnicodeCheck
begin
result := Default_RB_String_Compare(s1,s2);
end;
function FREDB_DBint64_Compare(const S1, S2: int64): NativeInt;
begin
result := s1-s2;
end;
function FREDB_DBuint64_Compare(const S1, S2: uint64): NativeInt;
begin
result := s1-s2;
end;
function FREDB_FieldtypeShortString2Fieldtype(const fts: TFRE_DB_String): TFRE_DB_FIELDTYPE;
begin
for result in TFRE_DB_FIELDTYPE do begin
if CFRE_DB_FIELDTYPE_SHORT[result]=fts then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid short fieldtype specifier : ['+fts+']');
end;
function FREDB_FieldDepVisString2FieldDepVis(const fts: TFRE_DB_String): TFRE_DB_FieldDepVisibility;
begin
for result in TFRE_DB_FieldDepVisibility do begin
if CFRE_DB_FIELDDEPVISIBILITY[result]=fts then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid fielddepvisibility specifier : ['+fts+']');
end;
function FREDB_FieldDepESString2FieldDepES(const fts: TFRE_DB_String): TFRE_DB_FieldDepEnabledState;
begin
for result in TFRE_DB_FieldDepEnabledState do begin
if CFRE_DB_FIELDDEPENABLEDSTATE[result]=fts then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid fielddepenabledstate specifier : ['+fts+']');
end;
function FREDB_FilterTypeString2Filtertype(const fts: TFRE_DB_String): TFRE_DB_FILTERTYPE;
begin
for result in TFRE_DB_FILTERTYPE do begin
if CFRE_DB_FILTERTYPE[result]=fts then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid short filtertype specifier : ['+fts+']');
end;
function FREDB_Bool2String(const bool: boolean): String;
begin
result := BoolToStr(bool,'1','0');
end;
function FREDB_EncodeVarRec(const v : TVarRec):TFRE_DB_String;
begin
result := Char(v.VType);
case v.VType of
vtInteger:
result := result + IntToStr(Int64(v.VInteger));
vtBoolean:
result := result + BoolToStr(v.VBoolean,'1','0');
vtChar:
result := result + v.VChar;
vtExtended:
result := result + FloatToStr(v.VExtended^);
vtString:
result := result + v.VString^;
vtAnsiString:
result := result + AnsiString(v.VAnsiString);
vtCurrency:
result := result + CurrToStr(v.VCurrency^);
//vtWideString:
// result := result + PWideString(v.VWideString)^;
vtInt64:
result := result + IntToStr(v.VInt64^);
vtQWord:
result := result + IntToStr(v.VInt64^);
vtUnicodeString :
result := result + UnicodeString(v.VUnicodeString);
else
raise Exception.Create('unsuported type'+inttostr(v.VType)+' for encoding');
end;
Result := GFRE_BT.Base64Encode(result);
end;
procedure FREDB_DecodeVarRecParams(const params: TFRE_DB_StringArray; var vaparams: TFRE_DB_ConstArray);
var i : NativeInt;
param : TFRE_DB_String;
begin
SetLength(vaparams,Length(params));
for i:=0 to high(params) do
begin
param := params[i];
if Length(param)=0 then
raise EFRE_DB_Exception.Create('invalid encoding');
vaparams[i].VType := ord(param[1]);
vaparams[i].VPointer := nil; { safe zero }
param := copy(param,2,maxint);
case vaparams[i].VType of
vtInteger:
vaparams[i].VInteger := StrToInt(param);
vtBoolean:
vaparams[i].VBoolean := param[1]='1';
vtChar:
vaparams[i].VChar := param[1];
vtExtended:
begin
New(vaparams[i].VExtended);
vaparams[i].VExtended^ := StrToFloat(param);
end;
vtString:
begin
New(vaparams[i].VString);
PShortString(vaparams[i].VString)^ := param;
end;
vtAnsiString:
AnsiString(vaparams[i].VAnsiString) := param;
vtCurrency:
begin
New(vaparams[i].VCurrency);
vaparams[i].VCurrency^:= StrToCurr(param);
end;
vtInt64:
begin
New(vaparams[i].VInt64);
vaparams[i].VInt64^ := StrToInt64(param);
end;
vtQWord:
begin
New(vaparams[i].VQWord);
vaparams[i].VQWord^ := StrToQWord(param);
end;
vtUnicodeString :
begin
UnicodeString(vaparams[i].VUnicodeString) := param;
end
else
raise Exception.Create('unsuported type'+inttostr(vaparams[i].VType)+' for encoding');
end;
end;
end;
function FREDB_EncodeTranslatableWithParams(const translation_key: TFRE_DB_String; params: array of const): TFRE_DB_String;
var s : TVarRec;
i : NativeInt;
begin
result:=translation_key;
for i := 0 to high(params) do
result:=result+'#'+FREDB_EncodeVarRec(params[i]); { no '#' in base64 !} // DO NOT USE # in unparametrized KEYS
end;
function FREDB_TranslatableHasParams(var translation_key: TFRE_DB_String; var params: TFRE_DB_StringArray): boolean;
var i : NativeInt;
begin
if Pos('#',translation_key)=0 then
result:=false
else
begin
result := true;
FREDB_SeperateString(translation_key,'#',params);
translation_key :=params[0];
for i := 1 to high(params) do
params[i] := GFRE_BT.Base64Decode(params[i]);
params := Copy(params,1,maxint);
end
end;
procedure FREDB_FinalizeVarRecParams(const vaparams: TFRE_DB_ConstArray);
var i : NativeInt;
begin
for i := 0 to High(vaparams) do
case vaparams[i].VType of
//vtInteger:
//vtBoolean:
//vtChar:
vtExtended:
begin
Dispose(vaparams[i].VExtended);
vaparams[i].VExtended:= nil;
end;
vtString:
begin
Dispose(vaparams[i].VString);
vaparams[i].VString := nil;
end;
vtAnsiString:
AnsiString(vaparams[i].VAnsiString) := '';
vtCurrency:
begin
Dispose(vaparams[i].VCurrency);
vaparams[i].VCurrency := nil;
end;
vtInt64:
begin
Dispose(vaparams[i].VInt64);
vaparams[i].VInt64 := nil;
end;
vtQWord:
begin
Dispose(vaparams[i].VQWord);
vaparams[i].VQWord := nil;
end;
vtUnicodeString :
begin
UnicodeString(vaparams[i].VUnicodeString) := '';
end;
end;
end;
procedure FREDB_FinalizeObjectArray(var obja: IFRE_DB_ObjectArray);
var obj : IFRE_DB_Object;
begin
for obj in obja do
obj.Finalize;
end;
function FREDB_G2H(const uid: TFRE_DB_GUID): ShortString;
begin
result := uid.AsHexString;
end;
function FREDB_G2SB(const uid : TFRE_DB_GUID):ShortString; { uid to binary shortstring }
begin
SetLength(result,16);
move(uid,result[1],16);
end;
function FREDB_SB2G(const uid_sb : ShortString):TFRE_DB_GUID; { binary shortstring to uid}
begin
assert(Length(uid_sb)=16,'error conversion sb2guid len '+inttostr(Length(uid_sb)));
move(uid_sb[1],result,16);
end;
function FREDB_H2G(const uidstr: shortstring): TFRE_DB_GUID;
var gs:ShortString;
i : NativeInt;
function HexStr2Str(const Value: ShortString): ShortString;
var len,i,j:integer;
v:ansistring;
function _dig2int(const dig:ansichar):integer;inline;
begin
result:=0;
case dig of
'0','1','2','3','4','5','6','7','8','9': begin
result:=ord(dig)-48;
end;
'A','B','C','D','E','F':begin
result:=ord(dig)-55;
end;
'a','b','c','d','e','f': begin
result:=ord(dig)-87;
end;
end;
end;
begin
v:=value;
len:=length(v);
setlength(result,len div 2);
i:=1;j:=1;
while i<len do begin
result[j]:=ansichar(_dig2int(v[i])*16+_dig2int(v[i+1])); // conservative
inc(i,2);inc(j);
end;
end;
begin
i := Length(uidstr);
if i<>32 then raise Exception.Create('a uid hexstring must be 32 chars not '+inttostr(i)+' chars');
gs := HexStr2Str(uidstr);
Move(gs[1],result.D[0],16);
end;
function FREDB_ExtractUidsfromRightArray(const str: TFRE_DB_StringArray; const rightname: TFRE_DB_STRING): TFRE_DB_GUIDArray;
var uid,uidv : TFRE_DB_GUID;
entry : TFRE_DB_String;
sp,cnt,i,j : NativeInt;
fnd : boolean;
begin
cnt := 0;
SetLength(result,length(str));
for i := 0 to high(str) do
begin
entry := str[i];
sp := pos('@',entry);
if sp>0 then
begin
if rightname<>'' then
if rightname<>copy(entry,1,sp-1) then
continue;
uid := FREDB_H2G(Copy(entry,sp+1,maxint));
fnd := false;
for j := 0 to cnt-1 do
begin
uidv := result[j];
if uidv=uid then
begin
fnd:=true;
break;
end;
end;
if not fnd then
begin
result[cnt] := uid;
inc(cnt);
end;
end;
end;
SetLength(result,cnt);
end;
function FREDB_H2GArray(const str: string): TFRE_DB_GUIDArray;
var sa : TFOSStringArray;
i : NativeInt;
begin
GFRE_BT.SeperateString(str,',',sa);
SetLength(result,length(sa));
for i:= 0 to high(sa) do
result[i] := FREDB_H2G(sa[i]);
end;
function FREDB_H2GArray(const str: TFRE_DB_String): TFRE_DB_GUIDArray;
var sa : TFOSStringArray;
i : NativeInt;
begin
GFRE_BT.SeperateString(str,',',sa);
SetLength(result,length(sa));
for i:= 0 to high(sa) do
result[i] := FREDB_H2G(sa[i]);
end;
function FREDB_String2Bool(const str: string): boolean;
begin
if (str='1') or (UpperCase(str)='TRUE') then begin
result := true;
end else
if (str='0') or (UpperCase(str)='FALSE') then begin
result := false;
end else raise EFRE_DB_Exception.Create(edb_ERROR,'invalid string to bool conversion : value=['+str+']');
end;
function FREDB_SplitRefLinkDescription(key_description: TFRE_DB_NameTypeRL; out rl_field, rl_scheme: TFRE_DB_NameTypeRL): boolean;
var fpos,tpos : NativeInt;
begin
key_description:=uppercase(key_description);
fpos := pos('>',key_description);
tpos := pos('<',key_description);
if (fpos=0) and
(tpos=0) then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid linkref spec, must include exactly one "<" or ">" ');
if (fpos>0) and
(tpos>0) then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid linkref spec, must include exactly "<" or ">"');
if fpos>0 then
result := true
else
result := false;
if result then
begin
rl_field := Copy(key_description,1,fpos-1);
rl_scheme := Copy(key_description,fpos+1,maxint);
end
else
begin
rl_scheme := Copy(key_description,1,tpos-1);
rl_field := Copy(key_description,tpos+1,maxint);
end;
end;
function FREDB_SplitRefLinkDescriptionEx(key_description: TFRE_DB_NameTypeRL; out rl_field, rl_scheme: TFRE_DB_NameTypeRL; out recursive: boolean): boolean;
var fpos,tpos : NativeInt;
incr : NativeInt;
begin
key_description:=uppercase(key_description);
fpos := pos('>>',key_description);
tpos := pos('<<',key_description);
if (fpos>0) or (tpos>0) then
begin
recursive := true;
end
else
begin
recursive := false;
fpos := pos('>',key_description);
tpos := pos('<',key_description);
end;
if (fpos=0) and
(tpos=0) then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid linkref spec, must include exactly one "<" or ">" ');
if (fpos>0) and
(tpos>0) then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid linkref spec, must include exactly "<" or ">"');
if fpos>0 then
result := true
else
result := false;
if recursive then
incr := 2
else
incr := 1;
if result then
begin
rl_field := Copy(key_description,1,fpos-1);
rl_scheme := Copy(key_description,fpos+incr,maxint);
end
else
begin
rl_scheme := Copy(key_description,1,tpos-1);
rl_field := Copy(key_description,tpos+incr,maxint);
end;
end;
function FREDB_String2NativeInt(const str: String): NativeInt;
var Error: word;
begin
Val(str, result, Error);
if Error <> 0 then raise Exception.Create('conversion failed str->nativeint');
end;
function FREDB_String2NativeUInt(const str: String) : NativeUint;
var Error: word;
begin
Val(str, result, Error);
if Error <> 0 then raise Exception.Create('conversion failed str->nativeuint');
end;
function FREDB_NumFilterType2String(const nft: TFRE_DB_NUM_FILTERTYPE): String;
begin
result := CFRE_DB_NUM_FILTERTYPE[nft];
end;
function FREDB_String2NumfilterType(const str: string): TFRE_DB_NUM_FILTERTYPE;
begin
for result in TFRE_DB_NUM_FILTERTYPE do begin
if CFRE_DB_NUM_FILTERTYPE[result]=str then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid numfiltertype specifier : ['+str+']');
end;
function FREDB_String2StrFilterType(const str: string): TFRE_DB_STR_FILTERTYPE;
begin
for result in TFRE_DB_STR_FILTERTYPE do begin
if CFRE_DB_STR_FILTERTYPE[result]=str then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid stringfiltertype specifier : ['+str+']');
end;
function FREDB_StrFilterType2String(const sft: TFRE_DB_STR_FILTERTYPE): String;
begin
result := CFRE_DB_STR_FILTERTYPE[sft];
end;
function FREDB_Guid_Same(const d1, d2: TFRE_DB_GUID): boolean;
begin
result := RB_Guid_Compare(d1,d2)=0;
end;
function FREDB_String2StdRightShort(const c: Char): TFRE_DB_STANDARD_RIGHT;
begin
if CFRE_DB_STANDARD_RIGHT_SHORT[sr_BAD]=c then
exit(sr_BAD);
if CFRE_DB_STANDARD_RIGHT_SHORT[sr_DELETE]=c then
exit(sr_DELETE);
if CFRE_DB_STANDARD_RIGHT_SHORT[sr_FETCH]=c then
exit(sr_FETCH);
if CFRE_DB_STANDARD_RIGHT_SHORT[sr_UPDATE]=c then
exit(sr_UPDATE);
if CFRE_DB_STANDARD_RIGHT_SHORT[sr_STORE]=c then
exit(sr_STORE);
raise EFRE_DB_Exception.Create(edb_ILLEGALCONVERSION,'parameter [%s] is not a stdrightshortencoding',[string(c)]);
end;
function FREDB_Guids_Same(const d1, d2: TFRE_DB_GUID): boolean;
begin
result := RB_Guid_Compare(d1,d2)=0;
end;
function FREDB_Guids_Compare(const d1, d2: TFRE_DB_GUID): NativeInt;
begin
result := RB_Guid_Compare(d1,d2);
end;
function FREDB_Guid_ArraysSame(const arr1, arr2: TFRE_DB_GUIDArray): boolean;
var i : NativeInt;
begin
if Length(arr1)<>Length(arr2) then
exit(false);
for i:=0 to high(arr1) do
if not FREDB_Guids_Same(arr1[i],arr2[i]) then
exit(false);
exit(true);
end;
function FREDB_GuidArray2String(const arr: TFRE_DB_GUIDArray): String;
var i : NativeInt;
begin
result:= '[';
for i := 0 to high(arr)-1 do
begin
result := result+arr[i].AsHexString+',';
end;
if High(arr)>=0 then
result := result+arr[high(arr)].AsHexString;
result:=result+']';
end;
function FREDB_CheckGuidsUnique(const arr: TFRE_DB_GUIDArray): boolean;
var l_check : TFRE_DB_CountedGuidArray;
i : NativeInt;
begin
l_check := FREDB_GuidList2Counted(arr);
result := true;
for i:=0 to High(l_check) do
if l_check[i].count>1 then
exit(false);
end;
function FREDB_GuidList2Counted(const arr: TFRE_DB_GUIDArray; const stop_on_first_double: boolean): TFRE_DB_CountedGuidArray;
var i,j : integer;
found : integer;
last : integer;
begin
SetLength(result,Length(arr));
for i := 0 to high(arr) do begin
found := -1;
for j := 0 to high(result) do begin
last := j;
if Result[j].count=0 then break;
if FREDB_Guids_Same(Result[j].link,arr[i]) then begin
found := j;
break;
end;
end;
if found=-1 then begin
result[last].count:=1;
result[last].link:=arr[i];
end else begin
inc(result[found].count);
if stop_on_first_double then break;
end;
end;
found := 0;
for i := 0 to high(result) do begin
if result[i].count=0 then begin
found:=i;
break;
end;
end;
SetLength(result,found);
end;
//function FREDB_ObjReferences2GuidArray(const ref: TFRE_DB_ObjectReferences): TFRE_DB_GUIDArray;
//var i,j : NativeInt;
// cnt : NativeInt;
//begin
// cnt := 0;
// for i := 0 to high(ref) do
// cnt := cnt + Length(ref[i].linklist);
// SetLength(Result,cnt);
// cnt := 0;
// for i := 0 to High(ref) do
// for j := 0 to high(ref[i].linklist) do
// begin
// Result[cnt] := ref[i].linklist[j];
// inc(cnt);
// end;
//end;
function FREDB_Guids_SortPredicate(const d1, d2: TFRE_DB_GUID): boolean;
var res : NativeInt;
begin
res := RB_Guid_Compare(d1,d2);
result := res=-1;
end;
function FREDB_ObjectToPtrUInt(const obj: TObject): PtrUInt;
begin
result := PtrUInt(obj);
end;
function FREDB_PtrUIntToObject(const obj: PtrUInt): TObject;
begin
result := TObject(obj);
end;
procedure FREDB_BinaryKey2ByteArray(const key: PByte; const k_len: NativeInt; var bytearr: TFRE_DB_ByteArray);
begin
SetLength(bytearr,k_len);
move(key^,bytearr[0],k_len);
end;
function FREDB_GetIndexTypeForFieldType(const fld_type: TFRE_DB_FIELDTYPE): TFRE_DB_INDEX_TYPE;
begin
case fld_type of
fdbft_GUID,
fdbft_ObjLink,
fdbft_Boolean,
fdbft_Byte,
fdbft_UInt16,
fdbft_UInt32,
fdbft_UInt64 : result := fdbit_Unsigned;
fdbft_Int16,
fdbft_Int32,
fdbft_Int64,
fdbft_Currency,
fdbft_DateTimeUTC: result := fdbit_Signed;
fdbft_Real32,
fdbft_Real64: result := fdbit_Real;
fdbft_String: result := fdbit_Text;
else
result := fdbit_Unsupported;
end;
end;
function FREDB_GetIndexTypeFromObjectEncoding(const obj_enc: IFRE_DB_Object): TFRE_DB_INDEX_TYPE;
var fld : IFRE_DB_Field;
begin
if not obj_enc.FieldOnlyExisting('IXT',fld) then
begin
result := fdbit_SpecialValue;
exit;
end;
if not (fld.FieldType=fdbft_Byte) then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'invalid index value encoding/field type');
case fld.AsByte of
0 : result := fdbit_Unsupported;
1 : result := fdbit_Unsigned;
2 : result := fdbit_Signed;
3 : result := fdbit_Real;
4 : result := fdbit_Text;
end;
end;
function FREDB_GetIndexFldValFromObjectEncoding(const obj_enc: IFRE_DB_Object): IFRE_DB_Field;
begin
obj_enc.FieldOnlyExisting('IXV',result);
end;
function FREDB_GetDomainIDFldValFromObjectEncoding(const obj_enc: IFRE_DB_Object): IFRE_DB_Field;
var fld : IFRE_DB_Field;
begin
result := nil;
if obj_enc.FieldOnlyExisting('IXD',fld) then
begin
try
obj_enc.Field('IXDD').AsGUID := FREDB_H2G(fld.AsString);
except
on e:exception do
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid domainid encoding : %s',[e.message]);
end;
end
else
begin
if obj_enc.FieldOnlyExisting('IXMD',fld) then
begin
try
obj_enc.Field('IXDD').AsGUID := fld.AsGUID;
except
on e:exception do
raise EFRE_DB_Exception.Create(edb_ERROR,'userfallback / invalid domainid encoding : %s',[e.message]);
end;
end
else
raise EFRE_DB_Exception.Create(edb_ERROR,'no domainid encoding,but needed');
end;
result := obj_enc.Field('IXDD');
end;
procedure FREDB_SetUserDomIDFldValForObjectEncoding(const obj_enc: IFRE_DB_Object; ut: IFRE_DB_USER_RIGHT_TOKEN);
begin
if assigned(ut) then
obj_enc.Field('IXMD').AsGUID := ut.GetMyDomainID;
end;
function FREDB_NewIndexFldValForObjectEncoding(const fld: IFRE_DB_Field; const domaid_uid_String: TFRE_DB_GUID_String): IFRE_DB_Object;
var ixt : TFRE_DB_INDEX_TYPE;
begin
if not assigned(fld) then
exit(GFRE_DBI.NewObject); { Null Value Encoding }
ixt := FREDB_GetIndexTypeForFieldType(fld.FieldType);
if ixt=fdbit_Unsupported then
raise EFRE_DB_Exception.Create(edb_ERROR,'the fieldtype [%s] is unsupported in index encodings',[fld.FieldTypeAsString]);
result := GFRE_DBI.NewObject;
case ixt of
fdbit_Unsigned: result.Field('IXT').AsByte:=1;
fdbit_Signed: result.Field('IXT').AsByte:=2;
fdbit_Real: result.Field('IXT').AsByte:=3;
fdbit_Text: result.Field('IXT').AsByte:=4;
end;
result.Field('IXV').CloneFromField(fld);
if domaid_uid_String<>'' then
result.Field('IXD').AsString:=domaid_uid_String;
end;
function FREDB_GetGlobalTextKey(const key: String): String;
begin
Result:='$TFRE_DB_GLOBAL_TEXTS_'+key;
end;
function FREDB_getThemedResource(const id: String): String;
begin
Result:='/fre_css/'+cFRE_WEB_STYLE+'/'+id;
end;
function FREDB_RightSetString2RightSet(const rightstr: ShortString): TFRE_DB_STANDARD_RIGHT_SET;
begin
end;
function FREDB_StringInArray(const src: string; const arr: TFRE_DB_StringArray): boolean;
begin
result := FREDB_StringInArrayIdx(src,arr)<>-1;
end;
function FREDB_StringInNametypeArray(const src: string; const arr: TFRE_DB_NameTypeArray): boolean;
begin
result := FREDB_StringInNametypeArrayIdx(src,arr)<>-1;
end;
function FREDB_StringArray2Upper(const sa: TFRE_DB_StringArray): TFRE_DB_StringArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := uppercase(sa[i]);
end;
function FREDB_NametypeArray2Upper(const sa: TFRE_DB_NameTypeArray): TFRE_DB_NameTypeArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := uppercase(sa[i]);
end;
function FREDB_StringArray2Lower(const sa: TFRE_DB_StringArray): TFRE_DB_StringArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := lowercase(sa[i]);
end;
function FREDB_StringArray2NametypeArray(const sa: TFRE_DB_StringArray): TFRE_DB_NameTypeArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := sa[i];
end;
function FREDB_StringArray2NametypeRLArray(const sa: TFRE_DB_StringArray): TFRE_DB_NameTypeRLArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := sa[i];
end;
function FREDB_StringArrayOpen2StringArray(const sa: array of TFRE_DB_String): TFRE_DB_StringArray;
var i :NativeInt;
begin
SetLength(result,length(sa));
for i := 0 to high(sa) do
result[i] := sa[i];
end;
function FREDB_ClassArray2StringArray(const sa: array of TClass): TFRE_DB_StringArray;
var i :NativeInt;
begin
SetLength(result,length(sa));
for i := 0 to high(sa) do
result[i] := sa[i].ClassName;
end;
function FREDB_NametypeArray2StringArray(const sa: TFRE_DB_NameTypeArray): TFRE_DB_StringArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := sa[i];
end;
function FREDB_NametypeArrayOpen2NametypeArray(const sa: array of TFRE_DB_NameType): TFRE_DB_NameTypeArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i] := sa[i];
end;
function FREDB_StringArray2UidArray(const sa: array of TFRE_DB_String): TFRE_DB_GUIDArray;
var
i: NativeInt;
begin
SetLength(result,Length(sa));
for i:=0 to high(result) do
result[i].SetFromHexString(sa[i]);
end;
function FREDB_GuidArrayOpen2GuidArray(const ga: array of TFRE_DB_GUID): TFRE_DB_GUIDArray;
var i : NativeInt;
begin
SetLength(result,Length(ga));
for i:=0 to high(ga) do
result[i] := ga[i];
end;
function FREDB_NumFld2Int64Array(const fld: IFRE_DB_Field; var a: TFRE_DB_Int64Array): boolean;
var i : integer;
begin
result := true;
SetLength(a,fld.ValueCount);
case fld.FieldType of
fdbft_Byte:
for i := 0 to high(a) do
a[i] := fld.AsByteItem[i];
fdbft_Int16:
for i := 0 to high(a) do
a[i] := fld.AsInt16Item[i];
fdbft_UInt16:
for i := 0 to high(a) do
a[i] := fld.AsUInt16Item[i];
fdbft_Int32:
for i := 0 to high(a) do
a[i] := fld.AsInt32Item[i];
fdbft_UInt32:
for i := 0 to high(a) do
a[i] := fld.AsUInt32Item[i];
fdbft_Int64:
a := fld.AsInt64Arr;
fdbft_UInt64:
for i := 0 to high(a) do
a[i] := fld.AsUInt64Item[i];
fdbft_Currency:
for i := 0 to high(a) do
a[i] := int64(fld.AsCurrencyItem[i]);
fdbft_DateTimeUTC:
for i := 0 to high(a) do
a[i] := fld.AsDateTimeUTCItem[i];
else
exit(false);
end;
end;
function FREDB_NumFld2UInt64Array(const fld: IFRE_DB_Field; var a: TFRE_DB_UInt64Array): boolean;
var i : integer;
begin
result := true;
SetLength(a,fld.ValueCount);
case fld.FieldType of
fdbft_Byte:
for i := 0 to high(a) do
a[i] := fld.AsByteItem[i];
fdbft_Int16:
for i := 0 to high(a) do
a[i] := fld.AsInt16Item[i];
fdbft_UInt16:
for i := 0 to high(a) do
a[i] := fld.AsUInt16Item[i];
fdbft_Int32:
for i := 0 to high(a) do
a[i] := fld.AsInt32Item[i];
fdbft_UInt32:
for i := 0 to high(a) do
a[i] := fld.AsUInt32Item[i];
fdbft_Int64:
for i := 0 to high(a) do
a[i] := fld.AsInt64Item[i];
fdbft_UInt64:
a := fld.AsUInt64Arr;
fdbft_Currency:
for i := 0 to high(a) do
a[i] := int64(fld.AsCurrencyItem[i]);
fdbft_DateTimeUTC:
for i := 0 to high(a) do
a[i] := fld.AsDateTimeUTCItem[i];
else
exit(false);
end;
end;
function FREDB_StringInArrayIdx(const src: string; const arr: TFRE_DB_StringArray): NativeInt;
var i: NativeInt;
begin
for i:=0 to High(arr) do
if src=arr[i] then
exit(i);
exit(-1);
end;
function FREDB_StringInNametypeArrayIdx(const src: string; const arr: TFRE_DB_NameTypeArray): NativeInt;
var i: NativeInt;
begin
for i:=0 to High(arr) do
if src=arr[i] then
exit(i);
exit(-1);
end;
function FREDB_PrefixStringInArray(const pfx: string; const arr: TFRE_DB_StringArray): boolean;
var i: NativeInt;
begin
result := false;
for i:=0 to High(arr) do
if Pos(pfx,arr[i])=1 then
exit(true);
end;
procedure FREDB_ConcatStringArrays(var TargetArr: TFRE_DB_StringArray; const add_array: TFRE_DB_StringArray);
var i,len_target,high_add_array,cnt :integer;
begin
len_target := Length(TargetArr);
SetLength(TargetArr,len_target+Length(add_array));
high_add_array := high(add_array);
cnt := 0;
for i:= 0 to high_add_array do
if not FREDB_StringInArray(add_array[i],TargetArr) then
begin
TargetArr[len_target+cnt] := add_array[i];
inc(cnt);
end;
SetLength(TargetArr,len_target+cnt);
end;
procedure FREDB_ConcatGUIDArrays(var TargetArr: TFRE_DB_GuidArray; const add_array: TFRE_DB_GuidArray);
var i,len_target,high_add_array,cnt :integer;
begin
len_target := Length(TargetArr);
SetLength(TargetArr,len_target+Length(add_array));
high_add_array := high(add_array);
cnt := 0;
for i:= 0 to high_add_array do
if FREDB_GuidInArray(add_array[i],TargetArr)=-1 then
begin
TargetArr[len_target+cnt] := add_array[i];
inc(cnt);
end;
SetLength(TargetArr,len_target+cnt);
end;
procedure FREDB_ConcatReferenceArrays(var TargetArr: TFRE_DB_ObjectReferences; const add_array: TFRE_DB_ObjectReferences);
var i,len_target,high_add_array,cnt :integer;
begin
len_target := Length(TargetArr);
SetLength(TargetArr,len_target+Length(add_array));
high_add_array := high(add_array);
cnt := 0;
for i:= 0 to high_add_array do
begin
TargetArr[len_target+cnt] := add_array[i];
inc(cnt);
end;
SetLength(TargetArr,len_target+cnt);
end;
function FREDB_GuidInArray(const check: TFRE_DB_GUID; const arr: TFRE_DB_GUIDArray): NativeInt;
var i: NativeInt;
begin
result := -1;
for i:=0 to High(arr) do
if FREDB_Guids_Same(check,arr[i]) then
exit(i);
end;
function FREDB_GuidInObjArray(const check: TFRE_DB_GUID; const arr: IFRE_DB_ObjectArray): NativeInt;
var i: NativeInt;
begin
result := -1;
for i:=0 to High(arr) do
if check=arr[i].UID then
exit(i);
end;
function FREDB_FindNthGuidIdx(n: integer; const guid: TFRE_DB_GUID; const arr: TFRE_DB_GUIDArray): integer;
var i: Integer;
begin
result:=-1;
if n<=0 then raise EFRE_DB_Exception.Create(edb_ERROR,'must specify a positive integer greater than zero');
for i:=0 to high(arr) do
if FREDB_Guids_Same(guid,arr[i]) then
begin
dec(n);
if n=0 then
exit(i);
end;
end;
function FREDB_CheckAllStringFieldsEmptyInObject(const obj: IFRE_DB_Object): boolean;
var check:boolean;
function CheckFunc(const field:IFRE_DB_FIELD):boolean;
begin
result := false;
if field.IsUIDField then
exit;
if field.FieldType=fdbft_Object then
begin
check := FREDB_CheckAllStringFieldsEmptyInObject(field.AsObject);
result := not check;
end
else
begin
if field.FieldType<>fdbft_String then
raise EFRE_DB_Exception.Create(edb_ERROR,'checkempty only works on stringfield-only objects');
if field.AsString<>'' then
begin
result:=true;
check:=false;
end;
end;
end;
begin
Check:=true;
obj.ForAllFieldsBreak(@CheckFunc);
result := check;
end;
function FREDB_RemoveIdxFomObjectArray(const arr: IFRE_DB_ObjectArray; const idx: NativeInt): IFRE_DB_ObjectArray;
var new_arr : IFRE_DB_ObjectArray;
cnt,i : NativeInt;
begin
if (idx<0) or (idx>High(arr)) then
raise EFRE_DB_Exception.Create(edb_ERROR,'FREDB_RemoveIdxFomObjectArray idx not in bounds failed -> [%d<=%d<=%d]', [0,idx,high(arr)]);
SetLength(new_arr,Length(arr)-1);
cnt := 0;
for i:=0 to idx-1 do
begin
new_arr[cnt] := arr[i];
inc(cnt)
end;
for i:=idx+1 to high(arr) do
begin
new_arr[cnt] := arr[i];
inc(cnt);
end;
result := new_arr;
end;
function FREDB_InsertAtIdxToObjectArray(const arr: IFRE_DB_ObjectArray; var at_idx: NativeInt; const new_obj: IFRE_DB_Object ; const before : boolean): IFRE_DB_ObjectArray;
var cnt,i,myat : NativeInt;
begin
SetLength(result,Length(arr)+1);
if (at_idx<0) or (at_idx>High(Result)) then
raise EFRE_DB_Exception.Create(edb_ERROR,'FREDB_InsertIdxFomObjectArray idx not in bounds failed -> [%d<=%d<=%d]', [0,at_idx,high(arr)]);
cnt := 0;
myat := at_idx;
if length(arr)=0 then
begin
result[0] := new_obj;
exit;
end;
for i:=0 to high(arr) do
begin
if i<>myat then
begin
result[cnt] := arr[i];
inc(cnt);
end
else
begin
if before then
begin
result[cnt] := new_obj;
at_idx := cnt;
inc(cnt);
result[cnt] := arr[i];
inc(cnt);
end
else
begin
result[cnt] := arr[i];
inc(cnt);
result[cnt] := new_obj;
at_idx := cnt;
inc(cnt);
end;
end;
end;
end;
function FREDB_String2DBDisplayType(const fts: string): TFRE_DB_DISPLAY_TYPE;
begin
for result in TFRE_DB_DISPLAY_TYPE do begin
if CFRE_DB_DISPLAY_TYPE[result]=fts then exit;
end;
raise Exception.Create('invalid short DBDisplayType specifier : ['+fts+']');
end;
function FieldtypeShortString2Fieldtype(const fts: TFRE_DB_String): TFRE_DB_FIELDTYPE;
begin
for result in TFRE_DB_FIELDTYPE do begin
if CFRE_DB_FIELDTYPE_SHORT[result]=fts then exit;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid short fieldtype specifier : ['+fts+']');
end;
procedure CheckDbResult(const res: TFRE_DB_Errortype; const error_string: TFRE_DB_String; const tolerate_no_change: boolean);
begin
CheckDbResultFmt(res,error_string,[],tolerate_no_change);
end;
procedure CheckDbResultFmt(const res: TFRE_DB_Errortype; const error_string: TFRE_DB_String; const params: array of const; const tolerate_no_change: boolean);
var str : string;
begin
if (res=edb_OK) or
((res=edb_NO_CHANGE) and tolerate_no_change) then
exit;
str := Format(error_string,params);
if res.Lineinfo='' then
str:=str+LineEnding+res.Msg
else
str:=str+LineEnding+res.Msg+LineEnding+res.Lineinfo;
raise EFRE_DB_Exception.Create(res,str);
end;
type
tmethodnamerec = packed record
name : pshortstring;
addr : pointer;
end;
tmethodnametable = packed record
count : dword;
entries : packed array[0..0] of tmethodnamerec;
end;
pmethodnametable = ^tmethodnametable;
{ TFRE_DB_ROLE }
function TFRE_DB_ROLE.GetDomain(const conn: IFRE_DB_CONNECTION): TFRE_DB_NameType;
begin
result := conn.sys.FetchDomainNameById(GetDomainIDLink);
end;
function TFRE_DB_ROLE.GetDomainIDLink: TFRE_DB_GUID;
begin
result := Field('domainidlink').AsObjectLink;
end;
function TFRE_DB_ROLE.GetIsInternal: Boolean;
begin
Result:=Field('internal').AsBoolean;
end;
function TFRE_DB_ROLE.GetIsDisabled: Boolean;
var f : IFRE_DB_FIELD;
begin
if FieldOnlyExisting('disabled',f) then
Result := f.AsBoolean
else
result := false;
end;
procedure TFRE_DB_ROLE.SetDomainIDLink(AValue: TFRE_DB_GUID);
begin
Field('domainidlink').AsObjectLink := AValue;
UpdateDomainRoleKey;
end;
procedure TFRE_DB_ROLE.SetIsInternal(AValue: Boolean);
begin
Field('internal').AsBoolean:=AValue;
end;
procedure TFRE_DB_ROLE.SetIsDisabled(AValue: Boolean);
begin
Field('disabled').AsBoolean:=AValue;
end;
procedure TFRE_DB_ROLE.UpdateDomainRoleKey;
begin
Field('domainrolekey').AsString := GetDomainRoleKey(ObjectName,domainid);
end;
class procedure TFRE_DB_ROLE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
class procedure TFRE_DB_ROLE.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
currentVersionId := '1.0';
role := CreateClassRole('assignRole','Assign Role','Allowed to assign Roles');
role.AddRight(GetRight4Domain(GetClassRightName('assignRole'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.assignRole role');
role := CreateClassRole('disableRole','Disable Role','Allowed to disable Roles');
role.AddRight(GetRight4Domain(GetClassRightName('disableRole'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.disableRole role');
end;
end;
class procedure TFRE_DB_ROLE.InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
inherited InstallDBObjects4SysDomain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
currentVersionId := '1.0';
role := CreateClassRole('assignRole','Assign System Role','Allowed to assign System Roles');
role.AddRight(GetRight4Domain(GetClassRightName('assignRole'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.assignRole role');
end;
end;
procedure TFRE_DB_ROLE.AddRight(const right: IFRE_DB_RIGHT);
begin
Field('rights').AddString(right);
end;
function TFRE_DB_ROLE.SubFormattedDisplayAvailable: boolean;
begin
Result:=true;
end;
function TFRE_DB_ROLE.GetSubFormattedDisplay(indent: integer): TFRE_DB_String;
var l_right : TFRE_DB_StringArray;
l_ident : shortstring;
i : Integer;
begin
l_right := Field('rights').AsStringArr;
l_ident := StringOfChar(' ',indent);
result := l_ident+FREDB_CombineString(l_right,',');
end;
function TFRE_DB_ROLE.GetRightNames: TFRE_DB_StringArray;
begin
result := Field('rights').AsStringArr;
end;
procedure TFRE_DB_ROLE.AddRightsFromRole(const role: IFRE_DB_ROLE);
var i : NativeInt;
rights : TFRE_DB_StringArray;
begin
rights := role.GetRightNames;
for i := 0 to high(rights) do
begin
AddRight(rights[i]);
end;
//TODO: MakeRightstringsUnique
end;
procedure TFRE_DB_ROLE.RemoveRightsOfRole(const role: IFRE_DB_ROLE);
var
rights : TFRE_DB_StringArray;
begin
rights := role.GetRightNames;
RemoveRights(rights);
end;
procedure TFRE_DB_ROLE.RemoveRights(const rights: TFRE_DB_StringArray);
var
my_rights : TFRE_DB_StringArray;
keep_right : Boolean;
i,j : Integer;
begin
my_rights:=Field('rights').AsStringArr;
DeleteField('rights');
for i := 0 to High(my_rights) do begin
keep_right:=true;
for j := 0 to High(rights) do begin
if my_rights[i]=rights[j] then begin
keep_right:=false;
end;
if keep_right then begin
AddRight(my_rights[i]);
end;
end;
end;
end;
class procedure TFRE_DB_ROLE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
Scheme.Strict(true);
Scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.AddSchemeField('appdataid',fdbft_ObjLink).SetupFieldDef(false,true);
// scheme.AddSchemeFieldSubscheme('rights','TFRE_DB_RIGHT').multiValues:=true;
scheme.AddSchemeField('domainidlink',fdbft_ObjLink).SetupFieldDef(false,false);
scheme.AddSchemeField('domainrolekey',fdbft_String).SetupFieldDef(false,false);
Scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.Create('objname','$DBTEXT:desc'),'%s - (%s)');
end;
class function TFRE_DB_ROLE.GetDomainRoleKey(const rolepart: TFRE_DB_String; const domain_id: TFRE_DB_GUID): TFRE_DB_String;
begin
result := lowercase(FREDB_G2H(domain_id)+'@'+rolepart);
end;
{ TFRE_DB_GROUP }
function TFRE_DB_GROUP.GetDomain(const conn: IFRE_DB_CONNECTION): TFRE_DB_NameType;
begin
conn.SYS.FetchDomainNameById(DomainID);
end;
function TFRE_DB_GROUP.GetDomainIDLink: TFRE_DB_GUID;
begin
result := Field('domainidlink').AsObjectLink;
end;
function TFRE_DB_GROUP.GetIsInternal: Boolean;
begin
Result:=Field('internal').AsBoolean;
end;
function TFRE_DB_GROUP.GetIsDelegation: Boolean;
var f : IFRE_DB_Field;
begin
if FieldOnlyExisting('delegation',f) then
Result:=f.AsBoolean
else
result := false;
end;
function TFRE_DB_GROUP.GetIsDisabled: Boolean;
var f : IFRE_DB_Field;
begin
if FieldOnlyExisting('disabled',f) then
Result:=f.AsBoolean
else
result := false;
end;
function TFRE_DB_GROUP.GetIsProtected: Boolean;
begin
Result:=Field('protected').AsBoolean;
end;
function TFRE_DB_GROUP.GetRoleIDs: TFRE_DB_ObjLinkArray;
begin
result := Field('roleids').AsObjectLinkArray;
end;
function TFRE_DB_GROUP.GetGroupIDs: TFRE_DB_ObjLinkArray;
begin
result := Field('groupids').AsObjectLinkArray;
end;
procedure TFRE_DB_GROUP.SetIsInternal(AValue: Boolean);
begin
Field('internal').AsBoolean:=AValue;
end;
procedure TFRE_DB_GROUP.SetIsDelegation(AValue: Boolean);
begin
Field('delegation').AsBoolean:=AValue;
end;
procedure TFRE_DB_GROUP.SetIsProtected(AValue: Boolean);
begin
Field('protected').AsBoolean:=AValue;
end;
procedure TFRE_DB_GROUP.SetIsDisabled(AValue: Boolean);
begin
Field('disabled').AsBoolean:=AValue;
end;
procedure TFRE_DB_GROUP.SetDomainIDLink(AValue: TFRE_DB_GUID);
begin
Field('domainidlink').AsObjectLink := AValue;
UpdateDomainGroupKey;
end;
procedure TFRE_DB_GROUP.SetRoleIDs(AValue: TFRE_DB_ObjLinkArray);
begin
Field('roleids').AsObjectLinkArray := AValue;
end;
procedure TFRE_DB_GROUP.SetGroupIDs(AValue: TFRE_DB_ObjLinkArray);
begin
Field('groupids').AsObjectLinkArray := AValue;
end;
procedure TFRE_DB_GROUP.UpdateDomainGroupKey;
begin
field('domaingroupkey').AsString := GetDomainGroupKey(ObjectName,domainid);
end;
class procedure TFRE_DB_GROUP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var input_group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
Scheme.Strict(false);
Scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.GetSchemeField('objname').required:=true;
scheme.AddSchemeField('roleids',fdbft_ObjLink).SetupFieldDef(false,true);
scheme.AddSchemeField('appdataid',fdbft_ObjLink);
scheme.AddSchemeField('domainidlink',fdbft_ObjLink).SetupFieldDef(true,false);
scheme.AddSchemeField('domaingroupkey',fdbft_String).SetupFieldDef(true,false);
scheme.AddSchemeField('delegation',fdbft_Boolean);
scheme.AddSchemeField('groupids',fdbft_ObjLink).SetupFieldDef(false,true);
Scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.Create('objname','$DBTEXT:desc'),'%s - (%s)');
input_group:=scheme.AddInputGroup('main').Setup('$TFRE_DB_GROUP_scheme_group_group');
input_group.AddInput('objname','$TFRE_DB_GROUP_scheme_name');
input_group.AddDomainChooser('domainidlink',sr_STORE,TFRE_DB_GROUP,true,'$TFRE_DB_GROUP_scheme_domainid');
input_group.AddInput('delegation','$TFRE_DB_GROUP_scheme_delegation');
input_group.UseInputGroup('TFRE_DB_TEXT','main','desc',true,true,false);
input_group:=scheme.AddInputGroup('main_edit').Setup('$TFRE_DB_GROUP_scheme_group_group');
input_group.AddInput('objname','$TFRE_DB_GROUP_scheme_name');
input_group.AddInput('delegation','$TFRE_DB_GROUP_scheme_delegation',true);
input_group.UseInputGroup('TFRE_DB_TEXT','main','desc',true,true,false);
end;
function TFRE_DB_GROUP.SubFormattedDisplayAvailable: boolean;
begin
if not FieldExists('roles') then exit(false);
result := true;
end;
function TFRE_DB_GROUP.GetSubFormattedDisplay(indent: integer): TFRE_DB_String;
var l_right : TFRE_DB_StringArray;
l_ident : shortstring;
i : Integer;
begin
l_right := Field('roles').AsStringArr;
if Length(l_right)>0 then begin
result := StringOfChar(' ',indent)+GFRE_DBI.StringArray2String(l_right);
end;
end;
class function TFRE_DB_GROUP.GetDomainGroupKey(const grouppart: TFRE_DB_String; const domain_id: TFRE_DB_GUID): TFRE_DB_String;
begin
result := lowercase(FREDB_G2H(domain_id)+'@'+grouppart);
end;
class procedure TFRE_DB_GROUP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_GROUP_scheme_group_group','Group'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_GROUP_scheme_group_domain','Domain'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_GROUP_scheme_name','Name'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_GROUP_scheme_domainid','Domain'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_GROUP_scheme_delegation','Delegation'));
end;
end;
class procedure TFRE_DB_GROUP.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
currentVersionId := '1.0';
role := CreateClassRole('assignGroup','Assign Group','Allowed to assign Groups');
role.AddRight(GetRight4Domain(GetClassRightName('assignGroup'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.assignGroup role');
role := CreateClassRole('disableGroup','Disable Group','Allowed to disable Groups');
role.AddRight(GetRight4Domain(GetClassRightName('disableGroup'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.disableGroup role');
end;
end;
class procedure TFRE_DB_GROUP.InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
inherited InstallDBObjects4SysDomain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
currentVersionId := '1.0';
role := CreateClassRole('assignGroup','Assign System Group','Allowed to assign System Groups');
role.AddRight(GetRight4Domain(GetClassRightName('assignGroup'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.assignGroup role');
end;
end;
{ TFRE_DB_DOMAIN }
function TFRE_DB_DOMAIN.GetIsDefaultDomain: boolean;
var fld : IFRE_DB_FIELD;
begin
if not FieldOnlyExisting('defdom',fld) then
exit(false);
result := fld.AsBoolean;
end;
function TFRE_DB_DOMAIN.GetIsInternal: Boolean;
begin
Result:=Field('internal').AsBoolean;
end;
procedure TFRE_DB_DOMAIN.SetIsDefaultDomain(AValue: boolean);
begin
Field('defdom').AsBoolean:=AValue;
end;
procedure TFRE_DB_DOMAIN.SetIsInternal(AValue: Boolean);
begin
Field('internal').AsBoolean:=AValue;
end;
function TFRE_DB_DOMAIN.GetSuspended: boolean;
var fld : IFRE_DB_FIELD;
begin
if not FieldOnlyExisting('suspended',fld) then
exit(false);
result := fld.AsBoolean;
end;
procedure TFRE_DB_DOMAIN.SetSuspended(AValue: boolean);
begin
Field('suspended').AsBoolean:=AValue;
end;
class procedure TFRE_DB_DOMAIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_DOMAIN_scheme_group','Domain'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_DOMAIN_scheme_name','Name'));
end;
end;
class procedure TFRE_DB_DOMAIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var input_group : IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
Scheme.Strict(false);
Scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.GetSchemeField('objname').required:=true;
Scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.Create('objname','$DBTEXT:desc'),'%s - (%s)');
input_group:=scheme.AddInputGroup('main').Setup('$TFRE_DB_DOMAIN_scheme_group');
input_group.AddInput('objname','$TFRE_DB_DOMAIN_scheme_name');
input_group.UseInputGroup('TFRE_DB_TEXT','main','desc',true,true,false);
end;
function TFRE_DB_DOMAIN.Domainname(const unique: boolean): TFRE_DB_NameType;
begin
if unique then
exit(uppercase(ObjectName))
else
exit(ObjectName)
end;
function TFRE_DB_DOMAIN.Domainkey: TFRE_DB_GUID_String;
begin
result := uppercase(UID_String);
end;
{ TFRE_DB_USER }
function TFRE_DB_USER.GetLogin: TFRE_DB_String;
begin
result := Field('login').AsString;
end;
function TFRE_DB_USER.GetUserclass: TFRE_DB_String;
begin
result := uppercase(Field('userclass').AsString);
if result='' then
result := 'WEBUSER';
end;
function TFRE_DB_USER.GetLoginAtDomain(conn: IFRE_DB_SYS_CONNECTION): TFRE_DB_NameType;
begin
result := login+'@'+conn.FetchDomainNameById(GetDomainIDLink);
end;
function TFRE_DB_USER.GetDomainIDLink: TFRE_DB_GUID;
begin
result := Field('DOMAINIDLINK').AsObjectLink;
end;
function TFRE_DB_USER.GetFirstName: TFRE_DB_String;
begin
result := Field('firstname').AsString;
end;
function TFRE_DB_USER.GetIsInternal: Boolean;
begin
Result:=Field('internal').AsBoolean;
end;
function TFRE_DB_USER.GetUserGroupIDS: TFRE_DB_ObjLinkArray;
begin
result := Field('usergroupids').AsObjectLinkArray;
end;
function TFRE_DB_USER.GetLastName: TFRE_DB_String;
begin
result := Field('lastname').AsString;
end;
procedure TFRE_DB_USER.SetFirstName(const AValue: TFRE_DB_String);
begin
Field('firstname').AsString := AValue;
end;
procedure TFRE_DB_USER.SetGIDA(AValue: TFRE_DB_ObjLinkArray);
begin
Field('usergroupids').AsObjectLinkArray := AValue;
end;
procedure TFRE_DB_USER.SetIsInternal(AValue: Boolean);
begin
Field('internal').AsBoolean:=AValue;
end;
procedure TFRE_DB_USER.SetLastName(const AValue: TFRE_DB_String);
begin
Field('lastname').AsString := AValue;
end;
procedure TFRE_DB_USER.Setlogin(const AValue: TFRE_DB_String);
begin
Field('login').AsString := AValue;
_UpdateDomainLoginKey;
end;
procedure TFRE_DB_USER.SetDomainIDLink(AValue: TFRE_DB_GUID);
begin
Field('domainidlink').AsObjectLink := AValue;
_UpdateDomainLoginKey;
end;
procedure TFRE_DB_USER.SetUserclass(AValue: TFRE_DB_String);
begin
Field('userclass').AsString := AValue;
end;
procedure TFRE_DB_USER._UpdateDomainLoginKey;
begin
field('domainloginkey').AsString := GetDomainLoginKey(login,GetDomainIDLink);
end;
function TFRE_DB_USER.SubFormattedDisplayAvailable: boolean;
begin
result := true;
end;
function TFRE_DB_USER.GetSubFormattedDisplay(indent: integer): TFRE_DB_String;
begin
//FIXME
// Result := StringOfChar(' ',indent)+GFRE_DB.StringArray2String(UserGroupNames);
end;
procedure TFRE_DB_USER.SetImage(const image_stream: TFRE_DB_Stream; const streamtype: string; const etag: string);
begin
Field('picture').AsStream := image_stream;
Field('picture'+cFRE_DB_STKEY).AsString := streamtype;
Field('picture'+cFRE_DB_ST_ETAG).AsString := etag;
end;
procedure TFRE_DB_USER.InitData(const nlogin, nfirst, nlast, npasswd: TFRE_DB_String; const userdomainid: TFRE_DB_GUID; const is_internal: Boolean; const long_desc, short_desc: TFRE_DB_String);
begin
SetDomainID(userdomainid);
SetDomainIDLink(userdomainid);
Login := nlogin;
Firstname := nfirst;
Lastname := nlast;
isInternal := is_internal;
Field('desc').AsDBText.Setlong(long_desc);
Field('desc').AsDBText.SetShort(short_desc);
SetPassword(npasswd);
end;
procedure TFRE_DB_USER.SetPassword(const pw: TFRE_DB_String);
var salt : string;
i : integer;
s : string;
pws : string;
begin
//Field('passwordMD5').AsString:=GFRE_BT.HashString_MD5_HEX(pw);
SetLength(salt,8);
For i:=1 to 8 do
salt[i]:=char(Random(256));
s := GFRE_BT.CalcSaltedSH1Password(pw,salt);
Field('passwordSHA1').AsString:=s;
Field('passwordSVSC').AsString:=s;
end;
function TFRE_DB_USER.Checkpassword(const pw: TFRE_DB_String): boolean;
begin
try
result := GFRE_BT.VerifySaltedSHA1Password(pw,Field('passwordSHA1').AsString);
except
result := false;
end;
end;
class procedure TFRE_DB_USER.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var field_def : IFRE_DB_FieldSchemeDefinition;
input_group : IFRE_DB_InputGroupSchemeDefinition;
params : IFRE_DB_Object;
begin
inherited RegisterSystemScheme(scheme);
Scheme.Strict(true);
scheme.AddSchemeField('login',fdbft_String).SetupFieldDef(true);
scheme.AddSchemeField('firstname',fdbft_String);
scheme.AddSchemeField('lastname',fdbft_String);
scheme.AddSchemeField('passwordMD5',fdbft_String).SetupFieldDef(true,false,'','',true,true);
scheme.AddSchemeField('usergroupids',fdbft_ObjLink).SetupFieldDef(false,true);
scheme.AddSchemeField('domainidlink',fdbft_ObjLink).SetupFieldDef(true,false);
scheme.AddSchemeField('domainloginkey',fdbft_String).SetupFieldDef(true,false);
field_def := scheme.AddSchemeField('picture',fdbft_Stream);
params:=GFRE_DBI.NewObject;
params.Field('width').AsInt16:=70;
params.Field('height').AsInt16:=90;
params.Field('absolute').AsBoolean:=true;
field_def.SetupFieldDef(false,false,'','image',false,false,params);
// scheme.AddSchemeFieldSubscheme('desc','TFRE_DB_TEXT');
Scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.Create('login','firstname','lastname'),'%s - (%s %s)');
input_group:=scheme.AddInputGroup('main').Setup('$TFRE_DB_USER_scheme_user_group');
input_group.AddInput('login','$TFRE_DB_USER_scheme_login');
input_group.AddDomainChooser('domainidlink',sr_STORE,TFRE_DB_USER,true,'$TFRE_DB_USER_scheme_domainidlink');
input_group.AddInput('firstname','$TFRE_DB_USER_scheme_firstname');
input_group.AddInput('lastname','$TFRE_DB_USER_scheme_lastname');
input_group.AddInput('passwordMD5','$TFRE_DB_USER_scheme_passwordMD5');
input_group:=scheme.AddInputGroup('main_edit').Setup('$TFRE_DB_USER_scheme_user_group');
input_group.AddInput('login','$TFRE_DB_USER_scheme_login',true);
input_group.AddInput('firstname','$TFRE_DB_USER_scheme_firstname');
input_group.AddInput('lastname','$TFRE_DB_USER_scheme_lastname');
//input_group.AddInput('passwordMD5','$TFRE_DB_USER_scheme_passwordMD5');
input_group:=scheme.AddInputGroup('descr').Setup('$TFRE_DB_USER_scheme_descr_group');
input_group.UseInputGroup('TFRE_DB_TEXT','main','desc');
input_group:=scheme.AddInputGroup('picture').Setup('$TFRE_DB_USER_scheme_picture_group');
input_group.AddInput('picture','$TFRE_DB_USER_scheme_picture',false,false,'');
end;
class function TFRE_DB_USER.GetDomainLoginKey(const loginpart: TFRE_DB_String; const domain_id: TFRE_DB_GUID): TFRE_DB_String;
begin
result := FREDB_G2H(domain_id)+'@'+lowercase(loginpart);
end;
function TFRE_DB_USER.DomainLoginKey: TFRE_DB_String;
begin
result := field('domainloginkey').AsString;
end;
class procedure TFRE_DB_USER.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_user_group','User'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_login','Login name'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_firstname','Firstname'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_lastname','Lastname'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_passwordMD5','Password'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_picture',''));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_domain_group','Domain'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_domainidlink','Domain'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_descr_group','Description'));
conn.StoreTranslateableText(GFRE_DBI.CreateText('$TFRE_DB_USER_scheme_picture_group','Picture'));
end;
end;
class procedure TFRE_DB_USER.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
inherited InstallDBObjects4Domain(conn, currentVersionId, domainUID);
if currentVersionId='' then begin
currentVersionId := '1.0';
role := CreateClassRole('resetpass','Can reset user password','Allowed to reset user password, without old password');
role.AddRight(GetRight4Domain(GetClassRightName('resetpass'),domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.resetpass role');
end;
end;
class function TFRE_DB_USER.WBC_NewUserOperation(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var dbo : IFRE_DB_Object;
data : IFRE_DB_Object;
res : TFRE_DB_Errortype;
loginf,pw,pwc,
fn,ln : String;
ldesc,sdesc : TFRE_DB_String;
fld : IFRE_DB_Field;
image : TFRE_DB_Stream;
imagetype : String;
domlink : TFRE_DB_GUID;
begin
data := input.Field('DATA').asobject;
domlink := data.field('domainidlink').AsGUID;
loginf := data.Field('login').AsString;
pw := data.Field('PASSWORDMD5').AsString;
pwc := data.Field('PASSWORDMD5_CONFIRM').AsString;
if not data.Field('firstname').IsSpecialClearMarked then
fn := data.Field('firstname').AsString
else
fn := '';
if not data.field('lastname').IsSpecialClearMarked then
ln := data.field('lastname').AsString
else
ln := '';
//dbc.sys.FetchDomainById(GFRE_BT.HexString_2_GUID(data.field('domainidlink').AsString),obj);
if pw<>pwc then
exit(TFRE_DB_MESSAGE_DESC.create.Describe('TRANSLATE: Error','TRANSLATE: Password confirm mismatch',fdbmt_error,nil));
if (data.FieldOnlyExisting('picture',fld) and (not fld.IsSpecialClearMarked)) then
begin
image := fld.AsStream;
imagetype := data.Field('picture'+cFRE_DB_STKEY).AsString;
fld.Clear(true);
end
else
begin
image:=nil;
imagetype:='';
end;
if data.FieldOnlyExisting('desc',fld) then
begin
data := data.Field('desc').AsObject;
if data.FieldOnlyExisting('txt',fld) then
begin
if fld.IsSpecialClearMarked then
ldesc := ''
else
ldesc := fld.AsString;
end;
if data.FieldOnlyExisting('txt_s',fld) then
if fld.IsSpecialClearMarked then
sdesc := ''
else
sdesc := fld.AsString;
end;
res := conn.sys.AddUser(loginf,domlink,pw,fn,ln,image,imagetype,false,ldesc,sdesc,'WEBUSER');
if res=edb_OK then
begin
exit(TFRE_DB_CLOSE_DIALOG_DESC.create.Describe());
end
else
exit(TFRE_DB_MESSAGE_DESC.create.Describe('TRANSLATE: ERROR','TRANSLATE: Creation failed '+CFRE_DB_Errortype[res],fdbmt_error,nil));
end;
function TFRE_DB_USER.WEB_SaveOperation(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var res : TFRE_DB_Errortype;
data : IFRE_DB_Object;
dn : TFRE_DB_NameType;
obj : IFRE_DB_DOMAIN;
modify : boolean;
txt : TFRE_DB_String;
fld : IFRE_DB_FIELD;
opw,npw,cpw : TFRE_DB_String;
checkold : boolean;
l_User : IFRE_DB_USER;
l_UserO : TFRE_DB_User;
begin
data := input.Field('DATA').asobject;
res := conn.sys.FetchUser(GetLogin,DomainID,l_User);
l_UserO := l_User.Implementor_HC as TFRE_DB_USER;
if res<>edb_OK then
exit(TFRE_DB_MESSAGE_DESC.create.Describe('TRANSLATE: Error','TRANSLATE: Fetch Failed',fdbmt_error,nil));
if data.FieldOnlyExisting('firstname',fld) then
begin
if fld.IsSpecialClearMarked then
l_UserO.Firstname:=''
else
l_UserO.Firstname:=fld.AsString;
end;
if data.FieldOnlyExisting('lastname',fld) then
begin
if fld.IsSpecialClearMarked then
l_UserO.Lastname :=''
else
l_UserO.Lastname := fld.AsString;
end;
if data.FieldOnlyExisting('picture',fld) then
begin
if fld.FieldType=fdbft_Stream then
begin
l_UserO.SetImage(fld.AsStream,data.Field('picture'+cFRE_DB_STKEY).AsString,data.Field('picture'+cFRE_DB_ST_ETAG).AsString);
fld.Clear(true);
end
else
begin
//raise EFRE_DB_Exception.Create(edb_ERROR,'the picture field must be a stream field, not [%s] val=[%s]',[fld.FieldTypeAsString,fld.AsString]);
end;
end;
if data.FieldOnlyExisting('pass',fld) then
begin
if not fld.AsObject.Field('new').IsSpecialClearMarked then
begin
opw := fld.AsObject.Field('old').AsString;
npw := fld.AsObject.Field('new').AsString;
cpw := fld.AsObject.Field('confirm').AsString;
if npw<>cpw then
exit(TFRE_DB_MESSAGE_DESC.create.Describe('TRANSLATE: Error','password confirm wrong',fdbmt_error,nil));
checkold := true;
if conn.SYS.GetCurrentUserTokenRef.CheckClassRight4DomainId('resetpass',TFRE_DB_USER,DomainID) and ((l_UserO.Login<>'admin') or ((l_UserO.DomainID<>conn.SYS.GetCurrentUserTokenRef.GetSysDomainID))) then
checkold := false;
if checkold and (not l_UserO.Checkpassword(opw)) then
exit(TFRE_DB_MESSAGE_DESC.create.Describe('TRANSLATE: Error','old password wrong',fdbmt_error,nil));
l_User.SetPassword(npw);
end;
end;
if data.FieldOnlyExisting('desc',fld) then
begin
data := data.Field('desc').AsObject;
if data.FieldOnlyExisting('txt',fld) then
begin
if fld.IsSpecialClearMarked then
l_UserO.Field('desc').AsDBText.ClearLong
else
l_UserO.Field('desc').AsDBText.Setlong(fld.AsString);
end;
if data.FieldOnlyExisting('txt_s',fld) then
if fld.IsSpecialClearMarked then
l_UserO.Field('desc').AsDBText.ClearShort
else
l_UserO.Field('desc').AsDBText.SetShort(fld.AsString);
end;
CheckDbResult(conn.sys.UpdateUser(l_User),'TRANSLATE !! ');// FIXXME CHRIS
exit(TFRE_DB_CLOSE_DIALOG_DESC.create.Describe());
end;
{ TFRE_DB_STATUS_PLUGIN }
procedure TFRE_DB_STATUS_PLUGIN.InternalSetup;
begin
setConfigIsApplied;
setPlanned;
end;
class procedure TFRE_DB_STATUS_PLUGIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_OBJECT_PLUGIN_BASE.Classname);
end;
class procedure TFRE_DB_STATUS_PLUGIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
function TFRE_DB_STATUS_PLUGIN.GetStateFieldForDiffSync: IFRE_DB_Field;
begin
result := Field('state');
end;
procedure TFRE_DB_STATUS_PLUGIN.lock;
begin
Field('locked').AsBoolean:=true;
end;
procedure TFRE_DB_STATUS_PLUGIN.unlock;
begin
Field('locked').AsBoolean:=false;
end;
function TFRE_DB_STATUS_PLUGIN.isLocked: Boolean;
var
fld: IFRE_DB_FIELD;
begin
if FieldOnlyExisting('locked',fld) then begin
Result:=fld.AsBoolean;
end else begin
Result:=false;
end;
end;
procedure TFRE_DB_STATUS_PLUGIN.setApplyConfirmedConfig;
begin
Field('applyconfig').AsBoolean := true;
end;
procedure TFRE_DB_STATUS_PLUGIN.setConfigIsApplied;
begin
Field('applyconfig').AsBoolean := false;
end;
procedure TFRE_DB_STATUS_PLUGIN.setPlanned;
begin
Field('state').AsInt32:=0;
end;
procedure TFRE_DB_STATUS_PLUGIN.setModified;
begin
Field('state').AsInt32:=1;
end;
procedure TFRE_DB_STATUS_PLUGIN.setDeleted;
begin
Field('state').AsInt32:=2;
end;
procedure TFRE_DB_STATUS_PLUGIN.setStable;
begin
Field('state').AsInt32:=3;
end;
procedure TFRE_DB_STATUS_PLUGIN.setPhysicalExisting;
begin
Field('physavail').AsBoolean := true;
end;
function TFRE_DB_STATUS_PLUGIN.getStatusText: TFRE_DB_String;
begin
Result:=Field('state').AsString; //FIXXME - use langres
end;
function TFRE_DB_STATUS_PLUGIN.isModifiedOrPlanned: Boolean;
begin
Result:=Field('state').AsInt32<2;
end;
function TFRE_DB_STATUS_PLUGIN.isLockedOrDeleted: Boolean;
begin
Result:=isLocked or isDeleted;
end;
function TFRE_DB_STATUS_PLUGIN.isPlanned: Boolean;
begin
Result:=Field('state').AsInt32=0;
end;
function TFRE_DB_STATUS_PLUGIN.isModified: Boolean;
begin
Result:=Field('state').AsInt32=1;
end;
function TFRE_DB_STATUS_PLUGIN.isDeleted: Boolean;
begin
Result:=Field('state').AsInt32=2;
end;
function TFRE_DB_STATUS_PLUGIN.isPhysicalExisting: boolean;
begin
result := FieldOnlyExistingBoolean('physavail');
end;
{ TFRE_DB_RIF_RESULT }
function TFRE_DB_RIF_RESULT.GetChildPid: int32;
begin
result := FieldOnlyExistingInt32('cpid',-1);
end;
function TFRE_DB_RIF_RESULT.GetErrorcode: Int32;
begin
result := FieldOnlyExistingInt32('ec',-1);
end;
function TFRE_DB_RIF_RESULT.GetErrorText: TFRE_DB_String;
begin
result := FieldOnlyExistingString('et','UNSET');
end;
function TFRE_DB_RIF_RESULT.GetJobKey: TFRE_DB_String;
begin
result := FieldOnlyExistingString('jk','');
end;
function TFRE_DB_RIF_RESULT.GetJobUid: TFRE_DB_GUID;
begin
result := FieldOnlyExistingUID('ju');
end;
function TFRE_DB_RIF_RESULT.GetTransferStatus: TFRE_DB_COMMAND_STATUS;
begin
result := TFRE_DB_COMMAND_STATUS(FieldOnlyExistingInt32('ts',2));
end;
procedure TFRE_DB_RIF_RESULT.SetChildPid(AValue: int32);
begin
Field('cpid').AsInt32 := AValue;
end;
procedure TFRE_DB_RIF_RESULT.SetErrorcode(AValue: Int32);
begin
Field('ec').AsInt32 := AValue;
end;
procedure TFRE_DB_RIF_RESULT.SetErrorText(AValue: TFRE_DB_String);
begin
Field('et').AsString := AValue;
end;
procedure TFRE_DB_RIF_RESULT.SetJobKey(AValue: TFRE_DB_String);
begin
field('jk').AsString := AValue;
end;
procedure TFRE_DB_RIF_RESULT.SetJobUid(AValue: TFRE_DB_GUID);
begin
field('ju').AsGUID := AValue;
end;
procedure TFRE_DB_RIF_RESULT.SetTransferStatus(AValue: TFRE_DB_COMMAND_STATUS);
begin
Field('ts').AsInt32 := Ord(AValue);
end;
function TFRE_DB_RIF_RESULT.GetTransferStatusString: TFRE_DB_String;
begin
case Transferstatus of
cdcs_OK: result := 'OK';
cdcs_TIMEOUT: result := 'TIMEOUT';
cdcs_ERROR: result := 'ERROR';
end;
end;
{ TFRE_DB_WORKFLOW_DATA }
class procedure TFRE_DB_WORKFLOW_DATA.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.AddSchemeField('wf',fdbft_ObjLink).Required:=true;
scheme.AddSchemeField('dataObj',fdbft_ObjLink);
end;
class procedure TFRE_DB_WORKFLOW_DATA.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
class procedure TFRE_DB_WORKFLOW_DATA.InstallUserDBObjects(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType);
var
coll: IFRE_DB_COLLECTION;
begin
if not conn.CollectionExists(CFOS_WF_DATA_COLLECTION) then begin
coll:=conn.CreateCollection(CFOS_WF_DATA_COLLECTION);
end;
end;
{ TFRE_DB_SESSION_UPO }
function TFRE_DB_SESSION_UPO.GetUpdateStore(const store_id, store_id_dc: shortstring): TFRE_DB_UPDATE_STORE_DESC;
begin
result := FStoreList.Find(store_id) as TFRE_DB_UPDATE_STORE_DESC;
if not Assigned(result) then
begin
result := TFRE_DB_UPDATE_STORE_DESC.create.Describe(store_id,store_id_dc);
FStoreList.Add(store_id,result);
end;
end;
constructor TFRE_DB_SESSION_UPO.Create(const session_id: TFRE_DB_NameType);
begin
FStoreList := TFPHashObjectList.Create(false);
FSessid := session_id;
end;
destructor TFRE_DB_SESSION_UPO.Destroy;
begin
FStoreList.Free;
inherited Destroy;
end;
procedure TFRE_DB_SESSION_UPO.AddStoreUpdate(const store_id, store_id_dc: TFRE_DB_String; const upo: IFRE_DB_Object; const oldpos, newpos, abscount: NativeInt);
var update_st : TFRE_DB_UPDATE_STORE_DESC;
begin
update_st := GetUpdateStore(store_id,store_id_dc);
update_st.addUpdatedEntry(upo,oldpos,newpos,abscount);
end;
procedure TFRE_DB_SESSION_UPO.AddStoreInsert(const store_id, store_id_dc: TFRE_DB_String; const upo: IFRE_DB_Object; const position, abscount: NativeInt);
var update_st : TFRE_DB_UPDATE_STORE_DESC;
begin
update_st := GetUpdateStore(store_id,store_id_dc);
update_st.addNewEntry(upo,position,abscount);
end;
procedure TFRE_DB_SESSION_UPO.AddStoreDelete(const store_id, store_id_dc: TFRE_DB_String; const id: TFRE_DB_String; const position, abscount: NativeInt);
var update_st : TFRE_DB_UPDATE_STORE_DESC;
begin
update_st := GetUpdateStore(store_id,store_id_dc);
update_st.addDeletedEntry(id,position,abscount);
end;
procedure TFRE_DB_SESSION_UPO.DispatchAllNotifications(const session: TFRE_DB_UserSession);
var i : NativeInt;
ct : TFRE_DB_UPDATE_STORE_DESC;
stid : TFRE_DB_NameType;
frt : IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION;
lang : TFRE_DB_StringArray;
procedure FinalTransform(const obj : IFRE_DB_Object);
begin
session.FinalRightTransform(obj,frt,lang);
end;
begin
for i := 0 to FStoreList.Count-1 do
begin
ct := FStoreList.Items[i] as TFRE_DB_UPDATE_STORE_DESC;
stid := ct.GetStoreID_DC;
session.FetchDerivedCollection(stid).GetDeriveTransformation.GetFinalRightTransformFunction(frt,lang);
ct.ForAllUpdated(@FinalTransform);
ct.ForAllInserted(@FinalTransform);
//writeln('HH>>> FINAL,FINAL UPDATE DESC ');
//writeln(ct.DumpToString);
//writeln('-------------------------------');
session.SendServerClientRequest(ct);
end;
end;
procedure TFRE_DB_SESSION_UPO.cs_SendUpdatesToSession;
var ses : TFRE_DB_UserSession;
res : boolean;
begin { In context of Netserver Channel Group }
if GFRE_DBI.NetServ.FetchSessionByIdLocked(FSessid,ses) then
try
res := ses.DispatchCoroutine(TFRE_APSC_CoRoutine(@Ses.COR_SendStoreUpdates),self);
if not res then
begin
Free;
end;
finally
ses.UnlockSession;
end;
end;
{ TFRE_DB_UPDATE_STORE_DESC }
function TFRE_DB_UPDATE_STORE_DESC.Describe(const storeId: String; const storeid_dc: string): TFRE_DB_UPDATE_STORE_DESC;
begin
Field('storeId').AsString:=storeId;
Field('storeIdDC').AsString:=storeid_dc;
Result:=Self;
end;
procedure TFRE_DB_UPDATE_STORE_DESC.addUpdatedEntry(const entry: IFRE_DB_Object; const old_position, new_position: Int64; const absolutecount: Int64);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('item').AsObject := entry.CloneToNewObject();
obj.Field('pos').AsInt64 := old_position;
obj.Field('newpos').AsInt64 := new_position;
obj.Field('total').AsInt32:=absolutecount;
Field('updated').AddObject(obj);
end;
procedure TFRE_DB_UPDATE_STORE_DESC.addDeletedEntry(const entryId: String; const position: Int64; const absolutecount: Int64);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('itemid').AddString(entryId);
obj.Field('pos').AsInt64:=position;
obj.Field('total').AsInt32:=absolutecount;
Field('deleted').AddObject(obj);
end;
procedure TFRE_DB_UPDATE_STORE_DESC.addNewEntry(const entry: IFRE_DB_Object; const position: Int64; const absolutecount: Int64);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('item').AsObject:=entry.CloneToNewObject();
obj.Field('pos').AsInt64:=position;
obj.Field('total').AsInt32:=absolutecount;
Field('new').AddObject(obj);
end;
procedure TFRE_DB_UPDATE_STORE_DESC.setTotalCount(const count: Integer);
begin
Field('total').AsInt32:=count;
end;
procedure TFRE_DB_UPDATE_STORE_DESC.ForAllUpdated(const obcb: IFRE_DB_Obj_Iterator);
var fld :IFRE_DB_Field;
arr : IFRE_DB_ObjectArray;
i: Integer;
begin
if FieldOnlyExisting('updated',fld) then
begin
arr := fld.AsObjectArr;
for i:=0 to high(arr) do
begin
obcb(arr[i].Field('item').AsObject);
end;
end;
end;
procedure TFRE_DB_UPDATE_STORE_DESC.ForAllInserted(const obcb: IFRE_DB_Obj_Iterator);
var fld :IFRE_DB_Field;
arr : IFRE_DB_ObjectArray;
i : Integer;
//procedure Internal(const obj:IFRE_DB_Object);
//begin
// obcb(obj.Field('item').AsObject);
//end;
begin
//if FieldOnlyExisting('new',fld) then
// fld.AsObject.ForAllObjects(@internal);
if FieldOnlyExisting('new',fld) then
begin
arr := fld.AsObjectArr;
for i:=0 to high(arr) do
begin
obcb(arr[i].Field('item').AsObject);
end;
end;
end;
function TFRE_DB_UPDATE_STORE_DESC.GetStoreID: TFRE_DB_NameType;
begin
result := Field('storeid').AsString;
end;
function TFRE_DB_UPDATE_STORE_DESC.GetStoreID_DC: TFRE_DB_NameType;
begin
result := Field('storeIdDC').AsString;
end;
function TFRE_DB_UPDATE_STORE_DESC.hasChanges: Boolean;
begin
Result:=(Field('new').ValueCount + Field('deleted').ValueCount + Field('updated').ValueCount)>0;
end;
{ TFRE_DB_SESSION_DC_RANGE_MGR_KEY }
procedure TFRE_DB_SESSION_DC_RANGE_MGR_KEY.Setup4QryId(const sid: TFRE_DB_SESSION_ID; const ok: TFRE_DB_TRANS_COLL_DATA_KEY; const fk: TFRE_DB_TRANS_COLL_FILTER_KEY; const pp: TFRE_DB_String);
begin
SessionID := sid;
DataKey := ok;
DataKey.filterkey := fk;
Parenthash := GFRE_BT.HashFast32_Hex(pp);
end;
function TFRE_DB_SESSION_DC_RANGE_MGR_KEY.GetRmKeyAsString: TFRE_DB_CACHE_DATA_KEY;
begin
result := SessionID+'@'+DataKey.DC_Name+'/'+Parenthash;
end;
function TFRE_DB_SESSION_DC_RANGE_MGR_KEY.GetFullKeyString: TFRE_DB_CACHE_DATA_KEY;
begin
result := SessionID+'@'+DataKey.GetFullKeyString+'/'+Parenthash;
end;
procedure TFRE_DB_SESSION_DC_RANGE_MGR_KEY.SetupFromQryID(qryid: TFRE_DB_CACHE_DATA_KEY);
var
posat : NativeInt;
parts : TFRE_DB_StringArray;
begin
posat := Pos('@',qryid);
if posat<0 then
raise EFRE_DB_Exception.Create(edb_ERROR,'cannot setup key rm key, no @ in key [%s]',[qryid]);
SessionID := GFRE_BT.SepLeft(qryid,'@');
qryid := GFRE_BT.SepRight(qryid,'@');
FREDB_SeperateString(qryid,'/',parts);
if Length(parts)<>5 then
raise EFRE_DB_Exception.Create(edb_ERROR,'cannot setup key rm key, syntax [%s]',[qryid]);
DataKey.Collname := parts[0];
DataKey.DC_Name := parts[1];
//DataKey.RL_Spec := parts[2];
DataKey.orderkey := parts[2];
DataKey.filterkey := parts[3];
Parenthash := parts[4]; // GFRE_BT.HashFast32_Hex(''); //FIXME : Need right StoreID
end;
{ TFRE_DB_STORE_DATA_DESC }
function TFRE_DB_STORE_DATA_DESC.Describe(const totalCount: Int32): TFRE_DB_STORE_DATA_DESC;
begin
Field('total').AsInt32:=totalCount;
Result:=Self;
end;
procedure TFRE_DB_STORE_DATA_DESC.addEntry(const entry: IFRE_DB_Object);
begin
Field('data').AddObject(entry);
end;
{ TFRE_DB_TRANS_COLL_DATA_KEY }
procedure TFRE_DB_TRANS_COLL_DATA_KEY.Seal;
begin
FSealed := true;
end;
function TFRE_DB_TRANS_COLL_DATA_KEY.IsSealed: Boolean;
begin
result := FSealed;
end;
function TFRE_DB_TRANS_COLL_DATA_KEY.GetFullKeyString: TFRE_DB_CACHE_DATA_KEY;
begin
//result := Collname+'/'+DC_Name+'/'+RL_Spec+'/'+OrderKey+'/'+filterkey;
result := Collname+'/'+DC_Name+'/'+OrderKey+'/'+filterkey;
if orderkey='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid cache key usage, order part is undefined');
if filterkey='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid cache key usage, filter part is undefined');
end;
function TFRE_DB_TRANS_COLL_DATA_KEY.GetOrderKeyPart: TFRE_DB_CACHE_DATA_KEY;
begin
//result := Collname+'/'+DC_Name+'/'+RL_Spec+'/'+OrderKey;
result := Collname+'/'+DC_Name+'/'+OrderKey;
if orderkey='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid cache key usage, order part is undefined');
end;
function TFRE_DB_TRANS_COLL_DATA_KEY.GetBaseDataKey: TFRE_DB_CACHE_DATA_KEY;
begin
//result := Collname+'/'+DC_Name+'/'+RL_Spec;
result := Collname+'/'+DC_Name;
end;
{ TFRE_DB_OBJECT_PLUGIN_BASE }
class procedure TFRE_DB_OBJECT_PLUGIN_BASE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
end;
class procedure TFRE_DB_OBJECT_PLUGIN_BASE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
class function TFRE_DB_OBJECT_PLUGIN_BASE.EnhancesGridRenderingTransform: Boolean;
begin
result := false;
end;
class function TFRE_DB_OBJECT_PLUGIN_BASE.EnhancesGridRenderingPreClientSend: Boolean;
begin
result := false;
end;
class function TFRE_DB_OBJECT_PLUGIN_BASE.EnhancesFormRendering: Boolean;
begin
result := false;
end;
function TFRE_DB_OBJECT_PLUGIN_BASE.CloneToNewPlugin: TFRE_DB_OBJECT_PLUGIN_BASE;
begin
result := self.CloneToNewObject().Implementor_HC as TFRE_DB_OBJECT_PLUGIN_BASE;
end;
function TFRE_DB_OBJECT_PLUGIN_BASE.MyObj: IFRE_DB_Object;
begin
result := Parent.Parent;
end;
{ TFRE_DB_Errortype }
procedure TFRE_DB_Errortype.SetIt(const ecode: TFRE_DB_Errortype_EC; const message: String; const lineinf: string);
begin
Code := ecode;
msg := message;
Lineinfo := lineinf;
end;
function TFRE_DB_Errortype.AsString: string;
begin
result := msg;
end;
{ TFRE_DB_QUERY_DEF }
function TFRE_DB_QUERY_DEF.GetReflinkSpec(const upper_refid: TFRE_DB_NameType): TFRE_DB_NameTypeRLArray;
var i:integer;
begin
for i:=0 to high(DependencyRefIds) do
if DependencyRefIds[i]=upper_refid then
exit(DepRefConstraints[i]);
raise EFRE_DB_Exception.Create(edb_ERROR,'cannot find a reflink spec for reference id '+upper_refid);
end;
function TFRE_DB_QUERY_DEF.GetReflinkStartValues(const upper_refid: TFRE_DB_NameType): TFRE_DB_GUIDArray;
var i:integer;
begin
for i:=0 to high(DependencyRefIds) do
if DependencyRefIds[i]=upper_refid then
exit(DepFilterUids[i]);
raise EFRE_DB_Exception.Create(edb_ERROR,'cannot find the filter values for reference id '+upper_refid);
end;
{ TFRE_DB_INDEX_DEF }
function TFRE_DB_INDEX_DEF.IndexDescription: TFRE_DB_String;
begin
result := IndexClass+' ['+IndexName+'] on Field ['+FieldName+'/'+CFRE_DB_FIELDTYPE[FieldType]+'] is '+BoolToStr(DomainIndex,'a domainindex','not a domainindex')+' '+BoolToStr(Unique,'unique','not unique')+','+BoolToStr(AllowNulls,'allows nulls','does not allow nulls')
+', is '+BoolToStr(UniqueNull,'null unique','not null unique')+' and '+BoolToStr(IgnoreCase,'case insensitive','case Sensitive');
end;
function TFRE_DB_INDEX_DEF.IndexDescriptionShort: TFRE_DB_String;
begin
result := Format('%s@%s(%s/%s) D/U/UN/AN/CS(%s/%s,%s,%s,%s)',[IndexName,FieldName,CFRE_DB_FIELDTYPE[FieldType],IndexClass,BoolToStr(DomainIndex),BoolToStr(Unique,'1','0'),BoolToStr(UniqueNull,'1','0'),BoolToStr(AllowNulls,'1','0'),BoolToStr(IgnoreCase,'0','1')]);
end;
{ TFRE_DB_APPLICATION_CONFIG }
class procedure TFRE_DB_APPLICATION_CONFIG.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
end;
class procedure TFRE_DB_APPLICATION_CONFIG.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
{ TFRE_DB_WORKFLOW_BASE }
function TFRE_DB_WORKFLOW_BASE.getState: UInt32;
var
fld: IFRE_DB_FIELD;
begin
if FieldOnlyExisting('state',fld) then begin
Result:=fld.AsUInt32;
end else begin
Result:=0;
end;
end;
procedure TFRE_DB_WORKFLOW_BASE.setState(const conn: IFRE_DB_CONNECTION; const state: UInt32);
begin
if getState<>state then begin
Field('state').AsUInt32:=state;
CheckDbResult(conn.Update(self.CloneToNewObject()));
end;
end;
function TFRE_DB_WORKFLOW_BASE._hasFailedChild(const conn: IFRE_DB_CONNECTION): Boolean;
var
refs : TFRE_DB_GUIDArray;
child : TFRE_DB_WORKFLOW_STEP;
i : Integer;
begin
refs:=conn.GetReferences(UID,false,'TFRE_DB_WORKFLOW_STEP','step_parent');
Result:=false;
for i := 0 to High(refs) do begin
CheckDbResult(conn.FetchAs(refs[i],TFRE_DB_WORKFLOW_STEP,child));
if child.isErrorStep then begin
continue; //skip error steps
end;
if child.getState=5 then begin
Result:=true;
exit;
end;
end;
end;
procedure TFRE_DB_WORKFLOW_BASE.update(const conn: IFRE_DB_CONNECTION);
var
refs : TFRE_DB_GUIDArray;
lowestIdChilds : IFRE_DB_ObjectArray;
lowestId : UInt32;
i : Integer;
child : TFRE_DB_WORKFLOW_STEP;
hasFailedChild : Boolean;
begin
refs:=conn.GetReferences(UID,false,'TFRE_DB_WORKFLOW_STEP','step_parent');
SetLength(lowestIdChilds,0);
hasFailedChild:=false;
for i := 0 to High(refs) do begin
CheckDbResult(conn.FetchAs(refs[i],TFRE_DB_WORKFLOW_STEP,child));
if child.isErrorStep then begin
continue; //skip error steps
end;
if child.getState=4 then begin
continue; //skip done
end;
if child.getState=5 then begin
hasFailedChild:=true;
continue; //skip failed steps
end;
if (child.getState=2) or (child.getState=3) then begin
exit; //do nothing - at least one child is still in progress
end;
//state = 1 waiting
if Length(lowestIdChilds)=0 then begin
SetLength(lowestIdChilds,1);
lowestId:=child.stepId;
lowestIdChilds[0]:=child;
end else begin
if lowestId=child.stepId then begin
SetLength(lowestIdChilds,Length(lowestIdChilds)+1);
lowestIdChilds[Length(lowestIdChilds)-1]:=child;
end;
if lowestId>child.stepId then begin
SetLength(lowestIdChilds,1);
lowestIdChilds[0]:=child;
lowestId:=child.stepId;
end;
end;
end;
if Length(lowestIdChilds)=0 then begin //no children or all children done
if FieldExists('action') then begin
setState(conn,3); //IN PROGRESS
end else begin
setState(conn,4); //DONE (since there is no action defined)
end;
end else begin
if getState=1 then begin
setState(conn,2); //CHILD IN PROGRESS
end;
for i := 0 to High(lowestIdChilds) do begin
(lowestIdChilds[i].Implementor_HC as TFRE_DB_WORKFLOW_BASE).update(conn);
end;
end;
end;
{ TFRE_DB_WORKFLOW }
procedure TFRE_DB_WORKFLOW.setState(const conn: IFRE_DB_CONNECTION; const state: UInt32);
begin
if state=3 then begin
if _hasFailedChild(conn) then begin
inherited setState(conn,5);
end else begin
inherited setState(conn,4);
end;
end else begin
inherited setState(conn,state);
end;
end;
procedure TFRE_DB_WORKFLOW._init(const conn: IFRE_DB_CONNECTION);
procedure _initChilds(const objGuid: TFRE_DB_GUID);
var
refs : TFRE_DB_GUIDArray;
child: TFRE_DB_WORKFLOW_STEP;
i : Integer;
begin
refs:=conn.GetReferences(objGuid,false,'TFRE_DB_WORKFLOW_STEP','step_parent');
for i := 0 to High(refs) do begin
CheckDbResult(conn.FetchAs(refs[i],TFRE_DB_WORKFLOW_STEP,child));
child.setState(conn,1);
_initChilds(child.UID);
CheckDbResult(conn.Update(child));
end;
end;
begin
_initChilds(UID);
end;
class procedure TFRE_DB_WORKFLOW.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.AddSchemeField('caption',fdbft_String).required:=true; { caption of the workflow }
scheme.AddSchemeField('state',fdbft_UInt32).required:=true; { should be an enum : -> 1-> WAITING, 2-> CHILD IN PROGRESS, 3-> IN PROGRESS, 4-> DONE, 5 -> FAILED }
end;
class procedure TFRE_DB_WORKFLOW.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
procedure TFRE_DB_WORKFLOW.start(const conn: IFRE_DB_CONNECTION);
begin
setState(conn,1);
_init(conn);
update(conn);
end;
{ TFRE_DB_NOTIFICATION }
procedure TFRE_DB_NOTIFICATION.setMenuFunc(const menuFunc: TFRE_DB_NameType; const objGuid: TFRE_DB_GUID);
begin
Field('menuFunc').AsString:=menuFunc;
Field('menuObjGuid').AsGUID:=objGuid;
end;
function TFRE_DB_NOTIFICATION.getMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
dbo: IFRE_DB_Object;
begin
Result:=nil;
if conn.Fetch(Field('menuObjGuid').AsGUID,dbo)=edb_OK then begin
if dbo.MethodExists(Field('menuFunc').AsString) then begin
Result:=dbo.Invoke(Field('menuFunc').AsString,input,ses,app,conn);
end;
end;
end;
class procedure TFRE_DB_NOTIFICATION.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.AddSchemeField('caption',fdbft_String).required:=true;
scheme.AddSchemeField('details',fdbft_String);
scheme.AddSchemeField('for',fdbft_ObjLink).required:=true;
scheme.AddSchemeField('menuFunc',fdbft_String);
scheme.AddSchemeField('menuObjGuid',fdbft_GUID);
end;
class procedure TFRE_DB_NOTIFICATION.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
{ TFRE_DB_WORKFLOW_ACTION }
class procedure TFRE_DB_WORKFLOW_ACTION.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group: IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
scheme.AddSchemeField('key',fdbft_String).required:=true; { key of the workflow action }
scheme.AddSchemeField('action_desc',fdbft_String).required:=true; { description of the workflow action }
scheme.AddSchemeField('grpkey',fdbft_String).required:=true; { group key of the context of the workflow action (='PROVISIONING') hardcoded (to enable filtering of autosteps) }
scheme.AddSchemeField('is_auto',fdbft_Boolean); { marks automatic workflow steps }
scheme.AddSchemeField('action_uidpath',fdbft_GUID).multiValues:=true; { uidpath of the automatic action to be set }
scheme.AddSchemeField('action_method',fdbft_String); { Classname.Methodname of the WEB_Action to be called, the input of the action contains all objects pointing to the WF Object !}
scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.create('key','action_desc'),'%s-(%s)');
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main_group'));
group.AddInput('key',GetTranslateableTextKey('scheme_key'));
group.AddInput('action_desc',GetTranslateableTextKey('scheme_action_desc'));
group.AddInput('is_auto',GetTranslateableTextKey('scheme_is_auto'));
end;
class procedure TFRE_DB_WORKFLOW_ACTION.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_key','Key');
StoreTranslateableText(conn,'scheme_action_desc','Description');
StoreTranslateableText(conn,'scheme_is_auto','Automatic');
end;
end;
{ TFRE_DB_FILTER_BASE }
function TFRE_DB_FILTER_BASE.GetKeyName: TFRE_DB_NameType;
begin
result := FKey;
end;
constructor TFRE_DB_FILTER_BASE.Create(const key: TFRE_DB_NameType);
begin
FKey := key;
end;
function TFRE_DB_FILTER_BASE.IsARootNodeOnlyFilter: Boolean;
begin
result := FOnlyRootNodes;
end;
{ TFRE_DB_AUDIT_ENTRY }
class procedure TFRE_DB_AUDIT_ENTRY.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
scheme.AddSchemeField('user',fdbft_ObjLink).required:=true; { the user who set the action }
scheme.AddSchemeField('action_lang_key',fdbft_String); { the description of the action, LANGUAGE KEY ? - TRANSLATION}
scheme.AddSchemeField('action_ts',fdbft_DateTimeUTC); { timestamp of the action}
scheme.AddSchemeField('note',fdbft_String); { inline note / which may be filled in by the user}
end;
class procedure TFRE_DB_AUDIT_ENTRY.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
{ TFRE_DB_WORKFLOW_STEP }
function TFRE_DB_WORKFLOW_STEP.getAction: TFRE_DB_GUID;
begin
Result:=Field('action').AsObjectLink;
end;
function TFRE_DB_WORKFLOW_STEP.getIsErrorStep: Boolean;
begin
Result:=FieldExists('is_error_step') and Field('is_error_step').AsBoolean;
end;
function TFRE_DB_WORKFLOW_STEP.getStepId: UInt32;
begin
Result:=Field('step_id').AsUInt32;
end;
procedure TFRE_DB_WORKFLOW_STEP.setAction(AValue: TFRE_DB_GUID);
begin
Field('action').AsObjectLink:=AValue;
end;
procedure TFRE_DB_WORKFLOW_STEP.setIsErrorStep(AValue: Boolean);
begin
Field('is_error_step').AsBoolean:=AValue;
end;
procedure TFRE_DB_WORKFLOW_STEP.setStepId(AValue: UInt32);
begin
Field('step_id').AsUInt32:=AValue;
end;
class procedure TFRE_DB_WORKFLOW_STEP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
group: IFRE_DB_InputGroupSchemeDefinition;
begin
inherited RegisterSystemScheme(scheme);
{
workflows can be either in the workflow scheme collection (to define a scheme, or in the workflow collection where scheme levels are linked to parent steps which may or may not be copied from schemes
example one OE MODULE points to a level of = steps 1, 2, 2 ,2 ,3 , 4 ,4 , 5 , and one Error step in the Workflow Scheme Collection
when the the Orrder is Entered, then multiple products and modules are grouped under one ORDER WF Step (Parent)-> and one WF Step per Product (Childs)-> and all LEVEL STEPS From each OE MODULE (Childs)
in the WF Collection (not the wf scheme collection)
the workflow engine advances to the next step id in this level, when all parallel id's are done, and the time condition is satisfied
}
scheme.AddSchemeField('step_caption',fdbft_String).required:=true; { caption of the workflow step }
scheme.AddSchemeField('step_parent',fdbft_ObjLink); { parent of this step }
scheme.AddSchemeField('step_id',fdbft_UInt32).required:=true; { order/prio in this wf level, all steps with the same prio are done parallel, all step childs are done before this step }
scheme.AddSchemeField('step_details',fdbft_String); { details of the wf step instance }
scheme.AddSchemeField('is_error_step',fdbft_Boolean); { if set to true this is the ERROR catcher step of this level, it's triggered when a step fails }
scheme.AddSchemeField('error_idx',fdbft_String); { index for the error step }
scheme.AddSchemeField('state',fdbft_UInt32).required:=true; { should be an enum : -> 1-> WAITING, 2-> CHILD IN PROGRESS, 3-> IN PROGRESS, 4-> DONE, 5 -> FAILED }
scheme.AddSchemeField('designated_group',fdbft_ObjLink).required:=true;{ exor this group should do the step }
scheme.AddSchemeField('done_by_user',fdbft_ObjLink); { who has done the step }
scheme.AddSchemeField('auth_group',fdbft_ObjLink); { step needs auth by this group }
scheme.AddSchemeField('auth_by_user',fdbft_ObjLink); { if the action was required to be authorized, by whom it was authorized}
scheme.AddSchemeField('creation_ts',fdbft_DateTimeUTC); { timestamp of the creation of the action}
scheme.AddSchemeField('finalization_ts',fdbft_DateTimeUTC); { timestamp of the finalization }
scheme.AddSchemeField('allowed_time',fdbft_UInt32); { time in seconds when the action is considered to be failed, and advances to failed state automatically }
scheme.AddSchemeField('auth_ts',fdbft_DateTimeUTC); { timestamp of the auth action }
scheme.AddSchemeField('note',fdbft_String); { inline note / which may be filled in by the user}
scheme.AddSchemeField('sys_note',fdbft_String); { inline note / which may be filled in by the system (e.g. chosen IP adress, whatever) }
scheme.AddSchemeField('sys_progress',fdbft_String); { system progress string, filled in by a (feeder) or the system }
scheme.AddSchemeField('user_progress',fdbft_String); { progress text that is presented to the end user (webuser), which hides detail of the actual progress, may be the same text for several steps or changing percent values / translation key ? .}
scheme.AddSchemeField('action',fdbft_ObjLink); { action }
group:=scheme.AddInputGroup('main').Setup(GetTranslateableTextKey('scheme_main_group'));
group.AddInput('step_caption',GetTranslateableTextKey('scheme_step_caption'));
group.AddInput('step_id',GetTranslateableTextKey('scheme_step_id'));
group.AddInput('designated_group',GetTranslateableTextKey('scheme_designated_group'),false,false,'',cFOS_WF_GROUPS_DC,true,dh_chooser_combo,coll_GROUP,true);
group.AddInput('auth_group',GetTranslateableTextKey('scheme_auth_group'),false,false,'',cFOS_WF_GROUPS_DC,true,dh_chooser_combo,coll_GROUP);
group.AddInput('allowed_time',GetTranslateableTextKey('scheme_allowed_time'));
group.AddInput('action',GetTranslateableTextKey('scheme_action'),false,false,'','',false,dh_chooser_combo,coll_WFACTION,true);
group:=scheme.AddInputGroup('error_main').Setup(GetTranslateableTextKey('scheme_error_main_group'));
group.AddInput('step_caption',GetTranslateableTextKey('scheme_step_caption'));
group.AddInput('designated_group',GetTranslateableTextKey('scheme_designated_group'),false,false,'',cFOS_WF_GROUPS_DC,true,dh_chooser_combo,coll_GROUP,true);
group.AddInput('action',GetTranslateableTextKey('scheme_action'),false,false,'','',false,dh_chooser_combo,coll_WFACTION,true);
end;
class procedure TFRE_DB_WORKFLOW_STEP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
StoreTranslateableText(conn,'scheme_main_group','General Information');
StoreTranslateableText(conn,'scheme_step_caption','Caption');
StoreTranslateableText(conn,'scheme_step_id','Order');
StoreTranslateableText(conn,'scheme_designated_group','Assigned Group');
StoreTranslateableText(conn,'scheme_auth_group','Authorizing Group');
StoreTranslateableText(conn,'scheme_allowed_time','Allowed time (seconds)');
StoreTranslateableText(conn,'scheme_action','Action');
StoreTranslateableText(conn,'scheme_error_main_group','General Information');
StoreTranslateableText(conn,'cm_notification_done','Done');
end;
end;
function TFRE_DB_WORKFLOW_STEP.WEB_NotificationMenu(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
res: TFRE_DB_MENU_DESC;
sf : TFRE_DB_SERVER_FUNC_DESC;
begin
res:=TFRE_DB_MENU_DESC.create.Describe;
sf:=CWSF(@WEB_Done);
sf.AddParam.Describe('selected',input.Field('selected').AsString);
res.AddEntry.Describe(GetTranslateableTextShort(conn,'cm_notification_done'),'',sf);
Result:=res;
end;
function TFRE_DB_WORKFLOW_STEP.WEB_Done(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
CheckDbResult(conn.Delete(FREDB_H2G(input.Field('selected').AsString)));
setState(conn,4);
Result:=GFRE_DB_NIL_DESC;
end;
procedure TFRE_DB_WORKFLOW_STEP.setState(const conn: IFRE_DB_CONNECTION; const state: UInt32);
var
notiObj : TFRE_DB_NOTIFICATION;
wfParent : TFRE_DB_WORKFLOW_BASE;
begin
inherited setState(conn,state);
if state=3 then begin //in progress
//create notification object
notiObj:=TFRE_DB_NOTIFICATION.CreateForDB;
notiObj.Field('caption').AsString:=Field('step_caption').AsString;
notiObj.Field('details').AsString:=Field('step_details').AsString;
notiObj.setMenuFunc('NotificationMenu',Self.UID);
notiObj.Field('for').AsObjectLink:=Field('designated_group').AsObjectLink;
CheckDbResult(conn.AdmGetNotificationCollection.Store(notiObj));
end;
if state=4 then begin //done
CheckDbResult(conn.FetchAs(Field('step_parent').AsObjectLink,TFRE_DB_WORKFLOW_BASE,wfParent));
wfParent.update(conn);
end;
end;
{ TFRE_DB_UNCONFIGURED_MACHINE }
class procedure TFRE_DB_UNCONFIGURED_MACHINE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
//'provisioningmac' fixme setup field definition for this FIELD !!
end;
class procedure TFRE_DB_UNCONFIGURED_MACHINE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
{ TFRE_DB_UPDATE_FORM_DESC }
function TFRE_DB_UPDATE_FORM_DESC.DescribeDBO(const updateObj: IFRE_DB_Object): TFRE_DB_UPDATE_FORM_DESC;
begin
Field('obj').AsObject:=updateObj;
Result:=Self;
end;
function TFRE_DB_UPDATE_FORM_DESC.Describe(const formId: String; const updateObj: IFRE_DB_Object): TFRE_DB_UPDATE_FORM_DESC;
begin
Field('formId').AsString:=formId;
Field('obj').AsObject:=updateObj;
Result:=Self;
end;
function TFRE_DB_UPDATE_FORM_DESC.DescribeReset(const formId: String): TFRE_DB_UPDATE_FORM_DESC;
begin
Field('formId').AsString:=formId;
Result:=Self;
end;
{ TFRE_DB_WeakObjectEx }
constructor TFRE_DB_WeakObjectEx.Create(const weakclname: Shortstring);
begin
if cFRE_WEAK_CLASSES_ALLOWED then
FWeakClassname := weakclname
else
raise EFRE_DB_Exception.Create(edb_ERROR,'the creation of weak classes is forbidden, you have to register/include [%s] code',[weakclname]);
end;
function TFRE_DB_WeakObjectEx.CloneInstance: TFRE_DB_WeakObjectEx;
begin
result := TFRE_DB_WeakObjectEx.Create(FWeakClassname);
end;
function TFRE_DB_WeakObjectEx.SchemeClass: TFRE_DB_NameType;
begin
Result := FWeakClassname;
end;
{ TFRE_DB_OPEN_NEW_LOCATION_DESC }
function TFRE_DB_OPEN_NEW_LOCATION_DESC.Describe(const url: String; const inNewWindow: Boolean): TFRE_DB_OPEN_NEW_LOCATION_DESC;
begin
Field('url').AsString:=url;
Field('newWindow').AsBoolean:=inNewWindow;
Result:=Self;
end;
{ TFRE_DB_RemoteSessionAnswerEncapsulation }
constructor TFRE_DB_RemoteSessionAnswerEncapsulation.Create(const data: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const original_command_id: Qword; const opaquedata: IFRE_DB_Object; Contmethod: TFRE_DB_GenericCBMethod; const isRifcb: Boolean; const SesID: TFRE_DB_String);
begin
FData := data;
FStatus := status;
FOCid := original_command_id;
Fopaquedata := opaquedata;
FContmethod := Contmethod;
FIsRifCB := isRifcb;
FSesID := SesID;
end;
procedure TFRE_DB_RemoteSessionAnswerEncapsulation.DispatchAnswer(const ses : IFRE_DB_UserSession);
var rr : TFRE_DB_RIF_RESULT;
begin
try
try
if FIsRifCB then
begin
if not assigned(FData) then
begin
FData := TFRE_DB_RIF_RESULT.create;
end;
try
FData.AsClass(TFRE_DB_RIF_RESULT,rr);
rr.Transferstatus := FStatus;
TFRE_DB_RemoteCB_RIF(FContmethod)(ses,rr,FOCid,Fopaquedata);
except
on e:exception do
begin
FData := TFRE_DB_RIF_RESULT.create;
FData.AsClass(TFRE_DB_RIF_RESULT,rr);
rr.Transferstatus := cdcs_ERROR;
rr.ErrorCode := -2;
rr.ErrorText := 'Internal: '+ e.message;
TFRE_DB_RemoteCB_RIF(FContmethod)(ses,rr,FOCid,Fopaquedata);
end;
end;
end
else
begin
TFRE_DB_RemoteCB(FContmethod)(ses,FData,FStatus,FOCid,Fopaquedata);
end;
except
on e:exception do
begin
GFRE_DBI.LogError(dblc_SESSION,'DISPATCH REMOTE ANSWER FAILED %s',[e.Message]);
end;
end;
finally
if assigned(FData) then
FData.Finalize;
end;
end;
{ TFRE_DB_RemoteSessionInvokeEncapsulation }
constructor TFRE_DB_RemoteSessionInvokeEncapsulation.Create(const rclassname, rmethodname: TFRE_DB_NameType; const ocid: QWord; const SessionID: TFRE_DB_SESSION_ID; const input: IFRE_DB_Object; const SyncCallback: TFRE_DB_GenericCBMethod; const opaquedata: IFRE_DB_Object; const is_rif_cb: boolean);
begin
Fclassname := rclassname;
Fmethodname := rmethodname;
Finput := input;
FsessionID := SessionID;
FSyncCallback := SyncCallback;
Fopaquedata := opaquedata;
FOCid := ocid;
FIsRifCB := is_rif_cb;
end;
{ TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC }
function TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC.Describe(const progressBarId: String; const percentage: Real): TFRE_DB_UPDATE_MESSAGE_PROGRESS_DESC;
begin
Field('progressBarId').AsString:=progressBarId;
Field('percentage').AsReal32:=percentage;
Result:=Self;
end;
{ TFRE_DB_SUPPRESS_ANSWER_DESC }
constructor TFRE_DB_SUPPRESS_ANSWER_DESC.Create;
begin
inc(NILInstances);
if NILInstances>1 then begin
GFRE_BT.CriticalAbort('THIS IS A SINGLETON, ONLY CREATE ONCE!');
end;
Inherited Create;
end;
procedure TFRE_DB_SUPPRESS_ANSWER_DESC.Free;
begin
GFRE_BT.CriticalAbort('DONT DESTROY A FRE SINGLETON WITH STANDARD CALLS');
end;
destructor TFRE_DB_SUPPRESS_ANSWER_DESC.Destroy;
begin
GFRE_BT.CriticalAbort('DONT DESTROY A FRE SINGLETON WITH STANDARD CALLS');
end;
destructor TFRE_DB_SUPPRESS_ANSWER_DESC.DestroySingleton;
begin
if self=nil then
exit;
FImplementor._InternalSetMediator(nil);
FImplementor.Finalize;
FImplementor := Nil;
Inherited Destroy;
end;
procedure TFRE_DB_SUPPRESS_ANSWER_DESC.FreeFromBackingDBO;
begin
exit;
end;
{ TFRE_DB_NOTE }
class procedure TFRE_DB_NOTE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.Classname);
scheme.AddSchemeField('link',fdbft_String).required:=true;
scheme.AddSchemeField('notetyp',fdbft_String); { IF EMPTY this is a Fully User definable NOTE (no logical meaning) -> If set it may be used by the Application logic () }
scheme.AddSchemeField('note',fdbft_String);
end;
class procedure TFRE_DB_NOTE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
end;
end;
{ TFRE_DB_EDITOR_DATA_DESC }
function TFRE_DB_EDITOR_DATA_DESC.Describe(const value: String): TFRE_DB_EDITOR_DATA_DESC;
begin
Field('value').AsString:=value;
Result:=Self;
end;
{ TFRE_DB_Stream }
destructor TFRE_DB_Stream.Destroy;
begin
inherited Destroy;
end;
function TFRE_DB_Stream.AsRawByteString : TFRE_DB_RawByteString;
begin
if size>0 then
begin
SetLength(result,Size);
Move(Memory^,result[1],Size);
end
else
result := '';
end;
procedure TFRE_DB_Stream.SetFromRawByteString(const rb_string: TFRE_DB_RawByteString);
begin
Size := Length(rb_string);
if size>0 then
Move(rb_string[1],Memory^,Size);
end;
function TFRE_DB_Stream.CalcETag: ShortString;
begin
result := GFRE_BT.HashString_MD5_HEX(AsRawByteString);
end;
{ TFRE_DB_CLOSE_DIALOG_DESC }
function TFRE_DB_CLOSE_DIALOG_DESC.Describe: TFRE_DB_CLOSE_DIALOG_DESC;
begin
Result:=Self;
end;
{ TFRE_DB_MENU_DESC }
function TFRE_DB_MENU_DESC.Describe: TFRE_DB_MENU_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
function TFRE_DB_MENU_DESC.AddEntry: TFRE_DB_MENU_ENTRY_DESC;
begin
Result := TFRE_DB_MENU_ENTRY_DESC.Create;
Field('entries').AddObject(Result);
end;
function TFRE_DB_MENU_DESC.AddMenu: TFRE_DB_SUBMENU_DESC;
begin
Result := TFRE_DB_SUBMENU_DESC.Create;
Field('entries').AddObject(Result);
end;
{ TFRE_DB_SUBMENU_DESC }
function TFRE_DB_SUBMENU_DESC.Describe(const caption,icon: String; const disabled: Boolean; const id:String): TFRE_DB_SUBMENU_DESC;
begin
inherited Describe();
Field('caption').AsString:=caption;
if icon<>'' then begin
Field('icon').AsString:=FREDB_getThemedResource(icon);
end;
if id<>'' then begin
Field('id').AsString:=id;
end;
Field('disabled').AsBoolean:=disabled;
Result:=Self;
end;
{ TFRE_DB_RESTORE_UI_DESC }
function TFRE_DB_RESTORE_UI_DESC.Describe(const baseContainerId: String; const sectionIds: TFRE_DB_StringArray): TFRE_DB_RESTORE_UI_DESC;
begin
Field('baseContainerId').AsString:=baseContainerId;
Field('sectionIds').AsStringArr:=sectionIds;
Result:=Self;
end;
{ TFRE_DB_SITEMAP_ENTRY_DESC }
function TFRE_DB_SITEMAP_ENTRY_DESC.Describe(const caption, icon: String; const restoreUIFunc: TFRE_DB_RESTORE_UI_DESC; const x, y: Integer; const id:String; const newsCount:Integer; const disabled: Boolean; const scale:Single): TFRE_DB_SITEMAP_ENTRY_DESC;
begin
Field('caption').AsString:=caption;
if icon<>'' then begin
Field('icon').AsString:=FREDB_getThemedResource(icon);
end;
Field('sectionpath').AsObject := restoreUIFunc;
Field('x').AsInt32:=x;
Field('y').AsInt32:=y;
Field('id').AsString:=id;
Field('newscount').AsInt16:=newsCount;
Field('disabled').AsBoolean:=disabled;
Field('scale').AsReal32:=scale;
Result:=Self;
end;
function TFRE_DB_SITEMAP_ENTRY_DESC.AddEntry: TFRE_DB_SITEMAP_ENTRY_DESC;
begin
Result:=TFRE_DB_SITEMAP_ENTRY_DESC.create;
Field('entries').AddObject(Result);
end;
{ TFRE_DB_SVG_DEF_ELEM_ATTR_DESC }
function TFRE_DB_SVG_DEF_ELEM_ATTR_DESC.Describe(const name, value: String): TFRE_DB_SVG_DEF_ELEM_ATTR_DESC;
begin
Field('name').AsString:=name;
Field('value').AsString:=value;
Result:=Self;
end;
{ TFRE_DB_SVG_DEF_ELEM_DESC }
function TFRE_DB_SVG_DEF_ELEM_DESC.Describe(const tagName: String): TFRE_DB_SVG_DEF_ELEM_DESC;
begin
Field('tagname').AsString:=tagName;
Result:=Self;
end;
function TFRE_DB_SVG_DEF_ELEM_DESC.AddElement: TFRE_DB_SVG_DEF_ELEM_DESC;
begin
Result:=TFRE_DB_SVG_DEF_ELEM_DESC.create;
Field('elems').AddObject(Result);
end;
function TFRE_DB_SVG_DEF_ELEM_DESC.AddAttribute: TFRE_DB_SVG_DEF_ELEM_ATTR_DESC;
begin
Result:=TFRE_DB_SVG_DEF_ELEM_ATTR_DESC.create;
Field('attrs').AddObject(Result);
end;
{ TFRE_DB_SITEMAP_DESC }
function TFRE_DB_SITEMAP_DESC.Describe(const svgDefs: TFRE_DB_SVG_DEF_ELEM_DESC_ARRAY=nil): TFRE_DB_SITEMAP_DESC;
var
i: Integer;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
if Assigned(svgDefs) then begin
for i := 0 to Length(svgDefs) - 1 do begin
Field('svgDefs').AddObject(svgDefs[i]);
end;
end;
Result:=Self;
end;
function TFRE_DB_SITEMAP_DESC.AddEntry: TFRE_DB_SITEMAP_ENTRY_DESC;
begin
Result:=TFRE_DB_SITEMAP_ENTRY_DESC.create;
Field('entries').AddObject(Result);
end;
{ TFRE_DB_SECTION_DESC }
function TFRE_DB_SECTION_DESC._Describe(const title: String; const ord: Int16; const sectionId: String; const size: Integer): TFRE_DB_SECTION_DESC;
var s:string;
begin
Field('title').AsString:=title;
Field('ord').AsInt16:=ord;
if sectionId<>'' then begin
Field('id').AsString:=sectionId;
end else begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
end;
if (size=-1) then begin
Field('size').AsInt16:=1;
end else begin
Field('size').AsInt16:=size;
end;
(Parent.Parent.Implementor_HC as TFRE_DB_SUBSECTIONS_DESC).SectionDescribed(UID_String,ord,Field('size').AsInt16);
end;
function TFRE_DB_SECTION_DESC.Describe(const contentFunc: TFRE_DB_SERVER_FUNC_DESC; const title: String; const ord: Int16; const sectionId: String; const size:Integer): TFRE_DB_SECTION_DESC;
begin
_Describe(title,ord,sectionId,size);
Field('contentFunc').AsObject:=contentFunc;
Result:=Self;
end;
function TFRE_DB_SECTION_DESC._internalDescribe(const content: TFRE_DB_CONTENT_DESC; const title: String; const ord: Int16; const sectionId: String; const size: Integer): TFRE_DB_SECTION_DESC;
begin
_Describe(title,ord,sectionId,size);
Field('content').AsObject:=content;
Result:=Self;
end;
procedure TFRE_DB_SECTION_DESC.SetActive(const active: Boolean);
begin
(Parent.Parent.Implementor_HC as TFRE_DB_SUBSECTIONS_DESC).SetActiveSectionUID(UID_String);
end;
procedure TFRE_DB_SECTION_DESC.SetMenu(const menu: TFRE_DB_MENU_DESC);
begin
Field('menu').AsObject:=menu;
end;
{ TFRE_DB_SUBSECTIONS_DESC }
procedure TFRE_DB_SUBSECTIONS_DESC.SetActiveSectionUID(const sectionUID: String);
begin
Field('activeSection').AsString:=sectionUID;
fnoActiveSectionSet:=false;
end;
procedure TFRE_DB_SUBSECTIONS_DESC.SectionDescribed(const sectionUID: String; const ord,size: Integer);
begin
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+size;
if fnoActiveSectionSet then begin
if not FieldExists('activeSection') or (ord<factiveSectionOrd) then begin
Field('activeSection').AsString:=sectionUID;
factiveSectionOrd:=ord;
end;
end;
end;
constructor TFRE_DB_SUBSECTIONS_DESC.Create;
begin
fnoActiveSectionSet:=true;
inherited Create;
end;
function TFRE_DB_SUBSECTIONS_DESC.Describe(const displayType: TFRE_DB_SUBSEC_DISPLAY_TYPE): TFRE_DB_SUBSECTIONS_DESC;
begin
Field('dt').AsString:=CFRE_DB_SUBSEC_DISPLAY_TYPE[displayType];
Field('sizeSum').AsInt16:=0;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
procedure TFRE_DB_SUBSECTIONS_DESC.OnUIChange(const serverFunc: TFRE_DB_SERVER_FUNC_DESC);
begin
Field('onUIChange').AsObject:=serverFunc;
end;
function TFRE_DB_SUBSECTIONS_DESC.AddSection(): TFRE_DB_SECTION_DESC;
begin
Result := TFRE_DB_SECTION_DESC.create;
Field('sections').AddObject(Result);
end;
procedure TFRE_DB_SUBSECTIONS_DESC.SetActiveSection(const sectionId: String);
var
i: Integer;
begin
for i:=0 to Field('sections').ValueCount - 1 do begin
if Field('sections').AsObjectItem[i].Field('id').AsString=sectionId then begin
SetActiveSectionUID(Field('sections').AsObjectItem[i].UID_String);
break;
end;
end;
end;
{ TFRE_DB_MENU_ENTRY_DESC }
function TFRE_DB_MENU_ENTRY_DESC._Describe(const caption, icon: String; const disabled: Boolean; const descr: String): TFRE_DB_MENU_ENTRY_DESC;
begin
Field('caption').AsString:=caption;
if icon<>'' then begin
Field('icon').AsString:=FREDB_getThemedResource(icon);
end;
Field('disabled').AsBoolean:=disabled;
Field('descr').AsString:=descr;
end;
function TFRE_DB_MENU_ENTRY_DESC.Describe(const caption, icon: String; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const disabled: Boolean; const id: String; const descr: String): TFRE_DB_MENU_ENTRY_DESC;
begin
_Describe(caption,icon,disabled,descr);
if Assigned(serverFunc) then begin
Field('serverFunc').AsObject:=serverFunc;
end;
if id<>'' then begin
Field('id').AsString:=id;
end;
Result:=Self;
end;
function TFRE_DB_MENU_ENTRY_DESC.DescribeDownload(const caption, icon: String; const downloadId: String; const disabled: Boolean; const descr: String): TFRE_DB_MENU_ENTRY_DESC;
begin
_Describe(caption,icon,disabled,descr);
Field('downloadId').AsString:=downloadId;
Result:=Self;
end;
{ TFRE_DB_MESSAGE_DESC }
function TFRE_DB_MESSAGE_DESC.Describe(const caption, msg: String; const msgType: TFRE_DB_MESSAGE_TYPE; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const progressBarId: String): TFRE_DB_MESSAGE_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('caption').AsString:=caption;
Field('msg').AsString:=msg;
Field('msgType').AsString:=CFRE_DB_MESSAGE_TYPE[msgType];
if Assigned(serverFunc) then begin
Field('serverFunc').AsObject:=serverFunc;
end;
Field('progressBarId').AsString:=progressBarId;
Result:=Self;
end;
{ TFRE_DB_REFRESH_STORE_DESC }
function TFRE_DB_REFRESH_STORE_DESC.Describe(const storeId: String): TFRE_DB_REFRESH_STORE_DESC;
begin
Field('storeId').AsString:=storeId;
Result:=Self;
end;
constructor TFRE_DB_NIL_DESC.Create;
begin
inc(NILInstances);
if NILInstances>1 then begin
GFRE_BT.CriticalAbort('THIS IS A SINGLETON, ONLY CREATE ONCE!');
end;
Inherited Create;
end;
procedure TFRE_DB_NIL_DESC.Free;
begin
GFRE_BT.CriticalAbort('DONT DESTROY A FRE SINGLETON WITH STANDARD CALLS');
end;
destructor TFRE_DB_NIL_DESC.Destroy;
begin
GFRE_BT.CriticalAbort('DONT DESTROY A FRE SINGLETON WITH STANDARD CALLS');
end;
destructor TFRE_DB_NIL_DESC.DestroySingleton;
begin
if self=nil then
exit;
FImplementor._InternalSetMediator(nil);
FImplementor.Finalize;
FImplementor := Nil;
inherited Destroy;
end;
procedure TFRE_DB_NIL_DESC.FreeFromBackingDBO;
begin
exit;
end;
procedure TFRE_DB_UserSession.LockSession;
begin
FSessionLock.Acquire;
end;
procedure TFRE_DB_UserSession.UnlockSession;
begin
FSessionLock.Release;
end;
class procedure TFRE_DB_UserSession.HandleContinuationTimeouts(const onfetch : TFRE_DB_OnFetchSessionByID);
var i : NativeInt;
now : TFRE_DB_DateTime64;
answerencap : TFRE_DB_RemoteSessionAnswerEncapsulation;
ses : TFRE_DB_UserSession;
begin
now := GFRE_BT.Get_DBTimeNow;
FContinuationLock.Acquire;
try
for i := 0 to high(FContinuationArray) do
if (FContinuationArray[i].CID<>0)
and (now > FContinuationArray[i].ExpiredAt) then
begin
answerencap := TFRE_DB_RemoteSessionAnswerEncapsulation.Create(nil,cdcs_TIMEOUT,FContinuationArray[i].ORIG_CID,FContinuationArray[i].opData,FContinuationArray[i].Contmethod,FContinuationArray[i].IsRif,FContinuationArray[i].SesID);
FContinuationArray[i].CID:=0; // mark slot free
FContinuationArray[i].Contmethod:=nil;
FContinuationArray[i].ExpiredAt:=0;
if onfetch(answerencap.FSesID,ses) then
begin
try
if ses.DispatchCoroutine(@ses.AnswerRemReqCoRoutine,answerencap) then
else
begin
writeln('TIMEOUT: (A) Session for answer is gone');
answerencap.free;
end;
finally
ses.UnlockSession;
end;
end
else
begin
writeln('TIMEOUT: (B) Session for answer is gone');
answerencap.free;
end;
end;
finally
FContinuationLock.Release;
end;
end;
procedure TFRE_DB_UserSession.SetOnWorkCommands(AValue: TNotifyEvent);
begin
FOnWorkCommands:=AValue;
end;
procedure TFRE_DB_UserSession._FixupDCName(var dcname: TFRE_DB_NameType);
begin
dcname := uppercase(dcname);
end;
constructor TFRE_DB_UserSession.Create(const cg: IFRE_APSC_CHANNEL_GROUP; const user_name, password: TFRE_DB_String; const default_app: TFRE_DB_String; const default_uid_path: TFRE_DB_GUIDArray; conn: IFRE_DB_CONNECTION; const interactive_session: boolean);
begin
GFRE_TF.Get_Lock(FSessionLock);
FUserName := user_name;
FDefaultApp := default_app;
FDBConnection := conn;
FDefaultUID := default_uid_path;
FSessionID := GFRE_DBI.Get_A_Guid_HEX;
FSessionTerminationTO := GCFG_SESSION_UNBOUND_TO;
FTimers := TList.Create;
FBinaryInputs := GFRE_DBI.NewObject;
FUpdateableDBOS := GFRE_DBI.NewObject;
FServerFuncDBOS := GFRE_DBI.NewObject;
FGlobalEventCallbacks := GFRE_DBI.NewObject;
FDifferentialUpdates := GFRE_DBI.NewObject;
FUpdateableContent := GFRE_DBI.NewObject;
FModuleInitialized := TFPHashList.Create;
FIsInteractive := interactive_session;
FSessionCG := cg;
_FetchAppsFromDB;
_InitApps;
if not assigned(FContinuationLock) then
GFRE_TF.Get_Lock(TFRE_DB_UserSession.FContinuationLock);
if not assigned(FGlobalDebugLock) then
GFRE_TF.Get_Lock(TFRE_DB_UserSession.FGlobalDebugLock);
GFRE_DBI.LogInfo(dblc_SESSION,'SESSION CREATE User:'+user_name+' App:'+default_app+' '+FSessionID);
end;
procedure TFRE_DB_UserSession.StoreSessionData;
var res : TFRE_DB_Errortype;
sd : IFRE_DB_Object;
begin
if not FPromoted then
begin
writeln('YOU COULD NOT STORE SESSION DATA FOR A UNPROMOTED (GUEST) SESSION');
exit;
end;
if assigned(FSessionData) then begin
GFRE_DBI.LogDebug(dblc_SESSION,'STORING SESSIONDATA FOR ['+FUserName+'] : '+FSessionID);
sd := FSessionData.CloneToNewObject;
res := GetDBConnection.StoreUserSessionData(sd);
if res=edb_OK then begin
GFRE_DBI.LogInfo(dblc_SESSION,'STORING SESSIONDATA FOR ['+FUserName+'] DONE ');
end else begin
GFRE_DBI.LogInfo(dblc_SESSION,'STORING SESSIONDATA FOR ['+FUserName+'] FAILED --> '+CFRE_DB_Errortype[res]);
end;
end;
end;
destructor TFRE_DB_UserSession.Destroy;
begin
RemoveAllTimers;
if FPromoted then
StoreSessionData;
try
FinishDerivedCollections;
except on e:exception do
writeln('***>> ERROR : FAILED TO FINISH DERIVED COLLECTIONS : '+e.Message);
end;
FDBConnection.ClearUserSessionBinding;
FDBConnection.Finalize;
FTimers.Free;
FBinaryInputs.Finalize;
FUpdateableContent.Finalize;
FDifferentialUpdates.Finalize;
FUpdateableDBOS.Finalize;
FServerFuncDBOS.Finalize;
FGlobalEventCallbacks.Finalize;
FModuleInitialized.Free;
FSessionLock.Finalize;
if assigned(FSessionData) then
FSessionData.Finalize;
FSessionData:=nil;
GFRE_DBI.LogInfo(dblc_SESSION,'FINALIZED USERSESSION [%s] USER [%s]',[FSessionID,FUserName]);
inherited Destroy;
end;
function TFRE_DB_UserSession.SearchSessionApp(const app_key: TFRE_DB_String; out app: TFRE_DB_APPLICATION; out idx: integer): boolean;
var i: Integer;
begin
app:=nil;
idx := -1;
for i:=0 to high(FAppArray) do begin
if not assigned(FAppArray[i]) then continue; // Skip empty Slots
if uppercase(FAppArray[i].AppClassname)=uppercase(app_key) then begin
idx := i;
app := FAppArray[i].Implementor_HC as TFRE_DB_APPLICATION;
exit(true);
end;
end;
result := false;
end;
procedure TFRE_DB_UserSession.InboundNotificationBlock(const block: IFRE_DB_Object);
begin
if IsInteractiveSession then
DispatchCoroutine(@self.COR_InboundNotifyBlock,block.Implementor_HC)
else
block.Finalize; { silently drop Notification handling for non interactive (currently feeder) sessions }
end;
procedure TFRE_DB_UserSession.COR_InboundNotifyBlock(const data: Pointer);
var block : IFRE_DB_Object;
begin
block := GFRE_DBI.AnonObject2Interface(data);
FREDB_ApplyNotificationBlockToNotifIF_Session(block,self);
end;
function TFRE_DB_UserSession.SearchSessionDC(dc_name: TFRE_DB_String; out dc: IFRE_DB_DERIVED_COLLECTION): boolean;
var i: Integer;
begin
dc:=nil;
for i:=0 to high(FDC_Array) do begin
if FDC_Array[i].CollectionName=dc_name then begin
dc := FDC_Array[i];
exit(true);
end;
end;
result := false;
end;
procedure TFRE_DB_UserSession._FetchAppsFromDB;
begin
FDBConnection.FetchApplications(FAppArray,FLoginApp,FIsInteractive);
end;
procedure TFRE_DB_UserSession._InitApps;
var i:integer;
begin
for i := 0 to High(FAppArray) do begin
if FcurrentApp='' then begin
SetCurrentApp(FAppArray[i].AppClassName);
end;
(FAppArray[i].Implementor_HC as TFRE_DB_APPLICATION).SessionInitialize(self);
end;
end;
procedure TFRE_DB_UserSession._ReinitializeApps;
var i:NativeInt;
begin
for i:=0 to high(FAppArray) do begin
(FAppArray[i].Implementor_HC as TFRE_DB_APPLICATION).SessionPromotion(self);
end;
end;
procedure TFRE_DB_UserSession.AddSyncContinuationEntry(const request_id, original_req_id: Qword; const for_session_id: String; const callback: TFRE_DB_GenericCBMethod; const is_rif: boolean; const expire_in: NativeUint; const opaquedata: IFRE_DB_Object);
var i : integer;
send_ok : boolean;
begin
send_ok := false;
FContinuationLock.Acquire;
for i := 0 to high(FContinuationArray) do begin
if FContinuationArray[i].CID=0 then begin
FContinuationArray[i].CID := request_id;
FContinuationArray[i].ORIG_CID := original_req_id;
FContinuationArray[i].Contmethod := callback;
FContinuationArray[i].IsRif := is_rif;
FContinuationArray[i].ExpiredAt := GFRE_BT.Get_DBTimeNow+expire_in;
FContinuationArray[i].SesID := for_session_id;
FContinuationArray[i].OpData := opaquedata;
//FContinuationArray[i].;
send_ok := true;
break;
end;
end;
FContinuationLock.Release;
if not send_ok then
raise EFRE_DB_Exception.Create(edb_ERROR,'SESSION/TOO MUCH PENDING S-C Commands !');
end;
procedure TFRE_DB_UserSession.INT_TimerCallBack(const timer: IFRE_APSC_TIMER; const flag1, flag2: boolean);
var wm:IFRE_DB_WebTimerMethod;
begin
wm := IFRE_DB_WebTimerMethod(timer.cs_GetMethod);
wm(self);
end;
procedure TFRE_DB_UserSession.RemoveAllTimers;
var
i: NativeInt;
begin
for i:=FTimers.Count-1 downto 0 do
IFRE_APSC_TIMER(FTimers[i]).cs_Finalize;
FTimers.Clear;
end;
function TFRE_DB_UserSession.HasFeature(const feature_name: TFRE_DB_NameType): Boolean;
begin
result := FDBConnection.GetFeatureStatus(feature_name);
end;
function TFRE_DB_UserSession.GetSystemMAC: TFOS_MAC_ADDR;
begin
result.SetFromString(cFRE_MACHINE_MAC);
end;
function TFRE_DB_UserSession.IsSystemManaged: Boolean;
begin
result := false; // FIXXME
end;
function TFRE_DB_UserSession.IsConfigurationMode: Boolean;
begin
result := cFRE_CONFIG_MODE;
end;
procedure TFRE_DB_UserSession.DoGlobalEvent(const ev_name: TFRE_DB_NameType; const ev_data: IFRE_DB_Object);
var m : TMethod;
fld : IFRE_DB_Field;
en : string;
begin
if FGlobalEventCallbacks.FieldOnlyExisting(ev_name+'_C',fld) then
begin
m.Code := CodePointer(fld.AsUInt64);
m.data := Pointer(FGlobalEventCallbacks.Field(ev_name+'_D').AsUInt64);
en := ev_data.Field('E').AsString;
GFRE_DBI.LogNotice(dblc_SESSION,'>SESSION [%s] DELIVER GLOBAL EVENT [%s]',[GetSessionID,ev_name,en]);
IFRE_DB_SessionDataCallback(m)(self,ev_data);
GFRE_DBI.LogNotice(dblc_SESSION,'<SESSION [%s] LEFT GLOBAL EVENT [%s]',[GetSessionID,ev_name,en]);
end;
end;
function TFRE_DB_UserSession.FetchStreamDBO_OTCU(const uid: TFRE_DB_GUID; var end_field: TFRE_DB_NameTypeRL; var lcontent: TFRE_DB_RawByteString; var content_type: TFRE_DB_String; var etag: TFRE_DB_String): Boolean;
var dbo: IFRE_DB_Object;
fld: IFRE_DB_Field;
begin
result := FDBConnection.Fetch(uid,dbo)=edb_OK;
if result then
begin
try
end_field := GFRE_BT.HexStr2Str(end_field);
if not dbo.FieldOnlyExisting(end_field,fld) then
exit(false);
if not (fld.FieldType=fdbft_Stream) then
exit(false);
lcontent := fld.AsStream.AsRawByteString;
if dbo.FieldOnlyExisting(end_field+cFRE_DB_STKEY,fld) then
content_type := fld.AsString
else
content_type := '';
if dbo.FieldOnlyExisting(end_field+cFRE_DB_ST_ETAG,fld) then
etag := fld.AsString
else
etag := '';
finally
dbo.Finalize;
end;
end;
end;
class destructor TFRE_DB_UserSession.destroyit;
begin
if assigned(FContinuationLock) then
FContinuationLock.Finalize;
end;
class constructor TFRE_DB_UserSession.createit;
begin
FMyReqID := 100000;
end;
procedure TFRE_DB_UserSession.SetSessionState(const sstate: TFRE_DB_SESSIONSTATE);
begin
FBindState := sstate;
end;
function TFRE_DB_UserSession.GetSessionState: TFRE_DB_SESSIONSTATE;
begin
result := FBindState;
end;
function TFRE_DB_UserSession.GetCurrentRequestID: QWord;
begin
result := FCurrentReqID;
end;
function TFRE_DB_UserSession.CheckUnboundSessionForPurge: boolean;
begin
result := false;
if FBoundSession_RA_SC=nil then
begin
dec(FSessionTerminationTO);
result := FSessionTerminationTO<1;
if ((FSessionTerminationTO) mod 60)=0 then
begin
GFRE_DBI.LogInfo(dblc_SESSION,'SESSION ['+fsessionid+'/'+FConnDesc+'/'+FUserName+'] KO in '+inttostr(FSessionTerminationTO));
end;
end;
end;
function TFRE_DB_UserSession.SearchSessionAppUID(const app_uid: TFRE_DB_GUID; out app: IFRE_DB_Object): boolean;
var i: Integer;
begin
for i:=0 to high(FAppArray) do begin
if not assigned(FAppArray[i]) then continue; // Skip empty Slots
if FREDB_Guids_Same(FAppArray[i].UID,app_uid) then begin
app := FAppArray[i].AsObject;
exit(true);
end;
end;
result := false;
end;
function TFRE_DB_UserSession.SearchSessionDCUID(const dc_uid: TFRE_DB_GUID; out dc: IFRE_DB_DERIVED_COLLECTION): boolean;
var i: Integer;
begin
for i:=0 to high(FDC_Array) do begin
if FREDB_Guids_Same(FDC_Array[i].UID,dc_uid) then begin
dc := FDC_Array[i];
exit(true);
end;
end;
result := false;
end;
procedure TFRE_DB_UserSession.RemSessionAppAndFinialize(const app_key: TFRE_DB_String);
var app : TFRE_DB_APPLICATION;
idx : integer;
begin
if not SearchSessionApp(app_key,app,idx) then raise EFRE_DB_Exception.Create(edb_ERROR,'want to remove/finalize a nonexisting app');
FAppArray[idx] := nil;
app.SessionFinalize(self);
end;
procedure TFRE_DB_UserSession.RemoveAllAppsAndFinalize;
var i : Integer;
applist : Array of String;
begin
setlength(applist,length(FAppArray));
for i:=0 to high(FAppArray) do begin
applist[i] := FAppArray[i].AppClassName;
end;
for i:=0 to high(applist) do begin
RemSessionAppAndFinialize(applist[i]);
end;
setlength(FAppArray,0);
end;
procedure TFRE_DB_UserSession.SetCurrentApp(const app_key: TFRE_DB_String);
begin
FcurrentApp:=app_key;
end;
procedure TFRE_DB_UserSession.Input_FRE_DB_Command(const cmd: IFRE_DB_COMMAND);
var x : TObject;
class_name : TFRE_DB_String;
method_name : TFRE_DB_String;
bdk : TFRE_DB_String;
request_id : int64;
request_typ : TFRE_DB_COMMANDTYPE;
input : IFRE_DB_Object;
uidp : TFRE_DB_GUIDArray;
session : TFRE_DB_String;
session_app : TFRE_DB_APPLICATION;
dummy_idx : integer;
st,et : QWord;
procedure _SendSyncServerClientAnswer;
begin
cmd.CommandType := fct_SyncReply;
cmd.Answer := true;
cmd.ClientCommand := false;
GFRE_DBI.LogDebug(dblc_SESSION,' SA:> %s',[cmd.Data.SchemeClass]);
SendServerClientCMD(cmd);
end;
procedure _SendSyncServerClienterror(const emessage:string); //TODO - Think about client Error Handling
begin
CMD.CommandType := fct_Error;
CMD.Answer := true;
CMD.ClientCommand := false;
CMD.ErrorText := 'INVOKE OF ['+class_name+'.'+method_name+'] FAILED '+#13#10+'['+emessage+']';
GFRE_DBI.LogError(dblc_SESSION,' SERROR:> %s',[cmd.ErrorText]);
SendServerClientCMD(cmd);
end;
procedure InvokeMethod(const async:boolean ; var input: IFRE_DB_Object);
var output : IFRE_DB_Object;
begin
try
output := nil;
if method_name='ONUICHANGE' then begin
output:=nil;
end;
FCurrentReqID := request_id;
output := FDBConnection.InvokeMethod(class_name,method_name,uidp,input,self);
FcurrentReqID := 0;
if output=nil then begin
raise EFRE_DB_Exception.Create('function '+class_name+'.'+method_name+' delivered nil result');
end;
CMD.Data := output;
if not(output.Implementor_HC is TFRE_DB_SUPPRESS_ANSWER_DESC)
and (not async) then
_SendSyncServerClientAnswer
else
CMD.Finalize;
except on e:exception do begin
et := GFRE_BT.Get_Ticks_ms;
GFRE_DBI.LogError(dblc_SERVER,'>>(%4.4d ms)<<DISPATCH METHOD %s(%s).%s RID = [%d] TYPE[%s] FAILED[%s]',[et-st,class_name,GFRE_DBI.GuidArray2SString(uidp),method_name,request_id,CFRE_DB_COMMANDTYPE[request_typ],e.Message]);
CMD.CheckoutData.Finalize;
input := nil;
if not async then
_SendSyncServerClientError(e.Message);
end;end;
end;
//procedure InvokeEvent(event :TFRE_DB_EVENT_METHOD_ENC);
//begin
// try
// event.params.SetReference(self);
// try
// event.method(event.params);
// finally
// event.params.Finalize;
// event.Free;
// end;
// finally
// end;
//end;
procedure _RegisterRemoteRequestSet(const requests: IFRE_DB_Object);
var cnt,i : NativeInt;
arr : TFRE_DB_RemoteReqSpecArray;
begin
cnt := requests.Field('mc').AsInt16;
SetLength(arr,cnt);
for i := 0 to cnt - 1 do begin
arr[i].classname := requests.Field('cl'+inttostr(i)).AsString;
arr[i].methodname := requests.Field('mn'+inttostr(i)).AsString;
arr[i].invokationright := requests.Field('ir'+inttostr(i)).AsString;
end;
RegisterRemoteRequestSet(arr);
end;
procedure DispatchSyncRemoteAnswer(const is_error : boolean);
var i : integer;
answer_matched : boolean;
match_id : integer;
now : TFRE_DB_DateTime64;
CID : Qword;
ses : TFRE_DB_UserSession;
opaq : IFRE_DB_Object;
answerencap : TFRE_DB_RemoteSessionAnswerEncapsulation;
begin
now := GFRE_BT.Get_DBTimeNow;
answer_matched := false;
answerencap := nil;
FContinuationLock.Acquire;
try
for i:=0 to high(FContinuationArray) do begin
cid := cmd.CommandID;
if cid = FContinuationArray[i].CID then begin
if is_error then
begin
input.Field('ERROR').AsString := CMD.ErrorText;
answerencap := TFRE_DB_RemoteSessionAnswerEncapsulation.Create(input,cdcs_ERROR,FContinuationArray[i].ORIG_CID,FContinuationArray[i].opData,FContinuationArray[i].Contmethod,FContinuationArray[i].IsRif,FContinuationArray[i].SesID);
end
else
answerencap := TFRE_DB_RemoteSessionAnswerEncapsulation.Create(input,cdcs_OK,FContinuationArray[i].ORIG_CID,FContinuationArray[i].opData,FContinuationArray[i].Contmethod,FContinuationArray[i].IsRif,FContinuationArray[i].SesID);
if now <= FContinuationArray[i].ExpiredAt then
begin
answer_matched := true;
FContinuationArray[i].CID:=0; // mark slot free
FContinuationArray[i].Contmethod:=nil;
FContinuationArray[i].ExpiredAt:=0;
end;
break;
end;
end;
finally
FContinuationLock.Release;
end;
if answer_matched then begin
if FSessionID = answerencap.FSesID then
begin
abort; // Check this path
answerencap.DispatchAnswer(self);
end
else
begin
if GFRE_DBI.NetServ.FetchSessionByIdLocked(answerencap.FSesID,ses) then
begin
try
input := nil ; // ! dont finalize here
if ses.DispatchCoroutine(@ses.AnswerRemReqCoRoutine,answerencap) then
else
begin
writeln('Session for answer is gone');
answerencap.free;
end;
finally
ses.UnlockSession;
end;
end
else
begin
GFRE_LOG.Log('CANNOT FETCH SESSION FOR SYNC ANSWER / CID=%d OR TIMEOUT',[CMD.CommandID],catError);
answerencap.free;
end;
end;
end else begin
GFRE_LOG.Log('GOT ANSWER FOR UNKNOWN/TIMEDOUT COMMAND CID=%d OR TIMEOUT',[CMD.CommandID],catError);
GFRE_LOG.Log('CMD: %s',[CMD.AsDBODump],catError);
answerencap.free;
end;
CMD.Finalize;
end;
procedure _ProcessInit;
begin
if not FPromoted and (cG_OVERRIDE_USER<>'') and (cG_OVERRIDE_PASS<>'') then
begin // AutoLogin
GFRE_DBI.LogInfo(dblc_SERVER,'>> SPECIFIC INVOKE FIRMOS.INIT AUTOLOGIN SID[%s] USER[%s]',[FSessionID,cG_OVERRIDE_USER]);
input.Field('data').AsObject.Field('uname').AsString := cG_OVERRIDE_USER;
input.Field('data').AsObject.Field('pass').AsString := cG_OVERRIDE_PASS;
class_name := FDefaultApp;
uidp := FDefaultUID;
method_name := 'doLogin';
CMD.ChangeSession := FSessionID;
InvokeMethod(false,input);
end
else
begin
GFRE_DBI.LogInfo(dblc_SERVER,'>> SPECIFIC INVOKE FIRMOS.INIT SID[%s]',[FSessionID]);
class_name := FDefaultApp;
uidp := FDefaultUID;
method_name := 'Content';
input.Field('CLEANUP').AsBoolean := TRUE;
CMD.ChangeSession := FSessionID;
InvokeMethod(false,input);
end;
end;
procedure _ProcessLogout;
begin
Logout;
class_name := FDefaultApp;
uidp := FDefaultUID;
method_name := 'Content';
CMD.ChangeSession := 'LOGGEDOUT';
InvokeMethod(false,input);
end;
procedure _ProcessDestroy;
var i : NativeInt;
begin
for i := 0 to input.Field('ids').ValueCount - 1 do begin
unregisterUpdatableContent(input.Field('ids').AsStringItem[i]);
UnregisterDBOChangeCB(input.Field('ids').AsStringItem[i]);
end;
CMD.Data := GFRE_DB_NIL_DESC;
_SendSyncServerClientAnswer;
end;
procedure _ProcessBinaryBulkTransferStart;
begin
CMD.Data := GFRE_DB_NIL_DESC;
_SendSyncServerClientAnswer;
end;
procedure _ProcessBinaryBulkTransferEnd;
begin
CMD.Data := GFRE_DB_NIL_DESC;
_SendSyncServerClientAnswer;
end;
procedure _ProcessBinaryBulkTransfer;
{Upload Chunks of Data for later reference by key, }
var bd : IFRE_DB_Object;
sz : NativeInt;
cs : NativeInt;
name : string;
typ : string;
fld : string;
fidx : NativeInt;
fcnt : NativeInt;
cidx : NativeInt;
data : IFRE_DB_Object;
{
DATA (OBJECT) :
{ [0]
NAME (STRING) : [ 'SuperSchramml.png' ]
SIZE (STRING) : [ '776241' ]
TYPE (STRING) : [ 'image/png' ]
FIELD (STRING) : [ 'picture' ]
CHUNKIDX (STRING) : [ '0' ]
FIELDIDX (STRING) : [ '0' ]
CHUNKSIZE (STRING) : [ '776241' ]
}
BINCHUNK (STREAM)
}
begin
if FBinaryInputs.FieldExists(bdk) then
raise EFRE_DB_Exception.Create(edb_ERROR,'chunking, array etc. not implemented');
data := input.Field('data').AsObject;
name := data.Field('name').AsString;
typ := data.Field('type').AsString;
fld := data.Field('field').AsString;
sz := StrTointDef(data.Field('size').AsString,-1);
fcnt := StrToIntDef(data.Field('FIELDCOUNT').AsString,-1);
fidx := StrTointDef(data.Field('FIELDIDX').AsString,-1);
cidx := StrTointDef(data.Field('CHUNKIDX').AsString,-1);
cs := StrToIntDef(data.Field('chunksize').AsString,-1);
if (cs=-1)
or (sz=1) then
raise EFRE_DB_Exception.Create(edb_ERROR,'size [%s] or chunksize not parseable [%s]',[input.Field('size').AsString,input.Field('chunksize').AsString]);
if cs<>sz then
raise EFRE_DB_Exception.Create(edb_ERROR,'size [%d] <> chunksize [%d], chunking not implemented',[sz,cs]);
if (fidx<>0) or
(cidx<>0) then
raise EFRE_DB_Exception.Create(edb_ERROR,'fieldindex must be 0, cidx must be 0',[]);
bd := FBinaryInputs.Field(bdk).AsObject;
bd.Field('n').AsString := name;
bd.Field('f').AsString := fld;
bd.Field('size').AsInt32 := sz; { overall size of binary data}
bd.Field('typ').AsString := typ;
bd.Field('fc').AsInt32 := fcnt;
bd.Field('fi').AsInt32 := fidx;
bd.Field('bin').AsStream := input.Field('binchunk').AsStream;
input.Field('binchunk').Clear(true);
CMD.Data := GFRE_DB_NIL_DESC;
_SendSyncServerClientAnswer;
end;
procedure _TryBinaryBulkReplacement;
var bd : IFRE_DB_Object;
fld : IFRE_DB_Field;
fn : TFRE_DB_NameType;
begin
if FBinaryInputs.FieldOnlyExisting(bdk,fld) then
begin
bd := fld.AsObject;
fn := bd.Field('f').AsString;
input.Field('data').AsObject.Field(fn).Clear;
input.Field('data').AsObject.Field(fn+cFRE_DB_STKEY).Clear;
input.Field('data').AsObject.Field(fn+cFRE_DB_ST_ETAG).Clear;
input.Field('data').AsObject.Field(fn).AsStream:=bd.Field('bin').AsStream;
input.Field('data').AsObject.Field(fn+cFRE_DB_STKEY).AsString:=bd.Field('typ').AsString;
input.Field('data').AsObject.Field(fn+cFRE_DB_ST_ETAG).AsString := input.Field('data').AsObject.Field(fn).AsStream.CalcETag;
bd.Field('bin').Clear(true);
FBinaryInputs.Field(bdk).Clear;
end
else
begin
raise EFRE_DB_Exception.Create(edb_ERROR,'binary key replacement failed, not found bdk='+bdk);
end;
end;
procedure _ProcessUnregisterDBO;
var i : NativeInt;
begin
for i := 0 to input.Field('ids').ValueCount - 1 do begin
unregisterUpdatableDBO(FREDB_H2G(input.Field('ids').AsStringItem[i]));
end;
CMD.Data := GFRE_DB_NIL_DESC;
_SendSyncServerClientAnswer;
end;
procedure _UpdateLiveStats(const input:IFRE_DB_Object);
var coo : IFRE_DB_Object;
procedure CheckoutUpdate(const fielname : TFRE_DB_NameType ; const obj : IFRE_DB_Object);
var g : TFRE_DB_GUID;
no : IFRE_DB_Object;
begin
try
g.SetFromHexString(fielname);
no := obj.CloneToNewObject;
no.Field('statuid').AsGUID:=g;
G_LiveStats.Field(fielname).AsObject := no;
except
end;
end;
begin
G_LiveStatLock.Acquire;
try
input.ForAllObjectsFieldName(@CheckoutUpdate);
finally
G_LiveStatLock.Release;
end;
end;
begin
//FGlobalDebugLock.Acquire;
//try
with cmd do
begin
class_name := InvokeClass;
method_name := InvokeMethod;
request_id := CommandID;
request_typ := CommandType;
uidp := UidPath;
bdk := BinaryDataKey;
input := CMD.CheckoutData; // Think about Finalization
if (bdk<>'') and
(method_name<>'BINARYBULKTRANSFER') and
(method_name<>'BINARYBULKTRANSFERSTART') and
(method_name<>'BINARYBULKTRANSFEREND') then
_TryBinaryBulkReplacement;
end;
st := GFRE_BT.Get_Ticks_ms;
GFRE_DBI.LogInfo(dblc_SESSION,'>>[%s/%s]-(%d/%s) %s[%s].%s ',[FSessionID,FUserName,request_id,CFRE_DB_COMMANDTYPE[request_typ],class_name,GFRE_DBI.GuidArray2SString(uidp),method_name]);
case request_typ of
fct_SyncRequest: begin
try
if (class_name='FIRMOS') then begin
if (method_name='INIT') then
_ProcessInit
else
if (method_name='LOGOUT') then
_ProcessLogout
else
if (method_name='DESTROY') then
_ProcessDestroy
else
if (method_name='BINARYBULKTRANSFERSTART') then
_ProcessBinaryBulkTransferStart
else
if (method_name='BINARYBULKTRANSFER') then
_ProcessBinaryBulkTransfer
else
if (method_name='BINARYBULKTRANSFEREND') then
_ProcessBinaryBulkTransferEnd
else
if (method_name='UNREGISTERDBO') then begin
_ProcessUnregisterDBO;
end else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'UNKNOWN FIRMOS SPECIFIC COMMAND '+method_name);
end;
end else begin
InvokeMethod(false,input);
end;
except on e:Exception do begin
cmd.CommandType := fct_Error;
cmd.Answer := true;
cmd.ClientCommand := false;
cmd.ErrorText := e.Message;
GFRE_DBI.LogInfo(dblc_SESSION,'<< ERROR (%s) [%s/%s]-(%d/%s) %s[%s].%s [%d ms]',[e.Message,FSessionID,FUserName,request_id,CFRE_DB_COMMANDTYPE[request_typ],class_name,GFRE_DBI.GuidArray2SString(uidp),method_name,et-st]);
end;end;
end;
fct_AsyncRequest: begin
if (class_name='FIRMOS') then
begin
if (method_name='REG_REM_METH') then
begin
GFRE_DBI.LogInfo(dblc_SERVER,'>> SPECIFIC INVOKE FIRMOS.REG_REM_METH SID[%s]',[FSessionID]);
_RegisterRemoteRequestSet(input);
CMD.Finalize;
end
else
if (method_name='UPDATELIVE') then
begin
_UpdateLiveStats(input);
end
else
begin
writeln('UNHANDLED ASYNC REQUEST ?? ',class_name,'.',method_name);
CMD.Finalize;
end;
end
else
begin
InvokeMethod(true,input);
end;
end;
fct_SyncReply: DispatchSyncRemoteAnswer(false);
fct_Error: DispatchSyncRemoteAnswer(true);
end;
if assigned(input) then
input.Finalize ;
et := GFRE_BT.Get_Ticks_ms;
GFRE_DBI.LogInfo(dblc_SESSION,'<<[%s/%s]-(%d/%s) %s[%s].%s [%d ms]',[FSessionID,FUserName,request_id,CFRE_DB_COMMANDTYPE[request_typ],class_name,GFRE_DBI.GuidArray2SString(uidp),method_name,et-st]);
//finally
// FGlobalDebugLock.Release;
//end;
end;
class procedure TFRE_DB_UserSession.CLS_ForceInvalidSessionReload(rac: IFRE_DB_COMMAND_REQUEST_ANSWER_SC; const cmd: IFRE_DB_COMMAND);
var input : IFRE_DB_Object;
begin
input := cmd.CheckoutData;
try
input.Finalize;
except
end;
// Send an async Reload in every Case
cmd.CommandType := fct_AsyncRequest;
cmd.Answer := false;
cmd.ClientCommand := false;
cmd.ChangeSession := 'NEW';
cmd.Data := TFRE_DB_OPEN_NEW_LOCATION_DESC.create.Describe('/',false);
GFRE_DBI.LogNotice(dblc_SESSION,'>FORCE INVALID SESSION RELOAD');
rac.Send_ServerClient(cmd);
end;
function TFRE_DB_UserSession.InternalSessInvokeMethod(const class_name, method_name: string; const uid_path: TFRE_DB_GUIDArray; var input: IFRE_DB_Object): IFRE_DB_Object;
var st,et : QWord;
SYNCWait : IFOS_E;
syncres : TObject;
begin
st := GFRE_BT.Get_Ticks_ms;
GFRE_DBI.LogDebug(dblc_SERVER,'>>SESSION/INTERNAL/DISPATCH METHOD %s.%s(%s) SID=[%s]',[class_name,method_name,GFRE_DBI.GuidArray2SString(uid_path),FSessionID]);
if assigned(input) then begin
GFRE_DBI.LogDebug(dblc_SERVER_DATA,'INPUT:');
GFRE_DBI.LogDebug(dblc_SERVER_DATA,'%s',[input.DumpToString(2)]);
end;
try
SYNCWait := SetupSyncWaitDataEvent;
try
result := FDBConnection.InvokeMethod(class_name,method_name,uid_path,input,self);
except on e:exception do begin
writeln('>INTERNAL INVOKE FAILED ',class_name,' ',method_name,' : ',e.Message);
FinalizeSyncWaitEvent;
raise;
end end;
if result.Implementor_HC is TFRE_DB_SUPPRESS_ANSWER_DESC then
begin
SYNCWait.WaitFor;
syncres := TObject(SYNCWait.GetData);
if syncres is TFRE_DB_QUERY_BASE then
begin
result := ProcessQryToDescription(syncres as TFRE_DB_QUERY_BASE);
end;
FinalizeSyncWaitEvent;
end
else
begin
FinalizeSyncWaitEvent;
end;
if assigned(result) then begin
GFRE_DBI.LogDebug(dblc_SERVER,'OUTPUT:');
GFRE_DBI.LogDebug(dblc_SERVER,'%s',[result.DumpToString(2)]);
end;
except on e:exception do begin
GFRE_DBI.LogError(dblc_SERVER_DATA,'INTERNAL DISPATCH METHOD %s.%s(%s) FAILED[%s] SID=[%s]',[class_name,method_name,GFRE_DBI.GuidArray2SString(uid_path),e.Message,FSessionID]);
raise;
end;end;
//GFRE_DBI.LogDebug(dblc_SERVER,'<<SESSION/INTERNAL/DISPATCH METHOD %s.%s(%s) SID=[%s]',[class_name,method_name,GFRE_DBI.GuidArray2SString(uid_path),FSessionID]);
et := GFRE_BT.Get_Ticks_ms;
GFRE_DBI.LogDebug(dblc_SERVER,'>>(%4.4d ms)<<SESSION/INTERNAL/DISPATCH METHOD %s.%s(%s) SID=[%s]',[et-st,class_name,method_name,GFRE_DBI.GuidArray2SString(uid_path),FSessionID]);
end;
function TFRE_DB_UserSession.SetupSyncWaitDataEvent: IFOS_E;
begin
if assigned(FSyncWaitE) then
raise EFRE_DB_Exception.Create(edb_ERROR,'double syncwait try - failure');
GFRE_TF.Get_Event(FSyncWaitE);
Result:=FSyncWaitE;
end;
function TFRE_DB_UserSession.GetSyncWaitEvent(out e: IFOS_E): boolean;
begin
if assigned(FSyncWaitE) then
begin
e := FSyncWaitE;
result := true;
end
else
begin
e := nil;
result := false;
end;
end;
procedure TFRE_DB_UserSession.FinalizeSyncWaitEvent;
begin
FSyncWaitE.Finalize;
FSyncWaitE := nil;
end;
function TFRE_DB_UserSession.InternalSessInvokeMethod(const app: IFRE_DB_APPLICATION; const method_name: string; const input: IFRE_DB_Object): IFRE_DB_Object;
var inp : IFRE_DB_Object;
begin
if not assigned(input) then
begin
inp := GFRE_DBI.NewObject;
try
result := app.AsObject.Invoke(method_name,inp,self,app,GetDBConnection);
finally
inp.Finalize;
end;
end
else
begin
result := app.AsObject.Invoke(method_name,input,self,app,GetDBConnection);
end;
end;
type
TCOR_TakeOverData=class
New_RA_SC : IFRE_DB_COMMAND_REQUEST_ANSWER_SC;
FClientDescription : String;
end;
function TFRE_DB_UserSession.Promote(const user_name, password: TFRE_DB_String; var promotion_status: TFRE_DB_String; force_new_session_data: boolean; const session_takeover: boolean; const auto_promote: boolean ; const allowed_user_classes: array of TFRE_DB_String): TFRE_DB_PromoteResult;
var err : TFRE_DB_Errortype;
l_NDBC : IFRE_DB_CONNECTION;
lStoredSessionData : IFRE_DB_Object;
promres : TFRE_DB_PromoteResult;
existing_session : TFRE_DB_UserSession;
app : TFRE_DB_APPLICATION;
function ConvertAllowedUserArray : TFRE_DB_StringArray;
var i:NativeInt;
begin
SetLength(result,length(allowed_user_classes));
for i:=0 to high(allowed_user_classes) do
result[i] := uppercase(allowed_user_classes[i]);
end;
function TakeOver : TFRE_DB_PromoteResult;
var tod : TCOR_TakeOverData;
begin
GFRE_DBI.LogInfo(dblc_SERVER,'>TAKEOVERSESSION SESSION [%s] USER [%s]',[FSessionID,FUserName]);
if GFRE_DBI.NetServ.ExistsUserSessionForKeyLocked(FConnDesc,existing_session) then
begin
try
assert(existing_session<>self);
tod := TCOR_TakeOverData.Create;
tod.New_RA_SC := FBoundSession_RA_SC;
tod.FClientDescription := FConnDesc;
if not existing_session.DispatchCoroutine(@existing_session.COR_InitiateTakeOver,tod) then
begin {cOld session binding dead (dangling unbound session, do in this thread/socket context) }
existing_session.COR_InitiateTakeOver(tod);
end;
result:=pr_Takeover;
ClearServerClientInterface; { clear my (guest) bound session RAC };
finally
try
GFRE_DBI.LogInfo(dblc_SERVER,'<OK : TAKEOVERSESSION FOR SESSION [%s] USER [%s]',[existing_session.FSessionID,existing_session.FUserName]);
except
end;
existing_session.UnlockSession;
end;
exit;
end
else
begin
promotion_status := 'login_failed_oldnotfound_cap';
result := pr_Failed;
GFRE_DBI.LogWarning(dblc_SERVER,'<FAIL : TAKEOVERSESSION FOR SESSION [%s]',[FSessionID]);
exit;
end;
end;
begin
if session_takeover then
begin
promres := TakeOver;
exit(promres);
end;
GFRE_DBI.NetServ.ExistsUserSessionForUserLocked(user_name,existing_session);
if assigned(existing_session) then begin
try
err := GFRE_DBI.NetServ.CheckUserNamePW(user_name,password,ConvertAllowedUserArray);
case err.Code of
edb_OK : begin
if assigned(existing_session.FBoundSession_RA_SC) then
begin
promotion_status := FREDB_EncodeTranslatableWithParams('login_failed_already_1P',[existing_session.GetClientDetails]); //'You are already logged in on '+existing_session.GetClientDetails+', would you like to takeover this existing session ?'//;
existing_session.FTakeoverPrepared := FConnDesc;
exit(pr_TakeoverPrepared);
if auto_promote then
begin
existing_session.AutoPromote(FBoundSession_RA_SC,FConnDesc);
FBoundSession_RA_SC := nil; { clear my (guest) bound sesison RAC };
exit(pr_TakeOver);
end;
end
else
begin
existing_session.FTakeoverPrepared := FConnDesc; { prepare for auto takeover, after lock release}
end;
end
else begin
promotion_status := 'login_takeover_failed';
result := pr_Failed;
exit;
end;
end;
finally
existing_session.UnlockSession;
end;
promres := TakeOver; { Auto Takeover dead web session }
exit(promres);
end else begin
err := GFRE_DBI.NetServ.GetImpersonatedDatabaseConnection(FDBConnection.GetDatabaseName,user_name,password,l_NDBC,ConvertAllowedUserArray);
case err.Code of
edb_OK: begin
FDBConnection.ClearUserSessionBinding;
FDBConnection.Finalize;
FDBConnection:=l_NDBC;
FDBConnection.BindUserSession(self);
GFRE_DBI.LogInfo(dblc_SERVER,'PROMOTED SESSION [%s] USER [%s] TO [%s]',[FSessionID,FUserName,user_name]);
if not force_new_session_data then begin
if not l_NDBC.FetchUserSessionData(lStoredSessionData) then begin
FSessionData := GFRE_DBI.NewObject;
GFRE_DBI.LogDebug(dblc_SERVER,'USING EMPTY/DEFAULT SESSION DATA [%s]',[FSessionData.UID_String]);
end else begin
GFRE_DBI.LogDebug(dblc_SERVER,'USING PERSISTENT SESSION DATA [%s]',[lStoredSessionData.UID_String]);
FSessionData:=lStoredSessionData;
end;
end else begin
FSessionData := GFRE_DBI.NewObject;
GFRE_DBI.LogDebug(dblc_SERVER,'FORCED USING EMPTY/DEFAULT SESSION DATA [%s]',[FSessionData.UID_String]);
end;
FUserName := user_name;
//FUserdomain := l_NDBC.SYS.GetCurrentUserTokenClone.User.DomainID;
//FUserdomain := l_NDBC.SYS.GetCurrentUserTokenRef.GetMyDomainID;
FPromoted := true;
result := pr_OK;
_FetchAppsFromDB;
try
(FLoginApp.Implementor_HC as TFRE_DB_APPLICATION).SessionInitialize(self);
_InitApps;
except
GFRE_DBI.LogEmergency(dblc_SERVER,'LOGIN APPLICATION INITIALIZATION FAILED [%s]',[FSessionData.UID_String]);
end;
try
_ReinitializeApps;
except
GFRE_DBI.LogEmergency(dblc_SERVER,'LOGIN APPLICATION INITIALIZATION FAILED [%s]',[FSessionData.UID_String]);
end;
end;
else begin
FPromoted := false;
promotion_status := 'login_failed_access';
result := pr_Failed;
end;
end;
end;
end;
procedure TFRE_DB_UserSession.COR_InitiateTakeOver(const data: Pointer);
var tod : TCOR_TakeOverData;
procedure InitiateTakeover(const NEW_RASC: IFRE_DB_COMMAND_REQUEST_ANSWER_SC ; const connection_desc: string);
var
MSG : TFRE_DB_MESSAGE_DESC;
APP : TFRE_DB_APPLICATION;
sId : TFRE_DB_SESSION_ID;
idx : integer;
take_over_content : TFRE_DB_CONTENT_DESC;
begin
if not FIsInteractive then begin
if assigned(FBoundSession_RA_SC) then begin //TODO - Handle interactive Session
FBoundSession_RA_SC.DeactivateSessionBinding;
end;
FBoundSession_RA_SC := NEW_RASC;
NEW_RASC.UpdateSessionBinding(self);
end else begin
if Assigned(FBoundSession_RA_SC) then
begin
MSG := TFRE_DB_MESSAGE_DESC.create.Describe('SESSION TAKEOVER','This session will be continued on another browser instance.',fdbmt_wait,nil);
sId := FSessionID;
SendServerClientRequest(msg,'NEW');
FBoundSession_RA_SC.DeactivateSessionBinding;
end;
FConnDesc := connection_desc;
NEW_RASC.UpdateSessionBinding(self);
FBoundSession_RA_SC := NEW_RASC;
if not DispatchCoroutine(@self.COR_FinalizeTakeOver,nil) then // continue in TM of new socket binding
COR_FinalizeTakeOver(nil);
end;
end;
begin
tod := TCOR_TakeOverData(data);
try
InitiateTakeover(tod.New_RA_SC,tod.FClientDescription);
finally
tod.free;
end;
end;
procedure TFRE_DB_UserSession.COR_FinalizeTakeOver(const data: Pointer);
begin
FDBConnection.SYS.RefreshUserRights;
//_FetchAppsFromDB;
try
//(FLoginApp.Implementor_HC as TFRE_DB_APPLICATION).SessionInitialize(self);
_InitApps;
except
GFRE_DBI.LogEmergency(dblc_SERVER,'LOGIN APPLICATION INITIALIZATION FAILED [%s]',[FSessionData.UID_String]);
end;
try
_ReinitializeApps;
except
GFRE_DBI.LogEmergency(dblc_SERVER,'LOGIN APPLICATION INITIALIZATION FAILED [%s]',[FSessionData.UID_String]);
end;
SendServerClientRequest(GFRE_DB_NIL_DESC,FSessionID);
SendServerClientRequest(TFRE_DB_OPEN_NEW_LOCATION_DESC.create.Describe('/',false)); // OR BETTER SEND THE FULL CONTENT ...
end;
procedure TFRE_DB_UserSession.AutoPromote(const NEW_RASC: IFRE_DB_COMMAND_REQUEST_ANSWER_SC; const conn_desc: String);
begin
if not FIsInteractive then
begin
if assigned(FBoundSession_RA_SC) then begin
FBoundSession_RA_SC.DeactivateSessionBinding;
end;
FBoundSession_RA_SC := NEW_RASC;
NEW_RASC.UpdateSessionBinding(self);
end
else
begin
abort;
end;
end;
procedure TFRE_DB_UserSession.Logout;
begin
//SendServerClientRequest(TFRE_DB_MESSAGE_DESC.create.Describe('Logged out.','You have been logged out',fdbmt_wait),'NEW');
StoreSessionData;
SendServerClientRequest(GFRE_DB_NIL_DESC,'NEW');
SendServerClientRequest(TFRE_DB_OPEN_NEW_LOCATION_DESC.create.Describe('/',false));
FBoundSession_RA_SC.DeactivateSessionBinding;
FBoundSession_RA_SC := nil;
FTakeoverPrepared:='';
FConnDesc:='LOGGEDOUT';
FSessionTerminationTO := 1;
SendServerClientRequest(TFRE_DB_OPEN_NEW_LOCATION_DESC.create.Describe('/',false));
end;
function TFRE_DB_UserSession.LoggedIn: Boolean;
begin
result := FPromoted;
end;
function TFRE_DB_UserSession.QuerySessionDestroy: Boolean;
begin
result := true;
GFRE_DBI.LogDebug(dblc_SERVER,'QUERY DISCONNECTING SESSION [%s] DESTROY=%s',[FSessionID,BoolToStr(result,'1','0')]);
end;
function TFRE_DB_UserSession.GetSessionID: TFRE_DB_SESSION_ID;
begin
result := FSessionID;
end;
function TFRE_DB_UserSession.GetSessionAppData(const app_key: TFRE_DB_String): IFRE_DB_Object;
begin
assert(assigned(FSessionData));
result := GetSessionGlobalData.Field('APP_DATA_'+app_key).AsObject;
end;
function TFRE_DB_UserSession.GetSessionModuleData(const mod_key: TFRE_DB_String): IFRE_DB_Object;
begin
result := GetSessionGlobalData.Field('MOD_DATA_'+mod_key).AsObject;
end;
function TFRE_DB_UserSession.GetSessionGlobalData: IFRE_DB_Object;
begin
result := FSessionData.Field('G_').AsObject;
end;
function TFRE_DB_UserSession.NewDerivedCollection(dcname: TFRE_DB_NameType): IFRE_DB_DERIVED_COLLECTION;
begin
_FixupDCName(dcname);
if not SearchSessionDC(dcname,result) then begin
result := GetDBConnection.CreateDerivedCollection(dcname);
result.BindSession(self);
if dcname<>Result.CollectionName then
raise EFRE_DB_Exception.Create(edb_ERROR,'PARANOIA '+dcname+' <> '+result.CollectionName);
SetLength(FDC_Array,Length(FDC_Array)+1);
FDC_Array[high(FDC_Array)] := result;
end else begin
raise EFRE_DB_Exception.create(edb_ERROR,'THE SESSION [%s] ALREADY HAS A DERIVED COLLECTION NAMED [%s]',[FSessionID,dcname]);
end;
end;
function TFRE_DB_UserSession.HasDerivedCollection(dcname: TFRE_DB_NameType): Boolean;
var
dc: IFRE_DB_DERIVED_COLLECTION;
begin
Result:=SearchSessionDC(dcname,dc);
end;
function TFRE_DB_UserSession.FetchDerivedCollection(dcname: TFRE_DB_NameType): IFRE_DB_DERIVED_COLLECTION;
begin
_FixupDCName(dcname);
if not SearchSessionDC(dcname,result) then
raise EFRE_DB_Exception.create(edb_ERROR,'THE SESSION [%s] HAS NO DERIVED COLLECTION NAMED [%s]',[FSessionID,dcname]);
end;
procedure TFRE_DB_UserSession.FinishDerivedCollections;
var i : integer;
//cn : string;
begin
for i:=0 to high(FDC_Array) do begin
try
//cn := FDC_Array[i].CollectionName;
FDC_Array[i].Finalize;
//GetDBConnection.DeleteCollection(cn);
except on e:EXception do begin
writeln('*** --- DC Clean failed -> ',e.Message);
end;end;
end;
SetLength(FDC_Array,0);
end;
function TFRE_DB_UserSession.GetUsername: String;
begin
result := FUserName;
end;
function TFRE_DB_UserSession.GetClientDetails: String;
begin
result := FConnDesc;
end;
procedure TFRE_DB_UserSession.SetClientDetails(const net_conn_desc: String);
begin
FConnDesc := net_conn_desc;
end;
function TFRE_DB_UserSession.GetTakeOverKey: String;
begin
result := FTakeoverPrepared;
end;
function TFRE_DB_UserSession.GetSessionAppArray: IFRE_DB_APPLICATION_ARRAY;
var i:integer;
begin
SetLength(result,length(FAppArray));
for i:=0 to high(FAppArray) do begin
result[i] := FAppArray[i];
end;
end;
function TFRE_DB_UserSession.GetModuleInitialized(const modulename: ShortString): Boolean;
begin
result := NativeInt(FModuleInitialized.Find(modulename))=1;
end;
function TFRE_DB_UserSession.SetModuleInitialized(const modulename: ShortString): Boolean;
begin
if GetModuleInitialized(modulename) then
raise EFRE_DB_Exception.Create(edb_ERROR,'double initialization tagging of '+modulename);
FModuleInitialized.Add(modulename,Pointer(1));
end;
function TFRE_DB_UserSession.FetchOrInitFeederMachines(const configmachinedata : IFRE_DB_Object): TFRE_DB_GUID;
var i : Integer;
apps : IFRE_DB_APPLICATION_ARRAY;
dummy : IFRE_DB_APPLICATION;
begin
if not FPromoted then
raise EFRE_DB_Exception.Create(edb_ERROR,'you not allowed the machineobjects [%s]',[FDBConnection.GetDatabaseName]);
GetDBConnection.FetchApplications(apps,dummy,IsInteractiveSession);
for i := 0 to High(apps) do
if apps[i].IsConfigurationApp then
begin
if apps[i].FetchOrInitFeederMachine(self,configmachinedata,FBoundMachineUid,FBoundMachineName,FBoundMachineMac) then
begin
result := FBoundMachineUid;
exit;
end;
end;
raise EFRE_DB_Exception.Create(edb_ERROR,'you not suceeded the configurations, machineobjects [%s]',[FDBConnection.GetDatabaseName]);
end;
function TFRE_DB_UserSession.GetMachineUidByName(const mname: TFRE_DB_String; out machuid: TFRE_DB_GUID): boolean;
var mcoll : IFRE_DB_COLLECTION;
begin
mcoll := FDBConnection.GetMachinesCollection;
result := false;
if mcoll.GetIndexedUIDText(mname,machuid)=1 then
result := true;
end;
function TFRE_DB_UserSession.GetMachineUidByMac(const mac: TFOS_MAC_ADDR; out machuid: TFRE_DB_GUID): boolean;
var mcoll : IFRE_DB_COLLECTION;
begin
mcoll := FDBConnection.GetMachinesCollection;
result := false;
if mcoll.GetIndexedUIDText(Mac.GetAsString,machuid,false,'pmac')=1 then
result := true;
end;
procedure TFRE_DB_UserSession.SetServerClientInterface(const sc_interface: IFRE_DB_COMMAND_REQUEST_ANSWER_SC);
begin
if assigned(FBoundSession_RA_SC) then
raise EFRE_DB_Exception.Create(edb_INTERNAL,' REUSE SESSION FAILED, ALREADY BOUND INTERFACE FOUND');
FBoundSession_RA_SC := sc_interface;
GFRE_DBI.LogNotice(dblc_SESSION,'SET SESSION INTERFACE (RESUE) -> SESSION ['+fsessionid+'/'+FConnDesc+'/'+FUserName+']');
GFRE_DB_TCDM.cs_DropAllQueryRanges(GetSessionID,true);
end;
procedure TFRE_DB_UserSession.ClearServerClientInterface;
begin
GFRE_DB_TCDM.cs_DropAllQueryRanges(GetSessionID,true);
RemoveAllTimers;
if FPromoted then
FSessionTerminationTO := GCFG_SESSION_UNBOUND_TO
else
FSessionTerminationTO := 1; // Free unpromoted Sessions Quick
FBoundSession_RA_SC := nil;
GFRE_DBI.LogNotice(dblc_SESSION,'CLEARED SESSION INTERFACE -> SESSION '+BoolToStr(FPromoted,'PROMOTED','GUEST') +' ['+fsessionid+'/'+FConnDesc+'/'+FUserName+'] KO in '+inttostr(FSessionTerminationTO));
end;
function TFRE_DB_UserSession.GetClientServerInterface(out sc: IFRE_DB_COMMAND_REQUEST_ANSWER_SC): boolean;
begin
sc := FBoundSession_RA_SC;
result := assigned(FBoundSession_RA_SC);
end;
procedure TFRE_DB_UserSession.ClearUpdatable;
begin
FUpdateableContent.ClearAllFields;
FUpdateableDBOS.ClearAllFields;
FServerFuncDBOS.ClearAllFields;
end;
procedure TFRE_DB_UserSession.RegisterUpdatableContent(const contentId: String);
var
fld: IFRE_DB_FIELD;
begin
if FUpdateableContent.FieldOnlyExisting(contentId,fld) then begin
fld.AsInt16:=fld.AsInt16+1; //in case of a self update it will be registered twice before the client sends destroy of the old one
end else begin
FUpdateableContent.Field(contentId).AsInt16:=1;
end;
end;
procedure TFRE_DB_UserSession.UnregisterUpdatableContent(const contentId: String);
var
fld: IFRE_DB_FIELD;
begin
if FUpdateableContent.FieldOnlyExisting(contentId,fld) then begin
if fld.AsInt16=1 then begin
FUpdateableContent.DeleteField(contentId);
end else begin
fld.AsInt16:=fld.AsInt16-1;
end;
end;
end;
procedure TFRE_DB_UserSession.RegisterUpdatableDBO(const UID_id: TFRE_DB_GUID);
var id:ShortString;
begin
id := FREDB_G2H(UID_id);
if FUpdateableDBOS.FieldExists(id) then begin
FUpdateableDBOS.Field(id).AsInt64:=FUpdateableDBOS.Field(id).AsInt64+1;
end else begin
FUpdateableDBOS.Field(id).AsInt64:=1;
end;
end;
procedure TFRE_DB_UserSession.UnregisterUpdatableDBO(const UID_id: TFRE_DB_GUID);
var id : ShortString;
begin
id := FREDB_G2H(UID_id);
if FUpdateableDBOS.Field(id).AsInt64=1 then begin
FUpdateableDBOS.Field(id).Clear();
end else begin
FUpdateableDBOS.Field(id).AsInt64:=FUpdateableDBOS.Field(id).AsInt64-1;
end;
end;
function TFRE_DB_UserSession.IsDBOUpdatable(const UID_id: TFRE_DB_GUID): boolean;
var id : ShortString;
begin
id := FREDB_G2H(UID_id);
result := FUpdateableDBOS.FieldExists(id);
end;
procedure TFRE_DB_UserSession.RegisterDBOChangeCB(const UID_id: TFRE_DB_GUID; const callback: TFRE_DB_SERVER_FUNC_DESC; const cbGroupId: TFRE_DB_String);
var id:ShortString;
begin
id := FREDB_G2H(UID_id);
if callback.hasParam then
raise EFRE_DB_Exception.Create(edb_ERROR,'no params allowed here');
FServerFuncDBOS.Field(id).AsObject.Field(cbGroupId).AsObject:=callback;
end;
procedure TFRE_DB_UserSession.UnregisterDBOChangeCB(const cbGroupId: TFRE_DB_String);
procedure _checkDBO(const field: IFRE_DB_Field);
begin
if field.AsObject.FieldExists(cbGroupId) then begin
field.AsObject.DeleteField(cbGroupId);
end;
end;
begin
FServerFuncDBOS.ForAllFields(@_checkDBO,true); //FIXXME Heli - cleanup if last callback is removed
end;
function TFRE_DB_UserSession.getDBOChangeCBs(const UID_id: TFRE_DB_GUID): IFRE_DB_Object;
var id : ShortString;
begin
id := FREDB_G2H(UID_id);
result := FServerFuncDBOS.FieldOnlyExistingObj(id);
end;
function TFRE_DB_UserSession.IsUpdatableContentVisible(const contentId: String): Boolean;
begin
Result:=FUpdateableContent.FieldExists(contentId);
end;
procedure TFRE_DB_UserSession.SendServerClientRequest(const description: TFRE_DB_CONTENT_DESC;const session_id:TFRE_DB_SESSION_ID);
var CMD : IFRE_DB_COMMAND;
request_id : Qword;
begin
cmd := GFRE_DBI.NewDBCommand;
cmd.SetIsClient(false);
cmd.SetIsAnswer(false);
request_id := FMyReqID;
FOS_IL_INC_NATIVE(FMyReqID);
cmd.SetCommandID(request_id);
cmd.CommandType:=fct_AsyncRequest;
cmd.Data := description;
if session_id<>'' then begin
cmd.ChangeSession:=session_id;
end;
GFRE_DBI.LogInfo(dblc_SESSION,'>>SERVER CLIENT REQUEST (%s) RID = [%d] TYPE[%s] SID=%s CHANGE SID=%s',[description.ClassName,request_id,CFRE_DB_COMMANDTYPE[cmd.CommandType],FSessionID,cmd.ChangeSession]);
try
if assigned(FBoundSession_RA_SC) then
begin
FBoundSession_RA_SC.Send_ServerClient(cmd);
end
else
begin
FBoundSession_RA_SC := FBoundSession_RA_SC;
// Client Session has gone ...
end;
except on e:exception do
begin
writeln('BOUND SESSION RAC EXC: '+e.Message+' ',FSessionID);
end;
end
end;
procedure TFRE_DB_UserSession.SendServerClientAnswer(const description: TFRE_DB_CONTENT_DESC; const answer_id: Qword);
var CMD : IFRE_DB_COMMAND;
begin
cmd := GFRE_DBI.NewDBCommand;
cmd.SetIsClient(false);
cmd.SetIsAnswer(True);
cmd.SetCommandID(answer_id);
cmd.CommandType:=fct_SyncReply;
cmd.Data := description;
GFRE_DBI.LogDebug(dblc_SESSION,'>>SERVER CLIENT ANSWER (%s) RID = [%d] TYPE[%s] SID=%s CHANGE SID=%s',[description.ClassName,answer_id,CFRE_DB_COMMANDTYPE[cmd.CommandType],FSessionID,cmd.ChangeSession]);
//GFRE_DBI.LogDebug(dblc_SESSION,'DATA: %s',[description.DumpToString()]);
SendServerClientCMD(CMD);
end;
procedure TFRE_DB_UserSession.SendServerClientCMD(const cmd: IFRE_DB_COMMAND);
begin
if assigned(FBoundSession_RA_SC) then
FBoundSession_RA_SC.Send_ServerClient(cmd)
else
GFRE_DBI.LogWarning(dblc_SESSION,'WARNING DROPPED COMMAND : %s %s',[cmd.InvokeClass+'.'+cmd.InvokeMethod,' ',cmd.Answer]);
end;
function TFRE_DB_UserSession.GetSessionChannelManager: IFRE_APSC_CHANNEL_MANAGER;
begin
{ FIXXME: Think lock, and Channel migration }
result := FBoundSession_RA_SC.GetChannel.cs_GetChannelManager;
end;
function TFRE_DB_UserSession.GetSessionChannelGroup: IFRE_APSC_CHANNEL_GROUP;
begin
result := FSessionCG;
end;
function TFRE_DB_UserSession.InvokeRemoteRequest(const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object ; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
var
right : TFRE_DB_String;
ses : TFRE_DB_UserSession;
rmethodenc : TFRE_DB_RemoteSessionInvokeEncapsulation;
begin
if GFRE_DBI.NetServ.FetchPublisherSessionLocked(uppercase(rclassname),uppercase(rmethodname),ses,right) then
begin
try
rmethodenc := TFRE_DB_RemoteSessionInvokeEncapsulation.Create(rclassname,rmethodname,FCurrentReqID,FSessionID,input,TFRE_DB_GenericCBMethod(SyncCallback),opaquedata,false);
if ses.DispatchCoroutine(@ses.InvokeRemReqCoRoutine,rmethodenc) then
result := edb_OK
else
Result := edb_ERROR;
finally
ses.UnlockSession;
end;
end
else
result := edb_NOT_FOUND;
end;
function TFRE_DB_UserSession.InvokeRemoteRequestMachine(const machineid: TFRE_DB_GUID; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
var
right : TFRE_DB_String;
ses : TFRE_DB_UserSession;
rmethodenc : TFRE_DB_RemoteSessionInvokeEncapsulation;
begin
if GFRE_DBI.NetServ.FetchPublisherSessionLockedMachine(machineid,uppercase(rclassname),uppercase(rmethodname),ses,right) then
begin
try
rmethodenc := TFRE_DB_RemoteSessionInvokeEncapsulation.Create(rclassname,rmethodname,FCurrentReqID,FSessionID,input,TFRE_DB_GenericCBMethod(SyncCallback),opaquedata,false);
if ses.DispatchCoroutine(@ses.InvokeRemReqCoRoutine,rmethodenc) then
result := edb_OK
else
Result := edb_ERROR;
finally
ses.UnlockSession;
end;
end
else
result := edb_NOT_FOUND;
end;
function TFRE_DB_UserSession.InvokeRemoteRequestMachineMac(const machine_mac: TFRE_DB_NameType; const rclassname, rmethodname: TFRE_DB_NameType; const input: IFRE_DB_Object; const SyncCallback: TFRE_DB_RemoteCB; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
var
right : TFRE_DB_String;
ses : TFRE_DB_UserSession;
rmethodenc : TFRE_DB_RemoteSessionInvokeEncapsulation;
begin
if GFRE_DBI.NetServ.FetchPublisherSessionLockedMachineMac(machine_mac,uppercase(rclassname),uppercase(rmethodname),ses,right) then
begin
try
rmethodenc := TFRE_DB_RemoteSessionInvokeEncapsulation.Create(rclassname,rmethodname,FCurrentReqID,FSessionID,input,TFRE_DB_GenericCBMethod(SyncCallback),opaquedata,false);
if ses.DispatchCoroutine(@ses.InvokeRemReqCoRoutine,rmethodenc) then
result := edb_OK
else
Result := edb_ERROR;
finally
ses.UnlockSession;
end;
end
else
result := edb_NOT_FOUND;
end;
function TFRE_DB_UserSession.InvokeRemoteInterface(const machineid: TFRE_DB_GUID; const RIFMethod: TFRE_DB_RIF_Method; const CompletionCallback: TFRE_DB_RemoteCB_RIF; const opaquedata: IFRE_DB_Object): TFRE_DB_Errortype;
var obj : IFRE_DB_Object;
class_name,
method_name : shortstring;
right : TFRE_DB_String;
ses : TFRE_DB_UserSession;
rmethodenc : TFRE_DB_RemoteSessionInvokeEncapsulation;
begin
if TFRE_DB_ObjectEx.CheckGetRIFMethodInstance(RIFMethod,class_name,method_name,obj) then
begin
//result := InvokeRemoteRequestMachine(machineid,class_name,method_name,obj,TFRE_DB_GenericCBMethod(CompletionCallback),opaquedata,true);
if GFRE_DBI.NetServ.FetchPublisherSessionLockedMachine(machineid,uppercase(class_name),uppercase(method_name),ses,right) then
begin
try
rmethodenc := TFRE_DB_RemoteSessionInvokeEncapsulation.Create(class_name,method_name,FCurrentReqID,FSessionID,obj,TFRE_DB_GenericCBMethod(CompletionCallback),opaquedata,true);
if ses.DispatchCoroutine(@ses.InvokeRemReqCoRoutine,rmethodenc) then
result := edb_OK
else
Result := edb_ERROR;
finally
ses.UnlockSession;
end;
end
else
begin
result := edb_NOT_FOUND;
result.Msg := 'not a rif method, undefined, not found';
end;
end
else
begin
result.Code := edb_NOT_FOUND;
result.Msg := 'not a rif method, undefined, not found';
end;
end;
procedure TFRE_DB_UserSession.InvokeRemReqCoRoutine(const data: Pointer);
var PublisherRAC : IFRE_DB_COMMAND_REQUEST_ANSWER_SC;
right : TFRE_DB_String;
CMD : IFRE_DB_COMMAND;
request_id : Int64;
ses : TFRE_DB_UserSession;
rmethodenc : TFRE_DB_RemoteSessionInvokeEncapsulation;
m : TFRE_APSC_CoRoutine;
begin
rmethodenc := TFRE_DB_RemoteSessionInvokeEncapsulation(data);
try
cmd := GFRE_DBI.NewDBCommand;
cmd.SetIsClient(false);
cmd.SetIsAnswer(False);
request_id := FMyReqID;
FOS_IL_INC_NATIVE(FMyReqID);
cmd.SetCommandID(request_id);
cmd.InvokeClass := rmethodenc.Fclassname;
cmd.InvokeMethod := rmethodenc.Fmethodname;
cmd.Data := rmethodenc.Finput;
if Assigned(rmethodenc.FSyncCallback) then
begin
cmd.CommandType:=fct_SyncRequest;
AddSyncContinuationEntry(request_id,rmethodenc.FOCid,rmethodenc.FsessionID,rmethodenc.FSyncCallback,rmethodenc.FIsRifCB,5000,rmethodenc.Fopaquedata);
end
else
begin
cmd.CommandType:=fct_AsyncRequest;
end;
try
FBoundSession_RA_SC.Send_ServerClient(cmd);
except on e:exception do
begin
writeln('REMOTE BOUND SESSION RAC EXC: '+e.Message);
end;
end
finally
rmethodenc.free;
end;
end;
procedure TFRE_DB_UserSession.AnswerRemReqCoRoutine(const data: Pointer);
begin
try
TFRE_DB_RemoteSessionAnswerEncapsulation(data).DispatchAnswer(self);
finally
TFRE_DB_RemoteSessionAnswerEncapsulation(data).free;
end;
end;
procedure TFRE_DB_UserSession.COR_SendContentOnBehalf(const data: Pointer);
var ct : TFRE_DB_CONTENT_DESC;
begin
ct := TFRE_DB_CONTENT_DESC(data);
SendServerClientRequest(ct);
end;
procedure TFRE_DB_UserSession.COR_ExecuteSessionCmd(const data: Pointer);
var sc : TFRE_DB_Usersession_COR;
begin
sc := TFRE_DB_Usersession_COR(data);
try
sc.Execute(self)
finally
sc.free
end;
end;
function TFRE_DB_UserSession.ProcessQryToDescription(const qry: TFRE_DB_QUERY_BASE): TFRE_DB_STORE_DATA_DESC;
var
st : IFRE_DB_SIMPLE_TRANSFORM;
frt : IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION;
langr : TFRE_DB_StringArray;
resdata : IFRE_DB_ObjectArray;
function GetGridDataDescription: TFRE_DB_STORE_DATA_DESC;
var
cnt,i : NativeInt;
begin
cnt := 0;
result := TFRE_DB_STORE_DATA_DESC.create;
cnt := Length(resdata); //query.ExecuteQuery(@GetData,self);
for i :=0 to cnt-1 do
begin
FinalRightTransform(resdata[i],frt,langr);
result.addEntry(resdata[i]);
end;
cnt := qry.GetTotalCount;
Result.Describe(cnt);
end;
begin
qry.GetTransfrom.GetFinalRightTransformFunction(frt,langr);
resdata := qry.GetResultData;
result := GetGridDataDescription;
//writeln('__>>> ANSWER GGD');
//writeln(result.DumpToString());
//writeln('__>>> ANSWER GGD');
qry.free;
end;
procedure TFRE_DB_UserSession.COR_AnswerGridData(const qry: TFRE_DB_QUERY_BASE);
begin
// { DO final right transform -> send }
SendServerClientAnswer(ProcessQryToDescription(qry),qry.GetReqID);
end;
procedure TFRE_DB_UserSession.COR_SendStoreUpdates(const data: TFRE_DB_SESSION_UPO);
begin
data.DispatchAllNotifications(self);
end;
procedure TFRE_DB_UserSession.FinalRightTransform(const transformed_filtered_cloned_obj: IFRE_DB_Object; const frt: IFRE_DB_FINAL_RIGHT_TRANSFORM_FUNCTION; const langres: TFRE_DB_StringArray);
var conn : IFRE_DB_CONNECTION;
procedure DoPreSend(const plugin : TFRE_DB_OBJECT_PLUGIN_BASE);
begin
if plugin.EnhancesGridRenderingPreClientSend then
plugin.TransformGridEntryClientSend(conn.sys.GetCurrentUserTokenRef,transformed_filtered_cloned_obj,GetSessionGlobalData,langres);
end;
begin
if assigned(frt) then
begin
try
conn := GetDBConnection;
frt(conn.sys.GetCurrentUserTokenRef,transformed_filtered_cloned_obj,GetSessionGlobalData,langres);
except
on e:exception do
begin
GFRE_DBI.LogError(dblc_DB,'Custom transform failed %s',[e.Message]);
writeln('CUSTOM FINAL TRANSFORM FAILED............... ',e.Message);
writeln(transformed_filtered_cloned_obj.DumpToString);
writeln('...............');
end;
end;
end;
transformed_filtered_cloned_obj.ForAllPlugins(@DoPreSend);
end;
function TFRE_DB_UserSession.DispatchCoroutine(const coroutine: TFRE_APSC_CoRoutine; const data: Pointer):boolean;
begin
try
result := true;
if assigned(FBoundSession_RA_SC) then
FBoundSession_RA_SC.GetChannel.cs_GetChannelManager.SwitchToContextEx(CoRoutine,data)
else
result:=false;
except
on E:Exception do
begin
result := false;
writeln('@Dispatchcoroutine Exception ',FSessionID,' ',FUserName);
raise;
end;
end;
end;
function TFRE_DB_UserSession.RegisterRemoteRequestSet(const requests: TFRE_DB_RemoteReqSpecArray): TFRE_DB_Errortype;
begin
FRemoteRequestSet := requests;
end;
function TFRE_DB_UserSession.RegisterTaskMethod(const TaskMethod: IFRE_DB_WebTimerMethod; const invocation_interval: integer; const id: TFRE_APSC_ID): boolean;
var my_timer : IFRE_APSC_TIMER;
i : NativeInt;
begin
for i:=0 to FTimers.Count-1 do begin
if lowercase(IFRE_APSC_TIMER(FTimers[i]).cs_GetID)=lowercase(id) then
exit(false);
end;
my_timer := FBoundSession_RA_SC.GetChannel.cs_GetChannelManager.AddChannelManagerTimer(id,invocation_interval,@INT_TimerCallBack,true,TMethod(TaskMethod).Code,TMethod(TaskMethod).Data);
//my_timer.TIM_Start;
//my_timer.TIM_SetID(id);
//my_timer.TIM_SetMethod(TMethod(TaskMethod));
//my_timer.TIM_SetCallback(@INT_TimerCallBack);
FTimers.Add(my_timer);
end;
function TFRE_DB_UserSession.RemoveTaskMethod(const id: string): boolean;
var
i: NativeInt;
begin
for i:=FTimers.Count-1 downto 0 do
if lowercase(IFRE_APSC_TIMER(FTimers[i]).cs_GetID)=lowercase(id) then
begin
IFRE_APSC_TIMER(FTimers[i]).cs_Finalize;
FTimers.Delete(i);
exit(true);
end;
exit(false);
end;
function TFRE_DB_UserSession.IsInteractiveSession: Boolean;
begin
result := FIsInteractive;
end;
//function TFRE_DB_UserSession.FetchTranslateableText(const translation_key: TFRE_DB_String; var textObj: IFRE_DB_TEXT): Boolean;
//begin
// result := GetDBConnection.FetchTranslateableText(translation_key,textObj);
//end;
function TFRE_DB_UserSession.GetDBConnection: IFRE_DB_CONNECTION;
begin
result := FDBConnection;
end;
function TFRE_DB_UserSession.GetDomain: TFRE_DB_String;
var
loc: TFRE_DB_String;
begin
FREDB_SplitLocalatDomain(FUserName,loc,Result);
end;
function TFRE_DB_UserSession.GetDomainUID: TFRE_DB_GUID;
begin
result := FDBConnection.SYS.GetCurrentUserTokenRef.GetMyDomainID;
if Result=CFRE_DB_NullGUID then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'not domainid found for current user');
end;
function TFRE_DB_UserSession.GetDomainUID_String: TFRE_DB_GUID_String;
begin
result := FREDB_G2H(GetDomainUID);
end;
function TFRE_DB_UserSession.GetLoginUserAsCollKey: TFRE_DB_NameType;
begin
result := GFRE_BT.HashString_MD5_HEX(FUserName);
end;
function TFRE_DB_UserSession.GetPublishedRemoteMeths: TFRE_DB_RemoteReqSpecArray;
begin
result := FRemoteRequestSet;
end;
function TFRE_DB_UserSession.GetDownLoadLink4StreamField(const obj_uid: TFRE_DB_GUID; const fieldname: TFRE_DB_NameType; const is_attachment: boolean; mime_type: string; file_name: string; force_url_etag: string): String;
begin
if mime_type='' then
mime_type:='application/binary';
if file_name='' then
file_name:='-';
if force_url_etag='' then
force_url_etag:='-';
result := '/FDBOSF/'+FSessionID+'/'+FREDB_G2H(obj_uid)+'/'+BoolToStr(is_attachment,'A','N')+'/'+ GFRE_BT.Str2HexStr(mime_type)+'/'+ GFRE_BT.Str2HexStr(file_name)+'/'+GFRE_BT.Str2HexStr(force_url_etag)+'/'+GFRE_BT.Str2HexStr(fieldname);
end;
procedure TFRE_DB_UserSession.FieldDelete(const old_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId);
begin
HandleDiffField(mode_df_del,old_field);
//if FCurrentNotificationBlockLayer='SYSTEM' then
// FDBConnection.SYS.GetNotif.FieldDelete(old_field)
//else
// FDBConnection.GetNotif.FieldDelete(old_field);
end;
procedure TFRE_DB_UserSession.FieldAdd(const new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId);
begin
HandleDiffField(mode_df_add,new_field);
//if FCurrentNotificationBlockLayer='SYSTEM' then
// FDBConnection.SYS.GetNotif.FieldAdd(new_field)
//else
// FDBConnection.GetNotif.FieldAdd(new_field);
end;
procedure TFRE_DB_UserSession.FieldChange(const old_field, new_field: IFRE_DB_Field; const tsid: TFRE_DB_TransStepId);
begin
HandleDiffField(mode_df_change,new_field);
//if FCurrentNotificationBlockLayer='SYSTEM' then
// FDBConnection.SYS.GetNotif.FieldChange(old_field,new_field)
//else
// FDBConnection.GetNotif.FieldChange(old_field,new_field);
end;
procedure TFRE_DB_UserSession.DifferentiallUpdEnds(const obj_uid: TFRE_DB_GUID; const tsid: TFRE_DB_TransStepId);
var upo : IFRE_DB_Object;
key : shortstring;
fld : IFRE_DB_Field;
cbs: IFRE_DB_Object;
upfo: TFRE_DB_UPDATE_FORM_DESC;
begin
key := FREDB_G2H(obj_uid);
if FDifferentialUpdates.FieldOnlyExisting(key,fld) then
begin
upo := fld.CheckOutObject;
//writeln('DIFF UPDATE O');
//writeln(upo.DumpToString);
if IsDBOUpdatable(upo.UID) then
begin
//writeln('-------------------------------------------------');
//writeln('-------------------------------------------------');
//writeln('SWL: DBO UPDATE ',upo.DumpToString());
//writeln('-------------------------------------------------');
//writeln('-------------------------------------------------');
upfo := TFRE_DB_UPDATE_FORM_DESC.create.DescribeDBO(upo.CloneToNewObject);
//writeln('----------------------RESULT UPFO-');
//writeln(upfo.DumpToString());
//writeln('----------------------------------');
SendServerClientRequest(upfo);
end;
//writeln('SENT');
upo.Finalize;
end;
end;
procedure TFRE_DB_UserSession.DifferentiallUpdStarts(const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId);
begin
FDifferentialUpdates.Field(obj.UID_String).AsObject := obj.CloneToNewObject;
end;
procedure TFRE_DB_UserSession.FinalizeNotif;
begin
raise EFRE_DB_Exception.Create(edb_INTERNAL,'should not be called');
end;
procedure TFRE_DB_UserSession.ObjectDeleted(const coll_names: TFRE_DB_NameTypeArray; const obj: IFRE_DB_Object; const tsid: TFRE_DB_TransStepId);
var cbs : IFRE_DB_Object;
input : IFRE_DB_Object;
procedure _executeCallback(const o: IFRE_DB_Object);
begin
SendServerClientRequest((o.Implementor_HC as TFRE_DB_SERVER_FUNC_DESC).InternalInvokeDI(self,input).Implementor_HC as TFRE_DB_CONTENT_DESC);
end;
begin
input:=GFRE_DBI.NewObject;
input.Field('TYPE').AsString := 'DEL';
input.Field('colls').AsStringArr := FREDB_NametypeArray2StringArray(coll_names);
input.Field('obj').AsObject := obj.CloneToNewObject;
cbs:=getDBOChangeCBs(obj.UID);
if Assigned(cbs) then
cbs.ForAllObjects(@_executeCallback);
end;
procedure TFRE_DB_UserSession.ObjectUpdated(const upobj: IFRE_DB_Object; const colls: TFRE_DB_StringArray; const tsid: TFRE_DB_TransStepId);
var cbs : IFRE_DB_Object;
input : IFRE_DB_Object;
procedure _executeCallback(const o: IFRE_DB_Object);
begin
SendServerClientRequest((o.Implementor_HC as TFRE_DB_SERVER_FUNC_DESC).InternalInvokeDI(self,input).Implementor_HC as TFRE_DB_CONTENT_DESC);
end;
begin
input:=GFRE_DBI.NewObject;
input.Field('TYPE').AsString := 'UPD';
input.Field('colls').AsStringArr := colls;
input.Field('obj').AsObject := upobj.CloneToNewObject;
cbs:=getDBOChangeCBs(upobj.UID);
if Assigned(cbs) then
cbs.ForAllObjects(@_executeCallback);
end;
//var cbs : IFRE_DB_Object;
//
// procedure _executeCallback(const o: IFRE_DB_Object);
// begin
// SendServerClientRequest((o.Implementor_HC as TFRE_DB_SERVER_FUNC_DESC).InternalInvokeDI(self,upobj.CloneToNewObject).Implementor_HC as TFRE_DB_CONTENT_DESC);
// end;
//
//begin
// cbs:=getDBOChangeCBs(upobj.UID); { On fullstate update check for session callbacks }
// if Assigned(cbs) then
// cbs.ForAllObjects(@_executeCallback);
//end;
procedure TFRE_DB_UserSession.SetupInboundRefLink(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
var cbs : IFRE_DB_Object;
input : IFRE_DB_Object;
procedure _executeCallback(const o: IFRE_DB_Object);
begin
SendServerClientRequest((o.Implementor_HC as TFRE_DB_SERVER_FUNC_DESC).InternalInvokeDI(self,input).Implementor_HC as TFRE_DB_CONTENT_DESC);
end;
begin
input:=GFRE_DBI.NewObject;
input.Field('TYPE').AsString := 'SIR';
input.Field('from').AsObject := from_obj.CloneToNewObject;
input.Field('obj').AsObject := to_obj.CloneToNewObject;
input.Field('spec').AsString := key_description;
cbs:=getDBOChangeCBs(to_obj.UID);
if Assigned(cbs) then
cbs.ForAllObjects(@_executeCallback);
end;
procedure TFRE_DB_UserSession.InboundReflinkDropped(const from_obj: IFRE_DB_Object; const to_obj: IFRE_DB_Object; const key_description: TFRE_DB_NameTypeRL; const tsid: TFRE_DB_TransStepId);
var cbs : IFRE_DB_Object;
input : IFRE_DB_Object;
procedure _executeCallback(const o: IFRE_DB_Object);
begin
SendServerClientRequest((o.Implementor_HC as TFRE_DB_SERVER_FUNC_DESC).InternalInvokeDI(self,input).Implementor_HC as TFRE_DB_CONTENT_DESC);
end;
begin
input:=GFRE_DBI.NewObject;
input.Field('TYPE').AsString := 'IRD';
input.Field('from').AsObject := from_obj.CloneToNewObject;
input.Field('obj').AsObject := to_obj.CloneToNewObject;
input.Field('spec').AsString := key_description;
cbs:=getDBOChangeCBs(to_obj.UID);
if Assigned(cbs) then
cbs.ForAllObjects(@_executeCallback);
end;
procedure TFRE_DB_UserSession.HandleDiffField(const mode: TDiffFieldUpdateMode; const fld: IFRE_DB_Field);
var upouidp : TFRE_DB_GUIDArray;
upofldp : TFRE_DB_StringArray;
uposchp : TFRE_DB_StringArray;
fldname : TFRE_DB_NameType;
fldsch : TFRE_DB_NameType;
upo : IFRE_DB_Object;
intero : IFRE_DB_Object;
i : NativeInt;
intrfld : IFRE_DB_Field;
begin
upouidp := fld.GetUpdateObjectUIDPath;
upofldp := fld.GetUpdateObjFieldPath;
uposchp := fld.GetUpdateObjSchemePath;
//writeln('Handlediffield ---------------------------------------------------------');
//writeln('>>>>>>>>>>>> ',mode,' ',FREDB_CombineString(upofldp,'.'),' ',FREDB_CombineString(uposchp,':'),' FLD ',fld.FieldType,' ',fld.FieldName,' ',fld.AsString);
upo := FDifferentialUpdates.FieldOnlyExistingObj(FREDB_G2H(upouidp[0])); { get root object }
if assigned(upo) then
begin
for i:=1 to high(upouidp) do
begin
fldname := upofldp[i-1];
fldsch := uposchp[i];
//writeln(' Field : ',fldname,' ',fldsch);
if not upo.FieldOnlyExisting(fldname,intrfld) then
begin
intero := GFRE_DBI.NewObjectSchemeByName(fldsch);
intero.Field('uid').AsGUID := upouidp[i];
upo.Field(fldname).AsObject := intero;
upo := intero;
end
else
begin
if intrfld.FieldType<>fdbft_Object then
begin
writeln('SWL ::: >> IGNORING UNEXPECTED DIFFUPDATE CASE ?? ');
exit; {}
end;
upo := intrfld.AsObject;
end;
end;
fldname := fld.FieldName;
case mode of
mode_df_add : upo.Field(fldname).CloneFromField(fld);
mode_df_del : upo.Field(fldname).AsString := cFRE_DB_SYS_CLEAR_VAL_STR;
mode_df_change : upo.Field(fldname).CloneFromField(fld);
end;
end;
//writeln('Handlediffield ---------------------------------------------------------');
end;
function TFRE_DB_UserSession.BoundMachineUID: TFRE_DB_GUID;
begin
result := FBoundMachineUid;
end;
function TFRE_DB_UserSession.BoundMachineMac: TFRE_DB_NameType;
begin
result := FBoundMachineMac;
end;
function TFRE_DB_UserSession.SysConfig: IECF_SystemConfiguration;
begin
result := self;
end;
function TFRE_DB_UserSession.SubscribeGlobalEvent(const ev_name: TFRE_DB_NameType; const event_callback: IFRE_DB_SessionDataCallback): boolean;
procedure _UpdateRecordEventCallback;
var m : TMethod;
begin
m := TMethod(event_callback);
FGlobalEventCallbacks.Field(ev_name+'_C').AsUInt64 := PtrUInt(m.Code);
FGlobalEventCallbacks.Field(ev_name+'_D').AsUInt64 := PtrUInt(m.Data);
end;
begin
result := GFRE_DBI.NetServ.SubscribeGlobalEvent(FSessionID,ev_name);
_UpdateRecordEventCallback;
GFRE_DBI.LogNotice(dblc_SESSION,'SESSION [%s] SUBSCRIBE GLOBAL EVENT [%s]',[GetSessionID,ev_name]);
end;
procedure TFRE_DB_UserSession.UnsubscribeGlobalEvent(const ev_name: TFRE_DB_NameType);
begin
FGlobalEventCallbacks.DeleteField(ev_name+'_C');
FGlobalEventCallbacks.DeleteField(ev_name+'_D');
GFRE_DBI.NetServ.UnsubscribeGlobalEvent(FSessionID,ev_name);
GFRE_DBI.LogNotice(dblc_SESSION,'SESSION [%s] SUBSCRIBE GLOBAL EVENT [%s]',[GetSessionID,ev_name]);
end;
procedure TFRE_DB_UserSession.PublishGlobalEvent(const ev_name: TFRE_DB_NameType; const ev_data: IFRE_DB_Object);
var
en : string;
begin
en := ev_data.Field('E').AsString;
GFRE_DBI.NetServ.PublishGlobalEvent(ev_name,ev_data);
GFRE_DBI.LogNotice(dblc_SESSION,'SESSION [%s] PUBLISH GLOBAL EVENT [%s/%s]',[GetSessionID,ev_name,en]);
end;
procedure TFRE_DB_UserSession.PublishGlobalEventText(const ev_name: TFRE_DB_NameType; const ev_data: Shortstring);
var evd : IFRE_DB_Object;
begin
evd := GFRE_DBI.NewObject;
evd.Field('E').AsString := ev_data;
PublishGlobalEvent(ev_name,evd);
end;
constructor TFOS_BASE.Create;
begin
inherited
end;
function TFOS_BASE.Implementor: TObject;
begin
result := self;
end;
function TFOS_BASE.Implementor_HC: TObject;
begin
result := self;
end;
function TFOS_BASE.GetImplementorsClass: TClass;
begin
result := self.ClassType;
end;
//class function TFRE_DB_Base.Get_DBI_ClassMethods : TFOSStringArray;
//var methodtable : pmethodnametable;
// i : dword;
// ovmt : PVmt;
//begin
// ovmt:=PVmt(self);
// while assigned(ovmt) do
// begin
// methodtable:=pmethodnametable(ovmt^.vMethodTable);
// if assigned(methodtable) then
// begin
// for i:=0 to methodtable^.count-1 do begin
// //writeln('******* : ',methodtable^.entries[i].name^);
// if pos('IMC_',methodtable^.entries[i].name^)=1 then begin
// SetLength(result,Length(result)+1);
// result[High(result)] := Copy(methodtable^.entries[i].name^,5,MaxInt);
// end;
// end;
// end;
// ovmt := ovmt^.vParent;
// end;
//end;
class procedure TFRE_DB_Base._InstallDBObjects4Domain(const conn:IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID : TFRE_DB_GUID);
var
role: IFRE_DB_ROLE;
begin
if not (self.ClassType=TFRE_DB_ObjectEx) then
begin
if currentVersionId='' then // Initial Install
begin
role := CreateClassRole('store','Store ' + ClassName,'Allowed to store new ' + ClassName + ' objects');
role.AddRight(GetRight4Domain(GetClassRightNameStore,domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.store role');
role := CreateClassRole('delete','Delete ' + ClassName,'Allowed to delete ' + ClassName + ' objects');
role.AddRight(GetRight4Domain(GetClassRightNameDelete,domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.delete role');
role := CreateClassRole('update','Update ' + ClassName,'Allowed to edit ' + ClassName + ' objects');
role.AddRight(GetRight4Domain(GetClassRightNameUpdate,domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.update role');
role := CreateClassRole('fetch','Fetch ' + ClassName,'Allowed to fetch ' + ClassName + ' objects');
role.AddRight(GetRight4Domain(GetClassRightNameFetch,domainUID));
CheckDbResult(conn.StoreRole(role,domainUID),'Error creating '+ClassName+'.fetch role');
end
end;
end;
function TFRE_DB_Base.Implementor_HC: TObject;
begin
if assigned(FMediatorExtention) then begin
result := FMediatorExtention;
end else begin
Result:=self;
end;
end;
function TFRE_DB_Base.Debug_ID: TFRE_DB_String;
begin
result := 'LOGIC: NO DEBUG ID SET';
end;
class procedure TFRE_DB_Base.VersionInstallationCheck(const currentVersionId, newVersionId: TFRE_DB_NameType);
begin
if ((newVersionId<>'UNUSED') and (newVersionId<>'BASE')) and (currentVersionId<>newVersionId) then
raise EFRE_DB_Exception.Create(edb_ERROR,'%s> install failed, not all versions handled properly old=[%s] new=[%s]',[classname,currentVersionId,newVersionId]);
end;
function TFRE_DB_Base.GetSystemSchemeByName(const schemename: TFRE_DB_String; var scheme: IFRE_DB_SchemeObject): Boolean;
begin
result := GFRE_DBI.GetSystemSchemeByName(schemename,scheme);
end;
function TFRE_DB_Base.GetSystemScheme(const schemename: TClass; var scheme: IFRE_DB_SchemeObject): Boolean;
begin
result := GFRE_DBI.GetSystemScheme(schemename,scheme);
end;
class function TFRE_DB_Base.GetStdObjectRightName(const std_right: TFRE_DB_STANDARD_RIGHT; const uid: TFRE_DB_GUID): TFRE_DB_String;
begin
case std_right of
sr_STORE : result := GetObjectRightName('S',uid);
sr_UPDATE : result := GetObjectRightName('U',uid);
sr_DELETE : result := GetObjectRightName('D',uid);
sr_FETCH : result := GetObjectRightName('F',uid);
else
raise EFRE_DB_Exception.Create(edb_INTERNAL,'rightname for standard right is not defined!');
end;
end;
class function TFRE_DB_Base.GetObjectRightName(const right: TFRE_DB_NameType; const uid: TFRE_DB_GUID): TFRE_DB_String;
begin
result := 'O#'+uppercase(right)+'%'+uppercase(FREDB_G2H(uid));
end;
class function TFRE_DB_Base._GetClassRight(const right: TFRE_DB_NameType): IFRE_DB_RIGHT;
begin
Result:= GetClassRightName(right);
end;
class function TFRE_DB_Base.GetRight4Domain(const right: TFRE_DB_NameType; const domainUID: TFRE_DB_GUID): IFRE_DB_RIGHT;
begin
result := uppercase(right+'@'+FREDB_G2H(domainUID));
end;
class function TFRE_DB_Base.GetClassRightName(const rclassname: ShortString; const right: TFRE_DB_NameType): TFRE_DB_String;
begin
Result := uppercase('$O_R_'+RClassName+'_'+right);
end;
class function TFRE_DB_Base.CreateClassRole(const rolename: TFRE_DB_String; const short_desc, long_desc: TFRE_DB_String): IFRE_DB_ROLE;
begin
result := GFRE_DBI.NewRole(GetClassRoleName(rolename),long_desc,short_desc,true);
end;
class function TFRE_DB_Base.GetClassRoleName(const rolename: TFRE_DB_String): TFRE_DB_String;
begin
Result:=uppercase('$CR_'+ClassName+'_'+rolename);
end;
class function TFRE_DB_Base.GetClassRoleNameUpdate: TFRE_DB_String;
begin
Result:=GetClassRoleName('update');
end;
class function TFRE_DB_Base.GetClassRoleNameDelete: TFRE_DB_String;
begin
Result:=GetClassRoleName('delete');
end;
class function TFRE_DB_Base.GetClassRoleNameStore: TFRE_DB_String;
begin
Result:=GetClassRoleName('store');
end;
class function TFRE_DB_Base.GetClassRoleNameFetch: TFRE_DB_String;
begin
Result:=GetClassRoleName('fetch');
end;
class function TFRE_DB_Base.GetClassStdRoles(const store: boolean; const update: boolean; const delete: boolean; const fetch: boolean): TFRE_DB_StringArray;
procedure _add(const name : TFRE_DB_String);
begin
SetLength(result,length(result)+1);
result[high(result)] := name;
end;
begin
SetLength(result,0);
if store then
_Add(GetClassRoleNameStore);
if update then
_Add(GetClassRoleNameUpdate);
if delete then
_Add(GetClassRoleNameDelete);
if fetch then
_Add(GetClassRoleNameFetch);
end;
class function TFRE_DB_Base.GetClassRightName(const right: TFRE_DB_NameType): TFRE_DB_String;
begin
Result := GetClassRightName(Classname,right);
end;
class function TFRE_DB_Base.GetClassRightNameSR(const rclassname: ShortString; const sright: TFRE_DB_STANDARD_RIGHT): TFRE_DB_String;
begin
case sright of
sr_STORE: Result:=GetClassRightName(rclassname,'store');
sr_UPDATE: Result:=GetClassRightName(rclassname,'update');
sr_DELETE: Result:=GetClassRightName(rclassname,'delete');
sr_FETCH: Result:=GetClassRightName(rclassname,'fetch');
else
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid standard right');
end;
end;
class function TFRE_DB_Base.GetClassRightNameUpdate: TFRE_DB_String;
begin
Result:=GetClassRightNameSR(ClassName,sr_UPDATE);
end;
class function TFRE_DB_Base.GetClassRightNameDelete: TFRE_DB_String;
begin
Result:=GetClassRightNameSR(ClassName,sr_DELETE);
end;
class function TFRE_DB_Base.GetClassRightNameStore: TFRE_DB_String;
begin
Result:=GetClassRightNameSR(ClassName,sr_STORE);
end;
class function TFRE_DB_Base.GetClassRightNameFetch: TFRE_DB_String;
begin
Result:=GetClassRightNameSR(ClassName,sr_FETCH);
end;
procedure TFRE_DB_Base.__SetMediator(const med: TFRE_DB_ObjectEx);
begin
FMediatorExtention := med;
end;
class function TFRE_DB_Base.CheckGetRIFMethodInstance(const rifmethod: TFRE_DB_RIF_Method; out rclassname, rmethodname: ShortString; out obj: IFRE_DB_Object): boolean;
var m : TMethod;
o : TObject;
begin
try
result := false;
m := TMethod(rifmethod);
o := TObject(m.Data);
obj := (o as TFRE_DB_ObjectEx);
rclassname := o.ClassName;
rmethodname := o.MethodName(m.Code);
result := rmethodname<>'';
except { someone fed us with shit }
exit;
end;
end;
class function TFRE_DB_Base.Get_DBI_InstanceMethods: TFRE_DB_StringArray;
var methodtable : pmethodnametable;
i : dword;
ovmt : PVmt;
begin
ovmt:=PVmt(self);
while assigned(ovmt) do
begin
methodtable:=pmethodnametable(ovmt^.vMethodTable);
if assigned(methodtable) then
begin
for i:=0 to methodtable^.count-1 do begin
if (pos('IMI_',methodtable^.entries[i].name^)=1) or (pos('WEB_',methodtable^.entries[i].name^)=1) then begin
SetLength(result,Length(result)+1);
result[High(result)] := uppercase(Copy(methodtable^.entries[i].name^,5,MaxInt));
end;
end;
end;
ovmt := ovmt^.vParent;
end;
end;
class function TFRE_DB_Base.Get_DBI_RemoteMethods: TFRE_DB_StringArray;
var methodtable : pmethodnametable;
i : dword;
ovmt : PVmt;
begin
SetLength(Result,0);
ovmt:=PVmt(self);
while assigned(ovmt) do
begin
methodtable:=pmethodnametable(ovmt^.vMethodTable);
if assigned(methodtable) then
begin
for i:=0 to methodtable^.count-1 do begin
if (pos('REM_',methodtable^.entries[i].name^)=1) then begin
SetLength(result,Length(result)+1);
result[High(result)] := uppercase(Copy(methodtable^.entries[i].name^,5,MaxInt));
end;
end;
end;
ovmt := ovmt^.vParent;
end;
end;
class function TFRE_DB_Base.Get_DBI_RIFMethods: TFRE_DB_StringArray;
var methodtable : pmethodnametable;
i : dword;
ovmt : PVmt;
begin
SetLength(Result,0);
ovmt:=PVmt(self);
while assigned(ovmt) do
begin
methodtable:=pmethodnametable(ovmt^.vMethodTable);
if assigned(methodtable) then
begin
for i:=0 to methodtable^.count-1 do begin
if (pos('RIF_',methodtable^.entries[i].name^)=1) then begin
SetLength(result,Length(result)+1);
result[High(result)] := uppercase(Copy(methodtable^.entries[i].name^,1,MaxInt));
end;
end;
end;
ovmt := ovmt^.vParent;
end;
end;
class function TFRE_DB_Base.Get_DBI_ClassMethods: TFRE_DB_StringArray;
var methodtable : pmethodnametable;
i : dword;
ovmt : PVmt;
begin
ovmt:=PVmt(self);
while assigned(ovmt) do
begin
methodtable:=pmethodnametable(ovmt^.vMethodTable);
if assigned(methodtable) then
begin
for i:=0 to methodtable^.count-1 do begin
//writeln('******* : ',methodtable^.entries[i].name^);
if (pos('IMC_',methodtable^.entries[i].name^)=1) or (pos('WBC_',methodtable^.entries[i].name^)=1) then begin
SetLength(result,Length(result)+1);
result[High(result)] := uppercase(Copy(methodtable^.entries[i].name^,5,MaxInt));
end;
end;
end;
ovmt := ovmt^.vParent;
end;
end;
class function TFRE_DB_Base.ClassMethodExists(const name: Shortstring): Boolean;
begin
result := (MethodAddress('IMC_'+name)<>nil) or (MethodAddress('WBC_'+name)<>nil);
end;
class function TFRE_DB_Base.Invoke_DBIMC_Method(const name: TFRE_DB_String; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var M :IFRE_DB_InvokeClassMethod;
MM :TMethod;
WM :IFRE_DB_WebClassMethod;
begin
result := nil;
MM.Code := MethodAddress('WBC_'+name);
MM.Data := self;
if assigned(MM.Code) then
begin
WM := IFRE_DB_WebClassMethod(mm);
try
result := wm(input,ses,app,conn);
except on e:exception do begin
raise EFRE_DB_Exception.Create(edb_ERROR,'CLASS METHOD INVOCATION %s.%s failed (%s)',[Classname,name,e.Message]);
end;end;
end
else
begin
MM.Code := MethodAddress('IMC_'+name);
MM.Data := self;
M := IFRE_DB_InvokeClassMethod(MM);
if assigned(mm.Code) then begin
try
result := m(input);
except on e:exception do begin
raise EFRE_DB_Exception.Create(edb_ERROR,'CLASS METHOD INVOCATION %s.%s failed (%s)',[Classname,name,e.Message]);
end;end;
end else begin
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'CLASS INVOCATION %s.%s failed (method not found)',[Classname,name]);
end;
end;
end;
function TFRE_DB_Base.Invoke_DBIMI_Method(const name: TFRE_DB_String; const input: IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var M : IFRE_DB_InvokeInstanceMethod;
MM : TMethod;
WM : IFRE_DB_WebInstanceMethod;
begin
result := nil;
MM.Data := self;
MM.Code := MethodAddress('WEB_'+name);
if not assigned(MM.Code) then
MM.Code := MethodAddress('FLX_'+name);
if assigned(MM.code) then
begin
WM := IFRE_DB_WebInstanceMethod(MM);
result := wm(input,ses,app,conn);
end
else
begin { Fallback / old IMI }
MM.Code := MethodAddress('IMI_'+name);
M := IFRE_DB_InvokeInstanceMethod(MM);
if assigned(mm.Code) then
result := m(input)
else
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'INSTANCE METHOD INVOCATION %s.%s (%s) failed (method not found)',[Classname,name,Debug_ID]);
end;
end;
procedure TFRE_DB_Base.Invoke_DBREM_Method(const rmethodname: TFRE_DB_NameType; const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
var M : IFRE_DB_RemInstanceMethod;
MM : TMethod;
begin
MM.Code := MethodAddress('REM_'+rmethodname);
MM.Data := self;
if assigned(MM.code) then
begin
M := IFRE_DB_RemInstanceMethod(MM);
m(command_id,input,cmd_type);
end
else
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'REM INSTANCE METHOD INVOCATION %s.%s failed (method not found)',[Classname,rmethodname]);
end;
function TFRE_DB_Base.Invoke_DBRIF_Method(const rmethodname: TFRE_DB_NameType ; const run_ctx : TObject ; const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE):IFRE_DB_Object;
var M : TFRE_DB_RIF_Method;
MM : TMethod;
rr : TFRE_DB_RIF_RESULT;
begin
result := nil;
MM.Code := MethodAddress(rmethodname);
MM.Data := self;
if assigned(MM.code) then
begin
M := TFRE_DB_RIF_Method(MM);
try
result := M(run_ctx);
except on
e: exception do
begin
rr := TFRE_DB_RIF_RESULT.create;
result := rr;
rr.ErrorCode:=-1;
rr.ErrorText:= Format('RIF INSTANCE METHOD INVOCATION %s.%s failed (%s)',[Classname,rmethodname,e.Message]);
end;
end;
end
else
begin
rr := TFRE_DB_RIF_RESULT.create;
result := rr;
rr.ErrorCode:=-1;
rr.ErrorText:= Format('RIF INSTANCE METHOD INVOCATION %s.%s failed (method not found)',[Classname,rmethodname]);
end;
end;
function TFRE_DB_Base.IMI_MethodExists(const name: TFRE_DB_String): boolean;
begin
if assigned(FMediatorExtention) then begin
result := FMediatorExtention.MethodExists(name);
end else begin
result := assigned(MethodAddress('IMI_'+name)) or assigned(MethodAddress('WEB_'+name)) or assigned(MethodAddress('FLX_'+name));
end;
end;
function TFRE_DB_Base.MethodExists(const name: Shortstring): Boolean;
begin
result := IMI_MethodExists(name);
end;
function TFRE_DB_Base.Supports(const InterfaceSpec: ShortString; out Intf): boolean;
begin
result := Sysutils.Supports(self,InterfaceSpec,Intf);
if (not result) and assigned(FMediatorExtention) then begin
result := Sysutils.Supports(FMediatorExtention,InterfaceSpec,Intf);
end;
end;
function TFRE_DB_Base.Supports(const InterfaceSpec: ShortString): boolean;
begin
result := Sysutils.Supports(self,InterfaceSpec);
if (not result) and assigned(FMediatorExtention) then begin
result := Sysutils.Supports(FMediatorExtention,InterfaceSpec);
end;
end;
procedure TFRE_DB_Base.IntfCast(const InterfaceSpec: ShortString; out Intf);
begin
if not self.Supports(InterfaceSpec,Intf) then begin
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'INTERFACE UPCAST FAILED FOR CLASS [%s] TO [%s]',[ClassName,InterfaceSpec]);
end;
end;
function TFRE_DB_Base.CSFT(const server_function_name: string; const obj: IFRE_DB_Object): TFRE_DB_SERVER_FUNC_DESC;
var sfo:IFRE_DB_Object;
begin
sfo := obj;
if sfo=nil then begin
self.IntfCast(IFRE_DB_Object,sfo);
end;
if not sfo.MethodExists(server_function_name) then raise EFRE_DB_Exception.Create(edb_ERROR,'no method named %s exists in object %s',[server_function_name,sfo.Implementor_HC.ClassName]);
result := TFRE_DB_SERVER_FUNC_DESC.create.Describe(sfo,server_function_name);
end;
function TFRE_DB_Base.CSF(const invoke_method: IFRE_DB_InvokeInstanceMethod): TFRE_DB_SERVER_FUNC_DESC;
var m : TMethod;
obj : TFRE_DB_Base;
sfo : IFRE_DB_Object;
method_name : string;
begin
m := TMethod(invoke_method);
obj := (TObject(m.Data) as TFRE_DB_Base);
obj.IntfCast(IFRE_DB_Object,sfo);
method_name := obj.MethodName(m.Code);
if pos('IMI_',method_name)=1 then begin
result := TFRE_DB_SERVER_FUNC_DESC.create.Describe(sfo,Copy(method_name,5,maxint));
end else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'the method named %s does not follow the IMI_* naming convention',[method_name]);
end;
end;
function TFRE_DB_Base.CWSF(const invoke_method: IFRE_DB_WebInstanceMethod): TFRE_DB_SERVER_FUNC_DESC;
var m : TMethod;
obj : TFRE_DB_Base;
sfo : IFRE_DB_Object;
method_name : string;
begin
m := TMethod(invoke_method);
obj := (TObject(m.Data) as TFRE_DB_Base);
obj.IntfCast(IFRE_DB_Object,sfo);
method_name := obj.MethodName(m.Code);
if pos('WEB_',method_name)=1 then begin
result := TFRE_DB_SERVER_FUNC_DESC.create.Describe(sfo,Copy(method_name,5,maxint));
end else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'the method named %s does not follow the WEB_* naming convention',[method_name]);
end;
end;
function TFRE_DB_Base.CSCF(const serv_classname, server_function_name: string; const param1: string; const value1: string): TFRE_DB_SERVER_FUNC_DESC;
begin
result := TFRE_DB_SERVER_FUNC_DESC.create.Describe(serv_classname,server_function_name);
if param1<>'' then
result.AddParam.Describe(param1,value1);
end;
function TFRE_DB_ObjectEx.Debug_ID: TFRE_DB_String;
begin
Result := UID_String;
end;
procedure TFRE_DB_ObjectEx.InternalSetup;
begin
end;
procedure TFRE_DB_ObjectEx.InternalFinalize;
begin
end;
procedure TFRE_DB_ObjectEx._InternalSetMediator(const mediator: TFRE_DB_ObjectEx);
begin
raise EFRE_DB_Exception.Create(edb_ERROR,'dont call this');
end;
function TFRE_DB_ObjectEx._InternalDecodeAsField: IFRE_DB_Field;
begin
abort;
end;
function TFRE_DB_ObjectEx.GetDescriptionID(const full_uid_path: boolean): String;
begin
result := FImplementor.GetDescriptionID(full_uid_path);
end;
class procedure TFRE_DB_ObjectEx.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
//Scheme.SetParentSchemeByName('');
Scheme.AddSchemeField('objname',fdbft_String);
Scheme.AddSchemeFieldSubscheme('desc','TFRE_DB_TEXT');
//Scheme.SetSysDisplayField(GFRE_DB.ConstructStringArray(['objname','$DBTEXT:desc']),'%s - (%s)');
scheme.Strict(false);
end;
function TFRE_DB_ObjectEx.Invoke(const method: TFRE_DB_String; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
result := Invoke_DBIMI_Method(method,input,ses,app,conn);
end;
//procedure TFRE_DB_ObjectEx.MyInitialize(const session : TFRE_DB_UserSession);
//begin
//
//end;
class procedure TFRE_DB_Base.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
end;
class procedure TFRE_DB_Base.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
if self.ClassType=TFRE_DB_ObjectEx then
newVersionId := 'BASE'
else
newVersionId := 'UNUSED';
end;
class procedure TFRE_DB_Base.InstallDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
_InstallDBObjects4Domain(conn,currentVersionId,domainUID);
end;
class procedure TFRE_DB_Base.InstallDBObjects4SysDomain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
_InstallDBObjects4Domain(conn,currentVersionId,domainUID);
end;
class procedure TFRE_DB_Base.InstallUserDBObjects(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType);
begin
end;
class procedure TFRE_DB_Base.InstallUserDBObjects4Domain(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_Base.InstallUserDBObjects4SysDomain(const conn: IFRE_DB_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_Base.RemoveDBObjects(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType);
begin
end;
class procedure TFRE_DB_Base.RemoveDBObjects4Domain(const conn: IFRE_DB_SYS_CONNECTION; currentVersionId: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
constructor TFRE_DB_ObjectEx.Create;
begin
CreateBound(GFRE_DBI.NewObject);
end;
constructor TFRE_DB_ObjectEx.CreateBound(const dbo: IFRE_DB_Object);
begin
FImplementor := dbo;
FImplementor._InternalSetMediator(self);
InternalSetup;
end;
destructor TFRE_DB_ObjectEx.Destroy;
begin
//if not FBound then
// begin
// if assigned(FNamedObject) then
// FNamedObject.Finalize;
// end;
inherited Destroy;
end;
destructor TFRE_DB_ObjectEx.DestroyFromBackingDBO;
begin
inherited Destroy;
end;
procedure TFRE_DB_ObjectEx.FreeFromBackingDBO;
begin
DestroyFromBackingDBO;
end;
procedure TFRE_DB_ObjectEx.Free;
begin
if self<>nil then
Finalize;
end;
function TFRE_DB_ObjectEx.GetUCTHashed: Shortstring;
begin
result := FImplementor.GetUCTHashed;
end;
function TFRE_DB_ObjectEx.GetDesc: IFRE_DB_TEXT;
begin
result := FImplementor.GetDesc;
end;
procedure TFRE_DB_ObjectEx.SetDesc(const AValue: IFRE_DB_TEXT);
begin
FImplementor.SetDesc(AValue);
end;
function TFRE_DB_ObjectEx.GetName: TFRE_DB_String;
begin
result := FImplementor.GetName;
end;
procedure TFRE_DB_ObjectEx.SetName(const AValue: TFRE_DB_String);
begin
FImplementor.SetName(AValue);
end;
function TFRE_DB_ObjectEx.UIDP: PByte;
begin
result := FImplementor.UIDP;
end;
function TFRE_DB_ObjectEx.PUID: PFRE_DB_Guid;
begin
result := FImplementor.PUID;
end;
function TFRE_DB_ObjectEx.ObjectRoot: IFRE_DB_Object;
begin
result := FImplementor.ObjectRoot;
end;
procedure TFRE_DB_ObjectEx.ForAllFields(const iter: IFRE_DB_FieldIterator ; const without_system_fields: boolean);
begin
FImplementor.ForAllFields(iter,without_system_fields);
end;
procedure TFRE_DB_ObjectEx.ForAllFieldsBreak(const iter: IFRE_DB_FieldIteratorBrk; const without_system_fields: boolean);
begin
FImplementor.ForAllFieldsBreak(iter,without_system_fields);
end;
procedure TFRE_DB_ObjectEx.ForAllObjects(const iter: IFRE_DB_Obj_Iterator);
begin
FImplementor.ForAllObjects(iter);
end;
procedure TFRE_DB_ObjectEx.ForAllObjectsBreak(const iter: IFRE_DB_ObjectIteratorBrk);
begin
FImplementor.ForAllObjectsBreak(iter);
end;
procedure TFRE_DB_ObjectEx.ForAllObjectsFieldName(const iter: IFRE_DB_Obj_NameIterator);
begin
FImplementor.ForAllObjectsFieldName(iter);
end;
function TFRE_DB_ObjectEx.UID: TFRE_DB_GUID;
begin
result := FImplementor.UID;
end;
function TFRE_DB_ObjectEx.UCT: TFRE_DB_String;
begin
result := FImplementor.UCT;
end;
procedure TFRE_DB_ObjectEx.SetUCT(const tag: TFRE_DB_String);
begin
FImplementor.SetUCT(tag);
end;
procedure TFRE_DB_ObjectEx.SetUID(const guid: TFRE_DB_GUID);
begin
FImplementor.SetUID(guid);
end;
function TFRE_DB_ObjectEx.UID_String: TFRE_DB_GUID_String;
begin
result := FImplementor.UID_String;
end;
function TFRE_DB_ObjectEx.DomainID: TFRE_DB_GUID;
begin
result := FImplementor.DomainID;
end;
procedure TFRE_DB_ObjectEx.SetDomainID(const domid: TFRE_DB_GUID);
begin
FImplementor.SetDomainID(domid);
end;
function TFRE_DB_ObjectEx.Parent: IFRE_DB_Object;
begin
result := FImplementor.Parent;
end;
function TFRE_DB_ObjectEx.ParentField: IFRE_DB_FIELD;
begin
result := FImplementor.ParentField;
end;
function TFRE_DB_ObjectEx.AsString: TFRE_DB_String;
begin
result := FImplementor.AsString;
end;
function TFRE_DB_ObjectEx.Field(const name: TFRE_DB_NameType): IFRE_DB_FIELD;
begin
result := FImplementor.Field(name);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingObj(const name: TFRE_DB_NameType): IFRE_DB_Object;
begin
result := FImplementor.FieldOnlyExistingObj(name);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingObject(const name: TFRE_DB_NameType; var obj: IFRE_DB_Object): boolean;
begin
result := FImplementor.FieldOnlyExistingObject(name,obj);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingObjAs(const name: TFRE_DB_NameType; const classref: TFRE_DB_BaseClass; var outobj): boolean;
begin
result := FImplementor.FieldOnlyExistingObjAs(name,classref,outobj);
end;
function TFRE_DB_ObjectEx.FieldOnlyExisting(const name: TFRE_DB_NameType; var fld: IFRE_DB_FIELD): boolean;
begin
result := FImplementor.FieldOnlyExisting(name,fld);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingUID(const name: TFRE_DB_NameType; const def: PFRE_DB_GUID): TFRE_DB_GUID;
begin
result := FImplementor.FieldOnlyExistingUID(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingByte(const name: TFRE_DB_NameType; const def: Byte): Byte;
begin
result := FImplementor.FieldOnlyExistingByte(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingInt16(const name: TFRE_DB_NameType; const def: Int16): Int16;
begin
result := FImplementor.FieldOnlyExistingInt16(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingUInt16(const name: TFRE_DB_NameType; const def: UInt16): UInt16;
begin
result := FImplementor.FieldOnlyExistingUInt16(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingInt32(const name: TFRE_DB_NameType; const def: Int32): Int32;
begin
result := FImplementor.FieldOnlyExistingInt32(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingUInt32(const name: TFRE_DB_NameType; const def: UInt32): UInt32;
begin
result := FImplementor.FieldOnlyExistingUInt32(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingInt64(const name: TFRE_DB_NameType; const def: Int64): Int64;
begin
result := FImplementor.FieldOnlyExistingInt64(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingUInt64(const name: TFRE_DB_NameType; const def: UInt64): UInt64;
begin
result := FImplementor.FieldOnlyExistingUInt64(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingReal32(const name: TFRE_DB_NameType; const def: Single): Single;
begin
result := FImplementor.FieldOnlyExistingReal32(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingReal64(const name: TFRE_DB_NameType; const def: Double): Double;
begin
result := FImplementor.FieldOnlyExistingReal64(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingCurrency(const name: TFRE_DB_NameType; const def: Currency): Currency;
begin
result := FImplementor.FieldOnlyExistingCurrency(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingString(const name: TFRE_DB_NameType; const def: String): String;
begin
result := FImplementor.FieldOnlyExistingString(name,def);
end;
function TFRE_DB_ObjectEx.FieldOnlyExistingBoolean(const name: TFRE_DB_NameType; const def: Boolean): Boolean;
begin
result := FImplementor.FieldOnlyExistingBoolean(name,def);
end;
function TFRE_DB_ObjectEx.FieldPath(const name: TFRE_DB_String; const dont_raise_ex: boolean): IFRE_DB_FIELD;
begin
result := FImplementor.FieldPath(name,dont_raise_ex);
end;
function TFRE_DB_ObjectEx.FieldPathCreate(const name: TFRE_DB_String): IFRE_DB_FIELD;
begin
result := FImplementor.FieldPathCreate(name);
end;
function TFRE_DB_ObjectEx.FieldPathExists(const name: TFRE_DB_String): Boolean;
begin
result := FImplementor.FieldPathExists(name);
end;
function TFRE_DB_ObjectEx.FieldPathExists(const name: TFRE_DB_String; out fld: IFRE_DB_Field): Boolean;
begin
result := FImplementor.FieldPathExists(name,fld);
end;
function TFRE_DB_ObjectEx.FieldPathExistsAndNotMarkedClear(const name: TFRE_DB_String): Boolean;
begin
result := FImplementor.FieldPathExistsAndNotMarkedClear(name);
end;
function TFRE_DB_ObjectEx.FieldPathExistsAndNotMarkedClear(const name: TFRE_DB_String; out fld: IFRE_DB_Field): Boolean;
begin
result := FImplementor.FieldPathExistsAndNotMarkedClear(name,fld);
end;
function TFRE_DB_ObjectEx.FieldPathListFormat(const field_list: TFRE_DB_NameTypeArray; const formats: TFRE_DB_String; const empty_val: TFRE_DB_String): TFRE_DB_String;
begin
result := FImplementor.FieldPathListFormat(field_list,formats,empty_val);
end;
function TFRE_DB_ObjectEx.FieldCount(const without_system_fields: boolean): SizeInt;
begin
result := FImplementor.FieldCount(without_system_fields);
end;
function TFRE_DB_ObjectEx.DeleteField(const name: TFRE_DB_String): Boolean;
begin
result := FImplementor.DeleteField(name);
end;
procedure TFRE_DB_ObjectEx.ClearAllFields;
begin
FImplementor.ClearAllFields;
end;
procedure TFRE_DB_ObjectEx.ClearAllFieldsExcept(const fieldnames: array of TFRE_DB_NameType);
begin
FImplementor.ClearAllFieldsExcept(fieldnames);
end;
function TFRE_DB_ObjectEx.FieldExists(const name: TFRE_DB_String): boolean;
begin
result := FImplementor.FieldExists(name);
end;
function TFRE_DB_ObjectEx.FieldExistsAndNotMarkedClear(const name: TFRE_DB_String): boolean;
begin
result := FImplementor.FieldExistsAndNotMarkedClear(name);
end;
procedure TFRE_DB_ObjectEx.DumpToStrings(const strings: TStrings; indent: integer);
begin
FImplementor.DumpToStrings(strings,indent);
end;
function TFRE_DB_ObjectEx.DumpToString(indent: integer; const dump_length_max: Integer): TFRE_DB_String;
begin
result := FImplementor.DumpToString(indent,dump_length_max);
end;
function TFRE_DB_ObjectEx.GetFormattedDisplay: TFRE_DB_String;
begin
result := FImplementor.GetFormattedDisplay;
end;
function TFRE_DB_ObjectEx.FormattedDisplayAvailable: boolean;
begin
result := FImplementor.FormattedDisplayAvailable;
end;
function TFRE_DB_ObjectEx.SubFormattedDisplayAvailable: boolean;
begin
result := FImplementor.SubFormattedDisplayAvailable;
end;
function TFRE_DB_ObjectEx.GetSubFormattedDisplay(indent: integer): TFRE_DB_String;
begin
result := FImplementor.GetSubFormattedDisplay(indent);
end;
function TFRE_DB_ObjectEx.SchemeClass: TFRE_DB_NameType;
begin
result := Classname;
end;
function TFRE_DB_ObjectEx.IsA(const schemename: shortstring): Boolean;
begin
result := FImplementor.IsA(schemename);
end;
function TFRE_DB_ObjectEx.IsA(const IsSchemeclass: TFRE_DB_OBJECTCLASSEX): Boolean;
begin
FImplementor.IsA(IsSchemeclass);
end;
function TFRE_DB_ObjectEx.IsA(const IsSchemeclass: TFRE_DB_OBJECTCLASSEX; out obj): Boolean;
begin
result := FImplementor.IsA(IsSchemeclass,obj);
end;
procedure TFRE_DB_ObjectEx.AsClass(const IsSchemeclass: TFRE_DB_OBJECTCLASSEX; out obj);
begin
FImplementor.AsClass(IsSchemeclass,obj);
end;
function TFRE_DB_ObjectEx.IsObjectRoot: Boolean;
begin
result := FImplementor.IsObjectRoot;
end;
function TFRE_DB_ObjectEx.IsPluginContainer: Boolean;
begin
result := FImplementor.IsPluginContainer;
end;
function TFRE_DB_ObjectEx.IsPlugin: Boolean;
begin
result := FImplementor.IsPluginContainer;
end;
procedure TFRE_DB_ObjectEx.SaveToFile(const filename: TFRE_DB_String);
begin
FImplementor.SaveToFile(filename);
end;
procedure TFRE_DB_ObjectEx.SaveToFileHandle(const handle: THandle);
begin
FImplementor.SaveToFileHandle(handle);
end;
function TFRE_DB_ObjectEx.ReferencesObjectsFromData: Boolean;
begin
result := FImplementor.ReferencesObjectsFromData;
end;
function TFRE_DB_ObjectEx.ForAllObjectsBreakHierarchic(const iter: IFRE_DB_ObjectIteratorBrk): boolean;
begin
result := FImplementor.ForAllObjectsBreakHierarchic(iter);
end;
function TFRE_DB_ObjectEx.FetchObjByUID(const childuid: TFRE_DB_GUID; var obj: IFRE_DB_Object): boolean;
begin
result := FImplementor.FetchObjByUID(childuid,obj);
end;
function TFRE_DB_ObjectEx.FetchObjWithStringFieldValue(const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; var obj: IFRE_DB_Object; ClassnameToMatch: ShortString): boolean;
begin
result := Fimplementor.FetchObjWithStringFieldValue(field_name,fieldvalue,obj,ClassnameToMatch);
end;
function TFRE_DB_ObjectEx.FetchObjWithStringFieldValueAs(const field_name: TFRE_DB_NameType; const fieldvalue: TFRE_DB_String; const exclasstyp: TFRE_DB_ObjectClassEx; var obj): boolean;
begin
result := FImplementor.FetchObjWithStringFieldValueAs(field_name,fieldvalue,exclasstyp,obj);
end;
procedure TFRE_DB_ObjectEx.SetAllSimpleObjectFieldsFromObject(const source_object: IFRE_DB_Object);
begin
FImplementor.SetAllSimpleObjectFieldsFromObject(source_object);
end;
function TFRE_DB_ObjectEx.GetFieldListFilter(const field_type: TFRE_DB_FIELDTYPE): TFRE_DB_StringArray;
begin
result := FImplementor.GetFieldListFilter(field_type);
end;
function TFRE_DB_ObjectEx.GetUIDPath: TFRE_DB_StringArray;
begin
result := FImplementor.GetUIDPath;
end;
function TFRE_DB_ObjectEx.GetUIDPathUA: TFRE_DB_GUIDArray;
begin
result := FImplementor.GetUIDPathUA;
end;
function TFRE_DB_ObjectEx.GetFieldValuePathString(const fieldname: TFRE_DB_NameType): TFRE_DB_StringArray;
begin
result := FImplementor.GetFieldValuePathString(fieldname);
end;
function TFRE_DB_ObjectEx.Implementor: TObject;
begin
result := FImplementor.Implementor; // THE DBO - not the own mediator class.
end;
function TFRE_DB_ObjectEx.Implementor_HC: TObject;
begin
result := self;
end;
function TFRE_DB_ObjectEx.Supports(const InterfaceSpec: ShortString; out Intf): boolean;
begin
result := FImplementor.Supports(InterfaceSpec,intf);
end;
function TFRE_DB_ObjectEx.Supports(const InterfaceSpec: ShortString): boolean;
begin
result := FImplementor.Supports(InterfaceSpec);
end;
procedure TFRE_DB_ObjectEx.IntfCast(const InterfaceSpec: ShortString; out Intf);
begin
FImplementor.IntfCast(InterfaceSpec,intf);
end;
function TFRE_DB_ObjectEx.IntfCast(const InterfaceSpec: ShortString): Pointer;
begin
IntfCast(InterfaceSpec,result);
end;
function TFRE_DB_ObjectEx.GetScheme(const raise_non_existing: boolean): IFRE_DB_SchemeObject;
begin
result := FImplementor.GetScheme(raise_non_existing);
end;
procedure TFRE_DB_ObjectEx.Finalize;
begin
//writeln('FINALIZE MEDIATOR CALL ',ClassName);
FImplementor.Finalize;
end;
function TFRE_DB_ObjectEx.GetAsJSON(const without_uid: boolean;const full_dump:boolean=false;const stream_cb:TFRE_DB_StreamingCallback=nil): TJSONData;
begin
result := FImplementor.GetAsJSON(without_uid,full_dump,stream_cb);
end;
function TFRE_DB_ObjectEx.GetAsJSONString(const without_reserved_fields: boolean; const full_dump: boolean; const stream_cb: TFRE_DB_StreamingCallback; const pretty: boolean): TFRE_DB_String;
begin
result := FImplementor.GetAsJSONString(without_reserved_fields,full_dump,stream_cb,pretty);
end;
function TFRE_DB_ObjectEx.CloneToNewObject(const generate_new_uids:boolean): IFRE_DB_Object;
begin
result := FImplementor.CloneToNewObject(generate_new_uids)
end;
function TFRE_DB_ObjectEx.Mediator: TFRE_DB_ObjectEx;
begin
result := FImplementor.Mediator;
end;
function TFRE_DB_ObjectEx.NeededSize: TFRE_DB_SIZE_TYPE;
begin
result := FImplementor.NeededSize;
end;
procedure TFRE_DB_ObjectEx.Set_ReadOnly;
begin
FImplementor.Set_ReadOnly;
end;
procedure TFRE_DB_ObjectEx.CopyField(const obj: IFRE_DB_Object; const field_name: String);
begin
FImplementor.CopyField(obj,field_name);
end;
class function TFRE_DB_ObjectEx.NewOperation(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_GUID;
var dbo : IFRE_DB_Object;
data : IFRE_DB_Object;
lSchemeclass : TFRE_DB_String;
lSchemeObject : IFRE_DB_SchemeObject;
lTransformScheme : TFRE_DB_String;
lCollectionName : TFRE_DB_String;
res : TFRE_DB_Errortype;
dbo_uid : TFRE_DB_GUID;
//dbc : IFRE_DB_CONNECTION;
begin
data := input.Field('DATA').asobject;
lCollectionName := input.field('COLLECTION').AsString;
lSchemeclass := ClassName;
if lSchemeclass ='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'the new operation requires a schemeclass!');
if lCollectionName='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'the new operation requires a collection!');
//dbc := input.GetReference as IFRE_DB_CONNECTION;
if not conn.CollectionExists(lCollectionName) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the collection [%s] is unknown and the implicit creation of collection is not allowed on new!',[lCollectionName]);
if not GFRE_DBI.GetSystemSchemeByName(lSchemeclass,lSchemeObject) then
raise EFRE_DB_Exception.Create(edb_ERROR,'the scheme [%s] is unknown!',[lSchemeclass]);
dbo := GFRE_DBI.NewObjectSchemeByName(lSchemeclass);
lSchemeObject.SetObjectFieldsWithScheme(data,dbo,true,conn);
dbo_uid := dbo.UID;
if lCollectionName='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'standard new operation requires a collection!')
else
CheckDbResult(conn.GetCollection(lCollectionName).Store(dbo),'failure on store/new collection='+lCollectionName);
result := dbo_uid;
end;
constructor TFRE_DB_ObjectEx.CreateForDB;
var scheme : IFRE_DB_SCHEMEOBJECT;
begin
if not GFRE_DBI.GetSystemScheme(ClassType,scheme) then
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'the hardcodeclass [%s] was not found in schemes, maybe not registered ?',[ClassName]);
Create;
end;
procedure TFRE_DB_ObjectEx.CopyToMemory(memory: Pointer);
begin
FImplementor.CopyToMemory(memory);
end;
class procedure TFRE_DB_ObjectEx.StoreTranslateableText(const conn: IFRE_DB_SYS_CONNECTION; const key: TFRE_DB_NameType; const short_text: TFRE_DB_String; const long_text: TFRE_DB_String; const hint_text: TFRE_DB_String);
begin
CheckDbResult(conn.StoreTranslateableText(GFRE_DBI.CreateText(GetTranslateableTextKey(key),short_text,long_text,hint_text)));
end;
class procedure TFRE_DB_ObjectEx.DeleteTranslateableText(const conn: IFRE_DB_SYS_CONNECTION; const key: TFRE_DB_NameType);
begin
CheckDbResult(conn.DeleteTranslateableText(GetTranslateableTextKey(key)));
end;
class function TFRE_DB_ObjectEx.GetTranslateableTextKey(const key: TFRE_DB_NameType): TFRE_DB_String;
begin
Result:='$'+ClassName+'_'+key;
end;
class function TFRE_DB_ObjectEx.GetTranslateableTextShort(const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType): TFRE_DB_String;
begin
Result:=conn.FetchTranslateableTextShort(GetTranslateableTextKey(key));
end;
class function TFRE_DB_ObjectEx.GetTranslateableTextLong(const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType): TFRE_DB_String;
begin
Result:=conn.FetchTranslateableTextLong(GetTranslateableTextKey(key));
end;
class function TFRE_DB_ObjectEx.GetTranslateableTextHint(const conn: IFRE_DB_CONNECTION; const key: TFRE_DB_NameType): TFRE_DB_String;
begin
Result:=conn.FetchTranslateableTextHint(GetTranslateableTextKey(key));
end;
function TFRE_DB_ObjectEx.CloneToNewObjectWithoutSubobjects(const generate_new_uids: boolean): IFRE_DB_Object;
begin
result := FImplementor.CloneToNewObjectWithoutSubobjects(generate_new_uids);
end;
procedure TFRE_DB_ObjectEx.SetGenericUCTTags(const check_unique_tagging: boolean);
begin
FImplementor.SetGenericUCTTags(check_unique_tagging);
end;
function TFRE_DB_ObjectEx.HasPlugin(const pluginclass: TFRE_DB_OBJECT_PLUGIN_CLASS): boolean;
begin
result := FImplementor.HasPlugin(pluginclass);
end;
function TFRE_DB_ObjectEx.HasPlugin(const pluginclass: TFRE_DB_OBJECT_PLUGIN_CLASS; out plugin): boolean;
begin
result := FImplementor.HasPlugin(pluginclass,plugin);
end;
procedure TFRE_DB_ObjectEx.GetPlugin(const pluginclass: TFRE_DB_OBJECT_PLUGIN_CLASS; out plugin);
begin
FImplementor.GetPlugin(pluginclass,plugin);
end;
function TFRE_DB_ObjectEx.GetStatusPlugin: TFRE_DB_STATUS_PLUGIN;
begin
result := FImplementor.GetStatusPlugin;
end;
function TFRE_DB_ObjectEx.AttachPlugin(const plugin: TFRE_DB_OBJECT_PLUGIN_BASE; const raise_if_existing: boolean): Boolean;
begin
FImplementor.AttachPlugin(plugin,raise_if_existing);
end;
procedure TFRE_DB_ObjectEx.ForAllPlugins(const plugin_iterator: IFRE_DB_PLUGIN_ITERATOR);
begin
FImplementor.ForAllPlugins(plugin_iterator);
end;
function TFRE_DB_ObjectEx.RemovePlugin(const pluginclass: TFRE_DB_OBJECT_PLUGIN_CLASS; const raise_if_not_existing: boolean): Boolean;
begin
result := FImplementor.RemovePlugin(pluginclass,raise_if_not_existing);
end;
procedure TFRE_DB_ObjectEx.CheckoutFromObject;
begin
FImplementor.CheckoutFromObject;
end;
function TFRE_DB_ObjectEx.GetInstanceRight(const right: TFRE_DB_NameType): IFRE_DB_RIGHT;
begin
Result := '$'+uppercase(UID_String+'_'+right);
end;
//My instance gets freed on function termination (fetch, invoke method, free) tus we need to change our copy and feed the uptade with the copy of us.
function TFRE_DB_ObjectEx.WEB_SaveOperation(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var scheme : IFRE_DB_SCHEMEOBJECT;
raw_object : IFRE_DB_Object;
begin
if not conn.sys.CheckClassRight4Domain(sr_UPDATE,Self.ClassType,ses.GetDomain) then
raise EFRE_DB_Exception.Create('Access denied.');
if Not IsObjectRoot then begin
result := TFRE_DB_MESSAGE_DESC.Create.Describe('SAVE','Error on saving! Saving of Subobject not supported!',fdbmt_error);
exit;
end;
result := nil;
scheme := GetScheme;
raw_object := input.Field('data').AsObject;
//writeln('SAVEOP----------RAW OBJECT---------');
//writeln(raw_object.DumpToString);
//writeln('----------RAW OBJECT---------');
scheme.SetObjectFieldsWithScheme(raw_object,self,false,conn);
CheckDbResult(conn.Update(self.CloneToNewObject()),'failure on update'); // This instance is freed by now, so rely on the stackframe only (self) pointer is garbage(!!)
result := TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe();
end;
function TFRE_DB_ObjectEx.WEB_DeleteOperation(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var db_res : TFRE_DB_Errortype;
begin
case input.Field('confirmed').AsString of
'true': begin
if not IsObjectRoot then begin
result := TFRE_DB_MESSAGE_DESC.Create.Describe('DELETE','Error on deleting! Deleting of Subobject not supported!',fdbmt_error);
end;
db_res := conn.Delete(UID);
if db_res=edb_OK then begin
result := GFRE_DB_NIL_DESC;
end else begin
raise EFRE_DB_Exception.Create(db_res,'delete of [%s] failed!',[UID_String]);
end;
end;
'false': begin
result:=GFRE_DB_NIL_DESC;
end;
'': begin
result := TFRE_DB_MESSAGE_DESC.create.Describe('Delete','Are you sure?',fdbmt_confirm,CWSF(@self.WEB_DeleteOperation));
end;
end;
end;
class function TFRE_DB_ObjectEx.WBC_NewOperation(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
try
NewOperation(input,ses,app,conn);
result := TFRE_DB_CLOSE_DIALOG_DESC.Create.Describe();
except
on E:Exception do begin
result := TFRE_DB_MESSAGE_DESC.Create.Describe('NEW','Error on creating object ['+e.Message+']',fdbmt_error);
end;
end;
end;
function TFRE_DB_ObjectEx.WEB_NoteLoad(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var noteobj: IFRE_DB_Object;
begin
if input.FieldExists('linkid') then begin
if conn.GetNotesCollection.GetIndexedObj(input.Field('linkid').asstring,noteobj) then begin
exit(TFRE_DB_EDITOR_DATA_DESC.create.Describe(noteobj.Field('note').asstring));
end else begin
exit(TFRE_DB_EDITOR_DATA_DESC.create.Describe(''));
end;
end else begin
exit(TFRE_DB_EDITOR_DATA_DESC.create.Describe(''));
end;
end;
function TFRE_DB_ObjectEx.WEB_NoteSave(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var
noteobj: IFRE_DB_Object;
res : TFRE_DB_Errortype;
begin
if input.FieldExists('linkid') then begin
if conn.GetNotesCollection.GetIndexedObj(input.Field('linkid').asstring,noteobj) then begin
noteobj.Field('note').asstring := input.Field('content').asstring;
res := conn.Update(noteobj);
if res<>edb_OK then
raise EFRE_DB_Exception.Create(res,'error updating note');
end else begin
noteobj := GFRE_DBI.NewObjectScheme(TFRE_DB_NOTE);
noteobj.Field('link').asstring:=input.Field('linkid').asstring;
noteobj.Field('note').asstring := input.Field('content').asstring;
res := conn.GetNotesCollection.Store(noteobj);
if res<>edb_OK then
raise EFRE_DB_Exception.Create(res,'error storing note');
end;
end;
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_DB_ObjectEx.WEB_NoteStartEdit(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=GFRE_DB_NIL_DESC;
end;
function TFRE_DB_ObjectEx.WEB_NoteStopEdit(const input:IFRE_DB_Object ; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
Result:=GFRE_DB_NIL_DESC;
end;
{ EFRE_DB_Exception }
constructor EFRE_DB_Exception.Create(const msg: TFRE_DB_String);
begin
Create(edb_ERROR,msg);
end;
constructor EFRE_DB_Exception.Create(const et: TFRE_DB_Errortype_EC; msg: TFRE_DB_String);
begin
ErrorType.Code := et;
ErrorType.Msg := msg;
if (et<low(TFRE_DB_Errortype_EC)) or (et>High(TFRE_DB_Errortype_EC)) then begin
GFRE_BT.CriticalAbort('internal fault - EDB Exception Range Check');
end;
case et of
edb_INTERNAL: msg := 'DB INTERNAL FAULT : '+msg+' ';
else msg := '('+CFRE_DB_Errortype[et]+') '+msg;
end;
if assigned(GFRE_DBI) then
GFRE_DBI.LogError(dblc_EXCEPTION,msg+LineEnding+GFRE_BT.DumpExceptionsBacktrace);
inherited create(msg);
end;
constructor EFRE_DB_Exception.Create(const et: TFRE_DB_Errortype_EC; msg: TFRE_DB_String; params: array of const);
begin
Create(et,Format(msg,params));
end;
function TFRE_DB_CONTENT_DESC.GetContentId: TFRE_DB_String;
begin
Result:=Field('id').AsString;
end;
function TFRE_DB_CONTENT_DESC.GetUpdateId: TFRE_DB_String;
begin
Result:=Field('updateId').AsString;
end;
function TFRE_DB_CONTENT_DESC.GetWindowCaption: TFRE_DB_String;
begin
Result:=Field('windowCaption').AsString;
end;
procedure TFRE_DB_CONTENT_DESC.SetContentId(AValue: TFRE_DB_String);
begin
Field('id').AsString:=AValue;
Field('destroyNotify').AsBoolean:=true;
end;
procedure TFRE_DB_CONTENT_DESC.SetUpdateId(AValue: TFRE_DB_String);
begin
Field('updateId').AsString:=AValue;
end;
procedure TFRE_DB_CONTENT_DESC.SetWindowCaption(AValue: TFRE_DB_String);
begin
Field('windowCaption').AsString:=AValue;
end;
function TFRE_DB_PARAM_DESC.Describe(const key, value: string): TFRE_DB_PARAM_DESC;
begin
Field('key').AsString:=key;
Field('value').AsString:=value;
Field('asArray').AsBoolean:=false;
Result:=Self;
end;
function TFRE_DB_PARAM_DESC.Describe(const key: String; const value: TFRE_DB_StringArray): TFRE_DB_PARAM_DESC;
begin
Field('key').AsString:=key;
Field('value').AsStringArr:=value;
Field('asArray').AsBoolean:=true;
Result:=Self;
end;
{ TFRE_DB_SERVER_FUNC_DESC }
function TFRE_DB_SERVER_FUNC_DESC.Describe(const obj: IFRE_DB_Object; const func: String): TFRE_DB_SERVER_FUNC_DESC;
begin
Result := Describe(obj.SchemeClass,obj.GetUIDPath,func);
end;
function TFRE_DB_SERVER_FUNC_DESC.Describe(const oschemeclass: String; const ouid: TFRE_DB_GUID; const func: String): TFRE_DB_SERVER_FUNC_DESC;
begin
result := Describe(oschemeclass,TFRE_DB_StringArray.Create(FREDB_G2H(ouid)),func);
end;
function TFRE_DB_SERVER_FUNC_DESC.Describe(const oschemeclass: String; const uidpath: TFRE_DB_StringArray; const func: String): TFRE_DB_SERVER_FUNC_DESC;
var
path : String;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('class').AsString:=oschemeclass;
Field('func').AsString:=func;
Field('uidPath').AsStringArr:=uidpath;
Result:=Self;
end;
function TFRE_DB_SERVER_FUNC_DESC.Describe(const oschemeclass: String; const func: String): TFRE_DB_SERVER_FUNC_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('class').AsString := oschemeclass;
Field('func').AsString := func;
Result:=Self;
end;
function TFRE_DB_SERVER_FUNC_DESC.InternalInvoke(const session: TFRE_DB_UserSession): IFRE_DB_Object;
var
i : Integer;
key,value: String;
newInput : IFRE_DB_Object;
begin
newInput:=GFRE_DBI.NewObject;
for i := 0 to Field('params').ValueCount - 1 do begin
key:=Field('params').AsObjectArr[i].Field('key').AsString;
value:=Field('params').AsObjectArr[i].Field('value').AsString;
newInput.Field(key).AsString:=value;
end;
result:=session.InternalSessInvokeMethod(Field('class').AsString,Field('func').AsString,GFRE_DBI.StringArray2GuidArray(Field('uidPath').AsStringArr),newInput);
end;
function TFRE_DB_SERVER_FUNC_DESC.InternalInvokeDI(const session: TFRE_DB_UserSession; const input: IFRE_DB_OBJECT): IFRE_DB_Object;
var inp : IFRE_DB_Object;
begin
inp := input;
result:=session.InternalSessInvokeMethod(Field('class').AsString,Field('func').AsString,GFRE_DBI.StringArray2GuidArray(Field('uidPath').AsStringArr),inp);
end;
function TFRE_DB_SERVER_FUNC_DESC.AddParam: TFRE_DB_PARAM_DESC;
begin
Result:=TFRE_DB_PARAM_DESC.Create;
Field('params').AddObject(Result);
end;
function TFRE_DB_SERVER_FUNC_DESC.hasParam: Boolean;
begin
Result:=FieldExists('params');
end;
function TFRE_DB_APPLICATION.GetSitemapMainiconFilename: string;
begin
result := Field('sm_mainicon_fn').asstring;
end;
function TFRE_DB_APPLICATION.GetSitemapMainiconSubpath: string;
begin
result := Field('sm_icon_path').asstring;
end;
procedure TFRE_DB_APPLICATION.SetDescTranslationKey(const AValue: TFRE_DB_String);
begin
Field('desc_tkey').AsString:=AValue;
end;
function TFRE_DB_APPLICATION.GetDescTranslationKey: TFRE_DB_String;
begin
result := Field('desc_tkey').AsString;
end;
procedure TFRE_DB_APPLICATION.ServerInitialize(const admin_dbc: IFRE_DB_CONNECTION);
procedure _initSubModules(const field: IFRE_DB_FIELD);
var app_module : TFRE_DB_APPLICATION_MODULE;
io : IFRE_DB_Object;
begin
if (field.FieldType=fdbft_Object) and field.AsObject.Supports(IFRE_DB_APPLICATION_MODULE) then begin
(field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE).MyServerInitializeModule(admin_dbc);
end;
end;
begin
MyServerInitialize(admin_dbc);
ForAllFields(@_initSubModules);
end;
procedure TFRE_DB_APPLICATION.ServerFinalize(const admin_dbc: IFRE_DB_CONNECTION);
begin
MyServerFinalize;
end;
procedure TFRE_DB_APPLICATION.InternalSetup;
begin
inherited InternalSetup;
SetupApplicationStructure;
end;
procedure TFRE_DB_APPLICATION.InitApp(const descr_translation_key: TFRE_DB_String; const icon: TFRE_DB_String);
begin
SetDescTranslationKey(descr_translation_key);
Field('icon').AsString:=icon;
end;
function TFRE_DB_APPLICATION.AsObject: IFRE_DB_Object;
begin
result := FImplementor;
end;
function TFRE_DB_APPLICATION.AppClassName: ShortString;
begin
result := ClassName;
end;
function TFRE_DB_APPLICATION.IsMultiDomainApp: Boolean;
begin
Result:=false;
end;
function TFRE_DB_APPLICATION.GetCaption(const ses: IFRE_DB_Usersession): TFRE_DB_String;
begin
result := FetchAppTextShort(ses,'caption');
end;
function TFRE_DB_APPLICATION.GetIcon: TFRE_DB_String;
begin
Result := Field('icon').AsString;
end;
procedure TFRE_DB_APPLICATION.SessionInitialize(const session: TFRE_DB_UserSession);
function _initSubModules(const field: IFRE_DB_FIELD):boolean;
var module : TFRE_DB_APPLICATION_MODULE;
begin
result := false;
if (field.FieldType=fdbft_Object) and field.AsObject.Supports(IFRE_DB_APPLICATION_MODULE) then
begin
try
module := field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE;
if not session.GetModuleInitialized(module.ClassName) then
begin
try
(field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE).MySessionInitializeModule(session);
finally
session.SetModuleInitialized(module.ClassName);
end;
end;
except
on e:Exception do
begin
GFRE_DBI.LogError(dblc_SESSION,'APP/MODULE SESSION INITIALIZATION FAILED SESS(%s) %s : %s ',[session.GetSessionID,classname,e.Message]);
end;
end;
end;
end;
begin
ForAllFieldsBreak(@_initSubModules); //init modules first cause app might call module functions during init
MySessionInitialize(session);
end;
procedure TFRE_DB_APPLICATION.SessionFinalize(const session: TFRE_DB_UserSession);
procedure _FinishSubModules(const field: IFRE_DB_FIELD);
var app_module : TFRE_DB_APPLICATION_MODULE;
begin
if (field.FieldType=fdbft_Object) and field.AsObject.Supports(IFRE_DB_APPLICATION_MODULE) then
(field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE).MySessionFinalizeModule(session);
end;
begin
ForAllFields(@_FinishSubmodules);
MySessionFinalize(session);
end;
procedure TFRE_DB_APPLICATION.SessionPromotion(const session: TFRE_DB_UserSession);
function _initSubModules(const field: IFRE_DB_FIELD):boolean;
var app_module : TFRE_DB_APPLICATION_MODULE;
begin
result:=false;
if (field.FieldType=fdbft_Object) and field.AsObject.Supports(IFRE_DB_APPLICATION_MODULE) then
(field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE).MySessionPromotionModule(session);
end;
begin
MySessionPromotion(session);
ForAllFieldsBreak(@_initSubModules);
end;
procedure TFRE_DB_APPLICATION.SetSitemapMainiconFilename(AValue: string);
begin
Field('sm_mainicon_fn').asstring := AValue;
end;
procedure TFRE_DB_APPLICATION.SetSitemapMainiconSubpath(AValue: string);
begin
Field('sm_icon_path').asstring:=AValue;
end;
class procedure TFRE_DB_APPLICATION.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='UNUSED';
end;
function TFRE_DB_APPLICATION.IsContentUpdateVisible(const session: IFRE_DB_UserSession; const update_content_id: string): Boolean;
begin
Result:=session.isUpdatableContentVisible(update_content_id);
end;
procedure TFRE_DB_APPLICATION.SetupApplicationStructure;
begin
end;
class procedure TFRE_DB_APPLICATION.EnableFeature4Domain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION.EnableFeature4SysDomain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION.DisableFeature4Domain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION.DisableFeature4SysDomain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION.CreateAppText(const conn: IFRE_DB_SYS_CONNECTION;const translation_key: TFRE_DB_String; const short_text: TFRE_DB_String; const long_text: TFRE_DB_String; const hint_text: TFRE_DB_String);
var txt :IFRE_DB_TEXT;
begin
txt := GFRE_DBI.NewText('$'+uppercase(classname)+'_'+translation_key,long_text,short_text,hint_text);
CheckDbResult(conn.StoreTranslateableText(txt),'CreateAppText ' + translation_key);
end;
class procedure TFRE_DB_APPLICATION.DeleteAppText(const conn: IFRE_DB_SYS_CONNECTION; const translation_key: TFRE_DB_String);
begin
CheckDbResult(conn.DeleteTranslateableText('$'+uppercase(classname)+'_'+translation_key),'DeleteAppText ' + translation_key);
end;
class procedure TFRE_DB_APPLICATION.UpdateAppText(const conn: IFRE_DB_SYS_CONNECTION; const translation_key: TFRE_DB_String; const short_text: TFRE_DB_String; const long_text: TFRE_DB_String; const hint_text: TFRE_DB_String);
var txt :IFRE_DB_TEXT;
begin
txt := GFRE_DBI.NewText('$'+uppercase(classname)+'_'+translation_key,long_text,short_text,hint_text);
CheckDbResult(conn.UpdateTranslateableText(txt),'UpdateAppText ' + translation_key);
end;
class function TFRE_DB_APPLICATION.StdSidebarCaptionKey: TFRE_DB_String;
begin
result := 'caption';
end;
class function TFRE_DB_APPLICATION.StdSitemapCaptionKey: TFRE_DB_String;
begin
result := 'sitemap_main';
end;
function TFRE_DB_APPLICATION._FetchAppText(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): IFRE_DB_TEXT;
begin
if not session.GetDBConnection.FetchTranslateableTextOBJ('$'+uppercase(classname)+'_'+translation_key,result) then
begin
Result := GFRE_DBI.CreateText('notfound',translation_key+'_short',translation_key+'_long',translation_key+'_is_missing!');
end;
end;
procedure TFRE_DB_APPLICATION.AddApplicationModule(const module: TFRE_DB_APPLICATION_MODULE; const sitemap_key: string; const icon_path: string);
var FSubmoduleOrder : Integer;
begin
Field(module.GetModuleClassName).AsObject := module;
if FieldExists('SubModuleOrder') then begin
FSubmoduleOrder:=Field('SubModuleOrder').AsInt32;
inc(FSubModuleOrder);
end else begin
FSubModuleOrder:=1;
end;
Field('SubModuleOrder').AsInt32 := FSubmoduleOrder;
Field(module.GetModuleClassName+'_O').AsInt16:=FSubModuleOrder;
Field(module.GetModuleClassName+'_IFN').AsString:=icon_path;
end;
function TFRE_DB_APPLICATION.DelegateInvoke(const modulename: TFRE_DB_String; const methname: string; const input: IFRE_DB_Object): IFRE_DB_Object;
begin
if FieldExists(modulename) then begin
result := Field(modulename).AsObject.Invoke(methname,input,nil,self,nil);
end else begin
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'DelegateInvoke: Module [%s] not found!',[modulename]);
end;
end;
procedure TFRE_DB_APPLICATION.MySessionInitialize(const session: TFRE_DB_UserSession);
begin
if session.IsInteractiveSession then begin
MyUpdateSitemap(session);
end;
end;
procedure TFRE_DB_APPLICATION.MySessionPromotion(const session: TFRE_DB_UserSession);
begin
if session.IsInteractiveSession then begin
MyUpdateSitemap(session);
end;
end;
procedure TFRE_DB_APPLICATION.MySessionFinalize(const session: TFRE_DB_UserSession);
begin
end;
procedure TFRE_DB_APPLICATION.MyServerInitialize(const admin_dbc: IFRE_DB_CONNECTION);
begin
end;
procedure TFRE_DB_APPLICATION.MyUpdateSitemap(const session: TFRE_DB_UserSession);
var
SiteMapData : IFRE_DB_Object;
conn : IFRE_DB_CONNECTION;
moduleclasspath : TFRE_DB_String;
keypath : TFRE_DB_String;
procedure BuildSiteMap(const module:IFRE_DB_APPLICATION_MODULE;const module_order:nativeint);
var
modulename : shortstring;
moduleclass : shortstring;
modl : TFRE_DB_APPLICATION_MODULE;
mymoduleclasspath : TFRE_DB_String;
oldkeypath : TFRE_DB_String;
oldmoduleclasspath : TFRE_DB_String;
begin
modl := module.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE;
moduleclass := module.GetModuleClassName;
if moduleclasspath='' then
mymoduleclasspath := moduleclass
else
mymoduleclasspath := moduleclasspath+':'+moduleclass;
FREDB_SiteMap_AddRadialEntry(SiteMapData,keypath+'/'+moduleclass,modl.FetchModuleTextShort(session,modl.StdSitemapModuleTitleKey),
'images_apps/'+SiteMapIconSubPath+DirectorySeparator+module.GetSitemapIconFilename,mymoduleclasspath,0,
conn.SYS.CheckClassRight4MyDomain(sr_FETCH,modl.ClassType));
oldkeypath := keypath;
oldmoduleclasspath := moduleclasspath;
keypath := keypath+'/'+moduleclass;
if moduleclasspath<>'' then
moduleclasspath := moduleclasspath+':'+moduleclass
else
moduleclasspath := moduleclass;
modl.ForAllAppModules(@BuildSiteMap);
keypath := oldkeypath;
moduleclasspath := oldmoduleclasspath;
end;
begin
conn:=session.GetDBConnection;
SiteMapData := GFRE_DBI.NewObject;
FREDB_SiteMap_AddRadialEntry(SiteMapData,'MAIN',FetchAppTextShort(session,StdSitemapCaptionKey),'images_apps'+DirectorySeparator+SiteMapIconSubPath+DirectorySeparator+SiteMapMainIconFilename,'',0,true);
moduleclasspath := '';
keypath := 'MAIN';
ForAllAppModules(@BuildSiteMap);
FREDB_SiteMap_RadialAutoposition(SiteMapData);
session.GetSessionAppData(ClassName).Field('SITEMAP').AsObject := SiteMapData;
end;
procedure TFRE_DB_APPLICATION.MyServerFinalize;
begin
end;
function TFRE_DB_APPLICATION.FetchOrInitFeederMachine(const ses: IFRE_DB_Usersession; const configmachinedata: IFRE_DB_Object; out machine_uid: TFRE_DB_GUID; out BoundMachineName, BoundMachineMac: TFRE_DB_String): boolean;
begin
result := false;
end;
procedure TFRE_DB_APPLICATION.ForAllAppModules(const module_iterator: TFRE_DB_APPLICATION_MODULE_ITERATOR);
procedure FieldIterator(const fld:IFRE_DB_Field);
var module :IFRE_DB_APPLICATION_MODULE;
begin
if fld.FieldType=fdbft_Object then begin
if fld.AsObject.Supports(IFRE_DB_APPLICATION_MODULE,module) then begin
module_iterator(module,Field(fld.FieldName+'_O').AsInt16);
end;
end;
end;
begin
ForAllFields(@FieldIterator);
end;
function TFRE_DB_APPLICATION.WEB_OnUIChange(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
ses.GetSessionAppData(classname).Field('activeSection').AsString:=input.Field('sectionid').AsString;
Result:=GFRE_DB_NIL_DESC;
end;
class procedure TFRE_DB_APPLICATION.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
Scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
Scheme.Strict(false);
Scheme.SetSysDisplayField(TFRE_DB_NameTypeArray.Create('objname','$DBTEXT:desc'),'%s - (%s)');
end;
procedure TFRE_DB_APPLICATION.Finalize;
begin
free;
end;
function TFRE_DB_APPLICATION.WEB_Content(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var ActiveSection : String;
appobj : TFRE_DB_APPLICATION;
res : TFRE_DB_SUBSECTIONS_DESC;
procedure DescribeAppModules(const module:IFRE_DB_APPLICATION_MODULE;const module_order:nativeint);
var
menu : TFRE_DB_MENU_DESC;
section : TFRE_DB_SECTION_DESC;
csf : TFRE_DB_SERVER_FUNC_DESC;
title : TFRE_DB_String;
id : String;
begin
if conn.sys.CheckClassRight4MyDomain(sr_FETCH,module.GetImplementorsClass) or
(conn.sys.CheckClassRight4AnyDomain(sr_FETCH,module.GetImplementorsClass) and isMultiDomainApp) then
begin
csf := TFRE_DB_SERVER_FUNC_DESC.Create.Describe(module.AsObject,'content');
title := module.GetModuleTitle(ses);
id := module.GetModuleClassName;
section:=TFRE_DB_SUBSECTIONS_DESC(res).AddSection.Describe(csf,title,module_order,id);
menu:=TFRE_DB_MENU_DESC(module.GetToolbarMenu(ses));
if Assigned(menu) then
section.SetMenu(menu);
end;
end;
begin
appobj := self;
res := TFRE_DB_SUBSECTIONS_DESC.create.Describe;
TFRE_DB_SUBSECTIONS_DESC(res).OnUIChange(CWSF(@WEB_OnUIChange));
appobj.ForAllAppModules(@DescribeAppModules);
ActiveSection := ses.GetSessionAppData(ClassName).Field('activeSection').AsString;
TFRE_DB_SUBSECTIONS_DESC(res).SetActiveSection(ActiveSection);
result := res;
end;
procedure TFRE_DB_APPLICATION.AddAppToSiteMap(const session: IFRE_DB_UserSession; const parent_entry: TFRE_DB_CONTENT_DESC);
//var app : TFRE_DB_APPLICATION;
var res : TFRE_DB_SITEMAP_DESC;
parent_e : TFRE_DB_SITEMAP_ENTRY_DESC;
sitemapdata : IFRE_DB_Object;
ientry : integer;
procedure BuildSM(const entry:IFRE_DB_Object);
var caption,
icon,id : String;
x,y,i,nc : integer;
scale : Single;
dis : Boolean;
next_lev : TFRE_DB_SITEMAP_ENTRY_DESC;
old_par : TFRE_DB_SITEMAP_ENTRY_DESC;
ial : TFRE_DB_StringArray;
oial : TFRE_DB_StringArray;
isubentry : integer;
begin
caption := entry.Field('CAP').AsString;
id := entry.Field('ID').AsString;
nc := entry.Field('NC').AsInt16;
icon := entry.Field('ICO').AsString;
x := entry.Field('CRD').AsInt32Arr[0];
y := entry.Field('CRD').AsInt32Arr[1];
oial := entry.Field('IAL').AsStringArr;
scale := entry.Field('SCL').AsReal32;
dis := entry.Field('DIS').AsBoolean;
SetLength(ial,length(oial)+3);
ial[0] := 'Home';
ial[1] := 'AppContainer';
ial[2] := AppClassName;
oial := entry.Field('IAL').AsStringArr;
for i:=0 to high(oial) do begin
ial[i+3] := oial[i];
end;
old_par := parent_e;
next_lev := parent_e.AddEntry.Describe(caption,icon,TFRE_DB_RESTORE_UI_DESC.create.Describe('FirmOSViewport',ial),x,y,id,nc,dis,scale);
if true then begin
parent_e := next_lev;
for isubentry := 0 to entry.Field('ENTRIES').valuecount-1 do begin
BuildSM(entry.Field('ENTRIES').AsObjectItem[isubentry]);
end;
parent_e := old_par;
end;
end;
begin
parent_e := parent_entry as TFRE_DB_SITEMAP_ENTRY_DESC;
SiteMapData := session.GetSessionAppData(ClassName).FieldOnlyExistingObj('SITEMAP');
if assigned(sitemapdata) then
for ientry := 0 to sitemapdata.Field('ENTRIES').ValueCount-1 do
BuildSM(sitemapdata.Field('ENTRIES').AsObjectItem[ientry]);
end;
function TFRE_DB_APPLICATION.ShowInApplicationChooser(const session: IFRE_DB_UserSession): Boolean;
begin
Result:=not IsConfigurationApp;
end;
function TFRE_DB_APPLICATION.IsConfigurationApp: Boolean;
begin
Result:=false;
end;
function TFRE_DB_APPLICATION.FetchAppTextShort(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchAppText(session,translation_key);
result := txt.Getshort;
txt.Finalize;
end;
function TFRE_DB_APPLICATION.FetchAppTextLong(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchAppText(session,translation_key);
result := txt.GetLong;
txt.Finalize;
end;
function TFRE_DB_APPLICATION.FetchAppTextHint(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchAppText(session,translation_key);
result := txt.GetHint;
txt.Finalize;
end;
function TFRE_DB_APPLICATION.FetchAppTextFull(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): IFRE_DB_TEXT;
begin
result := _FetchAppText(session,translation_key);
end;
{ TFRE_DB_APPLICATION_MODULE }
procedure TFRE_DB_APPLICATION_MODULE.InternalSetup;
begin
SetupAppModuleStructure;
end;
procedure TFRE_DB_APPLICATION_MODULE.SetSitemapIconFilename(AValue: TFRE_DB_String);
begin
Field('sm_icon_fn').asstring := AValue;
end;
procedure TFRE_DB_APPLICATION_MODULE.SetupAppModuleStructure;
begin
end;
procedure TFRE_DB_APPLICATION_MODULE.AddApplicationModule(const module: TFRE_DB_APPLICATION_MODULE);
var FSubmoduleOrder : Integer;
begin
Field(module.GetModuleClassName).AsObject := module;
if FieldExists('SubModuleOrder') then begin
FSubmoduleOrder:=Field('SubModuleOrder').AsInt32;
inc(FSubModuleOrder);
end else begin
FSubModuleOrder:=1;
end;
Field('SubModuleOrder').AsInt32 := FSubmoduleOrder;
Field(module.GetModuleClassName+'_O').AsInt16:=FSubModuleOrder;
end;
procedure TFRE_DB_APPLICATION_MODULE.InitModuleDesc(const descr_translation_key: TFRE_DB_String);
begin
SetDescrTranslationKey(descr_translation_key)
end;
procedure TFRE_DB_APPLICATION_MODULE.ForAllAppModules(const module_iterator: TFRE_DB_APPLICATION_MODULE_ITERATOR);
procedure FieldIterator(const fld:IFRE_DB_Field);
var module :IFRE_DB_APPLICATION_MODULE;
begin
if fld.FieldType=fdbft_Object then begin
if fld.AsObject.Supports(IFRE_DB_APPLICATION_MODULE,module) then begin
module_iterator(module,Field(fld.FieldName+'_O').AsInt16);
end;
end;
end;
begin
ForAllFields(@FieldIterator);
end;
procedure TFRE_DB_APPLICATION_MODULE.MyServerInitializeModule(const admin_dbc: IFRE_DB_CONNECTION);
begin
end;
procedure TFRE_DB_APPLICATION_MODULE.CheckClassVisibility4AnyDomain(const session: IFRE_DB_UserSession);
begin
if not session.GetDBConnection.sys.CheckClassRight4AnyDomain(sr_FETCH,ClassType) then
raise EFRE_DB_Exception.Create(session.GetDBConnection.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
end;
procedure TFRE_DB_APPLICATION_MODULE.CheckClassVisibility4MyDomain(const session: IFRE_DB_UserSession);
begin
if not session.GetDBConnection.sys.CheckClassRight4MyDomain(sr_FETCH,ClassType) then
raise EFRE_DB_Exception.Create(session.GetDBConnection.FetchTranslateableTextShort(FREDB_GetGlobalTextKey('error_no_access')));
end;
class procedure TFRE_DB_APPLICATION_MODULE.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId := 'UNUSED';
end;
class procedure TFRE_DB_APPLICATION_MODULE.EnableFeature4Domain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION_MODULE.EnableFeature4SysDomain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION_MODULE.DisableFeature4Domain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class procedure TFRE_DB_APPLICATION_MODULE.DisableFeature4SysDomain(const conn: IFRE_DB_CONNECTION; const feature_name: TFRE_DB_NameType; domainUID: TFRE_DB_GUID);
begin
end;
class function TFRE_DB_APPLICATION_MODULE.StdSitemapModuleTitleKey: TFRE_DB_String;
begin
result := '$SMTK_'+ClassName;
end;
class procedure TFRE_DB_APPLICATION_MODULE.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
if ClassName<>'TFRE_DB_APPLICATION_MODULE' then
scheme.SetParentSchemeByName('TFRE_DB_APPLICATION_MODULE');
end;
procedure TFRE_DB_APPLICATION_MODULE.MySessionInitializeModule(const session: TFRE_DB_UserSession);
procedure _initSubModules(const field: IFRE_DB_FIELD);
var app_module : IFRE_DB_APPLICATION_MODULE;
module : TFRE_DB_APPLICATION_MODULE;
begin
if field.IsObjectField and field.AsObject.Supports(IFRE_DB_APPLICATION_MODULE,app_module) then begin
try
module := field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE;
if not session.GetModuleInitialized(module.ClassName) then
begin
try
(field.AsObject.Implementor_HC as TFRE_DB_APPLICATION_MODULE).MySessionInitializeModule(session);
finally
session.SetModuleInitialized(module.ClassName);
end;
end;
except
on e:Exception do
begin
GFRE_DBI.LogError(dblc_SESSION,'MODULE SESSION INITIALIZATION FAILED SESS(%s) %s : %s ',[session.GetSessionID,classname,e.Message]);
end;
end;
end;
end;
begin
ForAllFields(@_initSubModules);
end;
procedure TFRE_DB_APPLICATION_MODULE.MySessionPromotionModule(const session: TFRE_DB_UserSession);
begin
end;
procedure TFRE_DB_APPLICATION_MODULE.MySessionFinalizeModule(const session: TFRE_DB_UserSession);
begin
end;
function TFRE_DB_APPLICATION_MODULE.ShowInSession(const ses: IFRE_DB_Usersession; const conn: IFRE_DB_CONNECTION; const app: IFRE_DB_APPLICATION): Boolean;
begin
Result:=conn.sys.CheckClassRight4MyDomain(sr_FETCH,GetImplementorsClass) or
(conn.sys.CheckClassRight4AnyDomain(sr_FETCH,GetImplementorsClass) and app.isMultiDomainApp);
end;
function TFRE_DB_APPLICATION_MODULE.GetEmbeddingApp: TFRE_DB_APPLICATION;
var obj:IFRE_DB_Object;
begin
obj := self;
repeat
obj := obj.Parent;
if obj.IsA(TFRE_DB_APPLICATION.ClassName) then begin
exit(obj.Implementor_HC as TFRE_DB_APPLICATION);
end;
until false;
end;
function TFRE_DB_APPLICATION_MODULE._FetchAppText(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): IFRE_DB_TEXT;
begin
result := GetEmbeddingApp._FetchAppText(session,translation_key);
end;
function TFRE_DB_APPLICATION_MODULE.GetToolbarMenu(const ses: IFRE_DB_Usersession): TFRE_DB_CONTENT_DESC;
begin
result := nil;
end;
function TFRE_DB_APPLICATION_MODULE.GetDependencyFiltervalues(const input: IFRE_DB_Object; const dependencyfield: string): TFRE_DB_StringArray;
begin
setlength(result,0);
if input.FieldExists('dependency') then begin
if input.Field('dependency').AsObject.FieldExists(dependencyfield) then begin
result := input.Field('dependency').AsObject.Field(dependencyfield).asobject.Field('filtervalues').AsStringArr;
end;
end;
end;
procedure TFRE_DB_APPLICATION_MODULE.SetDescrTranslationKey(const val: TFRE_DB_String);
begin
field('mod_desc_key').AsString:=val;
end;
function TFRE_DB_APPLICATION_MODULE.GetDescrTranslationKey: TFRE_DB_String;
begin
Result := field('mod_desc_key').AsString;
end;
function TFRE_DB_APPLICATION_MODULE.GetModuleTitle(const ses: IFRE_DB_Usersession): TFRE_DB_String; { TODO: Change all Modules to getstddescrkey }
var txt : IFRE_DB_TEXT;
key : string;
begin
key := GetDescrTranslationKey;
txt := FetchModuleTextFull(ses,key);
if txt.GetTKey='notfound' then
begin
txt.Finalize;
txt := GetEmbeddingApp._FetchAppText(ses,GetDescrTranslationKey);
end;
if txt.GetTKey='notfound' then
begin
txt.Finalize;
txt := FetchModuleTextFull(ses,StdSitemapModuleTitleKey);
end;
result := txt.Getshort;
txt.Finalize;
end;
function TFRE_DB_APPLICATION_MODULE.GetModuleClassName: Shortstring;
begin
result := ClassName;
end;
function TFRE_DB_APPLICATION_MODULE.AsObject: IFRE_DB_Object;
begin
result := FImplementor;
end;
function TFRE_DB_APPLICATION_MODULE.IsContentUpdateVisible(const session: IFRE_DB_UserSession; const update_content_id: string): Boolean;
begin
result := GetEmbeddingApp.IsContentUpdateVisible(session,update_content_id);
end;
function TFRE_DB_APPLICATION_MODULE._FetchModuleText(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): IFRE_DB_TEXT;
begin
if not session.GetDBConnection.FetchTranslateableTextOBJ('$'+uppercase(classname)+'_'+translation_key,result) then
begin
Result := GFRE_DBI.CreateText('notfound',translation_key+'_short',translation_key+'_long',translation_key+'_is_missing!');
end;
end;
function TFRE_DB_APPLICATION_MODULE.FetchModuleTextShort(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchModuleText(session,translation_key);
result := txt.Getshort;
txt.Finalize;
end;
function TFRE_DB_APPLICATION_MODULE.FetchModuleTextLong(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchModuleText(session,translation_key);
result := txt.GetLong;
txt.Finalize;
end;
function TFRE_DB_APPLICATION_MODULE.FetchModuleTextHint(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): TFRE_DB_String;
var txt : IFRE_DB_TEXT;
begin
txt := _FetchModuleText(session,translation_key);
result := txt.GetHint;
txt.Finalize;
end;
function TFRE_DB_APPLICATION_MODULE.FetchModuleTextFull(const session: IFRE_DB_UserSession; const translation_key: TFRE_DB_String): IFRE_DB_TEXT;
begin
result := _FetchModuleText(session,translation_key);
end;
function TFRE_DB_APPLICATION_MODULE.GetSitemapIconFilename: TFRE_DB_String;
begin
result := Field('sm_icon_fn').asstring;
if result='' then
result := GetEmbeddingApp.SiteMapMainIconFilename;
end;
class procedure TFRE_DB_APPLICATION_MODULE.CreateModuleText(const conn: IFRE_DB_SYS_CONNECTION; const translation_key: TFRE_DB_String; const short_text: TFRE_DB_String; const long_text: TFRE_DB_String; const hint_text: TFRE_DB_String);
var txt :IFRE_DB_TEXT;
begin
txt := GFRE_DBI.NewText('$'+uppercase(classname)+'_'+translation_key,long_text,short_text,hint_text);
CheckDbResult(conn.StoreTranslateableText(txt),'CreateModuleText ' + translation_key);
end;
class procedure TFRE_DB_APPLICATION_MODULE.DeleteModuleText(const conn: IFRE_DB_SYS_CONNECTION; const translation_key: TFRE_DB_String);
begin
CheckDbResult(conn.DeleteTranslateableText('$'+uppercase(classname)+'_'+translation_key),'DeleteModuleText ' + translation_key);
end;
class procedure TFRE_DB_APPLICATION_MODULE.UpdateModuleText(const conn: IFRE_DB_SYS_CONNECTION; const translation_key: TFRE_DB_String; const short_text: TFRE_DB_String; const long_text: TFRE_DB_String; const hint_text: TFRE_DB_String);
var txt :IFRE_DB_TEXT;
begin
txt := GFRE_DBI.NewText('$'+uppercase(classname)+'_'+translation_key,long_text,short_text,hint_text);
CheckDbResult(conn.UpdateTranslateableText(txt),'UpdateModuleText ' + translation_key);
end;
function TFRE_DB_APPLICATION_MODULE.WEB_Content(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
var ActiveSection : String;
res : TFRE_DB_SUBSECTIONS_DESC;
procedure DescribeAppModules(const module:IFRE_DB_APPLICATION_MODULE;const module_order:nativeint);
var
menu : TFRE_DB_MENU_DESC;
section : TFRE_DB_SECTION_DESC;
csf : TFRE_DB_SERVER_FUNC_DESC;
title : TFRE_DB_String;
id : String;
begin
if module.ShowInSession(ses,conn,app) then
begin
csf := TFRE_DB_SERVER_FUNC_DESC.Create.Describe(module.AsObject,'content');
title := module.GetModuleTitle(ses);
id := module.GetModuleClassName;
section:=TFRE_DB_SUBSECTIONS_DESC(res).AddSection.Describe(csf,title,module_order,id);
menu:=TFRE_DB_MENU_DESC(module.GetToolbarMenu(ses));
if Assigned(menu) then
section.SetMenu(menu);
end;
end;
begin
res := TFRE_DB_SUBSECTIONS_DESC.create.Describe;
TFRE_DB_SUBSECTIONS_DESC(res).OnUIChange(CWSF(@WEB_OnUIChange));
ForAllAppModules(@DescribeAppModules);
ActiveSection := ses.GetSessionAppData(ClassName).Field('activeSection').AsString;
TFRE_DB_SUBSECTIONS_DESC(res).SetActiveSection(ActiveSection);
result := res;
end;
function TFRE_DB_APPLICATION_MODULE.WEB_OnUIChange(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object;
begin
ses.GetSessionModuleData(ClassName).Field('activeSection').AsString:=input.Field('sectionid').AsString;
Result:=GFRE_DB_NIL_DESC;
end;
{ TFRE_DB_JOB }
procedure TFRE_DB_JOB.InternalSetup;
begin
inherited InternalSetup;
SetMaxAllowedTime(60); { set the internal allowed time to 60 seconds default }
AttachPlugin(TFRE_DB_JobReportPlugin.CreateForDB);
end;
function TFRE_DB_JOB.GetDontStartJob: Boolean;
begin
result := FieldOnlyExistingBoolean('dontstart');
end;
function TFRE_DB_JOB.GetJobLink: TFRE_DB_Guid;
begin
result := field('jlink').AsGUID;
end;
function TFRE_DB_JOB.GetRunningMachine: TFRE_DB_Guid;
begin
result := Field('rom').AsGUID;
end;
function TFRE_DB_JOB.GetConfig: IFRE_DB_Object;
begin
result := Field('c').AsObject;
end;
procedure TFRE_DB_JOB.SetConfig(AValue: IFRE_DB_Object);
begin
Field('c').AsObject := AValue;
end;
function TFRE_DB_JOB.GetReport: TFRE_DB_JobReportPlugin;
begin
GetPlugin(TFRE_DB_JobReportPlugin,result);
end;
function TFRE_DB_JOB.GetPidLockFilename: string;
begin
result := cFRE_PID_LOCK_DIR+DirectorySeparator+'SJ_'+uppercase(jobkey+'.flck');
end;
procedure TFRE_DB_JOB.SetDontStartJob(AValue: Boolean);
begin
Field('dontstart').AsBoolean:=AValue;
end;
function TFRE_DB_JOB.GetJobFilename: string;
var jobstate : TFRE_JobState;
begin
if jobkey='' then
raise EFRE_DB_Exception.Create('NO JOBKEY SET FOR GETJOBFILENAME');;
jobstate := GetJobState;
result := GetJobBaseFilename(jobstate,jobkey);
if (jobstate=jobStateDone) or (jobstate=jobStateFailed) then
result := result + '_'+inttostr(GetReport.GetStartTime(true));
result := result +'.dbo';
end;
procedure TFRE_DB_JOB.GetJobRemoteSSH;
begin
cFRE_REMOTE_HOST := FieldOnlyExistingString('remotehost');
cFRE_REMOTE_USER := FieldOnlyExistingString('remoteuser');
cFRE_REMOTE_SSL_PORT := FieldOnlyExistingInt32 ('remoteport');
cFRE_REMOTE_SSL_ID_FILE := FieldOnlyExistingString('remotekeyfilename');
end;
procedure TFRE_DB_JOB.SetJobLink(AValue: TFRE_DB_Guid);
begin
field('jlink').AsGUID := AValue;
end;
procedure TFRE_DB_JOB.SetRunningMachine(AValue: TFRE_DB_Guid);
begin
Field('rom').AsGUID := AValue;
end;
class procedure TFRE_DB_JOB.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('job_status').Setup(GFRE_DBI.CreateText('$enum_job_status','Job Status Enum'));
enum.addEntry('UNKNOWN',GetTranslateableTextKey('enum_job_status_unknown'));
enum.addEntry('TORUN',GetTranslateableTextKey('enum_job_status_torun'));
enum.addEntry('IMMEDIATESTART',GetTranslateableTextKey('enum_job_status_immediatestart'));
enum.addEntry('RUNNING',GetTranslateableTextKey('enum_job_status_running'));
enum.addEntry('DONE',GetTranslateableTextKey('enum_job_status_done'));
enum.addEntry('FAILED',GetTranslateableTextKey('enum_job_status_failed'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_ObjectEx.ClassName);
scheme.AddSchemeField('machine',fdbft_ObjLink);
scheme.AddSchemeField('troubleshooting',fdbft_String);
scheme.AddSchemeField('jobstate',fdbft_String).SetupFieldDef(true,false,'job_status');
end;
procedure TFRE_DB_JOB.SetStatus(const status: TFRE_SignalStatus; const statussummary: string);
begin
E_FOS_Implement;
abort;
end;
procedure TFRE_DB_JOB.SetDetailStatus(const detail: IFRE_DB_Object; const status: TFRE_SignalStatus; const statussummary: string);
begin
E_FOS_Implement;
abort;
end;
procedure TFRE_DB_JOB.SetMaxAllowedTime(const time_s: NativeInt);
begin
Field('MAX_ALLOWED_TIME').AsInt32 := time_s;
end;
procedure TFRE_DB_JOB.SetJobkeyDescription(const newjobkey: string; const jdescription: string);
begin
Field('jobkey').asstring := newjobkey;
ObjectName := newjobkey;
Field('desc').AsString := jdescription;
end;
procedure TFRE_DB_JOB.SaveJobToFile;
var
jobfilename : string;
begin
if DomainID.IsNullGuid then
raise EFRE_DB_Exception.Create(edb_INTERNAL,'a job [%s] without domainid cannot be saved!',[JobKey]);
jobfilename := GetJobFilename;
if GetJobState<>jobStateRunning then
ClearRunningOnMachine;
if not DirectoryExists(ExtractFileDir(jobfilename)) then
ForceDirectories(ExtractFileDir(jobfilename));
SaveToFile(jobfilename);
end;
procedure TFRE_DB_JOB.DeleteJobFile;
begin
if DeleteFile(GetJobFilename)=false then
raise EFRE_DB_Exception.Create('ERROR ON DELETING JOBFILE '+GetJobFilename);
end;
procedure TFRE_DB_JOB.SetJobStateAndDeleteFile(const value: TFRE_JobState);
begin
if (GetJobState<>value) and (GetJobstate<>jobStateToRun) then
DeleteFile(GetJobFilename);
Field('jobstate').asstring := CFRE_JobState[value];
end;
class procedure TFRE_DB_JOB.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId:='1.0';
StoreTranslateableText(conn,'enum_job_status_unknown','Unknown');
StoreTranslateableText(conn,'enum_job_status_torun','To run');
StoreTranslateableText(conn,'enum_job_status_immediatestart','Immediate start');
StoreTranslateableText(conn,'enum_job_status_running','Running');
StoreTranslateableText(conn,'enum_job_status_done','Done');
StoreTranslateableText(conn,'enum_job_status_failed','Failed');
end;
end;
function TFRE_DB_JOB.GetTransferFilename: TFRE_DB_String;
begin
result := cFRE_JOB_RESULT_DIR+'intransfer'+DirectorySeparator+uppercase(JobKey)+'_'+ inttostr(GetReport.GetStartTime(true))+'.dbo';
end;
procedure TFRE_DB_JOB.SetTransferTimeStamp;
begin
field('transfer').AsDateTimeUTC := GFRE_DT.Now_UTC;
end;
procedure TFRE_DB_JOB.SaveJobToTransferred;
var fn : TFRE_DB_String;
begin
DeleteJobFile;
SetTransferTimeStamp;
fn := GetTransferFilename;
if not DirectoryExists(ExtractFileDir(fn)) then
ForceDirectories(ExtractFileDir(fn));
SaveToFile(fn);
end;
procedure TFRE_DB_JOB.RemoveJobFromTransferred;
begin
DeleteFile(GetTransferFilename);
end;
procedure TFRE_DB_JOB.SetJobStateandSave(const value: TFRE_JobState);
begin
SetJobStateAndDeleteFile(value);
SaveJobToFile;
end;
function TFRE_DB_JOB.GetJobState: TFRE_JobState;
var i : TFRE_JobState;
begin
for i:=low(TFRE_JobState) to high(TFRE_JobState) do
if CFRE_JobState[i]=Field('jobstate').asstring then
begin
result := i;
exit;
end;
result := jobStateUnknown;
end;
procedure TFRE_DB_JOB.SetPid(const value: QWord);
begin
field('pid').AsUInt64:=value;
end;
function TFRE_DB_JOB.GetPid: QWord;
begin
result :=field('pid').AsUInt64;
end;
procedure TFRE_DB_JOB.ClearPid;
begin
DeleteField('pid');
end;
procedure TFRE_DB_JOB.SetProgress(const percent: single);
begin
GetReport.SetProgress(percent);
end;
procedure TFRE_DB_JOB.AddProgressLog(const key, msg: string; const percent: single);
begin
AddProgressLog(key,[],msg,percent);
end;
procedure TFRE_DB_JOB.AddProgressLog(const key: string; const stringparams: array of String; const msg: string; const percent: single);
begin
GetReport.AddProgressLog(key,msg,stringparams);
if percent<>-1 then
GetReport.SetProgress(percent);
SaveJobToFile;
end;
procedure TFRE_DB_JOB.AddProgressLog(const key: string; const stringparams: array of String; const msg: string; const msg_params: array of const; const percent: single);
begin
AddProgressLog(key,stringparams,Format(msg,msg_params),percent);
end;
procedure TFRE_DB_JOB.SetCurrentStateOnly(const key: string; const msg: string; const percent: single);
begin
GetReport.SetCurrentState(key,msg,[]);
if percent<>-1 then
GetReport.SetProgress(percent);
SaveJobToFile;
end;
procedure TFRE_DB_JOB.ManualStart(const only_safe_the_definition: boolean; const config_mode: boolean);
var result, childpid : integer;
begin
CheckNotRunningAndBinaryExists;
// Check if my Job Description is Good
SetJobStateandSave(jobStateImmediateStart);
if not only_safe_the_definition then
result := StartAsyncProcess(childpid,config_mode);
end;
procedure TFRE_DB_JOB.SetRecurrence(const rec: String);
begin
Field('recurrence').AsString:=rec;
end;
procedure TFRE_DB_JOB.CheckNotRunningAndBinaryExists;
var jobfile : string;
begin
if not FileExists(cFRE_SAFEJOB_BIN) then
raise EFRE_DB_Exception.Create(edb_ERROR,'NO SAFEJOB BINARY AVAILABLE IN '+cFRE_SAFEJOB_BIN);
jobfile := TFRE_DB_JOB.GetJobBaseFilename(jobStateRunning,JobKey)+'.dbo';
if FileExists(jobfile) then
raise EFRE_DB_Exception.Create(edb_ERROR,'SAFEJOB ALREADY RUNNING '+Jobkey);
end;
function TFRE_DB_JOB.StartAsyncProcess(out childpid: integer; const config_mode: boolean): integer;
var cmdline,os,es : string;
begin
cmdline := cFRE_SAFEJOB_BIN;
if cFRE_CONFIG_MODE then
cmdline := cmdline+' -c';
cmdline := cmdline + ' '+JobKey;
Result := FRE_ProcessCMDAsync(cmdline,childpid);
end;
class function TFRE_DB_JOB.GetJobBaseFilename(const state: TFRE_JobState; const vjobkey: string): string;
begin
result :=GetJobBaseDirectory(state)+DirectorySeparator+uppercase(vjobkey); //GFRE_BT.Str2HexStr(vJobKey);
end;
class function TFRE_DB_JOB.GetJobBaseDirectory(const state: TFRE_JobState): string;
begin
result :=cFRE_JOB_RESULT_DIR+LowerCase(CFRE_JobState[State]);
end;
procedure TFRE_DB_JOB.ClearConfig;
begin
Field('c').Clear();
end;
procedure TFRE_DB_JOB.ClearRunningOnMachine;
begin
Field('rom').Clear;
end;
procedure TFRE_DB_JOB.SetJobRemoteSSH(const user: string; const host: string; const keyfilename: string; const port: integer);
begin
Field('remoteuser').AsString := user;
Field('remotehost').AsString := host;
Field('remoteport').AsInt32 := port;
Field('remotekeyfilename').AsString := keyfilename;
end;
procedure TFRE_DB_JOB.ExecuteJob;
begin
// do nothing in default job
end;
function TFRE_DB_JOB.JobKey: string;
begin
result := Field('jobkey').asstring;
end;
procedure TFRE_DB_JOB.Do_the_Job;
var report : TFRE_DB_JobReportPlugin;
begin
try
report := GetReport;
report.SetProgress(0);
report.SetStartTimeUTC(GFRE_DT.Now_UTC);
report.SetDomainID(DomainID);
SetJobStateandSave(jobStateRunning);
GetJobRemoteSSH;
ExecuteJob;
report.SetEndTimeUTC(GFRE_DT.Now_UTC);
ClearPid;
SetJobStateandSave(jobStateDone);
except on E:Exception do
begin
AddProgressLog('EXCEPT','EXCEPTION:'+E.Message);
SetJobStateandSave(jobStateFailed);
raise;
end;
end;
end;
function TFRE_DB_JOB.RIF_Start(const runnning_ctx: TObject): TFRE_DB_RIF_RESULT;
var pid : integer;
begin
CheckNotRunningAndBinaryExists;
// Check if my Job Description is Good
SetJobStateandSave(jobStateImmediateStart);
result := TFRE_DB_RIF_RESULT.CreateForDB;
if not DontStartImmediateJob then
begin
result.ErrorCode:=StartAsyncProcess(pid);
result.ChildPid := pid;
end
else
begin
result.ChildPid:=-1;
result.ErrorCode:=0;
result.ErrorText:='DELAYED';
exit;
end;
if Result.ErrorCode=0 then
result.ErrorText:='OK'
else
result.ErrorText:='FAILED TO START';
end;
function TFRE_DB_JOB.RIF_Kill(const runnning_ctx: TObject): TFRE_DB_RIF_RESULT;
var jobfile : string;
pidlockfile : string;
sobj : IFRE_DB_Object;
sjob : TFRE_DB_JOB;
pid : QWord;
begin
jobfile := TFRE_DB_JOB.GetJobBaseFilename(jobStateRunning,JobKey)+'.dbo';
pidlockfile := GetPidlockFilename;
result := TFRE_DB_RIF_RESULT.CreateForDB;
if FileExists(jobfile) then
begin
sobj:= GFRE_DBI.CreateFromFile(jobfile);
if sobj.IsA(TFRE_DB_JOB,sjob) then
begin
pid := sjob.GetPid;
FPkill(pid,SIGKILL);
DeleteFile(jobfile);
if FileExists(pidlockfile) then
DeleteFile(pidlockfile);
result.Field('RESULT').AsString:='OK';
result.Field('PID').AsUInt64:=pid;
end
else
raise EFRE_DB_Exception.Create(edb_ERROR,'JOB FILE IS NOT A TFRE_DB_JOB');
end
else
begin
if FileExists(pidlockfile) then
begin
DeleteFile(pidlockfile);
result.Field('RESULT').AsString :='OK';
result.Field('NOTE').asstring :='NO JOB FILE FOUND, JUST DELETE PID LOCK';
end
else
raise EFRE_DB_Exception.Create(edb_ERROR,'NO JOBFILE AND NO PID FILE FOUND!');
end;
end;
function TFRE_DB_JOB.RIF_CreateJobDescription(const runnning_ctx: TObject): IFRE_DB_Object;
begin
abort;
end;
function TFRE_DB_JOB.RIF_DeleteJobDescription(const runnning_ctx: TObject): IFRE_DB_Object;
begin
abort;
end;
function TFRE_DB_JOB.RIF_GetAllJobDescriptions(const runnning_ctx: TObject): IFRE_DB_Object;
begin
abort;
end;
procedure TFRE_DB_JOBREPORTPLUGIN.SetProgress(const percent: single);
begin
Field('p').AsReal32:=percent;
writeln('DBG SET PROGRESS : '+Format('%3.2f %',[GetCurProgressValue])+GetCurProgressTransKey+' '+FREDB_CombineString(GetCurProgressStringParams,',')+' '+GetCurrentProgressMsg);
end;
procedure TFRE_DB_JOBREPORTPLUGIN.AddProgressLog(const key, msg: string; const stringparams: array of string);
var ts : TFRE_DB_DateTime64;
l : IFRE_DB_Object;
lo : IFRE_DB_Object;
begin
ts:=GFRE_DT.Now_UTC;
lo:=GFRE_DBI.NewObject;
lo.Field('TS').AsDateTimeUTC:= ts;
lo.Field('M').asstring := msg;
lo.Field('MP').AsStringArr := FREDB_StringArrayOpen2StringArray(stringparams);
lo.Field('K').asstring := lowercase(key);
lo.Field('P').AsReal32 := Field('p').AsReal32;
Field('L').AddObject(lo);
SetCurrentState(key,msg,stringparams);
GFRE_LOG.Log(key+': '+msg,'JOB',fll_Info);
writeln('DBG ADD PROGRESS LOG : '+Format('%3.2f %',[GetCurProgressValue])+GetCurProgressTransKey+' '+FREDB_CombineString(GetCurProgressStringParams,',')+' '+GetCurrentProgressMsg);
end;
procedure TFRE_DB_JOBREPORTPLUGIN.SetCurrentState(const key, msg: string; const stringparams: array of string);
begin
Field('SK').AsString := key;
Field('SM').AsString := msg;
Field('SP').AsStringArr := stringparams;
end;
function TFRE_DB_JOBREPORTPLUGIN.HasStartTime: Boolean;
begin
Result:=FieldExists('st');
end;
function TFRE_DB_JOBREPORTPLUGIN.HasEndTime: Boolean;
begin
Result:=FieldExists('et');
end;
function TFRE_DB_JOBREPORTPLUGIN.GetStartTime(const utc: boolean): TFRE_DB_DateTime64;
begin
if not utc then
result := Field('st').AsDateTime
else
result := Field('st').AsDateTimeUTC;
end;
function TFRE_DB_JOBREPORTPLUGIN.GetEndTime(const utc: boolean): TFRE_DB_DateTime64;
begin
if not utc then
result := Field('et').AsDateTime
else
result := Field('et').AsDateTimeUTC;
end;
procedure TFRE_DB_JOBREPORTPLUGIN.SetStartTimeUTC(const dt: TFRE_DB_DateTime64);
begin
Field('st').AsDateTimeUTC := dt;
end;
procedure TFRE_DB_JOBREPORTPLUGIN.SetEndTimeUTC(const dt: TFRE_DB_DateTime64);
begin
Field('et').AsDateTimeUTC := dt;
end;
function TFRE_DB_JOBREPORTPLUGIN.GetCurProgressValue: Single;
begin
result := FieldOnlyExistingReal32('P',0);
end;
function TFRE_DB_JOBREPORTPLUGIN.GetCurProgressTransKey: TFRE_DB_String;
begin
result := FieldOnlyExistingString('SK','');
end;
function TFRE_DB_JOBREPORTPLUGIN.GetCurProgressStringParams: TFRE_DB_StringArray;
var
fld: IFRE_DB_FIELD;
begin
if FieldOnlyExisting('SM',fld) then
result := fld.AsStringArr
else
result := nil;
end;
function TFRE_DB_JOBREPORTPLUGIN.GetCurrentProgressMsg: TFRE_DB_String;
begin
result := FieldOnlyExistingString('SM','');
end;
class procedure TFRE_DB_JOBREPORTPLUGIN.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
var
enum: IFRE_DB_Enum;
begin
inherited RegisterSystemScheme(scheme);
enum:=GFRE_DBI.NewEnum('tcr_signal_status').Setup(GFRE_DBI.CreateText('$enum_tcr_signal_status','signal status Enum'));
enum.addEntry('OK',GetTranslateableTextKey('enum_tcr_signal_status_ok'));
enum.addEntry('WARNING',GetTranslateableTextKey('enum_tcr_signal_status_warning'));
enum.addEntry('FAILURE',GetTranslateableTextKey('enum_tcr_signal_status_failure'));
enum.addEntry('UNKNOWN',GetTranslateableTextKey('enum_tcr_signal_status_unknown'));
GFRE_DBI.RegisterSysEnum(enum);
scheme.SetParentSchemeByName(TFRE_DB_STATUS_PLUGIN.ClassName);
//scheme.AddSchemeField('status',fdbft_String).SetupFieldDef(true,false,'tcr_signal_status');
scheme.AddSchemeField('statussummary',fdbft_String);
scheme.AddSchemeField('st',fdbft_DateTimeUTC);
scheme.AddSchemeField('et',fdbft_DateTimeUTC);
end;
class procedure TFRE_DB_JOBREPORTPLUGIN.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if (currentVersionId='') then begin
currentVersionId:='1.0';
StoreTranslateableText(conn,'enum_tcr_signal_status_ok','Ok');
StoreTranslateableText(conn,'enum_tcr_signal_status_warning','Warning');
StoreTranslateableText(conn,'enum_tcr_signal_status_failure','Failure');
StoreTranslateableText(conn,'enum_tcr_signal_status_unknown','Unknown');
end;
end;
{ TFRE_DB_TIMERTEST_JOB }
procedure TFRE_DB_TIMERTEST_JOB.InternalSetup;
begin
inherited InternalSetup;
SetMaxAllowedTime(86400);
end;
class procedure TFRE_DB_TIMERTEST_JOB.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName(TFRE_DB_JOB.ClassName);
end;
procedure TFRE_DB_TIMERTEST_JOB.SetTimeout(const value: integer);
begin
Field('testtimeout').asInt64 := value;
end;
procedure TFRE_DB_TIMERTEST_JOB.ExecuteJob;
var timeout: int64;
total : int64;
begin
timeout := Field('testtimeout').asint64;
total := timeout;
while timeout>0 do
begin
sleep(1000);
Field('timetogo').AsInt64 := timeout;
AddProgressLog('TIME','NOW WE HAVE '+inttostr(timeout)+' to go!',trunc((total-timeout)*100/total));
writeln('SWL JOBFILE:',DumpToString());
dec(timeout);
end;
AddProgressLog('DONE','Now we are done!',100);
writeln('SWL JOBFILE:',DumpToString());
end;
procedure FREDB_SiteMap_AddEntry(const SiteMapData : IFRE_DB_Object ; const key:string;const caption : String ; const icon : String ; InterAppLink : TFRE_DB_StringArray ;const x,y : integer; const newsCount:Integer; const scale:Single; const enabled:Boolean);
var i : integer;
//ial : TFOSStringArray;
key_arr : TFOSStringArray;
nodekey : String;
SiteMapEntry : IFRE_DB_Object;
ientry : integer;
found : boolean;
newentry : IFRE_DB_Object;
begin
GFRE_BT.SeperateString(key,'/',key_arr);
SiteMapEntry := SiteMapData;
for i := 0 to high(key_arr) do begin
nodekey := key_arr[i];
if i<high(key_arr) then begin
found := false;
for ientry := 0 to SiteMapEntry.Field('ENTRIES').ValueCount-1 do begin
if SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry].Field('ID').asstring = nodekey then begin
SiteMapEntry := SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry];
found := true;
break;
end;
end;
if found = false then begin
raise EFRE_DB_Exception.Create('SITEMAP ADDENTRY PARENT NOT FOUND '+key);
end;
end else begin
newentry := GFRE_DBI.NewObject;
SiteMapEntry.Field('ENTRIES').AddObject(newentry);
SiteMapEntry := newentry;
end;
end;
SiteMapEntry.Field('ID').AsString := nodekey;
SiteMapEntry.Field('NC').AsInt16 := newsCount;
SiteMapEntry.Field('CAP').AsString := caption;
SiteMapEntry.Field('ICO').AsString := icon;
//GFRE_BT.SeperateString(InterAppLink,':',ial);
SiteMapEntry.Field('IAL').AsStringArr := InterAppLink;
SiteMapEntry.Field('CRD').AsInt32Arr := TFRE_DB_Int32Array.Create(x,y);
SiteMapEntry.Field('SCL').AsReal32 := scale;
SiteMapEntry.Field('DIS').AsBoolean := not enabled;
end;
procedure FREDB_SiteMap_AddRadialEntry(const SiteMapData: IFRE_DB_Object; const key: string; const caption: String; const icon: String; InterAppLink: String; const newsCount: Integer; const enabled: Boolean);
var i : integer;
lvl : NativeInt;
ial : TFRE_DB_StringArray;
key_arr : TFOSStringArray;
nodeid : String;
SiteMapEntry : IFRE_DB_Object;
ientry : integer;
found : boolean;
newentry : IFRE_DB_Object;
begin
GFRE_BT.SeperateString(key,'/',key_arr);
lvl := Length(key_arr);
SiteMapEntry := SiteMapData;
for i := 0 to high(key_arr) do begin
nodeid := key_arr[i];
if i<high(key_arr) then begin
found := false;
for ientry := 0 to SiteMapEntry.Field('ENTRIES').ValueCount-1 do begin
if SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry].Field('ID').asstring = nodeid then begin
SiteMapEntry := SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry];
found := true;
break;
end;
end;
if found = false then begin
raise EFRE_DB_Exception.Create('SITEMAP ADDENTRY PARENT NOT FOUND '+key);
end;
end else begin
newentry := GFRE_DBI.NewObject;
SiteMapEntry.Field('ENTRIES').AddObject(newentry);
SiteMapEntry := newentry;
end;
end;
SiteMapEntry.Field('ID').AsString := nodeid;
SiteMapEntry.Field('NC').AsInt16 := newsCount;
SiteMapEntry.Field('CAP').AsString := caption;
SiteMapEntry.Field('ICO').AsString := icon;
FREDB_SeperateString(InterAppLink,':',ial); { class:class:class }
SiteMapEntry.Field('IAL').AsStringArr := ial;
SiteMapEntry.Field('LVL').AsInt32 := lvl;
SiteMapEntry.Field('DIS').AsBoolean := not enabled;
end;
procedure FREDB_SiteMap_RadialAutoposition(const SiteMapData: IFRE_DB_Object; rootangle:integer);
var
SiteMapRoot : IFRE_DB_Object;
x,y : integer;
xo,yo : integer;
r : Double;
scale : real;
lvl : integer;
procedure FREDB_PositionSitemapEntry (const angle : integer; const radius : Double; const origin_x, origin_y : integer; out x,y:integer);
var xr : double;
yr : double;
phi: double;
correct : double;
begin
correct := 1.15;
phi := (angle*pi)/180;
xr := radius * cos (phi);
yr := radius * sin (phi);
x := origin_x + round (xr * correct);
y := origin_y - round (yr);
// writeln ('Angle: ',angle, 'Phi:',phi, 'X: ',x, 'Y:',y);
end;
procedure PlaceChildren(const SiteMapEntry : IFRE_DB_OBject);
var
subcount : integer;
partangle : integer;
parentangle: integer;
minangle : integer;
maxangle : integer;
currangle : integer;
xp,yp : integer;
ientry : integer;
rangeangle : integer;
maxrange : integer;
lvl : Integer;
procedure PlaceSubentry(const subentry : IFRE_DB_Object);
var x,y : integer;
scl,rad : Double;
begin
lvl := subentry.Field('LVL').AsInt32;
case lvl of
2 :
begin
scl := 1.5;
rad := 360;
end;
3 :
begin
scl := 0.8;
rad := 220;
end;
4 :
begin
scl := 0.3;
rad := 100;
end;
5 :
begin
scl := 0.00;
rad := 50;
end
else
abort;
end;
subentry.Field('SCL').AsReal32 := scl*cFOS_RADIAL_SITEMAP_SCALE;
FREDB_PositionSitemapEntry(currangle, rad*cFOS_RADIAL_SITEMAP_SCALE, xp, yp, x, y);
subentry.Field('PNGL').asint32 := currangle;
subentry.Field('CRD').AsInt32Arr := TFRE_DB_Int32Array.Create(x,y);
dec(currangle,partangle);
if currangle<0 then begin
currangle := currangle + 360;
end;
end;
begin
maxrange := 135;
partangle := 0;
lvl := SiteMapEntry.Field('LVL').AsInt32;
subcount := SiteMapEntry.Field('ENTRIES').ValueCount;
if subcount>0 then begin
parentangle := SiteMapEntry.Field('PNGL').asint32;
if parentangle = -1 then begin // full circle
minangle := rootangle;
maxangle := minangle+360; { 360 }
partangle := (maxangle-minangle) div (subcount);
end else begin
if (lvl>1) and (subcount>4) then
rangeangle := (subcount-1) * (18)
else
rangeangle := (subcount-1) * (45 div 2);
if rangeangle > maxrange then begin
rangeangle := maxrange;
end;
minangle := parentangle - rangeangle;
maxangle := parentangle + rangeangle;
if subcount>1 then begin
partangle := (maxangle-minangle) div (subcount-1);
end;
end;
currangle := maxangle;
xp := SiteMapEntry.Field('CRD').AsInt32Item[0];
yp := SiteMapEntry.Field('CRD').AsInt32Item[1];
for ientry := 0 to SiteMapEntry.Field('ENTRIES').ValueCount-1 do begin
PlaceSubentry(SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry]);
PlaceChildren(SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry]);
end;
end;
end;
begin
xo := 300; yo := 300; r := 300; scale := 0.8;
rootangle := 90 - rootangle; // start at 12h, positive angle clockwise
SiteMapRoot:=SiteMapData.Field('ENTRIES').AsObjectItem[0];
if assigned(SiteMapRoot) then begin { Position RootNode }
lvl := SiteMapRoot.Field('LVL').AsInt32;
SiteMapRoot.Field('CRD').AsInt32Arr := TFRE_DB_Int32Array.Create(xo,yo);
SiteMapRoot.Field('SCL').AsReal32 := 2 * cFOS_RADIAL_SITEMAP_SCALE;
SiteMapRoot.Field('PNGL').asint32 := -1; // Place Children in full circle
PlaceChildren(SiteMapRoot);
end;
end;
procedure FREDB_SiteMap_DisableEntry(const SiteMapData: IFRE_DB_Object; const key: string);
var i : integer;
lvl : NativeInt;
ial : TFRE_DB_StringArray;
key_arr : TFOSStringArray;
nodeid : String;
SiteMapEntry : IFRE_DB_Object;
ientry : integer;
found : boolean;
newentry : IFRE_DB_Object;
begin
GFRE_BT.SeperateString(key,'/',key_arr);
lvl := Length(key_arr);
SiteMapEntry := SiteMapData;
for i := 0 to high(key_arr) do begin
nodeid := key_arr[i];
found := false;
for ientry := 0 to SiteMapEntry.Field('ENTRIES').ValueCount-1 do begin
if SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry].Field('ID').asstring = nodeid then begin
SiteMapEntry := SiteMapEntry.Field('ENTRIES').AsObjectItem[ientry];
found := true;
break;
end;
end;
if found = false then begin
raise EFRE_DB_Exception.Create('SITEMAP ADDENTRY PARENT NOT FOUND '+key);
end;
end;
SiteMapEntry.Field('DIS').AsBoolean := true;
end;
function FREDB_GuidArray2StringStream(const arr: TFRE_DB_GUIDArray): String;
var i : NativeInt;
begin
result := '[';
for i:=0 to high(arr) do
result:=result+FREDB_G2H(arr[i])+',';
if Length(arr)>0 then
result[Length(result)] :=']'
else
result:=result+']';
end;
function FREDB_StreamString2GuidArray(str: string): TFRE_DB_GUIDArray;
var sa : TFOSStringArray;
i : NativeInt;
s : string;
begin
str:=trim(str);
s := copy(str,2,Length(str)-2);
GFRE_BT.SeperateString(s,',',sa);
SetLength(result,length(sa));
for i:= 0 to high(sa) do
result[i] := FREDB_H2G(sa[i]);
end;
function FREDB_Get_Rightname_UID(const rightprefix: string; const id: TFRE_DB_GUID): string;
begin
result := uppercase(rightprefix)+'_'+FREDB_G2H(id);
end;
function FREDB_Get_Rightname_UID_STR(const rightprefix: string; const id_str: String): string;
begin
result := uppercase(rightprefix)+'_'+UpperCase(id_str);
end;
procedure FREDB_SplitLocalatDomain(const localatdomain: TFRE_DB_String; var localpart, domainpart: TFRE_DB_String);
begin
if Pos('@',localatdomain)=0 then raise EFRE_DB_Exception.Create('No @ in the full domain name '+localatdomain);
localpart := GFRE_BT.SepLeft(localatdomain,'@');
domainpart := GFRE_BT.SepRight(localatdomain,'@');
end;
function FREDB_GetDboAsBufferLen(const dbo: IFRE_DB_Object; var mem: Pointer): UInt32;
var len : UInt32;
ns : UInt32;
begin
ns := dbo.NeededSize;
Getmem(mem,ns+4);
dbo.CopyToMemory(mem+4);
PCardinal(mem)^:=ns;
result := ns+4;
end;
procedure FREDB_SetStringFromExistingFieldPathOrNoChange(const obj: IFRE_DB_Object; const fieldpath: string; var string_fld: TFRE_DB_String);
begin
if obj.FieldPathExists(fieldpath) then
begin
if obj.FieldPath(fieldpath).IsSpecialClearMarked then
string_fld := ''
else
string_fld := obj.FieldPath(fieldpath).AsString
end
else
string_fld := cFRE_DB_SYS_NOCHANGE_VAL_STR;
end;
function FREDB_HCV(const txt: TFRE_DB_String): TFRE_DB_String;
begin
if txt<>cFRE_DB_SYS_CLEAR_VAL_STR then
result := txt
else
result := '';
end;
function FREDB_IniLogCategory2LogCategory(const ini_logcategory: string): TFRE_DB_LOGCATEGORY;
begin
for result in TFRE_DB_LOGCATEGORY do begin
if CFRE_DB_LOGCATEGORY_INI_IDENT[result]=ini_logcategory then exit;
end;
raise EFRE_DB_Exception.Create('invalid db logcategory specifier : ['+ini_logcategory+']');
end;
function FREDB_String2EscapedJSString(const input_string: TFRE_DB_String; const replace_cr_with_br: boolean): TFRE_DB_String;
begin
result := StringReplace(input_string ,'\' , '\u005C', [rfReplaceAll]); // Backslash
result := StringReplace(result ,#0 , '\u0000', [rfReplaceAll]); // 0 Char
result := StringReplace(Result ,#8 , '\u0008', [rfReplaceAll]); // Backspace
result := StringReplace(Result ,#9 , '\u0009', [rfReplaceAll]); // Horizontal Tab
if not replace_cr_with_br then begin
result := StringReplace(Result ,#13#10 , '\u000A', [rfReplaceAll]); // WINDOWS to Single CR
result := StringReplace(Result ,#10 , '\u000A', [rfReplaceAll]); // CR
result := StringReplace(Result ,#13 , '\u000D', [rfReplaceAll]); // LF
end else begin
result := StringReplace(Result ,#13#10 , '<br>', [rfReplaceAll]); // WINDOWS to Single CR
result := StringReplace(Result ,#10 , '<br>', [rfReplaceAll]); // CR
result := StringReplace(Result ,#13 , '<br>', [rfReplaceAll]); // LF
end;
result := StringReplace(Result ,'"' , '\u0022', [rfReplaceAll]); // Double Qoute
result := StringReplace(Result ,'''' , '\u0027', [rfReplaceAll]); // Single Quote
end;
procedure FREDB_ApplyNotificationBlockToNotifIF(const block: IFRE_DB_Object; const deploy_if: IFRE_DB_DBChangedNotification; var layer: TFRE_DB_NameType);
var cmd : ShortString;
objs : IFRE_DB_ObjectArray;
i : NativeInt;
tsid : TFRE_DB_TransStepId;
begin
//writeln('----DUMP NOTIFY BLOCK');
//writeln(block.DumpToString());
//writeln('----DUMP NOTIFY BLOCK');
objs := block.Field('N').AsObjectArr;
layer := block.Field('L').AsString;
try
for i:=0 to High(objs) do
with objs[i] do
begin
cmd := Field('C').AsString;
tsid := Field('TSID').AsString;
assert(tsid<>'transaction id step must be set');
try
case cmd of
'CC' : deploy_if.CollectionCreated(Field('CC').AsString,Field('CV').AsBoolean,tsid);
'CD' : deploy_if.CollectionDeleted(Field('CC').AsString,tsid);
'IC' : deploy_if.IndexDefinedOnField(Field('CC').AsString,Field('FN').AsString,FREDB_FieldtypeShortString2Fieldtype(Field('FT').AsString),Field('UI').AsBoolean,Field('IC').AsBoolean,Field('IN').AsString,Field('AN').AsBoolean,Field('UN').AsBoolean,tsid);
'ID' : deploy_if.IndexDroppedOnField(Field('CC').AsString,Field('IN').AsString,tsid);
'OS' : deploy_if.ObjectStored(Field('CC').AsString,Field('obj').CheckOutObject,tsid);
'OU' : deploy_if.ObjectUpdated(Field('obj').CheckOutObject,Field('CC').AsStringArr,tsid);
'OD' : deploy_if.ObjectDeleted(FREDB_StringArray2NametypeArray(Field('CC').AsStringArr),Field('obj').CheckOutObject,tsid);
'OR' : deploy_if.ObjectRemoved(FREDB_StringArray2NametypeArray(Field('CC').AsStringArr),Field('obj').CheckOutObject,Field('fd').AsBoolean,tsid);
'FD' : deploy_if.FieldDelete(Field('FLD').AsObject._InternalDecodeAsField,tsid); { Field is created new .. free it in the deploy if }
'FA' : deploy_if.FieldAdd(Field('FLD').AsObject._InternalDecodeAsField,tsid); { Field is created new .. free it in the deploy if }
'FC' : deploy_if.FieldChange(Field('FLDO').AsObject._InternalDecodeAsField,Field('FLDN').AsObject._InternalDecodeAsField,tsid); { Field is created new .. free it in the deploy if }
'SOL' : deploy_if.SetupOutboundRefLink (field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
'SIL' : deploy_if.SetupInboundRefLink (field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
'DOL' : deploy_if.OutboundReflinkDropped(field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
'DIL' : deploy_if.InboundReflinkDropped (field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
'DUS' : deploy_if.DifferentiallUpdStarts(field('O').CheckOutObject,tsid);
'DUE' : deploy_if.DifferentiallUpdEnds(field('O').AsGUID,tsid);
else
raise EFRE_DB_Exception.Create(edb_ERROR,'undefined block notification encoding : '+cmd);
end;
except on
e:exception do
begin
GFRE_DBI.LogError(dblc_PERSISTANCE_NOTIFY,'APPLYNOTIFBLOCK [%s] failed due to [%s] on Step [%d of %d]',[cmd,e.Message,i,High(objs)]);
end;
end;
end;
finally
layer := '';
end;
end;
procedure FREDB_ApplyNotificationBlockToNotifIF_Connection(const block: IFRE_DB_Object; const deploy_if: IFRE_DB_DBChangedNotificationConnection);
var cmd : ShortString;
key : TFRE_DB_String;
objs : IFRE_DB_ObjectArray;
i : NativeInt;
tsid : TFRE_DB_TransStepId;
begin
objs := block.Field('N').AsObjectArr;
key := block.Field('KEY').AsString;
for i:=0 to High(objs) do
with objs[i] do
begin
cmd := Field('C').AsString;
tsid := Field('TSID').AsString;
assert(tsid<>'transaction id step must be set');
case cmd of
'CC' : deploy_if.CollectionCreated(Field('CC').AsString,Field('CV').AsBoolean,tsid);
'CD' : deploy_if.CollectionDeleted(Field('CC').AsString,tsid);
'IC' : deploy_if.IndexDefinedOnField(Field('CC').AsString,Field('FN').AsString,FREDB_FieldtypeShortString2Fieldtype(Field('FT').AsString),Field('UI').AsBoolean,Field('IC').AsBoolean,Field('IN').AsString,Field('AN').AsBoolean,Field('UN').AsBoolean,tsid);
'ID' : deploy_if.IndexDroppedOnField(Field('CC').AsString,Field('IN').AsString,tsid);
end;
end;
end;
procedure FREDB_ApplyNotificationBlockToNotifIF_Session(const block: IFRE_DB_Object; const deploy_if: IFRE_DB_DBChangedNotificationSession);
var cmd : ShortString;
objs : IFRE_DB_ObjectArray;
i : NativeInt;
tsid : TFRE_DB_TransStepId;
begin
objs := block.Field('N').AsObjectArr;
for i:=0 to High(objs) do
with objs[i] do
begin
cmd := Field('C').AsString;
tsid := Field('TSID').AsString;
assert(tsid<>'transaction id step must be set');
case cmd of
'FD' : deploy_if.FieldDelete(Field('FLD').AsObject._InternalDecodeAsField,tsid);
'FA' : deploy_if.FieldAdd(Field('FLD').AsObject._InternalDecodeAsField,tsid);
'FC' : deploy_if.FieldChange(Field('FLDO').AsObject._InternalDecodeAsField,Field('FLDN').AsObject._InternalDecodeAsField,tsid);
'DUS' : deploy_if.DifferentiallUpdStarts(field('O').AsObject,tsid);
'DUE' : deploy_if.DifferentiallUpdEnds(field('O').AsGUID,tsid);
'OU' : deploy_if.ObjectUpdated(Field('obj').CheckOutObject,Field('CC').AsStringArr,tsid);
'OD' : deploy_if.ObjectDeleted(FREDB_StringArray2NametypeArray(Field('CC').AsStringArr),Field('obj').CheckOutObject,tsid);
'SIL' : deploy_if.SetupInboundRefLink (field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
'DIL' : deploy_if.InboundReflinkDropped (field('FO').CheckOutObject,field('TO').CheckOutObject,field('KD').AsString,tsid);
end;
end;
end;
function FREDB_PP_ExtendParentPath(const uid: TFRE_DB_GUID; const pp: TFRE_DB_String): TFRE_DB_String;
begin
if pp='' then
result := uid.AsHexString
else
result := uid.AsHexString+'@'+pp; { extend reverse (!) to match client spec }
end;
function FREDB_TransformException2ec(const e: exception; const lineinfo: shortstring): TFRE_DB_Errortype;
begin
if e is EFRE_DB_Exception then
begin
result.SetIt(EFRE_DB_Exception(e).ErrorType,EFRE_DB_Exception(e).Message,lineinfo);
end
else
if e is EFRE_DB_PL_Exception then
begin
result.SetIt(EFRE_DB_PL_Exception(e).ErrorType,EFRE_DB_PL_Exception(e).Message,lineinfo);
end
else
begin
result.SetIt(edb_ERROR,'UERR: '+e.Message,lineinfo);
end;
end;
procedure FREDB_ShellExpandFixUserPath(var path_var:string);
begin
if pos('~',path_var)>0 then
begin
path_var := StringReplace(path_var,'~',GetUserDir,[]);
end;
if pos ('$',path_var)>0 then
begin
path_var := StringReplace(path_var,'$',cFRE_SERVER_DEFAULT_DIR,[]);
end;
if pos ('#',path_var)>0 then
begin
if cFRE_CONFIG_MODE then
path_var := StringReplace(path_var,'#',cFRE_CONFIG_BINARY_ROOT,[])
else
path_var := StringReplace(path_var,'#',cFRE_SERVER_DEFAULT_DIR,[])
end;
path_var := StringReplace(path_var,DirectorySeparator+DirectorySeparator,DirectorySeparator,[]);
end;
procedure FREDB_StringWrite2Stream(const msg: TFRE_DB_String; const str: TStream);
var line : TFRE_DB_String;
len : integer;
lens : TFRE_DB_String;
begin
line := msg+#13#10;
len := Length(line);
lens := IntToStr(len)+'C';
str.Write(Pointer(@lens[1])^,Length(lens));
str.Write(Pointer(@line[1])^,Length(line));
end;
function FREDB_ReadJSONEncodedObject(const str: TStream): IFRE_DB_Object;
var line : TFRE_DB_String;
elem : Byte;
count : Integer;
pos : integer;
begin
pos := 1;
repeat
elem := str.ReadByte;
inc(pos);
if char(elem)<>'C' then begin
line := line + char(elem);
end else break;
until false;
count := StrToInt(line);
SetLength(line,count-2);
str.ReadBuffer(line[1],count-2);
str.ReadByte;str.ReadByte;
result := GFRE_DBI.CreateFromJSONString(line);
end;
procedure FREDB_DumpDboEx(dbo: IFRE_DB_Object; const form: TFRE_DBO_DUMP_FORMAT; const filename: string);
begin
if not assigned(dbo) then
exit;
if filename<>'' then
begin
case form of
sdf_Binary:
dbo.SaveToFile(filename);
sdf_DBODump:
GFRE_BT.StringToFile(filename,dbo.DumpToString);
sdf_JSON_Encoded:
GFRE_BT.StringToFile(filename,dbo.GetAsJSONString(false,true));
sdf_JSON:
GFRE_BT.StringToFile(filename,dbo.GetAsJSONString(false,false));
sdf_JSON_SHORT:
GFRE_BT.StringToFile(filename,dbo.GetAsJSONString(true,false));
end;
end
else
begin
case form of
sdf_Binary:
dbo.SaveToFileHandle(StdOutputHandle);
sdf_DBODump:
writeln(dbo.DumpToString);
sdf_JSON_Encoded:
writeln(dbo.GetAsJSONString(false,true));
sdf_JSON:
writeln(dbo.GetAsJSONString(false,false));
sdf_JSON_SHORT:
writeln(dbo.GetAsJSONString(true,false));
end;
end;
end;
function FREDB_ApplyChangesFromTaggedUniqueObjectToObject(const to_update_object: IFRE_DB_Object; const source_object: IFRE_DB_Object; const ignore_fields: TFRE_DB_NameTypeArray; const unique_tag_field_name: TFRE_DB_NameType; const dry_run: boolean; const record_changes: IFOS_STRINGS; const dont_delete_plugin_deleted: boolean): NativeInt; { report changecount }
var ignu : TFRE_DB_NameTypeArray;
procedure _Update(const is_child_update : boolean ; const update_obj : IFRE_DB_Object ; const update_type :TFRE_DB_ObjCompareEventType ;const new_field, old_field: IFRE_DB_Field);
var line : string;
splug : TFRE_DB_STATUS_PLUGIN;
function childdata : string;
var pf : IFRE_DB_Field;
begin
pf := update_obj.ParentField;
if assigned(pf) then
result := BoolToStr(is_child_update,'CHILD '+update_obj.SchemeClass+' '+update_obj.UID_String+' ('+pf.FieldName+')','')
else
result := BoolToStr(is_child_update,'CHILD '+update_obj.SchemeClass+' '+update_obj.UID_String+' (-)','')
end;
begin
case update_type of
cev_FieldDeleted:
begin
if FREDB_StringInNametypeArray(old_field.FieldName,ignu) then
exit;
if (dont_delete_plugin_deleted) and (old_field.IsObjectField) and (old_field.AsObject.HasPlugin(TFRE_DB_STATUS_PLUGIN,splug)) then
begin
if splug.isPlanned then
exit;
if splug.isDeleted then
exit;
end;
if assigned(record_changes) then
begin
WriteStr(line,childdata,' DELETED FIELD ',old_field.FieldName,'(',CFRE_DB_FIELDTYPE[old_field.FieldType],') ',old_field.AsString);
record_changes.add(line);
end;
inc(result);
if not dry_run then
update_obj.DeleteField(old_field.FieldName);
end;
cev_FieldAdded:
begin
if FREDB_StringInNametypeArray(new_field.FieldName,ignu) then
exit;
if assigned(record_changes) then
begin
WriteStr(line,childdata,' ADDED FIELD ',new_field.FieldName,'(',CFRE_DB_FIELDTYPE[new_field.FieldType],') ',new_field.AsString);
record_changes.add(line);
end;
inc(result);
if not dry_run then
update_obj.Field(new_field.FieldName).CloneFromField(new_field);
end;
cev_FieldChanged:
begin
if new_field.IsObjectField then
begin
if old_field.ParentObject.Field(unique_tag_field_name).AsString=new_field.ParentObject.Field(unique_tag_field_name).AsString then
begin
exit;
end;
end;
if new_field.IsUIDField or new_field.IsDomainIDField then
exit; { IGNORING UID,DOMAINID UPDATE, UIDS FROM DB ARE STABLE }
if FREDB_StringInNametypeArray(new_field.FieldName,ignu) then
exit;
if Assigned(record_changes) then
begin
WriteStr(line,childdata,' CHANGED ',new_field.FieldName,' (',CFRE_DB_FIELDTYPE[new_field.FieldType],') ',old_field.AsString,'->',new_field.AsString);
record_changes.add(line);
end;
inc(result);
if not dry_run then
update_obj.Field(new_field.FieldName).CloneFromField(new_field);
end;
end;
end;
var uct_s,uct_t : TFRE_DB_String;
begin
result := 0;
uct_s := source_object.Field(unique_tag_field_name).AsString;
uct_t := to_update_object.Field(unique_tag_field_name).AsString;
if uct_s<>uct_t then
raise EFRE_DB_Exception.Create(edb_ERROR,'when applying changes form one object to the other the root unique tags must be the same ! [%s <> %s]',[uct_s,uct_t]);
ignu := FREDB_NametypeArray2Upper(ignore_fields);
GFRE_DBI.GenerateAnObjChangeListTagField(unique_tag_field_name,source_object,to_update_object,nil,nil,@_Update);
end;
function FREDB_IsFieldNameInIgnoreList(const fn: TFRE_DB_NameType): boolean;
begin
result := FREDB_StringInNametypeArray(uppercase(fn),cFRE_DB_IGNORE_SYS_FIELD_NAMES);
end;
function FREDB_CheckUniqueTags(const obj: IFRE_DB_Object; skip_root: boolean; const raise_ex: boolean; const dump_tags: boolean): boolean;
var checklist : IFOS_STRINGS;
procedure check(const obj:IFRE_DB_Object; var halt:boolean);
var uct : string;
fld : IFRE_DB_Field;
begin
if skip_root then
begin
skip_root := false;
exit;
end;
if not obj.FieldOnlyExisting('UCT',fld) then
begin
halt := true;
result := false;
if raise_ex then
raise EFRE_DB_Exception.Create(edb_ERROR,'missing unique tag field "UCT" in object [%s]',[obj.GetDescriptionID(false)]);
end;
uct := fld.AsString;
if uct='' then
begin
halt := true;
result := false;
if raise_ex then
raise EFRE_DB_Exception.Create(edb_ERROR,'empty value for unique tag field "UCT" in object [%s]',[obj.GetDescriptionID]);
end;
try
if dump_tags then
writeln(obj.GetDescriptionID(false),'UCT = ',uct);
checklist.Add(uct);
except
if raise_ex then
raise EFRE_DB_Exception.Create(edb_ERROR,'found duplicate unique tag field "UCT" TAG=[%s] in object [%s]',[uct,obj.GetDescriptionID]);
halt := true;
result := false;
end;
end;
begin
result := true;
checklist := GFRE_TF.Get_FOS_Strings;
checklist.SetSorted(true);
checklist.SetDuplicates(dupError);
obj.ForAllObjectsBreakHierarchic(@check);
end;
procedure FREDB_CheckFieldnameLength(const fn: string);
begin
if Length(fn)>SizeOf(TFRE_DB_NameType) then
begin
raise EFRE_DB_Exception.Create(edb_ERROR,'CHECK: fieldname is to long to be unique [%s] len= %d > max=%d',[fn,Length(fn),SizeOf(TFRE_DB_NameType)]);
end;
end;
function FREDB_GetPoolNameFromDatasetorDirectory(const ds_or_dir: string): String;
begin
if ds_or_dir='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'empty input for FREDB_GetPoolNameFromDatasetorDirectory');
if ds_or_dir[1]='/' then
result := Copy(ds_or_dir,2,maxint)
else
result := ds_or_dir;
if pos('/',Result)>0 then
result := GFRE_BT.SepLeft(Result,'/');
if result='' then
raise EFRE_DB_Exception.Create(edb_ERROR,'invalid input for FREDB_GetPoolNameFromDatasetorDirectory');
end;
operator=(e1: TFRE_DB_Errortype; e2: TFRE_DB_Errortype_EC)b: boolean;
begin
result := e1.Code = e2;
end;
operator=(e1: TFRE_DB_Errortype_EC; e2: TFRE_DB_Errortype)b: boolean;
begin
result := e1 = e2.Code;
end;
operator:=(e1: TFRE_DB_Errortype)r: TFRE_DB_Errortype_EC;
begin
result := e1.Code;
end;
operator:=(e1: TFRE_DB_Errortype_EC)r: TFRE_DB_Errortype;
begin
result.Code:=e1;
result.Msg:='';
end;
operator:=(o1: array of TFRE_DB_String)b: TFRE_DB_StringArray;
begin
result := FREDB_StringArrayOpen2StringArray(o1);
end;
operator:=(o1: array of TFRE_DB_NameType)b: TFRE_DB_NameTypeArray;
begin
result := FREDB_NametypeArrayOpen2NametypeArray(o1);
end;
operator:=(o1: array of TFRE_DB_GUID)b: TFRE_DB_GUIDArray;
begin
result := FREDB_GuidArrayOpen2GuidArray(o1);
end;
type
{ TFRE_DBI_REG_EXTMGR }
TFRE_DBI_REG_EXTMGR=class(TOBJECT,IFRE_DB_EXTENSION_MNGR)
private
FExtlist : TObjectList;
public
constructor create ;
destructor destroy ; override ;
procedure Finalize ;
function GetExtensionList : IFOS_STRINGS;
procedure ForAllExtensions (const iterator: IFRE_DB_EXTENSION_Iterator);
procedure RegisterNewExtension (const extension_name : String ; const MetaRegistrationFunction : IFRE_DB_EXTENSION_RegisterCB ; const MetaRegisterInitDBFunction : IFRE_DB_EXTENSION_INITDB_CB; const MetaRegisterRemoveFunction : IFRE_DB_EXTENSION_REMOVE_CB ; const MetaGentestdata : IFRE_DB_EXTENSION_INITDB_CB = nil ; const MetaGenUnitTest : IFRE_DB_EXTENSION_INITDB_CB = nil);
procedure RegisterExtensions4DB (const list:IFOS_STRINGS);
procedure InitDatabase4Extensions (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure GenerateTestData4Exts (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure GenerateUnitTestsdata (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
procedure Remove4Extensions (const list: IFOS_STRINGS ; const db:string ; const user,pass:string);
end;
{ TFRE_DB_EXTENSION_GRP }
TFRE_DB_EXTENSION_GRP = class(TObject,IFRE_DB_EXTENSION_GRP)
private
FCallBack : IFRE_DB_EXTENSION_RegisterCB;
FCallBackDB : IFRE_DB_EXTENSION_INITDB_CB;
FCallBackREM : IFRE_DB_EXTENSION_REMOVE_CB;
FCallBAckTestdata : IFRE_DB_EXTENSION_INITDB_CB;
FCallbackUnitTest : IFRE_DB_EXTENSION_INITDB_CB;
Fname : TFRE_DB_String;
public
function GetExtensionName : TFRE_DB_String;
procedure RegisterExtensionAndDependencies ;
procedure InitializeDatabaseForExtension (const db_name : string ; const user,pass:string);
procedure GenerateTestdataForExtension (const db_name : string ; const user,pass:string);
procedure DoUnitTestforExtension (const db_name : string ; const user,pass:string);
procedure RemoveForExtension (const db_name: string; const user, pass: string);
end;
{ TFRE_DB_EXTENSION_GRP }
function TFRE_DB_EXTENSION_GRP.GetExtensionName: TFRE_DB_String;
begin
result := FName;
end;
procedure TFRE_DB_EXTENSION_GRP.RegisterExtensionAndDependencies;
begin
FCallBack();
end;
procedure TFRE_DB_EXTENSION_GRP.InitializeDatabaseForExtension(const db_name: string; const user, pass: string);
begin
FCallBackDB(db_name,user,pass);
end;
procedure TFRE_DB_EXTENSION_GRP.GenerateTestdataForExtension(const db_name: string; const user, pass: string);
begin
if Assigned(FCallBAckTestdata) then
FCallBAckTestdata(db_name,user,pass);
end;
procedure TFRE_DB_EXTENSION_GRP.DoUnitTestforExtension(const db_name: string; const user, pass: string);
begin
if Assigned(FCallbackUnitTest) then
FCallbackUnitTest(db_name,user,pass);
end;
procedure TFRE_DB_EXTENSION_GRP.RemoveForExtension(const db_name: string; const user, pass: string);
begin
FCallBackREM(db_name,user,pass);
end;
{ TFRE_DBI_REG_EXTMGR }
constructor TFRE_DBI_REG_EXTMGR.create;
begin
inherited;
FExtlist := TObjectList.create(true);
end;
destructor TFRE_DBI_REG_EXTMGR.destroy;
begin
FExtlist.free;
inherited destroy;
end;
procedure TFRE_DBI_REG_EXTMGR.Finalize;
begin
Destroy;
end;
function TFRE_DBI_REG_EXTMGR.GetExtensionList: IFOS_STRINGS;
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
result.add(ext.GetExtensionName);
end;
begin
result := GFRE_TF.Get_FOS_Strings;
ForAllExtensions(@Iterate);
end;
procedure TFRE_DBI_REG_EXTMGR.ForAllExtensions(const iterator: IFRE_DB_EXTENSION_Iterator);
var i : integer;
ext : TFRE_DB_EXTENSION_GRP;
begin
for i := 0 to FExtlist.Count-1 do begin
iterator(FExtlist[i] as TFRE_DB_EXTENSION_GRP);
end;
end;
procedure TFRE_DBI_REG_EXTMGR.RegisterNewExtension(const extension_name: String; const MetaRegistrationFunction: IFRE_DB_EXTENSION_RegisterCB; const MetaRegisterInitDBFunction: IFRE_DB_EXTENSION_INITDB_CB; const MetaRegisterRemoveFunction: IFRE_DB_EXTENSION_REMOVE_CB; const MetaGentestdata: IFRE_DB_EXTENSION_INITDB_CB; const MetaGenUnitTest: IFRE_DB_EXTENSION_INITDB_CB);
var i : integer;
new_ext : TFRE_DB_EXTENSION_GRP;
begin
for i := 0 to FExtlist.Count-1 do begin
with FExtlist[i] as TFRE_DB_EXTENSION_GRP do begin
if lowercase(GetExtensionName) = lowercase(extension_name) then exit; // already registerd
end;
end;
new_ext := TFRE_DB_EXTENSION_GRP.Create;
new_ext.Fname := extension_name;
new_ext.FCallBack := MetaRegistrationFunction;
new_ext.FCallBackDB := MetaRegisterInitDBFunction;
new_ext.FCallBackREM := MetaRegisterRemoveFunction;
new_ext.FCallBAckTestdata := MetaGentestdata;
new_ext.FCallbackUnitTest := MetaGenUnitTest;
FExtlist.Add(new_ext);
end;
procedure TFRE_DBI_REG_EXTMGR.RegisterExtensions4DB(const list: IFOS_STRINGS);
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
if list.IndexOf(ext.GetExtensionName)>-1 then begin
ext.RegisterExtensionAndDependencies;
end;
end;
begin
list.SetCaseSensitive(false);
ForAllExtensions(@Iterate);
end;
procedure TFRE_DBI_REG_EXTMGR.InitDatabase4Extensions(const list: IFOS_STRINGS ; const db: string; const user, pass: string);
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
if list.IndexOf(ext.GetExtensionName)>-1 then begin
ext.InitializeDatabaseForExtension(db,user,pass);
end;
end;
begin
list.SetCaseSensitive(false);
ForAllExtensions(@Iterate);
end;
procedure TFRE_DBI_REG_EXTMGR.GenerateTestData4Exts(const list: IFOS_STRINGS; const db: string; const user, pass: string);
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
if list.IndexOf(ext.GetExtensionName)>-1 then begin
ext.GenerateTestdataForExtension(db,user,pass);
end;
end;
begin
list.SetCaseSensitive(false);
ForAllExtensions(@Iterate);
end;
procedure TFRE_DBI_REG_EXTMGR.GenerateUnitTestsdata(const list: IFOS_STRINGS; const db: string; const user, pass: string);
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
if list.IndexOf(ext.GetExtensionName)>-1 then begin
ext.DoUnitTestforExtension(db,user,pass);
end;
end;
begin
list.SetCaseSensitive(false);
ForAllExtensions(@Iterate);
end;
procedure TFRE_DBI_REG_EXTMGR.Remove4Extensions(const list: IFOS_STRINGS; const db: string; const user, pass: string);
procedure Iterate(const ext : IFRE_DB_EXTENSION_GRP);
begin
if list.IndexOf(ext.GetExtensionName)>-1 then begin
writeln('REMOVING APPS : ',ext.GetExtensionName,' DB : ',db);
ext.RemoveForExtension(db,user,pass);
end;
end;
begin
list.SetCaseSensitive(false);
ForAllExtensions(@Iterate);
end;
initialization
assert(sizeof(TFRE_DB_GUID_Access)=16);
assert(SizeOf(TFRE_DB_NameType)=64);
assert(CFRE_DB_NullGUID < CFRE_DB_MaxGUID);
assert(CFRE_DB_MaxGUID > CFRE_DB_NullGUID);
assert(CFRE_DB_MaxGUID = CFRE_DB_MaxGUID);
GFRE_DBI_REG_EXTMGR := TFRE_DBI_REG_EXTMGR.create;
finalization
GFRE_DBI_REG_EXTMGR.Finalize;
end.
|
unit API_Yandex;
interface
uses
API_HTTP;
type
TTransDirection = (tdRuEn, tdRuUa, tdEnRu);
TYaTranslater = class
private
FHTTP: THTTP;
FIDKey: string;
function GetIDKey: string;
function GetLangParam(aTransDirection: TTransDirection): string;
function GetPartArr(aText: string): TArray<string>;
function ProcessJSONResponse(aResponse: string): string;
public
function Translate(aTransDirection: TTransDirection; aText: string): string;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
API_Files,
API_Strings,
System.Classes,
System.JSON,
System.SysUtils;
function TYaTranslater.GetPartArr(aText: string): TArray<string>;
var
i: Integer;
Part: string;
Sub: string;
TextRest: string;
begin
Result := [];
TextRest := aText;
while TextRest.Length > 0 do
begin
Part := TextRest.Substring(0, 10000);
TextRest := TextRest.Substring(10000, TextRest.Length);
if TextRest.Length > 0 then
for i := Part.Length downto 1 do
if (Part[i] = '.') or
(Part[i] = #10) or
(Part[i] = #13)
then
begin
Sub := Part.Substring(i, Part.Length);
Part := Part.Remove(i, Part.Length);
TextRest := Sub + TextRest;
Break;
end;
Result := Result + [Part];
end;
end;
function TYaTranslater.GetLangParam(aTransDirection: TTransDirection): string;
begin
Result := '';
case aTransDirection of
tdRuEn: Result := 'ru-en';
tdRuUa: Result := 'ru-uk';
tdEnRu: Result := 'en-ru';
end;
end;
function TYaTranslater.ProcessJSONResponse(aResponse: string): string;
var
jsnResponse: TJSONObject;
jsnValueArr: TJSONArray;
begin
try
jsnResponse := TJSONObject.ParseJSONValue(aResponse) as TJSONObject;
jsnValueArr := jsnResponse.GetValue('text') as TJSONArray;
Result := jsnValueArr.Items[0].Value;
finally
if Assigned(jsnResponse) then
jsnResponse.Free;
end;
end;
destructor TYaTranslater.Destroy;
begin
FHTTP.Free;
inherited;
end;
constructor TYaTranslater.Create;
begin
FHTTP := THTTP.Create;
end;
function TYaTranslater.GetIDKey: string;
var
NewSIDArr: TArray<string>;
Page: string;
SID: string;
SIDItem: string;
SIDArr: TArray<string>;
begin
Page := FHTTP.Get('https://translate.yandex.by');
SID := TStrTool.CutByKey(Page, 'SID: ''', '''');
SIDArr := SID.Split(['.']);
for SIDItem in SIDArr do
NewSIDArr := NewSIDArr + [TStrTool.Reverse(SIDItem)];
Result := Result.Join('.', NewSIDArr);
end;
function TYaTranslater.Translate(aTransDirection: TTransDirection; aText: string): string;
var
i: Integer;
LangParam: string;
PartArr: TArray<string>;
SL: TStringList;
strJSONResponse: string;
URL: string;
begin
if FIDKey.IsEmpty then
FIDKey := GetIDKey;
LangParam := GetLangParam(aTransDirection);
PartArr := GetPartArr(aText);
URL := 'https://translate.yandex.net/api/v1/tr.json/translate?id=%s-0-0&srv=tr-touch&lang=%s&reason=auto';
URL := Format(URL, [FIDKey, LangParam]);
SL := TStringList.Create;
try
Result := '';
for i := 0 to Length(PartArr) - 1 do
begin
SL.Clear;
SL.Add('text=' + PartArr[i]);
SL.Add('options=0');
strJSONResponse := FHTTP.Post(URL, SL);
if i > 0 then Result := Result + ' ';
Result := Result + ProcessJSONResponse(strJSONResponse);
end;
finally
SL.Free;
end;
end;
end.
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
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.2 2000/07/14 17:37:16 mghie 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.
}
unit SynHighlighterMyGeneral;
{$I SynEdit.inc}
interface
uses
SysUtils, Windows, Messages, Classes, Controls, Graphics,
SynEditTypes, SynEditHighlighter;
type
TtkTokenKind = (tkComment, tkIdentifier, tkKey1, tkKey2, tkKey3, tkNull, tkNumber,
tkPreprocessor, tkSpace, tkString, tkSymbol, tkUnknown); // DJLP 2000-06-18
TRangeState = (rsANil, rsBlockComment, rsMultilineString, rsUnKnown);
TProcTableProc = procedure of object;
type
TSynMyGeneralSyn = class(TSynCustomHighlighter)
private
FLanguageName :string;
fRange: TRangeState;
fLine: PChar;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fLineNumber : Integer;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri1: TSynHighlighterAttributes;
fKeyAttri2: TSynHighlighterAttributes;
fKeyAttri3: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fPreprocessorAttri: TSynHighlighterAttributes; // DJLP 2000-06-18
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fKeyWords1: TStrings;
fKeyWords2: TStrings;
fKeyWords3: TStrings;
fIdentChars: TSynIdentChars;
fNumConstChars: TSynIdentChars;
fNumBegChars: TSynIdentChars;
fDetectPreprocessor: boolean; // DJLP 2000-06-18
FLineComment :string;
FCommentBeg :string;
FCommentEnd :string;
FStrBegChar :char;
FStrEndChar :char;
FMultilineStrings :boolean;
Identifiers: array[#0..#255] of ByteBool;
procedure AsciiCharProc;
procedure CRProc;
procedure IdentProc;
function MatchComment(CommentStr:string):boolean;
procedure LineCommentProc;
procedure CommentBegProc;
procedure CommentEndProc;
procedure StringBegProc;
procedure StringEndProc;
procedure IntegerProc;
procedure LFProc;
procedure NullProc;
procedure NumberProc;
procedure SpaceProc;
procedure UnknownProc;
function IsKeyWord1(aToken: String): Boolean;
function IsKeyWord2(aToken: String): Boolean;
function IsKeyWord3(aToken: String): Boolean;
procedure SetKeyWords1(const Value: TStrings);
procedure SetKeyWords2(const Value: TStrings);
procedure SetKeyWords3(const Value: TStrings);
function GetIdentifierChars: string;
function GetNumConstChars: string;
function GetNumBegChars: string;
procedure SetIdentifierChars(const Value: string);
procedure SetNumConstChars(const Value: string);
procedure SetNumBegChars(const Value: string);
procedure SetDetectPreprocessor(Value: boolean); // DJLP 2000-06-18
procedure SetLanguageName(Value:string);
procedure MakeIdentTable;
protected
function GetIdentChars: TSynIdentChars; override;
public
{$IFNDEF SYN_CPPB_1} class {$ENDIF} //mh 2000-07-14
function GetLanguageName: string; override;
public
CurrLineHighlighted :boolean;
RightEdgeColorFg :TColor;
RightEdgeColorBg :TColor;
HelpFile :string;
CaseSensitive :boolean;
IdentifierBegChars :string;
SourceFileName :string;
EscapeChar :char;
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;
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;
function SaveToRegistry(RootKey: HKEY; Key: string): boolean; override;
function LoadFromRegistry(RootKey: HKEY; Key: string): boolean; override;
procedure SetCommentStrings(LineComment, CommentBeg, CommentEnd:string);
procedure GetCommentStrings(var LineComment, CommentBeg, CommentEnd:string);
procedure SetStringParams(StrBegChar, StrEndChar:char; MultilineStrings:boolean);
procedure MakeMethodTables;
procedure AssignPropertiesTo(HL:TSynMyGeneralSyn);
published
property LanguageName: string read FLanguageName write SetLanguageName;
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property DetectPreprocessor: boolean read fDetectPreprocessor // DJLP 2000-06-18
write SetDetectPreprocessor;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property IdentifierChars: string read GetIdentifierChars
write SetIdentifierChars;
property NumConstChars: string read GetNumConstChars write SetNumConstChars;
property NumBegChars: string read GetNumBegChars write SetNumBegChars;
property KeyAttri1: TSynHighlighterAttributes read fKeyAttri1 write fKeyAttri1;
property KeyAttri2: TSynHighlighterAttributes read fKeyAttri2 write fKeyAttri2;
property KeyAttri3: TSynHighlighterAttributes read fKeyAttri3 write fKeyAttri3;
property KeyWords1: TStrings read fKeyWords1 write SetKeyWords1;
property KeyWords2: TStrings read fKeyWords2 write SetKeyWords2;
property KeyWords3: TStrings read fKeyWords3 write SetKeyWords3;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri
write fNumberAttri;
property PreprocessorAttri: TSynHighlighterAttributes // DJLP 2000-06-18
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;
end;
procedure Register;
implementation
uses
SynEditStrConst;
procedure Register;
begin
RegisterComponents(SYNS_HighlightersPage, [TSynMyGeneralSyn]);
end;
procedure TSynMyGeneralSyn.AssignPropertiesTo(HL:TSynMyGeneralSyn);
begin
HL.CurrLineHighlighted:=CurrLineHighlighted;
HL.RightEdgeColorFg:=RightEdgeColorFg;
HL.RightEdgeColorBg:=RightEdgeColorBg;
HL.HelpFile:=HelpFile;
HL.CaseSensitive:=CaseSensitive;
HL.IdentifierBegChars:=IdentifierBegChars;
HL.IdentifierChars:=IdentifierChars;
HL.NumConstChars:=NumConstChars;
HL.NumBegChars:=NumBegChars;
HL.DetectPreprocessor:=DetectPreprocessor;
HL.SetCommentStrings(FLineComment, FCommentBeg, FCommentEnd);
HL.SetStringParams(FStrBegChar, FStrEndChar, FMultilineStrings);
if CaseSensitive then begin
HL.Keywords1.Text:=Keywords1.Text;
HL.Keywords2.Text:=Keywords2.Text;
HL.Keywords3.Text:=Keywords3.Text;
end else begin
HL.Keywords1.Text:=UpperCase(Keywords1.Text);
HL.Keywords2.Text:=UpperCase(Keywords2.Text);
HL.Keywords3.Text:=UpperCase(Keywords3.Text);
end;
HL.MakeMethodTables;
end;
procedure TSynMyGeneralSyn.MakeIdentTable;
var
I: Char;
begin
for I := #0 to #255 do
Identifiers[I]:=(i in fIdentChars);
end;
function TSynMyGeneralSyn.IsKeyWord1(aToken: String): Boolean;
var
i :integer;
Token :string;
begin
Result := FALSE;
if not CaseSensitive then
Token := UpperCase(aToken)
else
Token := aToken;
i:=0;
while (i<fKeywords1.Count) do begin
if (fKeywords1[i]=Token) then begin
result:=TRUE;
BREAK;
end;
inc(i);
end;
end; { IsKeyWord1 }
function TSynMyGeneralSyn.IsKeyWord2(aToken: String): Boolean;
var
i :integer;
Token :string;
begin
Result := FALSE;
if not CaseSensitive then
Token := UpperCase(aToken)
else
Token := aToken;
i:=0;
while (i<fKeywords2.Count) do begin
if (fKeywords2[i]=Token) then begin
result:=TRUE;
BREAK;
end;
inc(i);
end;
end; { IsKeyWord2 }
function TSynMyGeneralSyn.IsKeyWord3(aToken: String): Boolean;
var
i :integer;
Token :string;
begin
Result := FALSE;
if not CaseSensitive then
Token := UpperCase(aToken)
else
Token := aToken;
i:=0;
while (i<fKeywords3.Count) do begin
if (fKeywords3[i]=Token) then begin
result:=TRUE;
BREAK;
end;
inc(i);
end;
end; { IsKeyWord3 }
procedure TSynMyGeneralSyn.MakeMethodTables;
var
I: Char;
procedure CommentToProcTable(var CommentStr:string; proc:TProcTableProc);
begin
if (Length(CommentStr)>0) then begin
if (UpCase(CommentStr[1]) in fIdentChars) then begin
fProcTable[UpCase(CommentStr[1])]:=proc;
fProcTable[LowerCase(CommentStr[1])[1]]:=proc;
CommentStr:=UpperCase(CommentStr);
end else
fProcTable[CommentStr[1]]:=proc;
end;
end;
begin
for I := #0 to #255 do begin
if (Pos(I,IdentifierBegChars)>0) then begin
fProcTable[I] := IdentProc;
end else begin
if (I in fNumBegChars) then begin
fProcTable[I] := NumberProc;
end else begin
case I of
'#': fProcTable[I] := AsciiCharProc;
#13: fProcTable[I] := CRProc;
// '$': fProcTable[I] := IntegerProc;
#10: fProcTable[I] := LFProc;
#0: fProcTable[I] := NullProc;
// '0'..'9': fProcTable[I] := NumberProc;
#1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;
else fProcTable[I] := UnknownProc;
end;
end;
end;
end;
if (FStrBegChar<>#00) then fProcTable[FStrBegChar]:=StringBegProc;
CommentToProcTable(FLineComment, LineCommentProc);
CommentToProcTable(FCommentBeg, CommentBegProc);
FCommentEnd:=UpperCase(FCommentEnd);
end;
constructor TSynMyGeneralSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fKeyWords1 := TStringList.Create;
TStringList(fKeyWords1).Sorted := True;
TStringList(fKeyWords1).Duplicates := dupIgnore;
fKeyWords2 := TStringList.Create;
TStringList(fKeyWords2).Sorted := True;
TStringList(fKeyWords2).Duplicates := dupIgnore;
fKeyWords3 := TStringList.Create;
TStringList(fKeyWords3).Sorted := True;
TStringList(fKeyWords3).Duplicates := dupIgnore;
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style := [fsItalic];
AddAttribute(fCommentAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri1 := TSynHighlighterAttributes.Create('Keywords 1');
fKeyAttri1.Style := [fsBold];
AddAttribute(fKeyAttri1);
fKeyAttri2 := TSynHighlighterAttributes.Create('Keywords 2');
fKeyAttri2.Style := [fsBold];
AddAttribute(fKeyAttri2);
fKeyAttri3 := TSynHighlighterAttributes.Create('Keywords 3');
fKeyAttri3.Style := [fsBold];
AddAttribute(fKeyAttri3);
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);
{begin} // DJLP 2000-06-18
fPreprocessorAttri := TSynHighlighterAttributes.Create(SYNS_AttrPreprocessor);
AddAttribute(fPreprocessorAttri);
{end} // DJLP 2000-06-18
SetAttributesOnChange(DefHighlightChange);
fIdentChars := inherited GetIdentChars;
NumConstChars:='0123456789';
NumBegChars:='0123456789';
MakeIdentTable;
fRange := rsUnknown;
end; { Create }
destructor TSynMyGeneralSyn.Destroy;
begin
fKeyWords1.Free;
fKeyWords2.Free;
fKeyWords3.Free;
inherited Destroy;
end; { Destroy }
procedure TSynMyGeneralSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end; { SetLine }
procedure TSynMyGeneralSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure TSynMyGeneralSyn.AsciiCharProc;
begin
if fDetectPreprocessor then begin
fTokenID := tkPreprocessor;
repeat
inc(Run);
until fLine[Run] in [#0, #10, #13];
end else begin
fTokenID := tkSymbol;
inc(Run);
end;
end;
procedure TSynMyGeneralSyn.IdentProc;
begin
inc(Run);
while Identifiers[fLine[Run]] do inc(Run);
if IsKeyWord1(GetToken) then
fTokenId := tkKey1
else
if IsKeyWord2(GetToken) then
fTokenId := tkKey2
else
if IsKeyWord3(GetToken) then
fTokenId := tkKey3
else
fTokenId := tkIdentifier;
end;
function TSynMyGeneralSyn.MatchComment(CommentStr:string):boolean;
var
i :integer;
len :integer;
ok :boolean;
begin
len:=Length(CommentStr);
ok:=(len>0);
if ok then begin
i:=1;
while ok and (i<=len) do begin
ok:=(UpCase(FLine[Run+i-1])=CommentStr[i]);
inc(i);
end;
ok:=ok and (i-1=len);
end;
if ok and (CommentStr[1] in fIdentChars) then
ok:=not (FLine[Run+Length(CommentStr)] in fIdentChars);
result:=ok;
end;
procedure TSynMyGeneralSyn.LineCommentProc;
begin
if MatchComment(FLineComment) then begin
inc(Run,Length(FLineComment));
fTokenID:=tkComment;
while (FLine[Run]<>#0) do begin
case FLine[Run] of
#10, #13: BREAK;
end;
inc(Run);
end;
end else begin
if (Length(FLineComment)>0) and (FLineComment[1] in fIdentChars) then
IdentProc
else begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
end;
procedure TSynMyGeneralSyn.CommentBegProc;
begin
if MatchComment(FLineComment) then
LineCommentProc
else begin
if MatchComment(FCommentBeg) then begin
fTokenID:=tkComment;
fRange:=rsBlockComment;
inc(Run,Length(FCommentBeg));
while (FLine[Run]<>#0) do begin
if MatchComment(FCommentEnd) then begin
fRange:=rsUnKnown;
inc(Run,Length(FCommentEnd));
BREAK;
end else begin
case FLine[Run] of
#10,#13: BREAK;
else
inc(Run);
end;
end;
end;
end else begin
if (Length(FCommentBeg)>0) and (FCommentBeg[1] in fIdentChars) then
IdentProc
else begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
end;
end;
procedure TSynMyGeneralSyn.CommentEndProc;
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 begin
if MatchComment(FCommentEnd) then begin
fRange:=rsUnKnown;
inc(Run,Length(FCommentEnd));
BREAK;
end else begin
case FLine[Run] of
#10,#13: BREAK;
else
inc(Run);
end;
end;
end;
end;
procedure TSynMyGeneralSyn.StringBegProc;
begin
fTokenID:=tkString;
repeat
if (FLine[Run]=EscapeChar) and (EscapeChar<>#0) then begin
inc(Run);
end else begin
case FLine[Run] of
#0, #10, #13:
begin
if FMultilineStrings then
fRange:=rsMultilineString;
BREAK;
end;
end;
end;
inc(Run);
until FLine[Run] = FStrEndChar;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TSynMyGeneralSyn.StringEndProc;
begin
fTokenID:=tkString;
case FLine[Run] of
#0:
begin
NullProc;
exit;
end;
#10:
begin
LFProc;
exit;
end;
#13:
begin
CRProc;
exit;
end;
end;
repeat
if (FLine[Run]=EscapeChar) and (EscapeChar<>#0) then begin
inc(Run);
end else begin
case FLine[Run] of
#0, #10, #13: BREAK;
end;
end;
inc(Run);
until FLine[Run]=FStrEndChar;
if (FLine[Run]=FStrEndChar) then
fRange:=rsUnKnown;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TSynMyGeneralSyn.IntegerProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', 'A'..'F', 'a'..'f'] do inc(Run);
end;
procedure TSynMyGeneralSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynMyGeneralSyn.NullProc;
begin
fTokenID := tkNull;
end;
{begin} // DJLP 2000-06-18
procedure TSynMyGeneralSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
// while FLine[Run] in ['0'..'9', '.', 'e', 'E', 'x'] do
while FLine[Run] in fNumConstChars do
begin
case FLine[Run] of
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
{end} // DJLP 2000-06-18
procedure TSynMyGeneralSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run);
end;
procedure TSynMyGeneralSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnKnown;
end;
procedure TSynMyGeneralSyn.Next;
begin
fTokenPos := Run;
Case fRange of
rsBlockComment: CommentEndProc;
rsMultilineString: StringEndProc;
else
fProcTable[fLine[Run]];
end;
end;
function TSynMyGeneralSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri1;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else Result := nil;
end;
end;
function TSynMyGeneralSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function TSynMyGeneralSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TSynMyGeneralSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TSynMyGeneralSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynMyGeneralSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey1: Result := fKeyAttri1;
tkKey2: Result := fKeyAttri2;
tkKey3: Result := fKeyAttri3;
tkNumber: Result := fNumberAttri;
tkPreprocessor: Result := fPreprocessorAttri; // DJLP 2000-06-18
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fSymbolAttri;
else Result := nil;
end;
end;
function TSynMyGeneralSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TSynMyGeneralSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TSynMyGeneralSyn.ReSetRange;
begin
fRange := rsUnknown;
end;
procedure TSynMyGeneralSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
procedure TSynMyGeneralSyn.SetKeyWords1(const Value: TStrings);
var
i: Integer;
begin
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do begin
if not CaseSensitive then
Value[i] := UpperCase(Value[i]);
end;
Value.EndUpdate;
end;
fKeyWords1.Assign(Value);
DefHighLightChange(nil);
end;
procedure TSynMyGeneralSyn.SetKeyWords2(const Value: TStrings);
var
i: Integer;
begin
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do begin
if not CaseSensitive then
Value[i] := UpperCase(Value[i]);
end;
Value.EndUpdate;
end;
fKeyWords2.Assign(Value);
DefHighLightChange(nil);
end;
procedure TSynMyGeneralSyn.SetKeyWords3(const Value: TStrings);
var
i: Integer;
begin
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do begin
if not CaseSensitive then
Value[i] := UpperCase(Value[i]);
end;
Value.EndUpdate;
end;
fKeyWords3.Assign(Value);
DefHighLightChange(nil);
end;
{$IFNDEF SYN_CPPB_1} class {$ENDIF} //mh 2000-07-14
function TSynMyGeneralSyn.GetLanguageName: string;
begin
result:='';
// SELF.GetStringDelim;
// Result := LanguageName;
end;
function TSynMyGeneralSyn.LoadFromRegistry(RootKey: HKEY; Key: string): boolean;
begin
result:=TRUE;
end;
function TSynMyGeneralSyn.SaveToRegistry(RootKey: HKEY; Key: string): boolean;
begin
result:=TRUE;
end;
procedure TSynMyGeneralSyn.SetCommentStrings(LineComment, CommentBeg, CommentEnd:string);
begin
FLineComment:=LineComment;
FCommentBeg:=CommentBeg;
FCommentEnd:=CommentEnd;
end;
procedure TSynMyGeneralSyn.GetCommentStrings(var LineComment, CommentBeg, CommentEnd:string);
begin
LineComment:=FLineComment;
CommentBeg:=FCommentBeg;
CommentEnd:=FCommentEnd;
end;
procedure TSynMyGeneralSyn.SetStringParams(StrBegChar, StrEndChar:char; MultilineStrings:boolean);
begin
FStrBegChar:=StrBegChar;
FStrEndChar:=StrEndChar;
FMultilineStrings:=MultilineStrings;
if (FStrBegChar<>#00) then fProcTable[FStrBegChar]:=StringBegProc;
end;
function TSynMyGeneralSyn.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;
function TSynMyGeneralSyn.GetNumConstChars: string;
var
ch: char;
s: shortstring;
begin
s := '';
for ch := #0 to #255 do
if ch in fNumConstChars then s := s + ch;
Result := s;
end;
function TSynMyGeneralSyn.GetNumBegChars: string;
var
ch: char;
s: shortstring;
begin
s := '';
for ch := #0 to #255 do
if ch in fNumBegChars then s := s + ch;
Result := s;
end;
procedure TSynMyGeneralSyn.SetIdentifierChars(const Value: string);
var
i: integer;
begin
fIdentChars := [];
for i := 1 to Length(Value) do begin
fIdentChars := fIdentChars + [Value[i]];
end; //for
MakeIdentTable;
end;
procedure TSynMyGeneralSyn.SetNumConstChars(const Value: string);
var
i: integer;
begin
fNumConstChars := [];
for i := 1 to Length(Value) do begin
fNumConstChars := fNumConstChars + [Value[i]];
end; //for
end;
procedure TSynMyGeneralSyn.SetNumBegChars(const Value: string);
var
i: integer;
begin
fNumBegChars := [];
for i := 1 to Length(Value) do begin
fNumBegChars := fNumBegChars + [Value[i]];
end; //for
end;
procedure TSynMyGeneralSyn.SetLanguageName(Value:string);
begin
FLanguageName:=Value;
end;
function TSynMyGeneralSyn.GetIdentChars: TSynIdentChars;
begin
Result := fIdentChars;
end;
{begin} // DJLP 2000-06-18
procedure TSynMyGeneralSyn.SetDetectPreprocessor(Value: boolean);
begin
if Value <> fDetectPreprocessor then begin
fDetectPreprocessor := Value;
DefHighlightChange(Self);
end;
end;
{end} // DJLP 2000-06-18
initialization
{$IFNDEF SYN_CPPB_1} //mh 2000-07-14
RegisterPlaceableHighlighter(TSynMyGeneralSyn);
{$ENDIF}
end.
|
unit uDMImportVCTextFile;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMImportTextFile, DB, ADODB, DBTables, uDMCalcPrice;
type
TDMImportVCTextFile = class(TDMImportTextFile)
spPurchaseDo: TADOStoredProc;
qryInsPurchase: TADOQuery;
qryGetIDPreInventoryMov: TADOQuery;
qryInsPurchaseItem: TADOQuery;
qryInsModel: TADOQuery;
private
IsClientServer: Boolean;
FDMCalcPrice: TDMCalcPrice;
FIDVendor: Integer;
FIDPurchase: Integer;
FVendorCode: String;
function GetIDVendor(Vendor :String): Integer;
function GetNewIDVendor(Vendor :String): Integer;
function GetTpPesLastCode: Integer;
procedure SetQueryConnections;
procedure BeforeImport; override;
procedure AfterImport; override;
procedure ImportLine; override;
procedure DeleteModelInformation( IDModel, IDVendor: Integer );
procedure InsertModelInformation( IDModel, IDVendor: Integer; Description, VendorCode: String;
CaseQty, Cost: Currency; MinQtyPO : Double );
procedure UpdateModelInformation( IDModel, IDVendor: Integer; Description, VendorCode: String;
CaseQty, Cost: Currency; MinQtyPO : Double );
end;
implementation
uses uNumericFunctions, uDMGlobal, uSystemConst, uContentClasses, udebugFunctions, uObjectServices;
{$R *.dfm}
{ TDMImportVCFile }
procedure TDMImportVCTextFile.ImportLine;
var
iIdModel : Integer;
sDescription : String;
begin
If ( TextFile.FieldByName('Update').AsInteger = 0 ) Then Exit;
inherited;
Try
{ Remove }
If ( TextFile.FieldByName('ChangeType').Asstring = 'R' ) Then Begin
Self.DeleteModelInformation( TextFile.FieldByName('IdModel').AsInteger,
FIDVendor );
{ Update }
End Else If ( TextFile.FieldByName('ChangeType').Asstring = 'U' ) Then Begin
Try
Self.UpdateModelInformation( TextFile.FieldByName('IdModel').AsInteger,
FIDVendor,
TextFile.FieldByName('Description').AsString,
TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString,
TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['Cost']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat );
Except
On E:Exception Do Begin
Raise;
End;
End;
{ New }
End Else If ( TextFile.FieldByName('ChangeType').Asstring = 'N' ) Then Begin
Try
Self.InsertModelInformation( TextFile.FieldByName('IdModel').AsInteger,
FIDVendor,
TextFile.FieldByName('Description').AsString,
TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString,
TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['Cost']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat );
Except
On E:Exception Do Begin
Raise;
End;
End;
End;
Finally
End;
end;
procedure TDMImportVCTextFile.InsertModelInformation( IDModel, IDVendor: Integer; Description, VendorCode: String;
CaseQty, Cost: Currency; MinQtyPO : Double );
Var
sSQL : String;
iIdVendorModelCode, VendorOrder : Integer;
begin
try
If ( DMGlobal.qryFreeSQL.Active ) Then DMGlobal.qryFreeSQL.Close;
VendorOrder := 1;
{ Testar se registro já existe antes de inserir, caso exista então atualizar }
sSQL := 'SELECT 1 FROM INV_MODELVENDOR ' +
'WHERE IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel );
DMGlobal.qryFreeSQL.SQL.Text := sSQL;
DMGlobal.qryFreeSQL.Open;
If ( DMGlobal.qryFreeSQL.IsEmpty ) Then Begin
sSQL := 'INSERT INTO INV_MODELVENDOR ( IDPESSOA, IDMODEL, VENDORORDER, '+
'MINQTYPO, CASEQTY, '+
'VENDORCOST, COSTLASTCHANGE )'+
'VALUES ( ' + IntToStr( IDVendor ) + ', ' + IntToStr( IDModel ) + ', ' + IntToStr( VendorOrder ) + ', ' +
CurrToStr( MinQtyPO ) + ', ' + CurrToStr( CaseQty ) + ', ' +
CurrToStr( Cost ) + ', GETDATE() ) ';
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
iIdVendorModelCode := DMGlobal.GetNextCode('VENDORMODELCODE', 'IDVENDORMODELCODE', SQLConnection );
sSQL := 'INSERT INTO VENDORMODELCODE ( IDVENDORMODELCODE, IDPESSOA, IDMODEL, VENDORCODE )'+
'VALUES ( ' + IntToStr( iIdVendorModelCode ) + ', ' + IntToStr( IDVendor ) + ', ' +
IntToStr( IDModel ) + ', ' + QuotedStr( VendorCode ) + ' ) ';
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
End Else Begin
Self.UpdateModelInformation( IDModel,
IDVendor,
TextFile.FieldByName('Description').AsString,
TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString,
TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['Cost']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat );
End;
finally
DMGlobal.qryFreeSQL.Close();
end;
end;
procedure TDMImportVCTextFile.DeleteModelInformation( IDModel, IDVendor : Integer );
Var
sSQL : String;
begin
try
If ( DMGlobal.qryFreeSQL.Active ) Then DMGlobal.qryFreeSQL.Close;
sSQL := 'DELETE FROM INV_MODELVENDOR '+
'WHERE IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel );
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
sSQL := 'DELETE FROM VENDORMODELCODE '+
'WHERE IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel );
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
finally
DMGlobal.qryFreeSQL.Close();
end;
end;
procedure TDMImportVCTextFile.UpdateModelInformation(IDModel, IDVendor: Integer; Description, VendorCode: String;
CaseQty, Cost: Currency; MinQtyPO : Double);
Var
sSQL : String;
iIdVendorModelCode, VendorOrder : Integer;
begin
try
If ( DMGlobal.qryFreeSQL.Active ) Then DMGlobal.qryFreeSQL.Close;
VendorOrder := 1;
{ Testar se registro já existe antes de atualizar, caso não exista então inserir }
sSQL := 'SELECT 1 FROM INV_MODELVENDOR ' +
'WHERE IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel );
DMGlobal.qryFreeSQL.SQL.Text := sSQL;
DMGlobal.qryFreeSQL.Open;
If ( DMGlobal.qryFreeSQL.IsEmpty ) Then Begin
Self.InsertModelInformation( IDModel,
IDVendor,
TextFile.FieldByName('Description').AsString,
TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString,
TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['Cost']).AsFloat,
TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat );
End Else Begin
sSQL := 'UPDATE INV_MODELVENDOR SET '+
' VENDORORDER = ' + IntToStr( VendorOrder ) + ', ' +
' MINQTYPO = ' + CurrToStr( MinQtyPO ) + ', ' +
' CASEQTY = ' + CurrToStr( CaseQty ) + ', ' +
' VENDORCOST = ' + CurrToStr( Cost ) + ', ' +
' COSTLASTCHANGE = GETDATE() '+
'WHERE '+
' IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel );
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
sSQL := 'UPDATE VENDORMODELCODE SET ' +
' VENDORCODE = '+ QuotedStr( VendorCode ) + ' ' +
'WHERE ' +
' IDPESSOA = ' + IntToStr( IDVendor ) +
' AND IDMODEL = ' + IntToStr( IDModel ) +
' AND VENDORCODE <> ' + QuotedStr( VendorCode );
DMGlobal.ExecuteSQL( sSQL, SQLConnection );
End;
finally
DMGlobal.qryFreeSQL.Close();
end;
end;
function TDMImportVCTextFile.GetIDVendor(Vendor: String): Integer;
begin
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT IDPessoa from Pessoa '+
' WHERE Pessoa = ' + QuotedStr(Vendor) + ' AND IDTipoPessoa = 2 ';
Open;
if IsEmpty then
Result := GetNewIDVendor(Vendor)
else
Result := FieldByName('IDPessoa').AsInteger;
end;
end;
function TDMImportVCTextFile.GetNewIDVendor(Vendor: String): Integer;
var
IDPessoa, Code : Integer;
begin
Result := -1;
try
IDPessoa := DMGlobal.GetNextCode('Pessoa', 'IDPessoa',SQLConnection);
DMGlobal.RunSQL(' UPDATE TipoPessoa SET LastCode = IsNull(LastCode,0) + 1 ' +
' Where IDTipoPessoa = 2 ',SQLConnection);
Code := GetTpPesLastCode;
DMGlobal.RunSQL('INSERT INTO Pessoa (IDPessoa,IDTipoPessoa,IDStore,IDTipoPessoaRoot,IDUSer,Pessoa,Juridico,Code) VALUES ' +
' (' + InttoStr(IDPessoa) + ' , 2 , ' + ImpExpConfig.Values['Store'] + ' , 2 , ' + ImpExpConfig.Values['User'] +
' , ' + QuotedStr(Vendor) + ' , 1 , ' + InttoStr(Code) + ' ) ' , SQLConnection);
Result := IDPessoa;
except
on E: Exception do
Log.Add(Format('Error: %s', [E.Message]));
end;
end;
function TDMImportVCTextFile.GetTpPesLastCode: Integer;
begin
Try
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
SQL.Text := ' SELECT LastCode from TipoPessoa WHERE IDTipoPessoa = 2 and Path = ''.002'' ';
Open;
Result := FieldByName('LastCode').AsInteger;
end;
finally
DMGlobal.qryFreeSQL.Close;
end;
end;
procedure TDMImportVCTextFile.SetQueryConnections;
begin
inherited;
DMGlobal.qryFreeSQL.Connection := SQLConnection;
qryInsPurchase.Connection := SQLConnection;
qryGetIDPreInventoryMov.Connection := SQLConnection;
qryInsPurchaseItem.Connection := SQLConnection;
spPurchaseDo.Connection := SQLConnection;
end;
procedure TDMImportVCTextFile.BeforeImport;
begin
inherited;
SetQueryConnections;
FIDVendor := GetIDVendor(ImpExpConfig.Values['Vendor']);
IsClientServer := DMGlobal.IsClientServer(SQLConnection);
End;
procedure TDMImportVCTextFile.AfterImport;
begin
inherited;
end;
end.
|
unit ibSHSQLMonitorActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHSQLMonitorPaletteAction = class(TSHAction)
private
function GetClassIID: TGUID;
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
property ClassIID: TGUID read GetClassIID;
end;
TibSHSQLMonitorPaletteAction_FIB = class(TibSHSQLMonitorPaletteAction)
end;
TibSHSQLMonitorPaletteAction_IBX = class(TibSHSQLMonitorPaletteAction)
end;
TibSHSQLMonitorFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHSQLMonitorToolbarAction_ = class(TSHAction)
private
FFIBTreeChecked: Boolean;
FIBXTreeChecked: Boolean;
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHSQLMonitorToolbarAction_Run = class(TibSHSQLMonitorToolbarAction_)
end;
TibSHSQLMonitorToolbarAction_Pause = class(TibSHSQLMonitorToolbarAction_)
end;
TibSHSQLMonitorToolbarAction_Region = class(TibSHSQLMonitorToolbarAction_)
end;
TibSHSQLMonitorToolbarAction_2App = class(TibSHSQLMonitorToolbarAction_)
end;
implementation
uses
ibSHConsts,
ibSHSQLMonitorFrm, ActnList;
{ TibSHSQLMonitorPaletteAction }
constructor TibSHSQLMonitorPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', ['SQL Monitor']);
if IsEqualGUID(ClassIID, IibSHFIBMonitor) then Caption := Format('%s', ['FIB Monitor']) else
if IsEqualGUID(ClassIID, IibSHIBXMonitor) then Caption := Format('%s', ['IBX Monitor']);
if IsEqualGUID(ClassIID, IibSHFIBMonitor) then ShortCut := TextToShortCut('Shift+Ctrl+M');
if IsEqualGUID(ClassIID, IibSHIBXMonitor) then ;
end;
function TibSHSQLMonitorPaletteAction.GetClassIID: TGUID;
begin
Result := IUnknown;
if Self is TibSHSQLMonitorPaletteAction_FIB then Result := IibSHFIBMonitor else
if Self is TibSHSQLMonitorPaletteAction_IBX then Result := IibSHIBXMonitor;
end;
function TibSHSQLMonitorPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHSQLMonitorPaletteAction.EventExecute(Sender: TObject);
begin
// Designer.CreateComponent(Designer.CurrentServer.InstanceIID, ClassIID, EmptyStr);
Designer.CreateComponent(Designer.CurrentBranch.InstanceIID, ClassIID, EmptyStr);
end;
procedure TibSHSQLMonitorPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHSQLMonitorPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentServer) and
SupportComponent(Designer.CurrentServer.BranchIID);
end;
{ TibSHSQLMonitorFormAction }
constructor TibSHSQLMonitorFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := '-'; // separator
SHRegisterComponentForm(IibSHFIBMonitor, SCallFIBTrace, TibSHSQLMonitorForm);
SHRegisterComponentForm(IibSHIBXMonitor, SCallIBXTrace, TibSHSQLMonitorForm);
end;
function TibSHSQLMonitorFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHFIBMonitor) or IsEqualGUID(AClassIID, IibSHIBXMonitor);
end;
procedure TibSHSQLMonitorFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHSQLMonitorFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHSQLMonitorFormAction.EventUpdate(Sender: TObject);
begin
if Supports(Designer.CurrentComponent, IibSHFIBMonitor) then Caption := SCallFIBTrace else
if Supports(Designer.CurrentComponent, IibSHIBXMonitor) then Caption := SCallIBXTrace;
FDefault := Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHSQLMonitorToolbarAction_ }
constructor TibSHSQLMonitorToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHSQLMonitorToolbarAction_Run then Tag := 1;
if Self is TibSHSQLMonitorToolbarAction_Pause then Tag := 2;
if Self is TibSHSQLMonitorToolbarAction_Region then Tag := 3;
if Self is TibSHSQLMonitorToolbarAction_2App then Tag := 4;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3: Caption := Format('%s', ['Tree']);
4: Caption := Format('%s', ['Application']);
end;
if Tag <> 0 then Hint := Caption;
// AutoCheck := Tag = 3; // Tree
end;
function TibSHSQLMonitorToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHFIBMonitor) or IsEqualGUID(AClassIID, IibSHIBXMonitor)
end;
procedure TibSHSQLMonitorToolbarAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Tree
3: begin
if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFIBTrace) then
FFIBTreeChecked := not Checked;
if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIBXTrace) then
FIBXTreeChecked := not Checked;
(Designer.CurrentComponentForm as ISHRunCommands).ShowHideRegion(not Checked);
end;
// Application
4: (Designer.CurrentComponentForm as IibSHSQLMonitorForm).JumpToApplication;
end;
end;
procedure TibSHSQLMonitorToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHSQLMonitorToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
(AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFIBTrace) or
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIBXTrace))then
begin
Visible := True;
case Tag of
// Separator
0: ;
// Run
1: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
// Pause
2: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
// Tree
3: begin
if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFIBTrace) then
Checked := FFIBTreeChecked;
if AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIBXTrace) then
Checked := FIBXTreeChecked;
(Designer.CurrentComponentForm as ISHRunCommands).ShowHideRegion(Checked);
// EventExecute(Sender)
end;
// Application
4: (Designer.CurrentComponentForm as IibSHSQLMonitorForm).CanJumpToApplication;
end;
end else
Visible := False;
end;
end.
|
{..............................................................................}
{ Summary Demo the use of ShowModal property of a script form }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
unit FormShowModal;
interface
Uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
Type
TFormShowModalEg = class(TForm)
bOk: TButton;
bCancel: TButton;
procedure bCancelClick(Sender: TObject);
procedure bOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
Var
FormShowModalEg: TFormShowModalEg;
Implementation
{$R *.DFM}
{..............................................................................}
{..............................................................................}
Procedure TFormShowModalEg.bCancelClick(Sender: TObject);
Begin
ModalResult := mrCancel;
Sender.Cancel := True;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormShowModalEg.bOkClick(Sender: TObject);
Begin
ModalResult := mrOk;
Sender.Default := True;
End;
{..............................................................................}
{..............................................................................}
Procedure RunShowModalExample;
Begin
// Form's Visible property must be false for ShowModal to work properly.
// FormStyle := fsNormal; FormKind := fkNone;
FormShowModalEg.ShowModal;
// FormShowModalEg dialog disappears before the ShowMessage appears.
If FormShowModalEg.ModalResult = mrOk Then ShowMessage('mrOk');
If FormShowModalEg.ModalResult = mrCancel Then ShowMessage('mrCancel');
End;
{..............................................................................}
{..............................................................................}
End.
|
unit OTFETrueCrypt_U;
// Description: Delphi TrueCrypt Component
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// TRUE if integer<>0
// FALSE if integer=0
interface
uses
Classes, SysUtils, Windows, forms, controls,
OTFE_U, OTFETrueCryptStructures_U;
type
TOTFETrueCrypt = class(TOTFE)
private
hTrueCryptVxD : THandle;
FPasswordPrompt: string;
FMountDeviceDlg9xStyle: boolean;
FTrueCryptVersionHint: TTrueCryptVersionHint;
FCachePasswordsInDriver: boolean;
FOpenExplorerWindowAfterMount: boolean;
FCloseExplorerWindowsOnDismount: boolean;
FSaveMountedVolumesHistory: boolean;
FWipePasswordCacheOnExit: boolean;
FLastSelectedDrive: AnsiChar;
FLastMountedVolume: TStringList;
function ld(driveNum: integer; mode: integer): boolean;
function CloseSlot(driveNum: integer; brutal: boolean): boolean;
function locklogdrive(drivenum: integer; mode: integer): boolean;
function ioctllock(nDrive: cardinal; permissions: integer; func: integer): integer;
function DoDeviceClose(driveNum: integer): boolean;
function EjectStop(driveLetter: AnsiChar; func: boolean): boolean;
function GetNextUnusedDrvLtr(afterDrv: AnsiChar): AnsiChar;
function GetUnusedDriveLetters(): Ansistring;
function UseVersionHint(): TTrueCryptVersionHint;
protected
TrueCryptDriverName: string;
FTrueCryptDriverVersion: cardinal;
CurrentOS: integer;
function Connect(): boolean;
function Disconnect(): boolean;
procedure SetActive(AValue : Boolean); override;
function GetDisksMounted(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
function GetDisksMounted_PRE30(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
function GetDisksMounted_30(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
function Mount_PRE30(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
function Mount_30(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
function GetWordFromHeader(buffer: array of byte; var posInBuffer: integer): cardinal;
function GetCipherNames(cyphers: array of TrueCrypt_CIPHER_TYPE): string;
function GetVolumeInfo(volumeFilename: string; info: pTOTFETrueCryptVolumeInfo): boolean;
function GetAvailableRemovables(dispNames: TStringList; deviceNames: TStringList): integer;
function GetAvailableFixedDisks(dispNames: TStringList; deviceNames: TStringList): integer;
function OpenDevice(device: string): boolean;
procedure ShortArrayToString(theArray: array of WCHAR; var theString: string);
procedure StringToShortArray(theString: string; var theArray: array of WCHAR);
function IdentifyVolumeFileType(volumeFilename: string): TrueCrypt_VOLUME_FILE_TYPE;
function GetCyphersForTrueCryptCypherID(cypherID: integer; var cyphers: array of TrueCrypt_CIPHER_TYPE; var cypherMode: TrueCrypt_CIPHER_MODE): boolean;
procedure LoadSettings();
procedure SaveSettings();
// Returns TRUE if "volumeFilename" is a partition, not a file
function IsFilePartition(volumeFilename: string): boolean;
function Dismount_PRE30(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
function Dismount_30(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
// TOTFE functions...
function Title(): string; overload; override;
function Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar; override;
function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; override;
function MountDevices(): AnsiString; override;
function CanMountDevice(): boolean; override;
function Dismount(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean; overload; override;
// !! WARNING !!
// Due to limitations of the TrueCrypt driver, only up to the first 64
// chars of the volumeFilename are significant!
function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; override;
function DrivesMounted(): Ansistring; override;
function GetVolFileForDrive(driveLetter: AnsiChar): string; override;
// !! WARNING !!
// Due to limitations of the TrueCrypt driver, only up to the first 64
// chars of the volumeFilename are significant!
function GetDriveForVolFile(volumeFilename: string): Ansichar; override;
function Version(): cardinal; override;
function VersionStr(): string; override;
function IsEncryptedVolFile(volumeFilename: string): boolean; override;
function GetMainExe(): string; override;
function GetDriveInfo(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
function GetDriveInfo_PRE30(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
function GetDriveInfo_30(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
function GetDriveInfo_31a(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
function ClearPasswords(driveLetter: AnsiChar): boolean;
function GetAvailableRawDevices(dispNames: TStringList; deviceNames: TStringList): boolean;
// "idx" should be between 1 and TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME
// Returns '' on error
// Also returns '' if there is no filename in that position
function GetLastMountedVolume(idx: integer): string;
function SetLastMountedVolume(idx: integer; filename: string): boolean;
// Note: Calling AddLastMountedVolume will push the oldest filename on the MRU
// list off
procedure AddLastMountedVolume(volumeFilename: string);
published
property PasswordPrompt: string read FPasswordPrompt write FPasswordPrompt;
property CachePasswordsInDriver: boolean read FCachePasswordsInDriver write FCachePasswordsInDriver default FALSE;
property OpenExplorerWindowAfterMount: boolean read FOpenExplorerWindowAfterMount write FOpenExplorerWindowAfterMount default FALSE;
property CloseExplorerWindowsOnDismount: boolean read FCloseExplorerWindowsOnDismount write FCloseExplorerWindowsOnDismount default FALSE;
property SaveMountedVolumesHistory: boolean read FSaveMountedVolumesHistory write FSaveMountedVolumesHistory default FALSE;
property WipePasswordCacheOnExit: boolean read FWipePasswordCacheOnExit write FWipePasswordCacheOnExit default FALSE;
property LastSelectedDrive: AnsiChar read FLastSelectedDrive write FLastSelectedDrive default #0;
property MountDeviceDlg9xStyle: boolean read FMountDeviceDlg9xStyle write FMountDeviceDlg9xStyle default FALSE;
property VersionHint: TTrueCryptVersionHint read FTrueCryptVersionHint write FTrueCryptVersionHint default tcvAuto;
end;
procedure Register;
implementation
uses
Messages, // Required for "WM_DEVICECHANGE"
ShellAPI,
dialogs,
Registry, RegStr,
INIFiles,
Math,
OTFEConsts_U,
OTFETrueCryptPasswordEntry_U,
OTFETrueCryptMountDevice_U,
OTFETrueCryptMountDevice9x_U,
OTFETrueCryptMountDeviceNT_U,
SDUGeneral,
ShlObj; // Required for SHChangeNotify
procedure Register;
begin
RegisterComponents('OTFE', [TOTFETrueCrypt]);
end;
constructor TOTFETrueCrypt.Create(AOwner : TComponent);
var
os: OSVERSIONINFO;
i: integer;
begin
inherited create(AOwner);
// Pull down the windows version
os.dwOSVersionInfoSize := sizeof(OSVERSIONINFO);
if (GetVersionEx(os) = FALSE) then
begin
raise ETrueCryptError.Create('Unable to determine OS');
end
else if (os.dwPlatformId = VER_PLATFORM_WIN32_NT) then
begin
CurrentOS := TrueCrypt_OS_WIN_NT;
end
else if ((os.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) and (os.dwMajorVersion = 4) and (os.dwMinorVersion = 0)) then
begin
CurrentOS := TrueCrypt_OS_WIN_95;
end
else if ((os.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS) and (os.dwMajorVersion = 4) and (os.dwMinorVersion >= 10)) then
begin
// Note: This is ">= 10" in order to catch both Win98 and WinMe
CurrentOS := TrueCrypt_OS_WIN_98;
end
else
begin
// Fallback to NT/2K/XP on the basis that only TrueCrypt v1.0 supported
// Windows 9x/Me
CurrentOS := TrueCrypt_OS_WIN_NT;
end;
FActive := False;
FTrueCryptDriverVersion := $FFFFFFFF;
FLastMountedVolume:= TStringList.Create();
// Initialise with empty strings
for i:=1 to TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME do
begin
FLastMountedVolume.Add('');
end;
FPasswordPrompt := 'Enter password for %s';
LoadSettings();
end;
destructor TOTFETrueCrypt.Destroy;
begin
SaveSettings();
FLastMountedVolume.Free();
if FActive then
begin
CloseHandle(hTrueCryptVxD);
end;
inherited Destroy;
end;
function TOTFETrueCrypt.Connect(): boolean;
var
OSVersion: TOSVersionInfo;
dwResult: DWORD;
begin
Result := Active;
if not(Active) then
begin
if CurrentOS = TrueCrypt_OS_WIN_NT then
begin
TrueCryptDriverName := TrueCrypt_WIN32_ROOT_PREFIX;
end
else
begin
TrueCryptDriverName := TrueCrypt_WIN9X_DRIVER_NAME;
end;
hTrueCryptVxD := CreateFile(
PChar(TrueCryptDriverName),
0,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
if hTrueCryptVxD = INVALID_HANDLE_VALUE then
begin
raise ETrueCryptVxdNotFound.Create('TrueCrypt device driver not found');
end
else
begin
OSVersion.dwOSVersionInfoSize := SizeOf(OSVersion);
GetVersionEx(OSVersion);
FActive := TRUE;
// This *ONLY* applies to Windows *98*
if (CurrentOS = TrueCrypt_OS_WIN_98) then
begin
// We're runninng TrueCrypt v2.0.1 under w98
DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_ALLOW_FAST_SHUTDOWN,
nil,
0,
nil,
0,
dwResult,
nil);
end;
Result := TRUE;
end;
end;
end;
function TOTFETrueCrypt.Disconnect(): boolean;
begin
if Active then
begin
CloseHandle(hTrueCryptVxD);
end;
Result := TRUE;
end;
procedure TOTFETrueCrypt.SetActive(AValue : Boolean);
var
allOK: boolean;
begin
allOK := FALSE;
if AValue <> Active then
begin
if AValue then
begin
allOK := Connect();
end
else
begin
allOK := Disconnect();
end;
end;
if allOK then
begin
inherited;
if Active then
begin
FTrueCryptDriverVersion := Version();
end;
end;
end;
function TOTFETrueCrypt.Dismount(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
begin
if (Version() < $300) then
begin
Result := Dismount_PRE30(driveLetter, emergency);
end
else
begin
Result := Dismount_30(driveLetter, emergency);
end;
end;
// Note that the emergency parameter is IGNORED
function TOTFETrueCrypt.Dismount_PRE30(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
var
inbuf: array [1..80] of AnsiChar;
outbuf: array [1..80] of AnsiChar;
bytesRead: DWORD;
serviceCmd: Ansistring;
i: integer;
nDosDriveNo: integer;
begin
CheckActive();
Result := FALSE;
driveLetter := upcase(driveLetter);
if (pos(driveLetter, DrivesMounted()) < 1) then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
exit;
end;
nDosDriveNo := ord(upcase(driveLetter))-ord('A');
if (CurrentOS = TrueCrypt_OS_WIN_NT) then
begin
// Unmount the volume using the TrueCryptService, this is done to allow
// non-administrators to unmount volumes
// Doing it with the DeviceIOControl DISMOUNT is a bad idea as we would need
// to lock the volume first, which non-administrators can't do
serviceCmd := 'unmount '+inttostr(nDosDriveNo);
for i:=1 to length(serviceCmd) do
begin
outbuf[i] := serviceCmd[i];
end;
outbuf[length(serviceCmd)+1] := #0;
if CallNamedPipe(
TrueCrypt_PIPE_SERVICE,
@outbuf,
sizeof(outbuf),
@inbuf,
sizeof(inbuf),
bytesRead,
NMPWAIT_WAIT_FOREVER
) then
begin
Result := (inbuf[1]<>'-');
if not(Result) then
begin
if pos(inttostr(TrueCrypt_ERR_FILES_OPEN_LOCK), inbuf)>0 then
begin
FLastErrCode := OTFE_ERR_FILES_OPEN;
end;
end;
end;
end // if CurrentOS = TrueCrypt_OS_WIN_NT then
else
begin
Result := CloseSlot(nDosDriveNo, emergency);
end; // if not(if CurrentOS = TrueCrypt_OS_WIN_NT) then
end;
function TOTFETrueCrypt.Dismount_30(driveLetter: AnsiChar; emergency: boolean = FALSE): boolean;
var
nDosDriveNo: integer;
query: TOTFETrueCrypt_UNMOUNT_STRUCT_30;
dwResult: DWORD;
allOK: boolean;
i: integer;
begin
CheckActive();
allOK := FALSE;
driveLetter := upcase(driveLetter);
if (pos(driveLetter, DrivesMounted()) < 1) then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
Result := FALSE;
exit;
end;
BroadcastDriveChangeMessage(DBT_DEVICEREMOVEPENDING, driveLetter);
nDosDriveNo := ord(driveLetter)-ord('A');
for i:=low(query.junkPadding) to high(query.junkPadding) do
begin
query.junkPadding[i] := 0;
end;
query.nDosDriveNo := nDosDriveNo;
query.ignoreOpenFiles := emergency;
query.nReturnCode := 0;
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_UNMOUNT,
@query,
sizeof(query),
@query,
sizeof(query),
dwResult,
nil) then
begin
allOK := (query.nReturnCode = 0);
end;
if allOK then
begin
BroadcastDriveChangeMessage(FALSE, driveLetter);
end
else
begin
// Assume files open...
FLastErrCode := OTFE_ERR_FILES_OPEN;
end;
Result := allOK;
end;
function TOTFETrueCrypt.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean;
begin
// Don't need to convert volumeFilename to SFN/LFN, this is done in
// GetDriveForVolFile(...)
Result := Dismount(GetDriveForVolFile(volumeFilename), emergency);
end;
function TOTFETrueCrypt.Mount(volumeFilename: Ansistring; readonly: boolean = FALSE): Ansichar;
var
stlVolumes: TStringList;
mountedAs: AnsiString;
begin
CheckActive();
Result := #0;
stlVolumes:= TStringList.Create();
try
stlVolumes.Add(volumeFilename);
if Mount(stlVolumes, mountedAs, readonly) then
begin
Result := mountedAs[1];
end;
finally
stlVolumes.Free();
end;
end;
function TOTFETrueCrypt.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
begin
if (Version() < $300) then
begin
Result := Mount_PRE30(volumeFilenames, mountedAs, readonly);
end
else
begin
Result := Mount_30(volumeFilenames, mountedAs, readonly);
end;
end;
function TOTFETrueCrypt.Mount_PRE30(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
var
query: TOTFETrueCrypt_MOUNT_STRUCT_PRE30;
dwBytesReturned: DWORD;
volumeLoop: integer;
i: integer;
driveLetter: AnsiChar;
thePassword: Ansistring;
oneOK: boolean;
passwordDlg: TOTFETrueCryptPasswordEntry_F;
currAllOK: boolean;
mountedDrvLetter: Ansichar;
drvLtrsFree: string;
pwEntryDlgTitle: string;
currVolValid: boolean;
serviceCmd: Ansistring;
inbuf: array [1..80] of Ansichar;
outbuf: array [1..80] of Ansichar;
bytesRead: DWORD;
tmpFilename: string;
begin
CheckActive();
Result := FALSE;
oneOK := FALSE;
mountedAs := '';
pwEntryDlgTitle := Format(FPasswordPrompt, [volumeFilenames[0]]);
// Get the password/starting drive
passwordDlg:= TOTFETrueCryptPasswordEntry_F.Create(nil);
try
passwordDlg.DriverCachePassword := FCachePasswordsInDriver;
passwordDlg.UserCanMountReadonly := FALSE;
passwordDlg.UserCanMountRemovable := FALSE;
passwordDlg.UserCanForceMount := FALSE;
// The user should be prompted for the drive letter, and offered the
// default
drvLtrsFree := GetUnusedDriveLetters();
driveLetter := LastSelectedDrive; // Last selected drive letter (if any) stored in registry
if (driveLetter=#0) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
// If we're on A or B, skip this drive
if (driveLetter='A') or (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
// If we're on B, skip this drive
if (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
end
else if (pos(driveLetter, drvLtrsFree) < 1) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
passwordDlg.DrivesAllowed := drvLtrsFree;
passwordDlg.Drive := driveLetter;
passwordDlg.DriverCachePassword := CachePasswordsInDriver; // looked up from the registry
passwordDlg.caption := pwEntryDlgTitle;
if passwordDlg.ShowModal()=mrCancel then
begin
passwordDlg.ClearEnteredPassword();
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_USER_CANCEL;
exit;
end;
CachePasswordsInDriver := passwordDlg.DriverCachePassword;
LastSelectedDrive := passwordDlg.Drive;
thePassword := passwordDlg.mePassword.text; { TODO 1 -otdk -cbug : alert user if use unicode }
passwordDlg.ClearEnteredPassword();
finally
passwordDlg.Free();
end;
driveLetter := LastSelectedDrive;
if (driveLetter=#0) then
begin
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
Result := FALSE;
exit;
end;
for i:=1 to length(thePassword) do
begin
query.szPassword[i-1] := thePassword[i];
// Overwrite password chars once used...
thePassword[i] := Ansichar(Random(256));
end;
// No +1 here; szPassword indexes from zero.
query.szPassword[length(thePassword)] := #0;
query.nPasswordLen := length(thePassword);
query.bCache := CachePasswordsInDriver;
for i:=low(query.junkPadding) to high(query.junkPadding) do
begin
query.junkPadding[i] := 0;
end;
for volumeLoop:=0 to (volumeFilenames.count-1) do
begin
mountedDrvLetter := #0;
if (driveLetter<>#0) then
begin
query.nDosDriveNo := ord(upcase(driveLetter))-ord('A');
// If it's not a partition, check that the file exists...
currVolValid := TRUE;
if not(IsFilePartition(volumeFilenames[volumeLoop])) then
begin
currVolValid := FileExists(volumeFilenames[volumeLoop]);
if not(currVolValid) then
begin
FLastErrCode:= OTFE_ERR_VOLUME_FILE_NOT_FOUND;
end;
end;
AddLastMountedVolume(volumeFilenames[volumeLoop]);
if currVolValid then
begin
query.time := DateTimeToFileDate(now);
query.nReturnCode := 0;
// Convert filename to UNICODE, if needed
StringToShortArray(volumeFilenames[volumeLoop], query.wszVolume);
currAllOK := DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_MOUNT,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil);
currAllOK := currAllOK AND (query.nReturnCode=0);
if not(currAllOK) then
begin
FLastErrCode:= OTFE_ERR_WRONG_PASSWORD;
end
else
begin
if (CurrentOS = TrueCrypt_OS_WIN_NT) then
begin
serviceCmd := 'mount '+inttostr(query.nDosDriveNo);
for i:=1 to length(serviceCmd) do
begin
outbuf[i] := serviceCmd[i];
end;
outbuf[length(serviceCmd)+1] := #0;
if CallNamedPipe(
TrueCrypt_PIPE_SERVICE,
@outbuf,
sizeof(outbuf),
@inbuf,
sizeof(inbuf),
bytesRead,
NMPWAIT_WAIT_FOREVER
) then
begin
// If the return value comes back with "-ERR", then there was a
// problem
if (inbuf[1] = '-') then
begin
FLastErrCode:= OTFE_ERR_DRIVER_FAILURE;
end
else
begin
// Set oneOK to TRUE if at least *one* volume mounted OK
oneOK := TRUE;
mountedDrvLetter := driveLetter;
end;
end;
end
else // if (CurrentOS = TrueCrypt_OS_WIN_NT) then
begin
tmpFilename := volumeFilenames[volumeLoop];
EjectStop(AnsiChar(upcase(tmpFilename[1])), TRUE);
// Set oneOK to TRUE if at least *one* volume mounted OK
oneOK := TRUE;
mountedDrvLetter := driveLetter;
end;
end;
end; // if IsEncryptedVolFile(currVolFilename) then
if volumeLoop<(volumeFilenames.count-1) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
if driveLetter=#0 then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
break;
end;
end;
end; // if (driveLetter<>#0) then
mountedAs := mountedAs + mountedDrvLetter;
end;
// Pad out the string with #0, if needed
while length(mountedAs)<volumeFilenames.count do
begin
mountedAs := mountedAs + #0;
end;
Result := oneOK;
end;
function TOTFETrueCrypt.Mount_30(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
var
query: TOTFETrueCrypt_MOUNT_STRUCT_30;
dwBytesReturned: DWORD;
volumeLoop: integer;
i: integer;
driveLetter: AnsiChar;
thePassword: Ansistring;
oneOK: boolean;
passwordDlg: TOTFETrueCryptPasswordEntry_F;
currAllOK: boolean;
mountedDrvLetter: AnsiChar;
drvLtrsFree: Ansistring;
pwEntryDlgTitle: string;
currVolValid: boolean;
forceMount: boolean;
removable: boolean;
osVersionInfo: TOSVERSIONINFO;
begin
CheckActive();
Result := FALSE;
oneOK := FALSE;
mountedAs := '';
pwEntryDlgTitle := Format(FPasswordPrompt, [volumeFilenames[0]]);
// Get the password/starting drive
passwordDlg:= TOTFETrueCryptPasswordEntry_F.Create(nil);
try
passwordDlg.DriverCachePassword := FCachePasswordsInDriver;
passwordDlg.UserCanMountReadonly := TRUE;
passwordDlg.UserCanMountRemovable := TRUE;
passwordDlg.UserCanForceMount := TRUE;
passwordDlg.MountReadonly := readonly;
// The user should be prompted for the drive letter, and offered the
// default
drvLtrsFree := GetUnusedDriveLetters();
driveLetter := LastSelectedDrive; // Last selected drive letter (if any) stored in registry
if (driveLetter=#0) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
// If we're on A or B, skip this drive
if (driveLetter='A') or (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
// If we're on B, skip this drive
if (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
end
else if (pos(driveLetter, drvLtrsFree) < 1) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
passwordDlg.DrivesAllowed := drvLtrsFree;
passwordDlg.Drive := driveLetter;
passwordDlg.DriverCachePassword := CachePasswordsInDriver; // looked up from the registry
passwordDlg.caption := pwEntryDlgTitle;
if passwordDlg.ShowModal()=mrCancel then
begin
passwordDlg.ClearEnteredPassword();
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_USER_CANCEL;
exit;
end;
CachePasswordsInDriver := passwordDlg.DriverCachePassword;
LastSelectedDrive := passwordDlg.Drive;
forceMount := passwordDlg.ForceMount;
readonly := passwordDlg.MountReadonly;
removable := passwordDlg.MountAsRemovable;
thePassword := passwordDlg.mePassword.text; { TODO 1 -otdk -cbug : alert user if use unicode }
passwordDlg.ClearEnteredPassword();
finally
passwordDlg.Free();
end;
driveLetter := LastSelectedDrive;
if (driveLetter=#0) then
begin
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
Result := FALSE;
exit;
end;
for i:=1 to length(thePassword) do
begin
query.szPassword[i-1] := thePassword[i];
// Overwrite password chars once used...
thePassword[i] := AnsiChar(Random(256));
end;
// No +1 here; szPassword indexes from zero.
query.szPassword[length(thePassword)] := #0;
query.nPasswordLen := length(thePassword);
query.bCache := CachePasswordsInDriver;
for i:=low(query.junkPadding1) to high(query.junkPadding1) do
begin
query.junkPadding1[i] := 0;
end;
for i:=low(query.junkPadding2) to high(query.junkPadding2) do
begin
query.junkPadding2[i] := 0;
end;
for i:=low(query.junkPadding3) to high(query.junkPadding3) do
begin
query.junkPadding3[i] := 0;
end;
for i:=low(query.junkPadding4) to high(query.junkPadding4) do
begin
query.junkPadding4[i] := 0;
end;
for i:=low(query.junkPadding5) to high(query.junkPadding5) do
begin
query.junkPadding5[i] := 0;
end;
for volumeLoop:=0 to (volumeFilenames.count-1) do
begin
mountedDrvLetter := #0;
if (driveLetter<>#0) then
begin
query.nDosDriveNo := ord(upcase(driveLetter))-ord('A');
// If it's not a partition, check that the file exists...
currVolValid := TRUE;
if not(IsFilePartition(volumeFilenames[volumeLoop])) then
begin
currVolValid := FileExists(volumeFilenames[volumeLoop]);
if not(currVolValid) then
begin
FLastErrCode:= OTFE_ERR_VOLUME_FILE_NOT_FOUND;
end;
end;
AddLastMountedVolume(volumeFilenames[volumeLoop]);
if currVolValid then
begin
query.bMountReadOnly := readOnly; // Mount volume in read-only mode
query.bMountRemovable := removable; // Mount volume as removable media
query.bExclusiveAccess := forceMount; // Open host file/device in exclusive access mode
// - i.e. "Force mount" user
// option; TrueCrypt v3.0a's
// GUI only allows this to be
// set to FALSE, but the user
// can override setting it to
// TRUE if a volume is mounted
// via the TrueCrypt command
// line
// The following logic taken from TrueCrypt v3.0a's "DLGCODE.C"...
query.bMountManager := TRUE; // Announce volume to mount manager
osVersionInfo.dwOSVersionInfoSize := sizeof(osVersionInfo);
GetVersionEx(osVersionInfo);
// Windows 2000 mount manager causes problems with remounted volumes
if ((osVersionInfo.dwMajorVersion = 5) and (osVersionInfo.dwMinorVersion = 0)) then
begin
query.bMountManager := FALSE; // Announce volume to mount manager
end;
query.time := DateTimeToFileDate(now);
query.nReturnCode := 0;
// Convert filename to UNICODE, if needed
StringToShortArray(volumeFilenames[volumeLoop], query.wszVolume);
currAllOK := DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_MOUNT,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil);
currAllOK := currAllOK AND (query.nReturnCode=0);
if not(currAllOK) then
begin
FLastErrCode:= OTFE_ERR_WRONG_PASSWORD;
end
else
begin
// Set oneOK to TRUE if at least *one* volume mounted OK
oneOK := TRUE;
mountedDrvLetter := driveLetter;
BroadcastDriveChangeMessage(TRUE, driveLetter);
end;
end; // if IsEncryptedVolFile(currVolFilename) then
if volumeLoop<(volumeFilenames.count-1) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
if driveLetter=#0 then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
break;
end;
end;
end; // if (driveLetter<>#0) then
mountedAs := mountedAs + mountedDrvLetter;
end;
// Pad out the string with #0, if needed
while length(mountedAs)<volumeFilenames.count do
begin
mountedAs := mountedAs + #0;
end;
Result := oneOK;
end;
function TOTFETrueCrypt.DrivesMounted(): Ansistring;
var
output: Ansistring;
begin
GetDisksMounted(output, nil);
Result := SortString(output);
end;
// !! WARNING !!
// Under NT, the TrueCrypt driver won't tell us the full filename if it's more than
// 64 chars long, it will only return the first 60 followed by "..."
function TOTFETrueCrypt.GetDisksMounted(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
begin
if (Version() < $300) then
begin
Result := GetDisksMounted_PRE30(mountedDrives, volumeFilenames);
end
else
begin
Result := GetDisksMounted_30(mountedDrives, volumeFilenames);
end;
end;
// !! WARNING !!
// Under NT, the TrueCrypt driver won't tell us the full filename if it's more than
// 64 chars long, it will only return the first 60 followed by "..."
function TOTFETrueCrypt.GetDisksMounted_PRE30(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
var
dwBytesReturned : DWORD;
query: TOTFETrueCrypt_MOUNT_LIST_STRUCT_PRE30;
i: integer;
currBit: cardinal;
currVolFilename: string;
retVal: boolean;
begin
retVal := FALSE;
CheckActive();
// Cleared query.ulMountedDrives now so we can can use either later...
query.ulMountedDrives := 0;
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_MOUNT_LIST,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil) then
begin
retVal := TRUE;
mountedDrives := '';
if volumeFilenames<>nil then
begin
volumeFilenames.Clear();
end;
currBit := 1;
for i:=low(query.wszVolume) to high(query.wszVolume) do
begin
// We cleared the query.ulMountedDrives earlier, so we can do this
if ((query.ulMountedDrives AND currBit)>0) then
begin
mountedDrives := mountedDrives + AnsiChar(ord('A')+i);
if volumeFilenames<>nil then
begin
currVolFilename := '';
ShortArrayToString(query.wszVolume[i], currVolFilename);
// If we're running under NT, and it's a file that's mounted, we need
// to strip off the "/??/" at the start of the filename returned
if (pos('\??\', currVolFilename)=1) then
begin
delete(currVolFilename, 1, 4);
end;
if IsFilePartition(currVolFilename) then
begin
volumeFilenames.Add(currVolFilename);
end
else
begin
// The file may not exist if we only have the first 60 chars of the
// filename followed by "..."
if FileExists(currVolFilename) then
begin
volumeFilenames.Add(SDUConvertSFNToLFN(currVolFilename));
end
else
begin
volumeFilenames.Add(currVolFilename);
end;
end;
end;
end;
currBit := currBit * 2;
end;
end;
Result := retVal;
end;
// !! WARNING !!
// Under NT, the TrueCrypt driver won't tell us the full filename if it's more than
// 64 chars long, it will only return the first 60 followed by "..."
function TOTFETrueCrypt.GetDisksMounted_30(var mountedDrives: Ansistring; volumeFilenames: TStrings): boolean;
var
dwBytesReturned : DWORD;
query: TOTFETrueCrypt_MOUNT_LIST_STRUCT_30;
i: integer;
currBit: cardinal;
currVolFilename: string;
retVal: boolean;
begin
retVal := FALSE;
CheckActive();
// Cleared query.ulMountedDrives now so we can can use either later...
query.ulMountedDrives := 0;
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_MOUNT_LIST,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil) then
begin
retVal := TRUE;
mountedDrives := '';
if volumeFilenames<>nil then
begin
volumeFilenames.Clear();
end;
currBit := 1;
for i:=low(query.wszVolume) to high(query.wszVolume) do
begin
// We cleared the query.ulMountedDrives earlier, so we can do this
if ((query.ulMountedDrives AND currBit)>0) then
begin
mountedDrives := mountedDrives + AnsiChar(ord('A')+i);
if volumeFilenames<>nil then
begin
currVolFilename := '';
ShortArrayToString(query.wszVolume[i], currVolFilename);
// If we're running under NT, and it's a file that's mounted, we need
// to strip off the "/??/" at the start of the filename returned
if (pos('\??\', currVolFilename)=1) then
begin
delete(currVolFilename, 1, 4);
end;
if IsFilePartition(currVolFilename) then
begin
volumeFilenames.Add(currVolFilename);
end
else
begin
// The file may not exist if we only have the first 60 chars of the
// filename followed by "..."
if FileExists(currVolFilename) then
begin
volumeFilenames.Add(SDUConvertSFNToLFN(currVolFilename));
end
else
begin
volumeFilenames.Add(currVolFilename);
end;
end;
end;
end;
currBit := currBit * 2;
end;
end;
Result := retVal;
end;
// !! WARNING !!
// Under NT, the TrueCrypt driver won't tell us the full filename if it's more than
// 64 chars long, it will only return the first 60 followed by "..."
function TOTFETrueCrypt.GetVolFileForDrive(driveLetter: AnsiChar): string;
var
mountedFilenames: TStringList;
mountedDrives: Ansistring;
begin
Result := '';
driveLetter := upcase(driveLetter);
// Use GetDisksMounted(...) to get the filenames
mountedFilenames:= TStringList.Create();
try
GetDisksMounted(mountedDrives, mountedFilenames);
if Pos(driveLetter, mountedDrives)>0 then
begin
Result := mountedFilenames[Pos(driveLetter, mountedDrives)-1];
end;
finally
mountedFilenames.Free();
end;
end;
// !! WARNING !!
// If running under NT, then if the lanegth of "volumeFilename" is >64, this
// function may FAIL as the TrueCrypt driver only gives us the first 60 chars
// followed by "..." to work with
function TOTFETrueCrypt.GetDriveForVolFile(volumeFilename: string): AnsiChar;
var
mountedFilenames: TStringList;
mountedDrives: Ansistring;
numChars: integer;
begin
Result := #0;
if not(IsFilePartition(volumeFilename)) then
begin
volumeFilename := SDUConvertSFNToLFN(volumeFilename);
end;
if (CurrentOS=TrueCrypt_OS_WIN_NT) AND
(length(volumeFilename)>63) then
begin
numChars := 60;
if not(IsFilePartition(volumeFilename)) then
begin
dec(numChars, 4);
end;
volumeFilename := Copy(volumeFilename, 1, numChars);
volumeFilename := volumeFilename + '...';
end;
mountedFilenames:= TStringList.Create();
try
GetDisksMounted(mountedDrives, mountedFilenames);
if mountedFilenames.IndexOf(volumeFilename)>-1 then
begin
Result := mountedDrives[mountedFilenames.IndexOf(volumeFilename)+1];
end;
finally
mountedFilenames.Free();
end;
end;
function TOTFETrueCrypt.GetDriveInfo(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
begin
if (Version() < $300) then
begin
Result := GetDriveInfo_PRE30(driveLetter, info);
end
else if (Version() >= $300) and (Version() < $31A) then
begin
Result := GetDriveInfo_30(driveLetter, info);
end
else
begin
Result := GetDriveInfo_31a(driveLetter, info);
end;
end;
// Function to be used for TrueCrypt versions prior to v3.0
function TOTFETrueCrypt.GetDriveInfo_PRE30(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
var
dwBytesReturned : DWORD;
query: TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_PRE30;
retVal: boolean;
sysTime: SYSTEMTIME;
hi: TrueCrypt_PKCS5_TYPE;
begin
retVal := FALSE;
CheckActive();
driveLetter := upcase(driveLetter);
query.driveNo := ord(driveLetter)-ord('A');
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_VOLUME_PROPERTIES,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil) then
begin
ShortArrayToString(query.wszVolume, info.volumeFilename);
// If we're running under NT, and it's a file that's mounted, we need
// to strip off the "/??/" at the start of the filename returned
if (pos('\??\', info.volumeFilename)=1) then
begin
delete(info.volumeFilename, 1, 4);
end;
info.mountedAs:= driveLetter;
info.diskLength:= query.diskLength;
// Note that we start from the end and work backwards; that way if the
// cypher is unsupported, it gets reported as "Unknown"
GetCyphersForTrueCryptCypherID(query.cipher, info.ciphers, info.cipherMode);
info.cipherNames := GetCipherNames(info.ciphers);
info.cipherModeName := TrueCrypt_CIPHER_MODE_NAMES[info.cipherMode];
info.pkcs5Type := pkcs5Unknown;
for hi:=low(TrueCrypt_PKCS5_IDS) to high(TrueCrypt_PKCS5_IDS) do
begin
if TrueCrypt_PKCS5_IDS[hi] = query.pkcs5 then
begin
info.pkcs5Type := hi;
break;
end;
end;
info.pkcs5Iterations:= query.pkcs5Iterations;
info.pkcs5TypeName := TrueCrypt_PKCS5_NAMES[info.pkcs5Type];
info.volumeLocation:= IdentifyVolumeFileType(info.volumeFilename);
info.volumeLocationName := TrueCrypt_VOLUME_FILE_TYPE_NAMES[info.volumeLocation];
FileTimeToSystemTime(FILETIME(query.volumeCreationTime), sysTime);
info.volumeCreated := SystemTimeToDateTime(sysTime);
FileTimeToSystemTime(FILETIME(query.headerCreationTime), sysTime);
info.passwordChanged := SystemTimeToDateTime(sysTime);
info.readOnly:= IsDriveReadonly(driveLetter);
info.hidden := FALSE;
retVal := TRUE;
end;
Result := retVal;
end;
// Function to be used for TrueCrypt versions v3.0-v3.1
function TOTFETrueCrypt.GetDriveInfo_30(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
var
dwBytesReturned : DWORD;
query: TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_30;
retVal: boolean;
sysTime: SYSTEMTIME;
hi: TrueCrypt_PKCS5_TYPE;
begin
retVal := FALSE;
CheckActive();
driveLetter := upcase(driveLetter);
query.driveNo := ord(driveLetter)-ord('A');
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_VOLUME_PROPERTIES,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil) then
begin
ShortArrayToString(query.wszVolume, info.volumeFilename);
// If we're running under NT, and it's a file that's mounted, we need
// to strip off the "/??/" at the start of the filename returned
if (pos('\??\', info.volumeFilename)=1) then
begin
delete(info.volumeFilename, 1, 4);
end;
info.mountedAs:= driveLetter;
info.diskLength:= query.diskLength;
// Note that we start from the end and work backwards; that way if the
// cypher is unsupported, it gets reported as "Unknown"
GetCyphersForTrueCryptCypherID(query.ea, info.ciphers, info.cipherMode);
info.cipherNames := GetCipherNames(info.ciphers);
info.cipherModeName := TrueCrypt_CIPHER_MODE_NAMES[info.cipherMode];
// Not sure why this is needed, but that's what TrueCrypt appears to have...
if (
(info.ciphers[0] = cphrTripleDES) and (info.ciphers[0] = cphrNone) and
(info.cipherMode = cphrmodeCBC)
) then
begin
info.cipherMode := cphrmodeOuterCBC;
end;
info.pkcs5Type := pkcs5Unknown;
for hi:=low(TrueCrypt_PKCS5_IDS) to high(TrueCrypt_PKCS5_IDS) do
begin
if TrueCrypt_PKCS5_IDS[hi] = query.pkcs5 then
begin
info.pkcs5Type := hi;
break;
end;
end;
info.pkcs5Iterations:= query.pkcs5Iterations;
info.pkcs5TypeName := TrueCrypt_PKCS5_NAMES[info.pkcs5Type];
info.volumeLocation:= IdentifyVolumeFileType(info.volumeFilename);
info.volumeLocationName := TrueCrypt_VOLUME_FILE_TYPE_NAMES[info.volumeLocation];
FileTimeToSystemTime(FILETIME(query.volumeCreationTime), sysTime);
info.volumeCreated := SystemTimeToDateTime(sysTime);
FileTimeToSystemTime(FILETIME(query.headerCreationTime), sysTime);
info.passwordChanged := SystemTimeToDateTime(sysTime);
info.readOnly:= IsDriveReadonly(driveLetter);
info.hidden := query.hiddenVolume;
retVal := TRUE;
end;
Result := retVal;
end;
// Function to be used for TrueCrypt versions v3.1a and later
function TOTFETrueCrypt.GetDriveInfo_31a(driveLetter: AnsiChar; info: pTOTFETrueCryptVolumeInfo): boolean;
var
dwBytesReturned : DWORD;
query: TOTFETrueCrypt_VOLUME_PROPERTIES_STRUCT_31a;
retVal: boolean;
sysTime: SYSTEMTIME;
hi: TrueCrypt_PKCS5_TYPE;
begin
retVal := FALSE;
CheckActive();
driveLetter := upcase(driveLetter);
query.driveNo := ord(driveLetter)-ord('A');
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_VOLUME_PROPERTIES,
@query,
sizeof(query),
@query,
sizeof(query),
dwBytesReturned,
nil) then
begin
ShortArrayToString(query.wszVolume, info.volumeFilename);
// If we're running under NT, and it's a file that's mounted, we need
// to strip off the "/??/" at the start of the filename returned
if (pos('\??\', info.volumeFilename)=1) then
begin
delete(info.volumeFilename, 1, 4);
end;
info.mountedAs:= driveLetter;
info.diskLength:= query.diskLength;
// Note that we start from the end and work backwards; that way if the
// cypher is unsupported, it gets reported as "Unknown"
GetCyphersForTrueCryptCypherID(query.ea, info.ciphers, info.cipherMode);
info.cipherNames := GetCipherNames(info.ciphers);
info.cipherModeName := TrueCrypt_CIPHER_MODE_NAMES[info.cipherMode];
// Not sure why this is needed, but that's what TrueCrypt appears to have...
if (
(info.ciphers[0] = cphrTripleDES) and (info.ciphers[0] = cphrNone) and
(info.cipherMode = cphrmodeCBC)
) then
begin
info.cipherMode := cphrmodeOuterCBC;
end;
info.pkcs5Type := pkcs5Unknown;
for hi:=low(TrueCrypt_PKCS5_IDS) to high(TrueCrypt_PKCS5_IDS) do
begin
if TrueCrypt_PKCS5_IDS[hi] = query.pkcs5 then
begin
info.pkcs5Type := hi;
break;
end;
end;
info.pkcs5Iterations:= query.pkcs5Iterations;
info.pkcs5TypeName := TrueCrypt_PKCS5_NAMES[info.pkcs5Type];
info.volumeLocation:= IdentifyVolumeFileType(info.volumeFilename);
info.volumeLocationName := TrueCrypt_VOLUME_FILE_TYPE_NAMES[info.volumeLocation];
FileTimeToSystemTime(FILETIME(query.volumeCreationTime), sysTime);
info.volumeCreated := SystemTimeToDateTime(sysTime);
FileTimeToSystemTime(FILETIME(query.headerCreationTime), sysTime);
info.passwordChanged := SystemTimeToDateTime(sysTime);
info.readOnly:= query.readOnly;
info.hidden := query.hiddenVolume;
retVal := TRUE;
end;
Result := retVal;
end;
function TOTFETrueCrypt.GetVolumeInfo(volumeFilename: string; info: pTOTFETrueCryptVolumeInfo): boolean;
var
retVal: boolean;
tgtVolumeFilename: string;
mountedDrives: Ansistring;
mountedVolumeFilenames: TStringList;
i: integer;
begin
retVal := FALSE;
// Uppercase volumeFilename, and convert to LFN if it's a file
if IsFilePartition(volumeFilename) then
begin
tgtVolumeFilename := uppercase(volumeFilename);
end
else
begin
tgtVolumeFilename := uppercase(SDUConvertSFNToLFN(volumeFilename));
if (tgtVolumeFilename = '') then
begin
tgtVolumeFilename := uppercase(volumeFilename);
end;
end;
mountedVolumeFilenames := TStringList.Create();
try
// Get the filenames for all mounted volumes, and scan through until we
// get the targetted volume - the just call GetVolumeInfo(...) with the
// appropriate drive letter
if GetDisksMounted(mountedDrives, mountedVolumeFilenames) then
begin
for i:=0 to (mountedVolumeFilenames.count-1) do
begin
if (uppercase(mountedVolumeFilenames[i]) = tgtVolumeFilename) then
begin
retVal := GetDriveInfo(mountedDrives[i+1], info);
break;
end;
end;
end;
finally
mountedVolumeFilenames.Free();
end;
Result := retVal;
end;
function TOTFETrueCrypt.IdentifyVolumeFileType(volumeFilename: string): TrueCrypt_VOLUME_FILE_TYPE;
var
retVal: TrueCrypt_VOLUME_FILE_TYPE;
begin
if IsFilePartition(volumeFilename) then
begin
retVal := vtidPartition;
end
else
begin
retVal := vtidTrueCryptFile;
end;
Result := retVal;
end;
function TOTFETrueCrypt.GetWordFromHeader(buffer: array of byte; var posInBuffer: integer): cardinal;
begin
Result := (buffer[posInBuffer-1] * 256) + buffer[posInBuffer];
inc(posInBuffer, 2);
end;
// Convert an array of cypher names into a human readable string of cypher names
function TOTFETrueCrypt.GetCipherNames(cyphers: array of TrueCrypt_CIPHER_TYPE): string;
var
i: integer;
retVal: string;
allNone: boolean;
allUnknown: boolean;
begin
retVal := '';
// Check to see if *all* the cyphers are still cphrNone/cphrUnknown
allNone := TRUE;
allUnknown := TRUE;
for i:=low(cyphers) to high(cyphers) do
begin
if (cyphers[i] <> cphrNone) then
begin
// At least *one* of the cyphers was not cphrNone
allNone := FALSE;
end;
if (cyphers[i] <> cphrUnknown) then
begin
// At least *one* of the cyphers was not cphrUnknown
allUnknown := FALSE;
end;
end;
if allNone then
begin
// Special case: All cyphers are unused
retVal := TrueCrypt_CIPHER_NAMES[cphrNone];
end
else if allUnknown then
begin
// Special case: All cyphers are unknown
retVal := TrueCrypt_CIPHER_NAMES[cphrUnknown];
end
else
begin
// Spin through the list of cyphers, converting to human readable names
// Now *THIS* is counter-intuitive. TrueCrypt's structures store the
// cyphers in the *REVERSE* order to that which they should be displayed
// in?! Yet more TrueCrypt freakyness...
for i:=high(cyphers) downto low(cyphers) do
begin
// Note: Skip unused cypher elements
if (cyphers[i] <> cphrNone) then
begin
if (retVal <> '') then
begin
retVal := retVal + '-';
end;
retVal := retVal + TrueCrypt_CIPHER_NAMES[cyphers[i]];
end;
end;
end;
Result := retVal;
end;
function TOTFETrueCrypt.ClearPasswords(driveLetter: AnsiChar): boolean;
var
dwResult: DWORD;
begin
Result := DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_WIPE_CACHE,
nil,
0,
nil,
0,
dwResult,
nil);
end;
function TOTFETrueCrypt.IsEncryptedVolFile(volumeFilename: string): boolean;
begin
CheckActive();
Result := TRUE;
end;
function TOTFETrueCrypt.Title(): string;
begin
Result := 'TrueCrypt';
end;
function TOTFETrueCrypt.Version(): cardinal;
var
driverVers: TOTFETrueCrypt_VERSION;
dwResult: DWORD;
begin
CheckActive();
if FTrueCryptDriverVersion=$FFFFFFFF then
begin
if DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_DRIVER_VERSION,
@driverVers,
sizeof(driverVers),
@driverVers,
sizeof(driverVers),
dwResult,
nil) then
begin
FTrueCryptDriverVersion := driverVers.version;
end
else
begin
FTrueCryptDriverVersion:=$FFFFFFFF;
end;
end;
Result := FTrueCryptDriverVersion;
end;
function TOTFETrueCrypt.CloseSlot(driveNum: integer; brutal: boolean): boolean;
begin
if (ld(driveNum, 1)) then
begin
Result := FALSE;
FLastErrCode := OTFE_ERR_FILES_OPEN;
end
else
begin
Result := DoDeviceClose(driveNum);
ld(driveNum, 0);
end;
end;
function TOTFETrueCrypt.ld(driveNum: integer; mode: integer): boolean;
var
a: boolean;
drivelett: integer;
begin
a:= TRUE;
drivelett := driveNum + 1;
if ((drivelett > 1) AND (drivelett<27)) then
begin
a := (locklogdrive(drivelett, mode));
end;
Result := a;
end;
// Returns TRUE if error
function TOTFETrueCrypt.locklogdrive(drivenum: integer; mode: integer): boolean;
var
a: integer;
begin
if (mode<>0) then
begin
ioctllock(drivenum, 0, 1);
a := ioctllock(drivenum, 4, 1);
end
else
begin
a := 0;
ioctllock(drivenum, 0, 0);
ioctllock(drivenum, 0, 0);
end;
Result := (a<>0);
end;
function TOTFETrueCrypt.ioctllock(nDrive: cardinal; permissions: integer; func: integer): integer;
var
hDevice: THANDLE;
reg: TDeviceIOControlRegisters;
cb: DWORD;
lockfunc: integer;
begin
if (func<>0) then
begin
lockfunc := $4a;
end
else
begin
lockfunc := $6a;
end;
hDevice := CreateFile('\\.\vwin32',
0, 0, nil, 0, FILE_FLAG_DELETE_ON_CLOSE, 0);
reg.reg_EAX := $440D;
reg.reg_EBX := nDrive;
reg.reg_ECX := $0800 OR lockfunc;
reg.reg_EDX := permissions;
reg.reg_Flags := $0001;
DeviceIoControl(hDevice,
VWIN32_DIOC_DOS_IOCTL,
@reg, sizeof(reg),
@reg, sizeof(reg),
cb, nil);
CloseHandle (hDevice);
Result := (reg.reg_Flags AND 1); // error if carry flag is set
end;
function TOTFETrueCrypt.DoDeviceClose(driveNum: integer): boolean;
var
mount_list: TOTFETrueCrypt_MOUNT_LIST_N_STRUCT;
unmount: TOTFETrueCrypt_UNMOUNT_STRUCT_PRE30;
tries: integer;
c: integer;
dwBytes: DWORD;
volFilename: string;
begin
mount_list.nDosDriveNo := driveNum;
if (DeviceIoControl(hTrueCryptVxD, TrueCrypt_IOCTL_MOUNT_LIST_N, @mount_list, sizeof(mount_list), nil, 0, dwBytes, nil) = FALSE) then
begin
FLastErrCode := OTFE_ERR_DRIVER_FAILURE;
Result := FALSE;
exit;
end
else
begin
if (mount_list.nReturnCode<>0) then
begin
FLastErrCode := OTFE_ERR_SUCCESS;
Result := TRUE;
exit;
end;
end;
if (mount_list.mountfilehandle<>0) then
begin
ShortArrayToString(mount_list.wszVolume, volFilename);
EjectStop(AnsiChar(upcase(volFilename[1])), FALSE);
end;
unmount.nDosDriveNo := driveNum;
if (DeviceIoControl (hTrueCryptVxD, TrueCrypt_IOCTL_UNMOUNT_PENDING, @unmount, sizeof(unmount), nil, 0, dwBytes, nil) = FALSE) then
begin
FLastErrCode := OTFE_ERR_DRIVER_FAILURE;
Result := FALSE;
exit;
end
else
begin
if (mount_list.nReturnCode<>0) then
begin
FLastErrCode := OTFE_ERR_SUCCESS;
Result := TRUE;
exit;
end;
end;
for c:=0 to 19 do
begin
DeviceIoControl(hTrueCryptVxD, TrueCrypt_IOCTL_RELEASE_TIME_SLICE, nil, 0, nil, 0, dwBytes, nil);
end;
for tries:=0 to 31 do
begin
DeviceIoControl (hTrueCryptVxd, TrueCrypt_IOCTL_RELEASE_TIME_SLICE, nil, 0, nil, 0, dwBytes, nil);
if (DeviceIoControl (hTrueCryptVxd, TrueCrypt_IOCTL_UNMOUNT, @unmount, sizeof(UNMOUNT), nil, 0, dwBytes, nil) = FALSE) then
begin
FLastErrCode := OTFE_ERR_DRIVER_FAILURE;
Result := FALSE;
exit;
end
else
begin
if (mount_list.nReturnCode=0) then
begin
FLastErrCode := OTFE_ERR_SUCCESS;
Result := TRUE;
exit;
end;
end;
end;
FLastErrCode := OTFE_ERR_SUCCESS;
Result := TRUE;
end;
function TOTFETrueCrypt.EjectStop(driveLetter: AnsiChar; func: boolean): boolean;
var
hDevice: THANDLE;
reg: TDeviceIOControlRegisters;
cb: DWORD;
lockfunc: integer;
p: TPARAMBLOCK;
driveNum: integer;
begin
if (driveletter = #0) then
begin
Result := FALSE;
exit;
end;
driveNum := ord('A') - ord(driveLetter) + 1;
lockfunc := $48;
if (func = TRUE) then
begin
p.Operation := 0; // lock
end
else
begin
p.Operation := 1;
end;
hDevice := CreateFile('\\.\vwin32', 0, 0, nil, 0,
FILE_FLAG_DELETE_ON_CLOSE, 0);
reg.reg_EAX := $440D;
reg.reg_EBX := driveNum;
reg.reg_ECX := $0800 OR lockfunc;
reg.reg_EDX := Cardinal(@p); // xxx - Not sure if this will work OK?
reg.reg_Flags := $0001;
DeviceIoControl(hDevice,
VWIN32_DIOC_DOS_IOCTL,
@reg, sizeof(reg),
@reg, sizeof(reg),
cb,
nil);
CloseHandle (hDevice);
Result := (reg.reg_Flags AND 1)>0; // error if carry flag is set */
end;
{
procedure TOTFETrueCrypt.AddVolumeToHistory(volumeFilename: string);
var
i: integer;
key: string;
iniFile: TIniFile;
lastVol: string;
historyMRU: TStringList;
begin
if SaveHistory then
begin
iniFile := TIniFile.Create(TrueCrypt_INI_FILE);
try
historyMRU:= TStringList.Create();
try
for i:=1 to TrueCrypt_SIZEOF_MRU_LIST do
begin
key := TrueCrypt_INI_KEY_LASTVOLUMEn + inttostr(i);
historyMRU.Add(iniFile.ReadString(TrueCrypt_INI_SECTION_LASTRUN, key, ''));
end;
// if volumeFilename does not exist in the list, add it. If it does
// exist, move it to the head of the list.
if historyMRU.IndexOf(volumeFilename)<0 then
begin
historyMRU.Add(lastVol);
end
else
begin
historyMRU.Delete(historyMRU.IndexOf(volumeFilename));
historyMRU.Insert(0, volumeFilename);
end;
for i:=1 to TrueCrypt_SIZEOF_MRU_LIST do
begin
key := TrueCrypt_INI_KEY_LASTVOLUMEn + inttostr(i);
iniFile.WriteString(TrueCrypt_INI_SECTION_LASTRUN, key, historyMRU[i-1]);
end;
finally
historyMRU.Free();
end;
finally
iniFile.Free();
end;
end;
end;
}
function TOTFETrueCrypt.GetNextUnusedDrvLtr(afterDrv: AnsiChar): AnsiChar;
var
finished: boolean;
unusedDrvs: Ansistring;
begin
Result := #0;
finished := FALSE;
unusedDrvs := GetUnusedDriveLetters();
while not(finished) do
begin
afterDrv := AnsiChar(ord(afterDrv)+1);
if ord(afterDrv)>ord('Z') then
begin
finished := TRUE;
end
else
begin
if pos(afterDrv, unusedDrvs)>0 then
begin
Result := afterDrv;
finished := TRUE;
end;
end;
end;
end;
// Returns a string containing the drive letters of "unallocated" drives
function TOTFETrueCrypt.GetUnusedDriveLetters(): Ansistring;
var
driveLetters: Ansistring;
DriveNum: Integer;
DriveBits: set of 0..25;
begin
driveLetters := '';
Integer(DriveBits) := GetLogicalDrives;
for DriveNum := 0 to 25 do
begin
if not(DriveNum in DriveBits) then
begin
driveLetters := driveLetters + AnsiChar(DriveNum + Ord('A'));
end;
end;
Result := driveLetters;
end;
function TOTFETrueCrypt.VersionStr(): string;
var
verNo: cardinal;
majorVer : integer;
minorVer1: integer;
minorVer2: integer;
retVal: string;
begin
verNo:= Version();
majorVer := (verNo AND $FF00) div $FF;
minorVer1 := (verNo AND $F0) div $F;
minorVer2 := (verNo AND $F);
retVal := Format('v%d.%d', [majorVer, minorVer1]);
// Check for version v2.1 and v2.1a - THEY HAVE DIFFERENT CYPHERS, BUT THE
// DRIVER REPORTS $0210 IN BOTH CASES
if (verNo = $0210) then
begin
// This is where it gets crappy... We've no idea if we're dealing with
// v2.1 or v2.1a! And... THE CYPHER, ETC IDS CHANGED BETWEEN THESE TWO VERSIONS!!!
if (UseVersionHint() = tcv21) then
begin
// No change to retVal - it's just straight v2.1
end
else if (UseVersionHint() = tcv21a) then
begin
retVal := retVal + 'a';
end
else
begin
// We know it's either v2.1 or v2.1a, but can't tell which.
// Indicate this.
retVal := retVal + '(???)';
end;
end
else
begin
if (minorVer2 > 0) then
begin
// We subtract $0A because v. 3.1a was $031A
retVal := retVal + char((minorVer2 - $0A) + ord('a'));
end;
end;
Result := retVal;
end;
function TOTFETrueCrypt.GetMainExe(): string;
var
registry: TRegistry;
keyName: string;
appPath: string;
exeLocation: string;
wholeString: string;
firstItem: string;
theRest: string;
begin
Result := '';
FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE;
registry := TRegistry.create();
try
registry.RootKey := TrueCrypt_REGISTRY_EXE_ROOT;
keyName := TrueCrypt_REGISTRY_EXE_PATH;
if registry.OpenKeyReadOnly(keyName) then
begin
appPath := registry.ReadString('');
exeLocation := ExtractFilePath(appPath) + TrueCrypt_APP_EXE_NAME;
if FileExists(exeLocation) then
begin
Result := exeLocation
end
else
begin
// The registry key may well be of the form:
// "C:\Program Files\TrueCrypt\TrueCrypt.exe" /v "%1"
wholeString := appPath;
if SDUSplitString(wholeString, firstItem, theRest, '"') then
begin
// The first item is just a dumn quote - ignore as "firstItem" will
// be an empty string
wholeString := theRest;
if SDUSplitString(wholeString, firstItem, theRest, '"') then
begin
exeLocation := firstItem;
if FileExists(exeLocation) then
begin
Result := exeLocation
end;
end;
end;
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
if Result<>'' then
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
end;
function TOTFETrueCrypt.GetAvailableRemovables(dispNames: TStringList; deviceNames: TStringList): integer;
var
cnt: integer;
szTmp: array [0..TrueCrypt_TC_MAX_PATH-1] of char;
begin
cnt := 0;
if CurrentOS=TrueCrypt_OS_WIN_NT then
begin
if (QueryDosDevice('A:', @szTmp[0], sizeof(szTmp))<>0) then
begin
dispNames.Add('Floppy (A:)');
deviceNames.Add('\Device\Floppy0');
inc(cnt);
end;
if (QueryDosDevice('B:', @szTmp[0], sizeof(szTmp))<>0) then
begin
dispNames.Add('Floppy (B:)');
deviceNames.Add('\Device\Floppy1');
inc(cnt);
end;
end;
Result := cnt;
end;
function TOTFETrueCrypt.GetAvailableFixedDisks(dispNames: TStringList; deviceNames: TStringList): integer;
var
i: integer;
n: integer;
cnt: integer;
strTmp: string;
begin
cnt := 0;
i := 0;
// This "64" is hardcoded in the TrueCrypt application (not a const!)
while (i<64) do
begin
// This "32" is hardcoded in the TrueCrypt application (not a const!)
for n:=1 to 32 do
begin
strTmp := Format(TrueCrypt_HDD_PARTITION_DEVICE_NAME_FORMAT, [i, n]);
if OpenDevice(strTmp) then
begin
dispNames.Add(strTmp);
deviceNames.Add(strTmp);
inc(cnt);
end
else
begin
if n=1 then
begin
i := 64;
break;
end;
end;
end;
inc(i);
end;
Result := cnt;
end;
function TOTFETrueCrypt.OpenDevice(device: string): boolean;
var
query: TOTFETrueCrypt_OPEN_TEST;
dwResult: DWORD;
currAllOK: boolean;
begin
CheckActive();
StringToShortArray(device, query.wszFileName);
currAllOK := DeviceIoControl(hTrueCryptVxD,
TrueCrypt_IOCTL_OPEN_TEST,
@query,
sizeof(query),
@query,
sizeof(query),
dwResult,
nil);
if not(currAllOK) then
begin
dwResult := GetLastError();
Result := (dwResult = ERROR_SHARING_VIOLATION);
end
else
begin
if CurrentOS=TrueCrypt_OS_WIN_NT then
begin
Result := TRUE;
end
else if (query.nReturnCode = 0) then
begin
Result := TRUE;
end
else
begin
FLastErrCode := OTFE_ERR_VOLUME_FILE_NOT_FOUND;
Result := FALSE;
end;
end;
end;
function TOTFETrueCrypt.GetAvailableRawDevices(dispNames: TStringList; deviceNames: TStringList): boolean;
var
stlTempDisp: TStringList;
stlTempDevice: TStringList;
begin
CheckActive();
dispNames.Clear();
deviceNames.Clear();
GetAvailableRemovables(dispNames, deviceNames);
stlTempDisp:= TStringList.Create();
try
stlTempDevice:= TStringList.Create();
try
GetAvailableFixedDisks(stlTempDisp, stlTempDevice);
dispNames.AddStrings(stlTempDisp);
deviceNames.AddStrings(stlTempDevice);
finally
stlTempDevice.Free();
end;
finally
stlTempDisp.Free();
end;
Result := TRUE;
end;
// This function is required under NT/2K/XP unicode is stored. Under 9x, it's
// just straight 8 bit chars
// Under NT to store WCHARs
// Under 95/98 to store chars
// as a result of this, we need to extract data from these arrays with in the
// correct way, depending on the OS being used...
// i.e. This function will take an TrueCrypt array of short and convert it back into
// a string
procedure TOTFETrueCrypt.ShortArrayToString(theArray: array of WCHAR; var theString: string);
var
i: integer;
hiNotLo: boolean;
shortChar: short;
begin
theString := '';
if CurrentOS<>TrueCrypt_OS_WIN_NT then
begin
i:=0;
hiNotLo:= TRUE;
shortChar := (short(theArray[0]) AND $FF);
while shortChar<>0 do
begin
theString := theString + chr(shortChar);
hiNotLo := not(hiNotLo);
shortChar := short(theArray[i]);
if hiNotLo then
begin
shortChar := shortChar AND $FF;
end
else
begin
shortChar := (shortChar AND $FF00) shr 8;
inc(i);
end;
end;
end
else
begin
i:=0;
shortChar := short(theArray[0]);
while shortChar<>0 do
begin
theString := theString + char(shortChar);
inc(i);
shortChar := short(theArray[i]);
end;
end;
end;
// This function is required as v2.0.1's short arrays are used:
// Under NT to store WCHARs
// Under 95/98 to store chars
// as a result of this, we need to fill in these arrays with correctly packed
// data, depending on the OS being used
// i.e. This function will take a string and put it into an TrueCrypt array of short
procedure TOTFETrueCrypt.StringToShortArray(theString: string; var theArray: array of WCHAR);
var
i: integer;
hiNotLo: boolean;
arrPos: integer;
begin
theString := theString + #0;
if CurrentOS<>TrueCrypt_OS_WIN_NT then
begin
hiNotLo:= TRUE;
arrPos := 0;
theArray[arrPos] := #0;
for i:=1 to length(theString) do
begin
if hiNotLo then
begin
theArray[arrPos] := WCHAR(theString[i]);
end
else
begin
theArray[arrPos] := WCHAR(cardinal(theArray[arrPos]) OR (ord(theString[i]) shl 8));
inc(arrPos);
theArray[arrPos] := #0;
end;
hiNotLo := not(hiNotLo);
end;
end
else
begin
for i:=1 to length(theString) do
begin
theArray[i-1] := WCHAR(theString[i]);
end;
end;
end;
// Returns TRUE if "volumeFilename" is a partition, not a file
function TOTFETrueCrypt.IsFilePartition(volumeFilename: string): boolean;
begin
Result := (pos('\DEVICE\', uppercase(volumeFilename))=1);
end;
procedure TOTFETrueCrypt.LoadSettings();
var
registry: TRegistry;
keyName: string;
tmpDriveLetter: Ansistring;
i: integer;
tmpLastMountedVolume: string;
begin
FLastErrCode:= OTFE_ERR_UNKNOWN_ERROR;
registry := TRegistry.create();
try
registry.RootKey := TrueCrypt_REGISTRY_SETTINGS_ROOT;
keyName := TrueCrypt_REGISTRY_SETTINGS_PATH;
if registry.OpenKeyReadOnly(keyName) then
begin
// Options
FCachePasswordsInDriver := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CACHEPASSWORDSINDRIVER;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_CACHEPASSWORDSINDRIVER) then
begin
try
FCachePasswordsInDriver := registry.ReadBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_CACHEPASSWORDSINDRIVER);
except
FCachePasswordsInDriver := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CACHEPASSWORDSINDRIVER;
end;
end;
FOpenExplorerWindowAfterMount := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_OPENEXPLORERWINDOWAFTERMOUNT;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_OPENEXPLORERWINDOWAFTERMOUNT) then
begin
try
FOpenExplorerWindowAfterMount := registry.ReadBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_OPENEXPLORERWINDOWAFTERMOUNT);
except
FOpenExplorerWindowAfterMount := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_OPENEXPLORERWINDOWAFTERMOUNT;
end;
end;
FCloseExplorerWindowsOnDismount := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CLOSEEXPLORERWINDOWSONDISMOUNT;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_CLOSEEXPLORERWINDOWSONDISMOUNT) then
begin
try
FCloseExplorerWindowsOnDismount := registry.ReadBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_CLOSEEXPLORERWINDOWSONDISMOUNT);
except
FCloseExplorerWindowsOnDismount := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_CLOSEEXPLORERWINDOWSONDISMOUNT;
end;
end;
FSaveMountedVolumesHistory := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_SAVEMOUNTEVOLUMESHISTORY;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_SAVEMOUNTEVOLUMESHISTORY) then
begin
try
FSaveMountedVolumesHistory := registry.ReadBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_SAVEMOUNTEVOLUMESHISTORY);
except
FSaveMountedVolumesHistory := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_SAVEMOUNTEVOLUMESHISTORY;
end;
end;
FWipePasswordCacheOnExit := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_WIPEPASSWORDCACHEONEXIT;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_WIPEPASSWORDCACHEONEXIT) then
begin
try
FWipePasswordCacheOnExit := registry.ReadBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_WIPEPASSWORDCACHEONEXIT);
except
FWipePasswordCacheOnExit := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_WIPEPASSWORDCACHEONEXIT;
end;
end;
// Drive Letter
tmpDriveLetter := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTSELECTEDDRIVE;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_LASTSELECTEDDRIVE) then
begin
try
tmpDriveLetter := registry.ReadString(TrueCrypt_REGISTRY_SETTINGS_PARAM_LASTSELECTEDDRIVE);
except
tmpDriveLetter := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTSELECTEDDRIVE;
end;
if (tmpDriveLetter <> '') then
begin
FLastSelectedDrive := tmpDriveLetter[1];
end
else
begin
FLastSelectedDrive := #0;
end;
end;
// History
for i:=0 to (TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME-1) do
begin
tmpLastMountedVolume := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTMOUNTEVOLUME;
if registry.ValueExists(TrueCrypt_REGISTRY_SETTINGS_PARAM_PREFIX_LASTMOUNTEVOLUME+inttostr(i)) then
begin
try
tmpLastMountedVolume := registry.ReadString(TrueCrypt_REGISTRY_SETTINGS_PARAM_PREFIX_LASTMOUNTEVOLUME+inttostr(i));
except
tmpLastMountedVolume := TrueCrypt_REGISTRY_SETTINGS_PARAM_DFLT_LASTMOUNTEVOLUME;
end;
SetLastMountedVolume(i+1, tmpLastMountedVolume);
end;
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
procedure TOTFETrueCrypt.SaveSettings();
var
registry: TRegistry;
keyName: string;
i: integer;
tmpLastMountedVolume: string;
begin
FLastErrCode:= OTFE_ERR_UNKNOWN_ERROR;
registry := TRegistry.create();
try
registry.RootKey := TrueCrypt_REGISTRY_SETTINGS_ROOT;
keyName := TrueCrypt_REGISTRY_SETTINGS_PATH;
if registry.OpenKey(keyName, TRUE) then
begin
// Options
registry.WriteBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_CACHEPASSWORDSINDRIVER, FCachePasswordsInDriver);
registry.WriteBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_OPENEXPLORERWINDOWAFTERMOUNT, FOpenExplorerWindowAfterMount);
registry.WriteBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_CLOSEEXPLORERWINDOWSONDISMOUNT, FCloseExplorerWindowsOnDismount);
registry.WriteBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_SAVEMOUNTEVOLUMESHISTORY, FSaveMountedVolumesHistory);
registry.WriteBool(TrueCrypt_REGISTRY_SETTINGS_PARAM_WIPEPASSWORDCACHEONEXIT, FWipePasswordCacheOnExit);
// Drive Letter
if ((FLastSelectedDrive = #0) OR (not(SaveMountedVolumesHistory))) then
begin
registry.WriteString(TrueCrypt_REGISTRY_SETTINGS_PARAM_LASTSELECTEDDRIVE, '');
end
else
begin
registry.WriteString(TrueCrypt_REGISTRY_SETTINGS_PARAM_LASTSELECTEDDRIVE, FLastSelectedDrive+':');
end;
// History
for i:=0 to (TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME-1) do
begin
tmpLastMountedVolume := GetLastMountedVolume(i+1);
registry.WriteString(TrueCrypt_REGISTRY_SETTINGS_PARAM_PREFIX_LASTMOUNTEVOLUME+inttostr(i), tmpLastMountedVolume);
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
function TOTFETrueCrypt.SetLastMountedVolume(idx: integer; filename: string): boolean;
begin
Result := FALSE;
if ((idx>=1) and (idx<TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME)) then
begin
FLastMountedVolume[idx-1] := filename;
Result := TRUE;
end;
end;
// "idx" should be between 1 and TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME
// Returns '' on error
// Also returns '' if there is no filename in that position
function TOTFETrueCrypt.GetLastMountedVolume(idx: integer): string;
begin
Result := '';
if ((idx>=1) and (idx<TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME)) then
begin
Result := FLastMountedVolume[idx-1];
end;
end;
// Note: Calling AddVolumeToHistory will push the oldest filename on the MRU
// list off
procedure TOTFETrueCrypt.AddLastMountedVolume(volumeFilename: string);
var
i: integer;
begin
for i:=1 to TrueCrypt_REGISTRY_SETTINGS_COUNT_LASTMOUNTEVOLUME do
begin
if (GetLastMountedVolume(i)<>'') then
begin
SetLastMountedVolume(i, volumeFilename);
end;
end;
end;
// Function to convert TrueCrypt cypher ID into the Delphi cypher type/types
// This function is required because TrueCrypt is *FOUL* and different versions
// of the TrueCrypt driver use different IDs - and sometimes the IDs change,
// but the driver version doens't?!!! (e.g. v2.1->v2.1a)
// YUCK! DISGUSTING! :(
// Returns: TRUE/FALSE, depending on whether the cypher ID was recognised
// If TRUE, the FIRST THREE ELEMENTS OF "cyphers" will be populated
// with the relevant cyphers; unused elements will be populated
// with cphrNone
function TOTFETrueCrypt.GetCyphersForTrueCryptCypherID(cypherID: integer; var cyphers: array of TrueCrypt_CIPHER_TYPE; var cypherMode: TrueCrypt_CIPHER_MODE): boolean;
var
i: integer;
allOK: boolean;
allUnknown: boolean;
verNo: cardinal;
begin
allOK := FALSE;
for i:=low(cyphers) to high(cyphers) do
begin
cyphers[i] := cphrUnknown;
end;
verNo := Version();
// OK, now *THIS* is *puke* - *every* different TrueCrypt versions use
// different IDs, so we're stuck with doing this :(
// Couldn't they just use nice enums in their code, as opposed to #defining
// everything?!! Ewww!
// WHY ON EARTH does the "cypher chaining system" use PROSCRIBED CYPHER
// COMBINATIONS?!! This is TRUELY IDIOTIC! Let the ***USER*** decide what
// combination they want to use - much more flexible!
if (verNo <= $0100) then
begin
// v1.0 driver...
cypherMode := cphrmodeCBC;
case cypherID of
0:
begin
cyphers[0] := cphrNone;
end;
1:
begin
cyphers[0] := cphrBlowfish;
end;
2:
begin
cyphers[0] := cphrCAST;
end;
3:
begin
cyphers[0] := cphrIDEA;
end;
4:
begin
cyphers[0] := cphrTRIPLEDES;
end;
100:
begin
cyphers[0] := cphrDES56;
end;
end; // case cypherID of
end
else if ( (verNo > $0100) and (verNo <= $0200) ) then
begin
// v2.0 driver...
cypherMode := cphrmodeCBC;
case cypherID of
0:
begin
cyphers[0] := cphrNone;
end;
1:
begin
cyphers[0] := cphrBlowfish;
end;
2:
begin
cyphers[0] := cphrAES;
end;
3:
begin
cyphers[0] := cphrCAST;
end;
4:
begin
cyphers[0] := cphrIDEA;
end;
5:
begin
cyphers[0] := cphrTRIPLEDES;
end;
100:
begin
cyphers[0] := cphrDES56;
end;
end; // case cypherID of
end
else if ( (verNo > $0200) and (verNo <= $0210) ) then
begin
// v2.1/v2.1a driver...
cypherMode := cphrmodeCBC;
// This is where it gets crappy... We've no idea if we're dealing with
// v2.1 or v2.1a! And... THE IDS CHANGED BETWEEN THESE TWO VERSIONS!!!
if (UseVersionHint() = tcv21) then
begin
// v2.1 driver...
case cypherID of
0:
begin
cyphers[0] := cphrNone;
end;
1:
begin
cyphers[0] := cphrBlowfish;
end;
2:
begin
cyphers[0] := cphrAES;
end;
3:
begin
cyphers[0] := cphrCAST;
end;
4:
begin
cyphers[0] := cphrIDEA;
end;
5:
begin
cyphers[0] := cphrTRIPLEDES;
end;
100:
begin
cyphers[0] := cphrDES56;
end;
end; // case cypherID of
end // if statement
else
begin
// v2.1a driver...
case cypherID of
0:
begin
cyphers[0] := cphrNone;
end;
1:
begin
cyphers[0] := cphrBlowfish;
end;
2:
begin
cyphers[0] := cphrAES;
end;
3:
begin
cyphers[0] := cphrCAST;
end;
4:
begin
cyphers[0] := cphrTRIPLEDES;
end;
100:
begin
cyphers[0] := cphrDES56;
end;
end; // case cypherID of
end; // ELSE PART
end
else if (verNo > $0210) then // e.g. 030A for v3.0a
begin
// v3.0 driver...
case cypherID of
0:
begin
cyphers[0] := cphrNone;
cypherMode := cphrmodeCBC;
end;
1:
begin
cyphers[0] := cphrAES;
cypherMode := cphrmodeCBC;
end;
2:
begin
cyphers[0] := cphrBlowfish;
cypherMode := cphrmodeCBC;
end;
3:
begin
cyphers[0] := cphrCAST;
cypherMode := cphrmodeCBC;
end;
4:
begin
cyphers[0] := cphrSerpent;
cypherMode := cphrmodeCBC;
end;
5:
begin
cyphers[0] := cphrTRIPLEDES;
cypherMode := cphrmodeCBC;
end;
6:
begin
cyphers[0] := cphrTwofish;
cypherMode := cphrmodeCBC;
end;
7:
begin
cyphers[0] := cphrBlowfish;
cyphers[1] := cphrAES;
cypherMode := cphrmodeInnerCBC;
end;
8:
begin
cyphers[0] := cphrSerpent;
cyphers[1] := cphrBlowfish;
cyphers[2] := cphrAES;
cypherMode := cphrmodeInnerCBC;
end;
9:
begin
cyphers[0] := cphrTwofish;
cyphers[1] := cphrAES;
cypherMode := cphrmodeOuterCBC;
end;
10:
begin
cyphers[0] := cphrSerpent;
cyphers[1] := cphrTwofish;
cyphers[2] := cphrAES;
cypherMode := cphrmodeOuterCBC;
end;
11:
begin
cyphers[0] := cphrAES;
cyphers[1] := cphrSerpent;
cypherMode := cphrmodeOuterCBC;
end;
12:
begin
cyphers[0] := cphrAES;
cyphers[1] := cphrTwofish;
cyphers[2] := cphrSerpent;
cypherMode := cphrmodeOuterCBC;
end;
13:
begin
cyphers[0] := cphrTwofish;
cyphers[1] := cphrSerpent;
cypherMode := cphrmodeOuterCBC;
end;
end; // case cypherID of
end;
// Check to see if *all* the cyphers are still cphrUnknown
allUnknown := TRUE;
for i:=low(cyphers) to high(cyphers) do
begin
if (cyphers[i] <> cphrUnknown) then
begin
// At least *one* of the cyphers was not cphrUnknown
allUnknown := FALSE;
break;
end;
end;
// Change unused cyphers from cphrUnknown to cphrNone
if not(allUnknown) then
begin
allOK := TRUE;
for i:=low(cyphers) to high(cyphers) do
begin
if (cyphers[i] = cphrUnknown) then
begin
cyphers[i] := cphrNone;
end;
end;
end;
Result := allOK;
end;
// This is a last ditch attempt to identify the version of TrueCrypt
// installed: Use the programmed hint, or failing that, check the file size of
// the TrueCrypt executable.
// Horrible hack, but it's all we can do because the driver doesn't report
// its's version ID correctly
function TOTFETrueCrypt.UseVersionHint(): TTrueCryptVersionHint;
var
exeFilename: string;
f: file of Byte;
size: integer;
i: TTrueCryptVersionHint;
retVal: TTrueCryptVersionHint;
begin
retVal := VersionHint;
if (VersionHint = tcvAuto) then
begin
// There is no user defined hint... Time for a last ditch attempt...
exeFilename := GetMainExe();
if (exeFilename <> '') then
begin
AssignFile(f, exeFilename);
FileMode := 0; // Reset is in readonly mode
Reset(f);
size := FileSize(f);
CloseFile(f);
// Check filesize against known executable sizes...
for i:=low(TrueCrypt_EXE_FILESIZES) to high(TrueCrypt_EXE_FILESIZES) do
begin
if (TrueCrypt_EXE_FILESIZES[i] = size) then
begin
retVal := i;
break;
end;
end; // for i:=low(TrueCrypt_EXE_FILESIZES) to high(TrueCrypt_EXE_FILESIZES) do
end; // if (exeFilename <> '') then
end; // if (VersionHint = tcvAuto) then
Result:= retVal;
end;
// -----------------------------------------------------------------------------
// Prompt the user for a device (if appropriate) and password (and drive
// letter if necessary), then mount the device selected
// Returns the drive letter of the mounted devices on success, #0 on failure
function TOTFETrueCrypt.MountDevices(): Ansistring;
var
mntDeviceDlg: TOTFETrueCryptMountDevice_F;
finished: boolean;
begin
Result := '';
if MountDeviceDlg9xStyle then
begin
mntDeviceDlg := TOTFETrueCryptMountDevice9x_F.Create(nil);
end
else
begin
mntDeviceDlg := TOTFETrueCryptMountDeviceNT_F.Create(nil);
end;
try
mntDeviceDlg.TrueCryptComponent := self;
if mntDeviceDlg.ShowModal()=mrOK then
begin
finished:=FALSE;
while not(finished) do
begin
Result := Mount(mntDeviceDlg.PartitionDevice, FALSE);
finished := (Result<>#0);
if not(finished) then
begin
finished := (LastErrorCode<>OTFE_ERR_WRONG_PASSWORD);
if not(finished) then
begin
MessageDlg('Wrong passsword entered; try again', mtError, [mbOK], 0);
end;
end;
end;
end;
finally
mntDeviceDlg.Free();
end;
end;
// -----------------------------------------------------------------------------
// Determine if OTFE component can mount devices.
// Returns TRUE if it can, otherwise FALSE
function TOTFETrueCrypt.CanMountDevice(): boolean;
begin
// Supported...
Result := TRUE;
end;
// -----------------------------------------------------------------------------
END.
|
{-----------------------------------------------------------------------------
Unit Name: UCMail
Author: QmD
Date: 09-nov-2004
Purpose: Send Mail messages (forget password, user add/change/password force/etc)
History: included indy 10 support
-----------------------------------------------------------------------------}
unit UCMail;
interface
{.$I 'UserControl.inc'}
uses
Classes,
Dialogs,
UCALSMTPClient,
SysUtils,
UcConsts_Language;
type
TUCMailMessage = class(TPersistent)
private
FAtivo: Boolean;
FTitulo: String;
FLines: TStrings;
procedure SetLines(const Value: TStrings);
protected
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Ativo: Boolean read FAtivo write FAtivo;
property Titulo: String read FTitulo write FTitulo;
property Mensagem: TStrings read FLines write SetLines;
end;
TUCMEsqueceuSenha = class(TUCMailMessage)
private
FLabelLoginForm: String;
FMailEnviado: String;
protected
public
published
property LabelLoginForm: String read FLabelLoginForm write FLabelLoginForm;
property MensagemEmailEnviado: String read FMailEnviado write FMailEnviado;
end;
TMessageTag = procedure(Tag: String; var ReplaceText: String) of object;
TMailUserControl = class(TComponent)
private
FPorta: Integer;
FEmailRemetente: String;
FUsuario: String;
FNomeRemetente: String;
FSenha: String;
FSMTPServer: String;
FAdicionaUsuario: TUCMailMessage;
FSenhaTrocada: TUCMailMessage;
FAlteraUsuario: TUCMailMessage;
FSenhaForcada: TUCMailMessage;
FEsqueceuSenha: TUCMEsqueceuSenha;
fAuthType: TAlSmtpClientAuthType;
function ParseMailMSG(Nome, Login, Senha, Email, Perfil, txt: String): String;
function TrataSenha(Senha: String; Key: Word): String;
procedure onStatus(Status: String);
protected
procedure EnviaEmailTp(Nome, Login, USenha, Email, Perfil: String; UCMSG: TUCMailMessage);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure EnviaEmailAdicionaUsuario(Nome, Login, Senha, Email, Perfil: String; Key: Word);
procedure EnviaEmailAlteraUsuario(Nome, Login, Senha, Email, Perfil: String; Key: Word);
procedure EnviaEmailSenhaForcada(Nome, Login, Senha, Email, Perfil: String);
procedure EnviaEmailSenhaTrocada(Nome, Login, Senha, Email, Perfil: String; Key: Word);
procedure EnviaEsqueceuSenha(Nome, Login, Senha, Email, Perfil: String; Key: Word);
published
property AuthType : TAlSmtpClientAuthType read fAuthType write fAuthType;
property ServidorSMTP: String read FSMTPServer write FSMTPServer;
property Usuario: String read FUsuario write FUsuario;
property Senha: String read FSenha write FSenha;
property Porta: Integer read FPorta write FPorta default 0;
property NomeRemetente: String read FNomeRemetente write FNomeRemetente;
property EmailRemetente: String read FEmailRemetente write FEmailRemetente;
property AdicionaUsuario: TUCMailMessage read FAdicionaUsuario write FAdicionaUsuario;
property AlteraUsuario: TUCMailMessage read FAlteraUsuario write FAlteraUsuario;
property EsqueceuSenha: TUCMEsqueceuSenha read FEsqueceuSenha write FEsqueceuSenha;
property SenhaForcada: TUCMailMessage read FSenhaForcada write FSenhaForcada;
property SenhaTrocada: TUCMailMessage read FSenhaTrocada write FSenhaTrocada;
end;
implementation
uses
UCBase,
UCEMailForm_U;
{ TMailAdicUsuario }
procedure TUCMailMessage.Assign(Source: TPersistent);
begin
if Source is TUCMailMessage then
begin
Self.Ativo := TUCMailMessage(Source).Ativo;
Self.Titulo := TUCMailMessage(Source).Titulo;
Self.Mensagem.Assign(TUCMailMessage(Source).Mensagem);
end
else
inherited;
end;
constructor TUCMailMessage.Create(AOwner: TComponent);
begin
FLines := TStringList.Create;
end;
destructor TUCMailMessage.Destroy;
begin
SysUtils.FreeAndNil(FLines);
inherited;
end;
procedure TUCMailMessage.SetLines(const Value: TStrings);
begin
FLines.Assign(Value);
end;
{ TMailUserControl }
constructor TMailUserControl.Create(AOwner: TComponent);
begin
inherited;
AdicionaUsuario := TUCMailMessage.Create(self);
AdicionaUsuario.FLines.Add('Inclusão de usuário');
AdicionaUsuario.FLines.Add('');
AdicionaUsuario.fLines.Add('Nome...: :nome');
AdicionaUsuario.fLines.Add('Login..: :login');
AdicionaUsuario.fLines.Add('Senha..: :senha');
AdicionaUsuario.fLines.Add('Email..: :email');
AdicionaUsuario.fLines.Add('Perfil.: :perfil');
AdicionaUsuario.fTitulo := 'Inclusão de usuário';
AlteraUsuario := TUCMailMessage.Create(self);
AlteraUsuario.FLines.Add('Alteração de usuário');
AlteraUsuario.FLines.Add('');
AlteraUsuario.fLines.Add('Nome...: :nome');
AlteraUsuario.fLines.Add('Login..: :login');
AlteraUsuario.fLines.Add('Senha..: :senha');
AlteraUsuario.fLines.Add('Email..: :email');
AlteraUsuario.fLines.Add('Perfil.: :perfil');
AlteraUsuario.fTitulo := 'Alteração de usuário';
EsqueceuSenha := TUCMEsqueceuSenha.Create(self);
EsqueceuSenha.FLines.Add('Esquecia a senha');
EsqueceuSenha.FLines.Add('');
EsqueceuSenha.fLines.Add('Nome...: :nome');
EsqueceuSenha.fLines.Add('Login..: :login');
EsqueceuSenha.fLines.Add('Senha..: :senha');
EsqueceuSenha.fLines.Add('Email..: :email');
EsqueceuSenha.fLines.Add('Perfil.: :perfil');
EsqueceuSenha.fTitulo := 'Lembrete de senha';
SenhaForcada := TUCMailMessage.Create(self);
SenhaForcada.FLines.Add('Troca de senha forçada');
SenhaForcada.FLines.Add('');
SenhaForcada.fLines.Add('Nome...: :nome');
SenhaForcada.fLines.Add('Login..: :login');
SenhaForcada.fLines.Add('Senha..: :senha');
SenhaForcada.fLines.Add('Email..: :email');
SenhaForcada.fLines.Add('Perfil.: :perfil');
SenhaForcada.fTitulo := 'Troca de senha forçada';
SenhaTrocada := TUCMailMessage.Create(self);
SenhaTrocada.FLines.Add('Alteração de senha');
SenhaTrocada.FLines.Add('');
SenhaTrocada.fLines.Add('Nome...: :nome');
SenhaTrocada.fLines.Add('Login..: :login');
SenhaTrocada.fLines.Add('Senha..: :senha');
SenhaTrocada.fLines.Add('Email..: :email');
SenhaTrocada.fLines.Add('Perfil.: :perfil');
SenhaTrocada.fTitulo := 'Alteração de senha';
fAuthType := alsmtpClientAuthPlain;
if csDesigning in ComponentState then
begin
Porta := 25;
AdicionaUsuario.Ativo := True;
AlteraUsuario.Ativo := True;
EsqueceuSenha.Ativo := True;
SenhaForcada.Ativo := True;
SenhaTrocada.Ativo := True;
EsqueceuSenha.LabelLoginForm := RetornaLingua( ucPortuguesBr, 'Const_Log_LbEsqueciSenha');
EsqueceuSenha.MensagemEmailEnviado := RetornaLingua( ucPortuguesBr,'Const_Log_MsgMailSend');
end;
end;
destructor TMailUserControl.Destroy;
begin
SysUtils.FreeAndNil(FAdicionaUsuario);
SysUtils.FreeAndNil(FAlteraUsuario);
SysUtils.FreeAndNil(FEsqueceuSenha);
SysUtils.FreeAndNil(FSenhaForcada);
SysUtils.FreeAndNil(FSenhaTrocada);
inherited;
end;
procedure TMailUserControl.EnviaEmailAdicionaUsuario(Nome, Login, Senha, Email, Perfil: String; Key: Word);
begin
Senha := TrataSenha(Senha, Key);
EnviaEmailTP(Nome, Login, Senha, Email, Perfil, AdicionaUsuario);
end;
procedure TMailUserControl.EnviaEmailAlteraUsuario(Nome, Login, Senha, Email, Perfil: String; Key: Word);
begin
Senha := TrataSenha(Senha, Key);
EnviaEmailTP(Nome, Login, Senha, Email, Perfil, AlteraUsuario);
end;
procedure TMailUserControl.EnviaEmailSenhaForcada(Nome, Login, Senha, Email, Perfil: String);
begin
EnviaEmailTP(Nome, Login, Senha, Email, Perfil, SenhaForcada);
end;
procedure TMailUserControl.EnviaEmailSenhaTrocada(Nome, Login, Senha, Email, Perfil: String; Key: Word);
begin
EnviaEmailTP(Nome, Login, Senha, Email, Perfil, SenhaTrocada);
end;
function TMailUserControl.ParseMailMSG(Nome, Login, Senha, Email, Perfil, txt: String): String;
begin
Txt := StringReplace(txt, ':nome', nome, [rfReplaceAll]);
Txt := StringReplace(txt, ':login', login, [rfReplaceAll]);
Txt := StringReplace(txt, ':senha', senha, [rfReplaceAll]);
Txt := StringReplace(txt, ':email', email, [rfReplaceAll]);
Txt := StringReplace(txt, ':perfil', perfil, [rfReplaceAll]);
Result := Txt;
end;
procedure TMailUserControl.onStatus( Status : String );
begin
if not Assigned(UCEMailForm) then Exit;
UCEMailForm.lbStatus.Caption := Status;
UCEMailForm.Update;
end;
procedure TMailUserControl.EnviaEmailTp(Nome, Login, USenha, Email, Perfil: String; UCMSG: TUCMailMessage);
var
MailMsg : TAlSmtpClient;
MailRecipients : TStringlist;
MailHeader : TALSMTPClientHeader;
begin
if Trim(Email) = '' then
Exit;
MailMsg := TAlSmtpClient.Create;
MailMsg.OnStatus := OnStatus;
MailRecipients := TStringlist.Create;
MailHeader := TALSMTPClientHeader.Create;
MailHeader.From := EmailRemetente; //'rodrigo@oxio.com.br';
MailHeader.SendTo := Email ;
MailRecipients.Append(Email);
MailHeader.Subject := UCMSG.Titulo;
try
try
UCEMailForm := TUCEMailForm.Create(Self);
UCEMailForm.lbStatus.Caption := '';
UCEMailForm.Show;
UCEMailForm.Update;
MailMsg.SendMail(ServidorSMTP, FPorta, NomeRemetente ,
MailRecipients, Usuario, Senha, fAuthType , MailHeader.RawHeaderText,
ParseMailMSG(Nome, Login, USenha, Email, Perfil, UCMSG.Mensagem.Text));
UCEMailForm.Update;
except
on e: Exception do
begin
Beep;
UCEMailForm.Close;
MessageDlg(E.Message,mtWarning,[mbok],0);
raise;
end;
end;
finally
FreeAndNil(MailMsg);
FreeAndNil(MailHeader);
FreeAndNil(MailRecipients);
FreeAndNil(UCEMailForm);
end;
end;
procedure TMailUserControl.EnviaEsqueceuSenha(Nome, Login, Senha, Email, Perfil: String; Key: Word);
begin
if Trim(Email) = '' then
Exit;
try
Senha := TrataSenha(Senha, Key);
EnviaEmailTP(Nome, Login, Senha, Email, Perfil, EsqueceuSenha);
MessageDlg(EsqueceuSenha.MensagemEmailEnviado, mtInformation, [mbOK], 0);
except
end;
end;
function TmailUserControl.TrataSenha(Senha: String; Key: Word): String;
begin
Result := Decrypt(Senha, Key);
end;
end.
|
unit MsTaskUtils;
interface
uses
Windows, WinSvc, SysUtils;
//+--------------------------------------------------------------------------
//
// Function: StartScheduler
//
// Synopsis: Start the task scheduler service if it isn't already running.
//
// Returns: ERROR_SUCCESS or a Win32 error code.
//
// Notes: This function works for either Win9x or Windows NT.
// If the service is running but paused, does nothing.
//
//---------------------------------------------------------------------------
function StartScheduler(): DWORD;
implementation
function StartScheduler(): DWORD;
const
SCHED_CLASS = 'SAGEWINDOWCLASS';
SCHED_TITLE = 'SYSTEM AGENT COM WINDOW';
SCHED_SERVICE_APP_NAME = 'mstask.exe';
SCHED_SERVICE_NAME = 'Schedule';
MAX_PATH: DWORD = 256;
var
StartupInfo: TStartupInfo;
ProcessInformation: TProcessInformation;
szApp: PChar;
pszPath: PChar;
hsc: SC_HANDLE;
hSchSvc: SC_HANDLE;
SvcStatus: TServiceStatus;
ServiceArgVectors: PChar;
begin
// Determine what version of OS we are running on.
if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then
begin
// Start the Win95 version of TaskScheduler.
if FindWindow(SCHED_CLASS, SCHED_TITLE) <> 0 then
// It is already running.
Result := ERROR_SUCCESS
else
begin
//
// Execute the task scheduler process.
//
FillChar(StartupInfo, sizeof(StartupInfo), 0);
StartupInfo.cb := sizeof(TStartupInfo);
GetMem(szApp, MAX_PATH);
try
if SearchPath(nil, SCHED_SERVICE_APP_NAME, nil, MAX_PATH,
szApp, pszPath) = 0 then
Result := GetLastError
else
begin
if not CreateProcess(szApp, nil, nil, nil, False,
CREATE_NEW_CONSOLE or CREATE_NEW_PROCESS_GROUP, nil, nil,
StartupInfo, ProcessInformation) then
Result := GetLastError
else
begin
CloseHandle(ProcessInformation.hProcess);
CloseHandle(ProcessInformation.hThread);
Result := ERROR_SUCCESS;
end;
end;
finally
FreeMem(szApp);
end;
end;
end
else
begin
// If not Win95 then start the NT version as a TaskScheduler service.
hsc := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
if hsc = 0 then
Result := GetLastError
else
begin
hSchSvc := OpenService(hsc, SCHED_SERVICE_NAME,
SERVICE_START or SERVICE_QUERY_STATUS);
CloseServiceHandle(hsc);
if hSchSvc = 0 then
Result := GetLastError
else
begin
if not QueryServiceStatus(hSchSvc, SvcStatus) then
begin
CloseServiceHandle(hSchSvc);
Result := GetLastError;
end
else
begin
if SvcStatus.dwCurrentState = SERVICE_RUNNING then
begin
// The service is already running.
CloseServiceHandle(hSchSvc);
Result := ERROR_SUCCESS;
end
else
begin
ServiceArgVectors := nil;
if not StartService(hSchSvc, 0, ServiceArgVectors) then
begin
CloseServiceHandle(hSchSvc);
Result := GetLastError();
end
else
begin
CloseServiceHandle(hSchSvc);
Result := ERROR_SUCCESS;
end;
end;
end;
end;
end;
end;
end;
end.
|
{: Verlet cloth simulation and verlet constraints controlled by an
actor's skeleton.<p>
Verlet physics is used to simulate a cloth-like effect on a mesh.
In this demo, the cape mesh is linked to the verlet world and the
verlet nodes control the surface of the mesh. Verlet constraints
define boundaries that the verlet nodes cannot enter.<p>
The skeleton colliders define the verlet constraints for the actor
using simple spheres and capsules (sphere-capped cylinders). The
constraints get updated each frame to match the actor's current
skeleton frame. Using simple primitives to approximate a mesh is
much quicker than determining mesh volume -> verlet interactions.<p>
A dynamic octree is used here to give a little performace boost to
the verlet testing.
}
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,
GLScene, GLVectorFileObjects, GLObjects, GLCadencer, GLTexture, GLLCLViewer,
GLFileSMD, GLFile3DS, GLVerletClothify, GLVerletSkeletonColliders,
GLShadowVolume,
OpenGLTokens, GLVectorGeometry, GLGeometryBB, GLVerletTypes,
GLSpacePartition, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses,
GLRenderContextInfo, GLState;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLActor1: TGLActor;
ActorDummy: TGLDummyCube;
Timer1: TTimer;
OctreeRenderer: TGLDirectOpenGL;
CheckBox_ShowOctree: TCheckBox;
GLLightSource1: TGLLightSource;
GLPlane1: TGLPlane;
GLShadowVolume1: TGLShadowVolume;
Cape: TGLActor;
GLLightSource2: TGLLightSource;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
procedure Timer1Timer(Sender: TObject);
procedure OctreeRendererRender(Sender: TObject; var rci: TRenderContextInfo);
private
{ Private declarations }
public
{ Public declarations }
mx, my: integer;
VerletWorld: TVerletWorld;
EdgeDetector: TEdgeDetector;
AirResistance: TVFAirResistance;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
FileUtil, GLContext;
// Mesh normal recalculation routines
procedure PrepareMeshForNormalsRecalc(BaseMesh: TGLBaseMesh);
var
i, j, k: integer;
mo: TMeshObject;
fg: TFGVertexNormalTexIndexList;
begin
// update normals
// (not very efficient, could use some work...)
for i := 0 to BaseMesh.MeshObjects.Count - 1 do
begin
mo := BaseMesh.MeshObjects[i];
for j := 0 to mo.FaceGroups.Count - 1 do
begin
if mo.FaceGroups[j] is TFGVertexNormalTexIndexList then
begin
fg := TFGVertexNormalTexIndexList(mo.FaceGroups[j]);
for k := 0 to fg.VertexIndices.Count - 1 do
begin
fg.NormalIndices.List[k] := fg.VertexIndices.List[k];
end;
end;
end;
end;
BaseMesh.StructureChanged;
end;
procedure RecalcMeshNormals(BaseMesh: TGLBaseMesh);
var
i, j, k: integer;
mo: TMeshObject;
fg: TFGVertexIndexList;
n: TAffineVector;
begin
// update normals
// (not very efficient, could use some work...)
for i := 0 to BaseMesh.MeshObjects.Count - 1 do
begin
mo := BaseMesh.MeshObjects[i];
FillChar(mo.Normals.List[0], SizeOf(TAffineVector) * mo.Normals.Count, 0);
for j := 0 to mo.FaceGroups.Count - 1 do
begin
if mo.FaceGroups[j] is TFGVertexIndexList then
begin
fg := TFGVertexIndexList(mo.FaceGroups[j]);
k := 0;
while k <= fg.VertexIndices.Count - 3 do
begin
n := CalcPlaneNormal(mo.Vertices.List[fg.VertexIndices.List[k]],
mo.Vertices.List[fg.VertexIndices.List[k + 1]],
mo.Vertices.List[fg.VertexIndices.List[k + 2]]);
mo.Normals.TranslateItem(fg.VertexIndices.List[k], n);
mo.Normals.TranslateItem(fg.VertexIndices.List[k + 1], n);
mo.Normals.TranslateItem(fg.VertexIndices.List[k + 2], n);//}
Inc(k, 3);
end;
end;
end;
mo.Normals.Normalize;
end;
BaseMesh.StructureChanged;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
path: UTF8String;
p: integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p + 5, Length(path));
path := IncludeTrailingPathDelimiter(path) + 'media';
SetCurrentDirUTF8(path);
Randomize;
// Load the actor and animations
GLActor1.LoadFromFile('trinityRAGE.smd');
GLActor1.AddDataFromFile('walk.smd');
GLActor1.Animations[1].MakeSkeletalTranslationStatic;
GLActor1.SwitchToAnimation('walk');
GLActor1.BuildSilhouetteConnectivityData;
// Load the cape
Cape.LoadFromFile('cape.3ds');
Cape.Position.Y := GLActor1.BoundingSphereRadius - 10;
PrepareMeshForNormalsRecalc(Cape);
Cape.BuildSilhouetteConnectivityData;
// Set up the floor texture and reposition to below the actors feet
with GLPlane1.Material.Texture do
begin
Image.LoadFromFile('beigemarble.jpg');
Disabled := False;
end;
GLPlane1.Position.Y := -GLActor1.BoundingSphereRadius;
// Setting up the verlet world using the optional dynamic octree can
// give good perfamnce increases.
VerletWorld := TVerletWorld.Create;
VerletWorld.CreateOctree(
AffineVectorMake(0, 0, 0),
AffineVectorMake(0, 0, 0), 10, 6);
VerletWorld.UpdateSpacePartion := uspEveryFrame;
VerletWorld.Iterations := 3;
// 'Clothify' the cape and add it to the verlet world
EdgeDetector := TEdgeDetector.Create(Cape);
EdgeDetector.ProcessMesh;
EdgeDetector.AddEdgesAsSticks(VerletWorld, 0.15);
EdgeDetector.AddEdgesAsSolidEdges(VerletWorld);
//EdgeDetector.AddOuterEdgesAsSolidEdges(VerletWorld);
// Set up verlet gravity and add the floor as a constraint
with TVFGravity.Create(VerletWorld) do
Gravity := AffineVectorMake(0, -98.1, 0);
with TVCFloor.Create(VerletWorld) do
begin
Normal := GLPlane1.Direction.AsAffineVector;
Location := VectorAdd(GLPlane1.Position.AsAffineVector,
VectorScale(GLPlane1.Direction.AsAffineVector, 0.1));
end;
// Load the skeleton colliders. Skeleton colliders define an
// approximate collision boundary for actors and are controlled
// by the actor's skeleton.
with GLActor1.Skeleton.Colliders do
begin
LoadFromFile('trinityRAGE.glsc');
AlignColliders;
end;
// Add the collider's verlet constraints to the verlet world
AddSCVerletConstriantsToVerletWorld(GLActor1.Skeleton.Colliders, VerletWorld);
{AirResistance := TVFAirResistance.Create(VerletWorld);
AirResistance.DragCoeff := 0.001;
AirResistance.WindDirection := AffineVectorMake(0,0,1);
AirResistance.WindMagnitude := 15;
AirResistance.WindChaos := 2;//}
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
VerletWorld.Free;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
// Step the verlet world (this is where the magic happens)
VerletWorld.Progress(deltaTime, newTime);
// Recalculate the cape's normals
RecalcMeshNormals(Cape);
// Cycle the floor texture to make it look like it's moving
GLPlane1.YOffset := GLPlane1.YOffset - 0.25 * deltaTime;
if GLPlane1.YOffset < 0 then
GLPlane1.YOffset := GLPlane1.YOffset + 1;
// Orbit the light (to show off the pretty shadow volumes)
GLLightSource1.MoveObjectAround(GLActor1, 0, -deltaTime * 20);
GLLightSource1.PointTo(GLActor1, YHMGVector);
end;
procedure TForm1.OctreeRendererRender(Sender: TObject; var rci: TRenderContextInfo);
procedure RenderAABB(AABB: TAABB; w, r, g, b: single);
begin
GL.Color3f(r, g, b);
rci.GLStates.LineWidth := w;
GL.Begin_(GL_LINE_STRIP);
GL.Vertex3f(AABB.min[0], AABB.min[1], AABB.min[2]);
GL.Vertex3f(AABB.min[0], AABB.max[1], AABB.min[2]);
GL.Vertex3f(AABB.max[0], AABB.max[1], AABB.min[2]);
GL.Vertex3f(AABB.max[0], AABB.min[1], AABB.min[2]);
GL.Vertex3f(AABB.min[0], AABB.min[1], AABB.min[2]);
GL.Vertex3f(AABB.min[0], AABB.min[1], AABB.max[2]);
GL.Vertex3f(AABB.min[0], AABB.max[1], AABB.max[2]);
GL.Vertex3f(AABB.max[0], AABB.max[1], AABB.max[2]);
GL.Vertex3f(AABB.max[0], AABB.min[1], AABB.max[2]);
GL.Vertex3f(AABB.min[0], AABB.min[1], AABB.max[2]);
GL.End_;
GL.Begin_(GL_LINES);
GL.Vertex3f(AABB.min[0], AABB.max[1], AABB.min[2]);
GL.Vertex3f(AABB.min[0], AABB.max[1], AABB.max[2]);
GL.Vertex3f(AABB.max[0], AABB.max[1], AABB.min[2]);
GL.Vertex3f(AABB.max[0], AABB.max[1], AABB.max[2]);
GL.Vertex3f(AABB.max[0], AABB.min[1], AABB.min[2]);
GL.Vertex3f(AABB.max[0], AABB.min[1], AABB.max[2]);
GL.End_;
end;
procedure RenderOctreeNode(Node: TSectorNode);
var
i: integer;
AABB: TAABB;
begin
if Node.NoChildren then
begin
AABB := Node.AABB;
if Node.RecursiveLeafCount > 0 then
RenderAABB(AABB, 1, 0, 0, 0)
else
RenderAABB(AABB, 1, 0.8, 0.8, 0.8);//}
end
else
begin
for i := 0 to Node.ChildCount - 1 do
RenderOctreeNode(Node.Children[i]);
end;
end;
begin
if CheckBox_ShowOctree.Checked then
begin
if VerletWorld.SpacePartition is TOctreeSpacePartition then
begin
rci.GLStates.Disable(stLighting);
rci.GLStates.Disable(stBlend);
rci.GLStates.Disable(stLineStipple);
rci.GLStates.Disable(stColorMaterial);
RenderOctreeNode(TOctreeSpacePartition(VerletWorld.SpacePartition).RootNode);
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption := Format('%2.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mx := x;
my := y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - y, mx - x);
mx := x;
my := y;
end;
end.
|
unit Nullpobug.MarubatsuTest;
interface
uses
Nullpobug.UnitTest
, Nullpobug.Marubatsu
;
type
TGameTableTest = class(TTestCase)
private
FGameTable: TGameTable;
published
procedure SetUp; override;
procedure TearDown; override;
procedure TestCellIsEmpty;
procedure TestUpdateCell;
end;
TGameTableIsFilledRowTest = class(TTestCase)
private
FGameTable: TGameTable;
published
procedure SetUp; override;
procedure TearDown; override;
procedure Test;
end;
TGameTableIsFilledColTest = class(TTestCase)
private
FGameTable: TGameTable;
published
procedure SetUp; override;
procedure TearDown; override;
procedure Test;
end;
TGameTableIsFilledDiagonalTest = class(TTestCase)
private
FGameTable: TGameTable;
published
procedure SetUp; override;
procedure TearDown; override;
procedure Test;
end;
TGameTest = class(TTestCase)
private
FGame: TGame;
published
procedure SetUp; override;
procedure TearDown; override;
procedure TestStartWithPlayer;
procedure TestStartWithCPU;
end;
TGamePutTest = class(TTestCase)
private
FGame: TGame;
published
procedure SetUp; override;
procedure TearDown; override;
procedure TestPutPlayer;
procedure TestPutCPU;
procedure TestInvalid;
end;
TPlayerTypeToCellStateTest = class(TTestCase)
published
procedure Test;
end;
TPlayerTypeToWinnerTest = class(TTestCase)
published
procedure Test;
end;
implementation
(* TGameTableTest *)
procedure TGameTableTest.SetUp;
begin
FGameTable := TGameTable.Create;
end;
procedure TGameTableTest.TearDown;
begin
FGameTable.Free;
end;
procedure TGameTableTest.TestCellIsEmpty;
(* すべてのセルが空の値になること *)
var
X, Y: Integer;
begin
for X := 0 to 2 do
for Y := 0 to 2 do
AssertTrue(FGameTable[X, Y] = csEmpty);
end;
procedure TGameTableTest.TestUpdateCell;
(* セルの更新ができること *)
begin
AssertTrue(FGameTable[0, 0] = csEmpty);
FGameTable[0, 0] := csPlayer;
AssertTrue(FGameTable[0, 0] = csPlayer);
end;
(* end of TGameTableTest *)
(* TGameTableIsFilledRowTest *)
procedure TGameTableIsFilledRowTest.SetUp;
begin
FGameTable := TGameTable.Create;
FGameTable[0, 0] := csPlayer;
FGameTable[0, 1] := csPlayer;
FGameTable[0, 2] := csPlayer;
end;
procedure TGameTableIsFilledRowTest.TearDown;
begin
FGameTable.Free;
end;
procedure TGameTableIsFilledRowTest.Test;
begin
// 0行だけ埋まっている
AssertTrue(FGameTable.IsFilledRow(0, csPlayer));
AssertFalse(FGameTable.IsFilledRow(1, csPlayer));
AssertFalse(FGameTable.IsFilledRow(2, csPlayer));
AssertFalse(FGameTable.IsFilledRow(0, csEmpty));
AssertTrue(FGameTable.IsFilledRow(1, csEmpty));
AssertTrue(FGameTable.IsFilledRow(2, csEmpty));
end;
(* end of TGameTableIsFilledRowTest *)
(* TGameTableIsFilledColTest *)
procedure TGameTableIsFilledColTest.SetUp;
begin
FGameTable := TGameTable.Create;
FGameTable[0, 0] := csPlayer;
FGameTable[1, 0] := csPlayer;
FGameTable[2, 0] := csPlayer;
end;
procedure TGameTableIsFilledColTest.TearDown;
begin
FGameTable.Free;
end;
procedure TGameTableIsFilledColTest.Test;
begin
// 0行だけ埋まっている
AssertTrue(FGameTable.IsFilledCol(0, csPlayer));
AssertFalse(FGameTable.IsFilledCol(1, csPlayer));
AssertFalse(FGameTable.IsFilledCol(2, csPlayer));
AssertFalse(FGameTable.IsFilledCol(0, csEmpty));
AssertTrue(FGameTable.IsFilledCol(1, csEmpty));
AssertTrue(FGameTable.IsFilledCol(2, csEmpty));
end;
(* end of TGameTableIsFilledColTest *)
(* TGameTableIsFilledDiagonalTest *)
procedure TGameTableIsFilledDiagonalTest.SetUp;
begin
FGameTable := TGameTable.Create;
FGameTable[0, 0] := csPlayer;
FGameTable[1, 1] := csPlayer;
FGameTable[2, 2] := csPlayer;
FGameTable[0, 2] := csPlayer;
FGameTable[2, 0] := csPlayer;
end;
procedure TGameTableIsFilledDiagonalTest.TearDown;
begin
FGameTable.Free;
end;
procedure TGameTableIsFilledDiagonalTest.Test;
begin
// \と/が埋まっている
AssertTrue(FGameTable.IsFilledDiagonal(dtBackSlash, csPlayer));
AssertTrue(FGameTable.IsFilledDiagonal(dtSlash, csPlayer));
AssertFalse(FGameTable.IsFilledDiagonal(dtBackSlash, csCPU));
AssertFalse(FGameTable.IsFilledDiagonal(dtSlash, csCPU));
end;
(* end of TGameTableIsFilledDiagonalTest *)
(* TGameTest *)
procedure TGameTest.SetUp;
begin
FGame := TGame.Create;
end;
procedure TGameTest.TearDown;
begin
FGame.Free;
end;
procedure TGameTest.TestStartWithPlayer;
(* プレイヤーを指定して開始(プレイヤー) *)
begin
FGame.Start(gptPlayer);
AssertTrue(FGame.State = gsPlayerTurn);
end;
procedure TGameTest.TestStartWithCPU;
(* プレイヤーを指定して開始(CPU) *)
begin
FGame.Start(gptCPU);
AssertTrue(FGame.State = gsCPUTurn);
end;
(* end of TGameTest *)
(* TGamePutTest *)
procedure TGamePutTest.SetUp;
begin
FGame := TGame.Create;
FGame.Table[0, 1] := csPlayer;
end;
procedure TGamePutTest.TearDown;
begin
FGame.Free;
end;
procedure TGamePutTest.TestPutPlayer;
(* TGame.PutメソッドでPlayerが値を置けること *)
begin
FGame.Put(0, 0, gptPlayer);
AssertTrue(FGame.Table[0, 0] = csPlayer);
end;
procedure TGamePutTest.TestPutCPU;
(* TGame.PutメソッドでCPUが値を置けること *)
begin
FGame.Put(0, 0, gptCPU);
AssertTrue(FGame.Table[0, 0] = csCPU);
end;
procedure TGamePutTest.TestInvalid;
(* TGame.Putメソッドで既に値が入っていると置けない *)
begin
AssertRaises(
EAleadyFilled,
procedure begin
FGame.Put(0, 1, gptPlayer);
end
);
end;
(* end of TGamePutTest *)
(* TPlayerTypeToCellStateTest *)
procedure TPlayerTypeToCellStateTest.Test;
begin
AssertTrue(PlayerTypeToCellState(gptPlayer) = csPlayer);
AssertTrue(PlayerTypeToCellState(gptCPU) = csCPU);
end;
(* end of TPlayerTypeToCellStateTest *)
(* TPlayerTypeToWinnerTest *)
procedure TPlayerTypeToWinnerTest.Test;
begin
AssertTrue(PlayerTypeToWinner(gptPlayer) = gwPlayer);
AssertTrue(PlayerTypeToWinner(gptCPU) = gwCPU);
end;
(* end of TPlayerTypeToWinnerTest *)
initialization
RegisterTest(TGameTableTest);
RegisterTest(TGameTableIsFilledRowTest);
RegisterTest(TGameTableIsFilledColTest);
RegisterTest(TGameTableIsFilledDiagonalTest);
RegisterTest(TGameTest);
RegisterTest(TGamePutTest);
RegisterTest(TPlayerTypeToCellStateTest);
RegisterTest(TPlayerTypeToWinnerTest);
end.
|
unit uUpdatingWindowsActions;
interface
uses
uActions,
uShellUtils;
const
InstallPoints_SystemInfo = 1024 * 1024;
type
TInstallUpdatingWindows = class(TInstallAction)
function CalculateTotalPoints : Int64; override;
procedure Execute(Callback : TActionCallback); override;
end;
implementation
{ TInstallUpdatingWindows }
function TInstallUpdatingWindows.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_SystemInfo;
end;
procedure TInstallUpdatingWindows.Execute(Callback: TActionCallback);
var
Terminate : Boolean;
begin
RefreshSystemIconCache;
Callback(Self, InstallPoints_SystemInfo, InstallPoints_SystemInfo, Terminate);
end;
end.
|
unit Common.Barcode.ITF14;
interface
uses
Common.Barcode,
Common.Barcode.IBarcode,
Common.Barcode.Drawer;
type
TITF14 = class(TBarcodeCustom)
protected const
Patterns: array of string = ['00110', '10001', '01001', '11000', '00101', '10100', '01100', '00011', '10010', '01010'];
PatternStart = '1010';
PatternStop = '1101';
PatternSpace = '000000000000000000000000000000';
protected
function GetLength: integer; override;
function GetType: TBarcodeType; override;
procedure ValidateRawData(const Value: string); override;
procedure ValidateRawAddon(const Value: string); override;
function GetCRC(const ARawData: string): integer; override;
procedure Encode; override;
procedure EncodeCenter(var AEncodeData: string; const ARawData: string);
end;
implementation
uses
System.SysUtils,
System.StrUtils;
resourcestring
StrExceptionLength = '%s: Length must be %d or %d digits';
StrExceptionNumbers = '%s: Must contain only numbers';
StrExceptionCRC = '%s: CRC Error';
{ TITF14 }
procedure TITF14.Encode;
begin
FEncodeData := PatternSpace;
FEncodeData := FEncodeData + PatternStart;
EncodeCenter(FEncodeData, FRawData);
FEncodeData := FEncodeData + PatternStop;
FEncodeData := FEncodeData + PatternSpace;
end;
procedure TITF14.EncodeCenter(var AEncodeData: string; const ARawData: string);
var
I: integer;
Sequences, Sequence, Sequence1, Sequence2: string;
k: Integer;
LRawData: string;
begin
LRawData := ARawData;
//Если нет контрольной суммы - добавляем
if ARawData.Length = (GetLength-1) then
LRawData := LRawData + GetCRC(ARawData).ToString;
I := 1;
while I <= LRawData.Length do begin
Sequence1 := Patterns[string(LRawData[I]).ToInteger];
Sequence2 := Patterns[string(LRawData[I+1]).ToInteger];
Sequence := string.Empty;
for k := 1 to 5 do begin
if Sequence1[k] = '0'
then Sequence := Sequence + '1'
else Sequence := Sequence + '11';
if Sequence2[k] = '0'
then Sequence := Sequence + '0'
else Sequence := Sequence + '00';
end;
Sequences := Sequences + Sequence;
Inc(I, 2);
end;
AEncodeData := AEncodeData + Sequences;
end;
function TITF14.GetCRC(const ARawData: string): integer;
var
Value: TArray<Char>;
Even: integer;
Odd: integer;
I: Integer;
begin
if ARawData.Length = GetLength
then Value := ReverseString(ARawData).Substring(1).ToCharArray
else Value := ReverseString(ARawData).ToCharArray;
Even := 0;
Odd := 0;
for I := 0 to Length(Value)-1 do
if ((I+1) mod 2) = 0 then
inc(Even, int32.Parse(string(Value[I])))
else
inc(Odd, int32.Parse(string(Value[I])));
result := (10-((3 * Odd + Even) mod 10)) mod 10;
end;
function TITF14.GetLength: integer;
begin
result := 14;
end;
function TITF14.GetType: TBarcodeType;
begin
result := TBarcodeType.ITF14;
end;
procedure TITF14.ValidateRawAddon(const Value: string);
begin
inherited;
end;
procedure TITF14.ValidateRawData(const Value: string);
var
Duck: int64;
BarLength: integer;
BarType: TBarcodeType;
begin
BarLength := GetLength;
BarType := GetType;
if (Value.Length < BarLength - 1) or (Value.Length > BarLength) then
raise EArgumentException.Create(format(StrExceptionLength, [BarType.ToString, BarLength-1, BarLength]));
if not TryStrToInt64(Value, Duck) then
raise EArgumentException.Create(format(StrExceptionNumbers, [BarType.ToString]));
if Value.Length = BarLength then
if not CheckCRC(Value) then
raise EArgumentException.Create(format(StrExceptionCRC, [BarType.ToString]));
end;
initialization
TBarcode.RegisterBarcode(TBarcodeType.ITF14, TITF14);
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_JS_SCANNER.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_JS_SCANNER;
interface
uses {$I uses.def}
SysUtils,
PAXCOMP_CONSTANTS,
PAXCOMP_SYS,
PAXCOMP_SCANNER;
type
TJavaScriptScanner = class(TBaseScanner)
private
procedure ScanCustDir;
procedure ScanOctalLiteral;
procedure ScanHexLiteral;
function GetNextSpecialChar: Char;
public
procedure ScanStringLiteral(ch: Char); override;
procedure ReadCustomToken; override;
end;
implementation
uses
PAXCOMP_KERNEL;
procedure TJavaScriptScanner.ReadCustomToken;
var
c: Char;
begin
repeat
GetNextChar;
c := LA(0);
Token.Position := Position;
if IsWhiteSpace(c) then
continue
else if c = #13 then
ScanSeparator
{$IFDEF MACOS}
else if c = #10 then
ScanSeparator
{$ENDIF}
{$IFDEF LINUX}
else if c = #10 then
ScanSeparator
{$ENDIF}
{$IFDEF ANDROID}
else if c = #10 then
ScanSeparator
{$ENDIF}
else if IsEOF(c) then
ScanSpecial
else if IsEOF(c) then
ScanSpecial
else if IsEOF then
ScanEOF
else if IsAlpha(c) or (c = '$') then
begin
while IsAlpha(LA(1)) or IsDigit(LA(1)) or (LA(1) = '$') do
GetNextChar;
Token.TokenClass := tcIdentifier;
SetScannerState(scanProg);
token.Length := Position - token.Position + 1;
if StrEql(Token.Text, 'in') then
ScanSpecial;
end
else if c = CHAR_DOUBLE_AP then
begin
ScanStringLiteral(CHAR_DOUBLE_AP);
Token.TokenClass := tcPCharConst;
end
else if c = CHAR_AP then
begin
ScanStringLiteral(CHAR_AP);
Token.TokenClass := tcPCharConst;
end
else if IsDigit(c) then
begin
if (c = '0') and (LA(1) = 'x') then
begin
GetNextChar;
ScanHexLiteral;
end
else
ScanNumberLiteral;
end
else if c = '{' then
ScanSpecial
else if c = '}' then
ScanSpecial
else if c = '(' then
ScanSpecial
else if c = ')' then
ScanSpecial
else if c = '[' then
ScanSpecial
else if c = ']' then
ScanSpecial
else if c = '.' then
ScanSpecial
else if c = ';' then
ScanSpecial
else if c = ',' then
ScanSpecial
else if c = '<' then
begin
ScanSpecial;
if LA(1) = '<' then
begin
GetNextChar;
if LA(1) = '=' then
GetNextChar;
end
else if LA(1) = '=' then
GetNextChar;
end
else if c = '>' then
begin
ScanSpecial;
if LA(1) = '>' then
begin
GetNextChar;
if LA(1) = '>' then
begin
GetNextChar;
if LA(1) = '=' then
GetNextChar;
end
else if LA(1) = '=' then
GetNextChar;
end
else if LA(1) = '=' then
GetNextChar;
end
else if c = '=' then
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
if LA(1) = '=' then
GetNextChar;
end;
end
else if c = '!' then
begin
ScanSpecial;
if LA(1) = '=' then
begin
GetNextChar;
if LA(1) = '=' then
GetNextChar;
end
end
else if c = '+' then
begin
ScanSpecial;
if LA(1) = '+' then
GetNextChar
else if LA(1) = '=' then
GetNextChar;
end
else if c = '-' then
begin
ScanSpecial;
if LA(1) = '-' then
GetNextChar
else if LA(1) = '=' then
GetNextChar;
end
else if c = '*' then
begin
ScanSpecial;
if LA(1) = '=' then
GetNextChar;
end
else if c = '%' then
begin
ScanSpecial;
if LA(1) = '=' then
GetNextChar;
end
else if c = '|' then
begin
ScanSpecial;
if LA(1) = '|' then
GetNextChar
else if LA(1) = '=' then
GetNextChar;
end
else if c = '^' then
begin
ScanSpecial;
if LA(1) = '=' then
GetNextChar;
end
else if c = '~' then
begin
ScanSpecial;
if LA(1) = '=' then
GetNextChar;
end
else if c = '&' then
begin
ScanSpecial;
if LA(1) = '&' then
GetNextChar
else if LA(1) = '=' then
GetNextChar;
end
else if c = '?' then
ScanSpecial
else if c = ':' then
ScanSpecial
else if c = '@' then
begin
if LA(1) = '@' then
begin
GetNextChar;
ScanCustDir;
Token.TokenClass := tcNone;
continue;
end
else
ScanSpecial;
end
else if c = '/' then
begin
if LA(1) = '/' then
begin
ScanSingleLineComment();
continue;
end
else if LA(1) = '*' then
begin
BeginComment(1);
repeat
GetNextChar;
if IsEOF then
break;
c := LA(0);
if ByteInSet(c, [10,13]) then
begin
Inc(LineCount);
GenSeparator;
if c = #13 then
GetNextChar;
end;
if LA(1) = '*' then
begin
if Position + 1 >= BuffLength then
break
else if LA(2) = '/' then
begin
GetNextChar;
GetNextChar;
break;
end
end;
until false;
EndComment(2);
end
else
ScanSpecial;
end
else
RaiseError(errSyntaxError, []);
until Token.TokenClass <> tcNone;
end;
procedure TJavaScriptScanner.ScanCustDir;
label
NextComment, Fin;
const
IdsSet = paxcomp_constants.IdsSet + [Ord('\'), Ord('/'), Ord('"')];
Start1 = '@';
var
S: String;
DirName: String;
ok: Boolean;
begin
DirName := '';
S := '';
repeat
GetNextChar;
if ByteInSet(LA(0), [10,13]) then
begin
Inc(LineCount);
GenSeparator;
if LA(0) = #13 then
GetNextChar;
end
else
S := S + LA(0);
until not ByteInSet(LA(0), IdsSet);
ScanChars(IdsSet + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'),
Ord(','), Ord('\'), Ord('/'), Ord('"'), Ord(' '), Ord(':')]);
DirName := s + Token.Text;
with TKernel(kernel) do
if Assigned(OnUnknownDirective) then
begin
ok := true;
OnUnknownDirective(Owner, DirName, ok);
if not ok then
Self.RaiseError(errInvalidCompilerDirective, [DirName]);
end;
ScanChars(WhiteSpaces);
GenSeparator;
end;
procedure TJavaScriptScanner.ScanOctalLiteral;
var
c: Char;
V: array[1..30] of Integer;
L, P: Integer;
begin
L := 0;
while IsDigit(LA(1)) do
begin
c := GetNextChar;
if ByteInSet(c, [8,9]) then
RaiseError(errSyntaxError, []);
Inc(L);
V[L] := ord(c) - ord('0');
end;
CustomInt64Val := 0;
if L > 0 then
begin
CustomInt64Val := V[L];
P := 1;
while L > 1 do
begin
Dec(L);
P := P * 8;
CustomInt64Val := CustomInt64Val + P * V[L];
end;
end;
Token.TokenClass := tcIntegerConst;
Token.Tag := 2;
SetScannerState(scanProg);
end;
procedure TJavaScriptScanner.ScanHexLiteral;
var
c: Char;
V: array[1..30] of Integer;
L, P: Integer;
begin
GetNextChar;
L := 0;
while IsHexDigit(LA(1)) do
begin
c := GetNextChar;
Inc(L);
if IsDigit(c) then
V[L] := ord(c) - ord('0')
else
V[L] := ord(c) - ord('A') + 10
end;
CustomInt64Val := 0;
if L > 0 then
begin
CustomInt64Val := V[L];
P := 1;
while L > 1 do
begin
Dec(L);
P := P * 16;
CustomInt64Val := CustomInt64Val + P * V[L];
end;
end;
Token.TokenClass := tcIntegerConst;
Token.Tag := 2;
SetScannerState(scanProg);
end;
function TJavaScriptScanner.GetNextSpecialChar: Char;
var
c: Char;
begin
c := LA(1);
if ByteInSet(c, [Ord('u'),Ord('U')]) then
ScanHexLiteral
else if ByteInSet(c, [Ord('0')..Ord('7')]) then
ScanOctalLiteral
else if ByteInSet(c, [Ord(CHAR_AP), Ord(CHAR_DOUBLE_AP), Ord('\')]) then
begin
CustomInt64Val := Ord(c);
GetNextChar;
end
else if c = 'r' then
begin
CustomInt64Val := 13;
GetNextChar;
end
else if c = 'n' then
begin
CustomInt64Val := 10;
GetNextChar;
end
else if c = 't' then
begin
CustomInt64Val := 9;
GetNextChar;
end
else if c = 'f' then
begin
CustomInt64Val := 12;
GetNextChar;
end
else if c = 'b' then
begin
CustomInt64Val := 8;
GetNextChar;
end;
result := Char(CustomInt64Val);
end;
procedure TJavaScriptScanner.ScanStringLiteral(ch: Char);
var
c: Char;
begin
CustomStringVal := '';
c := #0;
repeat
if LA(1) = '\' then
begin
GetNextChar;
CustomStringVal := CustomStringVal + GetNextSpecialChar;
continue;
end
else
c := GetNextChar;
if IsEOF then
begin
RaiseError(errUnterminatedString, []);
Exit;
end;
if c = ch then
begin
break;
end
else
CustomStringVal := CustomStringVal + c
until false;
Token.TokenClass := tcPCharConst;
Token.Tag := 2;
SetScannerState(scanProg);
end;
end.
|
unit Biotools;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Math, Graphics, Dialogs, Forms; // librerias cargadas
type
TPunto = record
X,Y,Z: real;
end;
TPuntos = array of TPunto; // array con un conjunto de puntos
TAtomPDB = record // con los átomos
NumAtom: integer;
ID: string;
Residuo: string;
Subunidad: char;
NumRes: integer;
coor: TPunto;
AltLoc: char;
Temp: real;
end;
TResiduoPDB = record // con los residuos
phi,psi: real;
NumRes: integer;
subunidad: char;
ID3: string;
ID1: char;
Atm1, AtmN: integer;
N, CA, C, O: integer;
end;
TsubunidadPDB = record // con las subunidades
ID: char;
Atm1, AtmN, res1, resN: integer;
AtomCount, ResCount: integer;
ResIndex: array of integer;
end;
TPDB = record // la proteína
header: string;
atm: array of TAtomPDB;
res: array of TResiduoPDB;
sub: array of TsubunidadPDB;
NumFichas, NumResiduos, NumSubunidades : integer;
subs, secuencia : string;
AtomIndex: array of integer;
end;
TTablaDatos = array of array of real;
TEscala = array ['A'..'Z'] of real;
const
AA = '***ALA=A#ARG=R#ASN=N#ASP=D'
+ '#CYS=C#GLN=Q#GLU=E#GLY=G#HIS=H'
+ '#ILE=I#LEU=L#LYS=K#MET=M#PHE=F'
+ '#PRO=P#SER=S#THR=T#TRP=W#TYR=Y'
+ '#VAL=V';
// para el cambio de código de 3 letras a 1 y viceversa
function distancia (x1,y1,z1,x2,y2,z2:real): real; // hay que publicar las funciones
function distancia(punto1,punto2:TPunto): real; overload;
function cargarPDB (var p: TPDB): string;
function cargarPDB (texto: Tstrings): TPDB; overload;
function sumaV (A,B: TPunto): TPunto;
function diferenciaV (A,B: TPunto): TPunto;
function moduloV( A: TPunto): real;
function escalarV(k:real; V: TPunto) : TPunto;
function prodEscalar(A, B: TPunto): real;
function angulo (A, B: Tpunto): real;
function angulo(A, B, C: TPunto):real; overload;
function torsion ( A, B, C, D: TPunto): real;
function prodVectorial(p1,p2: TPunto): Tpunto;
function AA3TO1 (aa3: string): char;
function giroOX(rad: real; v: TPunto): TPunto;
function giroOX(rad: real; puntos: TPuntos): TPuntos; overload;
function giroOY(rad: real; v: TPunto): TPunto;
function giroOY(rad: real; puntos: TPuntos): TPuntos; overload;
function giroOZ(rad: real; v: TPunto): TPunto;
function giroOZ(rad: real; puntos: TPuntos): TPuntos; overload;
function traslacion(dx, dy, dz: real; v: TPunto): TPunto;
function traslacion(dx, dy, dz: real; puntos: TPuntos): TPuntos; overload;
function plotXY(datos: TTablaDatos; im: TCanvas; OX: integer = 0; OY: integer =1;
borrar: boolean = false; linea: boolean =false; clpluma: TColor= clyellow;
clRelleno: TColor= clyellow; clFondo: TColor= clblack; radio: integer= 3;
borde: integer= 40; marcafin: boolean= false; clfin: TColor= clred): boolean;
function CargarEscala( var escala: TEscala): string;
function alinear_ejeZ(puntos:TPuntos):TPuntos ;
function Ind_Der(long_max, long: integer; var cadena: string): string;
function Ind_Izq(long_max, long: integer; var cadena: string): string;
function writePDB(atm: TAtomPDB): string;
implementation // tras esto se definen las funciones
function CargarEscala( var escala: TEscala): string;
var
texto: TStrings;
dial: TOpenDialog;
j: integer;
linea: string;
residuo: char;
begin
texto:= TStringList.create;
dial:= TOPenDialog.create(application);
if dial.execute then
begin
texto.loadfromfile(dial.FileName);
result:= dial.Filename;
for j:=0 to texto.count-1 do
begin
linea:= trim(texto[j]);
residuo:= linea[1]; // posición 1 de la línea
delete(linea,1,1); // borra en línea desde 1 con ancho de 1, es decir, solo el primero
escala[residuo]:= strtofloat(trim(linea));
end;
end else result:='';
dial.free; // libera la memoria, es decir, destruye el objeto
texto.free;
end;
function alinear_ejeZ(puntos: Tpuntos): Tpuntos;
var
salida: TPuntos;
a, b, c, d1, d2, alfa, fi, senofi, senoalfa: real;
p1, p2: TPunto;
begin
setlength(salida, high(puntos)+1);
p1:= puntos [0];
salida:= traslacion(-p1.X, -p1.Y, -p1.Z, puntos);
p2:= salida[high(salida)];
a:= p2.X; b:= p2.Y; c:= p2.Z;
d1:= sqrt(sqr(b)+sqr(c));
d2:= sqrt(sqr(a)+sqr(b)+sqr(c));
senofi:= b/d1;
senoalfa:= a/d2;
fi:= arcsin(senofi);
alfa:= arcsin(senoalfa);
if c<0 then fi:= -fi else alfa:= -alfa; //esto recoge los cambios de signos de todos los cuadrantes
salida:= GiroOX(fi, salida);
salida:= GiroOY(alfa, salida);
result:= salida;
end;
function giroOX(rad: real; v: TPunto): TPunto; // preguntar por los signos
var
seno, coseno: real;
begin
seno:= sin(rad);
coseno:= cos(rad);
GiroOX.X:= v.X;
GiroOX.Y:= v.Y*coseno - v.Z*seno;
GiroOX.Z:= v.Y*seno + v.Z*coseno;
end;
function giroOX(rad: real; puntos: TPuntos): TPuntos; overload; // hecho
var
seno, coseno:real;
salida:TPuntos;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
setlength(salida, high(puntos)+1);
for j:=0 to high(puntos) do
begin
salida[j].X:= puntos[j].X;
salida[j].Y:= puntos[j].Y*coseno - puntos[j].Z*seno;
salida[j].Z:= puntos[j].Y*seno + puntos[j].Z*coseno;
end;
result:= salida;
end;
procedure giroOX (rad: real; var p:TPDB) overload; // hecho
var
seno, coseno:real;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
for j:= 1 to p.NumFichas do
begin
p.atm[j].coor.X:= p.atm[j].coor.X;
p.atm[j].coor.Y:= p.atm[j].coor.Y*coseno - p.atm[j].coor.Z*seno;
p.atm[j].coor.Z:= p.atm[j].coor.Y*seno + p.atm[j].coor.Z*coseno;
end;
end;
function giroOY(rad: real; v: TPunto): TPunto;
var
seno, coseno: real;
begin
seno:= sin(rad);
coseno:= cos(rad);
GiroOY.X:= v.X*coseno + v.Z*seno;
GiroOY.Y:= v.Y;
GiroOY.Z:= -v.X*seno + v.Z*coseno;
end;
function giroOY(rad: real; puntos: TPuntos): TPuntos; overload;
var
seno, coseno:real;
salida:TPuntos;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
setlength(salida, high(puntos)+1);
for j:=0 to high(puntos) do
begin
salida[j].X:= puntos[j].X*coseno + puntos[j].Z*seno;
salida[j].Y:= puntos[j].Y;
salida[j].Z:= -puntos[j].X*seno + puntos[j].Z*coseno;
end;
result:= salida;
end;
procedure giroOY (rad: real; var p:TPDB) overload;
var
seno, coseno:real;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
for j:= 1 to p.NumFichas do
begin
p.atm[j].coor.X:= p.atm[j].coor.X*coseno + p.atm[j].coor.Z*seno;
p.atm[j].coor.Y:= p.atm[j].coor.Y;
p.atm[j].coor.Z:= -p.atm[j].coor.X*seno +p.atm[j].coor.Z*coseno;
end;
end;
function giroOZ(rad: real; v: TPunto): TPunto;
var
seno, coseno: real;
begin
seno:= sin(rad);
coseno:= cos(rad);
GiroOZ.X:= v.X*coseno - v.Y*seno;
GiroOZ.Y:= v.X*seno + v.Y*coseno;
GiroOZ.Z:= v.Z;
end;
function giroOZ(rad: real; puntos: TPuntos): TPuntos; overload;//hay que hacerlo
var
seno, coseno:real;
salida:TPuntos;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
setlength(salida, high(puntos)+1);
for j:=0 to high(puntos) do
begin
salida[j].X:= puntos[j].X*coseno - puntos[j].Y*seno;
salida[j].Y:= puntos[j].X*seno + puntos[j].Y*coseno;
salida[j].Z:= puntos[j].Z;
end;
result:= salida;
end;
procedure giroOZ (rad: real; var p:TPDB) overload; //también hay que hacerlo
var
seno, coseno:real;
j:integer;
begin
seno:= sin(rad);
coseno:= cos(rad);
for j:= 1 to p.NumFichas do
begin
p.atm[j].coor.X:= p.atm[j].coor.X*coseno - p.atm[j].coor.Y*seno;
p.atm[j].coor.Y:= p.atm[j].coor.X*seno + p.atm[j].coor.Y*coseno;
p.atm[j].coor.Z:= p.atm[j].coor.Z;
end;
end;
function traslacion(dx, dy, dz: real; v: TPunto): TPunto; // traslaciones
begin
traslacion.X:= v.X + dx;
traslacion.Y:= v.Y + dy;
traslacion.Z:= v.Z + dz;
end;
function traslacion(dx, dy, dz: real; puntos: TPuntos): TPuntos; overload;
var
salida: TPuntos;
j: integer;
begin
setlength(salida, high(puntos)+1);
for j:=0 to high(puntos) do
begin
salida[j].X:=puntos[j].X + dx;
salida[j].Y:=puntos[j].Y + dy;
salida[j].Z:=puntos[j].Z + dz;
end;
result:= salida;
end;
procedure traslacion(dx, dy, dz: real; var p: TPDB); overload;
var
j: integer;
begin
for j:= 1 to p.NumFichas do
begin
p.atm[j].coor.X:= p.atm[j].coor.X + dx;
p.atm[j].coor.Y:= p.atm[j].coor.Y + dy;
p.atm[j].coor.Z:= p.atm[j].coor.Z + dz;
end;
end;
function plotXY(datos: TTablaDatos; im: TCanvas; OX: integer = 0; OY: integer =1;
borrar: boolean = false; linea: boolean =false; clpluma: TColor= clyellow;
clRelleno: TColor= clyellow; clFondo: TColor= clblack; radio: integer= 3;
borde: integer= 40; marcafin: boolean= false; clfin: TColor= clred): boolean;
var
xmin, xmax, ymin, ymax, rangox, rangoy: real;
ancho, alto,Xp, Yp, j: integer;
OK: boolean;
function Xpixel (x:real): integer ;
begin
result:= round(((ancho-2*borde)*(x-xmin)/rangoX)+borde);
end;
function Ypixel (y:real):integer;
begin
result:= round(alto-(((alto-2*borde)*(y-ymin)/rangoY)+borde));
end;
begin
OK:= true;
xmin:= minvalue(datos[OX]);
xmax:= maxvalue(datos[OX]);
ymin:= minvalue(datos[OY]);
ymax:= maxvalue(datos[OY]);
rangox:= xmax-xmin;
rangoy:= ymax-ymin;
ancho:= im.width;
alto:= im.height;
if (rangox=0) or (rangoy=0) then OK:= false;
if borrar then
begin
im.brush.color:= clFondo;
im.clear;
end;
if OK then
begin
im.Pen.Color:= clpluma;
im.brush.color:= clrelleno;
Xp:= xpixel(datos[OX,0]);
Yp:= ypixel(datos[OY,0]);
im.MoveTo (Xp, Yp);
for j:=0 to high(datos[0]) do
begin
Xp:= xpixel(datos[OX,j]);
Yp:= ypixel(datos[OY,j]);
im.ellipse(Xp-radio, Yp-radio, Xp+radio, Yp+radio);
if linea then im.lineto(Xp,Yp);
end;
if marcafin then
begin
im.pen.Color:= clfin;
im.brush.color:=clfin;
im.ellipse(Xp-radio-2, Yp-radio-2, Xp+radio+2, Yp+radio+2);
end;
end;
result:= OK;
end;
function AA3TO1(aa3: string):char;
begin
result:= AA[pos(aa3,AA)+4];
end;
function AA1TO3 (aa1:char):string ; // comprobar que sea válida
begin
result:= copy(AA, pos(AA1, AA)-4, 2);
end;
function sumaV (A,B: TPunto): TPunto;
var
V: TPunto;
begin
V.X:= A.X + B.X;
V.Y:= A.Y + B.Y;
V.Z:= A.Z + B.Z;
result:=V;
end;
function diferenciaV (A,B: TPunto): TPunto;
var
V: TPunto;
begin
V.X:= A.X - B.X;
V.Y:= A.Y - B.Y;
V.Z:= A.Z - B.Z;
result:=V;
end;
function moduloV( A: TPunto): real;
begin
result:=sqrt(sqr(A.X)+sqr(A.Y)+sqr(A.Z));
end;
function escalarV(k:real; V: TPunto) :TPunto;
begin
result.X:= k*V.X;
result.Y:= k*V.Y;
result.Z:= k*V.Z;
end;
function prodEscalar(A, B: TPunto): real;
begin
result:= A.X*B.X + A.Y*B.Y + A.Z*B.Z;
end;
function angulo (A, B: Tpunto): real;
var
denominador: real;
begin
denominador:= moduloV(A)*moduloV(B);
if denominador > 0
then result:= arccos(prodEscalar(A,B)/denominador)
else result:= maxfloat;
end;
function angulo(A, B, C: TPunto):real; overload;
var
BA,BC: TPunto;
begin
BA:= diferenciaV( A,B);
BC:= diferenciaV(C,B);
result:= angulo( BA, BC);
end;
function prodVectorial(p1,p2: TPunto): Tpunto;
var
V:TPunto;
begin
V.X:=p1.Y*p2.Z - p1.Z*p2.Y;
V.Y:=P1.Z*P2.X - P1.X*P2.Z;
V.Z:=p1.X*p2.Y - p1.Y*p2.X;
result:= V;
end;
function torsion ( A, B, C, D: TPunto): real;
var
BA, BC, CB, CD, V1, V2, P: TPunto;
diedro, diedro_IUPAC, denominador, cosenoGamma: real;
begin
diedro_IUPAC:=0;
BA:= diferenciaV(A, B);
BC:= diferenciaV(C, B);
CB:= diferenciaV(B, C);
CD:= diferenciaV(D, C);
V1:= prodVectorial(BC, BA);
V2:= prodVectorial(CD, CB);
diedro:= angulo(V1, V2);
P:= prodVectorial(V2, V1);
denominador:= moduloV(P)* moduloV(CB);
if denominador >0 then
begin
cosenoGamma:= prodEscalar(P, CB)/ denominador;
if cosenoGamma >0 then cosenoGamma:=1 else cosenoGamma:=-1;
end else diedro_IUPAC:= maxfloat;
if diedro_IUPAC < maxfloat then diedro_IUPAC:= diedro*cosenoGamma;
result:=diedro_IUPAC;
end;
function distancia (x1,y1,z1,x2,y2,z2:real): real;
begin
result:=sqrt(sqr(x1-x2) + sqr(y1-y2) + sqr(z1-z2));
end;
function distancia(punto1,punto2:TPunto): real; overload;
begin
result:= sqrt(sqr( punto1.X - punto2.X) + sqr(punto1.Y - punto2.Y) + sqr(punto1.Z - punto2.Z));
end;
function cargarPDB (var p: TPDB): string;
var
dialogo: TOpenDialog;
textoPDB: TStrings;
begin
dialogo:= TOpenDialog.create(application);
textoPDB:= TStringlist.create;
if dialogo.execute then
begin
textoPDB.loadfromfile(dialogo.filename);
p:=cargarPDB(textoPDB);
result:= dialogo.filename;
end else result:= '';
dialogo.free;
textoPDB.free;
end;
function writePDB(atm: TAtomPDB): string;
var
n: integer;
pdb: TStrings;
linea, atom, res, coorX, coorY, coorZ, temp: String;
s: string;
begin
atom:= inttostr(atm.Numatom);
res := inttostr(atm.NumRes);
coorX := formatfloat('0.000', atm.coor.X);
coorY := formatfloat('0.000', atm.coor.Y);
coorZ := formatfloat('0.000', atm.coor.Z);
temp := formatfloat('0.00', atm.Temp);
linea:= 'ATOM'+ ' ' + ind_der(5,atom.Length,atom) + ' ' + ind_izq(3,atm.ID.length, atm.ID) +
' ' + atm.Residuo + ' ' + atm.subunidad + ' ' + ind_der(3,res.length,res) +
' ' + ind_der(7, coorX.Length, coorX)+ ' ' + ind_der(7, coorY.length, coorY) + ' ' +
ind_der(7, coorZ.Length, coorZ) + ' 1.00 ' + ind_der(5, temp.length, temp);
result:= linea; // funciones Ind para evitar hacerlo todo manualmente
end;
function Ind_Der(long_max, long: integer; var cadena: string): string;
var
n:integer;
espacio: string;
begin
espacio:=' ';
if long_max > long then
for n:=1 to long_max-long do insert(espacio,cadena,n); // inserta un espacio por cada uno que falte
result:= cadena;
end;
function Ind_Izq(long_max, long: integer; var cadena: string): string;
var
n:integer;
espacio: string;
begin
espacio:=' ';
if long_max > long then
for n:=1 to long_max-long do
begin
cadena:= cadena+espacio; // igual pero por el final
end;
result:= cadena;
end;
function CargarPDB(texto: TStrings): TPDB; overload;
var
p: TPDB; //proteína , El TPDB de salida de la función
linea: string;
j, k, F, R, S: integer;//contador de ficha, residuo, subunidad
resno: integer;
begin
p.secuencia:='';
F:=0; R:=0; S:=0; //para asegurarse de que el contador es 0 al inicio
setlength(p.atm, texto.count); // como no tenemos suficiente info todavía, establecemos el máximo posible,
//que sería el número de líneas total del memo(texto). Estimamos por alto
setlength(p.res, texto.count);
setlength(p.sub, texto.count);
for j:=0 to texto.count-1 do
begin
linea:= texto[j];
if (copy(linea,1,6)='ATOM ')then
begin
F:= F+1;//No podemos usar j como contador de átomos ya que cuando llegue a ATOM, valdrá mucho,
//necesitamos un contador de fichas a parte
//Atomos
p.atm[F].NumAtom :=strtoint(trim(copy(linea,7,5)));
p.atm[F].ID:= trim(copy(linea, 13, 4));
p.atm[F].Residuo:= copy(linea, 18,3); //Aquí no hace falta trim porque siempre son los 3 caracteres
p.atm[F].Subunidad:=linea[22]; //Introduce el caracter 22 del string linea, aunque puede que no tengamos subunidades.
p.atm[F].NumRes:= strtoint(trim(copy(linea,23,4)));
p.atm[F].coor.X:= strtofloat(trim(copy(linea,31,8)));
p.atm[F].coor.Y:= strtofloat(trim(copy(linea,39,8)));
p.atm[F].coor.Z:= strtofloat(trim(copy(linea,47,8)));
p.atm[F].AltLoc:=linea[17];
p.atm[F].Temp:= strtofloat(trim(copy(linea, 61,6)));
//Residuo
if p.atm[F].ID = 'N' then
begin
R:= R+1;
p.res[R].Atm1:= F;
p.res[R].ID3:=p.atm[F].Residuo;
p.res[R].ID1:=AA3to1(p.res[R].ID3);
p.res[R].N:= F;
p.res[R].NumRes:= p.atm[F].NumRes;
p.res[R].Subunidad:= p.atm[F].Subunidad;
p.secuencia:= p.secuencia + p.res[R].ID1;
//Subunidad
if pos(p.atm[F].Subunidad, p.subs)=0 then //Si es cabeza de subunidad (la letra no estaba en subs), se inicia.
begin
S:= S+1;
p.subs:= p.subs + p.atm[F].Subunidad;
p.sub[S].ID:=p.atm[F].Subunidad;
p.sub[S].atm1:=F;
p.sub[S].res1:=R;
end;
end;
if p.atm[F].ID='CA' then p.res[R].CA:= F;
if p.atm[F].ID='C' then p.res[R].C:= F;
if p.atm[F].ID='O' then p.res[R].O:= F;
p.res[R].AtmN:= F; //Se va a ir cambiando en cada bucle, pero cuando termine se quedará con la del número del último átomo que se lea dentro del R en cuestión
p.sub[S].atmN:= F;
p.sub[S].resN:= R; //Pasa lo mismo pero con la subunidad
end;
end;
setlength(p.atm, F+1); //Debido a que es una matriz dinamica, hay que dimensionarla.
setlength(p.res, R+1);
setlength(p.sub, S+1);
p.NumFichas:= F;
p.NumResiduos:= R;
p.NumSubunidades:= S;
setlength(p.atomindex, p.atm[p.NumFichas].NumAtom + 1); //Dimensionamos el vector.
//Es NumAtom porque buscamos el último número de átomos que tenemos. Suponiendo que no hay huecos, coincidiría con la numeración.
//Como el 0 lo ignoramos siempre, pues tenemos que sumar 1 pa las dimensiones.
//Hay que ir asignando el subíndice con el numatom y rellenar con el numero de ficha:
for j:=1 to p.NumFichas do p.atomindex[p.atm[j].NumAtom]:= j; //Elegimos el elemento NumaTOM DEL ELEMENTO J-ÉSIMO DE MI PROTEÍNA.
//y lo asignamos al subíndice de nuestra ficha.
for j:=1 to p.NumSubunidades do with p.sub[j] do //Para no tener que ponerlo todo el rato (peligroso)
begin
AtomCount:= atmN - atm1 + 1;
ResCount:= resN - res1 + 1;
for k:=p.sub[j].res1 + 1 to p.sub[j].resn - 1 do //Así eliminamos los extremos
begin
p.res[k].phi:=torsion(p.atm[p.res[k-1].C].coor,
p.atm[p.res[k].N].coor,
p.atm[p.res[k].CA].coor,
p.atm[p.res[k].C].coor); //Llamada a la función de torsión. //Se usa el p.atm porque buscamos la información
//del átomo que tiene ese número de residuo, para abrir la ficha y así acceder a las coordenadas.
p.res[k].psi:=torsion(p.atm[p.res[k].N].coor,
p.atm[p.res[k].CA].coor,
p.atm[p.res[k].C].coor, //El orden es muy importante.
p.atm[p.res[k+1].N].coor);
end;
setlength(p.sub[j].resindex, p.NumResiduos + 1); //Estamos recorriendo las subunidades de j.
for k:=1 to p.sub[j].ResCount do
begin
resno:= p.sub[j].res1 + k - 1; //resno es j, nuestra numeración en mi fichero. Restamos 1 porque las matrices abiertas acaban en n-1.
p.sub[j].resindex[p.res[resno].numres]:= resno; //Numres no es mio, es de PDB.
end;
end;
result:=p;
end;
end.
|
{ ******************************************************* }
{ *
{* uTVDBMatcher.pas
{* Delphi Implementation of the Class TVDBMatcher
{* Generated by Enterprise Architect
{* Created on: 09-févr.-2015 11:44:25
{* Original author: Labelleg
{*
{******************************************************* }
unit xmltvdb.TVDBMatcher;
interface
uses System.Generics.Collections, Xml.XMLIntf, xmltvdb.TVDBEpisode,
xmltvdb.Episode, uTVDBBind;
type
ITVDBMatcher = interface
['{E0A2B7C3-9639-4560-BD4F-DB2310308894}']
function GetcontainsTitleMatches: TVDBEpisodeColl;
function GetexactTitleMatches: TVDBEpisodeColl;
function GetfuzzyTitleMatches: TVDBEpisodeColl;
function GetoriginalAirDateMatches: TVDBEpisodeColl;
end;
TTVDBMatcher = class(TInterfacedObject, ITVDBMatcher)
strict private
FcontainsTitleMatches: TVDBEpisodeColl;
FexactTitleMatches: TVDBEpisodeColl;
FfuzzyTitleMatches: TVDBEpisodeColl;
ForiginalAirDateMatches: TVDBEpisodeColl;
public
function GetcontainsTitleMatches: TVDBEpisodeColl;
function GetexactTitleMatches: TVDBEpisodeColl;
function GetfuzzyTitleMatches: TVDBEpisodeColl;
function GetoriginalAirDateMatches: TVDBEpisodeColl;
constructor Create(guideEpisode: IEpisode; tvdbEpisodes: IXMLTVDBEpisodeTypeList); overload;
constructor Create; overload;
destructor Destroy; override;
end;
TGracenoteMatcher = class(TInterfacedObject) // , ITVDBMatcher)
strict private
// FcontainsTitleMatches: TVDBEpisodeColl;
// FexactTitleMatches: TVDBEpisodeColl;
// FfuzzyTitleMatches: TVDBEpisodeColl;
// ForiginalAirDateMatches: TVDBEpisodeColl;
Falreadymatched: ITVDBMatcher;
public
// function GetcontainsTitleMatches: TVDBEpisodeColl;
// function GetexactTitleMatches: TVDBEpisodeColl;
// function GetfuzzyTitleMatches: TVDBEpisodeColl;
// function GetoriginalAirDateMatches: TVDBEpisodeColl;
constructor Create(guideEpisode: IEpisode; var alreadymatched: ITVDBMatcher); overload;
// constructor Create; overload;
destructor Destroy; override;
end;
implementation
uses Rest.Utils, System.Math, System.SysUtils, xmltvdb.tvdb, uDataModule,
System.JSON, CodeSiteLogging, xmltv.Gracenote;
{ implementation of TVDBMatcher }
constructor TTVDBMatcher.Create(guideEpisode: IEpisode; tvdbEpisodes: IXMLTVDBEpisodeTypeList);
var
guideTitle: string;
hasTitle: Boolean;
epFirstAired: string;
hasOriginalAirDate: Boolean;
tvdbEp: IXMLTVDBEpisodeType;
tvdbTitle: string;
tvdbFirstAired: string;
tvdbSeasonNumber: string;
tvdbEpisodeNumber: string;
hasTVDBImage: Boolean;
i: Integer;
TVDBEpisode: ITVDBEpisode;
contains: Boolean;
containsNormalized: Boolean;
begin
FcontainsTitleMatches := TVDBEpisodeColl.Create;
FexactTitleMatches := TVDBEpisodeColl.Create;
FfuzzyTitleMatches := TVDBEpisodeColl.Create;
ForiginalAirDateMatches := TVDBEpisodeColl.Create;
{
* exact title & original airdate (check for multipart?)
* fuzzy title & original air date (check for multipart)
* contains title & original air date (check for multipart)
* exact title (must be a solo match)
* original airdate (must be a solo match)
* fuzzy title (must be a solo match)
* contains title (must be a solo match)
}
// episode info
guideTitle := guideEpisode.getTitle();
hasTitle := guideEpisode.hasTitle();
epFirstAired := iif(guideEpisode.hasOriginalAirDate(),
TTVGeneral.dateToTVDBString(guideEpisode.getOriginalAirDate()), '');
// String epFirstAired := guideEpisode.hasOriginalAirDate() ? dateToTVDBString(guideEpisode.getOriginalAirDate()) : null;
hasOriginalAirDate := (epFirstAired <> '');
if (not hasTitle and not hasOriginalAirDate) then
exit; // return;//nothing to do!
for i := 0 to tvdbEpisodes.Count - 1 do
begin
tvdbEp := tvdbEpisodes[i];
tvdbTitle := tvdbEp.EpisodeName; // .getChildText(' EpisodeName ');
tvdbFirstAired := tvdbEp.FirstAired; // getChildText(' FirstAired ');
tvdbSeasonNumber := tvdbEp.SeasonNumber; // getChildText(' SeasonNumber ');
tvdbEpisodeNumber := tvdbEp.EpisodeNumber; // getChildText(' EpisodeNumber ');
hasTVDBImage := (tvdbEp.Filename <> ''); // getChildText(' filename '));
// <filename> stores the path to the .jpg image for the episode
// final TVDBEpisode TVDBEpisode := new TVDBEpisode(tvdbTitle, tvdbFirstAired, tvdbSeasonNumber, tvdbEpisodeNumber, hasTVDBImage);
TVDBEpisode := TTVDBEpisode.Create(tvdbTitle, tvdbFirstAired, tvdbSeasonNumber, tvdbEpisodeNumber, hasTVDBImage);
if (hasTitle and (tvdbTitle <> '')) then
begin
// exact title matches (alwasy case-insensitive and special chars removed (normalized))
if SameText(TTVGeneral.normalize(guideTitle), TTVGeneral.normalize(tvdbTitle)) then
begin
GetexactTitleMatches.add(TVDBEpisode);
end
else // not exact title match, check for fuzzy and contains
begin
if (TTVGeneral.fuzzyTitleMatch(guideTitle, tvdbTitle, 15)) then
// allow 15 percent discrepency)
GetfuzzyTitleMatches.add(TVDBEpisode);
// check for contains (the program guide title contains the tvdb title)
contains := guideTitle.ToLower.contains(tvdbTitle.ToLower);
containsNormalized := TTVGeneral.normalize(guideTitle)
.ToLower.contains(TTVGeneral.normalize(tvdbTitle).ToLower);
if (contains or containsNormalized) then
GetcontainsTitleMatches.add(TVDBEpisode);
end;
end;
if (hasOriginalAirDate) then
begin
if SameText(epFirstAired, tvdbFirstAired) then
GetoriginalAirDateMatches.add(TVDBEpisode);
end;
end;
end;
constructor TTVDBMatcher.Create;
begin
inherited Create;
FcontainsTitleMatches := TVDBEpisodeColl.Create;
FexactTitleMatches := TVDBEpisodeColl.Create;
FfuzzyTitleMatches := TVDBEpisodeColl.Create;
ForiginalAirDateMatches := TVDBEpisodeColl.Create;
end;
destructor TTVDBMatcher.Destroy;
begin
FcontainsTitleMatches.free;
FexactTitleMatches.free;
FfuzzyTitleMatches.free;
ForiginalAirDateMatches.free;
inherited Destroy;
end;
function TTVDBMatcher.GetcontainsTitleMatches: TVDBEpisodeColl;
begin
REsult := FcontainsTitleMatches;
end;
function TTVDBMatcher.GetexactTitleMatches: TVDBEpisodeColl;
begin
REsult := FexactTitleMatches;
end;
function TTVDBMatcher.GetfuzzyTitleMatches: TVDBEpisodeColl;
begin
REsult := FfuzzyTitleMatches;
end;
function TTVDBMatcher.GetoriginalAirDateMatches: TVDBEpisodeColl;
begin
REsult := ForiginalAirDateMatches;
end;
constructor TGracenoteMatcher.Create(guideEpisode: IEpisode; var alreadymatched: ITVDBMatcher);
var
// JSONText: string;
// LJsonArr: TJSONArray;
// LJsonValue: TJsonValue;
// title: string;
// tmsId: string;
// rootId: string;
// seriesId: string;
// longDescription: string;
// tvdbID: string;
// programelem: TJsonValue;
// entityType: string;
Zap2itid: string;
// episodeTitle: string;
// episodeNum: string;
// seasonNum: string;
// LJPair: TJSONPair;
// LItem: TJsonValue;
guideTitle: string;
hasTitle: Boolean;
epFirstAired: string;
hasOriginalAirDate: Boolean;
EpisodeFound: Boolean;
TVDBEpisode: ITVDBEpisode;
origAirDate: string;
contains: Boolean;
containsNormalized: Boolean;
ep: ITVDBEpisode;
leprog: TGracenoteProgram;
title: string;
episodeTitle: string;
episodeNum: string;
seasonNum: string;
// qq: string;
begin
Falreadymatched := alreadymatched;
// episode info
guideTitle := guideEpisode.getTitle();
hasTitle := guideEpisode.hasTitle();
epFirstAired := iif(guideEpisode.hasOriginalAirDate(),
TTVGeneral.dateToTVDBString(guideEpisode.getOriginalAirDate()), '');
hasOriginalAirDate := (epFirstAired <> '');
if (not hasTitle and not hasOriginalAirDate) then
exit; // nothing to do!
EpisodeFound := False;
Zap2itid := guideEpisode.GetOriginalms_progid;
if hasOriginalAirDate and not Zap2itid.IsEmpty then
begin
if not Zap2itid.IsEmpty then
begin
Zap2itid := Zap2itid.Split(['.'])[1];
EpisodeFound := False;
if not Zap2itid.IsEmpty then
begin
if TGracenote.Coll.GetByTmsID(Zap2itid, leprog) then
begin
title := leprog.title; // ', title);
episodeTitle := leprog.SerieEpisodeData.episodeTitle;
episodeNum := leprog.SerieEpisodeData.episodeNum;
seasonNum := leprog.SerieEpisodeData.seasonNum;
origAirDate := leprog.origAirDate;
EpisodeFound := true;
end;
if not EpisodeFound then begin
if TGracenote.Coll.GetByNameAndDate(guideEpisode.getSeries.GetseriesName, TTVGeneral.dateToTVDBString(guideEpisode.getOriginalAirDate), leprog) then
begin
title := leprog.title; // ', title);
episodeTitle := leprog.SerieEpisodeData.episodeTitle;
episodeNum := leprog.SerieEpisodeData.episodeNum;
seasonNum := leprog.SerieEpisodeData.seasonNum;
origAirDate := leprog.origAirDate;
EpisodeFound := true;
end;
end;
end;
end;
end;
if EpisodeFound then
begin
// final TVDBEpisode TVDBEpisode := new TVDBEpisode(tvdbTitle, tvdbFirstAired, tvdbSeasonNumber, tvdbEpisodeNumber, hasTVDBImage);
TVDBEpisode := TTVDBEpisode.Create(episodeTitle, origAirDate, seasonNum, episodeNum, False);
if (hasTitle and (episodeTitle <> '')) then
begin
// exact title matches (alwasy case-insensitive and special chars removed (normalized))
if SameText(TTVGeneral.normalize(guideTitle), TTVGeneral.normalize(episodeTitle)) then
begin
Falreadymatched.GetexactTitleMatches.add(TVDBEpisode);
end
else // not exact title match, check for fuzzy and contains
begin
if (TTVGeneral.fuzzyTitleMatch(guideTitle, episodeTitle, 15)) then
// allow 15 percent discrepency)
Falreadymatched.GetfuzzyTitleMatches.add(TVDBEpisode);
// check for contains (the program guide title contains the tvdb title)
contains := guideTitle.ToLower.contains(episodeTitle.ToLower);
containsNormalized := TTVGeneral.normalize(guideTitle)
.ToLower.contains(TTVGeneral.normalize(episodeTitle).ToLower);
if (contains or containsNormalized) then
Falreadymatched.GetcontainsTitleMatches.add(TVDBEpisode);
end;
end;
if (hasOriginalAirDate) then
begin
if SameText(epFirstAired, origAirDate) then
if Falreadymatched.GetoriginalAirDateMatches.Count = 0 then
begin
Falreadymatched.GetoriginalAirDateMatches.add(TVDBEpisode);
end
else
begin
ep := Falreadymatched.GetoriginalAirDateMatches.FindByOriginalDate(origAirDate);
if ep <> nil then
begin
ep.AddMissingInfo(TVDBEpisode);
end;
end;
end;
end;
end;
destructor TGracenoteMatcher.Destroy;
begin
// FcontainsTitleMatches.free;
// FexactTitleMatches.free;
// FfuzzyTitleMatches.free;
// ForiginalAirDateMatches.free;
inherited Destroy;
end;
// function TGracenoteMatcher.GetcontainsTitleMatches: TVDBEpisodeColl;
// begin
// Result:= FcontainsTitleMatches;
// end;
//
// function TGracenoteMatcher.GetexactTitleMatches: TVDBEpisodeColl;
// begin
// Result := FexactTitleMatches;
// end;
//
// function TGracenoteMatcher.GetfuzzyTitleMatches: TVDBEpisodeColl;
// begin
// Result := FfuzzyTitleMatches;
// end;
//
// function TGracenoteMatcher.GetoriginalAirDateMatches: TVDBEpisodeColl;
// begin
// Result := ForiginalAirDateMatches;
// end;
end.
|
unit Embedded_GUI_ARM_Register;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
// LCL
Forms, Controls, StdCtrls, Dialogs, ExtCtrls,
// LazUtils
LazLoggerBase,
// IdeIntf
ProjectIntf, CompOptsIntf, LazIDEIntf, IDEOptionsIntf, IDEOptEditorIntf, MenuIntf,
// Embedded ( Eigene Units )
Embedded_GUI_IDE_Options_Frame,
Embedded_GUI_Common,
Embedded_GUI_ARM_Common,
Embedded_GUI_ARM_Project_Options_Form;
type
{ TProjectARMApp }
TProjectARMApp = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles(AProject: TLazProject): TModalResult; override;
function DoInitDescriptor: TModalResult; override;
end;
procedure ShowARMOptionsDialog(Sender: TObject);
implementation
procedure ShowARMOptionsDialog(Sender: TObject);
var
LazProject: TLazProject;
ProjOptiForm: TARM_Project_Options_Form;
begin
ProjOptiForm := TARM_Project_Options_Form.Create(nil);
LazProject := LazarusIDE.ActiveProject;
if (LazProject.LazCompilerOptions.TargetCPU <> 'arm') or (LazProject.LazCompilerOptions.TargetOS <> 'embedded') then begin
if MessageDlg('Warnung', 'Es handelt sich nicht um ein ARM Embedded Project.' + LineEnding + 'Diese Funktion kann aktuelles Projekt zerstören' + LineEnding + LineEnding + 'Trotzdem ausführen ?', mtWarning, [mbYes, mbNo], 0) = mrNo then begin
ProjOptiForm.Free;
Exit;
end;
end;
ARM_ProjectOptions.Load_from_Project(LazProject);
ProjOptiForm.IsNewProject:=False;
if ProjOptiForm.ShowModal = mrOk then begin
ARM_ProjectOptions.Save_to_Project(LazProject);
LazProject.LazCompilerOptions.GenerateDebugInfo := False;
end;
ProjOptiForm.Free;
end;
{ TProjectARMApp }
constructor TProjectARMApp.Create;
begin
inherited Create;
Name := Title + 'ARM-Project (STM32)';
Flags := DefaultProjectNoApplicationFlags - [pfRunnable];
end;
function TProjectARMApp.GetLocalizedName: string;
begin
Result := Title + 'ARM-Project (STM32)';
end;
function TProjectARMApp.GetLocalizedDescription: string;
begin
Result := Title + 'Erstellt ein ARM-Project (STM32)';
end;
function TProjectARMApp.DoInitDescriptor: TModalResult;
var
Form: TARM_Project_Options_Form;
begin
Form := TARM_Project_Options_Form.Create(nil);
Form.IsNewProject:=True;
Result := Form.ShowModal;
Form.Free;
end;
function TProjectARMApp.InitProject(AProject: TLazProject): TModalResult;
const
ProjectText =
'program Project1;' + LineEnding + LineEnding + '{$H-,J-,O-}' +
LineEnding + LineEnding + 'uses' + LineEnding + ' cortexm3;' +
LineEnding + LineEnding + 'begin' + LineEnding + ' // Setup' +
LineEnding + ' repeat' + LineEnding + ' // Loop;' + LineEnding +
' until false;' + LineEnding + 'end.';
var
MainFile: TLazProjectFile;
begin
inherited InitProject(AProject);
MainFile := AProject.CreateProjectFile('Project1.pas');
MainFile.IsPartOfProject := True;
AProject.AddFile(MainFile, False);
AProject.MainFileID := 0;
AProject.MainFile.SetSourceText(ProjectText, True);
AProject.LazCompilerOptions.TargetFilename := 'Project1';
AProject.LazCompilerOptions.Win32GraphicApp := False;
AProject.LazCompilerOptions.GenerateDebugInfo := False;
AProject.LazCompilerOptions.UnitOutputDirectory :=
'lib' + PathDelim + '$(TargetCPU)-$(TargetOS)';
AProject.Flags := AProject.Flags + [pfRunnable];
AProject.LazCompilerOptions.TargetCPU := 'avr';
AProject.LazCompilerOptions.TargetOS := 'embedded';
AProject.LazCompilerOptions.TargetProcessor := 'avr5';
AProject.LazCompilerOptions.ExecuteAfter.CompileReasons := [crRun];
ARM_ProjectOptions.Save_to_Project(AProject);
Result := mrOk;
end;
function TProjectARMApp.CreateStartFiles(AProject: TLazProject): TModalResult;
begin
Result := LazarusIDE.DoOpenEditorFile(AProject.MainFile.Filename,
-1, -1, [ofProjectLoading, ofRegularFile]);
end;
end.
|
unit umfmPrecompute;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TmfmPrecompute = class(TForm)
memoUI: TMemo;
procedure memoUIDblClick(Sender: TObject);
private
procedure Put( const Line: string);
procedure PutTable( Factor: integer; isLast: boolean);
public
{ Public declarations }
end;
var
mfmPrecompute: TmfmPrecompute;
implementation
uses Math;
{$R *.dfm}
function Poly_Mul( x, y: byte): word;
// Multiply two polynomials. Also known as Finite Field multiplication.
// Refer to section 4.2 in the standard.
// This is the multiplication BEFORE any modulo
var
j: integer;
Factor: word;
begin
result := 0;
Factor := y;
for j := 0 to 7 do
begin
if Odd( x) then
result := result xor Factor;
x := x shr 1;
Factor := Factor shl 1
end
end;
function BitCount( Value: word): integer;
begin
result := 0;
while Value <> 0 do
begin
Value := Value shr 1;
Inc( result)
end
end;
function Poly_Mod( Quotient, Modulus: word): word;
// Assume Modulus <> 0
var
QuotientBits, ModBits: integer;
OriginalModBits: integer;
ModShift, RightRoll: integer;
begin
QuotientBits := BitCount( Quotient);
OriginalModBits := BitCount( Modulus);
ModShift := QuotientBits - OriginalModBits;
if ModShift > 0 then
Modulus := Modulus shl ModShift
else if ModShift < 0 then
ModShift := 0;
ModBits := OriginalModBits + ModShift;
result := Quotient;
if Modulus = 0 then exit;
while QuotientBits = ModBits do
begin
result := result xor Modulus;
QuotientBits := BitCount( result);
RightRoll := Min( ModBits - QuotientBits, ModShift);
if RightRoll > 0 then
begin
Modulus := Modulus shr RightRoll;
Dec( ModShift, RightRoll);
Dec( ModBits, RightRoll)
end
end
end;
const GF2_8_Modulus = $011B; // == m(x) = x^8 + x^4 + x^3 + x + 1
function GF2_8_Mul( x, y: byte): byte;
begin
result := wordrec( Poly_Mod( Poly_Mul( x, y), GF2_8_Modulus)).Lo
end;
// Tables Needed: x1, x2, x3, 9 b d e
procedure TmfmPrecompute.memoUIDblClick( Sender: TObject);
var
SaveCursor: TCursor;
begin
SaveCursor := Screen.Cursor;
try
Screen.Cursor := crHourGlass;
memoUI.Clear;
memoUI.Font.Name := 'Courier';
Put( 'type');
Put( 'TMixColsFactor = (fx01, fx02, fx03, fx09, fx0b, fx0d, fx0e);');
Put( '');
Put( 'const');
Put( 'GF2_8_TimesTables: array [ TMixColsFactor, 0..255 ] of byte = (');
PutTable( $01, False);
PutTable( $02, False);
PutTable( $03, False);
PutTable( $09, False);
PutTable( $0b, False);
PutTable( $0d, False);
PutTable( $0e, True );
Put(' );')
finally
Screen.Cursor := SaveCursor
end end;
// Output should look like ....
// ================================
{
type
TMixColsFactor = (fx01, fx02, fx03, fx09, fx0b, fx0d, fx0e);
const
GF2_8_TimesTables: array [ TMixColsFactor, 0..255 ] of byte = (
( // fx01 --- Times 01 Table.
$00, $01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F,
$10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $1A, $1B, $1C, $1D, $1E, $1F,
$20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $2A, $2B, $2C, $2D, $2E, $2F,
$30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $3E, $3F,
$40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F,
$50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A, $5B, $5C, $5D, $5E, $5F,
$60, $61, $62, $63, $64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D, $6E, $6F,
$70, $71, $72, $73, $74, $75, $76, $77, $78, $79, $7A, $7B, $7C, $7D, $7E, $7F,
$80, $81, $82, $83, $84, $85, $86, $87, $88, $89, $8A, $8B, $8C, $8D, $8E, $8F,
$90, $91, $92, $93, $94, $95, $96, $97, $98, $99, $9A, $9B, $9C, $9D, $9E, $9F,
$A0, $A1, $A2, $A3, $A4, $A5, $A6, $A7, $A8, $A9, $AA, $AB, $AC, $AD, $AE, $AF,
$B0, $B1, $B2, $B3, $B4, $B5, $B6, $B7, $B8, $B9, $BA, $BB, $BC, $BD, $BE, $BF,
$C0, $C1, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $CB, $CC, $CD, $CE, $CF,
$D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $DA, $DB, $DC, $DD, $DE, $DF,
$E0, $E1, $E2, $E3, $E4, $E5, $E6, $E7, $E8, $E9, $EA, $EB, $EC, $ED, $EE, $EF,
$F0, $F1, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA, $FB, $FC, $FD, $FE, $FF
),
( // fx02 --- Times 02 Table.
$00, $02, $04, $06, $08, $0A, $0C, $0E, $10, $12, $14, $16, $18, $1A, $1C, $1E,
$20, $22, $24, $26, $28, $2A, $2C, $2E, $30, $32, $34, $36, $38, $3A, $3C, $3E,
$40, $42, $44, $46, $48, $4A, $4C, $4E, $50, $52, $54, $56, $58, $5A, $5C, $5E,
$60, $62, $64, $66, $68, $6A, $6C, $6E, $70, $72, $74, $76, $78, $7A, $7C, $7E,
$80, $82, $84, $86, $88, $8A, $8C, $8E, $90, $92, $94, $96, $98, $9A, $9C, $9E,
$A0, $A2, $A4, $A6, $A8, $AA, $AC, $AE, $B0, $B2, $B4, $B6, $B8, $BA, $BC, $BE,
$C0, $C2, $C4, $C6, $C8, $CA, $CC, $CE, $D0, $D2, $D4, $D6, $D8, $DA, $DC, $DE,
$E0, $E2, $E4, $E6, $E8, $EA, $EC, $EE, $F0, $F2, $F4, $F6, $F8, $FA, $FC, $FE,
$1B, $19, $1F, $1D, $13, $11, $17, $15, $0B, $09, $0F, $0D, $03, $01, $07, $05,
$3B, $39, $3F, $3D, $33, $31, $37, $35, $2B, $29, $2F, $2D, $23, $21, $27, $25,
$5B, $59, $5F, $5D, $53, $51, $57, $55, $4B, $49, $4F, $4D, $43, $41, $47, $45,
$7B, $79, $7F, $7D, $73, $71, $77, $75, $6B, $69, $6F, $6D, $63, $61, $67, $65,
$9B, $99, $9F, $9D, $93, $91, $97, $95, $8B, $89, $8F, $8D, $83, $81, $87, $85,
$BB, $B9, $BF, $BD, $B3, $B1, $B7, $B5, $AB, $A9, $AF, $AD, $A3, $A1, $A7, $A5,
$DB, $D9, $DF, $DD, $D3, $D1, $D7, $D5, $CB, $C9, $CF, $CD, $C3, $C1, $C7, $C5,
$FB, $F9, $FF, $FD, $F3, $F1, $F7, $F5, $EB, $E9, $EF, $ED, $E3, $E1, $E7, $E5
),
( // fx03 --- Times 03 Table.
$00, $03, $06, $05, $0C, $0F, $0A, $09, $18, $1B, $1E, $1D, $14, $17, $12, $11,
$30, $33, $36, $35, $3C, $3F, $3A, $39, $28, $2B, $2E, $2D, $24, $27, $22, $21,
$60, $63, $66, $65, $6C, $6F, $6A, $69, $78, $7B, $7E, $7D, $74, $77, $72, $71,
$50, $53, $56, $55, $5C, $5F, $5A, $59, $48, $4B, $4E, $4D, $44, $47, $42, $41,
$C0, $C3, $C6, $C5, $CC, $CF, $CA, $C9, $D8, $DB, $DE, $DD, $D4, $D7, $D2, $D1,
$F0, $F3, $F6, $F5, $FC, $FF, $FA, $F9, $E8, $EB, $EE, $ED, $E4, $E7, $E2, $E1,
$A0, $A3, $A6, $A5, $AC, $AF, $AA, $A9, $B8, $BB, $BE, $BD, $B4, $B7, $B2, $B1,
$90, $93, $96, $95, $9C, $9F, $9A, $99, $88, $8B, $8E, $8D, $84, $87, $82, $81,
$9B, $98, $9D, $9E, $97, $94, $91, $92, $83, $80, $85, $86, $8F, $8C, $89, $8A,
$AB, $A8, $AD, $AE, $A7, $A4, $A1, $A2, $B3, $B0, $B5, $B6, $BF, $BC, $B9, $BA,
$FB, $F8, $FD, $FE, $F7, $F4, $F1, $F2, $E3, $E0, $E5, $E6, $EF, $EC, $E9, $EA,
$CB, $C8, $CD, $CE, $C7, $C4, $C1, $C2, $D3, $D0, $D5, $D6, $DF, $DC, $D9, $DA,
$5B, $58, $5D, $5E, $57, $54, $51, $52, $43, $40, $45, $46, $4F, $4C, $49, $4A,
$6B, $68, $6D, $6E, $67, $64, $61, $62, $73, $70, $75, $76, $7F, $7C, $79, $7A,
$3B, $38, $3D, $3E, $37, $34, $31, $32, $23, $20, $25, $26, $2F, $2C, $29, $2A,
$0B, $08, $0D, $0E, $07, $04, $01, $02, $13, $10, $15, $16, $1F, $1C, $19, $1A
),
( // fx09 --- Times 09 Table.
$00, $09, $12, $1B, $24, $2D, $36, $3F, $48, $41, $5A, $53, $6C, $65, $7E, $77,
$90, $99, $82, $8B, $B4, $BD, $A6, $AF, $D8, $D1, $CA, $C3, $FC, $F5, $EE, $E7,
$3B, $32, $29, $20, $1F, $16, $0D, $04, $73, $7A, $61, $68, $57, $5E, $45, $4C,
$AB, $A2, $B9, $B0, $8F, $86, $9D, $94, $E3, $EA, $F1, $F8, $C7, $CE, $D5, $DC,
$76, $7F, $64, $6D, $52, $5B, $40, $49, $3E, $37, $2C, $25, $1A, $13, $08, $01,
$E6, $EF, $F4, $FD, $C2, $CB, $D0, $D9, $AE, $A7, $BC, $B5, $8A, $83, $98, $91,
$4D, $44, $5F, $56, $69, $60, $7B, $72, $05, $0C, $17, $1E, $21, $28, $33, $3A,
$DD, $D4, $CF, $C6, $F9, $F0, $EB, $E2, $95, $9C, $87, $8E, $B1, $B8, $A3, $AA,
$EC, $E5, $FE, $F7, $C8, $C1, $DA, $D3, $A4, $AD, $B6, $BF, $80, $89, $92, $9B,
$7C, $75, $6E, $67, $58, $51, $4A, $43, $34, $3D, $26, $2F, $10, $19, $02, $0B,
$D7, $DE, $C5, $CC, $F3, $FA, $E1, $E8, $9F, $96, $8D, $84, $BB, $B2, $A9, $A0,
$47, $4E, $55, $5C, $63, $6A, $71, $78, $0F, $06, $1D, $14, $2B, $22, $39, $30,
$9A, $93, $88, $81, $BE, $B7, $AC, $A5, $D2, $DB, $C0, $C9, $F6, $FF, $E4, $ED,
$0A, $03, $18, $11, $2E, $27, $3C, $35, $42, $4B, $50, $59, $66, $6F, $74, $7D,
$A1, $A8, $B3, $BA, $85, $8C, $97, $9E, $E9, $E0, $FB, $F2, $CD, $C4, $DF, $D6,
$31, $38, $23, $2A, $15, $1C, $07, $0E, $79, $70, $6B, $62, $5D, $54, $4F, $46
),
( // fx0B --- Times 0B Table.
$00, $0B, $16, $1D, $2C, $27, $3A, $31, $58, $53, $4E, $45, $74, $7F, $62, $69,
$B0, $BB, $A6, $AD, $9C, $97, $8A, $81, $E8, $E3, $FE, $F5, $C4, $CF, $D2, $D9,
$7B, $70, $6D, $66, $57, $5C, $41, $4A, $23, $28, $35, $3E, $0F, $04, $19, $12,
$CB, $C0, $DD, $D6, $E7, $EC, $F1, $FA, $93, $98, $85, $8E, $BF, $B4, $A9, $A2,
$F6, $FD, $E0, $EB, $DA, $D1, $CC, $C7, $AE, $A5, $B8, $B3, $82, $89, $94, $9F,
$46, $4D, $50, $5B, $6A, $61, $7C, $77, $1E, $15, $08, $03, $32, $39, $24, $2F,
$8D, $86, $9B, $90, $A1, $AA, $B7, $BC, $D5, $DE, $C3, $C8, $F9, $F2, $EF, $E4,
$3D, $36, $2B, $20, $11, $1A, $07, $0C, $65, $6E, $73, $78, $49, $42, $5F, $54,
$F7, $FC, $E1, $EA, $DB, $D0, $CD, $C6, $AF, $A4, $B9, $B2, $83, $88, $95, $9E,
$47, $4C, $51, $5A, $6B, $60, $7D, $76, $1F, $14, $09, $02, $33, $38, $25, $2E,
$8C, $87, $9A, $91, $A0, $AB, $B6, $BD, $D4, $DF, $C2, $C9, $F8, $F3, $EE, $E5,
$3C, $37, $2A, $21, $10, $1B, $06, $0D, $64, $6F, $72, $79, $48, $43, $5E, $55,
$01, $0A, $17, $1C, $2D, $26, $3B, $30, $59, $52, $4F, $44, $75, $7E, $63, $68,
$B1, $BA, $A7, $AC, $9D, $96, $8B, $80, $E9, $E2, $FF, $F4, $C5, $CE, $D3, $D8,
$7A, $71, $6C, $67, $56, $5D, $40, $4B, $22, $29, $34, $3F, $0E, $05, $18, $13,
$CA, $C1, $DC, $D7, $E6, $ED, $F0, $FB, $92, $99, $84, $8F, $BE, $B5, $A8, $A3
),
( // fx0D --- Times 0D Table.
$00, $0D, $1A, $17, $34, $39, $2E, $23, $68, $65, $72, $7F, $5C, $51, $46, $4B,
$D0, $DD, $CA, $C7, $E4, $E9, $FE, $F3, $B8, $B5, $A2, $AF, $8C, $81, $96, $9B,
$BB, $B6, $A1, $AC, $8F, $82, $95, $98, $D3, $DE, $C9, $C4, $E7, $EA, $FD, $F0,
$6B, $66, $71, $7C, $5F, $52, $45, $48, $03, $0E, $19, $14, $37, $3A, $2D, $20,
$6D, $60, $77, $7A, $59, $54, $43, $4E, $05, $08, $1F, $12, $31, $3C, $2B, $26,
$BD, $B0, $A7, $AA, $89, $84, $93, $9E, $D5, $D8, $CF, $C2, $E1, $EC, $FB, $F6,
$D6, $DB, $CC, $C1, $E2, $EF, $F8, $F5, $BE, $B3, $A4, $A9, $8A, $87, $90, $9D,
$06, $0B, $1C, $11, $32, $3F, $28, $25, $6E, $63, $74, $79, $5A, $57, $40, $4D,
$DA, $D7, $C0, $CD, $EE, $E3, $F4, $F9, $B2, $BF, $A8, $A5, $86, $8B, $9C, $91,
$0A, $07, $10, $1D, $3E, $33, $24, $29, $62, $6F, $78, $75, $56, $5B, $4C, $41,
$61, $6C, $7B, $76, $55, $58, $4F, $42, $09, $04, $13, $1E, $3D, $30, $27, $2A,
$B1, $BC, $AB, $A6, $85, $88, $9F, $92, $D9, $D4, $C3, $CE, $ED, $E0, $F7, $FA,
$B7, $BA, $AD, $A0, $83, $8E, $99, $94, $DF, $D2, $C5, $C8, $EB, $E6, $F1, $FC,
$67, $6A, $7D, $70, $53, $5E, $49, $44, $0F, $02, $15, $18, $3B, $36, $21, $2C,
$0C, $01, $16, $1B, $38, $35, $22, $2F, $64, $69, $7E, $73, $50, $5D, $4A, $47,
$DC, $D1, $C6, $CB, $E8, $E5, $F2, $FF, $B4, $B9, $AE, $A3, $80, $8D, $9A, $97
),
( // fx0E --- Times 0E Table.
$00, $0E, $1C, $12, $38, $36, $24, $2A, $70, $7E, $6C, $62, $48, $46, $54, $5A,
$E0, $EE, $FC, $F2, $D8, $D6, $C4, $CA, $90, $9E, $8C, $82, $A8, $A6, $B4, $BA,
$DB, $D5, $C7, $C9, $E3, $ED, $FF, $F1, $AB, $A5, $B7, $B9, $93, $9D, $8F, $81,
$3B, $35, $27, $29, $03, $0D, $1F, $11, $4B, $45, $57, $59, $73, $7D, $6F, $61,
$AD, $A3, $B1, $BF, $95, $9B, $89, $87, $DD, $D3, $C1, $CF, $E5, $EB, $F9, $F7,
$4D, $43, $51, $5F, $75, $7B, $69, $67, $3D, $33, $21, $2F, $05, $0B, $19, $17,
$76, $78, $6A, $64, $4E, $40, $52, $5C, $06, $08, $1A, $14, $3E, $30, $22, $2C,
$96, $98, $8A, $84, $AE, $A0, $B2, $BC, $E6, $E8, $FA, $F4, $DE, $D0, $C2, $CC,
$41, $4F, $5D, $53, $79, $77, $65, $6B, $31, $3F, $2D, $23, $09, $07, $15, $1B,
$A1, $AF, $BD, $B3, $99, $97, $85, $8B, $D1, $DF, $CD, $C3, $E9, $E7, $F5, $FB,
$9A, $94, $86, $88, $A2, $AC, $BE, $B0, $EA, $E4, $F6, $F8, $D2, $DC, $CE, $C0,
$7A, $74, $66, $68, $42, $4C, $5E, $50, $0A, $04, $16, $18, $32, $3C, $2E, $20,
$EC, $E2, $F0, $FE, $D4, $DA, $C8, $C6, $9C, $92, $80, $8E, $A4, $AA, $B8, $B6,
$0C, $02, $10, $1E, $34, $3A, $28, $26, $7C, $72, $60, $6E, $44, $4A, $58, $56,
$37, $39, $2B, $25, $0F, $01, $13, $1D, $47, $49, $5B, $55, $7F, $71, $63, $6D,
$D7, $D9, $CB, $C5, $EF, $E1, $F3, $FD, $A7, $A9, $BB, $B5, $9F, $91, $83, $8D
)
);
}
procedure TmfmPrecompute.Put( const Line: string);
begin
memoUI.Lines.Add( Line)
end;
procedure TmfmPrecompute.PutTable( Factor: integer; isLast: boolean);
var
Row, Col, Idx: integer;
s: string;
begin
Put( Format('( // fx%0:.2x --- Times %0:.2x Table.', [ Factor]));
Idx := 0;
for Row := 0 to 15 do
begin
s := ' ';
for Col := 0 to 15 do
begin
s := s + Format( '$%.2x', [GF2_8_Mul( Idx, Factor)]);
if Col < 15 then
s := s + ', '
else if Row < 15 then
s := s + ',';
Inc( Idx)
end;
Put( s)
end;
if isLast then
Put(' )')
else
begin
Put(' ),');
Put('')
end
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFPostData;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefPostDataRef = class(TCefBaseRefCountedRef, ICefPostData)
protected
function IsReadOnly: Boolean;
function HasExcludedElements: Boolean;
function GetCount: NativeUInt;
function GetElements(Count: NativeUInt): IInterfaceList; // ICefPostDataElement
function RemoveElement(const element: ICefPostDataElement): Integer;
function AddElement(const element: ICefPostDataElement): Integer;
procedure RemoveElements;
public
class function UnWrap(data: Pointer): ICefPostData;
class function New: ICefPostData;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFPostDataElement;
function TCefPostDataRef.IsReadOnly: Boolean;
begin
Result := PCefPostData(FData)^.is_read_only(PCefPostData(FData)) <> 0;
end;
function TCefPostDataRef.HasExcludedElements: Boolean;
begin
Result := PCefPostData(FData)^.has_excluded_elements(PCefPostData(FData)) <> 0;
end;
function TCefPostDataRef.AddElement(
const element: ICefPostDataElement): Integer;
begin
Result := PCefPostData(FData)^.add_element(PCefPostData(FData), CefGetData(element));
end;
function TCefPostDataRef.GetCount: NativeUInt;
begin
Result := PCefPostData(FData)^.get_element_count(PCefPostData(FData))
end;
function TCefPostDataRef.GetElements(Count: NativeUInt): IInterfaceList;
var
items: PCefPostDataElementArray;
i: Integer;
begin
Result := TInterfaceList.Create;
GetMem(items, SizeOf(PCefPostDataElement) * Count);
FillChar(items^, SizeOf(PCefPostDataElement) * Count, 0);
try
PCefPostData(FData)^.get_elements(PCefPostData(FData), @Count, items);
for i := 0 to Count - 1 do
Result.Add(TCefPostDataElementRef.UnWrap(items[i]));
finally
FreeMem(items);
end;
end;
class function TCefPostDataRef.New: ICefPostData;
begin
Result := UnWrap(cef_post_data_create);
end;
function TCefPostDataRef.RemoveElement(
const element: ICefPostDataElement): Integer;
begin
Result := PCefPostData(FData)^.remove_element(PCefPostData(FData), CefGetData(element));
end;
procedure TCefPostDataRef.RemoveElements;
begin
PCefPostData(FData)^.remove_elements(PCefPostData(FData));
end;
class function TCefPostDataRef.UnWrap(data: Pointer): ICefPostData;
begin
if data <> nil then
Result := Create(data) as ICefPostData else
Result := nil;
end;
end.
|
unit UnitJanelas;
interface
uses
Windows,
Messages,
TLhelp32,
PsAPI,
UnitServerUtils;
procedure FecharJanela(Janela: THandle);
procedure MostrarJanela(Janela: THandle);
procedure OcultarJanela(Janela: THandle);
procedure MaximizarJanela(Janela: THandle);
procedure MinimizarJanela(Janela: THandle);
procedure MinimizarTodas;
function GetProcessNameFromWnd(Wnd: HWND): string;
implementation
uses
UnitDiversos;
var
Win32Platform: integer;
Win32MajorVersion: Integer;
Win32MinorVersion: Integer;
Win32BuildNumber: Integer;
Win32CSDVersion: string;
procedure InitPlatformId;
var
OSVersionInfo: TOSVersionInfo;
begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then
with OSVersionInfo do
begin
Win32Platform := dwPlatformId;
Win32MajorVersion := dwMajorVersion;
Win32MinorVersion := dwMinorVersion;
if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then
Win32BuildNumber := dwBuildNumber and $FFFF
else
Win32BuildNumber := dwBuildNumber;
Win32CSDVersion := szCSDVersion;
end;
end;
function RunningProcessesList(var List: String; FullPath: Boolean): Boolean;
function ProcessFileName(PID: DWORD): string;
var
Handle: THandle;
begin
Result := '';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
if FullPath then
begin
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end
else
begin
if GetModuleBaseNameA(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end;
finally
CloseHandle(Handle);
end;
end;
const
RsSystemIdleProcess = 'Idle';
RsSystemProcess = 'System';
function IsWinXP: Boolean;
begin
Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and
(Win32MajorVersion = 5) and (Win32MinorVersion = 1);
end;
function IsWin2k: Boolean;
begin
Result := (Win32MajorVersion >= 5) and
(Win32Platform = VER_PLATFORM_WIN32_NT);
end;
function IsWinNT4: Boolean;
begin
Result := Win32Platform = VER_PLATFORM_WIN32_NT;
Result := Result and (Win32MajorVersion = 4);
end;
function IsWin3X: Boolean;
begin
Result := Win32Platform = VER_PLATFORM_WIN32_NT;
Result := Result and (Win32MajorVersion = 3) and
((Win32MinorVersion = 1) or (Win32MinorVersion = 5) or
(Win32MinorVersion = 51));
end;
function BuildListTH: Boolean;
var
SnapProcHandle: THandle;
ProcEntry: TProcessEntry32;
NextProc: Boolean;
FileName: string;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
if Result then
try
ProcEntry.dwSize := SizeOf(ProcEntry);
NextProc := Process32First(SnapProcHandle, ProcEntry);
while NextProc do
begin
if ProcEntry.th32ProcessID = 0 then
begin
FileName := RsSystemIdleProcess;
end
else
begin
if IsWin2k or IsWinXP then
begin
FileName := ProcessFileName(ProcEntry.th32ProcessID);
if FileName = '' then
FileName := ProcEntry.szExeFile;
end
else
begin
FileName := ProcEntry.szExeFile;
if not FullPath then
FileName := ExtractFileName(FileName);
end;
end;
List := List + inttostr(ProcEntry.th32ProcessID) + '#|#' + FileName + '#|#';
NextProc := Process32Next(SnapProcHandle, ProcEntry);
end;
finally
CloseHandle(SnapProcHandle);
end;
end;
function BuildListPS: Boolean;
var
PIDs: array [0..1024] of DWORD;
Needed: DWORD;
I: Integer;
FileName: string;
begin
Result := EnumProcesses(@PIDs, SizeOf(PIDs), Needed);
if Result then
begin
for I := 0 to (Needed div SizeOf(DWORD)) - 1 do
begin
case PIDs[i] of
0:
FileName := RsSystemIdleProcess;
2:
if IsWinNT4 then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[i]);
8:
if IsWin2k or IsWinXP then
FileName := RsSystemProcess
else
FileName := ProcessFileName(PIDs[i]);
else
FileName := ProcessFileName(PIDs[i]);
end;
if FileName <> '' then List := List + inttostr(PIDs[i]) + '#|#' + FileName + '#|#';
end;
end;
end;
begin
if IsWin3X or IsWinNT4 then
Result := BuildListPS
else
Result := BuildListTH;
end;
function GetProcessNameFromWnd(Wnd: HWND): string;
var
List: String;
PID: DWORD;
I: Integer;
begin
Result := '';
if IsWindow(Wnd) then
begin
PID := INVALID_HANDLE_VALUE;
GetWindowThreadProcessId(Wnd, @PID);
try
if RunningProcessesList(List, True) then
begin
if pos(inttostr(PID) + '#|#', list) > 0 then
begin
delete(List, 1, pos(inttostr(PID) + '#|#', List) - 1);
delete(List, 1, pos('#|#', List) - 1);
delete(List, 1, 3);
result := copy(List, 1, pos('#|#', List) - 1);
end;
end;
except
end;
end;
end;
procedure FecharJanela(Janela: THandle);
begin
PostMessage(Janela, WM_CLOSE, 0, 0);
// PostMessage(Janela, WM_DESTROY, 0, 0);
// PostMessage(Janela, WM_QUIT, 0, 0);
end;
procedure MostrarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_SHOW);
ShowWindow(janela, SW_NORMAL);
end;
procedure OcultarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_HIDE);
end;
procedure MaximizarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_MAXIMIZE);
end;
procedure MinimizarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_MINIMIZE);
end;
procedure MinimizarTodas;
begin
keybd_event(VK_LWIN,MapvirtualKey( VK_LWIN,0),0,0) ;
keybd_event(Ord('M'),MapvirtualKey(Ord('M'),0),0,0);
keybd_event(Ord('M'),MapvirtualKey(Ord('M'),0),KEYEVENTF_KEYUP,0);
keybd_event(VK_LWIN,MapvirtualKey(VK_LWIN,0),KEYEVENTF_KEYUP,0);
end;
initialization
InitPlatformId;
end.
|
unit UIOCRProductViewDialog;
interface
uses uImage2XML,
Windows,
SysUtils,
Classes,
Graphics,
Forms,
Controls,
StdCtrls,
Buttons,
ExtCtrls,
Menus,
OmniXML,
ComCtrls,
CommCtrl,
uReg,
uHashTable,
ShellAPI,
uFileDir,
uStrUtil;
type
TOCRProductViewDialog = class(TForm)
mnuMain: TMainMenu;
pmnClose: TMenuItem;
tv: TTreeView;
pmnuOptions: TMenuItem;
pmnuAlwaysOnTop: TMenuItem;
mnuViewXML: TMenuItem;
procedure pmnCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pmnuAlwaysOnTopClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tvMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure mnuViewXMLClick(Sender: TObject);
procedure FormHide(Sender: TObject);
private
reg : CReg;
FEnableUIEvents : boolean;
lastHintNode : TTreeNode;
FHintHashTable : THashStringTable;
FXMLTempFileName : string;
FXML : string;
procedure XMLToTreeview(DataTree: TTreeView; XMLDocument: IXMLDocument);
procedure BoldTreeNode(treeNode: TTreeNode; Value: Boolean);
function NodeHint(tn: TTreeNode): string;
public
function DisplayXML( const XMLToDisplay : string ) : boolean;
property XMLTempFileName : String read FXMLTempFileName write FXMLTempFileName;
end;
var
dlgOCRProductView: TOCRProductViewDialog;
implementation
{$R *.dfm}
function TOCRProductViewDialog.DisplayXML( const XMLToDisplay : string ): boolean;
var
FXmlDoc : IXMLDocument;
begin
FXML := '';
self.Show;
Result := false;
FXmlDoc := CreateXMLDoc();
FXML := XMLToDisplay;
if ( FXmlDoc.LoadXML( FXML ) ) then begin
XMLToTreeview( self.tv, FXmlDoc );
Result := true;
end;
self.Refresh;
end;
procedure TOCRProductViewDialog.FormCreate(Sender: TObject);
begin
FEnableUIEvents := false;
reg := CReg.Create();
pmnuAlwaysOnTop.Checked := ( reg.RegGet( REG_KEY, pmnuAlwaysOnTop.Name, 'N' ) = 'Y' );
FEnableUIEvents := true;
FHintHashTable := THashStringTable.Create();
end;
procedure TOCRProductViewDialog.FormDestroy(Sender: TObject);
Begin
FreeAndNil( Reg );
FreeAndNil( FHintHashTable );
End;
procedure TOCRProductViewDialog.FormHide(Sender: TObject);
begin
if ( FileExists( FXMLTempFileName ) ) then
DeleteFile( FXMLTempFileName );
end;
procedure TOCRProductViewDialog.mnuViewXMLClick(Sender: TObject);
var
filedir : CFileDir;
begin
try
filedir := CFileDir.Create();
FXMLTempFileName := AppTempDir + '\~XMLOCRProduct' + RandomString() + '.xml';
filedir.WriteString( FXML, FXMLTempFileName );
ShellExecute(Handle, 'open', pchar( FXMLTempFileName ), nil,nil,SW_SHOWNORMAL);
finally
FreeAndNil( filedir );
end;
end;
procedure TOCRProductViewDialog.pmnCloseClick(Sender: TObject);
Begin
self.Hide;
End;
procedure TOCRProductViewDialog.pmnuAlwaysOnTopClick(Sender: TObject);
Begin
if ( FEnableUIEvents ) then begin
pmnuAlwaysOnTop.Checked := not pmnuAlwaysOnTop.Checked;
if ( pmnuAlwaysOnTop.Checked ) then
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE)
else
SetWindowPos(Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE);
reg.RegSet( REG_KEY, pmnuAlwaysOnTop.Name, BoolToStr( pmnuAlwaysOnTop.Checked ) );
end;
End;
procedure TOCRProductViewDialog.tvMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
tree: TTreeView;
hoverNode: TTreeNode;
hitTest : THitTests;
//ht : THitTest;
begin
if (Sender is TTreeView) then
tree := TTreeView(Sender)
else
Exit;
hoverNode := tree.GetNodeAt(X, Y) ;
hitTest := tree.GetHitTestInfoAt(X, Y) ;
(*
//list the hitTest values
Caption := '';
for ht in hitTest do
begin
Caption := Caption + GetEnumName(TypeInfo(THitTest), integer(ht)) + ', ';
end;
*)
if (lastHintNode <> hoverNode) then
begin
Application.CancelHint;
if (hitTest <= [htOnItem, htOnIcon, htOnLabel, htOnStateIcon]) then
begin
lastHintNode := hoverNode;
tree.Hint := NodeHint(hoverNode) ;
Application.Hint := tree.Hint;
Application.ActivateHint(ClientToScreen(Point(X, Y)));
end;
end;
end;
function TOCRProductViewDialog.NodeHint(tn: TTreeNode): string;
begin
result := Format('%s',[ self.FHintHashTable[ IntToStr(tn.AbsoluteIndex) ] ]) ;
end;
procedure TOCRProductViewDialog.XMLToTreeview(DataTree: TTreeView; XMLDocument: IXMLDocument);
procedure AddNode(ParentNode: TTreeNode; Node: IXMLNode);
const
MaxTextLen = 50;
var
I: Integer;
NodeText, sNodeName, sAttrib : string;
NewNode: TTreeNode;
nod: IXMLNode;
nodeResultFlag : boolean;
begin
case Node.NodeType of
ELEMENT_NODE, TEXT_NODE, CDATA_SECTION_NODE:
begin
// Here you may want to retrieve the value
// of the id attribute instead of Node.Text
NodeText := Node.NodeValue;
nodeResultFlag := true;
if NodeText = '' then begin
NodeText := Node.NodeName;
nodeResultFlag := false;
end;
end;
DOCUMENT_TYPE_NODE:
//NodeText := Node.DOMNode.nodeName;
//NodeText := Node.na
//else
NodeText := Node.NodeName;
end;
NewNode := DataTree.Items.AddChildObject(ParentNode,
Copy(NodeText, 1, MaxTextLen),
Pointer(Node));
BoldTreeNode( NewNode, nodeResultFlag );
NewNode.ImageIndex := Ord(Node.nodeType);
if ( Node.Attributes.Length > 0 ) then begin
sAttrib := '';
for I := 0 to Node.Attributes.Length - 1 do begin
nod := Node.Attributes.Item[I];
with nod do
begin
sNodeName := NodeName;
if ( sNodeName = 'x' ) then
sNodeName := 'X'
else if ( sNodeName = 'y' ) then
sNodeName := 'Y'
else if ( sNodeName = 'w' ) then
sNodeName := 'Width'
else if ( sNodeName = 'h' ) then
sNodeName := 'Height'
else if ( sNodeName = 'a' ) then
sNodeName := 'Accuracy'
;
sAttrib := sAttrib + Format('%s=%s', [sNodeName, NodeValue]) + ' ';
//DataTree.Items.AddChildObject(NewNode,
// Copy(NodeText, 1, MaxTextLen),
// Pointer(Node.Attributes.Item[I]));
end;
end;
FHintHashTable.Add( IntToStr(NewNode.AbsoluteIndex), sAttrib );
end;
for I := 0 to Node.ChildNodes.Length - 1 do
AddNode(NewNode, Node.ChildNodes.Item[I]);
end;
var
I: Integer;
begin
if XMLDocument.ChildNodes.Length = 0 then
Exit;
DataTree.Items.BeginUpdate;
try
DataTree.Items.Clear;
for I := 0 to XMLDocument.ChildNodes.Length - 1 do
AddNode(nil, XMLDocument.ChildNodes.Item[I]);
DataTree.Items[0].Expand(True);
DataTree.Selected := DataTree.Items[0];
DataTree.TopItem := DataTree.Selected;
//DataTree.SetFocus;
finally
DataTree.Items.EndUpdate;
end;
end;
//Thanks http://delphi.about.com/od/adptips2006/qt/treeitembold.htm
procedure TOCRProductViewDialog.BoldTreeNode(treeNode: TTreeNode; Value: Boolean) ;
var
treeItem: TTVItem;
begin
if not Assigned(treeNode) then Exit;
with treeItem do
begin
hItem := treeNode.ItemId;
stateMask := TVIS_BOLD;
mask := TVIF_HANDLE or TVIF_STATE;
if Value then
state := TVIS_BOLD
else
state := 0;
end;
TreeView_SetItem(treeNode.Handle, treeItem) ;
end;
end.
|
unit BaseForm;
interface
uses
Forms, Controls, StdCtrls, Classes, Windows;
type
TBaseForm = class (TForm)
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Loaded; override;
end;
implementation
{ TBaseForm }
procedure TBaseForm.KeyDown(var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
begin
if not ((ActiveControl is TComboBox) and TComboBox(ActiveControl).DroppedDown) then
begin
ModalResult := mrCancel;
end;
end;
inherited;
end;
procedure TBaseForm.Loaded;
begin
inherited;
KeyPreview := True;
end;
end.
|
{*******************************************************}
{ }
{ 基于HCView的电子病历程序 作者:荆通 }
{ }
{ 此代码仅做学习交流使用,不可用于商业目的,由此引发的 }
{ 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 }
{ 交流。 }
{ }
{*******************************************************}
unit FunctionIntf;
interface
uses
FunctionConst;
const
FUN_CUSTOM = '{146E64A2-6C78-497B-B6A3-9DFBC8CE7B91}';
FUN_PLUGIN = '{14085FF8-D940-41B6-869D-49101CFA4BF1}';
type
ICustomFunction = interface(IInterface) // 插件提供的功能信息基类
[FUN_CUSTOM]
/// <summary> 返回功能的ID,即唯一标识 </summary>
/// <returns>ID</returns>
function GetID: string;
/// <summary> 设置功能的GUID </summary>
/// <param name="Value">GUID</param>
procedure SetID(const Value: string);
property ID: string read GetID write SetID;
end;
IObjectFunction = interface(ICustomFunction)
[FUN_OBJECT]
function GetObject: TObject;
procedure SetObject(const Value: TObject);
property &Object: TObject read GetObject write SetObject;
end;
IPluginFunction = interface(ICustomFunction)
[FUN_PLUGIN]
/// <summary> 在界面显示功能调用入口 </summary>
function GetShowEntrance: Boolean;
/// <summary> 设置是否在界面显示功能调用入口 </summary>
/// <param name="ASingleton">True:显示,False:不显示</param>
procedure SetShowEntrance(const Value: Boolean);
function GetName: string;
procedure SetName(const Value: string);
property Name: string read GetName write SetName;
property ShowEntrance: Boolean read GetShowEntrance write SetShowEntrance;
end;
/// <summary> 插件向主程序请求指定功能事件 </summary>
/// <param name="APluginID">请求功能的插件ID</param>
/// <param name="AFunctionID">请求的功能ID</param>
/// <param name="AData">功能对应的数据</param>
TFunctionNotifyEvent = procedure(const APluginID, AFunctionID: string;
const AObjectFun: IObjectFunction);
/// <summary> 业务窗体功能 </summary>
IFunBLLFormShow = interface(IPluginFunction)
[FUN_BLLFORMSHOW]
/// <summary> 获取主程序Application的句柄 </summary>
/// <returns>句柄</returns>
function GetAppHandle: THandle;
/// <summary> 设置主程序句柄 </summary>
/// <param name="Value">句柄</param>
procedure SetAppHandle(const Value: THandle);
/// <summary> 返回插件保存的主程序供插件请求处理功能的方法 </summary>
/// <returns>方法</returns>
function GetOnNotifyEvent: TFunctionNotifyEvent;
/// <summary> 插件保存主程序供插件请求处理功能的方法 </summary>
/// <param name="Value"></param>
procedure SetOnNotifyEvent(const Value: TFunctionNotifyEvent);
/// <summary> 主程序句柄 </summary>
property AppHandle: THandle read GetAppHandle write SetAppHandle;
/// <summary> 主程序处理功能事件 </summary>
property OnNotifyEvent: TFunctionNotifyEvent read GetOnNotifyEvent write SetOnNotifyEvent;
end;
implementation
end.
|
unit pyutil;
{$mode delphi}
interface
uses
Classes, SysUtils;
function booltoint(b: boolean): integer;
function inttobool(i:Integer):Boolean;
implementation
function booltoint(b: boolean): integer;
begin
if b then
Result := 1
else
Result := 0;
end;
function inttobool(i: Integer): Boolean;
begin
if i=1 then
Result := True
else
Result := False;
end;
end.
|
// ColorBtn ver 1.3 09/12/1999
// by SoftCos (Enzo Costantini)
unit ColorPicker;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Buttons;
type
TColBtn = class(TSpeedButton)
protected
procedure Paint; override;
public
property Canvas;
published
property Color;
end;
TColorPicker = class(TCustomPanel)
FColorDlg:TColorDialog;
private
FDropDownFlat : Boolean;
FAutomaticColor : TColor;
FIsAutomatic : Boolean;
FAutoClicked : Boolean;
procedure InitButtons;
procedure UpdateButtons;
procedure OtherBtnClick(Sender:TObject);
procedure BtnClick(Sender:TObject);
procedure SetAutomaticColor(Value:TColor);
procedure SetIsAutomatic(Value:boolean);
procedure SetDropDownFlat(Value:boolean);
procedure ReadReg;
procedure WriteReg;
public
AutoBtn,
OtherColBtn:TColBtn;
ColBtns: array[1..56] of TColBtn;
OtherBtn:TSpeedButton;
SelColor : TColor;
RegKey : string;
constructor Create(AOwner: TComponent); override;
property AutomaticColor : TColor read FAutomaticColor write SetAutomaticColor;
property IsAutomatic : boolean read FIsAutomatic write SetIsAutomatic;
property AutoClicked:boolean read FAutoClicked default false;
property DropDownFlat:Boolean read FDropDownFlat write SetDropDownFlat;
end;
TColPickDlg = class(TForm)
ColPick: TColorPicker;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
SendCtrl:TControl;
CloseOk:boolean;
OtherOk:boolean;
procedure WMKILLFOCUS(var message: TWMKILLFOCUS); message WM_KILLFOCUS;
procedure WMERASEBKGND(var message: TWMERASEBKGND); message WM_ERASEBKGND;
public
SelectedColor:TColor;
procedure Drop(Sender:TControl);
end;
TGlyphType = (gtForeground,gtBackground,gtLines,gtCustom);
TColorBtn = class(TCustomPanel)
private
FFlat,
FDropDownFlat : Boolean;
FActiveColor : TColor;
FAutomaticColor : TColor;
FTargetColor : TColor;
FGlyphType : TGlyphType;
FIsAutomatic : Boolean;
FOnBtnClick,
FBeforeDropDown : TNotifyEvent;
FAutoBtnCaption,
FOtherBtnCaption:TCaption;
FRegKey : string;
procedure InitButtons;
procedure Btn1Click(Sender:TObject);
procedure Btn2Click(Sender:TObject);
procedure SetFlat(Value:boolean);
procedure SetActiveColor(Value:TColor);
procedure SetGlyphType(Value:TGlyphType);
procedure SetGlyph(Value:TBitMap);
function GetGlyph:TBitMap;
procedure SetRegKey(Value:string);
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
Btn1:TColBtn;
Btn2:TSpeedButton;
procedure SetEnabled(Value:boolean);override;
public
AutoClicked:boolean;
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure AdjustBtnSize (var W: Integer; var H: Integer);
procedure WMSize(var Message: TWMSize); message WM_SIZE;
published
property ActiveColor : TColor read FActiveColor write SetActiveColor;
property TargetColor : TColor read FTargetColor write FTargetColor;
property Flat:Boolean read FFlat write SetFlat;
property DropDownFlat:Boolean read FDropDownFlat write FDropDownFlat;
property AutomaticColor : TColor read FAutomaticColor write FAutomaticColor;
property IsAutomatic : boolean read FIsAutomatic write FIsAutomatic;
property OnClick : TNotifyEvent read FOnBtnClick write FOnBtnClick;
property BeforeDropDown : TNotifyEvent read FBeforeDropDown write FBeforeDropDown;
property GlyphType : TGlyphType read FGlyphType write SetGlyphType default gtForeground;
property Glyph : TBitMap read GetGlyph write SetGlyph;
property AutoBtnCaption : TCaption read FAutoBtnCaption write FAutoBtnCaption;
property OtherBtnCaption:TCaption read FOtherBtnCaption write FOtherBtnCaption;
property RegKey : string read FRegKey write SetRegKey;
property Enabled;
property Hint;
property ShowHint;
property Visible;
property Constraints;
property Anchors;
property ParentShowHint;
property PopupMenu;
end;
procedure Register;
implementation
uses Registry;
{$R *.Res}
const
BtnDim=20;
BtnColors:array[1..56] of TColor
=($000000,$808080,$000040,$004040,$004000,$404000,$400000,$400040,
$202020,$909090,$000080,$008080,$008000,$808000,$800000,$800080,
$303030,$A0A0A0,$0000C0,$00C0C0,$00C000,$C0C000,$C00000,$C000C0,
$404040,$B0B0B0,$0000FF,$00FFFF,$00FF00,$FFFF00,$FF0000,$FF00FF,
$505050,$C0C0C0,$4040FF,$40FFFF,$40FF40,$FFFF40,$FF4040,$FF40FF,
$606060,$D0D0D0,$8080FF,$80FFFF,$80FF80,$FFFF80,$FF8080,$FF80FF,
$707070,$FFFFFF,$C0C0FF,$C0FFFF,$C0FFC0,$FFFFC0,$FFC0C0,$FFC0FF);
procedure Register;
begin
RegisterComponents('ConTEXT Components', [TColorBtn]);
end;
procedure TColBtn.Paint;
var B,X,Y:integer;
FColor,BColor:TColor;
begin
if Enabled
then
begin
FColor:=Color;
BColor:=clBlack;
end
else
begin
FColor:=clBtnFace;
BColor:=clGray;
end;
B:=Height div 5;
inherited;
with Canvas do
if Glyph.Handle<>0
then
begin
X:=(Width div 2)-4+Integer(FState in [bsDown]);
Y:= X+2;
Pen.color:=BColor;
Brush.Color:=FColor;
Rectangle(X,Y,X+12,Y+10);
end
else
if Caption=''
then
begin
Pen.color:=clgray;
Brush.Color:=FColor;
Brush.Style:=bsSolid;
Rectangle(B,B,Width-B,Height-B);
end
else
begin
Pen.color:=clgray;
Brush.Style:=bsClear;
Polygon([Point(B-1,B-1),
Point(Width-(B-1),B-1),
Point(Width-(B-1),Height-(B-1)),
Point(B-1,Height-(B-1))]);
Pen.color:=clgray;
Brush.Color:=FColor;
Brush.Style:=bsSolid;
Rectangle(B+1,B+1,Height,Height-B);
end;
end;
constructor TColorPicker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] + [csOpaque];
if not NewStyleControls then ControlStyle := ControlStyle + [csFramed];
Width := 170;
Height :=200;
FColorDlg:=TColorDialog.Create(self);
FColorDlg.Options:=[cdFullOpen];
InitButtons;
FIsAutomatic:=true;
FDropDownFlat:=true;
ParentBackground:=FALSE;
end;
procedure TColorPicker.InitButtons;
var
I : integer;
Btn: TColBtn;
ABtn:TSpeedButton;
X,Y: Integer;
begin
Btn:=TColBtn.Create(Self);
Btn.Parent := Self;
Btn.Flat:=true;
Btn.Tag:=100;
Btn.Color:=ClDefault;
Btn.GroupIndex:=1;
Btn.Anchors:=[akBottom];
Btn.SetBounds(5,4,Width-10,BtnDim);
Btn.OnClick:=BtnClick;
AutoBtn:=Btn;
for I := 1 to 56 do
begin
Btn := TColBtn.Create (Self);
Btn.Parent := Self;
Btn.Flat:=true;
Btn.Color:=BtnColors[I];
Btn.Anchors:=[akBottom];
Btn.GroupIndex:=1;
Btn.OnClick:=BtnClick;
X := 5 + ((I - 1) mod 8 ) * BtnDim;
Y := BtnDim+ 10 + BtnDim*((I-1) div 8);
Btn.SetBounds (X, Y , BtnDim,BtnDim);
ColBtns[I] := Btn;
end;
Btn:=TColBtn.Create(Self);
Btn.Parent := Self;
Btn.Flat:=true;
Btn.Color:=FColorDlg.Color;
Btn.SetBounds(5,BtnDim*8+15,BtnDim,BtnDim);
Btn.GroupIndex:=1;
Btn.Anchors:=[akBottom];
Btn.OnClick:=BtnClick;
OtherColBtn:=Btn;
ABtn:=TSpeedButton.Create(Self);
ABtn.Parent := Self;
ABtn.Flat:=true;
ABtn.SetBounds(5+BtnDim,BtnDim*8+15,Width-10-BtnDim,BtnDim);
ABtn.Anchors:=[akBottom];
OtherBtn:=ABtn;
OtherBtn.OnClick:=OtherBtnClick;
end;
procedure TColorPicker.UpdateButtons;
var I : integer;
begin
Height:=Height-22;
for I:=1 to 56
do ColBtns[I].Top:=ColBtns[I].Top-22;
OtherColBtn.Top:=OtherColBtn.Top-22;
OtherBtn.Top:=OtherBtn.Top-22;
end;
procedure TColorPicker.ReadReg;
var ECIni:TRegistry;
I : Integer;
begin
ECIni := TRegistry.Create;
try
with ECIni do
if OpenKey('SoftWare',false) and
OpenKey('SoftCos',false) and
OpenKey(RegKey,false)
then
for I:=0 to 15 do
FColorDlg.CustomColors.Add('Color'+Char(65+I)+'='+
ReadString('Color'+Char(65+I)));
finally
ECIni.Free;
end;
end;
procedure TColorPicker.WriteReg;
var ECIni:TRegistry;
I:integer;
begin
ECIni := TRegistry.Create;
try
with ECIni do
if OpenKey('SoftWare',true) and
OpenKey('SoftCos',true) and
OpenKey(RegKey,true)
then
for I:=0 to 15 do
WriteString(FColorDlg.CustomColors.Names[I],
FColorDlg.CustomColors.Values[FColorDlg.CustomColors.Names[I]]);
finally ECIni.Free; end;
end;
procedure TColorPicker.OtherBtnClick(Sender:TObject);
begin
FColorDlg.Color:=OtherColBtn.Color;
TColPickDlg(Owner).OtherOk:=true;
ReadReg;
if FColorDlg.Execute
then
begin
OtherColBtn.Color:=FColorDlg.Color;
WriteReg;
end;
TColPickDlg(Owner).OtherOk:=false;
SendMessage(TColPickDlg(Owner).Handle,WM_SETFOCUS,0,0);
end;
procedure TColorPicker.BtnClick(Sender:TObject);
begin
if TControl(Sender).Tag=100
then FAutoClicked:=true
else FAutoClicked:=false;
SelColor:=TColBtn(Sender).Color;
SendMessage(TwinControl(Owner).handle,WM_KeyDown,vk_return,0);
end;
procedure TColorPicker.SetAutomaticColor(Value:TColor);
begin
if Value<>FAutomaticColor
then
begin
FAutomaticColor:=Value;
AutoBtn.Color:=Value;
end;
end;
procedure TColorPicker.SetIsAutomatic(Value:boolean);
begin
if Value<>FIsAutomatic
then
begin
FIsAutoMatic:=Value;
AutoBtn.visible:=Value;
end;
if not FIsAutomatic
then UpdateButtons;
end;
procedure TColorPicker.SetDropDownFlat(Value:boolean);
var i:integer;
begin
if Value<>FDropDownFlat
then
try
FDropDownFlat:=Value;
for i:=1 to 56 do ColBtns[i].Flat:=Value;
AutoBtn.Flat:=Value;
OtherBtn.Flat:=Value;
OtherColBtn.Flat:=Value;
except
end;
end;
{TColPickDlg}
procedure TColPickDlg.Drop(Sender:TControl);
begin
SendCtrl:=Sender;
Show;
end;
procedure TColPickDlg.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=vk_escape then Close;
if Key=vk_return then
begin
SelectedColor:=ColPick.SelColor;
CloseOk:=true;
Close;
end;
Key:=0;
end;
procedure TColPickDlg.FormShow(Sender: TObject);
var i:integer;
ok:boolean;
begin
CloseOk:=false;
ok:=false;
for i:=1 to 56 do
begin
if BtnColors[i]=SelectedColor
then
begin
ColPick.ColBtns[i].down:=true;
Ok:=true;
end;
end;
if not Ok
then
begin
ColPick.OtherColBtn.Color:=SelectedColor;
ColPick.OtherColBtn.Down:=true;
end;
end;
procedure TColPickDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if CloseOk
then
with TColorBtn(SendCtrl) do
begin
Btn1.Color:=SelectedColor;
FActiveColor:=SelectedColor;
FTargetColor:=SelectedColor;
AutoClicked:=ColPick.AutoClicked;
Btn1Click(Sender);
end;
Action:=caFree;
end;
procedure TColPickDlg.WMKILLFOCUS(var message: TWMKILLFOCUS);
begin
if not OtherOk then Self.Close;
end;
procedure TColPickDlg.WMERASEBKGND(var message: TWMERASEBKGND);
begin
message.Result := 1;
end;
{TColorBtn}
constructor TColorBtn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ParentBackground:=FALSE;
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] + [csOpaque];
if not NewStyleControls then ControlStyle := ControlStyle + [csFramed];
Height :=22;
BevelOuter:=bvNone;
InitButtons;
FFlat:=false;
FDropDownFlat:=true;
FIsAutomatic:=True;
FAutoBtnCaption:='Automatic';
FOtherBtnCaption:='&Other colors...';
FRegKey:='Palette0';
end;
procedure TColorBtn.InitButtons;
begin
Btn1:=TColBtn.Create(Self);
Btn1.Parent := Self;
Btn1.Color:=FActiveColor;
Btn1.OnClick:=Btn1Click;
Btn1.Glyph.Handle:= LoadBitmap(HInstance,'FRCOLOR');
Btn2:=TSpeedButton.Create(Self);
Btn2.Parent := Self;
Btn2.Glyph.Handle:= LoadBitmap(HInstance,'DROPDOWN');
Btn2.OnClick:=Btn2Click;
end;
procedure TColorBtn.CMMouseEnter(var Message: TMessage);
begin//
end;
procedure TColorBtn.CMMouseLeave(var Message: TMessage);
begin//
end;
procedure TColorBtn.Btn1Click(Sender:TObject);
begin
if not (csDesigning in ComponentState) and Assigned(FOnBtnClick) then
FOnBtnClick(Self);
end;
procedure TColorBtn.Btn2Click(Sender:TObject);
var P:TPoint;
Dlg:TColPickDlg;
begin
if not (csDesigning in ComponentState) and
Assigned(FBeforeDropDown)
then FBeforeDropDown(Self);
P.X:=TControl(Sender).Left-TControl(Sender).height;
P.Y:=TControl(Sender).Top+TControl(Sender).height;
P:=ClientToScreen(P);
Dlg:= TColPickDlg.CreateNew(Application);
with Dlg do
begin
Left:=P.X;
Top:=P.Y;
BorderIcons := [];
BorderStyle := bsNone;
ColPick:=TColorPicker.Create(Dlg);
ColPick.Parent := Dlg;
ColPick.AutomaticColor:=FAutomaticColor;
ColPick.IsAutomatic:=FIsAutomatic;
ColPick.DropDownFlat:=FDropDownFlat;
ColPick.AutoBtn.Caption:=FAutoBtnCaption;
ColPick.OtherBtn.Caption:=FOtherBtnCaption;
ColPick.RegKey:=FRegKey;
ColPick.Left := Left;
ColPick.Top := Top;
ClientHeight:=ColPick.Height+ColPick.Top;
ClientWidth:=ColPick.Width+ColPick.Left;
OnKeyDown:= FormKeyDown;
OnShow:=FormShow;
OnClose:=FormClose;
SelectedColor:=TargetColor;
Drop(TColorBtn(self));
end;
end;
procedure TColorBtn.SetFlat(value:boolean);
begin
if Value<>FFlat
then
begin
FFlat:=Value;
Btn1.Flat:=Value;
Btn2.Flat:=Value;
end;
end;
procedure TColorBtn.AdjustBtnSize (var W: Integer; var H: Integer);
begin
if (csLoading in ComponentState) then Exit;
if Btn1 = nil then Exit;
W:=H+(H div 2)+4;
Btn1.SetBounds(0,0,H,H);
Btn2.SetBounds(H,0,(H div 2)+4,H);
end;
procedure TColorBtn.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
W, H: Integer;
begin
W := AWidth;
H := AHeight;
AdjustBtnSize (W, H);
inherited SetBounds (ALeft, ATop, W, H);
end;
procedure TColorBtn.WMSize(var Message: TWMSize);
var
W, H: Integer;
begin
inherited;
W := Width;
H := Height;
AdjustBtnSize (W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds(Left, Top, W, H);
Message.Result := 0;
end;
procedure TColorBtn.SetActiveColor(Value:TColor);
begin
if Value<>FActiveColor
then
begin
FActiveColor:=Value;
Btn1.Color:=Value;
end;
end;
procedure TColorBtn.SetGlyphType(Value:TGlyphType);
begin
if Value<>FGlyphType
then
begin
FGlyphType:=Value;
case FGlyphType of
gtForeground:
Btn1.Glyph.Handle:=LoadBitmap(HInstance,'FRCOLOR');
gtBackground:
Btn1.Glyph.Handle:=LoadBitmap(HInstance,'BKCOLOR');
gtLines:
Btn1.Glyph.Handle:=LoadBitmap(HInstance,'LNCOLOR');
gtCustom:
Btn1.Glyph:=nil;
end;
Btn1.Invalidate;
end;
end;
procedure TColorBtn.SetGlyph(Value:TBitMap);
begin
FGlyphType:=gtCustom;
Btn1.Glyph:=Value;
Btn1.Invalidate;
end;
function TColorBtn.GetGlyph:TBitMap;
begin
result:= btn1.Glyph;
end;
procedure TColorBtn.SetRegKey(Value:string);
begin
if Value<>FRegKey
then
begin
if Value=''
then FRegKey:='Palette0'
else FRegKey:=Value;
end;
end;
procedure TColorBtn.SetEnabled(Value:boolean);
begin
Btn1.Enabled:=Value;
Btn2.Enabled:=Value;
inherited;
end;
end.
|
unit LMap;
{$mode objfpc}{$H+}{$Define LMAP}
interface
uses
Classes, SysUtils, IniFiles, Graphics, LTypes, LIniFiles, LPixelStorage, LSize;
type
TLMap=class(TObject)
private
{types and vars}
var
FData: TBitmap;
FTexture: TLTexture;
Fini: TLIniFile;
FSize: TL3Dsize;
public
{functions and procedures}
constructor Create(Aini: TLIniFile);
destructor Destroy; override;
private
{propertyes}
property ini: TLIniFile read Fini write Fini;
public
{propertyes}
property data: TBitmap read FData write FData;
//procedure setTextures(Value: TLTextures);
property texture: TLTexture read FTexture write FTexture;
function getSize: TL3DSize;
procedure setSize(Value: TL3DSize);
property Size: TL3DSize read FSize write FSize;
end;
implementation
constructor TLMap.Create(AIni: TLIniFile);
begin
inherited Create;
Fini:=AIni;
data:=ini.ReadBitmap('Pictures', 'data', nil);
Size:=getSize;
end;
destructor TLMap.Destroy;
begin
inherited Destroy;
setSize(Size);
end;
{
procedure TLMap.setTextures(Value: TLTextures);
var i: integer;
begin
if Value=Nil then FTextures:=Nil
else
begin
SetLength(FTextures, Length(Value));
for i:=0 to Length(Value) do
FTextures[i]:=Value[i];
end;
end;
}
function TLMap.getSize: TL3DSize;
begin
Result:=ini.ReadL3DSize('Map', 'size');
end;
procedure TLMap.setSize(Value: TL3DSize);
begin
ini.WriteL3DSize('Map', 'size', Value);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.