text stringlengths 14 6.51M |
|---|
unit ssDBLookupCombo;
interface
uses
SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, DB, Dialogs, Windows, Messages;
type
TssDBLookupCombo = class;
TssDBlcbLink = class(TDataLink)
private
FControl: TssDBLookupCombo;
protected
procedure ActiveChanged; override;
end;
TssDBLookupCombo = class(TcxComboBox)
private
FDataLink: TssDBlcbLink;
FLoading: Boolean;
FDefFieldName: string;
FListField: string;
FKeyField: string;
FEmptyValue: Integer;
FDisplayEmpty: string;
FKeyValue: Integer;
procedure SetDefFieldName(const Value: string);
function GetListSource: TDataSource;
procedure SetListSource(const Value: TDataSource);
procedure SetListField(const Value: string);
procedure SetKeyField(const Value: string);
procedure SetEmptyValue(const Value: Integer);
procedure SetDisplayEmpty(const Value: string);
procedure SetKeyValue(const Value: Integer);
protected
procedure PropertiesChanged(Sender: TObject); override;
procedure SetEditValue(const Value: TcxEditValue); override;
procedure DoEditKeyPress(var Key: Char); override;
procedure DoEditKeyDown(var Key: Word; Shift: TShiftState); override;
function SetDisplayText(const Value: TCaption): Boolean; override;
procedure InternalSetEditValue(const Value: TcxEditValue; AValidateEditValue: Boolean); override;
function InternalSetText(const Value: TCaption): Boolean; override;
public
procedure ReloadData;
constructor Create(AOwner: TComponent); override;
procedure Loaded; override;
destructor Destroy; override;
property KeyValue: integer read FKeyValue write SetKeyValue;
published
property DefFieldName: string read FDefFieldName write SetDefFieldName;
property DisplayEmpty: string read FDisplayEmpty write SetDisplayEmpty;
property EmptyValue: integer read FEmptyValue write SetEmptyValue;
property KeyField: string read FKeyField write SetKeyField;
property ListField: string read FListField write SetListField;
property ListSource: TDataSource read GetListSource write SetListSource;
end;
implementation
{ TssDBComboBox }
//==============================================================================================
constructor TssDBLookupCombo.Create(AOwner: TComponent);
begin
inherited;
FDataLink := TssDBlcbLink.Create;
FDataLink.FControl := Self;
end;
//==============================================================================================
destructor TssDBLookupCombo.Destroy;
begin
FDataLink.Free;
inherited;
end;
//==============================================================================================
function TssDBLookupCombo.GetListSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
//==============================================================================================
procedure TssDBLookupCombo.PropertiesChanged(Sender: TObject);
begin
// ReloadData;
inherited;
end;
//==============================================================================================
procedure TssDBLookupCombo.ReloadData;
var
DS: TDataSet;
BM: TBookmark;
FList: TStringList;
FOldText: string;
FLocate: Boolean;
begin
if not FLoading then
try
FLoading := True;
DS := nil;
if ListSource <> nil then DS := FDataLink.DataSet;
if DS = nil then Exit;
if DS.Active then begin
FLocate := Properties.Items.Count = 0;
FOldText := EditText;
Properties.Items.Clear;
if DS.FindField(FKeyField) = nil then Exit;
if DS.FindField(FListField) = nil then Exit;
FList := TStringList.Create;
BM := DS.GetBookmark;
try
if FDisplayEmpty <> ''
then FList.AddObject(FDisplayEmpty, TObject(Pointer(FEmptyValue)));
DS.First;
while not DS.Eof do begin
if Trim(DS.fieldbyname(FListField).AsString) <> EmptyStr
then FList.AddObject(DS.fieldbyname(FListField).AsString,
TObject(Pointer(DS.fieldbyname(FKeyField).AsInteger)));
DS.Next;
end;
Properties.Items.Assign(FList);
if FLocate
then if Properties.Items.Count > 0 then ItemIndex := 0 else
else Text := FOldText;
finally
DS.GotoBookmark(BM);
DS.FreeBookmark(BM);
FList.Free;
end;
end;
finally
FLoading := False;
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetDefFieldName(const Value: string);
begin
{ FDefFieldName := Value;
try
Properties.ListSource.DataSet.Locate(Value, 1, []);
except
end;}
end;
//==============================================================================================
procedure TssDBLookupCombo.SetDisplayEmpty(const Value: string);
begin
if FDisplayEmpty <> Value then begin
FDisplayEmpty := Value;
if Properties.Items.Count > 0 then begin
if Value = ''
then Properties.Items.Delete(0)
else Properties.Items.Strings[0] := Value;
end;
end;
end;
//==============================================================================================
function TssDBLookupCombo.SetDisplayText(const Value: TCaption): Boolean;
begin
Result := True;
if (Value = '') and (FDisplayEmpty <> '')
then ItemIndex := 0
else Result := inherited SetDisplayText(Value);
end;
//==============================================================================================
procedure TssDBLookupCombo.SetEditValue(const Value: TcxEditValue);
var
i: integer;
begin
if (Value = '') and (FDisplayEmpty <> '') then begin
ItemIndex := 0;
FKeyValue := FEmptyValue;
end
else begin
i := Properties.Items.IndexOf(Value);
if FDataLink.DataSource = nil then Exit;
FKeyValue := Integer(Properties.Items.Objects[i]);
if not ListSource.DataSet.Active
then ListSource.DataSet.Open;
FDataLink.DataSet.Locate(FKeyField, FKeyValue, []);
end;
inherited;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetEmptyValue(const Value: integer);
begin
if FEmptyValue <> Value then begin
FEmptyValue := Value;
if (FDisplayEmpty <> '') and (Properties.Items.Count > 0)
then Properties.Items.Objects[0] := TObject(Pointer(Value));
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetKeyField(const Value: string);
begin
if FKeyField <> Value then begin
FKeyField := Value;
ReloadData;
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetListField(const Value: string);
begin
if FListField <> Value then begin
FListField := Value;
ReloadData;
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetListSource(const Value: TDataSource);
begin
if FDataLink.DataSource <> Value then begin
FDataLink.DataSource := Value;
if Value <> nil then Value.FreeNotification(Self);
ReloadData;
end;
end;
{ TssDBlcbLink }
//==============================================================================================
procedure TssDBlcbLink.ActiveChanged;
begin
FControl.ReloadData;
end;
//==============================================================================================
procedure TssDBLookupCombo.SetKeyValue(const Value: integer);
var
i: Integer;
begin
if Value <> FKeyValue then begin
i := Properties.Items.IndexOfObject(Pointer(Value));
if i = -1 then begin
if FDisplayEmpty = EmptyStr then Self.Clear;
if FDisplayEmpty <> '' then Self.ItemIndex := 0;
FKeyValue := FEmptyValue;
Exit;
end;
ItemIndex := i;
FDataLink.DataSet.Locate(FKeyField, Value, []);
FKeyValue := Value;
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.InternalSetEditValue(const Value: TcxEditValue;
AValidateEditValue: Boolean);
begin
inherited;
end;
//==============================================================================================
procedure TssDBLookupCombo.Loaded;
begin
inherited;
if FDisplayEmpty <> EmptyStr then begin
Properties.Items.AddObject(FDisplayEmpty, TObject(Pointer(FEmptyValue)));
FKeyValue := FEmptyValue;
Text := Properties.Items[0];
end;
end;
//==============================================================================================
procedure TssDBLookupCombo.DoEditKeyPress(var Key: Char);
begin
// if (Key = #27) and DroppedDown then DroppedDown := False
// else
inherited;
if ItemIndex >= 0
then FKeyValue := Integer(Properties.Items.Objects[ItemIndex]);
end;
//==============================================================================================
procedure TssDBLookupCombo.DoEditKeyDown(var Key: Word; Shift: TShiftState);
begin
if (Key = VK_DOWN) and Assigned(ListSource) and not ListSource.DataSet.Active
then ListSource.DataSet.Open;
inherited;
end;
//==============================================================================================
function TssDBLookupCombo.InternalSetText(const Value: TCaption): Boolean;
begin
Result := inherited InternalSetText(Value);
end;
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ * ------------------------------------------------------- * }
{ * # Arithmetic in Montgomery form * }
{ * # all numbers should be in range [0..N-1] * }
{ * # Reduce converts from Montgomery form * }
{ *********************************************************** }
unit tfMontMath;
{$I TFL.inc}
interface
uses
tfLimbs, tfTypes, tfNumbers;
type
PMontInstance = ^TMontInstance;
TMontInstance = record
FVTable: Pointer;
FRefCount: Integer;
FShift: Integer; // number of bits in R; R = 2^FShift; ! don't move !
FN: PBigNumber; // modulus
FRR: PBigNumber; // R^2 mod N, to convert to montgomery form
FNi: PBigNumber; // R*Ri - N*Ni = 1
// class function Release(Inst: PMontInstance): Integer; stdcall; static;
class procedure Burn(Inst: PMontInstance);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function Reduce(Inst: PMontInstance; A: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function Convert(Inst: PMontInstance; A: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function AddNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function SubNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function MulNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function ModMulNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function ModPowNumber(Inst: PMontInstance; BaseValue, ExpValue: PBigNumber; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function ModPowLimb(Inst: PMontInstance; BaseValue: PBigNumber; ExpValue: TLimb; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
class function GetRModulus(Inst: PMontInstance; var T: PBigNumber): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}static;
end;
function GetMontInstance(var P: PMontInstance; Modulus: PBigNumber): TF_RESULT;
implementation
uses
tfRecords;
const
MontVTable: array[0..12] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
// @TMontInstance.Release,
@TMontInstance.Burn,
@TMontInstance.Reduce,
@TMontInstance.Convert,
@TMontInstance.AddNumbers,
@TMontInstance.SubNumbers,
@TMontInstance.MulNumbers,
@TMontInstance.ModMulNumbers,
@TMontInstance.ModPowNumber,
@TMontInstance.ModPowLimb,
@TMontInstance.GetRModulus
);
// Ni*N = -1 mod 2^Power
function GetNi(N: PBigNumber; Power: Cardinal; var Ni: PBigNumber): TF_RESULT;
var
TmpNi, TmpProd, TmpMask, TmpPowerOfTwo: PBigNumber;
Count: Cardinal;
begin
if Power <= 1 then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// TmpNi:= 0(1) is solution for Power = 1;
Result:= TBigNumber.AllocNumber(TmpNi, 1);
if Result <> TF_S_OK then Exit;
if Odd(N.FLimbs[0]) then
TmpNi.FLimbs[0]:= 1;
// TmpMask:= 1
Result:= TBigNumber.AllocNumber(TmpMask, 1);
if Result <> TF_S_OK then begin
tfFreeInstance(TmpNi);
Exit;
end;
TmpMask.FLimbs[0]:= 1;
Count:= 1;
TmpProd:= nil;
TmpPowerOfTwo:= nil;
repeat
// TmpMask:= TmpMask shl 1 or 1;
Result:= TBigNumber.ShlNumber(TmpMask, 1, TmpMask);
if Result <> TF_S_OK then Break;
TmpMask.FLimbs[0]:= TmpMask.FLimbs[0] or 1;
// TmpProd:= (N * TmpNi) and TmpMask;
// -- we don't really need all the product, Count + 1 bits are enough;
// can be optimized
Result:= TBigNumber.MulNumbersU(N, TmpNi, TmpProd);
if Result <> TF_S_OK then Break;
Result:= TBigNumber.AndNumbersU(TmpProd, TmpMask, TmpProd);
if Result <> TF_S_OK then Break;
// if TmpProd <> 1 then TmpNi:= TmpNi + 2^Count
// -- Or (SetBit) can be used instead of AddNumbersU
if not ((TmpProd.FUsed = 1) and (TmpProd.FLimbs[0] = 1)) then begin
Result:= BigNumberPowerOfTwo(TmpPowerOfTwo, Count);
if Result <> TF_S_OK then Break;
Result:= TBigNumber.AddNumbersU(TmpNi, TmpPowerOfTwo, TmpNi);
if Result <> TF_S_OK then Break;
end;
Inc(Count);
until Count = Power;
if Result = TF_S_OK then begin
Result:= BigNumberPowerOfTwo(TmpPowerOfTwo, Power);
if Result = TF_S_OK then
Result:= TBigNumber.SubNumbersU(TmpPowerOfTwo, TmpNi, TmpNi);
end;
if Result = TF_S_OK then begin
tfFreeInstance(Ni);
Ni:= TmpNi;
end
else tfFreeInstance(TmpNi);
tfFreeInstance(TmpPowerOfTwo);
tfFreeInstance(TmpMask);
tfFreeInstance(TmpProd);
end;
function GetMontInstance(var P: PMontInstance; Modulus: PBigNumber): TF_RESULT;
var
TmpMont: PMontInstance;
TmpDividend: PBigNumber;
Shift: Cardinal;
begin
// Modulus should be odd to be coprime with powers of 2
if not Odd(Modulus.FLimbs[0]) or (Modulus.FSign < 0) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
Shift:= TBigNumber.NumBits(PBigNumber(Modulus));
Result:= tfTryAllocMem(Pointer(TmpMont), SizeOf(TMontInstance));
if Result = TF_S_OK then begin
TmpMont.FVTable:= @MontVTable;
TmpMont.FRefCount:= 1;
// setup Shift; R = 2^Shift
TmpMont.FShift:= Shift;
// setup N
Result:= TBigNumber.DuplicateNumber(Modulus, TmpMont.FN);
if Result = TF_S_OK then begin
// setup RR = 2^(2*Shift) mod Modulus
Result:= TBigNumber.AllocPowerOfTwo(TmpMont.FRR, Shift shl 1);
if Result = TF_S_OK then begin
TmpDividend:= nil;
Result:= TBigNumber.DivRemNumbers(TmpMont.FRR, TmpMont.FN,
TmpDividend, TmpMont.FRR);
if Result = TF_S_OK then begin
tfFreeInstance(TmpDividend);
// setup Ni
Result:= GetNi(TmpMont.FN, Shift, TmpMont.FNi);
end;
end;
end;
end;
if Result = TF_S_OK then begin
tfFreeInstance(P);
P:= TmpMont;
end
else
tfFreeInstance(TmpMont);
{ begin
tfFreeInstance(TmpMont.FNi);
tfFreeInstance(TmpMont.FRR);
tfFreeInstance(TmpMont.FN);
end;}
end;
(* todo: limbwise implementation of Montgomery multiplication,
{$IFDEF MONT_LIMB}
{$ELSE}
{$ENDIF}
*)
{ TMontEngine }
(*
class function TMontInstance.Release(Inst: PMontInstance): Integer;
begin
tfFreeInstance(Inst.FNi);
tfFreeInstance(Inst.FRR);
tfFreeInstance(Inst.FN);
Result:= TForgeInstance.Release(Inst);
end;
*)
class procedure TMontInstance.Burn(Inst: PMontInstance);
var
BurnSize: Integer;
begin
tfFreeInstance(Inst.FNi);
tfFreeInstance(Inst.FRR);
tfFreeInstance(Inst.FN);
BurnSize:= SizeOf(TMontInstance) - Integer(@PMontInstance(nil)^.FShift);
FillChar(Inst.FShift, BurnSize, 0);
end;
class function TMontInstance.Reduce(Inst: PMontInstance; A: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
Tmp:= nil;
// Tmp:= ((A mod R)*Ni) mod R
Result:= TBigNumber.DuplicateNumber(A, Tmp);
if Result <> TF_S_OK then Exit;
TBigNumber.MaskBits(Tmp, Inst.FShift);
Result:= TBigNumber.MulNumbers(Tmp, Inst.FNi, Tmp);
if Result = TF_S_OK then begin
TBigNumber.MaskBits(Tmp, Inst.FShift);
// Tmp:= (A + Tmp*N) div R
Result:= TBigNumber.MulNumbers(Tmp, Inst.FN, Tmp);
if Result = TF_S_OK then begin
Result:= TBigNumber.AddNumbers(A, Tmp, Tmp);
if Result = TF_S_OK then begin
Result:= TBigNumber.ShrNumber(Tmp, Inst.FShift, Tmp);
if Result = TF_S_OK then begin
// if Tmp >= N then Tmp:= Tmp - N
if TBigNumber.CompareNumbersU(Tmp, Inst.FN) >= 0 then
Result:= TBigNumber.SubNumbersU(Tmp, Inst.FN, Tmp);
end;
end;
end;
end;
if Result = TF_S_OK then begin
tfFreeInstance(T);
T:= Tmp;
end
else
tfFreeInstance(Tmp);
end;
class function TMontInstance.Convert(Inst: PMontInstance; A: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
Tmp:= nil;
Result:= TBigNumber.MulNumbersU(A, Inst.FRR, Tmp);
if Result = TF_S_OK then begin
Result:= Reduce(Inst, Tmp, T);
tfFreeInstance(Tmp);
end;
end;
// just for testing
class function TMontInstance.GetRModulus(Inst: PMontInstance; var T: PBigNumber): TF_RESULT;
begin
Result:= BigNumberPowerOfTwo(T, Inst.FShift);
end;
class function TMontInstance.AddNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
Tmp:= nil;
Result:= TBigNumber.AddNumbersU(A, B, Tmp);
if Result = TF_S_OK then begin
if TBigNumber.CompareNumbersU(Tmp, Inst.FN) >= 0 then begin
Result:= TBigNumber.SubNumbersU(Tmp, Inst.FN, T);
tfFreeInstance(Tmp);
end
else begin
tfFreeInstance(T);
T:= Tmp;
end;
end;
end;
class function TMontInstance.SubNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
Tmp:= nil;
Result:= TBigNumber.SubNumbers(A, B, Tmp);
if Result = TF_S_OK then begin
if Tmp.FSign < 0 then begin
Result:= TBigNumber.AddNumbers(Tmp, Inst.FN, T);
tfFreeInstance(Tmp);
end
else begin
tfFreeInstance(T);
T:= Tmp;
end;
end;
end;
class function TMontInstance.MulNumbers(Inst: PMontInstance; A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
Tmp:= nil;
Result:= TBigNumber.MulNumbersU(A, B, Tmp);
if Result = TF_S_OK then begin
Result:= Reduce(Inst, Tmp, T);
tfFreeInstance(Tmp);
end;
end;
class function TMontInstance.ModMulNumbers(Inst: PMontInstance;
A, B: PBigNumber; var T: PBigNumber): TF_RESULT;
var
Tmp: PBigNumber;
begin
if A.IsZero or B.IsZero then begin
SetBigNumberZero(T);
Result:= TF_S_OK;
Exit;
end;
// convert A to Montgomery form
Tmp:= nil;
Result:= Convert(Inst, A, Tmp);
if Result <> TF_S_OK then Exit;
// multiply and convert out of Montgomery form
Result:= TBigNumber.MulNumbersU(Tmp, B, Tmp);
if Result = TF_S_OK then
Result:= Reduce(Inst, Tmp, T);
tfFreeInstance(Tmp);
end;
class function TMontInstance.ModPowLimb(Inst: PMontInstance; BaseValue: PBigNumber;
ExpValue: TLimb; var T: PBigNumber): TF_RESULT;
var
MontX, TmpR: PBigNumber;
Limb: TLimb;
begin
if ExpValue = 0 then begin
SetBigNumberOne(T);
Result:= TF_S_OK;
Exit;
end;
if BaseValue.IsZero then begin
SetBigNumberZero(T);
Result:= TF_S_OK;
Exit;
end;
// convert Base to Montgomery form:
MontX:= nil;
Result:= Convert(Inst, BaseValue, MontX);
if Result <> TF_S_OK then Exit;
TmpR:= nil;
Limb:= ExpValue;
while Limb > 0 do begin
if Odd(Limb) then begin
if TmpR = nil then begin
TmpR:= MontX;
tfAddrefInstance(TmpR);
end
else begin
Result:= TBigNumber.MulNumbersU(MontX, TmpR, TmpR);
if Result = TF_S_OK then
Result:= Reduce(Inst, TmpR, TmpR);
if Result <> TF_S_OK then begin
tfFreeInstance(MontX);
tfFreeInstance(TmpR);
Exit;
end;
end;
if Limb = 1 then Break;
end;
Result:= TBigNumber.SqrNumber(MontX, MontX);
if Result = TF_S_OK then
Result:= Reduce(Inst, MontX, MontX);
if Result <> TF_S_OK then begin
tfFreeInstance(MontX);
tfFreeInstance(TmpR);
Exit;
end;
Limb:= Limb shr 1;
end;
tfFreeInstance(MontX);
// convert TmpR out of Montgomery form:
Result:= Reduce(Inst, TmpR, T);
tfFreeInstance(TmpR);
end;
class function TMontInstance.ModPowNumber(Inst: PMontInstance; BaseValue, ExpValue: PBigNumber;
var T: PBigNumber): TF_RESULT;
var
MontX: PBigNumber;
TmpR: PBigNumber;
Used, I: Cardinal;
Limb: TLimb;
P, Sentinel: PLimb;
begin
if ExpValue.FSign < 0 then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
if ExpValue.IsZero then begin
SetBigNumberOne(T);
Result:= TF_S_OK;
Exit;
end;
if BaseValue.IsZero then begin
SetBigNumberZero(T);
Result:= TF_S_OK;
Exit;
end;
// convert Base to Montgomery form:
MontX:= nil;
Result:= Convert(Inst, BaseValue, MontX);
if Result <> TF_S_OK then Exit;
TmpR:= nil;
// SetBigNumberOne(TmpR);
// Tmp:= BaseValue;
// tfAddrefInstance(Tmp);
// Q:= nil;
Used:= ExpValue.FUsed;
P:= @ExpValue.FLimbs;
Sentinel:= P + Used;
while P <> Sentinel do begin
I:= 0;
Limb:= P^;
while Limb > 0 do begin
if Odd(Limb) then begin
// TmpR:= Tmp * TmpR
// Result:= TBigNumber.MulNumbers(Tmp, TmpR, TmpR);
if TmpR = nil then begin
TmpR:= MontX;
tfAddrefInstance(TmpR);
end
else begin
Result:= TBigNumber.MulNumbersU(MontX, TmpR, TmpR);
if Result = TF_S_OK then
Result:= Reduce(Inst, TmpR, TmpR);
if Result <> TF_S_OK then begin
tfFreeInstance(MontX);
tfFreeInstance(TmpR);
Exit;
end;
end;
if Limb = 1 then Break;
end;
Result:= TBigNumber.SqrNumber(MontX, MontX);
if Result = TF_S_OK then
Result:= Reduce(Inst, MontX, MontX);
if Result <> TF_S_OK then begin
tfFreeInstance(MontX);
tfFreeInstance(TmpR);
Exit;
end;
Limb:= Limb shr 1;
Inc(I);
end;
Inc(P);
if P = Sentinel then Break;
while I < TLimbInfo.BitSize do begin
Result:= TBigNumber.SqrNumber(MontX, MontX);
if Result = TF_S_OK then
Result:= Reduce(Inst, MontX, MontX);
if Result <> TF_S_OK then begin
tfFreeInstance(MontX);
tfFreeInstance(TmpR);
Exit;
end;
Inc(I);
end;
end;
tfFreeInstance(MontX);
// convert TmpR out of Montgomery form:
Result:= Reduce(Inst, TmpR, T);
tfFreeInstance(TmpR);
end;
end.
|
unit MFichas.Controller.Venda.Metodos;
interface
uses
MFichas.Controller.Venda.Interfaces,
MFichas.Controller.Venda.Metodos.VenderItem,
MFichas.Controller.Venda.Metodos.CancelarItem,
MFichas.Controller.Venda.Metodos.Pagamento,
MFichas.Controller.Venda.Metodos.DevolverItem,
MFichas.Model.Venda.Interfaces;
type
TControllerVendaMetodos = class(TInterfacedObject, iControllerVendaMetodos)
private
[weak]
FParent : iControllerVenda;
FModel : iModelVenda;
FPagamento: iControllerVendaMetodosPagar;
constructor Create(AParent: iControllerVenda; AModel: iModelVenda);
public
destructor Destroy; override;
class function New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodos;
function AbrirVenda : iControllerVendaMetodos;
function Pagar : iControllerVendaMetodos;
function FinalizarVenda : iControllerVendaMetodos;
function VenderItem : iControllerVendaMetodosVenderItem;
function CancelarItem : iControllerVendaMetodosCancelarItem;
function DevolverItem : iControllerVendaMetodosDevolverItem;
function EfetuarPagamento: iControllerVendaMetodosPagar;
end;
implementation
{ TControllerVendaMetodos }
function TControllerVendaMetodos.AbrirVenda: iControllerVendaMetodos;
begin
Result := Self;
FModel
.Metodos
.Abrir
.Executar
.&End
.&End;
end;
function TControllerVendaMetodos.CancelarItem: iControllerVendaMetodosCancelarItem;
begin
Result := TControllerVendaMetodosCancelarItem.New(FParent, FModel);
end;
constructor TControllerVendaMetodos.Create(AParent: iControllerVenda; AModel: iModelVenda);
begin
FParent := AParent;
FModel := AModel;
FPagamento := TControllerVendaMetodosPagar.New(FParent, FModel);
end;
destructor TControllerVendaMetodos.Destroy;
begin
inherited;
end;
function TControllerVendaMetodos.DevolverItem: iControllerVendaMetodosDevolverItem;
begin
Result := TControllerVendaMetodosDevolverItem.New(FParent, FModel);
end;
function TControllerVendaMetodos.EfetuarPagamento: iControllerVendaMetodosPagar;
begin
Result := FPagamento;
end;
function TControllerVendaMetodos.FinalizarVenda: iControllerVendaMetodos;
begin
Result := Self;
FModel
.Metodos
.Finalizar
.Executar
.&End
.&End;
end;
class function TControllerVendaMetodos.New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodos;
begin
Result := Self.Create(AParent, AModel);
end;
function TControllerVendaMetodos.Pagar: iControllerVendaMetodos;
begin
Result := Self;
FModel
.Metodos
.Pagar
.Executar
.&End
.&End;
end;
function TControllerVendaMetodos.VenderItem: iControllerVendaMetodosVenderItem;
begin
Result := TControllerVendaMetodosVenderItem.New(FParent, FModel);
end;
end.
|
unit fBrokerCallHistory;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, dssrpc, ExtCtrls;
type
TfrmBrokerCallHistory = class(TForm)
memCallHistory: TMemo;
btnClose: TButton;
btnSaveToFile: TButton;
dlgSave: TSaveDialog;
btnClipboard: TButton;
Button1: TButton;
btnFindAgain: TButton;
chkMonitor: TCheckBox;
tmrUpdate: TTimer;
procedure btnCloseClick(Sender: TObject);
procedure btnSaveToFileClick(Sender: TObject);
procedure btnClipboardClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnFindAgainClick(Sender: TObject);
procedure chkMonitorClick(Sender: TObject);
procedure tmrUpdateTimer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
FBroker: TDSSRPCBroker;
FSearchTerm: string;
FSearchPos: integer;
procedure DoFind;
public
procedure ShowHistoryOfABroker(thisBroker: TDSSRPCBroker);
end;
var
frmBrokerCallHistory: TfrmBrokerCallHistory;
implementation
uses
clipbrd;
{$R *.DFM}
{ TfrmBrokerCallHistory }
function AppDir: string;
// Returns directory of application.exename
begin
//paramstr[0] is always the exe name, even in services.
Result := extractfilepath(ParamStr(0));
end;
procedure TfrmBrokerCallHistory.ShowHistoryOfABroker(thisBroker: TDSSRPCBroker);
begin
if FBroker = nil then
FBroker := thisBroker
else if FBroker <> thisBroker then
FBroker := thisBroker;
memCallHistory.Lines.Assign(thisBroker.CallHistoryList);
end;
procedure TfrmBrokerCallHistory.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmBrokerCallHistory.btnSaveToFileClick(Sender: TObject);
begin
dlgSave.InitialDir := appdir;
if dlgSave.Execute then
memCallHistory.Lines.SaveToFile(dlgSave.filename);
end;
procedure TfrmBrokerCallHistory.btnClipboardClick(Sender: TObject);
begin
if memCallHistory.SelLength > 0 then
//something is highlighted - just copy that.
clipboard.SetTextBuf(pchar(memCallHistory.seltext))
else
clipboard.SetTextBuf(pchar(memCallHistory.Text));
end;
procedure TfrmBrokerCallHistory.Button1Click(Sender: TObject);
var
sFind: string;
begin
sFind := inputbox('Find (not case sensitive)', 'Find what ?', '');
if sFind > '' then
begin
FSearchPos := 0;
FSearchTerm := sFind;
btnFindAgain.hint := 'Find "' + sFind + '" again';
DoFind;
end;
end;
procedure TfrmBrokerCallHistory.DoFind;
var
sSearchArea: string;
iPos: integer;
begin
sSearchArea := copy(memCallHistory.Text, FSearchPos, length(
memCallHistory.Text) - FSearchPos);
iPos := pos(ansilowercase(FSearchTerm), ansilowercase(sSearchArea));
if iPos > 0 then
begin
memCallHistory.selstart := FSearchPos - 1 + iPos;
memCallHistory.sellength := length(FSearchTerm);
Inc(FSearchPos, iPos + 1);
btnFindAgain.Enabled := true;
end
else
FSearchPos := 0;
end;
procedure TfrmBrokerCallHistory.btnFindAgainClick(Sender: TObject);
begin
DoFind;
end;
procedure TfrmBrokerCallHistory.chkMonitorClick(Sender: TObject);
begin
if chkMonitor.Checked then
self.formstyle := fsStayOnTop
else
self.formstyle := fsNormal;
tmrUpdate.Enabled := chkMonitor.Checked;
end;
procedure TfrmBrokerCallHistory.tmrUpdateTimer(Sender: TObject);
begin
if FBroker <> nil then
if copy(FBroker.CallHistoryList.Text, 1, 255) <> copy(memCallHistory.Text, 1, 255) then
ShowHistoryOfABroker(FBroker);
end;
procedure TfrmBrokerCallHistory.FormClose(Sender: TObject; var Action: TCloseAction);
begin
tmrUpdate.Enabled := FALSE;
end;
procedure TfrmBrokerCallHistory.FormShow(Sender: TObject);
begin
tmrUpdate.Enabled := chkMonitor.Checked;
end;
end.
|
unit fpcorm_common_interfaces;
{< @author(Andreas Lorenzen)
@created(2014-06-25)
@abstract(Common interface declarations, used throughout the object paradigms
of the project.)
This unit contains common interface declarations, that are applied in
multiple other places in the project.
@br
This is a list of what this unit includes:
@orderedList(
@item(Observer pattern interfaces)
) }
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ Forward declaration of interfaces }
IfoObserver = interface;
IfoObserverSubject = interface;
{ The observer interface for the observer design pattern, used in fpcorm }
IfoObserver = interface(IInterface)
['{406D054E-A3C3-43AE-8042-983E1EF0D258}']
procedure ReceiveSubjectUpdate(aSubject: IfoObserverSubject);
end;
{ The subject interface of the observer design pattern implementation used in fpcorm }
IfoObserverSubject = interface(IInterface)
['{CA223949-18FE-4044-AF30-6B3778DC45A4}']
procedure AttachObserver(aObserver: IfoObserver);
procedure DetachObserver(aObserver: IfoObserver);
end;
IloLogger = interface(IInterface)
['{354AB046-EA70-448C-9582-18F7C2E462E7}']
procedure Fatal(aMsg: String);
procedure Error(aMsg: String);
procedure Warning(aMsg: String);
procedure Info(aMsg: String);
procedure Debug(aMsg: String);
procedure Trace(aMsg: String);
end;
implementation
end.
|
unit htField;
// Модуль: "w:\common\components\rtl\Garant\HT\htField.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "ThtField" MUID: (559E77B902D8)
{$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, HT_Const
, htInterfaces
, daTypes
, l3Date
;
type
ThtField = class(Tl3ProtoObject, IdaField)
private
f_ClientInfo: IdaSelectField;
f_ServerInfo: OPEL;
f_DataBuffer: IdaResultBuffer;
f_DataConverter: IhtDataConverter;
private
function BufferPtr: Pointer;
protected
function Get_AsLargeInt: LargeInt;
function Get_AsInteger: Integer;
function Get_AsStDate: TStDate;
function Get_AsStTime: TStTime;
function Get_AsString: AnsiString;
function Get_AsByte: Byte;
function Get_Alias: AnsiString;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aDataBuffer: IdaResultBuffer;
const aDataConverter: IhtDataConverter;
const aClientInfo: IdaSelectField;
const aServerInfo: OPEL); reintroduce;
class function Make(const aDataBuffer: IdaResultBuffer;
const aDataConverter: IhtDataConverter;
const aClientInfo: IdaSelectField;
const aServerInfo: OPEL): IdaField; reintroduce;
end;//ThtField
implementation
uses
l3ImplUses
//#UC START# *559E77B902D8impl_uses*
//#UC END# *559E77B902D8impl_uses*
;
constructor ThtField.Create(const aDataBuffer: IdaResultBuffer;
const aDataConverter: IhtDataConverter;
const aClientInfo: IdaSelectField;
const aServerInfo: OPEL);
//#UC START# *559E77D30158_559E77B902D8_var*
//#UC END# *559E77D30158_559E77B902D8_var*
begin
//#UC START# *559E77D30158_559E77B902D8_impl*
inherited Create;
f_DataConverter := aDataConverter;
f_ClientInfo := aClientInfo;
f_ServerInfo := aServerInfo;
f_DataBuffer := aDataBuffer;
Assert(Assigned(f_DataBuffer));
f_DataBuffer.RegisterField(Self);
//#UC END# *559E77D30158_559E77B902D8_impl*
end;//ThtField.Create
class function ThtField.Make(const aDataBuffer: IdaResultBuffer;
const aDataConverter: IhtDataConverter;
const aClientInfo: IdaSelectField;
const aServerInfo: OPEL): IdaField;
var
l_Inst : ThtField;
begin
l_Inst := Create(aDataBuffer, aDataConverter, aClientInfo, aServerInfo);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//ThtField.Make
function ThtField.BufferPtr: Pointer;
//#UC START# *55C8A09B00F0_559E77B902D8_var*
//#UC END# *55C8A09B00F0_559E77B902D8_var*
begin
//#UC START# *55C8A09B00F0_559E77B902D8_impl*
Result := f_DataBuffer.FieldBufferPtr(f_ServerInfo.nNum - 1);
//#UC END# *55C8A09B00F0_559E77B902D8_impl*
end;//ThtField.BufferPtr
function ThtField.Get_AsLargeInt: LargeInt;
//#UC START# *5593905401D1_559E77B902D8get_var*
//#UC END# *5593905401D1_559E77B902D8get_var*
begin
//#UC START# *5593905401D1_559E77B902D8get_impl*
Result := f_DataConverter.ToLargeInt(BufferPtr, f_ServerInfo);
//#UC END# *5593905401D1_559E77B902D8get_impl*
end;//ThtField.Get_AsLargeInt
function ThtField.Get_AsInteger: Integer;
//#UC START# *55939068000C_559E77B902D8get_var*
//#UC END# *55939068000C_559E77B902D8get_var*
begin
//#UC START# *55939068000C_559E77B902D8get_impl*
Result := f_DataConverter.ToInteger(BufferPtr, f_ServerInfo);
//#UC END# *55939068000C_559E77B902D8get_impl*
end;//ThtField.Get_AsInteger
function ThtField.Get_AsStDate: TStDate;
//#UC START# *559393510239_559E77B902D8get_var*
//#UC END# *559393510239_559E77B902D8get_var*
begin
//#UC START# *559393510239_559E77B902D8get_impl*
Result := f_DataConverter.ToStDate(BufferPtr, f_ServerInfo);
//#UC END# *559393510239_559E77B902D8get_impl*
end;//ThtField.Get_AsStDate
function ThtField.Get_AsStTime: TStTime;
//#UC START# *5593936A031A_559E77B902D8get_var*
//#UC END# *5593936A031A_559E77B902D8get_var*
begin
//#UC START# *5593936A031A_559E77B902D8get_impl*
Result := f_DataConverter.ToStTime(BufferPtr, f_ServerInfo);
//#UC END# *5593936A031A_559E77B902D8get_impl*
end;//ThtField.Get_AsStTime
function ThtField.Get_AsString: AnsiString;
//#UC START# *55FA82A80085_559E77B902D8get_var*
//#UC END# *55FA82A80085_559E77B902D8get_var*
begin
//#UC START# *55FA82A80085_559E77B902D8get_impl*
Result := f_DataConverter.ToString(BufferPtr, f_ServerInfo);
//#UC END# *55FA82A80085_559E77B902D8get_impl*
end;//ThtField.Get_AsString
function ThtField.Get_AsByte: Byte;
//#UC START# *562E07C801CF_559E77B902D8get_var*
//#UC END# *562E07C801CF_559E77B902D8get_var*
begin
//#UC START# *562E07C801CF_559E77B902D8get_impl*
Result := f_DataConverter.ToByte(BufferPtr, f_ServerInfo);
//#UC END# *562E07C801CF_559E77B902D8get_impl*
end;//ThtField.Get_AsByte
function ThtField.Get_Alias: AnsiString;
//#UC START# *56375577038B_559E77B902D8get_var*
//#UC END# *56375577038B_559E77B902D8get_var*
begin
//#UC START# *56375577038B_559E77B902D8get_impl*
Result := f_ClientInfo.Alias;
//#UC END# *56375577038B_559E77B902D8get_impl*
end;//ThtField.Get_Alias
procedure ThtField.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_559E77B902D8_var*
//#UC END# *479731C50290_559E77B902D8_var*
begin
//#UC START# *479731C50290_559E77B902D8_impl*
Assert(Assigned(f_DataBuffer));
f_DataBuffer.UnregisterField(Self);
f_DataBuffer := nil;
f_ClientInfo := nil;
f_DataConverter := nil;
inherited;
//#UC END# *479731C50290_559E77B902D8_impl*
end;//ThtField.Cleanup
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.8 2/8/05 6:02:10 PM RLebeau
Try that again...
Rev 1.7 2/8/05 6:00:02 PM RLebeau
Updated SaveToFile() to call SaveToStream()
Rev 1.6 6/16/2004 2:10:48 PM EHill
Added SaveToStream method for TIdAttachment
Rev 1.5 2004.03.03 10:30:46 AM czhower
Removed warning.
Rev 1.4 2/24/04 1:23:58 PM RLebeau
Bug fix for SaveToFile() using the wrong Size
Rev 1.3 2004.02.03 5:44:50 PM czhower
Name changes
Rev 1.2 10/17/03 12:07:28 PM RLebeau
Updated Assign() to copy all available header values rather than select ones.
Rev 1.1 10/16/2003 10:55:24 PM DSiders
Added localization comments.
Rev 1.0 11/14/2002 02:12:36 PM JPMugaas
}
unit IdAttachment;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdMessageParts,
IdBaseComponent;
type
TIdAttachment = class(TIdMessagePart)
public
// here the methods you have to override...
// for open handling
// works like this:
// 1) you create an attachment - and do whatever it takes to put data in it
// 2) you send the message
// 3) this will be called - first OpenLoadStream, to get a stream
// 4) when the message is fully encoded, CloseLoadStream is called
// to close the stream. The Attachment implementation decides what to do
function OpenLoadStream: TStream; virtual; abstract;
procedure CloseLoadStream; virtual; abstract;
// for save handling
// works like this:
// 1) new attachment is created
// 2) PrepareTempStream is called
// 3) stuff is loaded
// 4) FinishTempStream is called of the newly created attachment
function PrepareTempStream: TStream; virtual; abstract;
procedure FinishTempStream; virtual; abstract;
procedure LoadFromFile(const FileName: String); virtual;
procedure LoadFromStream(AStream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure SaveToStream(AStream: TStream); virtual;
class function PartType: TIdMessagePartType; override;
end;
TIdAttachmentClass = class of TIdAttachment;
implementation
uses
IdGlobal, IdGlobalProtocols, IdCoderHeader,
SysUtils;
{ TIdAttachment }
class function TIdAttachment.PartType: TIdMessagePartType;
begin
Result := mptAttachment;
end;
procedure TIdAttachment.LoadFromFile(const FileName: String);
var
LStrm: TIdReadFileExclusiveStream;
begin
LStrm := TIdReadFileExclusiveStream.Create(FileName); try
LoadFromStream(LStrm);
finally
FreeAndNil(LStrm);
end;
end;
procedure TIdAttachment.LoadFromStream(AStream: TStream);
var
LStrm: TStream;
begin
LStrm := PrepareTempStream;
try
LStrm.CopyFrom(AStream, 0);
finally
FinishTempStream;
end;
end;
procedure TIdAttachment.SaveToFile(const FileName: String);
var
LStrm: TIdFileCreateStream;
begin
LStrm := TIdFileCreateStream.Create(FileName); try
SaveToStream(LStrm);
finally
FreeAndNil(LStrm);
end;
end;
procedure TIdAttachment.SaveToStream(AStream: TStream);
var
LStrm: TStream;
begin
LStrm := OpenLoadStream;
try
AStream.CopyFrom(LStrm, 0);
finally
CloseLoadStream;
end;
end;
end.
|
unit PhotoCorrectDemoMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Layouts,
FMX.Platform, GR32, GR32_Resamplers, GR32_Transforms, Math;
type
TPhotoCorrectMainForm = class(TForm)
Layout2: TLayout;
Image1: TImage;
Image2: TImage;
Rectangle3: TRectangle;
Label13: TLabel;
Rectangle1: TRectangle;
Label1: TLabel;
CmbResamplerClassNames: TComboBox;
btnReset: TButton;
btnApply: TButton;
Path1: TPath;
procedure Layout2Resize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure CmbResamplerClassNamesChange(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
private
{ Private declarations }
FChanging: Boolean;
Transformation: TProjectiveTransformation;
FScaleFactor: Single;
Vertices: array [0 .. 3] of TFloatPoint;
Shapes: array [0 .. 3] of TSelectionPoint;
procedure DoPointChanged(Sender: TObject; var X, Y: Single);
procedure DoTransform;
function GetSourceRect: TFloatRect;
procedure ChangePath;
public
{ Public declarations }
end;
var
PhotoCorrectMainForm: TPhotoCorrectMainForm;
implementation
{$R *.fmx}
uses
PerspectiveCorrect;
procedure TPhotoCorrectMainForm.btnApplyClick(Sender: TObject);
begin
DoTransform;
end;
procedure TPhotoCorrectMainForm.btnResetClick(Sender: TObject);
var
s: TSize;
I: Integer;
begin
FChanging := True;
s := Image1.Bitmap.Size;
Vertices[0] := FloatPoint(0, 0);
Vertices[1] := FloatPoint(s.Width, 0);
Vertices[2] := FloatPoint(s.Width, s.Height);
Vertices[3] := FloatPoint(0, s.Height);
for I := 0 to 3 do
Shapes[I].Position.Point := PointF(Vertices[I].X, Vertices[I].Y);
FChanging := False;
ChangePath;
end;
procedure TPhotoCorrectMainForm.ChangePath;
var
I: Integer;
begin
if FChanging then
Exit;
Path1.Position.Point := PointF(0,0);
Path1.Size.Size := Image1.Bitmap.Size;
Path1.BeginUpdate;
Path1.Data.Clear;
Path1.Data.MoveTo(PointF(Vertices[0].X,Vertices[0].Y));
for I := 1 to 3 do
begin
Path1.Data.LineTo(PointF(Vertices[I].X,Vertices[I].Y));
end;
Path1.Data.ClosePath;
Path1.EndUpdate;
Path1.Repaint;
end;
procedure TPhotoCorrectMainForm.CmbResamplerClassNamesChange(Sender: TObject);
begin
DoTransform;
end;
procedure TPhotoCorrectMainForm.DoPointChanged(Sender: TObject; var X, Y: Single);
var
idx: Integer;
begin
idx := (Sender as TComponent).Tag;
Vertices[idx].X := X;
Vertices[idx].Y := Y;
ChangePath;
end;
procedure TPhotoCorrectMainForm.DoTransform;
var
src, dst: TBitmap32;
I: Integer;
dstBitmap, tmp: TBitmap;
X, Y: array [0 .. 3] of TFloat;
W: Integer;
FQuadX: array [0 .. 3] of TFloat;
FQuadY: array [0 .. 3] of TFloat;
tr: TMyProjectiveTransformation;
srcPts, dstPts: TArray<TFloatPoint>;
begin
tr := TMyProjectiveTransformation.Create;
try
tr.SrcRect := Self.GetSourceRect;
tr.X0 := Vertices[0].X;
tr.X1 := Vertices[1].X;
tr.X2 := Vertices[2].X;
tr.X3 := Vertices[3].X;
tr.Y0 := Vertices[0].Y;
tr.Y1 := Vertices[1].Y;
tr.Y2 := Vertices[2].Y;
tr.Y3 := Vertices[3].Y;
src := TBitmap32.Create();
dst := TBitmap32.Create();
dstBitmap := TBitmap.Create;
try
src.Assign(Image1.Bitmap);
with CmbResamplerClassNames do
if ItemIndex >= 0 then
src.ResamplerClassName := Items[ItemIndex];
dst.SetSize(Round(tr.DestWidth), Round(tr.DestHeight));
dst.Clear($00000000);
Transform(dst, src, tr);
dstBitmap.Assign(dst);
if FScaleFactor = 1 then
Image2.Bitmap := dstBitmap
else
begin
tmp := TBitmap.Create;
try
tmp.SetSize(Round(dstBitmap.Width * FScaleFactor), Round(dstBitmap.Height * FScaleFactor));
tmp.Canvas.BeginScene;
tmp.Clear(0);
tmp.Canvas.DrawBitmap(dstBitmap, dstBitmap.Bounds, tmp.Bounds, 1);
tmp.Canvas.EndScene;
Image2.Bitmap := tmp;
finally
tmp.Free;
end;
end;
finally
dstBitmap.Free;
dst.Free;
src.Free;
end;
finally
tr.Free;
end;
end;
procedure TPhotoCorrectMainForm.FormCreate(Sender: TObject);
var
I: Integer;
ScreenSrv: IFMXScreenService;
s: TSize;
begin
FChanging := True;
if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenSrv) then
FScaleFactor := ScreenSrv.GetScreenScale
else
FScaleFactor := 1;
Transformation := TProjectiveTransformation.Create;
s := Image1.Bitmap.Size;
Vertices[0] := FloatPoint(0, 0);
Vertices[1] := FloatPoint(s.Width, 0);
Vertices[2] := FloatPoint(s.Width, s.Height);
Vertices[3] := FloatPoint(0, s.Height);
for I := 0 to 3 do
begin
Shapes[I] := TSelectionPoint.Create(Self);
Shapes[I].Parent := Image1;
Shapes[I].GripSize := 9;
Shapes[I].Position.X := Vertices[I].X;
Shapes[I].Position.Y := Vertices[I].Y;
Shapes[I].OnTrack := DoPointChanged;
Shapes[I].Tag := I;
end;
ResamplerList.GetClassNames(CmbResamplerClassNames.Items);
CmbResamplerClassNames.ItemIndex := 0;
FChanging := False;
ChangePath;
end;
function TPhotoCorrectMainForm.GetSourceRect: TFloatRect;
var
minx, maxx, miny, maxy: TFloat;
I: Integer;
begin
minx := MaxSingle;
miny := MaxSingle;
maxx := -MaxSingle;
maxy := -MaxSingle;
for I := 0 to 3 do
begin
maxx := Max(maxx, Vertices[I].X);
maxy := Max(maxy, Vertices[I].Y);
minx := Min(minx, Vertices[I].X);
miny := Min(miny, Vertices[I].Y);
end;
Result := FloatRect(minx, miny, maxx, maxy);
end;
procedure TPhotoCorrectMainForm.Layout2Resize(Sender: TObject);
begin
Image1.Position.Point := TPoint.Zero;
if Layout2.Width > Layout2.Height then
begin
Image1.Size.Size := TSizeF.Create(Layout2.Width / 2, Layout2.Height);
Image2.Position.Point := PointF(Layout2.Width / 2, 0);
Image2.Size.Size := TSizeF.Create(Layout2.Width / 2, Layout2.Height);
end
else
begin
Image1.Size.Size := TSizeF.Create(Layout2.Width, Layout2.Height / 2);
Image2.Position.Point := PointF(0, Layout2.Height / 2);
Image2.Size.Size := TSizeF.Create(Layout2.Width, Layout2.Height / 2);
end;
end;
end.
|
unit NativeFunctions;
interface
uses
Classes,
Data,
Common,
System.Generics.Collections,
SysUtils,
System.IOUtils,
Modules,
RegularExpressions,
Collections,
UserData,
Interfaces,
Rtti;
var
NativeFunctionList : TList<TFunction>;
type
ProcNativeFunction = reference to function(runtime : TRuntime;
context : TContext; args : Ref<TList>) : DataRef;
TNativeFunction = class(TFunction)
protected
FName : string;
FFunction : ProcNativeFunction;
public
constructor Create(name : string; func : ProcNativeFunction);
destructor Destroy(); override;
property Fn : ProcNativeFunction read FFunction write FFunction;
property name : string read FName;
/// <summary>Applies this function</summary>
/// <param name="args">UNEVALUATED arguments</param>
function Apply(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef; virtual;
end;
TEvaluatingNativeFunction = class(TNativeFunction)
public
function Apply(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef; override;
end;
function _get(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
implementation
{ TNativeFunction }
function TNativeFunction.Apply(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef;
begin
Result := FFunction(runtime, context, args);
end;
constructor TNativeFunction.Create(name : string; func : ProcNativeFunction);
begin
inherited Create(name);
FName := name;
FFunction := func;
NativeFunctionList.Add(self);
end;
destructor TNativeFunction.Destroy;
begin
inherited;
end;
{ TEvaluatingNativeFunction }
function TEvaluatingNativeFunction.Apply(runtime : TRuntime; context : TContext;
args : Ref<TList>) : DataRef;
var
evald : TList;
i : Integer;
begin
evald := TList.Create();
evald.Add(args[0]);
for i := 1 to args.Size - 1 do
evald.Add(runtime.Eval(args[i], context));
Result := inherited Apply(runtime, context, TRef<TList>.Create(evald));
end;
{ basic native functions }
function __quote(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef;
begin
Result := args[1];
end;
function __def(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef;
var
symbol : TSymbol;
begin
if args.Size < 3 then
raise Exception.Create('Too few arguments');
if args[1]() is TSymbol then
symbol := args[1]() as TSymbol
else
symbol := runtime.Eval(args[1], context)() as TSymbol;
Result := runtime.Eval(args[2], context);
context[symbol.Value] := Result;
end;
function __let(runtime : TRuntime; context : TContext; args : Ref<TList>) : DataRef;
var
bindings : TList;
subcontext : TContext;
i : Integer;
symbol : TSymbol;
exp : DataRef;
begin
bindings := args[1]() as TList;
subcontext := TContext.Create(context);
for i := 0 to (bindings.Size div 2) - 1 do
begin
symbol := bindings[1 + 2 * i]() as TSymbol;
exp := runtime.Eval(bindings[1 + 2 * i + 1], subcontext);
subcontext[symbol.Value] := exp;
end;
for i := 2 to args.Size - 1 do
begin
Result := runtime.Eval(args[i], subcontext);
end;
subcontext.Free;
end;
function _atom_(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
bool : Boolean;
begin
bool := args[1]() is TAtom;
Result := CreateRef(TBoolean.Create(bool));
end;
function __defn(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
symbol : TSymbol;
funcArgs : TList;
i : Integer;
begin
// symbol under which to define the function
symbol := args[1]() as TSymbol;
// TFunction.Create exptects basically the same arguments except the
// symbol in the front; so just copy the rest into a new list
funcArgs := TList.Create();
for i := 1 to args.Size - 1 do
begin
funcArgs.Add(args[i]);
end;
// Create and save the function
Result := CreateRef(TUserFunction.Create(TRef<TList>.Create(funcArgs), context));
context[symbol.Value] := Result;
end;
function _eq(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
a, b : TData;
begin
a := args[1]();
b := args[2]();
Result := CreateRef(TBoolean.Create(a.ValueEquals(b)));
end;
function _first(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
list : TList;
evald : DataRef;
begin
evald := args[1];
list := evald() as TList;
if list.Size = 0 then
Result := CreateRef(TNothing.Create())
else
Result := CreateRef(list[0]().Copy);
end;
function __fn(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
func : TUserFunction;
begin
func := TUserFunction.Create(args, context);
Result := CreateRef(func);
end;
function __if(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
cond : Ref<TData>;
bool : TBoolean;
Data : TData;
begin
cond := runtime.Eval(args[1], context);
Data := cond();
bool := Data as TBoolean;
if bool.BoolValue then
Result := runtime.Eval(args[2], context)
else if args.Size > 3 then
Result := runtime.Eval(args[3], context)
else
Result := CreateRef(TNothing.Create()); // if no else is supplied
end;
function _last(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
list : TList;
begin
list := args[1]() as TList;
Result := CreateRef(list[list.Size - 1]().Copy);
end;
function _length(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
Data : TData;
list : TList;
c : ICountable;
count : Integer;
begin
Data := args[1]();
if Data is TList then count := (Data as TList).Size
else if Supports(Data, ICountable, c) then count := c.count;
Result := CreateRef(TInteger.Create(count));
end;
function _list(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
list : TList;
i : Integer;
begin
list := TList.Create();
list.Executable := False;
for i := 1 to args.Size - 1 do
begin
list.Add(args[i]);
end;
Result := CreateRef(list);
end;
function _neq(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
bool : TBoolean;
begin
bool := _eq(runtime, context, args)() as TBoolean;
Result := CreateRef(TBoolean.Create(not bool.BoolValue));
end;
function _not(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
bool : TBoolean;
begin
bool := args[1]() as TBoolean;
Result := CreateRef(TBoolean.Create(not bool.BoolValue));
end;
function _nth(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
list : TList;
index : TInteger;
begin
list := args[1]() as TList;
index := args[2]() as TInteger;
Result := list[index.IntValue];
end;
function _print(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
i : Integer;
begin
for i := 1 to args.Size - 1 do
begin
Writeln(args[i]().Value);
end;
Result := CreateRef(TNothing.Create());
end;
function _rest(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
list : TList;
res : TList;
i : Integer;
begin
list := args[1]() as TList;
res := TList.Create();
for i := 1 to list.Size - 1 do
res.Add(CreateRef(list[i]().Copy));
Result := CreateRef(res);
end;
function _str(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
res : string;
i : Integer;
begin
res := '';
for i := 1 to args.Size - 1 do
begin
if args[i]() is TString then
res := res + args[i]().Value
else
begin
res := res + args[i]().ToString;
end;
end;
Result := CreateRef(TString.Create(res));
end;
function _type(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
val : Ref<TData>;
begin
val := args[1];
Result := CreateRef(TString.Create(val().ClassName));
end;
function __apply(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
params, newargs : TList;
i : Integer;
begin
newargs := TList.Create();
newargs.Add(runtime.Eval(args[1], context)); // the function to be applied
// arguments to the function
if args.Size > 2 then
begin
params := runtime.Eval(args[2], context)() as TList;
for i := 0 to params.Size - 1 do
newargs.Add(params[i]);
end;
Result := runtime.Eval(CreateRef(newargs), context);
end;
function _map(runtime : TRuntime; context : TContext; args : Ref<TList>) : Ref<TData>;
var
maplist, col, newargs : TList;
i : Integer;
Fn : DataRef;
Apply : DataRef;
begin
Apply := CreateRef(TSymbol.Create('apply'));
maplist := TList.Create();
Fn := args[1];
col := args[2]() as TList;
for i := 0 to col.Size - 1 do
begin
newargs := TList.Create();
newargs.Add(Fn);
newargs.Add(col[i]);
maplist.Add(runtime.Eval(CreateRef(newargs), context));
end;
Result := CreateRef(maplist);
end;
function _reduce(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
fn : DataRef;
list, col : TList;
i: Integer;
begin
Assert(args[1]() is TFunction);
fn := args[1];
// (reduce <fn> <col>)
if args().Size = 3 then
begin
col := args[2]() as TList;
if col.Size = 0 then
begin
list := TList.Create([fn], True);
Exit(runtime.Eval(CreateRef(list), context));
end
else if col.Size = 1 then
begin
Exit(col[0]);
end
else
begin
list := TList.Create([fn, col[0], col[1]]);
Result := runtime.Eval(CreateRef(list), context);
for i := 2 to col.Size - 1 do
begin
list := TList.Create([fn, Result, col[i]]);
Result := runtime.Eval(CreateRef(list), context);
end;
end;
end
// (reduce <fn> <init> <col>)
else if args().Size = 4 then
begin
col := args[3]() as TList;
if col.Size = 0 then Result := args[2]
else
begin
Result := args[2];
for i := 0 to col.Size - 1 do
begin
list := TList.Create([fn, Result, col[i]]);
Result := runtime.Eval(CreateRef(list), context);
end;
end;
end
else raise Exception.Create('invalid arity');
end;
function _plus(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
number, temp : TNumber;
i : Integer;
begin
Assert(args.Size >= 3);
Assert(args[1]() is TNumber);
number := args[1]() as TNumber;
for i := 2 to args.Size - 1 do
begin
Assert(args[i]() is TNumber);
temp := number;
number := number.Plus(args[i]() as TNumber);
if i > 2 then FreeAndNil(temp);
end;
Result := CreateRef(number);
end;
function _minus(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
number, temp : TNumber;
i : Integer;
begin
Assert(args.Size >= 3);
Assert(args[1]() is TNumber);
number := args[1]() as TNumber;
for i := 2 to args.Size - 1 do
begin
Assert(args[i]() is TNumber);
temp := number;
number := number.Minus(args[i]() as TNumber);
if i > 2 then FreeAndNil(temp);
end;
Result := CreateRef(number);
end;
function _multiply(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
number, temp : TNumber;
i : Integer;
begin
Assert(args.Size >= 3);
Assert(args[1]() is TNumber);
number := args[1]() as TNumber;
for i := 2 to args.Size - 1 do
begin
Assert(args[i]() is TNumber);
temp := number;
number := number.Multiply(args[i]() as TNumber);
if i > 2 then FreeAndNil(temp);
end;
Result := CreateRef(number);
end;
function _divide(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
number, temp : TNumber;
i : Integer;
begin
Assert(args.Size >= 3);
Assert(args[1]() is TNumber);
number := args[1]() as TNumber;
for i := 2 to args.Size - 1 do
begin
Assert(args[i]() is TNumber);
temp := number;
number := number.Divide(args[i]() as TNumber);
if i > 2 then FreeAndNil(temp);
end;
Result := CreateRef(number);
end;
function __do(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
i : Integer;
begin
if args.Size = 0 then
begin
Result := CreateRef(TNothing.Create);
Exit;
end;
for i := 1 to args.Size - 1 do
begin
Result := runtime.Eval(args[i], context);
end;
end;
function _inc(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
num : TNumber;
Add : TInteger;
begin
num := args[1]() as TNumber;
Add := TInteger.Create(1);
num := num.Plus(Add);
Result := CreateRef(num);
Add.Free;
end;
function _dec(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
num : TNumber;
sub : TInteger;
begin
num := args[1]() as TNumber;
sub := TInteger.Create(1);
num := num.Minus(sub);
Result := CreateRef(num);
sub.Free;
end;
function _filter(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
fnRef : DataRef;
col, filtered : TList;
params : DataRef;
bRef : DataRef;
i : Integer;
begin
fnRef := args[1];
col := args[2]() as TList;
filtered := TList.Create();
for i := 0 to col.Size - 1 do
begin
params := CreateRef(TList.Create([fnRef, col[i]], true));
bRef := runtime.Eval(params, context);
if (bRef is TBoolean) and (bRef as TBoolean).BoolValue then
begin
filtered.Add(col[i]);
end;
end;
Result := CreateRef(filtered);
end;
function _nil_(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
begin
Result := CreateRef(TBoolean.Create(args[1]() is TNothing));
end;
function _less(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
a, b, num : TNumber;
i : Integer;
begin
if (args[1]() is TNumber) and (args[2]() is TNumber) then
begin
a := args[1]() as TNumber;
b := args[2]() as TNumber;
num := a.Compare(b);
i := (num as TInteger).IntValue;
num.Free;
if i < 0 then Result := CreateRef(TBoolean.Create(True))
else Result := CreateRef(TBoolean.Create(False));
end
else
raise Exception.Create('unsupported operand');
end;
function _lessorequal(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
a, b, num : TNumber;
i : Integer;
begin
if (args[1]() is TNumber) and (args[2]() is TNumber) then
begin
a := args[1]() as TNumber;
b := args[2]() as TNumber;
num := a.Compare(b);
i := (num as TInteger).IntValue;
num.Free;
if i <= 0 then Result := CreateRef(TBoolean.Create(True))
else Result := CreateRef(TBoolean.Create(False));
end
else
raise Exception.Create('unsupported operand');
end;
function _greater(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
i : Integer;
a, b, num : TNumber;
begin
if (args[1]() is TNumber) and (args[2]() is TNumber) then
begin
a := args[1]() as TNumber;
b := args[2]() as TNumber;
num := a.Compare(b);
i := (num as TInteger).IntValue;
num.Free;
if i > 0 then Result := CreateRef(TBoolean.Create(True))
else Result := CreateRef(TBoolean.Create(False));
end
else
raise Exception.Create('unsupported operand');
end;
function _greaterorequal(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
i : Integer;
a, b, num : TNumber;
begin
if (args[1]() is TNumber) and (args[2]() is TNumber) then
begin
a := args[1]() as TNumber;
b := args[2]() as TNumber;
num := a.Compare(b);
i := (num as TInteger).IntValue;
num.Free;
if i >= 0 then Result := CreateRef(TBoolean.Create(True))
else Result := CreateRef(TBoolean.Create(False));
end
else
raise Exception.Create('unsupported operand');
end;
function __and(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
b : Boolean;
temp : DataRef;
expr : TData;
i : Integer;
begin
b := True;
for i := 1 to args.Size - 1 do
begin
temp := runtime.Eval(args[i], context);
expr := temp();
if (not(expr is TBoolean)) or (not(expr as TBoolean).BoolValue) then
begin
b := False;
break;
end;
end;
Result := CreateRef(TBoolean.Create(b));
end;
function __or(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
b : Boolean;
temp : DataRef;
expr : TData;
i : Integer;
begin
b := False;
for i := 1 to args.Size - 1 do
begin
temp := runtime.Eval(args[i], context);
expr := temp();
if (expr is TBoolean) and (expr as TBoolean).BoolValue then
begin
b := True;
break;
end;
end;
Result := CreateRef(TBoolean.Create(b));
end;
function __comment(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
begin
Result := CreateRef(TNothing.Create());
end;
function _read(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
text : Data.TString;
begin
Assert(args.Size = 2);
text := args[1]() as Data.TString;
Result := runtime.Read(text.Value);
end;
function _eval(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
begin
Result := runtime.Eval(args[1], context);
end;
// (foreach <symbol> [in] <list> <expr>)
function __foreach(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
c : TContext;
s : TSymbol;
expr : DataRef;
list : TList;
offset, i : Integer;
begin
s := args[1]() as TSymbol;
offset := 0;
if (args[2]() is TSymbol) and ((args[2]() as TSymbol).Value = 'in') then
offset := 1;
list := runtime.Eval(args[2 + offset], context)() as TList;
expr := args[3 + offset];
c := TContext.Create(context);
c['#i'] := CreateRef(TInteger.Create(0));
for i := 0 to list.Size - 1 do
begin
c[s.Value] := list[i];
(c['#i']() as TInteger).Value := IntToStr(i);
runtime.Eval(expr, c);
end;
Result := CreateRef(TNothing.Create);
c.Free;
end;
/// <summary>
/// Loads a LISP file by evaluating all contained expressions in the current
/// context.
/// </summary>
function _load(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
filename, code : string;
begin
filename := (args[1]() as TString).Value;
if not TFile.Exists(filename) then
raise Exception.Create('File does not exist: "' + filename + '"');
try
code := TFile.ReadAllText(filename);
except
Exit(CreateRef(TNothing.Create));
end;
// Wrap everything into a do statement and evaluate all expressions
code := '(do ' + code + ')';
runtime.Eval(code, context);
Result := CreateRef(TNothing.Create);
end;
// (use <path>) - import into current context without prefix
// (use <path> :ns) - import with prefix "<ModuleName>/"
// (use <path> :as <prefix>) - import with prefix "<prefix>/"
function _use(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
path : string;
module : TModule;
moduleManager : TModuleManager;
prefix : string;
begin
if args[1]() is TSymbol then
begin
// TODO: use search path additionally to CWD
path := (args[1]() as TSymbol).Value + '.cl';
end
else
path := (args[1]() as TString).Value;
moduleManager := context.GetObject<TModuleManager>('*module-manager*');
module := moduleManager.Load(path);
// import the symbols prefixed into the current context
if (args.Size = 4) and (args[2]().Value = ':as') then
prefix := args[3]().Value + '/'
else if (args.Size = 3) and (args[2]().Value = ':ns') then
prefix := module.name + '/'
else
prefix := '';
// Always import symbols with <ModuleName>/ prefix
if prefix <> (module.name + '/') then
context.Import(module.context, module.name + '/');
// Import with user defined prefix (default: empty)
context.Import(module.context, prefix);
Result := context['nil'];
end;
function __module_get(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
c : TDualLookupContext;
module : TModule;
moduleName : string;
moduleManager : TModuleManager;
begin
moduleName := (runtime.Eval(args[1], context)() as TSymbol).Value;
moduleManager := context.GetObject<TModuleManager>('*module-manager*');
module := moduleManager.Modules[moduleName];
c := TDualLookupContext.Create(context, module.context);
Result := runtime.Eval(args[2], c);
c.Free;
end;
function _in(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
list : TList;
i : Integer;
begin
list := args[1]() as TList;
for i := 0 to list.Size - 1 do
begin
if list[i]().ValueEquals(args[2]()) then
Exit(CreateRef(TBoolean.Create(True)));
end;
Result := CreateRef(TBoolean.Create(False));
end;
/// (anonymous-function expr)
/// creates an anonymous function that can make use of
/// implicit arguments in the form of "_\d?".
function __anonymous_function(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
i : Integer;
implicitArgs : TList;
code, expr : TList;
text, symbol : string;
matches : TMatchCollection;
match : TMatch;
symbols : TList<string>;
begin
implicitArgs := TList.Create();
symbols := TList<string>.Create();
expr := TList.Create();
for i := 1 to args.Size - 1 do
expr.Add(args[i]);
// scan for placeholders to find the required arguments
text := expr.ToString;
matches := TRegEx.matches(text, '%\d?');
for match in matches do
begin
symbol := match.Value;
if not symbols.Contains(symbol) then symbols.Add(symbol);
end;
symbols.Sort;
// list arguments to the anonymous functions
implicitArgs.Add(CreateRef(TSymbol.Create('list')));
for symbol in symbols do
begin
implicitArgs.Add(CreateRef(TSymbol.Create(symbol)));
end;
implicitArgs.Executable := False;
// generate the code (fn [p0 p1 ... pN] expr)
code := TList.Create();
code.Add(CreateRef(TSymbol.Create('fn'))); // (fn
code.Add(CreateRef(implicitArgs)); // (fn <args>
code.Add(CreateRef(expr)); // (fn <args> <expr>)
// evaluate the code
Result := runtime.Eval(CreateRef(code), context);
symbols.Free;
end;
function _create(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
qualifiedName : string;
constructorArgs : TList;
valueArray : array of TValue;
i : Integer;
obj : TDelphiObject;
begin
Assert((args[1]() is TSymbol) or (args[1]() is TString)); // class name
Assert(args[2]() is TList); // constructor arguments
qualifiedName := args[1]().Value;
constructorArgs := (args[2]() as TList);
SetLength(valueArray, constructorArgs.Size);
for i := 0 to constructorArgs.Size - 1 do
valueArray[i] := constructorArgs[i]().ToTValue();
obj := TDelphiObject.CreateOwned(qualifiedName, valueArray);
Result := CreateRef(obj);
end;
function _dict(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
dict : TDictionary;
i : Integer;
begin
dict := TDictionary.Create();
i := 1;
while i < args().Size - 1 do
begin
dict.Add(args[i], args[i + 1]);
i := i + 2;
end;
Result := CreateRef(dict);
end;
function _get(runtime : TRuntime; context : TContext; args : ListRef) : DataRef;
var
dict : TDictionary;
begin
if args[1]() is TDictionary then
begin
dict := args[1]() as TDictionary;
if dict.Contains(args[2]) then Result := dict.Get(args[2])
else if args().Size = 4 then Result := args[3]// default value
else Result := TNothing.Instance;
end
else
raise Exception.Create('Unsupported operand');
end;
initialization
NativeFunctionList := TList<TFunction>.Create();
TNativeFunction.Create('quote', __quote);
TNativeFunction.Create('def', __def);
TNativeFunction.Create('defn', __defn);
TNativeFunction.Create('apply', __apply);
TNativeFunction.Create('fn', __fn);
TNativeFunction.Create('if', __if);
TNativeFunction.Create('do', __do);
TNativeFunction.Create('let', __let);
TNativeFunction.Create('and', __and);
TNativeFunction.Create('or', __or);
TNativeFunction.Create('comment', __comment);
TNativeFunction.Create('foreach', __foreach);
TNativeFunction.Create('module-get', __module_get);
TNativeFunction.Create('anonymous-function', __anonymous_function);
TEvaluatingNativeFunction.Create('read', _read);
TEvaluatingNativeFunction.Create('eval', _eval);
TEvaluatingNativeFunction.Create('print', _print);
TEvaluatingNativeFunction.Create('type', _type);
TEvaluatingNativeFunction.Create('str', _str);
TEvaluatingNativeFunction.Create('atom?', _atom_);
TEvaluatingNativeFunction.Create('=', _eq);
TEvaluatingNativeFunction.Create('first', _first);
TEvaluatingNativeFunction.Create('last', _last);
TEvaluatingNativeFunction.Create('length', _length);
TEvaluatingNativeFunction.Create('list', _list);
TEvaluatingNativeFunction.Create('dict', _dict);
TEvaluatingNativeFunction.Create('not=', _neq);
TEvaluatingNativeFunction.Create('not', _not);
TEvaluatingNativeFunction.Create('nth', _nth);
TEvaluatingNativeFunction.Create('rest', _rest);
TEvaluatingNativeFunction.Create('map', _map);
TEvaluatingNativeFunction.Create('reduce', _reduce);
TEvaluatingNativeFunction.Create('filter', _filter);
TEvaluatingNativeFunction.Create('nil?', _nil_);
TEvaluatingNativeFunction.Create('load', _load);
TEvaluatingNativeFunction.Create('use', _use);
TEvaluatingNativeFunction.Create('in', _in);
TEvaluatingNativeFunction.Create('get', _get);
TEvaluatingNativeFunction.Create('+', _plus);
TEvaluatingNativeFunction.Create('-', _minus);
TEvaluatingNativeFunction.Create('/', _divide);
TEvaluatingNativeFunction.Create('*', _multiply);
TEvaluatingNativeFunction.Create('inc', _inc);
TEvaluatingNativeFunction.Create('dec', _dec);
TEvaluatingNativeFunction.Create('<', _less);
TEvaluatingNativeFunction.Create('<=', _lessorequal);
TEvaluatingNativeFunction.Create('>', _greater);
TEvaluatingNativeFunction.Create('>=', _greaterorequal);
TEvaluatingNativeFunction.Create('create', _create);
finalization
NativeFunctionList.Free;
end.
|
unit uSceneChar;
interface
uses Graphics, uImage, uScene, uResFont, Classes;
type
TSceneChar = class(TSceneFrame)
private
FAtr: TImages;
Image: TImage;
FVLine: TBitmap;
FHLine: TBitmap;
FIsLoad: Boolean;
FSL: TStringList;
FResFont: TResFont;
procedure Load();
procedure AtrUp(A: byte);
public
//** Конструктор.
constructor Create;
destructor Destroy; override;
function Click(Button: TMouseBtn): Boolean; override;
procedure Draw(); override;
function Keys(var Key: Word): Boolean; override;
function Enum(): TSceneEnum; override;
end;
var
SceneChar: TSceneChar;
implementation
uses
SysUtils, uMain, uIni, uSCR, uVars, uUtils, uEffects, uInvBox, uSounds,
uScript, uSaveLoad;
{ TSceneChar }
constructor TSceneChar.Create;
begin
FIsLoad := False;
inherited Create(spLeft);
Image := TImage.Create;
Image.Split(Path + 'Data\Images\GUI\Atribs.png', FAtr, 32);
FResFont := TResFont.Create;
FResFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName);
Back.Canvas.Font.Name := FResFont.FontName;
FSL := TStringList.Create;
end;
destructor TSceneChar.Destroy;
var
I: Byte;
begin
for I := 0 to High(FAtr) do FAtr[I].Free;
FResFont.Free;
FVLine.Free;
FHLine.Free;
Image.Free;
FSL.Free;
inherited;
end;
procedure TSceneChar.Draw;
var
IsLP: Boolean;
I, C: Byte;
begin
inherited;
if not FIsLoad then Load;
with Back.Canvas do
begin
IsLP := VM.GetInt('Hero.LP') > 0;
if VM.GetInt('Hero.HP') < 0 then VM.SetInt('Hero.HP', 0);
if VM.GetInt('Hero.MP') < 0 then VM.SetInt('Hero.MP', 0);
Font.Color := $006089A2;
Font.Size := 18;
TextOut(10, 10, VM.GetStr('Hero.Name'));
Font.Size := 14;
TextOut(205, 10, VM.GetStr('Hero.RaceName') + ' ' + VM.GetStr('Hero.ClassName'));
Draw(205, 32, Effects.Effect[88]); TextOut(225, 30, 'Уровень ' + VM.GetStrInt('Hero.Level') + ' Очки ' + VM.GetStrInt('Hero.LP'));
Draw(205, 52, Effects.Effect[99]); TextOut(225, 50, 'Опыт ' + VM.GetStrInt('Hero.Exp') + '/' +
VM.GetStrInt('Hero.NextExp'));
// Strength
Font.Size := 18;
TextOut(10, 120, 'Сила ' + IntToStr(MyGetStrength));
Font.Size := 14;
Draw(205, 122, Effects.Effect[60]); TextOut(225, 120, 'Урон ' + VM.GetStrInt('Hero.DamageMin') + '-' + VM.GetStrInt('Hero.DamageMax'));
Draw(205, 142, Effects.Effect[70]); TextOut(225, 140, 'Крит. урон ' + VM.GetStrInt('Hero.CritDamage'));
Draw(205, 162, Effects.Effect[89]); TextOut(225, 160, 'Нагрузка ' + IntToStr(InvBox.InvCount) + '/' +
VM.GetStrInt('Hero.InvLoad'));
// Agility
Font.Size := 18;
TextOut(10, 190, 'Ловкость ' + IntToStr(MyGetAgility));
Font.Size := 14;
Draw(205, 192, Effects.Effect[78]); TextOut(225, 190, 'Точность ' + VM.GetStrInt('Hero.Accuracy') + '%');
Draw(205, 212, Effects.Effect[61]); TextOut(225, 210, 'Крит. попадание ' + VM.GetStrInt('Hero.CritAccuracy') + '%');
Draw(205, 232, Effects.Effect[39]); TextOut(225, 230, 'Уклоняемость ' + VM.GetStrInt('Hero.Evade') + '%');
// Stamina
Font.Size := 18;
TextOut(10, 260, 'Статность ' + IntToStr(MyGetStamina));
Font.Size := 14;
Draw(205, 262, Effects.Effect[74]); TextOut(225, 260, 'Здоровье ' + VM.GetStrInt('Hero.HP') + '/' +
VM.GetStrInt('Hero.MHP'));
Draw(205, 282, Effects.Effect[1]); TextOut(225, 280, 'Радиус обзора ' + IntToStr(VM.GetInt('Hero.Rad') + VM.GetInt('Hero.AdvRad') + VM.GetInt('Hero.TimeRad')));
// TextOut(210, 280, 'Здоровье: ' + VM.GetStr('Hero.HP'));
// Intellect
Font.Size := 18;
TextOut(10, 330, 'Ум ' + IntToStr(MyGetIntellect));
Font.Size := 14;
Draw(205, 332, Effects.Effect[0]); TextOut(225, 330, 'Мана ' + VM.GetStrInt('Hero.MP') + '/' +
VM.GetStrInt('Hero.MMP'));
Draw(205, 352, Effects.Effect[9]); TextOut(225, 350, 'Сила магии ' + VM.GetStrInt('Hero.Magic'));
// Spirit
Font.Size := 18;
TextOut(10, 400, 'Дух ' + IntToStr(MyGetSpirit));
Font.Size := 14;
Draw(205, 402, Effects.Effect[87]); TextOut(225, 400, 'Регенер. жизни ' +
IntToStr(VM.GetInt('Hero.Spirit') +
VM.GetInt('Hero.AdvSpirit') + VM.GetInt('Hero.TimeSpirit') +
VM.GetInt('Hero.ReplenishLife')));
Draw(205, 422, Effects.Effect[80]); TextOut(225, 420, 'Регенер. магии ' +
IntToStr(Round((VM.GetInt('Hero.Spirit') +
VM.GetInt('Hero.AdvSpirit') + VM.GetInt('Hero.TimeSpirit')) * 1.7) +
VM.GetInt('Hero.ReplenishMana')));
//
Font.Size := 14;
Draw(5, 472, Effects.Effect[71]); TextOut(25, 470, 'От дробящего ' + VM.GetStrInt('Hero.Protect.Crash'));
Draw(5, 492, Effects.Effect[72]); TextOut(25, 490, 'От режущего ' + VM.GetStrInt('Hero.Protect.Slash'));
Draw(5, 512, Effects.Effect[73]); TextOut(25, 510, 'От колющего ' + VM.GetStrInt('Hero.Protect.Pierce'));
Draw(5, 532, Effects.Effect[74]); TextOut(25, 530, 'От кислоты ' + VM.GetStrInt('Hero.Protect.Acid'));
//
Draw(205, 472, Effects.Effect[98]); TextOut(225, 470, 'От холода ' + VM.GetStrInt('Hero.Protect.Ice'));
Draw(205, 492, Effects.Effect[85]); TextOut(225, 490, 'От молнии ' + VM.GetStrInt('Hero.Protect.Lightning'));
Draw(205, 512, Effects.Effect[19]); TextOut(225, 510, 'От огня ' + VM.GetStrInt('Hero.Protect.Fire'));
Draw(205, 532, Effects.Effect[11]); TextOut(225, 530, 'От яда ' + VM.GetStrInt('Hero.Protect.Poison'));
// Lines
Draw(200, 0, FVLine);
Draw(0, 115, FHLine);
Draw(0, 185, FHLine);
Draw(0, 255, FHLine);
Draw(0, 325, FHLine);
Draw(0, 395, FHLine);
Draw(0, 465, FHLine);
// Buttons
if IsLP then C := 0 else C := 5;
for I := 0 to 4 do Draw((I * 37) + 210, 75, FAtr[I + C]);
// Hint
Font.Size := 24;
if IsMouseInRect(210, 75, 242, 107) then
begin
FSL.Clear;
FSL.Append('Сила');
FSL.Append('Влияет на урон, наносимый врагам');
FSL.Append('и на грузопереносимость');
Hint.Show(210, 75, 32, FSL, False, Origin, HintBack);
end;
if IsMouseInRect(247, 75, 279, 107) then
begin
FSL.Clear;
FSL.Append('Ловкость');
FSL.Append('Краткое описание');
Hint.Show(247, 75, 32, FSL, False, Origin, HintBack);
end;
if IsMouseInRect(284, 75, 316, 107) then
begin
FSL.Clear;
FSL.Append('Статность');
FSL.Append('Краткое описание');
Hint.Show(284, 75, 32, FSL, False, Origin, HintBack);
end;
if IsMouseInRect(321, 75, 353, 107) then
begin
FSL.Clear;
FSL.Append('Ум');
FSL.Append('Краткое описание');
Hint.Show(321, 75, 32, FSL, False, Origin, HintBack);
end;
if IsMouseInRect(358, 75, 390, 107) then
begin
FSL.Clear;
FSL.Append('Дух');
FSL.Append('Краткое описание');
Hint.Show(358, 75, 32, FSL, False, Origin, HintBack);
end;
if IsMouseInRect(205, 120, 395, 140) then
begin
FSL.Clear;
FSL.Append('Урон ' + VM.GetStrInt('Hero.DamageMin') + '-' + VM.GetStrInt('Hero.DamageMax'));
FSL.Append('Дробящий ' + VM.GetStrInt('Hero.Damage.Crash'));
FSL.Append('Режущий ' + VM.GetStrInt('Hero.Damage.Slash'));
FSL.Append('Колющий ' + VM.GetStrInt('Hero.Damage.Pierce'));
FSL.Append('Холодом ' + VM.GetStrInt('Hero.Damage.Ice'));
FSL.Append('Молнией ' + VM.GetStrInt('Hero.Damage.Lightning'));
FSL.Append('Огнем ' + VM.GetStrInt('Hero.Damage.Fire'));
FSL.Append('Ядом ' + VM.GetStrInt('Hero.Damage.Poison'));
FSL.Append('Кислотой ' + VM.GetStrInt('Hero.Damage.Acid'));
Hint.Show(205, 140, 0, FSL, False, Origin, HintBack);
end;
end;
Refresh;
end;
function TSceneChar.Enum: TSceneEnum;
begin
Result := scHero;
end;
function TSceneChar.Click(Button: TMouseBtn): Boolean;
begin
Result := False;
inherited Click(Button);
if IsMouseInRect(210, 75, 242, 107) then AtrUp(1);
if IsMouseInRect(247, 75, 279, 107) then AtrUp(2);
if IsMouseInRect(284, 75, 316, 107) then AtrUp(3);
if IsMouseInRect(321, 75, 353, 107) then AtrUp(4);
if IsMouseInRect(358, 75, 390, 107) then AtrUp(5);
end;
function TSceneChar.Keys(var Key: Word): Boolean;
begin
Result := inherited Keys(Key);
{ case Key of
ord('A'): AtrUp(1);
ord('S'): AtrUp(2);
ord('D'): AtrUp(3);
ord('F'): AtrUp(4);
ord('G'): AtrUp(5);
end; }
end;
procedure TSceneChar.Load;
begin
FIsLoad := True;
FVLine := TBitmap.Create;
Graph.LoadImage('VLine.bmp', FVLine);
FHLine := TBitmap.Create;
Graph.LoadImage('HLine.bmp', FHLine);
end;
procedure TSceneChar.AtrUp(A: Byte);
var
P: Integer;
begin
P := VM.GetInt('Hero.LP');
if (P <= 0) then Exit;
case A of
1: VM.Inc('Hero.Strength');
2: VM.Inc('Hero.Agility');
3: VM.Inc('Hero.Stamina');
4: VM.Inc('Hero.Intellect');
5: VM.Inc('Hero.Spirit');
end;
Run('Calculator.pas');
VM.Dec('Hero.LP');
Sound.PlayClick();
fMain.RefreshBox;
end;
initialization
SceneChar := TSceneChar.Create;
finalization
SceneChar.Free;
end.
|
unit InfoNEWSRCHTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoNEWSRCHRecord = record
PLender: String[4];
PLoanNumber: String[18];
PCIndex: String[1];
PWaived: String[1];
PRank: Integer;
PPriority: Integer;
PShortName: String[30];
PAddressSearch: String[40];
PCollateral: String[100];
PVin: String[85];
PPolicyString: String[30];
End;
TInfoNEWSRCHBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoNEWSRCHRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoNEWSRCH = (InfoNEWSRCHPrimaryKey, InfoNEWSRCHByRankPriority);
TInfoNEWSRCHTable = class( TDBISAMTableAU )
private
FDFLender: TStringField;
FDFLoanNumber: TStringField;
FDFCIndex: TStringField;
FDFWaived: TStringField;
FDFRank: TIntegerField;
FDFPriority: TIntegerField;
FDFShortName: TStringField;
FDFAddressSearch: TStringField;
FDFCollateral: TStringField;
FDFVin: TStringField;
FDFPolicyString: TStringField;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPCIndex(const Value: String);
function GetPCIndex:String;
procedure SetPWaived(const Value: String);
function GetPWaived:String;
procedure SetPRank(const Value: Integer);
function GetPRank:Integer;
procedure SetPPriority(const Value: Integer);
function GetPPriority:Integer;
procedure SetPShortName(const Value: String);
function GetPShortName:String;
procedure SetPAddressSearch(const Value: String);
function GetPAddressSearch:String;
procedure SetPCollateral(const Value: String);
function GetPCollateral:String;
procedure SetPVin(const Value: String);
function GetPVin:String;
procedure SetPPolicyString(const Value: String);
function GetPPolicyString:String;
procedure SetEnumIndex(Value: TEIInfoNEWSRCH);
function GetEnumIndex: TEIInfoNEWSRCH;
protected
procedure CreateFields;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoNEWSRCHRecord;
procedure StoreDataBuffer(ABuffer:TInfoNEWSRCHRecord);
property DFLender: TStringField read FDFLender;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFCIndex: TStringField read FDFCIndex;
property DFWaived: TStringField read FDFWaived;
property DFRank: TIntegerField read FDFRank;
property DFPriority: TIntegerField read FDFPriority;
property DFShortName: TStringField read FDFShortName;
property DFAddressSearch: TStringField read FDFAddressSearch;
property DFCollateral: TStringField read FDFCollateral;
property DFVin: TStringField read FDFVin;
property DFPolicyString: TStringField read FDFPolicyString;
property PLender: String read GetPLender write SetPLender;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PCIndex: String read GetPCIndex write SetPCIndex;
property PWaived: String read GetPWaived write SetPWaived;
property PRank: Integer read GetPRank write SetPRank;
property PPriority: Integer read GetPPriority write SetPPriority;
property PShortName: String read GetPShortName write SetPShortName;
property PAddressSearch: String read GetPAddressSearch write SetPAddressSearch;
property PCollateral: String read GetPCollateral write SetPCollateral;
property PVin: String read GetPVin write SetPVin;
property PPolicyString: String read GetPPolicyString write SetPPolicyString;
published
property Active write SetActive;
property EnumIndex: TEIInfoNEWSRCH read GetEnumIndex write SetEnumIndex;
end; { TInfoNEWSRCHTable }
procedure Register;
implementation
procedure TInfoNEWSRCHTable.CreateFields;
begin
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFCIndex := CreateField( 'CIndex' ) as TStringField;
FDFWaived := CreateField( 'Waived' ) as TStringField;
FDFRank := CreateField( 'Rank' ) as TIntegerField;
FDFPriority := CreateField( 'Priority' ) as TIntegerField;
FDFShortName := CreateField( 'ShortName' ) as TStringField;
FDFAddressSearch := CreateField( 'AddressSearch' ) as TStringField;
FDFCollateral := CreateField( 'Collateral' ) as TStringField;
FDFVin := CreateField( 'Vin' ) as TStringField;
FDFPolicyString := CreateField( 'PolicyString' ) as TStringField;
end; { TInfoNEWSRCHTable.CreateFields }
procedure TInfoNEWSRCHTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoNEWSRCHTable.SetActive }
procedure TInfoNEWSRCHTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TInfoNEWSRCHTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TInfoNEWSRCHTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TInfoNEWSRCHTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TInfoNEWSRCHTable.SetPCIndex(const Value: String);
begin
DFCIndex.Value := Value;
end;
function TInfoNEWSRCHTable.GetPCIndex:String;
begin
result := DFCIndex.Value;
end;
procedure TInfoNEWSRCHTable.SetPWaived(const Value: String);
begin
DFWaived.Value := Value;
end;
function TInfoNEWSRCHTable.GetPWaived:String;
begin
result := DFWaived.Value;
end;
procedure TInfoNEWSRCHTable.SetPRank(const Value: Integer);
begin
DFRank.Value := Value;
end;
function TInfoNEWSRCHTable.GetPRank:Integer;
begin
result := DFRank.Value;
end;
procedure TInfoNEWSRCHTable.SetPPriority(const Value: Integer);
begin
DFPriority.Value := Value;
end;
function TInfoNEWSRCHTable.GetPPriority:Integer;
begin
result := DFPriority.Value;
end;
procedure TInfoNEWSRCHTable.SetPShortName(const Value: String);
begin
DFShortName.Value := Value;
end;
function TInfoNEWSRCHTable.GetPShortName:String;
begin
result := DFShortName.Value;
end;
procedure TInfoNEWSRCHTable.SetPAddressSearch(const Value: String);
begin
DFAddressSearch.Value := Value;
end;
function TInfoNEWSRCHTable.GetPAddressSearch:String;
begin
result := DFAddressSearch.Value;
end;
procedure TInfoNEWSRCHTable.SetPCollateral(const Value: String);
begin
DFCollateral.Value := Value;
end;
function TInfoNEWSRCHTable.GetPCollateral:String;
begin
result := DFCollateral.Value;
end;
procedure TInfoNEWSRCHTable.SetPVin(const Value: String);
begin
DFVin.Value := Value;
end;
function TInfoNEWSRCHTable.GetPVin:String;
begin
result := DFVin.Value;
end;
procedure TInfoNEWSRCHTable.SetPPolicyString(const Value: String);
begin
DFPolicyString.Value := Value;
end;
function TInfoNEWSRCHTable.GetPPolicyString:String;
begin
result := DFPolicyString.Value;
end;
procedure TInfoNEWSRCHTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Lender, String, 4, N');
Add('LoanNumber, String, 18, N');
Add('CIndex, String, 1, N');
Add('Waived, String, 1, N');
Add('Rank, Integer, 0, N');
Add('Priority, Integer, 0, N');
Add('ShortName, String, 30, N');
Add('AddressSearch, String, 40, N');
Add('Collateral, String, 100, N');
Add('Vin, String, 85, N');
Add('PolicyString, String, 30, N');
end;
end;
procedure TInfoNEWSRCHTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Lender;LoanNumber;CIndex, Y, Y, N, N');
Add('ByRankPriority, Rank;Priority, N, N, N, N');
end;
end;
procedure TInfoNEWSRCHTable.SetEnumIndex(Value: TEIInfoNEWSRCH);
begin
case Value of
InfoNEWSRCHPrimaryKey : IndexName := '';
InfoNEWSRCHByRankPriority : IndexName := 'ByRankPriority';
end;
end;
function TInfoNEWSRCHTable.GetDataBuffer:TInfoNEWSRCHRecord;
var buf: TInfoNEWSRCHRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLender := DFLender.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PCIndex := DFCIndex.Value;
buf.PWaived := DFWaived.Value;
buf.PRank := DFRank.Value;
buf.PPriority := DFPriority.Value;
buf.PShortName := DFShortName.Value;
buf.PAddressSearch := DFAddressSearch.Value;
buf.PCollateral := DFCollateral.Value;
buf.PVin := DFVin.Value;
buf.PPolicyString := DFPolicyString.Value;
result := buf;
end;
procedure TInfoNEWSRCHTable.StoreDataBuffer(ABuffer:TInfoNEWSRCHRecord);
begin
DFLender.Value := ABuffer.PLender;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFCIndex.Value := ABuffer.PCIndex;
DFWaived.Value := ABuffer.PWaived;
DFRank.Value := ABuffer.PRank;
DFPriority.Value := ABuffer.PPriority;
DFShortName.Value := ABuffer.PShortName;
DFAddressSearch.Value := ABuffer.PAddressSearch;
DFCollateral.Value := ABuffer.PCollateral;
DFVin.Value := ABuffer.PVin;
DFPolicyString.Value := ABuffer.PPolicyString;
end;
function TInfoNEWSRCHTable.GetEnumIndex: TEIInfoNEWSRCH;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoNEWSRCHPrimaryKey;
if iname = 'BYRANKPRIORITY' then result := InfoNEWSRCHByRankPriority;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoNEWSRCHTable, TInfoNEWSRCHBuffer ] );
end; { Register }
function TInfoNEWSRCHBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..11] of string = ('LENDER','LOANNUMBER','CINDEX','WAIVED','RANK','PRIORITY'
,'SHORTNAME','ADDRESSSEARCH','COLLATERAL','VIN','POLICYSTRING'
);
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 11) and (flist[x] <> s) do inc(x);
if x <= 11 then result := x else result := 0;
end;
function TInfoNEWSRCHBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftInteger;
6 : result := ftInteger;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
end;
end;
function TInfoNEWSRCHBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLender;
2 : result := @Data.PLoanNumber;
3 : result := @Data.PCIndex;
4 : result := @Data.PWaived;
5 : result := @Data.PRank;
6 : result := @Data.PPriority;
7 : result := @Data.PShortName;
8 : result := @Data.PAddressSearch;
9 : result := @Data.PCollateral;
10 : result := @Data.PVin;
11 : result := @Data.PPolicyString;
end;
end;
end.
|
unit uVK_API;
interface
uses
SysUtils, Generics.Collections, IdHTTP, uGnGeneral, Data.DBXJSON,
uGnLog, DateUtils, RegularExpressions, IdException;
type
IHttp = interface
function Get(const AUrl: string): string;
end;
TPost = record
Id, ToId, FromId, Text, CopyOwnerId, CopyPostId, CopyText: string;
DateTime, Date: TDateTime;
Comments, Likes, Reposts: Cardinal;
end;
// comments - содержит информацию о количестве комментариев к записи. Более подробная информация представлена на странице Описание поля comments
// attachments - содержит массив объектов, которые присоединены к текущей записи (фотографии, ссылки и т.п.). Более подробная информация представлена на странице Описание поля attachments
// geo - если в записи содержится информация о местоположении, то она будет представлена в данном поле. Более подробная информация представлена на странице Описание поля geo
// signer_id - если запись была опубликована от имени группы и подписана пользователем, то в поле содержится идентификатор её автора
TPostList = class(TList<TPost>)
private
FNumDays: Word;
public
property NumDay: Word read FNumDays write FNumDays;
end;
TVkGroupType = (gtGroup, gtPage, gtEvent);
TVkGroup = record
Name, Description, Gid, ScreenName, Activity : string;
// IsClosed, IsAdmin, CanPost: Boolean;
// GroupType: TGroupType;
MembersCount, Photos, Albums, Topics, Videos, Audios, Docs: Cardinal;
end;
TVkGroupList = TArray<TVkGroup>;
TVkPage = record
Pid, Title, GroupId, CreatorId, CreatorName, EditorId, EditorName: string;
Created, Edited: TDateTime;
WhoCanView, WhoCanEdit: Byte;
//2 - все, 1 - только участники группы, 0 - только руководители группы.
end;
TVkPageList = TArray<TVkPage>;
TVK = class
strict private
FHttp: IHttp;
FAccessToken: string;
function GetURL(const AMethod: string; AArgs: array of string): string;
function GetVK(const AMethod: string; AArgs: array of string): string;
public
constructor Create(const AAccessToken: string; AHttp: IHttp); reintroduce;
function Pages_GetTitles(const AGid: string): string;
// function Pages_GetId(const AGid, APid: string): string;
function Pages_Get_Title(const AGid, ATitle: string): string;
function Pages_Save_Title(const AGid, ATitle, AText: string): string;
function Pages_SaveAccess(const AGid, APid, AView, AEdit: string): string;
function Groups_GetById(const AGid: string): string;
function Groups_Search(const Aq: string): string;
function Wall_Get(const AOwnerId,
AOffset,
ACount,
AFilter,
AExtended : string
): string;
end;
TVKWrapper = class
strict private
FVK: TVK;
FObj: TJSONObject;
function TestResponse(const AStr: string): Boolean;
function GetResponse(const AStr: string): TJSONValue;
public
constructor Create(const AAccessToken: string; AHttp: IHttp); reintroduce;
destructor Destroy; override;
class function IsLoginStr(const AStr: string): Boolean;
class function IsLoginError(const AStr: string): Boolean;
class function ParseGroupID(const AStr: string): string;
function AddNewPage(const AGid, ATitle, AText: string): string;
function GroupSearch(const Aq: string): TVkGroupList;
function GetGroup(const AGid: string): TVkGroup;
function GetNumberPosts(const AGid: string): Cardinal;
function GetPages(const AGid: string): TVkPageList;
procedure GetPosts(const AGid: string; const ANumDay: Word; APostList: TPostList);
end;
implementation
function UrlEncode(Str: AnsiString): AnsiString;
function CharToHex(Ch: ansiChar): Integer;
asm
and eax, 0FFh
mov ah, al
shr al, 4
and ah, 00fh
cmp al, 00ah
jl @@10
sub al, 00ah
add al, 041h
jmp @@20
@@10:
add al, 030h
@@20:
cmp ah, 00ah
jl @@30
sub ah, 00ah
add ah, 041h
jmp @@40
@@30:
add ah, 030h
@@40:
shl eax, 8
mov al, '%'
end;
var
i, Len: Integer;
Ch: ansiChar;
N: Integer;
P: PansiChar;
begin
Result := '';
Len := Length(Str);
P := PansiChar(@N);
for i := 1 to Len do
begin
Ch := Str[i];
if Ch in ['0'..'9', 'A'..'Z', 'a'..'z', '_'] then
Result := Result + Ch
else
begin
if Ch = ' ' then
Result := Result + '+'
else
begin
N := CharToHex(Ch);
Result := Result + P;
end;
end;
end;
end;
{ TVK }
constructor TVK.Create(const AAccessToken: string; AHttp: IHttp);
begin
inherited Create;
FAccessToken := AAccessToken;
FHttp := AHttp;
end;
function TVK.GetURL(const AMethod: string; AArgs: array of string): string;
var
i: integer;
begin
Result := 'https://api.vk.com/method/' + AMethod;
Result := Result + '?access_token=' + FAccessToken;
i := 0;
while i < Length(AArgs) do
begin
if not IsEmptyStr(AArgs[i + 1]) then
Result := Result + '&' + AArgs[i] + '=' + AArgs[i + 1];
inc(i, 2);
end;
TLog.Log('TVK.GetURL: ' + Result);
end;
function TVK.GetVK(const AMethod: string; AArgs: array of string): string;
begin
Result := FHttp.Get(GetURL(AMethod, AArgs));
TLog.Log('TVK.GetVK: ' + Result);
end;
function TVK.Groups_GetById(const AGid: string): string;
begin
Result := GetVK('groups.getById',
['gid', AGid,
'fields', 'city,country,place,description,'
+ 'wiki_page,members_count,counters,'
+ 'start_date,end_date,can_post,activity'
]);
end;
function TVK.Groups_Search(const Aq: string): string;
begin
Result := GetVK('groups.search',
['q', string(UrlEncode(AnsiToUtf8(Aq))),
'offset', '0',
'count', '50'
]);
end;
function TVK.Pages_Get_Title(const AGid, ATitle: string): string;
begin
Result := GetVK('pages.get', [
'gid', AGid,
'title', string(UrlEncode(AnsiToUtf8(ATitle))),
'need_html', '0'
]);
end;
function TVK.Pages_GetTitles(const AGid: string): string;
begin
Result := GetVK('pages.getTitles',
['gid', AGid]);
end;
function TVK.Pages_SaveAccess(const AGid, APid, AView, AEdit: string): string;
begin
Result := GetVK('pages.saveAccess',
[ 'gid', AGid,
'pid', APid,
'view', AView,
'edit', AEdit
]);
end;
function TVK.Pages_Save_Title(const AGid, ATitle, AText: string): string;
begin
Result := GetVK('pages.save',
[ 'gid', AGid,
'title', string(UrlEncode(AnsiToUtf8(ATitle))),
'Text', string(UrlEncode(AnsiToUtf8(AText)))
]);
end;
function TVK.Wall_Get(const AOwnerId, AOffset, ACount, AFilter,
AExtended: string): string;
begin
Result := GetVK('wall.get',
[ 'owner_id', AOwnerId,
'offset', AOffset,
'count', ACount
]);
end;
{ TVKWrapper }
function TVKWrapper.AddNewPage(const AGid, ATitle, AText: string): string;
var
Response: TJSONValue;
begin
if TestResponse(FVK.Pages_Get_Title(AGid, ATitle)) then
AbortMsg('Станица с таким заголовком уже существует!');
Response := GetResponse(FVK.Pages_Save_Title(AGid, ATitle, AText));
Result := Response.Value;
GetResponse(FVK.Pages_SaveAccess(AGid, Result, '2', '0'));
end;
constructor TVKWrapper.Create(const AAccessToken: string; AHttp: IHttp);
begin
FVK := TVK.Create(AAccessToken, AHttp);
end;
destructor TVKWrapper.Destroy;
begin
FreeAndNil(FVK);
FreeAndNil(FObj);
inherited;
end;
function TVKWrapper.GetGroup(const AGid: string): TVkGroup;
var
Group, Counters: TJSONObject;
Response: TJSONArray;
begin
Response := GetResponse(FVK.Groups_GetById(AGid)) as TJSONArray;
Group := Response.Get(0) as TJSONObject;
Result.Name := Group.Get('name').JsonValue.Value;
Result.Description := Group.Get('description').JsonValue.Value;
Result.Gid := Group.Get('gid').JsonValue.Value;
Result.ScreenName := Group.Get('screen_name').JsonValue.Value;
Result.Activity := Group.Get('activity').JsonValue.Value;
Result.MembersCount := StrToInt(Group.Get('members_count').JsonValue.Value);
Counters := Group.Get('counters').JsonValue as TJSONObject;
Result.Photos := Counters.GetValInt('photos');
Result.Albums := Counters.GetValInt('albums');
Result.Topics := Counters.GetValInt('topics');
Result.Videos := Counters.GetValInt('videos');
Result.Audios := Counters.GetValInt('audios');
Result.Docs := Counters.GetValInt('docs');
end;
function TVKWrapper.GetNumberPosts(const AGid: string): Cardinal;
var
Response: TJSONArray;
begin
Response := GetResponse(FVK.Wall_Get(AGid, '0', '2', '', '')) as TJSONArray;
Result := StrToInt(Response.Get(0).Value);
end;
function TVKWrapper.GetPages(const AGid: string): TVkPageList;
var
i: Integer;
ObjPage: TJSONObject;
Response: TJSONArray;
function ObjToPage(AObj: TJSONObject): TVkPage;
begin
Result.Pid := AObj.GetValStr('pid');
Result.Title := AObj.GetValStr('title');
Result.GroupId := AObj.GetValStr('group_id');
Result.CreatorId := AObj.GetValStr('creator_id');
Result.CreatorName := AObj.GetValStr('creator_name');
Result.EditorId := AObj.GetValStr('editor_id');
Result.EditorName := AObj.GetValStr('editor_name');
// Result.Created := StrToDateTime(); AObj.GetValDateTime('created');
// Result.Edited := AObj.GetValDateTime('edited');
Result.WhoCanView := AObj.GetValInt('who_can_view');
Result.WhoCanEdit := AObj.GetValInt('who_can_edit');
end;
begin
Response := GetResponse(FVK.Pages_GetTitles(AGid)) as TJSONArray;
SetLength(Result, Response.Size);
for i := 0 to Response.Size - 1 do
begin
ObjPage := Response.Get(i) as TJSONObject;
Result[i] := ObjToPage(ObjPage);
end;
end;
procedure TVKWrapper.GetPosts(const AGid: string; const ANumDay: Word;
APostList: TPostList);
var
Response: TJSONArray;
i, Offset: Integer;
Post: TPost;
StartDate, EndDate: TDateTime;
function ObjToPost(AObj: TJSONObject): TPost;
var
Obj: TJSONObject;
begin
Result.Id := AObj.GetValStr('id');
Result.FromId := AObj.GetValStr('from_id');
Result.ToId := AObj.GetValStr('to_id');
Result.Text := AObj.GetValStr('text');
Result.DateTime := UnixToDateTime(StrToInt(AObj.GetValStr('date')));
Result.Date := Trunc(Result.DateTime);
Obj := AObj.Get('likes').JsonValue as TJSONObject;
Result.Likes := StrToInt(Obj.GetValStr('count'));
Obj := AObj.Get('reposts').JsonValue as TJSONObject;
Result.Reposts := StrToInt(Obj.GetValStr('count'));
Obj := AObj.Get('comments').JsonValue as TJSONObject;
Result.Comments := StrToInt(Obj.GetValStr('count'));
end;
begin
StartDate := Date;
EndDate := IncDay(Date, - ANumDay - 1);
APostList.NumDay := ANumDay;
Offset := 0;
Response := GetResponse(FVK.Wall_Get(AGid, IntToStr(Offset), '100', '', '')) as TJSONArray;
while Response.Size > 1 do
begin
for i := 1 to Response.Size - 1 do
begin
Post := ObjToPost(Response.Get(i) as TJSONObject);
if Post.Date <= EndDate then
Exit;
if (Post.Date < StartDate) then
APostList.Add(Post);
end;
Inc(Offset, 100);
Response := GetResponse(FVK.Wall_Get(AGid, IntToStr(Offset), '100', '', '')) as TJSONArray;
end
end;
function TVKWrapper.GetResponse(const AStr: string): TJSONValue;
var
Error: TJSONObject;
begin
FreeAndNil(FObj);
FObj := TJSONObject.ParseJSONValue(AStr) as TJSONObject;
if not Assigned(FObj) then
raise Exception.Create('Ошибка!');
if SameText(FObj.Get(0).JsonString.Value, 'error') then
begin
Error := FObj.Get(0).JsonValue as TJSONObject;
raise Exception.CreateFmt('Получен ответ с ошибкой: code: %s, msg: %s',
[Error.Get('error_code').JsonValue.Value,
Error.Get('error_msg').JsonValue.Value
]);
end;
Result := FObj.Get('response').JsonValue;
end;
function TVKWrapper.GroupSearch(const Aq: string): TVkGroupList;
var
i: Integer;
ObjPage: TJSONObject;
Response: TJSONArray;
function ObjToGroup(AObj: TJSONObject): TVkGroup;
begin
Result.Gid := AObj.GetValStr('gid');
Result.Name := AObj.GetValStr('name');
Result.ScreenName := AObj.GetValStr('screen_name');
// Result.CreatorId := AObj.GetValStr('creator_id');
// Result.CreatorName := AObj.GetValStr('creator_name');
// Result.EditorId := AObj.GetValStr('editor_id');
// Result.EditorName := AObj.GetValStr('editor_name');
// "is_closed":0,
// "type":"page",
// "is_admin":1,
// "is_member":0,
// "photo":"http:\/\/cs4145.userapi.com\/g22545685\/e_004871af.jpg",
// "photo_medium":"http:\/\/cs4145.userapi.com\/g22545685\/d_511a7bae.jpg",
// "photo_big":"http:\/\/cs4145.userapi.com\/g22545685\/a_fdf0fb46.jpg"
end;
begin
Response := GetResponse(FVK.Groups_Search(Aq)) as TJSONArray;
SetLength(Result, Response.Size - 1);
for i := 1 to Response.Size - 1 do
begin
ObjPage := Response.Get(i) as TJSONObject;
Result[i - 1] := ObjToGroup(ObjPage);
end;
end;
class function TVKWrapper.IsLoginStr(const AStr: string): Boolean;
begin
Result := TRegEx.IsMatch(AStr,
'oauth\.vk\.com/blank\.html#access_token=[^&]+&expires_in=\d+&user_id=\d+');
end;
class function TVKWrapper.IsLoginError(const AStr: string): Boolean;
begin
Result := TRegEx.IsMatch(AStr, 'oauth\.vk\.com/blank\.html?error=access_denied');
end;
class function TVKWrapper.ParseGroupID(const AStr: string): string;
var
Match: TMatch;
begin
if TRegEx.IsMatch(AStr, '^\d+$') then
Result := AStr
else
begin
Match := TRegEx.Match(AStr, '-(\d+)_\d+');
if Match.Groups.Count <> 2 then
AbortMsg('Идентификатор сообщества введен неправильно.');
Result := Match.Groups[1].Value;
end;
end;
function TVKWrapper.TestResponse(const AStr: string): Boolean;
var
Error: TJSONObject;
begin
FreeAndNil(FObj);
FObj := TJSONObject.ParseJSONValue(AStr) as TJSONObject;
if not Assigned(FObj) then
raise Exception.Create('Ошибка!');
Result := not SameText(FObj.Get(0).JsonString.Value, 'error');
end;
end.
|
program V_AV;
const DEFAULT_CAP_SIZE = 16;
type
intArray = array[1..1] of integer;
Vector = ^VectorObj;
VectorObj = OBJECT
PRIVATE
arrPtr : ^intArray;
capacityCount : integer;
top : integer; //equals size
initCapacity : integer;
PUBLIC
constructor init(userCapacity : integer);
procedure add(val : integer);
procedure insertElementAt(pos : integer; val : integer);
procedure getElementAt(pos : integer; var val : integer; var ok : boolean);
function size : integer;
function capacity : integer;
procedure clear;
PRIVATE
procedure realloc;
function isOutOfRange(pos : integer) : boolean;
end;
constructor VectorObj.init(userCapacity : integer);
begin
if(arrPtr <> NIL) then begin
writeln('Can''t initialize non-empty stack!');
halt;
end;
if(userCapacity <= 0) then begin
writeLn('No capacity given. Creating with default size ', DEFAULT_CAP_SIZE);
initCapacity := DEFAULT_CAP_SIZE;
end else
initCapacity := userCapacity;
new(arrPtr);
top := 0;
capacityCount := initCapacity;
GetMem(arrPtr, SIZEOF(integer) * capacityCount);
end;
procedure VectorObj.add(val : integer);
begin
if top >= capacityCount then begin
realloc;
end;
inc(top);
(*$R-*)
arrPtr^[top] := val;
(*$R+*)
end;
procedure VectorObj.insertElementAt(pos : integer; val : integer);
var i : integer;
begin
inc(top);
if(isOutOfRange(pos)) then
pos := top
else if pos < 0 then
pos := 0;
i := top;
while (i > pos) do begin
(*$R-*)
arrPtr^[i] := arrPtr^[i-1];
(*$R+*)
dec(i);
end;
(*$R-*)
arrPtr^[pos] := val;
(*$R+*)
end;
procedure VectorObj.getElementAt(pos : integer; var val : integer; var ok : boolean);
begin
ok := TRUE;
if(isOutOfRange(pos)) then begin
ok := FALSE;
val := -1;
exit;
end;
(*$R-*)
val := arrPtr^[pos];
(*$R+*)
end;
function VectorObj.size : integer;
begin
size := top;
end;
function VectorObj.capacity : integer;
begin
capacity := capacityCount;
end;
procedure VectorObj.clear;
begin
if arrPtr = NIL then begin
writeLn('Cannot dispose uninitialized vector!');
halt;
end;
freeMem(arrPtr, SIZEOF(integer) * capacityCount);
arrPtr := NIL;
init(initCapacity);
end;
procedure VectorObj.realloc;
var newArray : ^intArray;
i : integer;
begin
getMem(newArray, SIZEOF(INTEGER) * 2 * capacityCount);
for i := 1 to top do begin
(*$R-*)
newArray^[i] := arrPtr^[i];
(*$R+*)
end;
freeMem(arrPtr, SIZEOF(integer) * capacityCount);
capacityCount := 2 * capacityCount;
arrPtr := newArray;
end;
function VectorObj.isOutOfRange(pos : integer) : boolean;
begin
if pos > top then
isOutOfRange := TRUE
else
isOutOfRange := FALSE
end;
var
intVector : Vector;
i : integer;
tVal : integer;
ok : boolean;
begin
New(intVector, init(4));
writeLn(intVector^.size);
for i := 1 to 40 do begin
intVector^.add(i);
end;
writeLn('Current size: ', intVector^.size);
intVector^.getElementAt(30, tVal, ok);
writeLn('Element 30:', tVal);
writeLn('Current capacity: ', intVector^.capacity);
intVector^.insertElementAt(30, 100);
intVector^.getElementAt(30, tVal, ok);
if(ok) then
writeLn('Element 30:', tVal)
else
writeLn('Ok: ', ok);
intVector^.getElementAt(31, tVal, ok);
if(ok) then
writeLn('Element 31:', tVal)
else
writeLn('Ok: ', ok);
writeLn('Current size: ', intVector^.size);
intVector^.clear;
writeLn('Current size: ', intVector^.size);
intVector^.getElementAt(31, tVal, ok);
if(ok) then
writeLn('Element 31:', tVal)
else
writeLn('Ok: ', ok);
writeLn('Current capacity: ', intVector^.capacity);
end.
|
object fmQuoteConfig: TfmQuoteConfig
Left = 311
Top = 211
BorderStyle = bsDialog
Caption = 'Quote Expert'
ClientHeight = 119
ClientWidth = 287
Color = clBtnFace
ParentFont = True
OldCreateOrder = True
Position = poScreenCenter
Scaled = False
DesignSize = (
287
119)
PixelsPerInch = 96
TextHeight = 13
object gbxStyle: TGroupBox
Left = 9
Top = 9
Width = 269
Height = 64
Anchors = [akLeft, akTop, akRight, akBottom]
Caption = 'Style'
TabOrder = 0
DesignSize = (
269
64)
object lblEndOfLine: TLabel
Left = 16
Top = 27
Width = 56
Height = 13
Caption = 'End Of Line'
end
object cbxEndOfLine: TComboBox
Left = 94
Top = 24
Width = 164
Height = 21
Anchors = [akLeft, akTop, akRight]
ItemHeight = 13
TabOrder = 0
end
end
object btnOK: TButton
Left = 122
Top = 86
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 1
end
object btnCancel: TButton
Left = 203
Top = 86
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 2
end
end
|
unit BaseActionUnit;
interface
uses
IConnectionUnit;
type
TBaseAction = class abstract
protected
FConnection: IConnection;
public
constructor Create(Connection: IConnection);
destructor Destroy; override;
end;
implementation
{ TBaseAction }
constructor TBaseAction.Create(Connection: IConnection);
begin
Inherited Create;
FConnection := Connection;
end;
destructor TBaseAction.Destroy;
begin
FConnection := nil;
inherited;
end;
end.
|
unit UTaskDialogDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.TMSBaseControl, FMX.TMSBaseGroup, FMX.TMSCheckGroup, FMX.TMSTaskDialog,
FMX.Layouts, FMX.ListBox;
type
TForm4 = class(TForm)
TMSFMXTaskDialog1: TTMSFMXTaskDialog;
btShow: TButton;
TMSFMXCheckGroup1: TTMSFMXCheckGroup;
Label1: TLabel;
lbEvents: TListBox;
procedure FormCreate(Sender: TObject);
procedure TMSFMXCheckGroup1CheckBoxChange(Sender: TObject; Index: Integer);
procedure btShowClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Init;
end;
var
Form4: TForm4;
implementation
{$R *.fmx}
procedure TForm4.btShowClick(Sender: TObject);
var
s: string;
begin
TMSFMXTaskDialog1.Show(
procedure(ButtonID: Integer)
begin
case ButtonID of
mrOk: s := 'OK';
mrCancel: s := 'Cancel';
mrYes: s := 'Yes';
mrNo: s := 'No';
else
s := 'Other';
end;
lbEvents.Items.Add(s + ' button clicked');
if TMSFMXTaskDialog1.InputSettings.InputType <> None then
lbEvents.Items.Add('Input text: ' + TMSFMXTaskDialog1.InputSettings.Text);
end
);
end;
procedure TForm4.FormCreate(Sender: TObject);
var
it: TTMSFMXGroupItem;
begin
TMSFMXCheckGroup1.BeginUpdate;
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show verification checkbox';
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show expand/collaps button';
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show title';
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show footer';
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show input';
it := TMSFMXCheckGroup1.Items.Add;
it.Text := 'Show OK/Cancel buttons';
TMSFMXCheckGroup1.CheckAll;
TMSFMXCheckGroup1.EndUpdate;
TMSFMXCheckGroup1.IsChecked[4] := false;
TMSFMXCheckGroup1.IsChecked[5] := false;
TMSFMXTaskDialog1.InstructionText := 'Do you like the TMS TaskDialog for Firemonkey?';
TMSFMXTaskDialog1.Content := 'The <b>TaskDialog for Firemonkey</b> provides an enhanced way for interacting with the user.';
Init;
end;
procedure TForm4.Init;
begin
if TMSFMXCheckGroup1.IsChecked[0] then
TMSFMXTaskDialog1.VerificationText := 'Verification text'
else
TMSFMXTaskDialog1.VerificationText := '';
if TMSFMXCheckGroup1.IsChecked[1] then
TMSFMXTaskDialog1.ExpandedText := '<b><font color="#FF0000">Expanded text</font></b>'
else
TMSFMXTaskDialog1.ExpandedText := '';
if TMSFMXCheckGroup1.IsChecked[2] then
TMSFMXTaskDialog1.Title := 'TaskDialog with expandable text, footer and input'
else
TMSFMXTaskDialog1.Title := '';
if TMSFMXCheckGroup1.IsChecked[3] then
TMSFMXTaskDialog1.FooterText := 'Footer text'
else
TMSFMXTaskDialog1.FooterText := '';
if TMSFMXCheckGroup1.IsChecked[4] then
TMSFMXTaskDialog1.InputSettings.InputType := TFMXInputType.Edit
else
TMSFMXTaskDialog1.InputSettings.InputType := TFMXInputType.None;
if TMSFMXCheckGroup1.IsChecked[5] then
TMSFMXTaskDialog1.CommonButtons := [OK, Cancel]
else
TMSFMXTaskDialog1.CommonButtons := [Yes, No];
end;
procedure TForm4.TMSFMXCheckGroup1CheckBoxChange(Sender: TObject;
Index: Integer);
begin
Init;
end;
end.
|
unit sortalg;
interface
const size = 10; //numbers of elements in the array
type stuRec = record
num : integer;
name : string;
mark : real;
end;
type arr = array[1..size] of stuRec;
procedure bubbleSort(var list : arr; var s : string; n : integer);
procedure selectionSort(var a : arr; var s : string; n : integer);
{procedure insertionSort(var a : arr; var s : string);
procedure insertionSortV2(var a: arr; var s : string);
procedure insertionSortV3(var a : arr; var s : string);}
procedure insertionSortV4(var a : arr; var s : string; n : integer);
{procedure insertionSortV5(var a : arr; var s : string);}
implementation
procedure swap(var a, b: stuRec);
var temp : stuRec;
begin
temp := b;
b := a;
a := temp;
end;
{---------------------------------v--------------------v--------------------------------------------------------------}
procedure bubbleSort(var list : arr; var s : string; n : integer);
(*Bubble sort | pass(i): n-1(can be skipped --> if u can see that there is no swap in a pass, then it is sorted) | round: n*(n-1)/2*)
var i, j : integer;
begin
s := 'Using bubble sort: ';
for i := n - 1 downto 1 do //Alternative: for x := 1 to size - 1 do
begin
for j := 1 to i do // for y := 1 to size - x do
if list[j+1].name < list[j].name then //'<'(ascending) or '>'(desending)????
swap(list[j],list[j+1]);
end;
end;
procedure selectionSort(var a : arr; var s : string; n : integer);
(*OUT OF SYLLBLES*)
var i, j : integer;
position : integer;
num : stuRec;
begin
s := 'Using selection sort: ';
for j := 1 to n-1 do
begin
num := a[j]; //assume the first element is the smallest
position := j; //get its position
for i := j+1 to n do
if a[i].name < num.name then //if a smaller value can be found in the array
begin
num := a[i]; //replace 'num' with that value (this variable is only used for comparision)
position := i; //also replace the position
end;
swap(a[j], a[position]); //swap the array[1, 2, 3, 4, 5] with the smallest value found array[position]
end;
end;
{procedure insertionSort(var a : arr; var s : string);
var sortedPosition, pos : integer;
i, j : integer;
num : integer;
begin
s := 'Using insertion sort(1): ';
for j := 2 to size do
begin
sortedPosition := j;
num := a[j];
pos := 1;
for i := 1 to sortedPosition - 1 do
if a[i] < num then
pos := i + 1;
for i := j-1 downto pos do
a[i+1] := a[i];
a[pos] := num;
//printPass(a);
end;
end; }
{procedure insertionSortV2(var a: arr; var s : string);
var pos : integer;
i, j : integer;
num : integer;
begin
s := 'Using insertion sort(2): ';
for j := 2 to size do
begin
num := a[j];
pos := j;
for i := pos - 1 downto 1 do
if a[i] > num then
begin
pos := i;
a[i+1] := a[i];
end;
a[pos] := num;
//printPass(a);
end;
end; }
{procedure insertionSortV3(var a : arr; var s : string);
var pos : integer;
i, j : integer;
num : integer;
begin
s := 'Using insertion sort(3): ';
for j := 2 to size do
begin
num := a[j];
pos := j;
i := pos - 1;
while (i >= 1) and (num < a[i]) do
begin
pos := i;
a[i+1] := a[i];
i := i - 1;
end;
a[pos] := num;
//printPass(a);
end;
end; }
procedure insertionSortV4(var a : arr; var s : string; n : integer);
{V4 and V5 are both ok}
var i : integer;
position : integer;
num : stuRec;
begin
s := 'Using insertion sort(4): ';
for i := 2 to n do
begin
num := a[i];
position := i;
while (position > 1) and (a[position-1].name > num.name) do // > means the array will be sorted in ascending order
begin
a[position] := a[position-1];
position := position - 1;
end;
a[position] := num;
end;
end;
{procedure insertionSortV5(var a : arr; var s : string);
pass : n-1(cannot be skipped)
var i : integer;
num, position : integer;
begin
s := 'Using insertion sort(5): ';
for i := 2 to size do
begin
num := a[i];
position := i - 1;
while (position >= 1) and (a[position] > num) do
begin
a[position+1] := a[position];
position := position - 1;
end;
a[position+1] := num;
//printPass(a);
end;
end; }
end.
|
unit evCommentParaDecorator;
{* Фильтр, довешивающий комментариям юристов специфическое оформление. [$140285546] }
// Модуль: "w:\common\components\gui\Garant\Everest\evCommentParaDecorator.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevCommentParaDecorator" MUID: (49E48A670254)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evdLeafParaFilter
, l3Variant
;
type
TevCheckStyle = (
ev_cstNone
, ev_cstTxtComment
, ev_cstVerComment
);//TevCheckStyle
TevCommentParaDecorator = class(TevdLeafParaFilter)
{* Фильтр, довешивающий комментариям юристов специфическое оформление. [$140285546] }
private
f_CheckComment: TevCheckStyle;
protected
procedure OpenStream; override;
{* вызывается один раз при начале генерации. Для перекрытия в потомках. }
procedure DoWritePara(aLeaf: Tl3Variant); override;
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
end;//TevCommentParaDecorator
implementation
uses
l3ImplUses
, evdStyles
, k2Tags
, TextPara_Const
, Graphics
, nevInterfaces
//#UC START# *49E48A670254impl_uses*
//#UC END# *49E48A670254impl_uses*
;
procedure TevCommentParaDecorator.OpenStream;
{* вызывается один раз при начале генерации. Для перекрытия в потомках. }
//#UC START# *4836D49800CA_49E48A670254_var*
//#UC END# *4836D49800CA_49E48A670254_var*
begin
//#UC START# *4836D49800CA_49E48A670254_impl*
inherited;
f_CheckComment := ev_cstNone;
//#UC END# *4836D49800CA_49E48A670254_impl*
end;//TevCommentParaDecorator.OpenStream
procedure TevCommentParaDecorator.DoWritePara(aLeaf: Tl3Variant);
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
//#UC START# *49E4883E0176_49E48A670254_var*
procedure lp_OutStyleDecor;
begin
Generator.StartChild(k2_typTextPara);
try
Generator.AddIntegerAtom(k2_tiStyle, ev_saTxtComment);
Generator.AddStringAtom(k2_tiText, aLeaf.Attr[k2_tiStyle].PCharLenA[k2_tiShortName]);
// - http://mdp.garant.ru/pages/viewpage.action?pageId=297712959
Generator.StartTag(k2_tiFont);
try
Generator.AddIntegerAtom(k2_tiForeColor, clBlack);
Generator.AddIntegerAtom(k2_tiSize, 8);
finally
Generator.Finish;
end;//try..finally
finally
Generator.Finish;
end;//try..finally
end;
var
l_Style: Integer;
//#UC END# *49E4883E0176_49E48A670254_var*
begin
//#UC START# *49E4883E0176_49E48A670254_impl*
l_Style := aLeaf.IntA[k2_tiStyle];
if (l_Style = ev_saTxtComment) then
begin
if (f_CheckComment = ev_cstVerComment) or (f_CheckComment = ev_cstNone) then
begin
f_CheckComment := ev_cstTxtComment;
lp_OutStyleDecor;
end; // if (f_CheckComment = ev_cstVerComment) or (f_CheckComment = ev_cstNone) then
end
else
if (l_Style = ev_saVersionInfo) then
begin
if (f_CheckComment = ev_cstTxtComment) or (f_CheckComment = ev_cstNone) then
begin
f_CheckComment := ev_cstVerComment;
lp_OutStyleDecor;
end; // if (f_CheckComment = ev_cstVerComment) or (f_CheckComment = ev_cstNone) then
end
else
f_CheckComment := ev_cstNone;
inherited;
//#UC END# *49E4883E0176_49E48A670254_impl*
end;//TevCommentParaDecorator.DoWritePara
end.
|
unit OverbyteIcsHttpCCodZLib;
interface
{$I OverbyteIcsZlib.inc}
uses
Classes,
OverbyteIcsHttpContCod,
OverbyteIcsZlibHigh,
{$IFDEF USE_ZLIB_OBJ}
OverbyteIcsZLibObj; {interface to access ZLIB C OBJ files}
{$ELSE}
OverbyteIcsZLibDll; {interface to access zLib1.dll}
{$ENDIF}
type
THttpCCodzlib = class(THttpContentCoding)
private
FStream: TMemoryStream;
protected
class function GetActive: Boolean; override;
class function GetCoding: String; override;
public
constructor Create(WriteBufferProc: TWriteBufferProcedure); override;
destructor Destroy; override;
procedure Complete; override;
procedure WriteBuffer(Buffer: Pointer; Count: Integer); override;
end;
implementation
{ THttpCCodzlib }
constructor THttpCCodzlib.Create(WriteBufferProc: TWriteBufferProcedure);
begin
inherited Create(WriteBufferProc);
FStream := TMemoryStream.Create;
end;
destructor THttpCCodzlib.Destroy;
begin
FStream.Free;
inherited Destroy;
end;
class function THttpCCodzlib.GetActive: Boolean;
begin
Result := ZlibGetDllLoaded and (Pos('1.2', String(ZlibGetVersionDll)) = 1);
end;
class function THttpCCodzlib.GetCoding: String;
begin
Result := 'gzip';
end;
{ this version writes an uncompressed stream, that's then copied to the content stream
procedure THttpCCodzlib.Complete;
var
OutStream: TMemoryStream;
begin
OutStream := TMemoryStream.Create;
try
FStream.Position := 0;
ZlibDecompressStream (FStream, OutStream) ;
OutputWriteBuffer(OutStream.Memory, OutStream.Size);
finally
OutStream.Free;
end ;
end; }
function Strm_Write(BackObj: PZBack; buf: PByte; size: Integer): Integer; cdecl;
begin
THttpCCodzlib (BackObj.MainObj).OutputWriteBuffer(buf, size) ;
Result := 0 ; // assume we wrote all the data OK
end;
{ this version does not use an uncompress stream, but writes the content
stream a block at a time, it handles gzip, zlib or raw streams }
procedure THttpCCodzlib.Complete;
var
strm: z_stream;
BackObj: PZBack;
begin
FStream.Position := 0;
FillChar (strm, sizeof(strm), 0);
GetMem (BackObj, SizeOf(BackObj^));
try
BackObj.InMem := FStream.Memory; //direct memory access
BackObj.InStream := FStream;
BackObj.OutStream := Nil ; // not used
BackObj.MainObj := Self;
BackObj.ProgressCallback := nil;
//use our own function for reading
strm.avail_in := Strm_in_func (BackObj, PByte(strm.next_in));
strm.next_out := @BackObj.Window; // buffer
strm.avail_out := 0;
ZlibCheckInitInflateStream (strm, nil); // returns stream type which we ignore
strm.next_out := nil;
strm.avail_out := 0;
ZlibDCheck (inflateBackInit (strm, MAX_WBITS, BackObj.Window));
try
ZlibDCheck (inflateBack (strm, @Strm_in_func, BackObj,
@Strm_Write, BackObj));
//seek back when unused data
FStream.Seek (-strm.avail_in, soFromCurrent);
//now trailer can be checked
finally
ZlibDCheck (inflateBackEnd (strm));
end;
finally
FreeMem (BackObj);
end;
end ;
procedure THttpCCodzlib.WriteBuffer(Buffer: Pointer; Count: Integer);
begin
FStream.WriteBuffer(Buffer^, Count);
end;
initialization
THttpContCodHandler.RegisterContentCoding(1, THttpCCodzlib);
finalization
THttpContCodHandler.UnregisterAuthenticateClass(THttpCCodzlib);
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
{ Rev 1.4 28.09.2004 21:04:44 Andreas Hausladen
{ Delphi 5 does not have a Owner property in TCollection
}
{
{ Rev 1.3 24.08.2004 18:01:42 Andreas Hausladen
{ Added AttachmentBlocked property to TIdAttachmentFile.
}
{
{ Rev 1.2 2004.02.03 5:44:50 PM czhower
{ Name changes
}
{
Rev 1.1 5/9/2003 10:27:20 AM BGooijen
Attachment is now opened in fmShareDenyWrite mode
}
{
{ Rev 1.0 11/14/2002 02:12:42 PM JPMugaas
}
unit IdAttachmentFile;
interface
uses
IdAttachment,
IdMessageParts,
IdObjs,
IdSys;
type
TIdAttachmentFile = class(TIdAttachment)
protected
FTempFileStream: TIdFileStream;
FStoredPathName: String;
FFileIsTempFile: Boolean;
FAttachmentBlocked: Boolean;
public
constructor Create(Collection: TIdMessageParts; const AFileName: String = ''); reintroduce;
destructor Destroy; override;
function OpenLoadStream: TIdStream; override;
procedure CloseLoadStream; override;
function PrepareTempStream: TIdStream; override;
procedure FinishTempStream; override;
procedure SaveToFile(const FileName: String); override;
property FileIsTempFile: Boolean read FFileIsTempFile write FFileIsTempFile;
property StoredPathName: String read FStoredPathName write FStoredPathName;
property AttachmentBlocked: Boolean read FAttachmentBlocked;
end;
implementation
uses
IdGlobal, IdGlobalProtocols, IdException, IdResourceStringsProtocols,
IdMessage;
{ TIdAttachmentFile }
procedure TIdAttachmentFile.CloseLoadStream;
begin
Sys.FreeAndNil(FTempFileStream);
end;
constructor TIdAttachmentFile.Create(Collection: TIdMessageParts; const AFileName: String = '');
begin
inherited Create(Collection);
FFilename := Sys.ExtractFilename(AFilename);
FTempFileStream := nil;
FStoredPathName := AFileName;
FFileIsTempFile := False;
end;
destructor TIdAttachmentFile.Destroy;
begin
if FileIsTempFile then begin
Sys.DeleteFile(StoredPathName);
end;
inherited Destroy;
end;
procedure TIdAttachmentFile.FinishTempStream;
begin
Sys.FreeAndNil(FTempFileStream);
// An on access virus scanner meight delete/block the temporary file.
FAttachmentBlocked := not Sys.FileExists(StoredPathName);
if FAttachmentBlocked and TIdMessage(TIdMessageParts(Collection).OwnerMessage).ExceptionOnBlockedAttachments then
begin
raise EIdMessageCannotLoad.Create(Sys.Format(RSTIdMessageErrorAttachmentBlocked, [StoredPathName]));
end;
end;
function TIdAttachmentFile.OpenLoadStream: TIdStream;
begin
FTempFileStream := TReadFileExclusiveStream.Create(StoredPathName);
Result := FTempFileStream;
end;
function TIdAttachmentFile.PrepareTempStream: TIdStream;
begin
if Assigned(Collection) and (TIdMessageParts(Collection).OwnerMessage is TIdMessage) then
FStoredPathName := MakeTempFilename(TIdMessage(TIdMessageParts(Collection).OwnerMessage).AttachmentTempDirectory)
else
FStoredPathName := MakeTempFilename();
FTempFileStream := TIdFilestream.Create(FStoredPathName, fmCreate);
Result := FTempFileStream;
FFileIsTempFile := True;
end;
procedure TIdAttachmentFile.SaveToFile(const FileName: String);
begin
if not CopyFileTo(StoredPathname, FileName) then begin
raise EIdException.Create(RSTIdMessageErrorSavingAttachment);
end;
end;
initialization
// MtW: Shouldn't be neccessary??
// RegisterClass(TIdAttachmentFile);
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIAsn1Sequence;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIProxiedInterface,
ClpIAsn1SequenceParser,
ClpCryptoLibTypes;
type
IAsn1Sequence = interface(IAsn1Object)
['{37A263B7-6724-422B-9B4C-08EBA272045F}']
function GetCount: Int32;
function GetParser: IAsn1SequenceParser;
function GetSelf(Index: Integer): IAsn1Encodable;
function GetCurrent(const e: IAsn1Encodable): IAsn1Encodable;
procedure AddObject(const obj: IAsn1Encodable);
function ToString(): String;
function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>;
property Self[Index: Int32]: IAsn1Encodable read GetSelf; default;
property Parser: IAsn1SequenceParser read GetParser;
property Count: Int32 read GetCount;
end;
type
IAsn1SequenceParserImpl = interface(IAsn1SequenceParser)
['{B986EDD8-A7F3-4E9C-9D5B-2FF9120D9A91}']
end;
implementation
end.
|
unit l3DataObjectEnum;
{* Реализация итератора для данных Tl3DataObject. }
// Модуль: "w:\common\components\rtl\Garant\L3\l3DataObjectEnum.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tl3DataObjectEnum" MUID: (4680F5FF01EA)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, l3Interfaces
, l3DataObject
, Windows
, ActiveX
;
type
Tl3DataObjectEnum = class(Tl3ProtoObject, IEnumFormatEtc)
{* Реализация итератора для данных Tl3DataObject. }
private
f_DataObject: Tl3DataObject;
f_Index: Integer;
protected
function Next(celt: Integer;
out elt;
pceltFetched: PLongint): HResult; stdcall;
function Skip(celt: Integer): HResult; stdcall;
function Reset: HResult; stdcall;
function Clone(out Enum: IEnumFORMATETC): HResult; stdcall;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
class function Make(aDataObject: Tl3DataObject): IEnumFormatEtc; reintroduce;
constructor Create(aDataObject: Tl3DataObject); reintroduce;
end;//Tl3DataObjectEnum
implementation
uses
l3ImplUses
, l3MinMax
, SysUtils
//#UC START# *4680F5FF01EAimpl_uses*
//#UC END# *4680F5FF01EAimpl_uses*
;
class function Tl3DataObjectEnum.Make(aDataObject: Tl3DataObject): IEnumFormatEtc;
var
l_Inst : Tl3DataObjectEnum;
begin
l_Inst := Create(aDataObject);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tl3DataObjectEnum.Make
constructor Tl3DataObjectEnum.Create(aDataObject: Tl3DataObject);
//#UC START# *48F33CE302EC_4680F5FF01EA_var*
//#UC END# *48F33CE302EC_4680F5FF01EA_var*
begin
//#UC START# *48F33CE302EC_4680F5FF01EA_impl*
inherited Create;
aDataObject.SetRefTo(f_DataObject);
//#UC END# *48F33CE302EC_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Create
function Tl3DataObjectEnum.Next(celt: Integer;
out elt;
pceltFetched: PLongint): HResult;
//#UC START# *48F33755005D_4680F5FF01EA_var*
var
l_Index : Integer;
l_P : PFormatEtc;
l_Tail : Integer;
//#UC END# *48F33755005D_4680F5FF01EA_var*
begin
//#UC START# *48F33755005D_4680F5FF01EA_impl*
if (f_DataObject = nil) OR (celt <= 0) then
Result := E_NotImpl
else
begin
l_P := @elt;
with f_DataObject do
begin
l_Tail := Min(Pred(f_Index + celt), Formats.Hi);
if (pceltFetched <> nil) then
pceltFetched^ := Succ(l_Tail - f_Index);
if (f_Index > l_Tail) then
Result := S_False
else
begin
Result := S_Ok;
for l_Index := f_Index to l_Tail do
begin
with l_P^ do
begin
cfFormat := Formats[l_Index];
ptd := nil;
dwAspect := DVASPECT_CONTENT;
lindex := -1;
if (cfFormat = CF_Locale) then
tymed := TYMED_HGLOBAL
else
tymed := AcceptableTymed;
end;//with l_P
Inc(l_P);
Inc(f_Index);
end;//for l_Index
end;//f_Index > l_Tail
end;//f_DataObject
end;//f_DataObject = nil
//#UC END# *48F33755005D_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Next
function Tl3DataObjectEnum.Skip(celt: Integer): HResult;
//#UC START# *48F33790021D_4680F5FF01EA_var*
//#UC END# *48F33790021D_4680F5FF01EA_var*
begin
//#UC START# *48F33790021D_4680F5FF01EA_impl*
Inc(f_Index, celt);
if (f_DataObject = nil) OR (f_Index > f_DataObject.Formats.Hi) then
Result := S_False
else
Result := S_Ok;
//#UC END# *48F33790021D_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Skip
function Tl3DataObjectEnum.Reset: HResult;
//#UC START# *48F337A20394_4680F5FF01EA_var*
//#UC END# *48F337A20394_4680F5FF01EA_var*
begin
//#UC START# *48F337A20394_4680F5FF01EA_impl*
Result := S_Ok;
f_Index := 0;
//#UC END# *48F337A20394_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Reset
function Tl3DataObjectEnum.Clone(out Enum: IEnumFORMATETC): HResult;
//#UC START# *48F337B1039E_4680F5FF01EA_var*
//#UC END# *48F337B1039E_4680F5FF01EA_var*
begin
//#UC START# *48F337B1039E_4680F5FF01EA_impl*
Result := E_NotImpl;
//#UC END# *48F337B1039E_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Clone
procedure Tl3DataObjectEnum.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4680F5FF01EA_var*
//#UC END# *479731C50290_4680F5FF01EA_var*
begin
//#UC START# *479731C50290_4680F5FF01EA_impl*
FreeAndNil(f_DataObject);
inherited;
//#UC END# *479731C50290_4680F5FF01EA_impl*
end;//Tl3DataObjectEnum.Cleanup
end.
|
unit VisioUtils;
interface
uses Classes,Variants,ActiveX, ComObj,
Visio_TLB,
ResourceUtils, MainUtils;
type
TVisioConverter = Class(TDocumentConverter)
Private
FVSVersion : String;
VisioApp : OleVariant;
public
constructor Create();
function CreateOfficeApp() : boolean; override;
function DestroyOfficeApp() : boolean; override;
function ExecuteConversion(fileToConvert: String; OutputFilename: String; OutputFileFormat : Integer): TConversionInfo; override;
function AvailableFormats() : TStringList; override;
function FormatsExtensions(): TStringList; override;
function OfficeAppVersion() : String; override;
End;
implementation
{ TVisioConverter }
function TVisioConverter.AvailableFormats: TStringList;
begin
Formats := TResourceStrings.Create('VSFORMATS');
result := Formats;
end;
constructor TVisioConverter.Create;
begin
inherited;
//setup defaults
InputExtension := '.vsd*';
OfficeAppName := 'Visio';
end;
function TVisioConverter.CreateOfficeApp: boolean;
begin
if VarIsEmpty(VisioApp) then
begin
VisioApp := CreateOleObject('Visio.Application');
VisioApp.Visible := false;
end;
Result := true;
end;
function TVisioConverter.DestroyOfficeApp: boolean;
begin
if not VarIsEmpty(VisioApp) then
begin
VisioApp.Quit;
end;
Result := true;
end;
function TVisioConverter.ExecuteConversion(
fileToConvert,
OutputFilename: String;
OutputFileFormat: Integer): TConversionInfo;
var
ActiveVisioDoc : OleVariant;
Format: integer;
begin
Result.Successful := false;
Result.InputFile := fileToConvert;
// Open file
ActiveVisioDoc := VisioApp.Documents.Open(fileToConvert);
// Save as file and close
if OutputFileFormat = 50000 then
begin
Format := visFixedFormatPDF;
end else if OutputFileFormat = 50001 then
begin
Format := visFixedFormatXPS;
end;
ActiveVisioDoc.ExportAsFixedFormat(Format, //FixedFormat
OutputFilename, //OutputFileName
visDocExIntentPrint, //Intent
visPrintAll, //PrintRange
emptyParam, //FromPage
emptyParam, //ToPage
emptyParam, //ColorAsBlack
emptyParam, //IncludeBackground
IncludeDocProps, //IncludeDocumentProperties
DocStructureTags, //IncludeStructureTags
Self.useISO190051); //UseISO19005_1
//FixedFormatExtClass //
ActiveVisioDoc.Close;
Result.InputFile := fileToConvert;
Result.Successful := true;
Result.OutputFile := OutputFilename;
end;
function TVisioConverter.FormatsExtensions: TStringList;
begin
fFormatsExtensions := TResourceStrings.Create('VSEXTENSIONS');
result := fFormatsExtensions;
end;
function TVisioConverter.OfficeAppVersion: String;
begin
FVSVersion := ReadOfficeAppVersion;
if FVSVersion = '' then
begin
CreateOfficeApp();
FVSVersion := VisioApp.Version;
WriteOfficeAppVersion(FVSVersion);
end;
result := FVSVersion;
end;
end.
|
unit uProspectVO;
interface
type
TProspectVO = class
private
FFantasia: string;
FAtivo: Boolean;
FIdUsuario: Integer;
FCodigo: Integer;
FId: Integer;
FIdRevenda: Integer;
FContato: string;
FEnquadramento: string;
FDocto: string;
FNome: string;
FEndereco: string;
FTelefone: string;
procedure SetAtivo(const Value: Boolean);
procedure SetCodigo(const Value: Integer);
procedure SetContato(const Value: string);
procedure SetDocto(const Value: string);
procedure SetEndereco(const Value: string);
procedure SetEnquadramento(const Value: string);
procedure SetFantasia(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdRevenda(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
procedure SetNome(const Value: string);
procedure SetTelefone(const Value: string);
public
property Id: Integer read FId write SetId;
property Nome: string read FNome write SetNome;
property Fantasia: string read FFantasia write SetFantasia;
property Docto: string read FDocto write SetDocto;
property Enquadramento: string read FEnquadramento write SetEnquadramento;
property Endereco: string read FEndereco write SetEndereco;
property Telefone: string read FTelefone write SetTelefone;
property Contato: string read FContato write SetContato;
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
property IdRevenda: Integer read FIdRevenda write SetIdRevenda;
property Ativo: Boolean read FAtivo write SetAtivo;
property Codigo: Integer read FCodigo write SetCodigo;
end;
implementation
{ TProspectVO }
procedure TProspectVO.SetAtivo(const Value: Boolean);
begin
FAtivo := Value;
end;
procedure TProspectVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TProspectVO.SetContato(const Value: string);
begin
FContato := Value;
end;
procedure TProspectVO.SetDocto(const Value: string);
begin
FDocto := Value;
end;
procedure TProspectVO.SetEndereco(const Value: string);
begin
FEndereco := Value;
end;
procedure TProspectVO.SetEnquadramento(const Value: string);
begin
FEnquadramento := Value;
end;
procedure TProspectVO.SetFantasia(const Value: string);
begin
FFantasia := Value;
end;
procedure TProspectVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TProspectVO.SetIdRevenda(const Value: Integer);
begin
FIdRevenda := Value;
end;
procedure TProspectVO.SetIdUsuario(const Value: Integer);
begin
FIdUsuario := Value;
end;
procedure TProspectVO.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TProspectVO.SetTelefone(const Value: string);
begin
FTelefone := Value;
end;
end.
|
unit UUndo;
interface
uses
Math;
type
RUndo = record
xcord: word;
ycord: word;
Layer: byte; // 0 - idx, 1- dcr, 2-obj, 3-item
idx: integer; // for undo
redx: Integer; // for redo
group: Integer;
end;
T2IntEvent = procedure(a, b: Integer) of object;
T4IntEvent = procedure(a, b, c, d: Integer) of object;
TUndo = class(TObject) // tcomponent ancestor for autodestruction
private
OnChange: T4IntEvent;
OnDraw: T2IntEvent;
AUndol: Cardinal;
FCurUndo: Cardinal;
Aundo: array of RUndo;
FCurGroup: Cardinal;
InGroup: Boolean;
MaxGroup: Cardinal;
MaxUndo: Cardinal;
procedure setundo(const Value: cardinal);
procedure SetGroup(const Value: Cardinal);
property Curgroup: Cardinal read FCurGroup write SetGroup;
public
constructor Create(changeevt: T4IntEvent; drawevt: T2IntEvent);
procedure Clear;
property curundo: cardinal read fcurundo write setundo;
procedure Add(xcord, ycord, Layer, Idx, redx: Word);
procedure StartGroup();
procedure EndGroup();
procedure Undo;
procedure Redo;
end;
function BuildUndo(xcord, ycord, Layer, idx, redx, group: Integer): RUndo;
implementation
function BuildUndo(xcord, ycord, Layer, idx, redx, group: Integer): RUndo;
begin
Result.xcord := xcord;
Result.ycord := ycord;
Result.Layer := Layer;
Result.idx := idx;
Result.redx := redx;
Result.group := group;
end;
{ Tundo }
procedure TUndo.Add(xcord, ycord, Layer, Idx, redx: Word);
begin
if MaxUndo = curundo then
MaxUndo := curundo + 1;
curundo := curundo + 1;
if (Curgroup < MaxGroup) then
MaxGroup := Curgroup; // for clearing all redos on adding after undo
if not InGroup then
CurGroup := CurGroup + 1;
AUndo[curundo] := BuildUndo(xcord, ycord, Layer, Idx, redx, CurGroup);
end;
procedure TUndo.Clear;
begin
FCurGroup := 0;
curundo := 0;
aundol := 0;
setlength(aundo, aundol);
end;
constructor TUndo.Create(changeevt: T4IntEvent; drawevt: T2IntEvent);
begin
inherited Create();
OnDraw := drawevt;
OnChange := changeevt;
end;
procedure TUndo.EndGroup;
begin
InGroup := False;
end;
procedure Tundo.Redo;
var
Cur: Cardinal;
begin
if not Assigned(OnChange) or not Assigned(OnDraw) or (Curgroup = MaxGroup) then
exit;
CurGroup := CurGroup + 1;
repeat
with aundo[curundo] do
begin // restore changes via redo
OnChange(xcord, ycord, Layer, redx);
OnDraw(xcord, ycord); // draw tile on a grid
end;
curundo := curundo + 1;
until (aundo[curundo].group <> CurGroup) or (Curundo = Maxundo);
end;
procedure TUndo.SetGroup(const Value: Cardinal);
begin
if value = -1 then
Exit;
if (Curgroup = MaxGroup) and (Value - Curgroup = 1) then
MaxGroup := Value;
FCurGroup := Value;
end;
procedure Tundo.setundo(const Value: cardinal);
begin
if Value > maxundo then
Exit;
fcurundo := value;
if aundol <= Value then
begin // increase undolimit
inc(aundol, 100);
setlength(aundo, aundol);
end;
end;
procedure TUndo.StartGroup;
begin
Curgroup := Curgroup + 1;
InGroup := True;
end;
procedure Tundo.Undo;
begin
if (curundo = 0) or not Assigned(OnChange) or not Assigned(OnDraw) then
exit;
while aundo[curundo].group = CurGroup do
with aundo[curundo] do
begin // restore changes via undo
curundo := curundo - 1;
OnChange(xcord, ycord, Layer, idx);
OnDraw(xcord, ycord); // draw tile on a grid
end;
CurGroup := CurGroup - 1;
end;
end.
|
unit ElRadioButtonDemoMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ElImgFrm, StdCtrls, ElACtrls, ElBtnEdit, ElXPThemedControl, ElBtnCtl,
ElCheckCtl, ElVCLUtils, ElSpin, ElImgLst, ImgList, ElEdits, ElCombos;
type
TElRadioButtonDemoMainForm = class(TForm)
Label9: TLabel;
ElRadioButtonTextTypeCombo: TElComboBox;
Label8: TLabel;
ElRadioButtonTextButtonEdit: TElButtonEdit;
ElRadioButtonImageForm: TElImageForm;
Label6: TLabel;
ElRadioButtonImageTypeCombo: TElComboBox;
ElRadioButtonUseImageFormCB: TElCheckBox;
ElRadioButtonFlatCB: TElCheckBox;
ElRadioButtonTextHTMLCB: TElCheckBox;
ElRadioButtonAutosizeCB: TElCheckBox;
ElRadioButtonGlyphs: TElImageList;
Label2: TLabel;
ElRadioButtonAlignmentCombo: TElComboBox;
sampleElRadioButton: TElRadioButton;
ElRadioButtonUseXPThemesCB: TElCheckBox;
procedure ElRadioButtonTextButtonEditButtonClick(Sender: TObject);
procedure ElRadioButtonTextTypeComboChange(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ElRadioButtonTextHTMLCBClick(Sender: TObject);
procedure ElRadioButtonImageTypeComboChange(Sender: TObject);
procedure ElRadioButtonAutosizeCBClick(Sender: TObject);
procedure ElRadioButtonUseImageFormCBClick(Sender: TObject);
procedure ElRadioButtonAlignmentComboChange(Sender: TObject);
procedure ElRadioButtonFlatCBClick(Sender: TObject);
procedure ElRadioButtonUseXPThemesCBClick(Sender: TObject);
private
NotFirstTime : boolean;
public
{ Public declarations }
end;
var
ElRadioButtonDemoMainForm: TElRadioButtonDemoMainForm;
implementation
{$R *.DFM}
procedure TElRadioButtonDemoMainForm.ElRadioButtonTextButtonEditButtonClick(
Sender: TObject);
begin
sampleElRadioButton.Caption := ElRadioButtonTextButtonEdit.Text;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonTextTypeComboChange(
Sender: TObject);
begin
sampleElRadioButton.TextDrawType := TElTextDrawType(ElRadioButtonTextTypeCombo.ItemIndex);
end;
procedure TElRadioButtonDemoMainForm.FormActivate(Sender: TObject);
begin
if not NotFirstTime then
begin
ElRadioButtonAlignmentCombo.ItemIndex := 1;
ElRadioButtonImageTypeCombo.ItemIndex := 0;
ElRadioButtonTextTypeCombo.ItemIndex := 0;
end;
NotFirstTime := true;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonTextHTMLCBClick(
Sender: TObject);
begin
SampleElRadioButton.IsHTML := ElRadioButtonTextHTMLCB.Checked;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonImageTypeComboChange(
Sender: TObject);
begin
case ElRadioButtonImageTypeCombo.ItemIndex of
0: begin
sampleElRadioButton.UseCustomGlyphs := false;
sampleElRadioButton.UseImageList := false;
end;
1: begin
sampleElRadioButton.UseCustomGlyphs := true;
sampleElRadioButton.UseImageList := false;
end;
2: begin
sampleElRadioButton.UseCustomGlyphs := false;
sampleElRadioButton.UseImageList := true;
end;
end;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonAutosizeCBClick(
Sender: TObject);
begin
sampleElRadioButton.AutoSize := ElRadioButtonAutosizeCB.Checked;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonUseImageFormCBClick(
Sender: TObject);
begin
if ElRadioButtonUseImageFormCB.Checked then
ElRadioButtonImageForm.Backgroundtype := bgtTileBitmap
else
ElRadioButtonImageForm.Backgroundtype := bgtColorFill;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonAlignmentComboChange(
Sender: TObject);
begin
sampleElRadioButton.CheckAlignment := TLeftRight(ElRadioButtonAlignmentCombo.ItemIndex);
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonFlatCBClick(Sender: TObject);
begin
SampleElRadioButton.Flat := ElRadioButtonFlatCB.Checked;
end;
procedure TElRadioButtonDemoMainForm.ElRadioButtonUseXPThemesCBClick(
Sender: TObject);
begin
SampleElRadioButton.UseXPThemes := ElRadioButtonUseXPThemesCB.Checked;
end;
end.
|
(**
This module contains a class which imlements the INTAAddInOptions interface to provide
an options page within the IDEs options dialogue.
@Version 1.0
@Author David Hoyle
@Date 28 Mar 2016
**)
Unit IDEOptionsInterface;
Interface
Uses
ToolsAPI,
Forms,
DGHIDEHelpHelperOptionsFrame;
{$INCLUDE CompilerDefinitions.inc}
{$IFDEF DXE00}
Type
(** A class to create an options frame page for the IDEs options dialogue. **)
TIDEHelpHelperIDEOptionsInterface = Class(TInterfacedObject, INTAAddInOptions)
Strict Private
FFrame : TfmIDEHelpHelperOptions;
Strict Protected
Public
Procedure DialogClosed(Accepted: Boolean);
Procedure FrameCreated(AFrame: TCustomFrame);
Function GetArea: String;
Function GetCaption: String;
Function GetFrameClass: TCustomFrameClass;
Function GetHelpContext: Integer;
Function IncludeInIDEInsight: Boolean;
Function ValidateContents: Boolean;
End;
{$ENDIF}
Implementation
Uses
ApplicationsOptions;
{TIDEHelpHelperIDEOptionsInterface}
{$IFDEF DXE00}
(**
This method is call when the IDEs Options dialogue is closed. Accepted = True if the
dialogue is confirmed and settings should be saved or Accepted = False if the dialogue
if dismissed and setting changes should not be saved.
@precon None.
@postcon If the dialogue is accepted then the options frame settings are retreived and
saved back to the applications options class.
@param Accepted as a Boolean
**)
Procedure TIDEHelpHelperIDEOptionsInterface.DialogClosed(Accepted: Boolean);
Var
iSearchURL: Integer;
Begin
If Accepted Then
Begin
FFrame.FinaliseFrame(AppOptions.SearchURLs, AppOptions.PermanentURLs, iSearchURL);
AppOptions.SearchURLIndex := iSearchURL;
End;
End;
(**
This method is called when IDE creates the Options dialogue and creates your options
frame for you and should be used to initialise the frame information.
@precon None.
@postcon Checks the frame is the corrct frames and is so initialises the frame through
its InitialiseFrame method.
@param AFrame as a TCustomFrame
**)
Procedure TIDEHelpHelperIDEOptionsInterface.FrameCreated(AFrame: TCustomFrame);
Begin
If AFrame Is TfmIDEHelpHelperOptions Then
Begin
FFrame := AFrame As TfmIDEHelpHelperOptions;
FFrame.InitialiseFrame(AppOptions.SearchURLs, AppOptions.PermanentURLs,
AppOptions.SearchURLIndex);
End;
End;
(**
This is called by the IDE to get the primary area in the options tree where your options
frame is to be displayed. Recommended to return a null string to have your options
displayed under a third party node.
@precon None.
@postcon Returns a null string to place the options under the Third Parrty node.
@return a String
**)
Function TIDEHelpHelperIDEOptionsInterface.GetArea: String;
Begin
Result := '';
End;
(**
This method is caled by the IDE to get the sub node tre items where the page is to be
displayed. The period acts as a separator for another level of node in the tree.
@precon None.
@postcon Returns the name of the expert then the page name separated by a period.
@return a String
**)
Function TIDEHelpHelperIDEOptionsInterface.GetCaption: String;
Begin
Result := 'IDE Help Helper.Options';
End;
(**
This method should return a class reference to your frame for so that the IDe can create
an instance of your frame for you.
@precon None.
@postcon Returns a class reference to the options frame form.
@return a TCustomFrameClass
**)
Function TIDEHelpHelperIDEOptionsInterface.GetFrameClass: TCustomFrameClass;
Begin
Result := TfmIDEHelpHelperOptions;
End;
(**
This method returns the help context reference for the optins page.
@precon None.
@postcon Returns 0 for no context.
@return an Integer
**)
Function TIDEHelpHelperIDEOptionsInterface.GetHelpContext: Integer;
Begin
Result := 0;
End;
(**
This method determines whether your options frame page appears in the IDE Insight
search. Its recommended you return true.
@precon None.
@postcon Returns true to include in IDE Insight.
@return a Boolean
**)
Function TIDEHelpHelperIDEOptionsInterface.IncludeInIDEInsight: Boolean;
Begin
Result := True;
End;
(**
This method should be used to valdate you options frame. You should display an error
message if there is something wrong and return false else if all is okay return true.
@precon None.
@postcon Checks the interval is a valid integer greater than zero.
@return a Boolean
**)
Function TIDEHelpHelperIDEOptionsInterface.ValidateContents: Boolean;
Begin
Result := True;
End;
{$ENDIF}
End.
|
unit uTitulosDAO;
interface
uses uDM, ZAbstractConnection, ZConnection, Data.DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset, System.SysUtils, uTitulos;
type
TitulosDAO = class
private
zquery: TZQuery;
ds: TDataSource;
public
procedure setNovoTitulo(titulo: TTitulos);
procedure editarTitulo(titulo: TTitulos);
procedure excluirTitulo(id: integer);
function getTitulos: TDataSource;
function getTitulosByParam(descricao, statusid: string): TDataSource;
function getStatus: TDataSource;
end;
implementation
{ TitulosDAO }
procedure TitulosDAO.editarTitulo(titulo: TTitulos);
var
zqSet: TZQuery;
begin
zqSet := TZQuery.Create(zquery);
zqSet.Connection := dm.conexao;
try
dm.conexao.StartTransaction;
try
zqSet.Close;
zqSet.SQL.Clear;
zqSet.SQL.Add(' update Titulo set ');
zqSet.SQL.Add(' descricao = :descricao, ');
zqSet.SQL.Add(' valor = :valor, ');
zqSet.SQL.Add(' datavencimento = :datavencimento, ');
zqSet.SQL.Add(' statusid = :statusid, ');
zqSet.SQL.Add(' observacoes = :observacoes ');
zqSet.SQL.Add(' where id = :id ');
zqSet.ParamByName('descricao').AsString := titulo.descricao;
zqSet.ParamByName('valor').AsFloat := titulo.valor;
zqSet.ParamByName('datavencimento').AsDate := titulo.datavencimento;
zqSet.ParamByName('statusid').AsInteger := titulo.statusid;
zqSet.ParamByName('observacoes').AsString := titulo.observacoes;
zqSet.ParamByName('id').AsInteger := titulo.ID;
zqSet.ExecSQL;
dm.conexao.Commit;
except
on e: Exception do
dm.conexao.Rollback;
end;
finally
zqSet.Close;
zqSet.Free;
end;
end;
procedure TitulosDAO.excluirTitulo(id: integer);
var
zqSet: TZQuery;
begin
zqSet := TZQuery.Create(zquery);
zqSet.Connection := dm.conexao;
try
zqSet.Close;
zqSet.SQL.Clear;
zqSet.SQL.Add(' delete from Titulo where id = :id ');
zqSet.ParamByName('id').AsInteger := id;
zqSet.ExecSQL;
finally
zqSet.Close;
zqSet.Free;
end;
end;
function TitulosDAO.getStatus: TDataSource;
var
zqGet: TZQuery;
data: TDataSource;
begin
zqGet := TZQuery.Create(zquery);
zqGet.Connection := dm.conexao;
data := TDataSource.Create(ds);
zqGet.Close;
zqGet.SQL.Clear;
zqGet.SQL.Add(' select id, descricao from Status where id in (1, 2, 5)');
zqGet.Open;
data.DataSet := zqGet;
Result := data;
end;
function TitulosDAO.getTitulos: TDataSource;
var
zqGet: TZQuery;
data: TDataSource;
begin
zqGet := TZQuery.Create(zquery);
zqGet.Connection := dm.conexao;
data := TDataSource.Create(ds);
zqGet.Close;
zqGet.SQL.Clear;
zqGet.SQL.Add(' select Titulo.id as id, cast(Titulo.descricao as varchar(30)) as descricao, valor, ');
zqGet.SQL.Add(' datalancamento, datavencimento, statusid, ');
zqGet.SQL.Add(' cast(observacoes as varchar(100)), ');
zqGet.SQL.Add(' Status.descricao as status ');
zqGet.SQL.Add(' from Titulo ');
zqGet.SQL.Add(' join Status on Status.id = Titulo.statusid ');
zqGet.SQL.Add(' order by Titulo.id ');
zqGet.Open;
data.DataSet := zqGet;
Result := data;
end;
function TitulosDAO.getTitulosByParam(descricao, statusid: string): TDataSource;
var
zqGet: TZQuery;
data: TDataSource;
begin
zqGet := TZQuery.Create(zquery);
zqGet.Connection := dm.conexao;
data := TDataSource.Create(ds);
zqGet.Close;
zqGet.SQL.Clear;
zqGet.SQL.Add(' select Titulo.id as id, cast(Titulo.descricao as varchar(30)) as descricao, valor, ');
zqGet.SQL.Add(' datalancamento, datavencimento, statusid, ');
zqGet.SQL.Add(' cast(observacoes as varchar(100)), ');
zqGet.SQL.Add(' Status.descricao as status ');
zqGet.SQL.Add(' from Titulo ');
zqGet.SQL.Add(' join Status on Status.id = Titulo.statusid ');
zqGet.SQL.Add(' where Titulo.descricao like :descricao or statusid = :statusid ');
zqGet.SQL.Add(' order by Titulo.id ');
if Trim(descricao) <> '' then
zqGet.ParamByName('descricao').AsString := '%'+descricao+'%';
if Trim(statusid) <> '' then
zqGet.ParamByName('statusid').AsString := statusid;
zqGet.Open;
data.DataSet := zqGet;
Result := data;
end;
procedure TitulosDAO.setNovoTitulo(titulo: TTitulos);
var
zqSet: TZQuery;
sql: string;
begin
zqSet := TZQuery.Create(zquery);
zqSet.Connection := dm.conexao;
sql :=
' insert into Titulo ( '+
' descricao, '+
' valor, '+
' datalancamento, '+
' datavencimento, '+
' statusid, '+
' observacoes '+
' ) values ( '+
' :descricao, '+
' :valor, '+
' :datalancamento, '+
' :datavencimento, '+
' :statusid, '+
' :observacoes '+
' ) ';
try
dm.conexao.StartTransaction;
try
zqSet.Close;
zqSet.SQL.Clear;
zqSet.SQL.Add(sql);
zqSet.ParamByName('descricao').AsString := titulo.descricao;
zqSet.ParamByName('valor').AsFloat := titulo.valor;
zqSet.ParamByName('datalancamento').AsDate := titulo.datalancamento;
zqSet.ParamByName('datavencimento').AsDate := titulo.datavencimento;
zqSet.ParamByName('statusid').AsInteger := titulo.statusid;
zqSet.ParamByName('observacoes').AsString := titulo.observacoes;
zqSet.ExecSQL;
dm.conexao.Commit;
except
on e: Exception do
dm.conexao.Rollback;
end;
finally
zqSet.Close;
zqSet.Free;
end;
end;
end.
|
unit PasteColumnTest;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "TestFormsTest"
// Модуль: "w:/common/components/gui/Garant/Daily/PasteColumnTest.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TPasteColumnTest
//
// Тест копирования и вставки из буфера колонки с объединенной ячейкой.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
TextViaEditorProcessor,
PrimTextLoad_Form
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
TPasteColumnTest = {abstract} class(TTextViaEditorProcessor)
{* Тест копирования и вставки из буфера колонки с объединенной ячейкой. }
protected
// realized methods
procedure Process(aForm: TPrimTextLoadForm); override;
{* Собственно процесс обработки текста }
protected
// overridden protected methods
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TPasteColumnTest
{$IfEnd} //nsTest AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoVCM)}
uses
evCursorTools,
nevTools,
l3Base,
TestFrameWork
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// start class TPasteColumnTest
procedure TPasteColumnTest.Process(aForm: TPrimTextLoadForm);
//#UC START# *4BE13147032C_4C88AA1A00AB_var*
var
l_Selection : InevSelection;
//#UC END# *4BE13147032C_4C88AA1A00AB_var*
begin
//#UC START# *4BE13147032C_4C88AA1A00AB_impl*
l_Selection := aForm.Text.Selection;
if (l_Selection <> nil) then
begin
evSelectTableColumn(l_Selection, aForm.Text.Document.Para[0].AsList, 0);
aForm.Text.Copy;
evSelectTableColumn(l_Selection, aForm.Text.Document.Para[2].AsList, 0);
aForm.Text.Paste;
l3System.ClearClipboard;
end; // if (l_Selection <> nil) then
//#UC END# *4BE13147032C_4C88AA1A00AB_impl*
end;//TPasteColumnTest.Process
function TPasteColumnTest.GetFolder: AnsiString;
{-}
begin
Result := 'Everest';
end;//TPasteColumnTest.GetFolder
function TPasteColumnTest.GetModelElementGUID: AnsiString;
{-}
begin
Result := '4C88AA1A00AB';
end;//TPasteColumnTest.GetModelElementGUID
{$IfEnd} //nsTest AND not NoVCM
end. |
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.5 10/26/2004 10:03:24 PM JPMugaas
Updated refs.
Rev 1.4 4/19/2004 5:05:40 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.3 2004.02.03 5:45:26 PM czhower
Name changes
Rev 1.2 10/19/2003 3:48:22 PM DSiders
Added localization comments.
Rev 1.1 4/7/2003 04:04:42 PM JPMugaas
User can now descover what output a parser may give.
Rev 1.0 2/19/2003 05:49:46 PM JPMugaas
Parsers ported from old framework.
}
unit IdFTPListParseXecomMicroRTOS;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase;
type
TIdXecomMicroRTOSTPListItem = class(TIdFTPListItem)
protected
FMemStart: LongWord;
FMemEnd: LongWord;
public
constructor Create(AOwner: TCollection); override;
property MemStart: LongWord read FMemStart write FMemStart;
property MemEnd: LongWord read FMemEnd write FMemEnd;
end;
TIdFTPLPXecomMicroRTOS = class(TIdFTPListBaseHeader)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function IsHeader(const AData: String): Boolean; override;
class function IsFooter(const AData : String): Boolean; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseXecomMicroRTOS"'*)
implementation
uses
IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings,
SysUtils;
{ TIdFTPLPXecomMicroRTOS }
class function TIdFTPLPXecomMicroRTOS.GetIdent: String;
begin
Result := 'Xercom Micro RTOS'; {do not localize}
end;
class function TIdFTPLPXecomMicroRTOS.IsFooter(const AData: String): Boolean;
var
s : TStrings;
begin
Result := False;
s := TStringList.Create;
try
SplitColumns(AData, s);
if s.Count = 7 then
begin
Result := (s[0] = '**') and {do not localize}
(s[1] = 'Total') and {do not localize}
IsNumeric(s[2]) and
(s[3] = 'files,') and {do not localize}
IsNumeric(s[4]) and
(s[5] = 'bytes') and {do not localize}
(s[6] = '**'); {do not localize}
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPXecomMicroRTOS.IsHeader(const AData: String): Boolean;
var
s : TStrings;
begin
Result := False;
s := TStringList.Create;
try
SplitColumns(AData, s);
if s.Count = 5 then
begin
Result := (s[0] = 'Start') and {do not localize}
(s[1] = 'End') and {do not localize}
(s[2] = 'length') and {do not localize}
(s[3] = 'File') and {do not localize}
(s[4] = 'name'); {do not localize}
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPXecomMicroRTOS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdXecomMicroRTOSTPListItem.Create(AOwner);
end;
class function TIdFTPLPXecomMicroRTOS.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LBuf : String;
LI : TIdXecomMicroRTOSTPListItem;
begin
LI := AItem as TIdXecomMicroRTOSTPListItem;
LBuf := TrimLeft(AItem.Data);
//start memory offset
LBuf := TrimLeft(LBuf);
LI.MemStart := IndyStrToInt('$'+Fetch(LBuf), 0);
//end memory offset
LBuf := TrimLeft(LBuf);
LI.MemEnd := IndyStrToInt('$'+Fetch(LBuf),0);
//file size
LBuf := TrimLeft(LBuf);
LI.Size := IndyStrToInt64(Fetch(LBuf), 0);
//File name
LI.FileName := TrimLeft(LBuf);
//note that the date is not provided and I do not think there are
//dirs in this real-time operating system.
Result := True;
end;
{ TIdXecomMicroRTOSTPListItem }
constructor TIdXecomMicroRTOSTPListItem.Create(AOwner: TCollection);
begin
inherited Create(AOwner);
ModifiedAvail := False;
end;
initialization
RegisterFTPListParser(TIdFTPLPXecomMicroRTOS);
finalization
UnRegisterFTPListParser(TIdFTPLPXecomMicroRTOS);
end.
|
unit NtUtils.Sections;
interface
uses
Winapi.WinNt, Ntapi.ntmmapi, NtUtils.Exceptions;
// Create a section
function NtxCreateSection(out hSection: THandle; MaximumSize: UInt64;
PageProtection: Cardinal; AllocationAttributes: Cardinal = SEC_COMMIT;
hFile: THandle = 0; ObjectName: String = ''; RootDirectory: THandle = 0;
HandleAttributes: Cardinal = 0): TNtxStatus;
// Open a section
function NtxOpenSection(out hSection: THandle; DesiredAccess: TAccessMask;
ObjectName: String; RootDirectory: THandle = 0; HandleAttributes
: Cardinal = 0): TNtxStatus;
// Map a section
function NtxMapViewOfSection(hSection: THandle; hProcess: THandle;
Win32Protect: Cardinal; out Status: TNtxStatus; SectionOffset: UInt64 = 0;
Size: NativeUInt = 0): Pointer;
type
NtxSection = class
// Query fixed-size information
class function Query<T>(hSection: THandle;
InfoClass: TSectionInformationClass; out Buffer: T): TNtxStatus; static;
end;
implementation
uses
Ntapi.ntdef, Ntapi.ntpsapi, NtUtils.Access.Expected;
function NtxCreateSection(out hSection: THandle; MaximumSize: UInt64;
PageProtection, AllocationAttributes: Cardinal; hFile: THandle;
ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal)
: TNtxStatus;
var
ObjAttr: TObjectAttributes;
NameStr: UNICODE_STRING;
begin
if ObjectName <> '' then
begin
NameStr.FromString(ObjectName);
InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes,
RootDirectory);
end
else
InitializeObjectAttributes(ObjAttr, nil, HandleAttributes);
// TODO: Expected file handle access
Result.Location := 'NtCreateSection';
Result.Status := NtCreateSection(hSection, SECTION_ALL_ACCESS, @ObjAttr,
@MaximumSize, PageProtection, AllocationAttributes, 0);
end;
function NtxOpenSection(out hSection: THandle; DesiredAccess: TAccessMask;
ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal):
TNtxStatus;
var
ObjAttr: TObjectAttributes;
NameStr: UNICODE_STRING;
begin
NameStr.FromString(ObjectName);
InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes,
RootDirectory);
Result.Location := 'NtOpenSection';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @SectionAccessType;
Result.Status := NtOpenSection(hSection, DesiredAccess, ObjAttr);
end;
function NtxMapViewOfSection(hSection: THandle; hProcess: THandle;
Win32Protect: Cardinal; out Status: TNtxStatus; SectionOffset: UInt64;
Size: NativeUInt): Pointer;
var
ViewSize: NativeUInt;
begin
Status.Location := 'NtMapViewOfSection';
RtlxComputeSectionMapAccess(Status.LastCall, Win32Protect);
Status.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType);
Result := nil;
ViewSize := Size;
Status.Status := NtMapViewOfSection(hSection, hProcess, Result, 0, 0,
@SectionOffset, ViewSize, ViewUnmap, 0, Win32Protect);
end;
class function NtxSection.Query<T>(hSection: THandle;
InfoClass: TSectionInformationClass; out Buffer: T): TNtxStatus;
begin
Result.Location := 'NtQuerySection';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TSectionInformationClass);
Result.LastCall.Expects(SECTION_QUERY, @SectionAccessType);
Result.Status := NtQuerySection(hSection, InfoClass, @Buffer, SizeOf(Buffer),
nil);
end;
end.
|
{ Mark Sattolo 428500 }
{ CSI-1100A DGD-1 Chris Lankester }
{ Test program for Assignment#3 Question#2 }
program Insert (input, output);
{ This program takes a non-decreasing sorted array X with N numbers, and a number NUM,
and finds the first position in X where NUM can be inserted in the proper order. }
{ Data Dictionary
GIVENS: NUM - a number to insert in X in the proper sorted position.
RESULTS: none
Modifieds: X, N - X is a non-decreasing list of N numbers.
INTERMEDIATES: J - the index position in X to insert NUM.
USES: Search, MakeRoom }
type
Markarray = array[1..66] of integer;
var
N, NUM, J : integer;
X : Markarray;
{*************************************************************************}
procedure Swap(var X, Y : integer);
var
Temp : integer;
begin
Temp := X;
X := Y;
Y := Temp
end;
{*************************************************************************}
procedure Search(N, NUM : integer; X : Markarray; var J : integer);
var
Jfound : boolean;
begin { Search }
J := 0;
Jfound := false;
while ((J < N) and (NOT Jfound)) do
begin
J := J + 1;
if (NUM <= X[J]) then
Jfound := true
else { do nothing }
end; { while }
if NOT Jfound then
J := N + 1
end; { procedure FindSmallX }
{***********************************************************************************}
procedure MakeRoom(J : integer; var X: Markarray; var N : integer);
var
I : integer;
Jroom : boolean;
begin
Jroom := false;
N := N + 1;
X[N] := 0;
I := N;
while NOT Jroom do
begin
I := I - 1;
if (I < J) then
Jroom := true
else
Swap(X[I], X[I+1])
end { while }
end; { procedure Compare }
{*************************************************************************************}
procedure FillArray(var ArrayName : MarkArray; var ArraySize : integer);
var
K : integer; { K - an index in the prompt for values. }
begin
write('Please enter the size of the array? ');
readln(ArraySize);
for K := 1 to ArraySize do
begin
write('Please enter array value #', K, '? ');
read(ArrayName[K])
end { for }
end; { procedure FillArray }
{*************************************************************************************}
begin { program }
{ Get the input values }
writeln('For X:');
FillArray(X, N);
writeln;
writeln('Please enter the value for NUM:');
Readln(NUM);
{ body }
Search(N, NUM, X, J);
MakeRoom(J, X, N);
X[J] := NUM;
{ Print out the results. }
writeln;
writeln('*************************************');
writeln('Mark Sattolo 428500');
writeln('CSI-1100A DGD-1 Chris Lankester');
writeln('Assignment 3, Question 2');
writeln('*************************************');
writeln;
writeln('The new value of X is: ');
for J := 1 to N do
write(X[J], ' ');
end. { program }
|
unit uVK_Stat;
interface
uses
uVK_API, VCLTee.Chart, VCLTee.Series, VCLTee.TeEngine, VCLTee.TeeProcs,
System.Classes, SysUtils, DateUtils;
type
TVKStats = class
private
FPostList: TPostList;
FLikes, FReposts, FComments,
FLikesPost, FRepostsPost, FCommentsPost,
FLikesDay, FRepostsDay, FCommentsDay,
FPostDay, FRepostLike : Single;
procedure SetPostList(APostList: TPostList);
procedure ClearChart(AChart: TChart);
public
procedure Refresh;
procedure Chart_PostDay(AChart: TChart);
procedure Chart_PostHour(AChart: TChart);
procedure Chart_LikeRepComPost(AChart: TChart);
property PostList: TPostList write SetPostList;
property Likes : Single read FLikes;
property Reposts : Single read FReposts;
property Comments : Single read FComments;
property LikesPost : Single read FLikesPost;
property RepostsPost : Single read FRepostsPost;
property CommentsPost : Single read FCommentsPost;
property LikesDay : Single read FLikesDay;
property RepostsDay : Single read FRepostsDay;
property CommentsDay : Single read FCommentsDay;
property PostDay : Single read FPostDay;
property RepostLike : Single read FRepostLike;
end;
implementation
{ TVKStats }
procedure TVKStats.Chart_LikeRepComPost(AChart: TChart);
var
Counter: Integer;
Post: TPost;
SeriesLike, SeriesRepost, SeriesComment: TChartSeries;
begin
ClearChart(AChart);
SeriesLike := AChart.Series[0];
SeriesRepost := AChart.Series[1];
SeriesComment := AChart.Series[2];
SeriesLike.Visible := True;
SeriesRepost.Visible := True;
SeriesComment.Visible := True;
SeriesLike.Title := 'Лайки';
SeriesRepost.Title := 'Репосты';
SeriesComment.Title := 'Комментарии';
AChart.LeftAxis.Title.Caption := 'Кол-во';
AChart.BottomAxis.Title.Caption := 'Дата';
AChart.Legend.Visible := True;
Counter := 0;
for Post in FPostList do
begin
SeriesLike.AddXY(Counter, Post.Likes, '');
SeriesRepost.AddXY(Counter, Post.Reposts, '');
SeriesComment.AddXY(Counter, Post.Comments, '');
Inc(Counter);
end;
end;
procedure TVKStats.Chart_PostDay(AChart: TChart);
var
i, Counter: Integer;
Post: TPost;
CurentDate: TDateTime;
Series: TChartSeries;
begin
ClearChart(AChart);
Series := AChart.Series[0];
Series.Visible := True;
AChart.LeftAxis.Title.Caption := 'Кол-во';
AChart.BottomAxis.Title.Caption := 'Дата';
CurentDate := IncDay(Date, -1);
for i := 0 to FPostList.NumDay - 1 do
begin
Counter := 0;
for Post in FPostList do
if Post.Date = CurentDate then
Inc(Counter);
Series.AddXY(i, Counter, DateTimeToStr(CurentDate));
CurentDate := IncDay(CurentDate, -1);
end;
end;
procedure TVKStats.Chart_PostHour(AChart: TChart);
var
Hour, i: Integer;
Post: TPost;
Hours: array[0..23] of Integer;
Series: TChartSeries;
begin
ClearChart(AChart);
Series := AChart.Series[0];
Series.Visible := True;
AChart.LeftAxis.Title.Caption := 'Кол-во';
AChart.BottomAxis.Title.Caption := 'Часы (Мск)';
FillChar(Hours, 24 * SizeOf(Integer), 0);
for Post in FPostList do
begin
Hour := HourOf(Post.DateTime);
Hour := (Hour + 4) mod 24; // мск = UTC + 4
Hours[Hour] := Hours[Hour] + 1;
end;
for i := 0 to 23 do
Series.AddXY(i, Hours[i], IntToStr(i));
end;
procedure TVKStats.ClearChart(AChart: TChart);
var
i: Integer;
begin
for i := 0 to AChart.SeriesCount - 1 do
begin
AChart.Series[i].Clear;
AChart.Series[i].Visible := False;
end;
AChart.Legend.Visible := False;
end;
procedure TVKStats.Refresh;
var
Post: TPost;
begin
FLikes := 0;
FReposts := 0;
FComments := 0;
for Post in FPostList do
begin
FLikes := FLikes + Post.Likes;
FReposts := FReposts + Post.Reposts;
FComments := FComments + Post.Comments;
end;
FLikesDay := FLikes / FPostList.NumDay;
FRepostsDay := FReposts / FPostList.NumDay;
FCommentsDay := FComments / FPostList.NumDay;
FLikesPost := FLikes / FPostList.Count;
FRepostsPost := FReposts / FPostList.Count;
FCommentsPost := FComments / FPostList.Count;
FPostDay := FPostList.Count / FPostList.NumDay;
if FLikes > 0 then
FRepostLike := FReposts / FLikes
else
FRepostLike := 0;
end;
procedure TVKStats.SetPostList(APostList: TPostList);
begin
FPostList := APostList;
Refresh;
end;
end.
|
unit entradaController;
interface
uses
IBQuery, IBDataBase, Classes, SysUtils, DateUtils, Entrada, EntradaDao,
tanqueDao, Tanque;
const
STATUS_ENTRADA: array [1..4] of string =
(
'Sucesso!',
'Não aceita valor negativo',
'Não aceita 0 ou nulo',
'Excede a capacidade do tanque.'
);
type
T_EntradaController = class(TObject)
private
F_TanqueDao: T_TanqueDao;
F_EntradaDao: T_EntradaDao;
F_Tanque: T_Tanque;
F_Entrada: T_Entrada;
public
constructor Create(db: TIBDatabase; pEntrada: T_Entrada; pTanque_Id: Integer);
destructor Destroy();
function efetuarEntrada(var Status: String): boolean;
end;
implementation
constructor T_EntradaController.Create(db: TIBDatabase; pEntrada: T_Entrada; pTanque_Id: Integer);
begin
F_EntradaDao := T_EntradaDao.Create(db);
F_TanqueDao := T_TanqueDao.Create(db);
F_Entrada := pEntrada;
F_Tanque := F_TanqueDao.get(pTanque_Id);;
end;
destructor T_EntradaController.Destroy();
begin
F_EntradaDao.Destroy();
F_TanqueDao.Destroy();
end;
function T_EntradaController.efetuarEntrada(var Status: String): boolean;
var
espacoExtra: Double;
begin
result := false;
espacoExtra := F_Tanque.Capacidade_Litros - F_Tanque.Quantidade_Litros;
if F_Entrada.Litros = 0 then
begin
Status := STATUS_ENTRADA[3];
result := false;
end
else if F_Entrada.Litros < 0 then
begin
Status := STATUS_ENTRADA[2];
result := false;
end
else if F_Entrada.Litros > espacoExtra then
begin
Status := STATUS_ENTRADA[4];
result := false;
end
else if F_Entrada.Litros <= espacoExtra then
begin
Status := STATUS_ENTRADA[1];
result := true;
F_EntradaDao.incluir(F_Entrada);
F_Tanque.Quantidade_Litros := F_Tanque.Quantidade_Litros + F_Entrada.Litros;
F_TanqueDao.atualizar(F_Tanque);
end;
end;
end.
|
unit ObjectInspectorInterfaces;
interface
uses
Classes, VoyagerInterfaces, VoyagerServerInterfaces, Controls;
const
tidSheetHandlerEntryPoint = 'GetPropertySheetHandler';
type
IPropertySheetHandler = interface;
IPropertySheetContainerHandler = interface;
TSheetHandlerCreatorFunction = function : IPropertySheetHandler; stdcall;
IPropertySheetHandler =
interface
procedure Lock;
procedure UnLock;
procedure SetContainer(aContainer : IPropertySheetContainerHandler);
procedure UnsetContainer;
procedure StartSettingProperties;
procedure StopSettingProperties;
function Busy : boolean;
function CreateControl(Owner : TControl) : TControl;
function GetControl : TControl;
procedure RenderProperties(Properties : TStringList);
procedure SetFocus;
procedure LostFocus;
procedure Clear;
procedure Refresh;
function HandleURL( URL : TURL ) : TURLHandlingResult;
function Exposed : boolean;
function Loaded : boolean;
end;
IPropertySheetContainerHandlerInit =
interface
procedure SetClientView(ClientView : IClientView);
procedure SetClassId(ClassId : integer);
procedure SetObjectId(ObjectId : integer);
procedure SetXPos(xPos : integer);
procedure SetYPos(yPos : integer);
procedure ClearSheets(release : boolean);
function AddSheet(Handler : string) : integer;
end;
IPropertySheetContainerHandler =
interface
procedure Lock;
procedure UnLock;
function GetClientView : IClientView;
function GetClassId : integer;
function GetObjectId : integer;
function GetXPos : integer;
function GetYPos : integer;
function GetProperties(Names : TStringList) : TStringList;
function GetPropertyList (Proxy : OleVariant; Names, Results : TStringList) : boolean;
function GetPropertyArray(Proxy : OleVariant; Names : array of string; Results : TStringList) : boolean;
function SheetCount : integer;
procedure FocusSheet(index : integer);
function GetFocusedSheet : IPropertySheetHandler;
function GetCacheServerProxy : OleVariant;
function CreateCacheObjectProxy : OleVariant;
function GetCacheObjectProxy : OleVariant;
function GetMSProxy : OleVariant;
function HandleURL(URL : TURL; incoming : boolean) : TURLHandlingResult;
procedure KeepAlive;
function GetCacheDir : string;
procedure Refresh;
procedure ClearConnections; // NEW!
end;
implementation
end.
|
unit uSolicitacaoViewModel;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TSolicitacaoViewModel = class
private
FTitulo: string;
FTempoAberto: Boolean;
FNomeCliente: string;
FNomeStatus: string;
FId: Integer;
FNivel: string;
FIdUsuarioAtendeAtual: Integer;
FIdStatus: Integer;
FTempoPrevisto: Currency;
FTempoDecorrido: string;
FQuadro: string;
FAberta: Integer;
FUsuarioNome: string;
FPerfil: string;
procedure SetId(const Value: Integer);
procedure SetNivel(const Value: string);
procedure SetNomeCliente(const Value: string);
procedure SetNomeStatus(const Value: string);
procedure SetTempoAberto(const Value: Boolean);
procedure SetTitulo(const Value: string);
procedure SetIdUsuarioAtendeAtual(const Value: Integer);
procedure SetIdStatus(const Value: Integer);
procedure SetTempoPrevisto(const Value: Currency);
procedure SetTempoDecorrido(const Value: string);
procedure SetQuadro(const Value: string);
procedure SetAberta(const Value: Integer);
procedure SetUsuarioNome(const Value: string);
procedure SetPerfil(const Value: string);
public
property Quadro: string read FQuadro write SetQuadro;
property Id: Integer read FId write SetId;
property NomeCliente: string read FNomeCliente write SetNomeCliente;
property Titulo: string read FTitulo write SetTitulo;
property Nivel: string read FNivel write SetNivel;
property NomeStatus: string read FNomeStatus write SetNomeStatus;
property TempoAberto: Boolean read FTempoAberto write SetTempoAberto;
property IdUsuarioAtendeAtual: Integer read FIdUsuarioAtendeAtual write SetIdUsuarioAtendeAtual;
property IdStatus: Integer read FIdStatus write SetIdStatus;
property TempoPrevisto: Currency read FTempoPrevisto write SetTempoPrevisto;
property TempoDecorrido: string read FTempoDecorrido write SetTempoDecorrido;
property UsuarioNome: string read FUsuarioNome write SetUsuarioNome;
property Aberta: Integer read FAberta write SetAberta;
property Perfil: string read FPerfil write SetPerfil;
end;
TListaSolicitacaoViewModel = TObjectList<TSolicitacaoViewModel>;
implementation
{ TSolicitacaoViewModel }
procedure TSolicitacaoViewModel.SetAberta(const Value: Integer);
begin
FAberta := Value;
end;
procedure TSolicitacaoViewModel.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TSolicitacaoViewModel.SetIdStatus(const Value: Integer);
begin
FIdStatus := Value;
end;
procedure TSolicitacaoViewModel.SetIdUsuarioAtendeAtual(const Value: Integer);
begin
FIdUsuarioAtendeAtual := Value;
end;
procedure TSolicitacaoViewModel.SetNivel(const Value: string);
begin
FNivel := Value;
end;
procedure TSolicitacaoViewModel.SetNomeCliente(const Value: string);
begin
FNomeCliente := Value;
end;
procedure TSolicitacaoViewModel.SetNomeStatus(const Value: string);
begin
FNomeStatus := Value;
end;
procedure TSolicitacaoViewModel.SetPerfil(const Value: string);
begin
FPerfil := Value;
end;
procedure TSolicitacaoViewModel.SetQuadro(const Value: string);
begin
FQuadro := Value;
end;
procedure TSolicitacaoViewModel.SetTempoAberto(const Value: Boolean);
begin
FTempoAberto := Value;
end;
procedure TSolicitacaoViewModel.SetTempoDecorrido(const Value: string);
begin
FTempoDecorrido := Value;
end;
procedure TSolicitacaoViewModel.SetTempoPrevisto(const Value: Currency);
begin
FTempoPrevisto := Value;
end;
procedure TSolicitacaoViewModel.SetTitulo(const Value: string);
begin
FTitulo := Value;
end;
procedure TSolicitacaoViewModel.SetUsuarioNome(const Value: string);
begin
FUsuarioNome := Value;
end;
end.
|
{ Interface invocable Idemos }
unit udemosIntf;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns;
type
TEnumTest = (etNone, etAFew, etSome, etAlot);
TDoubleArray = array of Double;
TMyEmployee = class(TRemotable)
private
FLastName: UnicodeString;
FFirstName: UnicodeString;
FSalary: Double;
published
property LastName: UnicodeString read FLastName write FLastName;
property FirstName: UnicodeString read FFirstName write FFirstName;
property Salary: Double read FSalary write FSalary;
end;
{ Les interfaces invocables doivent dériver de IInvokable }
Idemos = interface(IInvokable)
['{0C40A3CD-F3B3-4ED9-9A3B-986E1676BA9D}']
{ Les méthodes de l'interface invocable ne doivent pas utiliser la valeur par défaut }
{ convention d'appel ; stdcall est recommandé }
function echoEnum(const Value: TEnumTest): TEnumTest; stdcall;
function echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall;
function echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall;
function echoDouble(const Value: Double): Double; stdcall;
end;
implementation
initialization
{ Les interfaces invocables doivent être enregistrées }
InvRegistry.RegisterInterface(TypeInfo(Idemos));
end.
|
program trayrestore;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, Windows, Messages
{ you can add units after this };
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
procedure ClearDeadIcons; virtual;
end;
{ TMyApplication }
function NextWindow(wnd:LongWord; list:LongInt): LongBool; stdcall;
var
WM_TASKBAR_CREATED: Cardinal;
begin
WM_TASKBAR_CREATED := RegisterWindowMessage('TaskbarCreated');
SendMessage(wnd, WM_TASKBAR_CREATED, 0, 0);
result := true;
end;
procedure TMyApplication.DoRun;
var
ErrorMsg: String;
begin
// quick check parameters
ErrorMsg:=CheckOptions('h','help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h','help') then begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
ClearDeadIcons;
EnumWindows(@NextWindow, 0);
writeln('All possible tray icons have been restored.');
// stop program loop
Terminate;
end;
constructor TMyApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TMyApplication.Destroy;
begin
inherited Destroy;
end;
procedure TMyApplication.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ',ExeName);
writeln('This application restores icons of running applications to the tray in the case of Explorer crashing.');
writeln('');
writeln('Copyright (c) 2013 Owen Winkler http://owenw.com');
writeln('');
writeln('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:');
writeln('');
writeln('The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.');
writeln('');
writeln('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.');
end;
procedure TMyApplication.ClearDeadIcons;
var
wnd : cardinal;
rec : TRect;
w,h : integer;
x,y : integer;
begin
// find a handle of a tray
wnd := FindWindow('Shell_TrayWnd', nil);
wnd := FindWindowEx(wnd, 0, 'TrayNotifyWnd', nil);
wnd := FindWindowEx(wnd, 0, 'SysPager', nil);
wnd := FindWindowEx(wnd, 0, 'ToolbarWindow32', nil);
// get client rectangle (needed for width and height of tray)
windows.GetClientRect(wnd, rec);
// get size of small icons
w := GetSystemMetrics(sm_cxsmicon);
h := GetSystemMetrics(sm_cysmicon);
// initial y position of mouse - half of height of icon
y := w shr 1;
while y < rec.Bottom do begin // while y < height of tray
x := h shr 1; // initial x position of mouse - half of width of icon
while x < rec.Right do begin // while x < width of tray
SendMessage(wnd, wm_mousemove, 0, y shl 16 or x); // simulate moving mouse over an icon
x := x + w; // add width of icon to x position
end;
y := y + h; // add height of icon to y position
end;
end;
var
Application: TMyApplication;
begin
Application:=TMyApplication.Create(nil);
Application.Title:='My Application';
Application.Run;
Application.Free;
end.
|
unit dirstack;
interface
uses SysUtils,Classes;
const
MAX_DIR_COUNT = 50000;
type
TDirectoryStack = class;
TOnDirectoryEvent = procedure (Stack: TDirectoryStack; Dir: string) of object;
TDirectoryStack = class
private
FDirList: TStringList;
function GetCount: integer;
function GetItem(Index: integer): string;
function GetSorted: boolean;
procedure SetSorted(const Value: boolean);
public
function Pop: string;
function Peek: string;
procedure Push(Dir: string);
property Count: integer read GetCount;
property Items[Index: integer]: string read GetItem; default;
property Sorted: boolean read GetSorted write SetSorted;
constructor Create;
destructor Destroy; override;
end;
TDirs = class(TDirectoryStack)
private
FRootPath: string;
FDirDelim: char;
FMaxDirCount: integer;
FOnDirectory: TOnDirectoryEvent;
procedure PopulateDirStack;
procedure DoOnDirectory(Dir: string);
public
property OnDirectory: TOnDirectoryEvent read FOnDirectory write FOnDirectory;
property DirDelimiter: char read FDirDelim write FDirDelim;
procedure Populate;
procedure Enumerate;
constructor Create(RootPath: string; Max: integer = MAX_DIR_COUNT;
DirDelim: char = '\');
destructor Destroy; override;
end;
implementation
uses FileCtrl;
function DropTrailingDirDelim(Dir: string; Delim: char = '\'): string;
begin
if Length(SysUtils.Trim(Dir)) > 0 then
if Dir[Length(Dir)] = Delim then
Delete(Dir,Length(Dir),1);
Result := Dir;
end;
{ TDirectoryStack }
constructor TDirectoryStack.Create;
begin
inherited Create;
FDirList := TStringList.Create;
end;
destructor TDirectoryStack.Destroy;
begin
FDirList.Free;
inherited Destroy;
end;
function TDirectoryStack.GetCount: integer;
begin
Result := FDirList.Count;
end;
function TDirectoryStack.GetItem(Index: integer): string;
begin
Result := '';
if Index < FDirList.Count then
Result := FDirList[Index];
end;
function TDirectoryStack.GetSorted: boolean;
begin
Result := FDirList.Sorted;
end;
function TDirectoryStack.Peek: string;
begin
Result := '';
if FDirList.Count > 0 then
Result := FDirList[FDirList.Count-1];
end;
function TDirectoryStack.Pop: string;
begin
Result := '-1';
if FDirList.Count > 0 then
begin
Result := FDirList[FDirList.Count-1];
FDirList.Delete(FDirList.Count-1);
end;
end;
procedure TDirectoryStack.Push(Dir: string);
begin
//FDirList.Add(Dir);
FDirList.Insert(0,Dir);
end;
procedure TDirectoryStack.SetSorted(const Value: boolean);
begin
if FDirList.Sorted <> Value then
FDirList.Sorted := Value;
end;
{ TDirs }
constructor TDirs.Create(RootPath: string; Max: integer = MAX_DIR_COUNT;
DirDelim: char = '\');
begin
inherited Create;
if DirectoryExists(RootPath) then
FRootPath := DropTrailingDirDelim(RootPath);
FDirDelim := DirDelim;
FMaxDirCount := Max;
end;
destructor TDirs.Destroy;
begin
inherited Destroy;
end;
procedure TDirs.DoOnDirectory(Dir: string);
begin
if Assigned(FOnDirectory) then
FOnDirectory(Self,Dir);
end;
procedure TDirs.Enumerate;
begin
PopulateDirStack;
end;
procedure TDirs.Populate;
begin
PopulateDirStack;
end;
procedure TDirs.PopulateDirStack;
var
sr: TSearchRec;
srRes,i: integer;
ThisDir: string;
RootDirs: TDirectoryStack;
begin
RootDirs := TDirectoryStack.Create;
try
//Push(FRootPath);
if FMaxDirCount > 0 then
begin
srRes := FindFirst(FRootPath + FDirDelim + '*.*',faAnyFile,sr);
try
while srRes = 0 do
begin
if (Count > FMaxDirCount - 1) then Break;
if ((sr.Attr and faDirectory) = faDirectory) and
(sr.Name[1] <> '.') then
begin
//RootDirs.Push(FRootPath + FDirDelim + sr.Name);
Push(FRootPath + FDirDelim + sr.Name);
end;
srRes := FindNext(sr);
end;
finally
FindClose(sr);
end;
//if RootDirs.Count > 0 then
if Count > 0 then
begin
i := 0;
//while RootDirs.Count > 0 do
while Count > 0 do
begin
//ThisDir := RootDirs.Pop;
ThisDir := Pop;
//Push(ThisDir);
DoOnDirectory(ThisDir);
srRes := FindFirst(ThisDir + FDirDelim + '*.*',faAnyFile,sr);
try
if srRes = 0 then
begin
while srRes = 0 do
begin
if ((sr.Attr and faDirectory) = faDirectory) and
(sr.Name[1] <> '.') then
begin
//RootDirs.Push(ThisDir + FDirDelim + sr.Name);
Push(ThisDir + FDirDelim + sr.Name);
DoOnDirectory(ThisDir + FDirDelim + sr.Name);
end;
srRes := FindNext(sr);
end;
end;
finally
FindClose(sr);
end;
end;
end;
end;
finally
RootDirs.Free;
end;
end;
end.
|
unit DW.PermissionsRequester.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Messaging,
// Android
Androidapi.JNI,
// DW
DW.PermissionsRequester;
type
TPlatformPermissionsRequester = class(TCustomPlatformPermissionsRequester)
private
FIsSubmitted: Boolean;
FPermissions: array of string;
FRequestCode: Integer;
procedure ApplicationEventMessageHandler(const Sender: TObject; const AMsg: TMessage);
procedure CheckPermissionsResults;
protected
procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); override;
public
constructor Create(const APermissionsRequester: TPermissionsRequester); override;
destructor Destroy; override;
end;
implementation
uses
// RTL
System.SysUtils, System.Classes,
// FMX
FMX.Platform,
// Android
Androidapi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.App,
// DW
DW.PermissionsTypes, DW.OSDevice;
type
TOpenPermissionsRequester = class(TPermissionsRequester);
{ TPlatformPermissionsRequester }
constructor TPlatformPermissionsRequester.Create(const APermissionsRequester: TPermissionsRequester);
begin
inherited;
TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ApplicationEventMessageHandler);
end;
destructor TPlatformPermissionsRequester.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ApplicationEventMessageHandler);
inherited;
end;
procedure TPlatformPermissionsRequester.ApplicationEventMessageHandler(const Sender: TObject; const AMsg: TMessage);
begin
case TApplicationEventMessage(AMsg).Value.Event of
TApplicationEvent.BecameActive:
begin
if FIsSubmitted then
CheckPermissionsResults;
end;
end;
end;
procedure TPlatformPermissionsRequester.CheckPermissionsResults;
var
LResults: TPermissionResults;
LIndex, I: Integer;
begin
SetLength(LResults, Length(FPermissions));
for I := Low(FPermissions) to High(FPermissions) do
begin
LIndex := I - Low(FPermissions);
LResults[LIndex].Permission := FPermissions[I];
LResults[LIndex].Granted := TOSDevice.CheckPermission(FPermissions[I], True);
end;
FIsSubmitted := False;
TOpenPermissionsRequester(PermissionsRequester).DoPermissionsResult(FRequestCode, LResults);
end;
procedure TPlatformPermissionsRequester.RequestPermissions(const APermissions: array of string; const ARequestCode: Integer);
var
LPermissions: TJavaObjectArray<JString>;
I: Integer;
begin
FRequestCode := ARequestCode;
SetLength(FPermissions, Length(APermissions));
for I := 0 to Length(APermissions) - 1 do
FPermissions[I] := APermissions[I];
LPermissions := TJavaObjectArray<JString>.Create(Length(FPermissions));
for I := Low(FPermissions) to High(FPermissions) do
LPermissions.Items[I] := StringToJString(FPermissions[I]);
FIsSubmitted := True;
TAndroidHelper.Activity.requestPermissions(LPermissions, ARequestCode);
end;
end.
|
unit MFichas.View.Cadastros.GrupoProduto;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.ListView.Types,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base,
FMX.StdCtrls,
FMX.ListView,
FMX.Controls.Presentation,
FMX.Objects,
FMX.TabControl,
FMX.Layouts,
FMX.Platform,
FMX.VirtualKeyboard,
FMX.Gestures,
FMX.Effects,
FMX.ListBox,
FMX.Edit,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
MultiDetailAppearanceU,
Data.DB,
MFichas.Model.GrupoProduto;
type
TTypeTabs = (tTabListarGrupos, tTabCadastrarGrupos, tTabEditarGrupos, tTabMenu);
TCadastroGrupoProdutoView = class(TForm)
GestureManager1: TGestureManager;
LayoutPrincipal: TLayout;
TabControlPrincipal: TTabControl;
TabItemListarGrupos: TTabItem;
RectangleListar: TRectangle;
Layout1: TLayout;
Circle1: TCircle;
ShadowEffect1: TShadowEffect;
ToolBarListar: TToolBar;
LabelToolBarListar: TLabel;
ButtonBackListar: TButton;
ListViewGrupos: TListView;
Layout2: TLayout;
Layout3: TLayout;
Image1: TImage;
TabItemCadastrarGrupos: TTabItem;
Rectangle1: TRectangle;
ToolBar1: TToolBar;
LabelToolBarCadastrar: TLabel;
ButtonBackCadastrar: TButton;
Layout4: TLayout;
LayoutDireita: TLayout;
RoundRectBotaoConfirmarCadastro: TRoundRect;
LabelBotaoConfirmar: TLabel;
LayoutEsquerda: TLayout;
RoundRectBotaoCancelarCadastro: TRoundRect;
LabelBotaoCancelar: TLabel;
Layout6: TLayout;
EditCadastrarDescricao: TEdit;
TabItemEditarGrupos: TTabItem;
Rectangle2: TRectangle;
ToolBar2: TToolBar;
LabelToolBarEditar: TLabel;
ButtonBackEditar: TButton;
Layout5: TLayout;
Layout8: TLayout;
RoundRectBotaoConfirmarAlteracao: TRoundRect;
Label7: TLabel;
Layout9: TLayout;
RoundRectBotaoCancelarAlteracao: TRoundRect;
Label8: TLabel;
Layout7: TLayout;
Label4: TLabel;
EditEditarDescricao: TEdit;
CheckBoxEditarAtivoInativo: TCheckBox;
RectangleFundo: TRectangle;
RectangleMenu: TRectangle;
LabelEditar: TLabel;
ShadowEffectEditar: TShadowEffect;
FDMemTableGrupos: TFDMemTable;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure ListViewGruposGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure RectangleMenuClick(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure ListViewGruposDblClick(Sender: TObject);
procedure ButtonBackListarClick(Sender: TObject);
procedure ButtonBackCadastrarClick(Sender: TObject);
procedure ButtonBackEditarClick(Sender: TObject);
procedure RoundRectBotaoCancelarCadastroClick(Sender: TObject);
procedure RoundRectBotaoCancelarAlteracaoClick(Sender: TObject);
procedure RoundRectBotaoConfirmarCadastroClick(Sender: TObject);
procedure RoundRectBotaoConfirmarAlteracaoClick(Sender: TObject);
procedure RectangleFundoClick(Sender: TObject);
procedure EditCadastrarDescricaoChangeTracking(Sender: TObject);
procedure EditEditarDescricaoChangeTracking(Sender: TObject);
private
{ Private declarations }
FTabs: TTypeTabs;
FListItemGrupo: TListViewItem;
procedure BuscarGrupos;
procedure PreencherListViewGrupos;
procedure LimparTelaDeCadastro;
procedure LimparTelaDeEdicao;
procedure AbrirMenu;
procedure FecharMenu;
procedure VoltarAbas;
procedure MudarAba(ATabControl: TTabControl; ATypeTabs: TTypeTabs;
AProximaTabItem: TTabItem);
public
{ Public declarations }
end;
var
CadastroGrupoProdutoView: TCadastroGrupoProdutoView;
implementation
{$R *.fmx}
procedure TCadastroGrupoProdutoView.AbrirMenu;
begin
RectangleFundo.Visible := True;
RectangleMenu.Visible := True;
FTabs := tTabMenu;
end;
procedure TCadastroGrupoProdutoView.BuscarGrupos;
begin
TModelGrupoProduto.New
.Metodos
.Buscar
.FDMemTable(FDMemTableGrupos)
.BuscarTodos
.&End
.&End;
PreencherListViewGrupos;
end;
procedure TCadastroGrupoProdutoView.ButtonBackCadastrarClick(Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.ButtonBackEditarClick(Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.ButtonBackListarClick(Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.EditCadastrarDescricaoChangeTracking(
Sender: TObject);
begin
EditCadastrarDescricao.Text := AnsiUpperCase(EditCadastrarDescricao.Text);
end;
procedure TCadastroGrupoProdutoView.EditEditarDescricaoChangeTracking(
Sender: TObject);
begin
EditEditarDescricao.Text := AnsiUpperCase(EditEditarDescricao.Text);
end;
procedure TCadastroGrupoProdutoView.FecharMenu;
begin
RectangleFundo.Visible := False;
RectangleMenu.Visible := False;
end;
procedure TCadastroGrupoProdutoView.FormCreate(Sender: TObject);
begin
RectangleMenu.Margins.Top := LayoutPrincipal.Height / 2.20;
RectangleMenu.Margins.Bottom := LayoutPrincipal.Height / 2.20;
RectangleMenu.Margins.Right := LayoutPrincipal.Height / 13;
RectangleMenu.Margins.Left := LayoutPrincipal.Height / 13;
TabControlPrincipal.TabPosition := TTabPosition.None;
TabControlPrincipal.ActiveTab := TabItemListarGrupos;
FTabs := tTabListarGrupos;
FecharMenu;
BuscarGrupos;
end;
procedure TCadastroGrupoProdutoView.FormKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
var
LTeclado: IFMXVirtualKeyboardService;
begin
if (Key = vkHardwareBack) then
begin
TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(LTeclado));
if (LTeclado <> nil) and (TVirtualKeyboardState.Visible in LTeclado.VirtualKeyboardState) then
begin
end
else
begin
Key := 0;
VoltarAbas;
end;
end;
end;
procedure TCadastroGrupoProdutoView.Image1Click(Sender: TObject);
begin
MudarAba(TabControlPrincipal, tTabCadastrarGrupos, TabItemCadastrarGrupos);
end;
procedure TCadastroGrupoProdutoView.LimparTelaDeCadastro;
begin
EditCadastrarDescricao.Text := '';
end;
procedure TCadastroGrupoProdutoView.LimparTelaDeEdicao;
begin
EditEditarDescricao.Text := '';
end;
procedure TCadastroGrupoProdutoView.ListViewGruposDblClick(Sender: TObject);
begin
AbrirMenu;
end;
procedure TCadastroGrupoProdutoView.ListViewGruposGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
if EventInfo.GestureID = igiLongTap then
begin
AbrirMenu;
end;
end;
procedure TCadastroGrupoProdutoView.MudarAba(ATabControl: TTabControl;
ATypeTabs: TTypeTabs; AProximaTabItem: TTabItem);
begin
ATabControl.ActiveTab := AProximaTabItem;
FTabs := ATypeTabs;
end;
procedure TCadastroGrupoProdutoView.PreencherListViewGrupos;
begin
ListViewGrupos.Items.Clear;
FDMemTableGrupos.First;
while not FDMemTableGrupos.EOF do
begin
FListItemGrupo := ListViewGrupos.Items.Add;
FListItemGrupo.Text := FDMemTableGrupos.FieldByName('DESCRICAO').AsString;
case FDMemTableGrupos.FieldByName('STATUS').AsInteger of
0: FListItemGrupo.Data[TMultiDetailAppearanceNames.Detail1] := 'Inativo';
1: FListItemGrupo.Data[TMultiDetailAppearanceNames.Detail1] := 'Ativo';
end;
FListItemGrupo.Detail := FDMemTableGrupos.FieldByName('GUUID').AsString;
FDMemTableGrupos.Next;
end;
end;
procedure TCadastroGrupoProdutoView.RectangleFundoClick(Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.RectangleMenuClick(Sender: TObject);
var
LCount : Integer;
LGuuidIsEqual: Boolean;
begin
FDMemTableGrupos.First;
LCount := 0;
while not FDMemTableGrupos.Eof do
begin
LGuuidIsEqual := FDMemTableGrupos.FieldByName('GUUID').AsString = ListViewGrupos.Items.AppearanceItem[ListViewGrupos.ItemIndex].Detail;
if LGuuidIsEqual then
begin
EditEditarDescricao.Text := FDMemTableGrupos.FieldByName('DESCRICAO').AsString;
case FDMemTableGrupos.FieldByName('STATUS').AsInteger of
0: CheckBoxEditarAtivoInativo.IsChecked := False;
1: CheckBoxEditarAtivoInativo.IsChecked := True;
end;
Break;
end;
Inc(LCount);
FDMemTableGrupos.Next;
end;
FecharMenu;
MudarAba(TabControlPrincipal, tTabEditarGrupos, TabItemEditarGrupos);
end;
procedure TCadastroGrupoProdutoView.RoundRectBotaoCancelarAlteracaoClick(
Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.RoundRectBotaoCancelarCadastroClick(
Sender: TObject);
begin
VoltarAbas;
end;
procedure TCadastroGrupoProdutoView.RoundRectBotaoConfirmarAlteracaoClick(
Sender: TObject);
begin
TModelGrupoProduto.New
.Metodos
.Editar
.GUUID(ListViewGrupos.Items.AppearanceItem[ListViewGrupos.ItemIndex].Detail)
.Descricao(EditEditarDescricao.Text)
.AtivoInativo(Integer(CheckBoxEditarAtivoInativo.IsChecked))
.&End
.&End;
BuscarGrupos;
PreencherListViewGrupos;
LimparTelaDeEdicao;
MudarAba(TabControlPrincipal, tTabListarGrupos, TabItemListarGrupos);
end;
procedure TCadastroGrupoProdutoView.RoundRectBotaoConfirmarCadastroClick(
Sender: TObject);
begin
TModelGrupoProduto.New
.Metodos
.Cadastrar
.Descricao(EditCadastrarDescricao.Text)
.&End
.&End;
BuscarGrupos;
PreencherListViewGrupos;
LimparTelaDeCadastro;
MudarAba(TabControlPrincipal, tTabListarGrupos, TabItemListarGrupos);
end;
procedure TCadastroGrupoProdutoView.VoltarAbas;
begin
case FTabs of
tTabListarGrupos: begin
CadastroGrupoProdutoView.Close;
{$IFDEF ANDROID OR IOS}
if Assigned(CadastroGrupoProdutoView) then
begin
CadastroGrupoProdutoView.DisposeOf;
CadastroGrupoProdutoView.Free;
end;
{$ENDIF}
end;
tTabCadastrarGrupos: begin
LimparTelaDeCadastro;
MudarAba(TabControlPrincipal, tTabListarGrupos, TabItemListarGrupos);
end;
tTabEditarGrupos: begin
LimparTelaDeEdicao;
MudarAba(TabControlPrincipal, tTabListarGrupos, TabItemListarGrupos);
end;
tTabMenu: begin
FecharMenu;
FTabs := tTabListarGrupos;
end;
end;
end;
end.
|
unit np.fs;
interface
uses sysUtils, np.common, np.libuv, np.core;
const
oct777 = 511;
oct666 = 438;
oct444 = 292;
type
fs = record
type
TRWCallback = TProc<PNPError, size_t, TBytes>;
TDirentWithTypes = record
name : UTF8String;
type_ : uv_dirent_type_t;
end;
TCallback = TProc<PNPError>;
TReadlinkCallBack = TProc<PNPError,UTF8String>;
TStatCallback = TProc<PNPError, puv_stat_t>;
TDirentCallBack = TProc<PNPError, TArray<UTF8String>>;
TDirentArray = TArray<UTF8String>;
TDirentWithTypesArray = TArray<TDirentWithTypes>;
TDirentWithTypesCallBack = TProc<PNPError, TDirentWithTypesArray>;
class procedure open(const path: UTF8String; flags:integer; mode:integer; cb : TProc<PNPError,uv_file>);static;
class procedure close(Afile : uv_file; cb : TCallback); static;
class procedure read(Afile : uv_file; Abuffer:TBytes; Aoffset : size_t; Alength: size_t; APosition:int64; cb : TRWCallback); overload; static;
class procedure read(Afile : uv_file; Abuffer:TBytes; Aoffset : size_t; Alength: size_t; cb : TRWCallback); overload; static;
class procedure read(Afile : uv_file; Abuffer:TBytes; APosition:int64; cb : TRWCallback); overload; static;
class procedure read(Afile : uv_file; Abuffer:TBytes; cb : TRWCallback); overload; static;
class procedure write(Afile : uv_file; Abuffer:TBytes; Aoffset : size_t; Alength: size_t; APosition:int64; cb : TRWCallback); overload; static;
class procedure write(Afile : uv_file; Abuffer:TBytes; Aoffset : size_t; Alength: size_t; cb : TRWCallback); overload; static;
class procedure write(Afile : uv_file; Abuffer:TBytes; APosition:int64; cb : TRWCallback); overload; static;
class procedure write(Afile : uv_file; Abuffer:TBytes; cb : TRWCallback); overload; static;
class procedure ftruncate(Afile : uv_file;offset:int64; cb: TCallback); overload; static;
class procedure ftruncate(Afile : uv_file;cb: TCallback); overload; static;
class procedure unlink(const path:UTF8String; cb: TCallback); static;
class procedure stat(const path:UTF8String; cb: TStatCallback); static;
class procedure fstat(const aFile:uv_file; cb: TStatCallback); static;
class procedure lstat(const path:UTF8String; cb: TStatCallback); static;
class procedure utime(const path:UTF8String;Aatime:Double; Amtime:Double; cb: TCallback); static;
class procedure futime(const aFile:uv_file;Aatime:Double; Amtime:Double; cb: TCallback); static;
class procedure fsync(Afile: uv_file; cb : TCallBack); static;
class procedure access(const path: UTF8String; mode: integer; cb: TCallBack); static;
class procedure fdatasync(Afile: uv_file; cb : TCallBack); static;
class procedure mkdir(const path:UTF8String; mode:integer; cb: TCallBack); static;
class procedure mkdtemp(const path:UTF8String; mode:integer; cb: TCallBack); static;
class procedure rmdir(const path:UTF8String; mode:integer; cb: TCallBack); static;
class procedure readdir(const path:UTF8String; cb: TDirentCallBack); overload; static;
class procedure readdir(const path:UTF8String; cb: TDirentWithTypesCallBack); overload; static;
class procedure rename(const path:UTF8String; const new_path : UTF8String; cb : TCallBack); static;
class procedure copyfile(const path:UTF8String; const new_path : UTF8String; flags: integer; cb : TCallBack); overload; static;
class procedure copyfile(const path:UTF8String; const new_path : UTF8String; cb : TCallBack); overload; static;
class procedure symlink(const path:UTF8String; const new_path : UTF8String; flags: integer; cb : TCallBack); overload; static;
class procedure link(const path:UTF8String; const new_path : UTF8String; cb : TCallBack); overload; static;
class procedure readlink(const path:UTF8String; cb : TReadlinkCallBack); static;
class procedure realpath(const path:UTF8String; cb : TReadlinkCallBack); static;
end;
implementation
uses generics.collections;
type
PReqInternal = ^TReqInternal;
TReqInternal = packed record
base: uv_fs_t;
//path: UTF8String; //keep ref
callback_open: TProc<PNPError,uv_file>;
callback_error: fs.TCallback;
buffer: TBytes;
callback_rw: fs.TRWCallback;
callback_stat: fs.TStatCallback;
callback_dirent: fs.TDirentCallBack;
callback_direntWithTypes: fs.TDirentWithTypesCallBack;
callback_readlink : fs.TReadlinkCallBack;
end;
procedure fs_cb(req :puv_fs_t); cdecl;
var
cast : PReqInternal;
error : TNPError;
perror: PNPError;
res : SSIZE_T;
dirent: uv_dirent_t;
direntResWt : TList<fs.TDirentWithTypes>;
direntRes : TList<UTF8String>;
direntItem : fs.TDirentWithTypes;
stat : puv_stat_t;
begin
cast := PReqInternal(req);
perror := nil;
res := uv_fs_get_result(req);
if res < 0 then
begin
error.Init( integer(res) );
perror := @error;
end;
try
case uv_fs_get_type(req) of
UV_FS_OPEN_:
begin
if assigned( cast.callback_open ) then
cast.callback_open(pError, res );
end;
UV_FS_READ_,UV_FS_WRITE_:
begin
if assigned( cast.callback_rw ) then
cast.callback_rw(perror,res,cast.buffer);
end;
UV_FS_STAT_, UV_FS_LSTAT_, UV_FS_FSTAT_:
begin
if assigned( cast.callback_stat) then
begin
if res >= 0 then
begin
stat := uv_fs_get_statbuf(cast.base);
cast.callback_stat(nil, stat);
end
else
cast.callback_stat(perror, nil);
end;
end;
UV_FS_SCANDIR_:
begin
if assigned(perror) then
begin
if assigned(cast.callback_direntWithTypes) then
cast.callback_direntWithTypes(perror,nil)
else
if assigned(cast.callback_dirent) then
cast.callback_dirent(perror,nil);
end
else
if assigned(cast.callback_direntWithTypes) then
begin
direntResWt := TList<fs.TDirentWithTypes>.Create;
try
while uv_fs_scandir_next( req, @dirent ) >= 0 do
begin
direntItem.name := CStrUtf8( dirent.name );
direntItem.type_ := dirent.&type;
direntResWt.Add( direntItem );
end;
cast.callback_direntWithTypes(nil, direntResWt.ToArray);
finally
direntResWt.Free;
end;
end
else
if assigned(cast.callback_dirent) then
begin
direntRes := TList<UTF8String>.Create;
try
while uv_fs_scandir_next( req, @dirent ) >= 0 do
begin
direntRes.Add( CStrUtf8( dirent.name ) );
end;
cast.callback_dirent(nil, direntRes.ToArray);
finally
direntRes.Free;
end;
end;
end;
UV_FS_READLINK_, UV_FS_REALPATH_:
begin
if assigned( cast.callback_readlink ) then
begin
if assigned(pError) then
cast.callback_readlink(pError,'')
else
cast.callback_readlink(pError,CStrUtf8( uv_fs_get_ptr(req) ));
end;
end;
else
begin
if assigned( cast.callback_error ) then
cast.callback_error(pError)
end;
end;
finally
uv_fs_req_cleanup(req);
Dispose(cast);
end;
end;
{ fs }
class procedure fs.access(const path: UTF8String; mode: integer; cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_access(loop.uvloop, @req.base, @path[1], mode, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.close(Afile: uv_file; cb: TProc<PNPError>);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_close(loop.uvloop, @req.base, aFile, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.ftruncate(Afile: uv_file; cb: TCallback);
begin
fs.ftruncate(aFile,0,cb);
end;
class procedure fs.ftruncate(Afile: uv_file; offset: int64; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_ftruncate(loop.uvloop, @req.base, aFile, offset, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.open(const path: UTF8String; flags, mode: integer;
cb: TProc<PNPError,uv_file>);
var
req : PReqInternal;
res : Integer;
begin
New(req);
//req.path := path; //keep ref...but why?!
req.callback_open := cb;
res := uv_fs_open(loop.uvloop, @req.base, @path[1], flags, mode, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,res);
end;
end);
end;
end;
class procedure fs.read(Afile : uv_file; Abuffer:TBytes;
Aoffset : size_t; Alength: size_t;
APosition:int64;
cb : TRWCallback);
var
req : PReqInternal;
res : Integer;
buf : uv_buf_t;
begin
if Alength > High(buf.len) then
ALength := High(buf.len);
if ALength + AOffset > Length(Abuffer) then
raise ERangeError.CreateFmt('range error buffer[%d..%d] length = %d', [AOffset,AOffset + ALength-1, Length(ABuffer)] );
New(req);
req.callback_rw := cb;
req.buffer := Abuffer;
buf.len := Alength;
buf.base := @ABuffer[AOffset];
res := uv_fs_read(loop.uvloop, @req.base, Afile, @buf, 1, APosition, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,0,ABuffer);
end;
end);
end;
end;
class procedure fs.write(Afile : uv_file; Abuffer:TBytes;
Aoffset : size_t; Alength: size_t;
APosition:int64;
cb : TRWCallback);
var
req : PReqInternal;
res : Integer;
buf : uv_buf_t;
begin
if ALength + AOffset > Length(Abuffer) then
raise ERangeError.CreateFmt('range error buffer[%d..%d] length = %d', [AOffset,AOffset + ALength-1, Length(ABuffer)] );
New(req);
req.callback_rw := cb;
req.buffer := Abuffer;
if Alength > High(buf.len) then
ALength := High(buf.len);
buf.len := Alength;
buf.base := @ABuffer[AOffset];
res := uv_fs_write(loop.uvloop, @req.base, Afile, @buf, 1, APosition, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,0,ABuffer);
end;
end);
end;
end;
class procedure fs.read(Afile : uv_file; Abuffer:TBytes; Aoffset : size_t; Alength: size_t; cb : TRWCallback);
begin
fs.read(Afile,ABuffer,Aoffset, Alength, -1, cb);
end;
class procedure fs.read(Afile : uv_file; Abuffer:TBytes; APosition:int64; cb : TRWCallback);
begin
fs.read(Afile,ABuffer,0, length(ABuffer), APosition, cb);
end;
class procedure fs.read(Afile : uv_file; Abuffer:TBytes; cb : TRWCallback);
begin
fs.read(Afile,ABuffer, -1, cb);
end;
class procedure fs.readdir(const path: UTF8String;
cb: TDirentWithTypesCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_direntWithTypes := cb;
res := uv_fs_scandir(loop.uvloop, @req.base, @path[1],0, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,nil);
end;
end);
end;
end;
class procedure fs.readlink(const path: UTF8String; cb: TReadlinkCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_readlink := cb;
res := uv_fs_readlink(loop.uvloop, @req.base, @path[1],@fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,'');
end;
end);
end;
end;
class procedure fs.realpath(const path: UTF8String; cb: TReadlinkCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_readlink := cb;
res := uv_fs_realpath(loop.uvloop, @req.base, @path[1],@fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,'');
end;
end);
end;
end;
class procedure fs.rename(const path, new_path: UTF8String; cb:TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_rename(loop.uvloop, @req.base, @path[1],@new_path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.readdir(const path: UTF8String; cb: TDirentCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_dirent := cb;
res := uv_fs_scandir(loop.uvloop, @req.base, @path[1],0, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,nil);
end;
end);
end;
end;
class procedure fs.stat(const path: UTF8String; cb: TStatCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_stat := cb;
res := uv_fs_stat(loop.uvloop, @req.base, @path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,nil);
end;
end);
end;
end;
class procedure fs.symlink(const path, new_path: UTF8String; flags: integer;
cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_symlink(loop.uvloop, @req.base, @path[1],@new_path[1],flags, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.link(const path, new_path: UTF8String; cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_link(loop.uvloop, @req.base, @path[1],@new_path[1],@fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.lstat(const path: UTF8String; cb: TStatCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_stat := cb;
res := uv_fs_lstat(loop.uvloop, @req.base, @path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,nil);
end;
end);
end;
end;
class procedure fs.mkdir(const path: UTF8String; mode: integer; cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_mkdir(loop.uvloop, @req.base, @path[1],mode, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.mkdtemp(const path: UTF8String; mode: integer; cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_mkdtemp(loop.uvloop, @req.base, @path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.rmdir(const path: UTF8String; mode: integer; cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_rmdir(loop.uvloop, @req.base, @path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.fstat(const afile: uv_file; cb: TStatCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_stat := cb;
res := uv_fs_fstat(loop.uvloop, @req.base, afile, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error,nil);
end;
end);
end;
end;
class procedure fs.fsync(afile: uv_file; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_fsync(loop.uvloop, @req.base, afile, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.copyfile(const path, new_path: UTF8String; flags: integer;
cb: TCallBack);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_copyfile(loop.uvloop, @req.base, @path[1],@new_path[1],flags, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.copyfile(const path, new_path: UTF8String; cb: TCallBack);
begin
copyfile(path, new_path,0,cb);
end;
class procedure fs.fdatasync(afile: uv_file; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_fdatasync(loop.uvloop, @req.base, afile, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error);
end;
end);
end;
end;
class procedure fs.unlink(const path: UTF8String; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_unlink(loop.uvloop, @req.base, @path[1], @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.futime(const aFile:uv_file;Aatime:Double; Amtime:Double; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_futime(loop.uvloop, @req.base,afile,Aatime,Amtime, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.utime(const path: UTF8String; Aatime:Double; Amtime:Double; cb: TCallback);
var
req : PReqInternal;
res : Integer;
begin
New(req);
req.callback_error := cb;
res := uv_fs_utime(loop.uvloop, @req.base, @path[1],Aatime,Amtime, @fs_cb);
if res < 0 then
begin
Dispose(req);
NextTick(
procedure
var
error : TNPError;
begin
if assigned(cb) then
begin
error.Init(res);
cb(@error)
end;
end);
end;
end;
class procedure fs.write(Afile: uv_file; Abuffer: TBytes; cb: TRWCallback);
begin
fs.write(afile,aBuffer,0,length(aBuffer),cb);
end;
class procedure fs.write(Afile: uv_file; Abuffer: TBytes; APosition: int64;
cb: TRWCallback);
begin
fs.write(afile,aBuffer,0,length(aBuffer),APosition,cb);
end;
class procedure fs.write(Afile: uv_file; Abuffer: TBytes; Aoffset,
Alength: size_t; cb: TRWCallback);
begin
fs.write(afile,ABuffer,AOffset,ALength,-1,cb);
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAsn1InputStream;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
Generics.Collections,
{$IFDEF DELPHI}
ClpIDerNull,
{$ENDIF DELPHI}
ClpAsn1Tags,
ClpDefiniteLengthInputStream,
ClpDerOctetString,
ClpIndefiniteLengthInputStream,
ClpAsn1StreamParser,
ClpIAsn1StreamParser,
ClpDerBitString,
ClpDerBmpString,
// ClpDerGeneralizedTime,
// ClpDerUtcTime,
ClpDerGeneralString,
ClpDerGraphicString,
ClpDerIA5String,
ClpDerNumericString,
ClpDerPrintableString,
ClpDerT61String,
ClpDerUniversalString,
ClpDerUtf8String,
ClpDerVideotexString,
ClpDerVisibleString,
ClpDerBoolean,
ClpDerEnumerated,
ClpDerApplicationSpecific,
ClpDerExternal,
ClpDerInteger,
ClpDerNull,
ClpDerObjectIdentifier,
ClpBerOctetString,
ClpIProxiedInterface,
ClpIDerSequence,
ClpIDerOctetString,
ClpIDerSet,
ClpLimitedInputStream,
ClpAsn1EncodableVector,
ClpDerSequence,
ClpDerSet,
ClpIAsn1EncodableVector,
ClpFilterStream,
ClpCryptoLibTypes;
resourcestring
SCorruptedStream = 'Corrupted Stream - Invalid High Tag Number Found';
SEOFFound = 'EOF Found Inside Tag Value';
SInvalidEnd = 'EOF Found When Length Expected';
SInvalidDerLength = 'DER Length More Than 4 Bytes: %d';
SEndOfStream = 'EOF Found Reading Length';
SNegativeLength = 'Corrupted Stream - Negative Length Found';
SOutOfBoundsLength = 'Corrupted stream - Out of Bounds Length Found';
SUnknownTag = 'Unknown Tag " %d " Encountered';
SEndOfContent = 'Unexpected End-of-Contents Marker';
SIndefiniteLength = 'Indefinite Length Primitive Encoding Encountered';
SUnknownBerObject = 'Unknown BER Object Encountered';
SCorruptedStreamTwo = 'Corrupted Stream Detected: %s';
type
/// <summary>
/// a general purpose ASN.1 decoder - note: this class differs from the <br />
/// others in that it returns null after it has read the last object in <br />
/// the stream. If an ASN.1 Null is encountered a DerBER Null object is <br />
/// returned. <br />
/// </summary>
TAsn1InputStream = class(TFilterStream)
strict private
var
Flimit: Int32;
FtmpBuffers: TCryptoLibMatrixByteArray;
FStream: TStream;
/// <summary>
/// build an object given its tag and the number of bytes to construct it
/// from.
/// </summary>
function BuildObject(tag, tagNo, length: Int32): IAsn1Object;
public
constructor Create(const inputStream: TStream); overload;
/// <summary>
/// Create an ASN1InputStream where no DER object will be longer than
/// limit.
/// </summary>
/// <param name="inputStream">
/// stream containing ASN.1 encoded data.
/// </param>
/// <param name="limit">
/// maximum size of a DER encoded object.
/// </param>
constructor Create(const inputStream: TStream; limit: Int32); overload;
destructor Destroy(); override;
/// <summary>
/// the stream is automatically limited to the length of the input array.
/// </summary>
/// <param name="input">
/// array containing ASN.1 encoded data.
/// </param>
constructor Create(const input: TCryptoLibByteArray); overload;
function ReadObject(): IAsn1Object;
function BuildEncodableVector(): IAsn1EncodableVector;
function BuildDerEncodableVector(const dIn: TDefiniteLengthInputStream)
: IAsn1EncodableVector; virtual;
function CreateDerSequence(const dIn: TDefiniteLengthInputStream)
: IDerSequence; virtual;
function CreateDerSet(const dIn: TDefiniteLengthInputStream)
: IDerSet; virtual;
class function FindLimit(const input: TStream): Int32; static;
class function ReadTagNumber(const s: TStream; tag: Int32): Int32; static;
class function ReadLength(const s: TStream; limit: Int32): Int32; static;
class function GetBuffer(const defIn: TDefiniteLengthInputStream;
const tmpBuffers: TCryptoLibMatrixByteArray): TCryptoLibByteArray;
static; inline;
class function CreatePrimitiveDerObject(tagNo: Int32;
const defIn: TDefiniteLengthInputStream;
const tmpBuffers: TCryptoLibMatrixByteArray): IAsn1Object; static;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpStreamSorter,
ClpBerOctetStringParser,
ClpBerSequenceParser,
ClpBerSetParser,
ClpDerExternalParser,
ClpBerApplicationSpecificParser,
ClpBerTaggedObjectParser,
ClpIBerOctetStringParser,
ClpIBerSequenceParser,
ClpIBerSetParser,
ClpIDerExternalParser,
ClpIBerApplicationSpecificParser,
ClpIBerTaggedObjectParser;
{ TAsn1InputStream }
class function TAsn1InputStream.FindLimit(const input: TStream): Int32;
var
limitedInputStream: TLimitedInputStream;
mem: TMemoryStream;
begin
limitedInputStream := input as TLimitedInputStream;
if (limitedInputStream <> Nil) then
begin
result := limitedInputStream.GetRemaining();
Exit;
end
else if (input is TMemoryStream) then
begin
mem := input as TMemoryStream;
result := Int32(mem.Size - mem.Position);
Exit;
end;
result := System.High(Int32);
end;
class function TAsn1InputStream.GetBuffer(const defIn
: TDefiniteLengthInputStream; const tmpBuffers: TCryptoLibMatrixByteArray)
: TCryptoLibByteArray;
var
len: Int32;
buf, temp: TCryptoLibByteArray;
begin
len := defIn.GetRemaining();
if (len >= System.length(tmpBuffers)) then
begin
result := defIn.ToArray();
Exit;
end;
buf := tmpBuffers[len];
if (buf = Nil) then
begin
System.SetLength(temp, len);
tmpBuffers[len] := temp;
buf := tmpBuffers[len];
end;
defIn.ReadAllIntoByteArray(buf);
result := buf;
end;
class function TAsn1InputStream.CreatePrimitiveDerObject(tagNo: Int32;
const defIn: TDefiniteLengthInputStream;
const tmpBuffers: TCryptoLibMatrixByteArray): IAsn1Object;
var
bytes: TCryptoLibByteArray;
begin
case tagNo of
TAsn1Tags.Boolean:
begin
result := TDerBoolean.FromOctetString(GetBuffer(defIn, tmpBuffers));
Exit;
end;
TAsn1Tags.Enumerated:
begin
result := TDerEnumerated.FromOctetString(GetBuffer(defIn, tmpBuffers));
Exit;
end;
TAsn1Tags.ObjectIdentifier:
begin
result := TDerObjectIdentifier.FromOctetString
(GetBuffer(defIn, tmpBuffers));
Exit;
end;
end;
bytes := defIn.ToArray();
case tagNo of
TAsn1Tags.BitString:
begin
result := TDerBitString.FromAsn1Octets(bytes);
Exit;
end;
TAsn1Tags.BmpString:
begin
result := TDerBmpString.Create(bytes);
Exit;
end;
// TAsn1Tags.GeneralizedTime:
// begin
// result := TDerGeneralizedTime.Create(bytes);
// Exit;
// end;
TAsn1Tags.GeneralString:
begin
result := TDerGeneralString.Create(bytes);
Exit;
end;
TAsn1Tags.GraphicString:
begin
result := TDerGraphicString.Create(bytes);
Exit;
end;
TAsn1Tags.IA5String:
begin
result := TDerIA5String.Create(bytes);
Exit;
end;
TAsn1Tags.Integer:
begin
result := TDerInteger.Create(bytes);
Exit;
end;
TAsn1Tags.Null:
begin
// actual content is ignored (enforce 0 length?)
result := TDerNull.Instance;
Exit;
end;
TAsn1Tags.NumericString:
begin
result := TDerNumericString.Create(bytes);
Exit;
end;
TAsn1Tags.OctetString:
begin
result := TDerOctetString.Create(bytes);
Exit;
end;
TAsn1Tags.PrintableString:
begin
result := TDerPrintableString.Create(bytes);
Exit;
end;
TAsn1Tags.T61String:
begin
result := TDerT61String.Create(bytes);
Exit;
end;
TAsn1Tags.UniversalString:
begin
result := TDerUniversalString.Create(bytes);
Exit;
end;
// TAsn1Tags.UtcTime:
// begin
// result := TDerUtcTime.Create(bytes);
// Exit;
// end;
TAsn1Tags.Utf8String:
begin
result := TDerUtf8String.Create(bytes);
Exit;
end;
TAsn1Tags.VideotexString:
begin
result := TDerVideotexString.Create(bytes);
Exit;
end;
TAsn1Tags.VisibleString:
begin
result := TDerVisibleString.Create(bytes);
Exit;
end;
else
begin
raise EIOCryptoLibException.CreateResFmt(@SUnknownTag, [tagNo]);
end;
end;
end;
destructor TAsn1InputStream.Destroy;
begin
FStream.Free;
inherited Destroy;
end;
constructor TAsn1InputStream.Create(const inputStream: TStream; limit: Int32);
begin
Inherited Create(inputStream);
Flimit := limit;
System.SetLength(FtmpBuffers, 16);
end;
constructor TAsn1InputStream.Create(const inputStream: TStream);
begin
Create(inputStream, FindLimit(inputStream));
end;
constructor TAsn1InputStream.Create(const input: TCryptoLibByteArray);
begin
// used TBytesStream here for one pass creation and population with byte array :)
FStream := TBytesStream.Create(input);
Create(FStream, System.length(input));
end;
class function TAsn1InputStream.ReadLength(const s: TStream;
limit: Int32): Int32;
var
&length, Size, next, I: Int32;
begin
length := TStreamSorter.ReadByte(s);
if (length < 0) then
begin
raise EEndOfStreamCryptoLibException.CreateRes(@SInvalidEnd);
end;
if (length = $80) then
begin
result := -1; // indefinite-length encoding
Exit;
end;
if (length > 127) then
begin
Size := length and $7F;
// Note: The invalid long form "$ff" (see X.690 8.1.3.5c) will be caught here
if (Size > 4) then
begin
raise EIOCryptoLibException.CreateResFmt(@SInvalidDerLength, [Size]);
end;
length := 0;
I := 0;
while I < Size do
begin
next := TStreamSorter.ReadByte(s);
if (next < 0) then
begin
raise EEndOfStreamCryptoLibException.CreateRes(@SEndOfStream);
end;
length := (length shl 8) + next;
System.Inc(I);
end;
if (length < 0) then
begin
raise EIOCryptoLibException.CreateRes(@SNegativeLength);
end;
if (length >= limit) then // after all we must have read at least 1 byte
begin
raise EIOCryptoLibException.CreateRes(@SOutOfBoundsLength);
end;
end;
result := length;
end;
function TAsn1InputStream.ReadObject: IAsn1Object;
var
tag, tagNo, &length: Int32;
isConstructed: Boolean;
indIn: TIndefiniteLengthInputStream;
sp: IAsn1StreamParser;
begin
tag := ReadByte();
if (tag <= 0) then
begin
if (tag = 0) then
begin
raise EIOCryptoLibException.CreateRes(@SEndOfContent);
end;
result := Nil;
Exit;
end;
//
// calculate tag number
//
tagNo := ReadTagNumber(Fs, tag);
isConstructed := (tag and TAsn1Tags.Constructed) <> 0;
//
// calculate length
//
length := ReadLength(Fs, Flimit);
if (length < 0) then // indefinite length method
begin
if (not isConstructed) then
begin
raise EIOCryptoLibException.CreateRes(@SIndefiniteLength);
end;
indIn := TIndefiniteLengthInputStream.Create(Fs, Flimit);
sp := TAsn1StreamParser.Create(indIn, Flimit);
if ((tag and TAsn1Tags.Application) <> 0) then
begin
result := (TBerApplicationSpecificParser.Create(tagNo, sp)
as IBerApplicationSpecificParser).ToAsn1Object();
Exit;
end;
if ((tag and TAsn1Tags.Tagged) <> 0) then
begin
result := (TBerTaggedObjectParser.Create(true, tagNo, sp)
as IBerTaggedObjectParser).ToAsn1Object();
Exit;
end;
// TODO There are other tags that may be constructed (e.g. BitString)
case tagNo of
TAsn1Tags.OctetString:
begin
result := (TBerOctetStringParser.Create(sp) as IBerOctetStringParser)
.ToAsn1Object();
Exit;
end;
TAsn1Tags.Sequence:
begin
result := (TBerSequenceParser.Create(sp) as IBerSequenceParser)
.ToAsn1Object();
Exit;
end;
TAsn1Tags.&Set:
begin
result := (TBerSetParser.Create(sp) as IBerSetParser).ToAsn1Object();
Exit;
end;
TAsn1Tags.External:
begin
result := (TDerExternalParser.Create(sp) as IDerExternalParser)
.ToAsn1Object();
Exit;
end;
else
begin
raise EIOCryptoLibException.CreateRes(@SUnknownBerObject);
end;
end;
end
else
begin
try
result := BuildObject(tag, tagNo, length);
except
on e: EArgumentCryptoLibException do
begin
raise EAsn1CryptoLibException.CreateResFmt(@SCorruptedStreamTwo,
[e.Message]);
end;
end;
end;
end;
function TAsn1InputStream.BuildDerEncodableVector
(const dIn: TDefiniteLengthInputStream): IAsn1EncodableVector;
var
res: TAsn1InputStream;
begin
res := TAsn1InputStream.Create(dIn);
try
result := res.BuildEncodableVector();
finally
res.Free;
end;
end;
function TAsn1InputStream.BuildEncodableVector: IAsn1EncodableVector;
var
v: IAsn1EncodableVector;
o: IAsn1Object;
begin
v := TAsn1EncodableVector.Create();
o := ReadObject();
while (o <> Nil) do
begin
v.Add([o]);
o := ReadObject();
end;
result := v;
end;
function TAsn1InputStream.BuildObject(tag, tagNo, length: Int32): IAsn1Object;
var
isConstructed: Boolean;
defIn: TDefiniteLengthInputStream;
v: IAsn1EncodableVector;
strings: TList<IDerOctetString>;
I: Int32;
begin
isConstructed := (tag and TAsn1Tags.Constructed) <> 0;
defIn := TDefiniteLengthInputStream.Create(Fs, length);
if ((tag and TAsn1Tags.Application) <> 0) then
begin
try
result := TDerApplicationSpecific.Create(isConstructed, tagNo,
defIn.ToArray());
Exit;
finally
defIn.Free;
end;
end;
if ((tag and TAsn1Tags.Tagged) <> 0) then
begin
result := (TAsn1StreamParser.Create(defIn) as IAsn1StreamParser)
.ReadTaggedObject(isConstructed, tagNo);
Exit;
end;
if (isConstructed) then
begin
// TODO There are other tags that may be constructed (e.g. BitString)
case (tagNo) of
TAsn1Tags.OctetString:
//
// yes, people actually do this...
//
begin
try
v := BuildDerEncodableVector(defIn);
strings := TList<IDerOctetString>.Create;
strings.Capacity := v.Count;
I := 0;
while (I <> v.Count) do
begin
strings.Add(v[I] as IDerOctetString);
end;
result := TBerOctetString.Create(strings);
Exit;
finally
defIn.Free;
end;
end;
TAsn1Tags.Sequence:
begin
try
result := CreateDerSequence(defIn);
Exit;
finally
defIn.Free;
end;
end;
TAsn1Tags.&Set:
begin
try
result := CreateDerSet(defIn);
Exit;
finally
defIn.Free;
end;
end;
TAsn1Tags.External:
begin
try
result := TDerExternal.Create(BuildDerEncodableVector(defIn));
Exit;
finally
defIn.Free;
end;
end;
else
begin
defIn.Free; // free the stream incase an unsupported tag is encountered.
raise EIOCryptoLibException.CreateResFmt(@SUnknownTag, [tagNo]);
end;
end;
end;
try
result := CreatePrimitiveDerObject(tagNo, defIn, FtmpBuffers);
finally
defIn.Free;
end;
end;
function TAsn1InputStream.CreateDerSequence
(const dIn: TDefiniteLengthInputStream): IDerSequence;
begin
result := TDerSequence.FromVector(BuildDerEncodableVector(dIn));
end;
function TAsn1InputStream.CreateDerSet(const dIn
: TDefiniteLengthInputStream): IDerSet;
begin
result := TDerSet.FromVector(BuildDerEncodableVector(dIn), false);
end;
class function TAsn1InputStream.ReadTagNumber(const s: TStream;
tag: Int32): Int32;
var
tagNo, b: Int32;
begin
tagNo := tag and $1F;
//
// with tagged object tag number is bottom 5 bits, or stored at the start of the content
//
if (tagNo = $1F) then
begin
tagNo := 0;
b := TStreamSorter.ReadByte(s);
// X.690-0207 8.1.2.4.2
// "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
if ((b and $7F) = 0) then // Note: -1 will pass
begin
raise EIOCryptoLibException.CreateRes(@SCorruptedStream);
end;
while ((b >= 0) and ((b and $80) <> 0)) do
begin
tagNo := tagNo or (b and $7F);
tagNo := tagNo shl 7;
b := TStreamSorter.ReadByte(s);
end;
if (b < 0) then
begin
raise EEndOfStreamCryptoLibException.CreateRes(@SEOFFound);
end;
tagNo := tagNo or (b and $7F);
end;
result := tagNo;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_Solids
* Implements generic platonic solid meshes
***********************************************************************************************************************
}
Unit TERRA_Solids;
{$I terra.inc}
//http://www.geometrictools.com/Documentation/PlatonicSolids.pdf
Interface
Uses TERRA_Utils, TERRA_Math, TERRA_GraphicsManager, TERRA_Resource, TERRA_BoundingBox, TERRA_Vector3D,
TERRA_Vector2D, TERRA_Vector4D, TERRA_Matrix4x4, TERRA_Color, TERRA_Mesh, TERRA_MeshFilter, TERRA_Texture,
TERRA_VertexFormat;
Type
SolidVertex = Class(Vertex)
Protected
Procedure Load(); Override;
Procedure Save(); Override;
Public
Position:Vector3D;
Normal:Vector3D;
Tangent:Vector4D;
TextureCoords:Vector2D;
Color:TERRA_Color.Color;
End;
InternalSolidVertex = Packed Record
Position:Vector3D;
Normal:Vector3D;
TextureCoords:Vector2D;
End;
SolidMesh = Class(Renderable)
Protected
_VertexList:Array Of InternalSolidVertex;
_VertexCount:Integer;
_IndexList:Array Of Word;
_IndexCount:Integer;
_Box:BoundingBox;
Procedure AddTriangle(A,B,C:Word);
Procedure MoveToOrigin;
Procedure AddMesh(Mesh:SolidMesh);
Function DuplicateVertex(Index:Integer):Integer;
Procedure UpdateBoundingBox;
Public
Procedure Transform(MyMatrix:Matrix4x4);
Procedure Weld(Radius:Single);
Function GetBoundingBox:BoundingBox; Override;
Procedure Render(Translucent:Boolean); Override;
Procedure Invert;
Function GetVertex(Index:Integer):InternalSolidVertex;
Function GetIndex(Index:Integer):Integer;
Property VertexCount:Integer Read _VertexCount;
Property IndexCount:Integer Read _IndexCount;
End;
TetrahedronMesh = Class(SolidMesh)
Public
Constructor Create();
End;
OctahedronMesh = Class(SolidMesh)
Public
Constructor Create();
End;
IcosahedronMesh = Class(SolidMesh)
Public
Constructor Create();
End;
PlaneMesh = Class(SolidMesh)
Public
Constructor Create(Const Normal:Vector3D; SubDivisions:Cardinal; OfsX, OfsY:Single);
End;
CubeMesh = Class(SolidMesh)
Public
Constructor Create(SubDivisions:Cardinal);
End;
SphereMesh = Class(SolidMesh)
Public
Constructor Create(SubDivisions:Cardinal);
End;
CylinderMesh = Class(SolidMesh)
Public
Constructor Create(Stacks, Slices:Cardinal; Capped:Boolean = True);
End;
ConeMesh = Class(SolidMesh)
Public
Constructor Create(Stacks, Slices:Cardinal; Inverted:Boolean; Capped:Boolean = True);
End;
Function CreateMeshFromSolid(S:SolidMesh; Tex:Texture = Nil):Mesh;
Implementation
Uses TERRA_Error;
{Procedure SolidMesh.AddPolygon(IndexList:Array Of Word; Count:Integer);
Var
I,N:Integer;
Begin
N := _IndexCount;
Inc(_IndexCount, (Count - 2) * 3);
SetLength(_IndexList, _IndexCount);
For I := 1 To (Count - 2) Do
Begin
_IndexList[N] := IndexList[0]; Inc(N);
_IndexList[N] := IndexList[I + 0]; Inc(N);
_IndexList[N] := IndexList[I + 1]; Inc(N);
End;
End;}
Procedure SolidMesh.UpdateBoundingBox;
Var
I:Integer;
Begin
_Box.Reset;
For I:=0 To Pred(_VertexCount) Do
_Box.Add(_VertexList[I].Position);
End;
Function SolidMesh.GetBoundingBox:BoundingBox;
Begin
Result := _Box;
End;
Procedure SolidMesh.AddTriangle(A,B,C:Word);
Var
N:Integer;
Begin
N := _IndexCount;
Inc(_IndexCount, 3);
SetLength(_IndexList, _IndexCount);
If (A>=_VertexCount) Or (B>=_VertexCount) Or (C>=_VertexCount) Then
IntToString(2);
_IndexList[N+0] := A;
_IndexList[N+1] := B;
_IndexList[N+2] := C
End;
Procedure SolidMesh.Render(Translucent:Boolean);
Var
I:Integer;
Begin
If (_IndexCount<=0) Or (Translucent) Then
Exit;
GraphicsManager.Instance.EnableColorShader(ColorWhite, Matrix4x4Identity);
(*
glDisable(GL_CULL_FACE);
glBegin(GL_TRIANGLES);
I := 0;
While (I < _IndexCount) Do
Begin
glNormal3fv(@_VertexList[_IndexList[I]].Normal);
glMultiTexCoord3fv(GL_TEXTURE0, @_VertexList[_IndexList[I]].TextureCoords);
glVertex3fv(@_VertexList[_IndexList[I]].Position);
Inc(I);
End;
glEnd;
glEnable(GL_CULL_FACE);
BIBI *)
End;
Function SolidMesh.DuplicateVertex(Index:Integer):Integer;
Begin
Inc(_VertexCount);
SetLength(_VertexList, _VertexCount);
_VertexList[Pred(_VertexCount)] := _VertexList[Index];
Result := Pred(_VertexCount);
End;
Procedure SolidMesh.Transform(MyMatrix:Matrix4x4);
Var
I:Integer;
Begin
For I:=0 To Pred(_VertexCount) Do
Begin
_VertexList[I].Position := MyMatrix.Transform(_VertexList[I].Position);
End;
UpdateBoundingBox;
End;
Procedure SolidMesh.Weld(Radius:Single);
Var
I,J,K:Integer;
Begin
I := 0;
While (I<_VertexCount) Do
Begin
J:=0;
While (J<_VertexCount) Do
Begin
If (I=J) Then
Begin
Inc(J);
End Else
If (_VertexList[I].Position.Distance(_VertexList[J].Position)<=Radius) Then
Begin
For K:=0 To Pred(_IndexCount) Do
If (_IndexList[K] = J) Then
Begin
_IndexList[K] := I;
End Else
If (_IndexList[K] = Pred(_VertexCount)) Then
_IndexList[K] := J;
_VertexList[J] := _VertexList[Pred(_VertexCount)];
Dec(_VertexCount);
End Else
Inc(J);
End;
Inc(I);
End;
End;
Procedure SolidMesh.MoveToOrigin;
Var
I:Integer;
BB:BoundingBox;
Center:Vector3D;
Begin
BB.Reset;
For I:=0 To Pred(_VertexCount) Do
BB.Add(_VertexList[I].Position);
Center := BB.Center;
For I:=0 To Pred(_VertexCount) Do
_VertexList[I].Position := VectorSubtract(_VertexList[I].Position, Center);
UpdateBoundingBox;
End;
Procedure SolidMesh.Invert;
Var
I, K:Integer;
Begin
For I:=0 To Pred(_IndexCount) Do
If (I Mod 3 = 2) Then
Begin
K := _IndexList[I];
_IndexList[I] := _IndexList[I-2];
_IndexList[I-2] := K;
End;
End;
Procedure SolidMesh.AddMesh(Mesh:SolidMesh);
Var
I:Cardinal;
VO, IO:Cardinal;
Begin
VO := _VertexCount;
IO := _IndexCount;
Inc(_VertexCount, Mesh.VertexCount);
Inc(_IndexCount, Mesh.IndexCount);
SetLength(_VertexList, _VertexCount);
SetLength(_IndexList, _IndexCount);
For I:=0 To Pred(Mesh.VertexCount) Do
_VertexList[VO + I] := Mesh._VertexList[I];
For I:=0 To Pred(Mesh.IndexCount) Do
_IndexList[IO + I] := Mesh._IndexList[I] + VO;
UpdateBoundingBox;
End;
Function SolidMesh.GetVertex(Index:Integer):InternalSolidVertex;
Begin
If (Index>=0) And (Index<_VertexCount) Then
Result := _VertexList[Index]
Else
Begin
Result.Position := VectorZero;
RaiseError('Invalid vertex index');
End;
End;
Function SolidMesh.GetIndex(Index:Integer):Integer;
Begin
Result := _IndexList[Index];
End;
{Constructor SimpleCubeMesh.Create();
Begin
_VertexCount := 8;
SetLength(_VertexList, _VertexCount);
_VertexList[0].Position := VectorCreate(-Scale, -Scale, -Scale);
_VertexList[1].Position := VectorCreate(Scale, -Scale, -Scale);
_VertexList[2].Position := VectorCreate(Scale, Scale, -Scale);
_VertexList[3].Position := VectorCreate(-Scale, Scale, -Scale);
_VertexList[4].Position := VectorCreate(-Scale, -Scale, Scale);
_VertexList[5].Position := VectorCreate(Scale, -Scale, Scale);
_VertexList[6].Position := VectorCreate(Scale, Scale, Scale);
_VertexList[7].Position := VectorCreate(-Scale, Scale, Scale);
_IndexCount := 0;
AddTriangle(0,3,2);
AddTriangle(0,2,1);
AddTriangle(0,1,5);
AddTriangle(0,5,4);
AddTriangle(0,4,7);
AddTriangle(0,7,3);
AddTriangle(6,5,1);
AddTriangle(6,1,2);
AddTriangle(6,2,3);
AddTriangle(6,3,7);
AddTriangle(6,7,4);
AddTriangle(6,4,5);
Self.GenerateData;
End;}
{
v number of vertices A dihedral angle between adjacent faces
e number of edges R radius of circumscribed sphere
f number of faces r radius of inscribed sphere
p number of edges per face L edge length
q number of edges sharing a vertex S surface area
V volume
}
Constructor TetrahedronMesh.Create;
Const
Scale = 1.0;
Begin
_VertexCount := 4;
SetLength(_VertexList, _VertexCount);
_VertexList[0].Position := VectorCreate(0, 0, Scale);
_VertexList[1].Position := VectorCreate((2 * Sqrt(2)/3) * Scale, 0.0, (-1/3)*Scale);
_VertexList[2].Position := VectorCreate((-Sqrt(2)/3) * Scale, (Sqrt(6)/3) * Scale, (-1/3)*Scale);
_VertexList[3].Position := VectorCreate((-Sqrt(2)/3) * Scale, (-Sqrt(6)/3) * Scale, (-1/3)*Scale);
_IndexCount := 0;
AddTriangle(0,0,1);
AddTriangle(0,2,3);
AddTriangle(0,3,1);
AddTriangle(1,3,2);
Self.UpdateBoundingBox();
End;
Constructor OctahedronMesh.Create;
Const
Scale = 1.0;
Begin
_VertexCount := 6;
SetLength(_VertexList, _VertexCount);
_VertexList[0].Position := VectorCreate(Scale, 0, 0);
_VertexList[1].Position := VectorCreate(-Scale, 0, 0);
_VertexList[2].Position := VectorCreate(0, Scale, 0);
_VertexList[3].Position := VectorCreate(0, -Scale, 0);
_VertexList[4].Position := VectorCreate(0, 0, Scale);
_VertexList[5].Position := VectorCreate(0, 0, -Scale);
_IndexCount := 0;
AddTriangle(4,0,2);
AddTriangle(4,2,1);
AddTriangle(4,1,3);
AddTriangle(4,3,0);
AddTriangle(5,2,0);
AddTriangle(5,1,2);
AddTriangle(5,3,1);
AddTriangle(5,0,3);
Self.UpdateBoundingBox();
End;
Constructor IcosahedronMesh.Create();
Const
Scale = 1.0;
Var
T:Single;
Begin
T := ((1+Sqrt(5))/2) * Scale;
// S := (Sqrt(1 + Sqr(T))) * Scale;
_VertexCount := 12;
SetLength(_VertexList, _VertexCount);
_VertexList[0].Position := VectorCreate(T,1,0);
_VertexList[1].Position := VectorCreate(-T,1,0);
_VertexList[2].Position := VectorCreate(T,-1,0);
_VertexList[3].Position := VectorCreate(-T,-1,0);
_VertexList[4].Position := VectorCreate(1,0,T);
_VertexList[5].Position := VectorCreate(1,0,-T);
_VertexList[6].Position := VectorCreate(-1,0,T);
_VertexList[7].Position := VectorCreate(-1,0,-T);
_VertexList[8].Position := VectorCreate(0,T,1);
_VertexList[9].Position := VectorCreate(0,-T,1);
_VertexList[10].Position := VectorCreate(0,T,-1);
_VertexList[11].Position := VectorCreate(0,-T,-1);
_IndexCount := 0;
AddTriangle(0,8,4);
AddTriangle(0,5,10);
AddTriangle(2,4,9);
AddTriangle(2,11,5);
AddTriangle(1,6,8);
AddTriangle(1,10,7);
AddTriangle(3,9,6);
AddTriangle(3,7,11);
AddTriangle(0,10,8);
AddTriangle(1,8,10);
AddTriangle(2,9,11);
AddTriangle(3,11,9);
AddTriangle(4,2,0);
AddTriangle(5,0,2);
AddTriangle(6,1,3);
AddTriangle(7,3,1);
AddTriangle(8,6,4);
AddTriangle(9,4,6);
AddTriangle(10,5,7);
AddTriangle(11,7,5);
Self.UpdateBoundingBox();
End;
{ CylinderMesh }
Constructor CylinderMesh.Create(Stacks, Slices: Cardinal; Capped:Boolean);
Var
I,J:Cardinal ;
Dy, Angle:Single;
A,B,C,D:Cardinal;
Begin
_VertexCount := Succ(Stacks) * Succ(Slices);
SetLength(_VertexList, _VertexCount);
Dy := 1/Stacks;
For J:=0 To Stacks Do
Begin
For I:=0 To (Slices) Do
Begin
Angle := (I/Slices)*360*RAD;
_VertexList[J*Succ(Slices) + I].Position := VectorCreate(Cos(Angle), Dy * J, -Sin(Angle));
_VertexList[J*Succ(Slices) + I].TextureCoords.X := (I/(Slices));
_VertexList[J*Succ(Slices) + I].TextureCoords.Y := (J/Stacks);
_VertexList[J*Succ(Slices) + I].Normal := VectorCreate(Cos(Angle), 0, -Sin(Angle));
End;
End;
For J:=0 To Pred(Stacks) Do
Begin
For I:=0 To (Slices) Do
Begin
A := I;
B := Succ(I) Mod Succ(Slices);
C := A + Succ(Slices);
D := B + Succ(Slices);
AddTriangle(J*Succ(Slices) + A, J*Succ(Slices) + B, J*Succ(Slices) + C);
AddTriangle(J*Succ(Slices) + C, J*Succ(Slices) + B, J*Succ(Slices) + D);
End;
End;
If (Capped) Then
Begin
A := _VertexCount;
B := A + 1;
Inc(_VertexCount, 2);
SetLength(_VertexList, _VertexCount);
For J:=0 To 1 Do
Begin
If (J=0) Then
Begin
_VertexList[A+J].Position := VectorCreate(0, 1, 0);
_VertexList[A+J].Normal := VectorUp;
End Else
Begin
_VertexList[A+J].Position := VectorCreate(0, 0, 0);
_VertexList[A+J].Normal := VectorCreate(0, -1, 0);
End;
_VertexList[A+J].TextureCoords := VectorCreate2D(0.5, 0.5);
For I:=0 To Pred(Slices) Do
Begin
C := I;
D := Succ(I) Mod Succ(Slices);
If J=0 Then
AddTriangle(A+J, Stacks*Succ(Slices) + C, Stacks*Succ(Slices) + D)
Else
AddTriangle(D, C, A+J);
End;
End;
End;
End;
{ ConeMesh }
Constructor ConeMesh.Create(Stacks, Slices: Cardinal; Inverted, Capped:Boolean);
Var
I,J:Cardinal;
Dy, Scale, Angle:Single;
A,B,C,D:Cardinal;
Begin
_VertexCount := Succ(Stacks) * Succ(Slices);
SetLength(_VertexList, _VertexCount);
Dy := 1/Stacks;
For J:=0 To Stacks Do
Begin
Scale := (J/Stacks);
If Inverted Then
Scale := 1.0 - Scale;
For I:=0 To (Slices) Do
Begin
Angle := (I/Slices)*360*RAD;
_VertexList[J*Succ(Slices) + I].Position := VectorCreate(Cos(Angle)*Scale, Dy * Scale, -Sin(Angle)*Scale);
_VertexList[J*Succ(Slices) + I].TextureCoords.X := (I/(Slices));
_VertexList[J*Succ(Slices) + I].TextureCoords.Y := (J/Stacks);
_VertexList[J*Succ(Slices) + I].Normal := VectorCreate(Cos(Angle), 0, -Sin(Angle));
End;
End;
For J:=0 To Pred(Stacks) Do
Begin
For I:=0 To (Slices) Do
Begin
A := I;
B := Succ(I) Mod Succ(Slices);
C := A + Succ(Slices);
D := B + Succ(Slices);
AddTriangle(J*Succ(Slices) + A, J*Succ(Slices) + B, J*Succ(Slices) + C);
AddTriangle(J*Succ(Slices) + C, J*Succ(Slices) + B, J*Succ(Slices) + D);
End;
End;
If (Capped) Then
Begin
A := _VertexCount;
Inc(_VertexCount, 1);
SetLength(_VertexList, _VertexCount);
If Inverted Then
_VertexList[A].Position := VectorCreate(0, 0, 0)
Else
_VertexList[A].Position := VectorCreate(0, 1, 0);
_VertexList[A].Normal := VectorCreate(0, -1, 0);
_VertexList[A].TextureCoords := VectorCreate2D(0.5, 0.5);
For I:=0 To Pred(Slices) Do
Begin
C := I;
D := Succ(I) Mod Succ(Slices);
If Not Inverted Then
Begin
Inc(C, (Stacks) * Succ(Slices));
Inc(D, (Stacks) * Succ(Slices));
AddTriangle(A, C, D);
End Else
AddTriangle(D, C, A);
End;
End;
End;
Constructor PlaneMesh.Create(Const Normal:Vector3D; SubDivisions:Cardinal; OfsX, OfsY:Single);
Const
Size = 1.0;
Var
Index, I,J:Cardinal;
U,V:Vector3D;
S, SX,SY:Single;
Begin
_VertexCount := Sqr(Succ(SubDivisions));
SetLength(_VertexList, _VertexCount);
If (Abs(Normal.Y)>Abs(Normal.X)) And (Abs(Normal.Y)>Abs(Normal.Z)) Then
Begin
U := VectorCreate(Normal.X, Normal.Z, Normal.Y);
End Else
Begin
U := VectorCreate(Normal.Z, Normal.Y, Normal.X);
End;
V := VectorCross(Normal, U);
S := (1.0 / (SubDivisions)) * Size;
For J:=0 To SubDivisions Do
For I:=0 To SubDivisions Do
Begin
Index := (J * Succ(SubDivisions)) + I;
Sx := S * I;
Sy := S * J;
_VertexList[Index].Position := VectorAdd(VectorScale(U, Sx + OfsX), VectorScale(V, Sy + OfsY));
_VertexList[Index].TextureCoords.X := (1.0/Succ(SubDivisions)) * I;
_VertexList[Index].TextureCoords.Y := (1.0/Succ(SubDivisions)) * J;
_VertexList[Index].Normal := Normal;
End;
_IndexCount := 0;
For J:=0 To Pred(SubDivisions) Do
For I:=0 To Pred(SubDivisions) Do
Begin
Index := (J * Succ(SubDivisions));
AddTriangle(Index + I, Index + Succ(I), Index + I + Succ(SubDivisions));
AddTriangle(Index + Succ(I), Index + Succ(I) + Succ(SubDivisions) , Index + I + Succ(SubDivisions));
End;
Self.UpdateBoundingBox();
End;
Constructor CubeMesh.Create(SubDivisions:Cardinal);
Const
Size = 1.0;
Var
Mesh:SolidMesh;
MyMatrix:Matrix4x4;
I:Integer;
Begin
Mesh := PlaneMesh.Create(VectorCreate(0,0,1.0), SubDivisions, 0.0, 0.0);
MyMatrix := Matrix4x4Translation(-Size, -Size, Size);
Mesh.Transform(MyMatrix);
For I:=0 To Pred(Mesh._VertexCount) Do
Begin
Mesh._VertexList[I].TextureCoords.X := 1.0 - Mesh._VertexList[I].TextureCoords.X;
Mesh._VertexList[I].TextureCoords.Y := 1.0 - Mesh._VertexList[I].TextureCoords.Y;
End;
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Mesh := PlaneMesh.Create(VectorCreate(0,0,-1.0), SubDivisions, 0.0, 0.0);
MyMatrix := Matrix4x4Translation(0, -Size, 0);
Mesh.Transform(MyMatrix);
For I:=0 To Pred(Mesh._VertexCount) Do
Begin
Mesh._VertexList[I].TextureCoords.X := 1.0 - Mesh._VertexList[I].TextureCoords.X;
Mesh._VertexList[I].TextureCoords.Y := 1.0 - Mesh._VertexList[I].TextureCoords.Y;
End;
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Mesh := PlaneMesh.Create(VectorCreate(1.0,0,0.0), SubDivisions, 0.0, 0.0);
For I:=0 To Pred(Mesh._VertexCount) Do
Begin
Mesh._VertexList[I].TextureCoords.X := 1.0 - Mesh._VertexList[I].TextureCoords.X;
End;
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Mesh := PlaneMesh.Create(VectorCreate(-1.0,0,0.0), SubDivisions, 0.0, 0.0);
MyMatrix := Matrix4x4Translation(-Size, 0, Size);
For I:=0 To Pred(Mesh._VertexCount) Do
Begin
Mesh._VertexList[I].TextureCoords.X := 1.0 - Mesh._VertexList[I].TextureCoords.X;
End;
Mesh.Transform(MyMatrix);
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Mesh := PlaneMesh.Create(VectorCreate(0.0,1.0,0.0), SubDivisions, 0.0, 0.0);
MyMatrix := Matrix4x4Translation(-Size, 0, 0);
Mesh.Transform(MyMatrix);
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Mesh := PlaneMesh.Create(VectorCreate(0.0,-1.0,0.0), SubDivisions, 0.0, 0.0);
MyMatrix := Matrix4x4Translation(-Size, -Size, Size);
Mesh.Transform(MyMatrix);
For I:=0 To Pred(Mesh._VertexCount) Do
Begin
Mesh._VertexList[I].TextureCoords.X := 1.0 - Mesh._VertexList[I].TextureCoords.X;
Mesh._VertexList[I].TextureCoords.Y := 1.0 - Mesh._VertexList[I].TextureCoords.Y;
End;
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
Self.MoveToOrigin;
End;
Constructor SphereMesh.Create(SubDivisions:Cardinal);
Const
Size = 1.0;
Var
Mesh:SolidMesh;
I,K:Integer;
Normal:Vector3D;
A,B:Integer;
Procedure EdgeFix(A,B:Integer);
Var
Diff:Single;
Begin
Diff := Abs(_VertexList[_IndexList[A]].TextureCoords.X - _VertexList[_IndexList[B]].TextureCoords.X);
If (Diff>=0.75) Then
Begin
If (_VertexList[_IndexList[B]].TextureCoords.X>=1.0) Then
Begin
_IndexList[B] := DuplicateVertex(_IndexList[B]);
_VertexList[_IndexList[B]].TextureCoords.X := _VertexList[_IndexList[B]].TextureCoords.X - 1.0;
End Else
Begin
_IndexList[A] := DuplicateVertex(_IndexList[A]);
_VertexList[_IndexList[A]].TextureCoords.X := _VertexList[_IndexList[A]].TextureCoords.X - 1.0;
End;
End;
End;
Function IsPole(Index:Integer):Boolean;
Begin
Result := (_VertexList[Index].Normal.Y >=1.0) Or (_VertexList[Index].Normal.Y <=-1.0);
End;
Procedure FixPole(Pole, A,B:Integer);
Begin
_IndexList[Pole] := DuplicateVertex(_IndexList[Pole]);
_VertexList[_IndexList[Pole]].TextureCoords.X := 0.5 * (_VertexList[_IndexList[A]].TextureCoords.X + _VertexList[_IndexList[B]].TextureCoords.X);
End;
Begin
Mesh := CubeMesh.Create(SubDivisions);
Mesh.Weld(0.01);
Self.AddMesh(Mesh);
ReleaseObject(Mesh);
For I:=0 To Pred(_VertexCount) Do
Begin
Normal := _VertexList[I].Position;
Normal.Normalize();
_VertexList[I].Position := VectorScale(Normal, Size);
_VertexList[I].Normal := Normal;
_VertexList[I].TextureCoords.X := ((Atan2(Normal.X, Normal.Z) / PI) * 0.5) + 0.5; //(Normal.X * 0.5) + 0.5;
_VertexList[I].TextureCoords.Y := Arccos(Normal.Y) / PI;//(Normal.Y * 0.5) + 0.5;
End;
// fix all discontinuities in the U coord
For I:=0 To Pred(_IndexCount) Do
If (I Mod 3 = 0) Then
Begin
For K:=0 To 2 Do
EdgeFix(I+K, I+((K+1) Mod 3));
End;
For I:=0 To Pred(_IndexCount) Do
If (I Mod 3 = 0) Then
Begin
For K:=0 To 2 Do
If (IsPole(_IndexList[I+K])) Then
Begin
A := I + ((K+1) Mod 3);
B := I + ((K+2) Mod 3);
FixPole(I+K, A,B);
End;
End;
End;
Function CreateMeshFromSolid(S:SolidMesh; Tex:Texture):Mesh;
Var
Group:MeshGroup;
I:Integer;
It:VertexIterator;
Dest:SolidVertex;
Begin
Result := Mesh.Create(rtDynamic, S.ClassName);
Group := Result.AddGroup([vertexFormatPosition, vertexFormatColor, vertexFormatNormal, vertexFormatTangent, vertexFormatUV0], '');
Group.Flags := 0;
// Group.AmbientColor := ColorWhite;
Group.DiffuseColor := ColorWhite;
Group.TriangleCount := S._IndexCount Div 3;
Group.VertexCount := S._VertexCount;
It := Group.Vertices.GetIteratorForClass(SolidVertex);
While It.HasNext() Do
Begin
Dest := SolidVertex(It.Value);
I := It.Position;
Dest.Position := S._VertexList[I].Position;
Dest.Normal := S._VertexList[I].Normal;
Dest.TextureCoords := S._VertexList[I].TextureCoords;
Dest.Color := ColorWhite;
End;
ReleaseObject(It);
For I:=0 To Pred(Group.TriangleCount) Do
Begin
Group.Triangles[I].Indices[0] := S._IndexList[I*3+0];
Group.Triangles[I].Indices[1] := S._IndexList[I*3+1];
Group.Triangles[I].Indices[2] := S._IndexList[I*3+2];
End;
Group.DiffuseMap := Tex;
Group.CalculateTangents();
Group.CalculateTriangleNormals();
Result.UpdateBoundingBox();
End;
{ SolidVertex }
Procedure SolidVertex.Load;
Begin
Self.GetVector3D(vertexPosition, Self.Position);
Self.GetVector3D(vertexNormal, Self.Normal);
Self.GetVector2D(vertexUV0, Self.TextureCoords);
Self.GetColor(vertexColor, Self.Color);
End;
Procedure SolidVertex.Save;
Begin
Self.SetVector3D(vertexPosition, Self.Position);
Self.SetVector3D(vertexNormal, Self.Normal);
Self.SetVector2D(vertexUV0, Self.TextureCoords);
Self.SetColor(vertexColor, Self.Color);
End;
End.
|
unit htUserManager;
// Модуль: "w:\common\components\rtl\Garant\HT\htUserManager.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "ThtUserManager" MUID: (5629E343023B)
{$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, daUserStatusChangedSubscriberList
, daTypes
, l3DatLst
, l3LongintList
, Classes
;
type
ThtUserManager = class(Tl3ProtoObject, IdaUserManager)
private
f_UserStatusChangedSubscriberList: TdaUserStatusChangedSubscriberList;
f_PriorityCalculator: IdaPriorityCalculator;
protected
function CheckPassword(const aLogin: AnsiString;
const aPassword: AnsiString;
RequireAdminRights: Boolean;
out theUserID: TdaUserID): TdaLoginError;
function IsUserAdmin(anUserID: TdaUserID): Boolean;
function Get_AllUsers: Tl3StringDataList;
function Get_AllGroups: Tl3StringDataList;
function GetUserName(anUserID: TdaUserID): AnsiString;
function GetUserPriorities(aGroupId: TdaUserID;
var aImportPriority: TdaPriority;
var aExportPriority: TdaPriority): Boolean;
procedure ReSortUserList;
function Get_ArchiUsersCount: Integer;
function UserByID(aID: TdaUserID): IdaArchiUser;
function UserByLogin(const aLogin: AnsiString): IdaArchiUser;
procedure UpdateUserInfo(aUserID: TdaUserID;
aIsGroup: Boolean);
procedure MakeFullArchiUsersList;
function GetUserDisplayName(anID: TdaUserID): AnsiString;
function IsUserExists(anID: TdaUserID): Boolean;
procedure RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber);
procedure UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber);
procedure NotifyUserActiveChanged(anUserID: TdaUserID;
anActive: Boolean);
function CSCheckPassword(const aLogin: AnsiString;
const aPassword: AnsiString;
RequireAdminRights: Boolean;
out theUserID: TdaUserID): Boolean;
procedure GetUserInfo(aUser: TdaUserID;
var aUserName: AnsiString;
var aLoginName: AnsiString;
var aActFlag: Byte);
function Get_PriorityCalculator: IdaPriorityCalculator;
function IsMemberOfGroup(aUserGroupID: TdaUserGroupID;
aUserID: TdaUserID): Boolean;
function GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray;
procedure GetUserGroupsList(aUser: TdaUserID;
aList: Tl3StringDataList); overload;
procedure GetUserGroupsList(aUser: TdaUserID;
aList: Tl3LongintList); overload;
procedure SetUserGroupsList(aUser: TdaUserID;
aList: Tl3StringDataList);
function AddUserGroup(const aName: AnsiString): TdaUserGroupID;
procedure EditUserGroup(aGroupID: TdaUserGroupID;
const aName: AnsiString;
aImportPriority: TdaPriority;
aExportPriority: TdaPriority);
procedure DelUserGroup(aGroupID: TdaUserGroupID);
procedure RemoveUserFromAllGroups(aUser: TdaUserID);
procedure SetUserGroup(aUser: TdaUserID;
aGroup: TdaUserGroupID;
Add: Boolean = True);
procedure AdminChangePassWord(aUser: TdaUserID;
const NewPass: AnsiString);
procedure GetHostUserListOnGroup(aGroupID: TdaUserGroupID;
aList: Tl3StringDataList;
NeedSort: Boolean = False);
procedure SetHostUserListOnGroup(aGroupID: TdaUserGroupID;
aList: Tl3StringDataList);
function AddUser(const aUserName: AnsiString;
const aLoginName: AnsiString;
const aPassword: AnsiString;
ActFlag: Byte): TdaUserID;
function AddUserID(anID: TdaUserID;
const aUserName: AnsiString;
const aLoginName: AnsiString;
const aPassword: AnsiString;
ActFlag: Byte): TdaUserID;
procedure EditUser(aUser: TdaUserID;
const aUserName: AnsiString;
const aLoginName: AnsiString;
ActFlag: Byte;
const EditMask: TdaUserEditMask);
procedure DelUser(aUser: TdaUserID);
procedure GetUserListOnGroup(aUsGroup: TdaUserGroupID;
aList: Tl3StringDataList;
GetActiveUsersOnly: Boolean = False);
procedure GetFiltredUserList(aList: TStrings;
aOnlyActive: Boolean = False);
procedure GetDocGroupData(aUserGroup: TdaUserGroupID;
aFamily: TdaFamilyID;
aDocDataList: Tl3StringDataList);
procedure PutDocGroupData(aUserGroup: TdaUserGroupID;
aFamily: TdaFamilyID;
aDocDataList: Tl3StringDataList);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create; reintroduce;
class function Make: IdaUserManager; reintroduce;
procedure IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action);
procedure IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action);
end;//ThtUserManager
implementation
uses
l3ImplUses
{$If NOT Defined(Nemesis)}
, dt_User
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
, dt_Serv
{$IfEnd} // NOT Defined(Nemesis)
, SysUtils
, htPriorityCalculator
, l3Types
, l3Base
//#UC START# *5629E343023Bimpl_uses*
//#UC END# *5629E343023Bimpl_uses*
;
constructor ThtUserManager.Create;
//#UC START# *5629F0F901C8_5629E343023B_var*
//#UC END# *5629F0F901C8_5629E343023B_var*
begin
//#UC START# *5629F0F901C8_5629E343023B_impl*
inherited Create;
f_UserStatusChangedSubscriberList := TdaUserStatusChangedSubscriberList.Make;
//#UC END# *5629F0F901C8_5629E343023B_impl*
end;//ThtUserManager.Create
class function ThtUserManager.Make: IdaUserManager;
var
l_Inst : ThtUserManager;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//ThtUserManager.Make
function ThtUserManager.CheckPassword(const aLogin: AnsiString;
const aPassword: AnsiString;
RequireAdminRights: Boolean;
out theUserID: TdaUserID): TdaLoginError;
//#UC START# *5628D14D0151_5629E343023B_var*
var
l_Result: Boolean;
//#UC END# *5628D14D0151_5629E343023B_var*
begin
//#UC START# *5628D14D0151_5629E343023B_impl*
l_Result:= GlobalHtServer.xxxCheckArchivariusPassword(aLogin, aPassword, RequireAdminRights);
if l_Result then
Result := da_leOk
else
begin
if RequireAdminRights and GlobalHtServer.xxxCheckArchivariusPassword(aLogin, aPassword, False) then
Result := da_leInsufficientRights
else
Result := da_leUserParamsWrong;
end;
theUserID := GlobalHTServer.xxxUserID;
//#UC END# *5628D14D0151_5629E343023B_impl*
end;//ThtUserManager.CheckPassword
function ThtUserManager.IsUserAdmin(anUserID: TdaUserID): Boolean;
//#UC START# *56EA993D0218_5629E343023B_var*
//#UC END# *56EA993D0218_5629E343023B_var*
begin
//#UC START# *56EA993D0218_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxIsUserAdmin(anUserID);
//#UC END# *56EA993D0218_5629E343023B_impl*
end;//ThtUserManager.IsUserAdmin
function ThtUserManager.Get_AllUsers: Tl3StringDataList;
//#UC START# *5715DEF20209_5629E343023Bget_var*
//#UC END# *5715DEF20209_5629E343023Bget_var*
begin
//#UC START# *5715DEF20209_5629E343023Bget_impl*
Result := dt_User.xxxUserManager.xxxAllUsers;
//#UC END# *5715DEF20209_5629E343023Bget_impl*
end;//ThtUserManager.Get_AllUsers
function ThtUserManager.Get_AllGroups: Tl3StringDataList;
//#UC START# *5715DF0D03C2_5629E343023Bget_var*
//#UC END# *5715DF0D03C2_5629E343023Bget_var*
begin
//#UC START# *5715DF0D03C2_5629E343023Bget_impl*
Result := dt_User.xxxUserManager.xxxAllGroups;
//#UC END# *5715DF0D03C2_5629E343023Bget_impl*
end;//ThtUserManager.Get_AllGroups
function ThtUserManager.GetUserName(anUserID: TdaUserID): AnsiString;
//#UC START# *5718B5CF0399_5629E343023B_var*
//#UC END# *5718B5CF0399_5629E343023B_var*
begin
//#UC START# *5718B5CF0399_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxGetUserName(anUserID);
//#UC END# *5718B5CF0399_5629E343023B_impl*
end;//ThtUserManager.GetUserName
function ThtUserManager.GetUserPriorities(aGroupId: TdaUserID;
var aImportPriority: TdaPriority;
var aExportPriority: TdaPriority): Boolean;
//#UC START# *571DCFB50217_5629E343023B_var*
//#UC END# *571DCFB50217_5629E343023B_var*
begin
//#UC START# *571DCFB50217_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxGetUserPriorities(aGroupId, aImportPriority, aExportPriority);
//#UC END# *571DCFB50217_5629E343023B_impl*
end;//ThtUserManager.GetUserPriorities
procedure ThtUserManager.ReSortUserList;
//#UC START# *5721F5E60367_5629E343023B_var*
//#UC END# *5721F5E60367_5629E343023B_var*
begin
//#UC START# *5721F5E60367_5629E343023B_impl*
dt_User.xxxUserManager.xxxReSortUserList;
//#UC END# *5721F5E60367_5629E343023B_impl*
end;//ThtUserManager.ReSortUserList
function ThtUserManager.Get_ArchiUsersCount: Integer;
//#UC START# *5729C59E00D5_5629E343023Bget_var*
//#UC END# *5729C59E00D5_5629E343023Bget_var*
begin
//#UC START# *5729C59E00D5_5629E343023Bget_impl*
Result := dt_User.xxxUserManager.xxxGetArchiUsersCount(Get_PriorityCalculator);
//#UC END# *5729C59E00D5_5629E343023Bget_impl*
end;//ThtUserManager.Get_ArchiUsersCount
procedure ThtUserManager.IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action);
//#UC START# *5729DD530330_5629E343023B_var*
var
Hack : Pointer absolute anAction;
//#UC END# *5729DD530330_5629E343023B_var*
begin
//#UC START# *5729DD530330_5629E343023B_impl*
try
dt_User.xxxUserManager.xxxIterateArchiUsers(anAction);
finally
l3FreeLocalStub(Hack);
end;//try..finally
//#UC END# *5729DD530330_5629E343023B_impl*
end;//ThtUserManager.IterateArchiUsersF
function ThtUserManager.UserByID(aID: TdaUserID): IdaArchiUser;
//#UC START# *57358B940211_5629E343023B_var*
//#UC END# *57358B940211_5629E343023B_var*
begin
//#UC START# *57358B940211_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxUserByID(Get_PriorityCalculator, aID);
//#UC END# *57358B940211_5629E343023B_impl*
end;//ThtUserManager.UserByID
function ThtUserManager.UserByLogin(const aLogin: AnsiString): IdaArchiUser;
//#UC START# *57358BCB0360_5629E343023B_var*
//#UC END# *57358BCB0360_5629E343023B_var*
begin
//#UC START# *57358BCB0360_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxUserByLogin(Get_PriorityCalculator, aLogin);
//#UC END# *57358BCB0360_5629E343023B_impl*
end;//ThtUserManager.UserByLogin
procedure ThtUserManager.UpdateUserInfo(aUserID: TdaUserID;
aIsGroup: Boolean);
//#UC START# *5735AE4D0017_5629E343023B_var*
//#UC END# *5735AE4D0017_5629E343023B_var*
begin
//#UC START# *5735AE4D0017_5629E343023B_impl*
dt_User.xxxUserManager.xxxUpdateUserInfo(Get_PriorityCalculator, aUserID, aIsGroup);
//#UC END# *5735AE4D0017_5629E343023B_impl*
end;//ThtUserManager.UpdateUserInfo
procedure ThtUserManager.MakeFullArchiUsersList;
//#UC START# *5735AE7F0071_5629E343023B_var*
//#UC END# *5735AE7F0071_5629E343023B_var*
begin
//#UC START# *5735AE7F0071_5629E343023B_impl*
dt_User.xxxUserManager.xxxmakeFullUsersList(Get_PriorityCalculator);
//#UC END# *5735AE7F0071_5629E343023B_impl*
end;//ThtUserManager.MakeFullArchiUsersList
function ThtUserManager.GetUserDisplayName(anID: TdaUserID): AnsiString;
//#UC START# *5735AECA0121_5629E343023B_var*
//#UC END# *5735AECA0121_5629E343023B_var*
begin
//#UC START# *5735AECA0121_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxGetUserDisplayName(Get_PriorityCalculator, anID);
//#UC END# *5735AECA0121_5629E343023B_impl*
end;//ThtUserManager.GetUserDisplayName
function ThtUserManager.IsUserExists(anID: TdaUserID): Boolean;
//#UC START# *5739732402E4_5629E343023B_var*
//#UC END# *5739732402E4_5629E343023B_var*
begin
//#UC START# *5739732402E4_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxIsUserExists(anID);
//#UC END# *5739732402E4_5629E343023B_impl*
end;//ThtUserManager.IsUserExists
procedure ThtUserManager.RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber);
//#UC START# *5739832A00A2_5629E343023B_var*
//#UC END# *5739832A00A2_5629E343023B_var*
begin
//#UC START# *5739832A00A2_5629E343023B_impl*
if f_UserStatusChangedSubscriberList.IndexOf(aSubscriber) = -1 then
f_UserStatusChangedSubscriberList.Add(aSubscriber);
//#UC END# *5739832A00A2_5629E343023B_impl*
end;//ThtUserManager.RegisterUserStatusChangedSubscriber
procedure ThtUserManager.UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber);
//#UC START# *5739834700B2_5629E343023B_var*
//#UC END# *5739834700B2_5629E343023B_var*
begin
//#UC START# *5739834700B2_5629E343023B_impl*
f_UserStatusChangedSubscriberList.Remove(aSubscriber);
//#UC END# *5739834700B2_5629E343023B_impl*
end;//ThtUserManager.UnRegisterUserStatusChangedSubscriber
procedure ThtUserManager.NotifyUserActiveChanged(anUserID: TdaUserID;
anActive: Boolean);
//#UC START# *5739835200CF_5629E343023B_var*
type
PIdaUserStatusChangedSubscriber = ^IdaUserStatusChangedSubscriber;
function DoIt(aData : PIdaUserStatusChangedSubscriber; anIndex : Integer) : Boolean;
begin
aData^.UserStatusChanged(anUserID, anActive);
Result := True;
end;
//#UC END# *5739835200CF_5629E343023B_var*
begin
//#UC START# *5739835200CF_5629E343023B_impl*
f_UserStatusChangedSubscriberList.IterateAllF(l3L2IA(@DoIt));
//#UC END# *5739835200CF_5629E343023B_impl*
end;//ThtUserManager.NotifyUserActiveChanged
function ThtUserManager.CSCheckPassword(const aLogin: AnsiString;
const aPassword: AnsiString;
RequireAdminRights: Boolean;
out theUserID: TdaUserID): Boolean;
//#UC START# *573AC17202BF_5629E343023B_var*
//#UC END# *573AC17202BF_5629E343023B_var*
begin
//#UC START# *573AC17202BF_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxCSCheckPassword(Get_PriorityCalculator, aLogin, aPassword, RequireAdminRights, theUserID);
//#UC END# *573AC17202BF_5629E343023B_impl*
end;//ThtUserManager.CSCheckPassword
procedure ThtUserManager.GetUserInfo(aUser: TdaUserID;
var aUserName: AnsiString;
var aLoginName: AnsiString;
var aActFlag: Byte);
//#UC START# *573AEE9902DF_5629E343023B_var*
var
l_UserName: ShortString;
l_LoginName: ShortString;
//#UC END# *573AEE9902DF_5629E343023B_var*
begin
//#UC START# *573AEE9902DF_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetUserInfo(aUser, l_UserName, l_LoginName, aActFlag);
aUserName := l_UserName;
aLoginName := l_LoginName;
//#UC END# *573AEE9902DF_5629E343023B_impl*
end;//ThtUserManager.GetUserInfo
function ThtUserManager.Get_PriorityCalculator: IdaPriorityCalculator;
//#UC START# *575020410175_5629E343023Bget_var*
//#UC END# *575020410175_5629E343023Bget_var*
begin
//#UC START# *575020410175_5629E343023Bget_impl*
if f_PriorityCalculator = nil then
f_PriorityCalculator := ThtPriorityCalculator.Make;
Result := f_PriorityCalculator;
//#UC END# *575020410175_5629E343023Bget_impl*
end;//ThtUserManager.Get_PriorityCalculator
procedure ThtUserManager.IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action);
//#UC START# *5757D9BB0116_5629E343023B_var*
var
Hack : Pointer absolute anAction;
lAction : Tl3IteratorAction;
function lp_UserGroupIter(aData: Pointer; aIndex: Long): Bool;
var
l_Name: String;
begin
l_Name := PAnsiChar(aData);
Result := anAction(l_Name, aIndex);
end;
//#UC END# *5757D9BB0116_5629E343023B_var*
begin
//#UC START# *5757D9BB0116_5629E343023B_impl*
try
lAction := l3L2IA(@lp_UserGroupIter);
try
dt_User.xxxUserManager.xxxIterateUserGroups(lAction);
finally
l3FreeFA(Tl3FreeAction(lAction));
end;
finally
l3FreeLocalStub(Hack);
end;//try..finally
//#UC END# *5757D9BB0116_5629E343023B_impl*
end;//ThtUserManager.IterateUserGroupsF
function ThtUserManager.IsMemberOfGroup(aUserGroupID: TdaUserGroupID;
aUserID: TdaUserID): Boolean;
//#UC START# *575A8B790353_5629E343023B_var*
//#UC END# *575A8B790353_5629E343023B_var*
begin
//#UC START# *575A8B790353_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxIsMemberOfGroup(aUserGroupID, aUserID);
//#UC END# *575A8B790353_5629E343023B_impl*
end;//ThtUserManager.IsMemberOfGroup
function ThtUserManager.GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray;
//#UC START# *57625B5002DD_5629E343023B_var*
//#UC END# *57625B5002DD_5629E343023B_var*
begin
//#UC START# *57625B5002DD_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxGetUserGroups(aUserID);
//#UC END# *57625B5002DD_5629E343023B_impl*
end;//ThtUserManager.GetUserGroups
procedure ThtUserManager.GetUserGroupsList(aUser: TdaUserID;
aList: Tl3StringDataList);
//#UC START# *576289510024_5629E343023B_var*
//#UC END# *576289510024_5629E343023B_var*
begin
//#UC START# *576289510024_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetUserGroupList(aUser, aList);
//#UC END# *576289510024_5629E343023B_impl*
end;//ThtUserManager.GetUserGroupsList
procedure ThtUserManager.GetUserGroupsList(aUser: TdaUserID;
aList: Tl3LongintList);
//#UC START# *57628A9403C6_5629E343023B_var*
//#UC END# *57628A9403C6_5629E343023B_var*
begin
//#UC START# *57628A9403C6_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetUserGroupList(aUser, aList);
//#UC END# *57628A9403C6_5629E343023B_impl*
end;//ThtUserManager.GetUserGroupsList
procedure ThtUserManager.SetUserGroupsList(aUser: TdaUserID;
aList: Tl3StringDataList);
//#UC START# *5767ABE002DC_5629E343023B_var*
//#UC END# *5767ABE002DC_5629E343023B_var*
begin
//#UC START# *5767ABE002DC_5629E343023B_impl*
dt_User.xxxUserManager.xxxSetUserGroupList(aUser, aList);
//#UC END# *5767ABE002DC_5629E343023B_impl*
end;//ThtUserManager.SetUserGroupsList
function ThtUserManager.AddUserGroup(const aName: AnsiString): TdaUserGroupID;
//#UC START# *576B95A600B9_5629E343023B_var*
var
l_Name: ShortString;
//#UC END# *576B95A600B9_5629E343023B_var*
begin
//#UC START# *576B95A600B9_5629E343023B_impl*
l_Name := aName;
Result := dt_User.xxxUserManager.xxxAddUserGroup(l_Name);
//#UC END# *576B95A600B9_5629E343023B_impl*
end;//ThtUserManager.AddUserGroup
procedure ThtUserManager.EditUserGroup(aGroupID: TdaUserGroupID;
const aName: AnsiString;
aImportPriority: TdaPriority;
aExportPriority: TdaPriority);
//#UC START# *576B960500C5_5629E343023B_var*
var
l_Name: ShortString;
//#UC END# *576B960500C5_5629E343023B_var*
begin
//#UC START# *576B960500C5_5629E343023B_impl*
l_Name := aName;
dt_User.xxxUserManager.xxxEditUserGroup(aGroupID, l_Name, aImportPriority, aExportPriority);
//#UC END# *576B960500C5_5629E343023B_impl*
end;//ThtUserManager.EditUserGroup
procedure ThtUserManager.DelUserGroup(aGroupID: TdaUserGroupID);
//#UC START# *576BAC4402D8_5629E343023B_var*
//#UC END# *576BAC4402D8_5629E343023B_var*
begin
//#UC START# *576BAC4402D8_5629E343023B_impl*
dt_User.xxxUserManager.xxxDelUserGroupByID(aGroupID);
//#UC END# *576BAC4402D8_5629E343023B_impl*
end;//ThtUserManager.DelUserGroup
procedure ThtUserManager.RemoveUserFromAllGroups(aUser: TdaUserID);
//#UC START# *577F6AD90170_5629E343023B_var*
//#UC END# *577F6AD90170_5629E343023B_var*
begin
//#UC START# *577F6AD90170_5629E343023B_impl*
dt_User.xxxUserManager.xxxRemoveUserFromAllGroups(aUser);
//#UC END# *577F6AD90170_5629E343023B_impl*
end;//ThtUserManager.RemoveUserFromAllGroups
procedure ThtUserManager.SetUserGroup(aUser: TdaUserID;
aGroup: TdaUserGroupID;
Add: Boolean = True);
//#UC START# *577F80C503AF_5629E343023B_var*
//#UC END# *577F80C503AF_5629E343023B_var*
begin
//#UC START# *577F80C503AF_5629E343023B_impl*
dt_User.xxxUserManager.xxxSetUserGroup(aUser, aGroup, Add);
//#UC END# *577F80C503AF_5629E343023B_impl*
end;//ThtUserManager.SetUserGroup
procedure ThtUserManager.AdminChangePassWord(aUser: TdaUserID;
const NewPass: AnsiString);
//#UC START# *5783537E00A1_5629E343023B_var*
//#UC END# *5783537E00A1_5629E343023B_var*
begin
//#UC START# *5783537E00A1_5629E343023B_impl*
dt_User.xxxUserManager.xxxAdminChangePassWord(aUser, NewPass);
//#UC END# *5783537E00A1_5629E343023B_impl*
end;//ThtUserManager.AdminChangePassWord
procedure ThtUserManager.GetHostUserListOnGroup(aGroupID: TdaUserGroupID;
aList: Tl3StringDataList;
NeedSort: Boolean = False);
//#UC START# *578392E7026A_5629E343023B_var*
//#UC END# *578392E7026A_5629E343023B_var*
begin
//#UC START# *578392E7026A_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetHostUserListOnGroup(aGroupID, aList, NeedSort);
//#UC END# *578392E7026A_5629E343023B_impl*
end;//ThtUserManager.GetHostUserListOnGroup
procedure ThtUserManager.SetHostUserListOnGroup(aGroupID: TdaUserGroupID;
aList: Tl3StringDataList);
//#UC START# *5783933A010B_5629E343023B_var*
//#UC END# *5783933A010B_5629E343023B_var*
begin
//#UC START# *5783933A010B_5629E343023B_impl*
dt_User.xxxUserManager.xxxSetHostUserListOnGroup(aGroupID, aList);
//#UC END# *5783933A010B_5629E343023B_impl*
end;//ThtUserManager.SetHostUserListOnGroup
function ThtUserManager.AddUser(const aUserName: AnsiString;
const aLoginName: AnsiString;
const aPassword: AnsiString;
ActFlag: Byte): TdaUserID;
//#UC START# *5784BBF10299_5629E343023B_var*
//#UC END# *5784BBF10299_5629E343023B_var*
begin
//#UC START# *5784BBF10299_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxAddUser(aUserName, aLoginName, aPassword, ActFlag);
//#UC END# *5784BBF10299_5629E343023B_impl*
end;//ThtUserManager.AddUser
function ThtUserManager.AddUserID(anID: TdaUserID;
const aUserName: AnsiString;
const aLoginName: AnsiString;
const aPassword: AnsiString;
ActFlag: Byte): TdaUserID;
//#UC START# *5784BC420208_5629E343023B_var*
//#UC END# *5784BC420208_5629E343023B_var*
begin
//#UC START# *5784BC420208_5629E343023B_impl*
Result := dt_User.xxxUserManager.xxxAddUserID(anID, aUserName, aLoginName, aPassword, ActFlag);
//#UC END# *5784BC420208_5629E343023B_impl*
end;//ThtUserManager.AddUserID
procedure ThtUserManager.EditUser(aUser: TdaUserID;
const aUserName: AnsiString;
const aLoginName: AnsiString;
ActFlag: Byte;
const EditMask: TdaUserEditMask);
//#UC START# *5784BD1501E8_5629E343023B_var*
//#UC END# *5784BD1501E8_5629E343023B_var*
begin
//#UC START# *5784BD1501E8_5629E343023B_impl*
dt_User.xxxUserManager.xxxEditUser(aUser, aUserName, aLoginName, ActFlag, EditMask);
//#UC END# *5784BD1501E8_5629E343023B_impl*
end;//ThtUserManager.EditUser
procedure ThtUserManager.DelUser(aUser: TdaUserID);
//#UC START# *5784BE1E02F7_5629E343023B_var*
//#UC END# *5784BE1E02F7_5629E343023B_var*
begin
//#UC START# *5784BE1E02F7_5629E343023B_impl*
dt_User.xxxUserManager.xxxDelUser(aUser);
//#UC END# *5784BE1E02F7_5629E343023B_impl*
end;//ThtUserManager.DelUser
procedure ThtUserManager.GetUserListOnGroup(aUsGroup: TdaUserGroupID;
aList: Tl3StringDataList;
GetActiveUsersOnly: Boolean = False);
//#UC START# *57A87EF901F3_5629E343023B_var*
//#UC END# *57A87EF901F3_5629E343023B_var*
begin
//#UC START# *57A87EF901F3_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetUserListOnGroup(aUsGroup, aList, GetActiveUsersOnly);
//#UC END# *57A87EF901F3_5629E343023B_impl*
end;//ThtUserManager.GetUserListOnGroup
procedure ThtUserManager.GetFiltredUserList(aList: TStrings;
aOnlyActive: Boolean = False);
//#UC START# *57A9DF2103CE_5629E343023B_var*
//#UC END# *57A9DF2103CE_5629E343023B_var*
begin
//#UC START# *57A9DF2103CE_5629E343023B_impl*
if dt_User.xxxUserManager = nil then
aList.Clear
else
dt_User.xxxUserManager.xxxGetFiltredUserList(aList, aOnlyActive);
//#UC END# *57A9DF2103CE_5629E343023B_impl*
end;//ThtUserManager.GetFiltredUserList
procedure ThtUserManager.GetDocGroupData(aUserGroup: TdaUserGroupID;
aFamily: TdaFamilyID;
aDocDataList: Tl3StringDataList);
//#UC START# *57AC28890131_5629E343023B_var*
//#UC END# *57AC28890131_5629E343023B_var*
begin
//#UC START# *57AC28890131_5629E343023B_impl*
dt_User.xxxUserManager.xxxGetDocGroupData(aUserGroup, aFamily, aDocDataList);
//#UC END# *57AC28890131_5629E343023B_impl*
end;//ThtUserManager.GetDocGroupData
procedure ThtUserManager.PutDocGroupData(aUserGroup: TdaUserGroupID;
aFamily: TdaFamilyID;
aDocDataList: Tl3StringDataList);
//#UC START# *57AC289F0257_5629E343023B_var*
//#UC END# *57AC289F0257_5629E343023B_var*
begin
//#UC START# *57AC289F0257_5629E343023B_impl*
dt_User.xxxUserManager.xxxPutDocGroupData(aUserGroup, aFamily, aDocDataList);
//#UC END# *57AC289F0257_5629E343023B_impl*
end;//ThtUserManager.PutDocGroupData
procedure ThtUserManager.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_5629E343023B_var*
//#UC END# *479731C50290_5629E343023B_var*
begin
//#UC START# *479731C50290_5629E343023B_impl*
f_PriorityCalculator := nil;
FreeAndNil(f_UserStatusChangedSubscriberList);
inherited;
//#UC END# *479731C50290_5629E343023B_impl*
end;//ThtUserManager.Cleanup
end.
|
unit ODListF;
interface
uses
Qt, SysUtils, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, Types;
type
TODListForm = class(TForm)
ListBox1: TListBox;
ColorDialog1: TColorDialog;
procedure FormCreate(Sender: TObject);
procedure ListBox1DblClick(Sender: TObject);
procedure ListBox1DrawItem(Sender: TObject; Index: Integer;
Rect: TRect; State: TOwnerDrawState; var Handled: Boolean);
private
{ Private declarations }
public
procedure AddColors (Colors: array of TColor);
end;
var
ODListForm: TODListForm;
implementation
{$R *.xfm}
procedure TODListForm.AddColors (Colors: array of TColor);
var
I: Integer;
begin
for I := Low (Colors) to High (Colors) do
ListBox1.Items.AddObject (
ColorToString (Colors[I]),
TObject(Colors[I]));
end;
function RGB (red, green, blue: Byte): Cardinal;
begin
Result := blue + green * 256 + red * 256 * 256;
end;
procedure TODListForm.FormCreate(Sender: TObject);
begin
Canvas.Font := ListBox1.Font;
ListBox1.ItemHeight := Canvas.TextHeight('0');
AddColors ([clRed, clBlue, clYellow, clGreen, clFuchsia, clLime, clPurple,
clGray, RGB (213, 23, 123), RGB (0, 0, 0), clAqua, clNavy, clOlive, clTeal]);
end;
procedure TODListForm.ListBox1DblClick(Sender: TObject);
begin
if ColorDialog1.Execute then
AddColors ([ColorDialog1.Color]);
end;
procedure TODListForm.ListBox1DrawItem(Sender: TObject; Index: Integer;
Rect: TRect; State: TOwnerDrawState; var Handled: Boolean);
begin
with Sender as TListbox do
begin
// erase
Canvas.FillRect (Rect);
// draw item
Canvas.Font.Color := TColor (
Items.Objects [Index]);
Canvas.TextOut(Rect.Left, Rect.Top,
Listbox1.Items[Index]);
// InflateRect (Rect, -1, -1);
if (odFocused in State) and (odSelected in State) then
Canvas.DrawFocusRect (Rect);
end;
end;
end.
|
Program Aufgabe5;
{$codepage utf8}
Var Eingabe: String;
Tage: Integer;
Fehler: Boolean = False;
Begin
Write('Bitte gib den Monat ein ("jan", "feb", "mrz", ...): ');
Read(Eingabe);
Case Eingabe Of
'jan', 'mrz', 'mai', 'jul', 'aug', 'okt', 'dez': Tage := 31;
'apr', 'jun', 'sep', 'nov': Tage := 30;
'feb': Tage := 28;
Else
Fehler := True;
End;
If Fehler Then
WriteLn('Es gab einen Fehler bei der Eingabe: ', Eingabe, ' ist kein Monat!')
Else
WriteLn('Der Monat ', Eingabe, ' hat ', Tage, ' Tage.');
End. |
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: TFingerCli is a FINGER protocol client using TWSocket
Conform to RFC-1288 (supercede RFCs 1196, 1194 and 742)
Creation: December 18, 1997
Version: 6.00
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1997-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Aug 20, 1999 V1.01 Added compile time options. Revised for BCB4.
Aug 18, 2001 V1.02 Angus Robertson <angus@magsys.co.uk> removed
@domain from the request.
May 31, 2004 V1.03 Used ICSDEFS.INC, removed unused units
Mar 26, 2006 V6.00 Started new version 6
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsFingCli;
interface
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFNDEF VER80} { Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
uses
Messages,
{$IFDEF USEWINDOWS}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Classes, OverbyteIcsWSocket;
const
FingCliVersion = 600;
CopyRight : String = ' FingCli (c) 1997-2006 F. Piette V6.00 ';
type
TFingerCli = class(TComponent)
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure StartQuery;
function Receive(Buffer : Pointer; Len : Integer) : Integer;
procedure Abort;
protected
FWSocket : TWSocket;
FQuery : String;
FQueryDoneFlag : Boolean;
FOnSessionConnected : TSessionConnected;
FOnDataAvailable : TDataAvailable;
FOnQueryDone : TSessionClosed;
procedure WSocketDnsLookupDone(Sender: TObject; Error: Word);
procedure WSocketSessionConnected(Sender: TObject; Error: Word);
procedure WSocketDataAvailable(Sender: TObject; Error: Word);
procedure WSocketSessionClosed(Sender: TObject; Error: Word);
procedure TriggerQueryDone(Error: Word);
published
property Query : String read FQuery
write FQuery;
property OnSessionConnected : TSessionConnected read FOnSessionConnected
write FOnSessionConnected;
property OnDataAvailable : TDataAvailable read FOnDataAvailable
write FOnDataAvailable;
property OnQueryDone : TSessionClosed read FOnQueryDone
write FOnQueryDone;
end;
procedure Register;
implementation
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Register;
begin
RegisterComponents('FPiette', [TFingerCli]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TFingerCli.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWSocket := TWSocket.Create(Self);
FWSocket.OnSessionConnected := WSocketSessionConnected;
FWSocket.OnDataAvailable := WSocketDataAvailable;
FWSocket.OnSessionClosed := WSocketSessionClosed;
FWSocket.OnDnsLookupDone := WSocketDnsLookupDone;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TFingerCli.Destroy;
begin
if Assigned(FWSocket) then
FWSocket.Destroy;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.StartQuery;
var
I : Integer;
Host : String;
begin
I := Pos('@', FQuery);
if I <= 0 then
raise Exception.CreateFmt('TFingerCli, Invalid Query: %s', [FQuery]);
Host := Copy(FQuery, I + 1, Length(FQuery));
if Length(Host) <= 0 then
raise Exception.CreateFmt('TFingerCli, Invalid Host in query: %s', [FQuery]);
FQueryDoneFlag := FALSE;
FWSocket.DnsLookup(Host);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.Abort;
begin
FWSocket.CancelDnsLookup;
FWSocket.Abort;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TFingerCli.Receive(Buffer : Pointer; Len : Integer) : Integer;
begin
Result := FWSocket.Receive(Buffer, Len);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.WSocketDnsLookupDone(Sender: TObject; Error: Word);
begin
if Error <> 0 then
TriggerQueryDone(Error)
else begin
FWSocket.Addr := FWSocket.DnsResult;
FWSocket.Proto := 'tcp';
FWSocket.Port := 'finger';
FWSocket.Connect;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.WSocketSessionConnected(Sender: TObject; Error: Word);
var
I: integer ;
begin
if Assigned(FOnSessionConnected) then
FOnSessionConnected(Self, Error);
if Error <> 0 then begin
TriggerQueryDone(Error);
FWSocket.Close
end
else
begin
I := Pos('@', FQuery); { angus }
FWSocket.SendStr(copy (FQuery, 1, pred (I)) + #13 + #10);
end ;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.WSocketDataAvailable(Sender: TObject; Error: Word);
begin
if Assigned(FOnDataAvailable) then
FOnDataAvailable(Self, Error);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.TriggerQueryDone(Error: Word);
begin
if (FQueryDoneFlag = FALSE) and Assigned(FOnQueryDone) then
FOnQueryDone(Self, Error);
FQueryDoneFlag := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TFingerCli.WSocketSessionClosed(Sender: TObject; Error: Word);
begin
TriggerQueryDone(Error);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
Unit Dt_Log;
{ $Id: DT_LOG.PAS,v 1.81 2013/04/01 11:46:28 voba Exp $ }
// $Log: DT_LOG.PAS,v $
// Revision 1.81 2013/04/01 11:46:28 voba
// - трассировщик лог записей (для демидова)
//
// Revision 1.80 2013/03/07 07:32:13 voba
// - усиленное логирование для поиска проблем Демидова
//
// Revision 1.79 2012/10/18 12:03:49 voba
// no message
//
// Revision 1.78 2012/01/13 11:12:41 fireton
// - исправил ошибки и оптимизировал по скорости (K 326776318)
//
// Revision 1.77 2012/01/13 09:27:40 fireton
// - добавил новый и переименовал старый метод (проверка действий над документами)
//
// Revision 1.76 2012/01/13 08:54:40 fireton
// - добавил новый и переименовал старый метод (проверка действий над документами)
//
// Revision 1.75 2010/09/24 12:11:14 voba
// - k : 235046326
//
// Revision 1.74 2010/08/03 13:16:38 voba
// - k: 229672814
//
// Revision 1.73 2010/03/10 14:09:47 narry
// - не собиралось
//
// Revision 1.72 2009/11/09 09:15:49 voba
// - add param to Procedure PutLogRecToDocs
//
// Revision 1.71 2009/06/23 07:32:59 voba
// - стандартизация доступа к атрибутам
//
// Revision 1.70 2009/06/08 13:23:25 voba
// - enh. унификация атрибутов. Избавился от псевдоатрибутов atDateNumsChDate, atRelHLink,
//
// Revision 1.69 2009/05/19 12:16:28 voba
// - унификация атрибутов
//
// Revision 1.68 2009/05/13 10:52:54 voba
// - cc
//
// Revision 1.67 2009/05/08 11:10:07 voba
// - заменил TblH на Handle
//
// Revision 1.66 2009/03/02 08:15:08 voba
// - изменил список параметров у constructor TPrometTbl.Create
//
// Revision 1.65 2009/02/03 12:00:00 voba
// - сс выкинул ненужную функцию
//
// Revision 1.64 2008/12/17 10:10:06 voba
// - bug fix предотвращение повторной записи VINCLUDED
//
// Revision 1.63 2008/10/31 09:54:33 voba
// - add overload procedure TLogBookTbl.PutLogRecToDocs with ISAB
//
// Revision 1.62 2008/04/18 14:09:14 voba
// - bug fix
//
// Revision 1.61 2008/04/09 06:08:35 voba
// - refact.
//
// Revision 1.60 2008/01/10 14:57:44 voba
// - ref.
//
// Revision 1.59 2007/08/14 20:25:14 lulin
// - bug fix: не собиралася Архивариус.
//
// Revision 1.58 2007/08/14 14:30:08 lulin
// - оптимизируем перемещение блоков памяти.
//
// Revision 1.57 2007/05/25 15:20:42 voba
// - DeleteRecsByKeys теперь возвращает количество удаленных и подывмает exception в случае ошибок
//
// Revision 1.56 2007/04/25 07:52:37 fireton
// - Рефакторинг. Уходим от прямых упоминаний имен таблиц в пользу перечислимых типов в DT_Types
//
// Revision 1.55 2007/04/17 11:38:13 fireton
// - регионы в имени пользователей
//
// Revision 1.54 2007/02/22 09:23:51 voba
// - ren DelRecsOnKeys -> DeleteRecsByKeys, _move this to TdtTable
//
// Revision 1.53 2007/02/12 16:11:00 voba
// - заменил использование htModifyRecs на вызов TAbsHtTbl.ModifyRecs
// - выделил TdtTable в модуль dt_Table (обертка вокруг функций HyTech по работе с таблицей целиком)
// - выделил функции HyTech по работе с Sab в dt_Sab, потом объект сделаю
//
// Revision 1.52 2006/12/01 11:22:14 voba
// - add TImpExLogRec
//
// Revision 1.51 2006/10/04 08:35:53 voba
// - merge with b_archi_ht64
//
// Revision 1.50.6.2 2006/09/19 09:35:39 voba
// - remove procedure DelLogOnDocsID
//
// Revision 1.50.6.1 2006/09/19 08:22:02 voba
// - переход на HTStub
//
// Revision 1.50 2006/06/08 15:54:46 fireton
// - подготовка к переходу на большой User ID
//
// Revision 1.49.16.1 2006/06/08 09:08:01 fireton
// - перевод User ID на Longword
//
// Revision 1.49 2006/01/10 10:13:58 step
// добавлен перегруженный метод TLogBookTbl.DeleteRecords
//
// Revision 1.48 2005/05/17 10:21:06 step
// изменена TLogBookTbl.DelLogOnDocsID
//
// Revision 1.47 2005/05/11 12:16:16 voba
// no message
//
// Revision 1.46 2005/03/21 16:29:38 voba
// - replace cfOrdinal to dt_Const.cOrdLogActions
// - replace cfJuror to dt_Const.cJurLogActions
//
// Revision 1.45 2005/03/02 16:06:42 narry
// - исправление: процедура очистки записей журнала
//
// Revision 1.44 2005/02/28 18:38:18 step
// new: TLogBookTbl.DeleteRecsBy
//
// Revision 1.43 2005/02/25 08:38:19 step
// расширен cfJuror (добавлено acAnnoDate)
//
// Revision 1.42 2005/01/26 15:30:02 step
// исправлены TLogBookTbl.ActionsToSab и TLogBookTbl.DocIdsBy
//
// Revision 1.41 2005/01/14 16:23:16 step
// new: TLogBookTbl.DocIdsBy, TLogBookTbl.ActionsToSab
//
// Revision 1.40 2005/01/11 09:56:09 voba
// - небольшая чистка кода
//
// Revision 1.39 2004/11/05 13:00:08 voba
// - add overload DelLogOnDocID
//
// Revision 1.38 2004/11/02 09:47:57 step
// bug fix
//
// Revision 1.37 2004/11/01 16:59:10 step
// добавлена проверка в TLogBookTbl.CopyRecords
//
// Revision 1.36 2004/11/01 11:43:50 step
// new: TLogBookTbl.CopyRecords
//
// Revision 1.35 2004/09/14 15:58:14 lulin
// - удален модуль Str_Man - используйте вместо него - l3String.
//
// Revision 1.34 2004/08/09 15:21:29 step
// new: TLogBookTbl.DeleteRecords
//
// Revision 1.33 2004/08/03 08:52:49 step
// замена dt_def.pas на DtDefine.inc
//
// Revision 1.32 2004/07/14 15:27:14 step
// замена Buffering на StartCaching/StopCaching
//
// Revision 1.31 2004/07/01 14:14:27 voba
// - merge newCashe
//
// Revision 1.30.2.1 2004/06/17 18:03:49 step
// В методах TAbsHtTbl.AddRec и TAbsHtTbl.UpdRec убран параметр AbsNum.
//
// Revision 1.30 2004/05/31 13:58:53 narry
// - change: при импорте документов в лог добавляется запись "Импортирован"
//
// Revision 1.29 2004/05/31 13:38:26 voba
// - redefine cfOrdinal
//
// Revision 1.28 2004/04/14 13:51:12 narry
// - bug fix: вместо последней даты юридического изменения документа возвращалась первая
//
// Revision 1.27 2004/04/14 12:22:32 step
// bug fix: вместо последней даты возвращалась первая
//
// Revision 1.26 2004/03/17 11:11:11 voba
// -new behavior: изменил порядок сортировки в Function TLogBookTbl.GetDocHistory
//
// Revision 1.25 2004/03/05 16:54:44 step
// чистка кода
//
// Revision 1.24 2004/02/03 09:42:39 voba
// -code clean
//
// Revision 1.23 2003/06/19 09:20:05 voba
// -new method DelIncludedLogOnDocsID
//
// Revision 1.22 2003/01/23 16:42:17 demon
// - new: поплнил операцию GetLogDataList в объекте TLogBookTbl одним дополнительным,
// необязательным параметром
//
// Revision 1.21 2002/08/01 09:14:37 voba
// -bug fix: присутствие журнальных записей с ID пользователя, отсутствующими в списке пользователей приводило к невозможности открыть журнал документа
//
// Revision 1.20 2002/05/29 14:05:03 voba
// - bug fix: защищаем изменение времени ожидания.
//
// Revision 1.19 2002/03/07 10:15:36 demon
// - add new function PutLogRecToDocs
//
// Revision 1.18 2001/07/06 14:38:15 demon
// - new behavior: add transactions to all massive operation of Add, Modify and Delete of tbl records
//
// Revision 1.17 2001/04/24 13:39:56 demon
// - new behavior: many search functions now works with Usre Groups too
//
// Revision 1.16 2001/01/25 09:40:18 demon
// - add function GetDocsInDatesNotAction
//
// Revision 1.15 2001/01/11 10:59:29 demon
// Add MasterUser property for Import procedure
//
// Revision 1.14 2000/12/15 15:36:16 law
// - вставлены директивы Log.
//
{$I DtDefine.inc}
Interface
uses
l3DatLst,l3Date,
HT_Const,
Dt_Types, Dt_Const,
Dt_ATbl, DT_Sab,
dt_Link;
const
lgDocID_Key = 1;
lgAction_Key = 2;
lgDate_Key = 3;
lgTime_Key = 4;
lgActionFlag_Key = 5;
lgStation_Key = 6;
lgAuthor_Key = 7;
lgUniKey = 8;
Type
PDatesArr = ^TDatesArr;
TDatesArr = Array [1..16000] of TStDate;
Type
PReadDisplayLogRec = ^TReadDisplayLogRec;
TReadDisplayLogRec = Record
Action : Byte;
Date : TStDate;
Time : TStTime;
Author : TUserID;
end;
PDisplayLogRec = ^TDisplayLogRec;
TDisplayLogRec = Record
Action : Byte;
Date : TStDate;
Time : TStTime;
Author : TUserNameStr;
end;
TUniqLogRec = Record
DocID : TDocID;
Action : TLogActionType;
Date : TStDate;
Time : TStTime;
end;
PImpExLogRec = ^TImpExLogRec;
TImpExLogRec = Record
rDocID : TDocID;
rAction : TLogActionType;
rDate : TStDate;
rTime : TStTime;
rAuthor : TUserID;
end;
TLogBookTbl = Class(TDocAttrTbl)
private
//fSaveInt : Byte;
function GetDocHistory(aDocID : LongInt;
aFlag : TLogActionFlags;
WithSort : Boolean) : Sab;
//function MakeSabOfActions(aActions: TLogActionSet) : ISab;
public
Constructor Create(aFamID : TFamilyID); Reintroduce;
procedure PutDateLogRec(aDocID : LongInt;
aAction : TLogActionType;
aDate : TStDate = 0;
aTime : TStTime = 0;
aUser : TUserID = 0);
Procedure PutLogRec(aDocID : LongInt;aAction : TLogActionType;aUser : TUserID = 0);
Procedure PutLogRecSet(aDocID : LongInt; aActSet : TLogActionSet);
Procedure PutLogRecToDocs(aDocIDs : ISAB; aAction : TLogActionType; aUser : TUserID = 0; aDate : TStDate = 0);
Procedure ClearLogBook;
//Function LastModified(aDocID : LongInt; LogRecType : TLogActionFlags = acfNone) : TStDateTimeRec;
function IsDocHadAction(aDocID : LongInt;aAction : TLogActionType; aDate : TStDate = 0): Boolean;
Function IsDocModified(aDocID : LongInt) : Boolean;
//Function GetMaxDateOnAction(aDocID : LongInt;aAction : TLogActionType) : TStDate;
//Function GetDatesOnAction(aDocID : LongInt;aAction : TLogActionType;
// Var Dates : PStDate) : Word;
Function GetDocsOnAction(aAction : TLogActionType;UserID : TUserID = 0;
UserGr : Boolean = False) : Sab;
//function MakeDocIdsSabBy(aActions: TLogActionSet;
// aFromDate, aToDate: TStDate;
// aUserID : TUserID = 0;
// aUserGr : Boolean = False): ISab;
Procedure GetLogDataList(aDocID : LongInt;aFlag : TLogActionFlags;
aDataList : Tl3DataList;InternalFormat : Boolean = False);
Function GetDocsHistory(aDocSab : Sab;aFlag : TLogActionFlags) : Sab;
//procedure DelLogOnDocID(aID : LongInt); overload;
//Procedure DelAllLogOnDocsID(aIDs : ISab);
//Procedure DelUrLogOnDocsID(aIDs : Sab);
//Procedure DelIncludedLogOnDocsID(aIDs : ISab);
//{Стирает VIncluded у пачки}
procedure CopyRecords(aSrcDocId, aDstDocId: Longint);
// делает копии всех записей от документа aSrcDocId для документа aDstDocId
//function DeleteRecords(aUserId: TUserID; aFromDate, aToDate: TStDate): Integer; overload;
// Удаление записей из журнала по номеру юзера и во заданному интервалу дат.
// Возвращает кол-то удаленных записей.
//function DeleteRecords(aDocID: TDocID;
// aAction: TLogActionType;
// aDate: TStDate): Integer; overload; // Возвращает кол-то удаленных записей.
Procedure DelSingleLogRec(aDocID : TDocID;aAction : TLogActionType;
aDate : TStDate;aTime : TStTime);
function IsDocHadActions(aDocID : LongInt; aActions: array of TLogActionType; aDate : TStDate = 0): Boolean;
//Property SaveInterval : Byte read fSaveInt write fSaveInt;
end;
Implementation
Uses
SysUtils, WinProcs,
TypInfo,
l3Base,
HT_DLL,
dt_AttrSchema,
Dt_Serv, Dt_Err, Dt_User,
vConst;
{ TLogBookTbl }
Const
DateTimeArr : Array [1..2] of SmallInt = (lgDate_Key,lgTime_Key);
DisplayArr : Array [1..4] of SmallInt = (lgAction_Key,lgDate_Key,lgTime_Key,
lgAuthor_Key);
constructor TLogBookTbl.Create(aFamID : TFamilyID);
begin
Assert(aFamID <> MainTblsFamily);
inherited Create(aFamID, atOrdLogRecords);
end;
Function TLogBookTbl.GetDocHistory(aDocID : LongInt;aFlag : TLogActionFlags;
WithSort : Boolean) : Sab;
Var
TmpSab1,
TmpSab2,
TmpSab3 : Sab;
SortArr : Array [1..2] of SmallInt;
Begin
l3FillChar(Result,SizeOf(Sab));
with fTable do
begin
RefreshSrchList;
htSearch(@fSrchList,TmpSab1,Handle,lgDocID_Key,Equal,@aDocID,Nil);
If aFlag<>acfNone
then
Begin
TmpSab3:=TmpSab1;
htSearch(@fSrchList,TmpSab2,Handle,lgActionFlag_Key,Equal,@aFlag,Nil);
Try
htAndResults(TmpSab1,TmpSab3,TmpSab2);
finally
htClearResults(TmpSab2);
htClearResults(TmpSab3);
end;
end;
If WithSort
then
Try
SortArr[1] := -lgDate_Key;
SortArr[2] := -lgTime_Key;
Ht(htSortResults(Result,TmpSab1,@SortArr,2));
finally
htClearResults(TmpSab1);
end
else
Result:=TmpSab1;
end;
end;
Function TLogBookTbl.GetDocsHistory(aDocSab : Sab;aFlag : TLogActionFlags) : Sab;
Var
TmpSab1,
TmpSab2,
TmpSab3 : Sab;
Begin
l3FillChar(Result,SizeOf(Sab));
htRecordsByKey(TmpSab1,aDocSab);
If aFlag<>acfNone
then
Begin
TmpSab3:=TmpSab1;
htSearch(@aDocSab,TmpSab2,Table.Handle,lgActionFlag_Key,Equal,@aFlag,Nil);
Try
htAndResults(TmpSab1,TmpSab3,TmpSab2);
finally
htClearResults(TmpSab2);
htClearResults(TmpSab3);
end;
end;
Result:=TmpSab1;
end;
procedure TLogBookTbl.PutDateLogRec(aDocID : LongInt;
aAction : TLogActionType;
aDate : TStDate = 0;
aTime : TStTime = 0;
aUser : TUserID = 0);
var
TmpFlag : TLogActionFlags;
TmpPChar: PChar;
function CheckSingleAction(aAction : TLogActionType) : boolean;
begin
Result := not (aAction in cSingleJurLogActions) or not IsDocHadAction(aDocID, aAction);
end;
{$IfDef DocSaveTrace}
var
lAge : Int64;
{$EndIf}
begin
{$IfDef DocSaveTrace}
l3System.Msg2Log('PutDateLogRec : DocID=%d, Action=%s', [aDocID, GetEnumName(TypeInfo(TLogActionType), Ord(aAction))]);
{$EndIf}
if not CheckSingleAction(aAction) then exit;
{$IfDef DocSaveTrace}
l3System.Msg2Log('PutDateLogRec : DocID=%d Check pass', [aDocID]);
{$EndIf}
with fTable do
begin
ClearFullRec;
PutToFullRec(lgDocID_Key,aDocID);
TmpPChar:=@GlobalHtServer.CurStationName;
PutToFullRec(lgStation_Key,TmpPChar);
if aUser = 0 then
aUser := GlobalHtServer.CurUserID;
if aDate = 0 then
aDate := CurrentDate;
if aTime = 0 then
aTime := CurrentTime;
PutToFullRec(lgAuthor_Key,aUser);
PutToFullRec(lgDate_Key,aDate);
PutToFullRec(lgTime_Key,aTime);
TmpFlag := acfNone;
if aAction in cOrdLogActions then
TmpFlag:=acfOrdinal;
if aAction in cJurLogActions then
TmpFlag:=acfJuror;
PutToFullRec(lgActionFlag_Key,TmpFlag);
PutToFullRec(lgAction_Key,aAction);
{$IfDef DocSaveTrace}
l3System.Msg2Log('PutDateLogRec : DocID=%d AddFRec', [aDocID]);
l3System.Msg2Log('PutDateLogRec : TblPath=%s', [TblFullName]);
lAge := MakePhoto(Self).Age;
{$EndIf}
Try
AddFRec;
{$IfDef DocSaveTrace}
if MakePhoto(Self).Age > lAge then
l3System.Msg2Log('PutDateLogRec : AgeCheck OK')
else
l3System.Msg2Log('PutDateLogRec : !!!! AgeCheck Fault');
{$EndIf}
except
On E : Exception do
l3System.Exception2Log(E);
end;
end; //with fTable do
end;
Procedure TLogBookTbl.PutLogRec(aDocID : LongInt;aAction : TLogActionType;aUser : TUserID);
Begin
PutDateLogRec(aDocID,aAction,0,0,aUser);
end;
Procedure TLogBookTbl.PutLogRecSet(aDocID : LongInt;aActSet : TLogActionSet);
Var
I : TLogActionType;
Begin
with fTable do
begin
StartCaching;
try
for I:=Low(TLogActionType) to High(TLogActionType) do
if I in aActSet then
PutLogRec(aDocID,I);
finally
StopCaching;
end;
end;
end;
procedure TLogBookTbl.PutLogRecToDocs(aDocIDs : ISAB; aAction : TLogActionType; aUser : TUserID = 0; aDate : TStDate = 0);
function lRecAccessProc(aItemPtr : Pointer) : Boolean;
begin
Result := True;
PutDateLogRec(PDocID(aItemPtr)^, aAction, aDate, 0, aUser);
end;
var
lSab : ISab;
lRAProcStub : TdtRecAccessProc;
begin
Assert(aDocIDs.TypeOfSab = RES_VALUE);
if aDocIDs.IsEmpty then Exit;
with fTable do
begin
StartCaching;
try
lRAProcStub := L2RecAccessProc(@lRecAccessProc);
try
aDocIDs.IterateRecords(lRAProcStub);
finally
FreeRecAccessProc(lRAProcStub);
end;
finally
StopCaching;
end;
end;
end;
Procedure TLogBookTbl.ClearLogBook;
Var
TmpSab : SAB;
DelDate : Word;
Begin
(* Вычищать не все записи, а только неюридические и Annoced *)
{ l3FillChar(TmpSab,SizeOf(SAB));
RefreshSrchList;
DelDate:=GlobalHtServer.CurDate-fSaveInt;
htSearch(@fSrchList,TmpSab,Table.Handle,lgDate_Key,Less,@DelDate,Nil);
Try
If (TmpSab.gFoundCnt<>0) then
if StartTA then
try
Ht(htDeleteRecords(TmpSab));
SuccessTA;
except
RollBackTA;
raise;
end;
finally
htClearResults(TmpSab);
end;}
end;
(*Function TLogBookTbl.LastModified(aDocID : LongInt; LogRecType : TLogActionFlags = acfNone) : TStDateTimeRec;
Var
DocHistory : Sab;
Begin
l3FillChar(Result,SizeOf(TStDateTimeRec));
DocHistory:=GetDocHistory(aDocID,{acfNone}LogRecType,True);
Try
If DocHistory.gFoundCnt<>0
then
Begin
htOpenResults(DocHistory,ROPEN_READ,@DateTimeArr,2);
Try
htReadResults(DocHistory,@Result,SizeOf(TStDateTimeRec));
finally
htCloseResults(DocHistory);
end;
end;
finally
htClearResults(DocHistory);
end;
end;*)
function TLogBookTbl.IsDocHadAction(aDocID : LongInt;aAction : TLogActionType; aDate : TStDate = 0): Boolean;
var
lSab : ISab;
Begin
Result := False;
lSab := MakeSab(Self);
lSab.Select(lgDocID_Key, aDocID);
if lSab.Count = 0 then Exit;
lSab.SubSelect(lgAction_key, aAction);
if lSab.Count = 0 then Exit;
if aDate <> 0 then
lSab.SubSelect(lgDate_Key, aDate);
Result := lSab.Count > 0;
end;
Function TLogBookTbl.IsDocModified(aDocID : LongInt) : Boolean;
Var
TmpSab : Sab;
Begin
TmpSab:=GetDocHistory(aDocID,acfOrdinal,False);
Try
If TmpSab.gFoundCnt>1 then
Result:=True
else
Result:=False;
finally
htClearResults(TmpSab);
end;
end;
(*
Function TLogBookTbl.GetMaxDateOnAction(aDocID : LongInt;aAction : TLogActionType) : TStDate;
Var
TmpSab1,
TmpSab2,
TmpSab3 : Sab;
Begin
Result:=0;
TmpSab1:=GetDocHistory(aDocID,acfNone,False);
Try
If TmpSab1.gFoundCnt<>0
then
Begin
htSearch(@TmpSab1,TmpSab2,Table.Handle,lgAction_key,Equal,@aAction,Nil);
Try
htAndResults(TmpSab3,TmpSab1,TmpSab2);
finally
htClearResults(TmpSab2);
end;
If TmpSab3.gFoundCnt<>0
then
htKeyMaximum(TmpSab3,lgDate_key,@Result);
htClearResults(TmpSab3);
end;
finally
htClearResults(TmpSab1);
end;
end;
Function TLogBookTbl.GetDatesOnAction(aDocID : LongInt;aAction : TLogActionType;
Var Dates : PStDate) : Word;
Var
TmpSab1,
TmpSab2,
TmpSab3 : Sab;
I,
TmpDate : TStDate;
TmpFld : SmallInt;
Begin
Result:=0;
Dates:=Nil;
TmpSab1:=GetDocHistory(aDocID,acfNone,False);
Try
If TmpSab1.gFoundCnt<>0
then
Begin
htSearch(@TmpSab1,TmpSab2,Table.Handle,lgAction_key,Equal,@aAction,Nil);
Try
htAndResults(TmpSab3,TmpSab1,TmpSab2);
Try
Result:=TmpSab3.gFoundCnt;
If Result<>0
then
Begin
l3System.GetLocalMem(Dates,SizeOf(TStDate)*Result);
TmpFld:=lgDate_key;
Ht(htOpenResults(TmpSab3,ROPEN_READ,@TmpFld,1));
Try
TmpDate:=0;
I:=1;
While htReadResults(TmpSab3,@TmpDate,SizeOf(TmpDate))<>0 do
Begin
PDatesArr(Dates)^[I]:=TmpDate;
Inc(I);
TmpDate:=0;
end;
finally
htCloseResults(TmpSab3);
end;
end
else
Dates:=Nil;
finally
htClearResults(TmpSab3);
end;
finally
htClearResults(TmpSab2);
end;
end
else
Begin
Result:=0;
Dates:=Nil;
end;
finally
htClearResults(TmpSab1);
end;
end; *)
Function TLogBookTbl.GetDocsOnAction(aAction : TLogActionType;UserID : TUserID;UserGr : Boolean) : Sab;
Var
TmpSab : Sab;
TmpSab1,
TmpSab2 : Sab;
Begin
with fTable do
begin
RefreshSrchList;
htSearch(@fSrchList,TmpSab,Handle,lgAction_key,Equal,@aAction,Nil);
Try
If UserID<>0 then
If UserGr then
begin
TmpSab2:=UserManager.GetUserIDSabOnGroup(UserID);
Try
htTransferToPhoto(TmpSab2,fSrchList,lgAuthor_Key);
htRecordsByKey(TmpSab1,TmpSab2);
finally
htClearResults(TmpSab2);
end;
try
TmpSab2:=TmpSab;
Try
htAndResults(TmpSab,TmpSab1,TmpSab2);
finally
htClearResults(TmpSab2);
end;
finally
htClearResults(TmpSab1);
end;
end
else
begin
htSearch(@fSrchList,TmpSab1,Handle,lgAuthor_Key,Equal,@UserID,Nil);
try
TmpSab2:=TmpSab;
Try
htAndResults(TmpSab,TmpSab1,TmpSab2);
finally
htClearResults(TmpSab2);
end;
finally
htClearResults(TmpSab1);
end;
end;
htValuesOfKey(Result,lgDocID_Key,TmpSab);
finally
htClearResults(TmpSab);
end;
end; //with fTable do
end;
procedure TLogBookTbl.GetLogDataList(aDocID : LongInt;aFlag : TLogActionFlags;
aDataList : Tl3DataList; InternalFormat : Boolean);
var
DocHistory : Sab;
ReadRec : TReadDisplayLogRec;
DisplayRec : TDisplayLogRec;
begin
DocHistory:=GetDocHistory(aDocID,aFlag,True);
try
aDataList.Changing;
try
aDataList.Clear;
if DocHistory.gFoundCnt<>0 then
begin
htOpenResults(DocHistory,ROPEN_READ,@DisplayArr,4);
try
while htReadResults(DocHistory,@ReadRec,SizeOf(TReadDisplayLogRec))<>0 do
if not InternalFormat then
with ReadRec do
begin
DisplayRec.Action:=Action;
DisplayRec.Date:=Date;
DisplayRec.Time:=Time;
DisplayRec.Author:=UserManager.GetUserDisplayName(Author);
aDataList.Add(@DisplayRec);
end
else
aDataList.Add(@ReadRec);
finally
htCloseResults(DocHistory);
end;
end;
finally
aDataList.Changed;
end;
finally
htClearResults(DocHistory);
end;
end;
{Procedure TLogBookTbl.DelLogOnDocID(aID : Longint);
Var
TmpSab : Sab;
Begin
TmpSab:=GetDocHistory(aID,acfNone,False);
Try
If (TmpSab.gFoundCnt<>0) then
if StartTA then
try
Ht(htDeleteRecords(TmpSab));
SuccessTA;
except
RollBackTA;
raise;
end;
finally
htClearResults(TmpSab);
end;
end; }
{procedure TLogBookTbl.DelAllLogOnDocsID(aIDs : ISab);
begin
DeleteRecsByKeys(aIDs,lgDocID_Key);
end;}
{
Procedure TLogBookTbl.DelUrLogOnDocsID(aIDs : Sab);
Var
TmpSab1,
TmpSab2,
TmpSab3 : SAB;
TmpFlag : TLogActionFlags;
Begin
RefreshSrchList;
htTransferToPhoto(aIDs,fSrchList,lgDocID_Key);
If aIDs.nRetCode = 0 then
Begin
htRecordsByKey(TmpSab1,aIDs);
Try
TmpFlag:=acfJuror;
htSearch(@fSrchList,TmpSab2,Table.Handle,lgActionFlag_Key,Equal,@TmpFlag,Nil);
Try
htAndResults(TmpSab3,TmpSab1,TmpSab2);
Try
If (TmpSab3.gFoundCnt<>0) then
if StartTA then
try
htDeleteRecords(TmpSab3);
SuccessTA;
except
RollBackTA;
raise;
end;
finally
htClearResults(TmpSab3);
end;
finally
htClearResults(TmpSab2);
end;
finally
htClearResults(TmpSab1);
end;
end;
end;
}
(*Procedure TLogBookTbl.DelIncludedLogOnDocsID(aIDs : ISab);
{Стирает VIncluded у пачки}
var
lAction : TLogActionType;
begin
aIDs.TransferToPhoto(lgDocID_Key, Self);
aIDs.RecordsByKey;
lAction := acIncluded;
aIDs.SubSelect(lgAction_Key, lAction);
aIDs.DeleteFromTable;
end;*)
Procedure TLogBookTbl.DelSingleLogRec(aDocID : TDocID;aAction : TLogActionType;
aDate : TStDate;aTime : TStTime);
var
SrchRec : TUniqLogRec;
AbsNum : LongInt;
RecH : RHANDLE;
begin
With SrchRec do
begin
DocID:=aDocID;
Action:=aAction;
Date:=aDate;
Time:=aTime;
end;
AbsNum:=Ht(htRecordByUniq(Nil,Table.Handle,lgUniKey,@SrchRec,@RecH));
If AbsNum <> 0 then
begin
Ht(htRecordDelete(Table.Handle,AbsNum));
{$IfDef DelLogTrace}
l3System.Msg2Log('Delete Journal: DocID=%d, TLogBookTbl.DelSingleLogRec', [aDocID]);
{$EndIf}
end;
end;
{function TLogBookTbl.DeleteRecords(aUserId: TUserID;
aFromDate, aToDate: TStDate): Integer;
Var
l_RecordsOfAuthor,
l_FilteredRecords: SAB;
Begin
Result := 0;
if StartTA then
try
RefreshSrchList;
// фильтрация по Auther'у
htSearch(@fSrchList,
l_RecordsOfAuthor,
Handle,
lgAuthor_Key,
EQUAL,
@aUserId,
nil);
Ht(l_RecordsOfAuthor.nRetCode);
try
if (l_RecordsOfAuthor.gFoundCnt > 0) then
begin
// фильтрация по интервалу дат
htSubSearch(l_RecordsOfAuthor,
l_FilteredRecords,
Handle,
lgDate_Key,
IN_RANGE,
@aFromDate,
@aToDate);
Ht(l_FilteredRecords.nRetCode);
try
if l_FilteredRecords.gFoundCnt > 0 then
begin
// удаление
Result := Ht(htDeleteRecords(l_FilteredRecords));
end;
finally
htClearResults(l_FilteredRecords);
end;
end; // if
finally
htClearResults(l_RecordsOfAuthor);
end;
SuccessTA;
except
RollBackTA;
raise;
end; // if
end;
}
procedure TLogBookTbl.CopyRecords(aSrcDocId, aDstDocId: Longint);
function lRecModifyProc(aBuffer : Pointer) : Boolean;
begin
PDocID(aBuffer)^ := aDstDocId; //Модифицируем первое поле записи
Result := True;
end;
var
lSab : ISab;
lRecModifyProcStub : TdtRecAccessProc;
begin
lSab := MakeSab(fTable);
lSab.Select(lgDocID_Key, aSrcDocId);
// заносим получившиеся записи в таблицу
lRecModifyProcStub := L2RecAccessProc(@lRecModifyProc);
try
fTable.CopyRecs(lSab, lRecModifyProcStub);
finally
FreeRecAccessProc(lRecModifyProcStub);
end;
end;
function TLogBookTbl.IsDocHadActions(aDocID : LongInt; aActions: array of TLogActionType; aDate : TStDate = 0): Boolean;
var
I: Integer;
l_Sab : ISab;
l_Sab2 : ISab;
Begin
Result := False;
l_Sab := MakeSab(Self);
l_Sab.Select(lgDocID_Key, aDocID);
if l_Sab.Count = 0 then Exit;
if aDate <> 0 then
begin
l_Sab.SubSelect(lgDate_Key, aDate);
if l_Sab.Count = 0 then Exit;
end;
for I := Low(aActions) to High(aActions) do
begin
l_Sab2 := MakeSabCopy(l_Sab);
l_Sab2.SubSelect(lgAction_key, aActions[I]);
Result := l_Sab2.Count > 0;
if Result then
Exit;
end;
end;
{function TLogBookTbl.MakeSabOfActions(aActions: TLogActionSet) : ISab;
var
l_Action: TLogActionType;
l_ActionFieldLength: Word;
l_SabIsBuilt: Boolean;
function lFillBufferProc(aBuffer: Pointer; aBufSize: Longint): Longint; register;
var
l_WrittenAmount: Longint;
begin
l_WrittenAmount := 0;
while not l_SabIsBuilt
and (l_Action <= High(TLogActionType))
and (l_WrittenAmount < aBufSize div l_ActionFieldLength) do
begin
if l_Action in aActions then
begin
PLogActionType(PChar(aBuffer) + l_WrittenAmount * l_ActionFieldLength)^ := l_Action;
Inc(l_WrittenAmount);
end;
if l_Action < High(TLogActionType) then
Inc(l_Action)
else
l_SabIsBuilt := True;
end;
Result := l_WrittenAmount * l_ActionFieldLength;
end;
var
lSab : TSab;
lFillBufferProcStub : TFillBufferProc;
begin
l_SabIsBuilt := False;
l_Action := Low(TLogActionType);
l_ActionFieldLength := Self.fldLength[lgAction_Key];
lFillBufferProcStub := L2FillBufferProc(@lFillBufferProc);
try
lSab := TSab.MakeValueSet(Self, lgAction_Key, lFillBufferProcStub);
finally
FreeFillBufferProc(lFillBufferProcStub);
end;
Result := lSab;
l3Free(lSab);
end;
function TLogBookTbl.MakeDocIdsSabBy(aActions: TLogActionSet;
aFromDate, aToDate: TStDate;
aUserId: TUserID = 0;
aUserGr: Boolean = False): ISab;
var
lUsersSab : ISab;
lTime : TStTime;
begin
//Ищем по Actions
Result := MakeSabOfActions(aActions);
Result.RecordsByKey;
// фильтруем по датам
Result.SubSelect(lgDate_Key, aFromDate, aToDate);
//lTime := HMStoStTime(11, 00, 00);
//Result.SubSelect(lgTime_Key, lTime, LESS_EQUAL);
if (aUserId > 0) then
begin
if aUserGr then
begin //фильтруем по группе
lUsersSab := UserManager.MakeUserIdSabOnGroup(aUserId);
lUsersSab.TransferToPhoto(lgAuthor_Key, Result);
lUsersSab.RecordsByKey;
Result.AndSab(lUsersSab);
end
else //фильтруем по юзеру
Result.SubSelect(lgAuthor_Key, aUserId);
end;
Result.ValuesOfKey(lgDocID_Key);
end;
function TLogBookTbl.DeleteRecords(aDocID: TDocID;
aAction: TLogActionType;
aDate: TStDate): Integer;
var
l_RecordsByDocId,
l_RecordsByAction,
l_RecordsByDate,
l_RecordsByDocIdAndAction,
l_FilteredRecords: SAB;
begin
Result := 0;
if StartTA then
try
RefreshSrchList;
// фильтрация по aDocID
htSearch(@fSrchList,
l_RecordsByDocId,
Handle,
lgDocID_Key,
EQUAL,
@aDocID,
nil);
Ht(l_RecordsByDocId.nRetCode);
try
if (l_RecordsByDocId.gFoundCnt > 0) then
begin
// фильтрация по aAction
htSearch(@fSrchList,
l_RecordsByAction,
Handle,
lgAction_Key,
EQUAL,
@aAction,
nil);
Ht(l_RecordsByAction.nRetCode);
try
if (l_RecordsByAction.gFoundCnt > 0) then
begin
// фильтрация по aDate
htSearch(@fSrchList,
l_RecordsByDate,
Handle,
lgDate_Key,
EQUAL,
@aDate,
nil);
Ht(l_RecordsByDate.nRetCode);
try
if (l_RecordsByDate.gFoundCnt > 0) then
begin
htAndResults(l_RecordsByDocIdAndAction,
l_RecordsByDocId,
l_RecordsByAction);
Ht(l_RecordsByDocIdAndAction.nRetCode);
try
if (l_RecordsByDocIdAndAction.gFoundCnt > 0) then
begin
htAndResults(l_FilteredRecords,
l_RecordsByDocIdAndAction,
l_RecordsByDate);
Ht(l_FilteredRecords.nRetCode);
try
if (l_FilteredRecords.gFoundCnt > 0) then
begin
// собственно удаление
if l_FilteredRecords.gFoundCnt > 0 then
Result := Ht(htDeleteRecords(l_FilteredRecords));
end; // if
finally
htClearResults(l_FilteredRecords);
end;
end; // if
finally
htClearResults(l_RecordsByDocIdAndAction);
end;
end; // if
finally
htClearResults(l_RecordsByDate);
end;
end; // if
finally
htClearResults(l_RecordsByAction);
end;
end; // if
finally
htClearResults(l_RecordsByDocId);
end;
SuccessTA;
except
RollBackTA;
raise;
end; // if
end;
}
end.
|
unit SctData;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995-2004 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses
classes, sysutils, sctcalc;
{$WARNINGS OFF}
type
{ TSctDataTypes }
TSctDataTypes = (dtypeUnknown, dtypeString, dtypeFloat, dtypeInteger,
dtypeBoolean, dtypeDateTime, dtypeBlob, dtypeMemo,
dtypeGraphic, dtypeCurrency);
{ TSctTextCase }
TSctTextCase = (tcNone, tcUpper, tcLower);
{ TSctData }
TSctData = class;
{ TSctTotalType }
TSctTotalType = (ttSum, ttCount, ttMax, ttMin, ttAverage, ttValue);
{ TSctRootformat }
TSctRootFormat = class(TPersistent)
private
FDisplayFormat: String;
FTextCase: TsctTextCase;
FFloatFormat: TFloatFormat;
FWidth, FDigits: Integer;
FSctLabel: TComponent;
FReturnStream: TStream;
FSuppressNulls: Boolean;
FUseCurrencyDecimals: Boolean;
protected
procedure SetDisplayFormat(DF: String);
procedure SetTextCase(TC: TSctTextCase);
procedure SetFloatFormat( FF: TFloatFormat);
procedure SetWidth(W: Integer);
procedure SetDigits(D: Integer);
procedure SetCurrencyDecimals(C: Boolean);
function GetReturnStream: TStream;
property ReturnStream: TStream read GetReturnStream write FReturnStream;
procedure SetSuppressNulls(sn: Boolean);
public
constructor Create; virtual;
destructor Destroy; override;
function FormatAsString(Data: TSctData): String;
function FormatAsStream(Data: TSctData): TStream;
property SctLabel: TComponent read FSctLabel write FSctLabel;
property FloatFormat: TFloatFormat read FFloatFormat write SetFloatFormat default ffGeneral;
property Digits: Integer read FDigits write SetDigits default 0;
published
property DisplayFormat: String read FDisplayFormat write SetDisplayFormat;
property Width: Integer read FWidth write SetWidth default 15;
property TextCase: TsctTextCase read FTextCase write SetTextCase default tcNone;
property SuppressNulls: Boolean read FSuppressNulls write SetSuppressNulls default False;
property UseCurrencyDecimals: Boolean read FUseCurrencyDecimals write SetCurrencyDecimals default False;
end;
{ TSctFormat }
TSctFormat = class(TSctRootFormat)
published
property FloatFormat;
property Digits;
end;
{ TSctFloatFormat }
TSctFloatFormat = class(TSctRootFormat)
public
constructor Create; override;
published
property FloatFormat default ffNumber;
property Digits default 2;
end;
{ TSctData }
TSctData = class(TObject)
private
FDataType: TSctDataTypes;
FReturnStream: TStream;
FStrings: TStrings;
protected
FIsNull: Boolean;
function GetReturnStream: TStream;
function GetAsString: String; virtual; abstract;
function GetAsInteger: LongInt; virtual; abstract;
function GetAsFloat: Double; virtual;
function GetAsCurrency: Currency; virtual;
function GetAsDateTime: TDateTime; virtual; abstract;
function GetAsBoolean: Boolean; virtual;
function GetAsStream: TStream; virtual;
function GetAsStrings: TStrings; virtual;
procedure SetAsString(Value: String); virtual; abstract;
procedure SetAsInteger(Value: LongInt); virtual; abstract;
procedure SetAsFloat(Value: Double); virtual; abstract;
procedure SetAsCurrency(Value: Currency); virtual; abstract;
procedure SetAsDateTime(Value: TDateTime); virtual; abstract;
procedure SetAsBoolean(Value: Boolean); virtual; abstract;
procedure SetAsStream(Stream: TStream); virtual; abstract;
procedure SetAsStrings(Strings: TStrings); virtual; abstract;
property ReturnStream: TStream read GetReturnStream write FReturnStream;
public
constructor Create; virtual;
destructor Destroy; override;
procedure SetValue( var Value ); virtual;
procedure SetData( Data: TSctData ); virtual;
procedure Reset; virtual;
property DataType: TSctDataTypes read FDataType write FDataType;
property AsString: String read GetAsString write SetAsString;
property AsInteger: LongInt read GetAsInteger write SetAsInteger;
property AsFloat: Double read GetAsFloat write SetAsFloat;
property AsCurrency: Currency read GetAsCurrency write SetAsCurrency;
property AsDateTime: TDateTime read GetAsDateTime write SetAsDateTime;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsStream: TStream read GetAsStream write SetAsStream;
function AsFormat(format: TSctFormat): String; virtual;
property IsNull: Boolean read FIsNull write FIsNull;
property AsStrings: TStrings read GetAsStrings write SetAsStrings;
end;
{ TSctString }
TSctString = class(TSctData)
private
FValueString: String;
protected
function GetAsString: String; override;
function GetAsInteger: LongInt; override;
function GetAsFloat: Double; override;
function GetAsDateTime: TDateTime; override;
function GetAsBoolean: Boolean; override;
procedure SetAsString(Value: String); override;
procedure SetAsInteger(Value: LongInt); override;
procedure SetAsFloat(Value: Double); override;
procedure SetAsDateTime(Value: TDateTime); override;
procedure SetAsBoolean(Value: Boolean); override;
public
constructor Create; override;
procedure Reset; override;
procedure SetValue( var Value); override;
procedure SetData( Data: TSctData ); override;
property ValueString: String read FValueString write FValueString;
end;
{ TSctInteger }
TSctInteger = class(TSctData)
private
FValueInteger: LongInt;
protected
function GetAsString: String; override;
function GetAsInteger: LongInt; override;
function GetAsFloat: Double; override;
function GetAsBoolean: Boolean; override;
procedure SetAsString(Value: String); override;
procedure SetAsInteger(Value: LongInt); override;
procedure SetAsFloat(Value: Double); override;
procedure SetAsBoolean(Value: Boolean); override;
public
constructor Create; override;
procedure Reset; override;
procedure SetValue( var Value); override;
procedure SetData( data: TSctData ); override;
property ValueInteger: LongInt read FValueInteger write FValueInteger;
end;
{ TSctDateTime }
TSctDateTime = class(TSctData)
private
FValueDateTime: TDateTime;
protected
function GetAsString: String; override;
function GetAsDateTime: TDateTime; override;
function GetAsFloat: Double; override;
procedure SetAsString(Value: String); override;
procedure SetAsDateTime( Value: TDateTime); override;
procedure SetAsFloat( Value: Double ); override;
public
constructor Create; override;
procedure Reset; override;
procedure SetValue( var Value); override;
procedure SetData( Data: TSctData ); override;
property ValueDateTime: TDateTime read FValueDateTime write FValueDateTime;
end;
{ TSctBoolean }
TSctBoolean = class(TSctData)
private
FValueBoolean: Boolean;
protected
function GetAsString: String; override;
function GetAsInteger: LongInt; override;
function GetAsFloat: Double; override;
function GetAsBoolean: Boolean; override;
procedure SetAsString(Value: String); override;
procedure SetAsInteger(Value: LongInt); override;
procedure SetAsFloat(Value: Double); override;
procedure SetAsBoolean(Value: Boolean); override;
public
constructor Create; override;
procedure Reset; override;
procedure SetValue( var Value); override;
procedure SetData( Data: TSctData ); override;
property ValueBoolean: Boolean read FValueBoolean write FValueBoolean;
end;
{ TSctBlob }
TSctBlob = class(TSctData)
private
FValueStream: TMemoryStream;
protected
function GetAsString: String; override;
function GetAsStream: TStream; override;
procedure SetAsStream(Stream: TStream); override;
procedure SetAsString(Value: String); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Reset; override;
procedure SetValue( var Value); override;
procedure SetData( Data: TSctData ); override;
property ValueStream: TMemoryStream read FValueStream write FValueStream;
end;
{ TSctMemo }
TSctMemo = class(TSctBlob)
private
protected
function GetAsString: String; override;
function GetAsStrings: TStrings; override;
procedure SetAsStrings(Strings: TStrings); override;
public
constructor Create; override;
end;
{ TSctGraphic }
TSctGraphic = class(TSctBlob)
private
protected
public
constructor Create; override;
end;
{ TSctUnknown }
TSctUnknown = class(TSctBlob)
private
protected
function GetAsString: String; override;
public
constructor Create; override;
end;
implementation
uses
{$ifdef VCL140PLUS}maskutils {$else} mask {$endif}
, sctutil, dialogs, sctctrl;
{ TsctFormat }
constructor TSctRootFormat.Create;
begin
inherited Create;
FDisplayFormat := '';
FTextCase := tcNone;
FFloatFormat := ffGeneral;
FWidth := 15;
FDigits := 0;
FReturnStream := nil;
FSuppressNulls := False;
FUseCurrencyDecimals := False;
end;
destructor TSctRootFormat.Destroy;
begin
if FReturnStream <> nil then FReturnStream.Free;
inherited destroy;
end;
function TSctRootFormat.GetReturnStream: TStream;
begin
if FReturnStream = nil then FReturnStream := TMemoryStream.Create;
result := FReturnStream;
end;
procedure TSctRootFormat.SetDisplayFormat(DF: String);
begin
if FDisplayFormat <> DF Then
begin
FDisplayFormat := DF;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetTextCase(TC: TSctTextCase);
begin
if FTextCase <> TC Then
begin
FTextCase := TC;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetFloatFormat( FF: TFloatFormat);
begin
if FFloatFormat <> FF Then
begin
FFloatFormat := FF;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetWidth(W: Integer);
begin
if FWidth <> W Then
begin
FWidth := W;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetDigits(D: Integer);
begin
if FDigits <> D Then
begin
FDigits := D;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetSuppressNulls(sn: Boolean);
begin
if FSuppressNulls <> sn Then
begin
FSuppressNulls := sn;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
procedure TSctRootFormat.SetCurrencyDecimals(C: Boolean);
begin
if FUseCurrencyDecimals <> C Then
begin
FUseCurrencyDecimals := C;
if SctLabel <> nil Then TSctLabel(SctLabel).Invalidate;
end;
end;
function TsctRootFormat.FormatAsString(data: TSctData): String;
var
S: string;
lDF: Boolean;
bFalse, bTrue: String;
spot: Integer;
begin
lDF := Not sctEmpty(DisplayFormat);
if FSuppressNulls And Data.IsNull then result := ''
else
begin
case data.DataType of
dtypeString:
if lDF Then S := FormatMaskText(DisplayFormat, data.AsString )
else S := data.AsString;
dtypeCurrency:
if lDF Then
begin
if displayformat='HH:MM' then
s:=formatCurr('###00',round(1440*data.asCurrency)/60)
+':'+formatCurr('00',frac(round(1440*data.asCurrency)/60)*60)
else
S := FormatCurr(DisplayFormat, data.AsCurrency);
end
else
begin
if (FloatFormat = ffCurrency) And FUseCurrencyDecimals then
begin
S := CurrToStrF(data.AsCurrency, FloatFormat,
{$ifdef VCL230PLUS}
FormatSettings.CurrencyDecimals);
{$else}
CurrencyDecimals);
{$endif}
end
else
S := CurrToStrF(data.AsCurrency, FloatFormat, Digits);
end;
dtypeInteger, dtypeFloat:
if lDF Then
begin
if displayformat='HH:MM' then
s:=formatfloat('###00',round(1440*data.asfloat)/60)
+':'+formatfloat('00',frac(round(1440*data.asfloat)/60)*60)
else
S := FormatFloat(DisplayFormat, data.AsFloat);
end
else
begin
if (FloatFormat = ffCurrency) And FUseCurrencyDecimals then
begin
S := FloatToStrF(data.AsFloat, FloatFormat, Width,
{$ifdef VCL230PLUS}
FormatSettings.CurrencyDecimals);
{$else}
CurrencyDecimals);
{$endif}
end
else
S := FloatToStrF(data.AsFloat, FloatFormat, Width, Digits);
end;
dtypeDateTime:
if lDF Then S := FormatDateTime(DisplayFormat, data.AsDateTime)
else S := data.AsString;
dtypeBoolean:
if lDF then
begin
spot := Pos(';', DisplayFormat);
if spot = 0 then spot := 256;
bFalse := Copy(DisplayFormat, spot + 1, 255);
bTrue := Copy(DisplayFormat, 1, spot - 1);
if Data.AsBoolean then S := bTrue
else S := bFalse;
end else S := Data.AsString;
else
S := data.AsString;
end;
case TextCase of
tcNone: result := S;
tcUpper: result := UpperCase(S);
tcLower: result := LowerCase(S);
end;
end;
end;
{$IFDEF VER80}
function TSctRootFormat.FormatAsStream(data: TSctData): TStream;
var
text: array[0..256] of Char;
tempStr, str: String;
begin
TMemoryStream(ReturnStream).Clear;
str := FormatAsString(data);
while length(str) > 255 do
begin
tempStr := Copy(str,0,255);
strPCopy(text, tempStr);
ReturnStream.Write(text,255);
Delete(str,1,255);
end;
strPCopy(text, str);
ReturnStream.Write(text, length(str));
ReturnStream.Position := 0;
result := ReturnStream;
end;
{$ELSE}
{Revised FormatAsStream function submitted by Richard C. Haven}
function TSctRootFormat.FormatAsStream(data : TSctData) : TStream;
var
ThisString : string;
{$ifdef UNICODE}
B: TBytes;
{$endif}
begin
TMemoryStream(ReturnStream).Clear;
ThisString := FormatAsString(data);
{$ifdef UNICODE}
B := TEncoding.Unicode.GetPreamble;
ReturnStream.Write(B[0],Length(B));
{$endif}
ReturnStream.Write(PChar(ThisString)^, Length(ThisString)*sizeof(Char));
ReturnStream.Position := 0;
Result := ReturnStream;
end;
{$ENDIF}
{ TSctFloatFormat }
constructor TSctFloatFormat.Create;
begin
inherited Create;
FDigits := 2;
FFloatFormat := ffNumber;
end;
{ TSctData }
constructor TSctData.Create;
begin
inherited Create;
DataType := dtypeUnknown;
FIsNull := False;
Reset;
FStrings := TStringList.Create;
end;
destructor TSctData.Destroy;
begin
if FReturnStream <> nil then FReturnStream.Free;
if FStrings <> nil then FStrings.Free;
inherited Destroy;
end;
function TSctData.GetReturnStream: TStream;
begin
if FReturnStream = nil then FReturnStream := TMemoryStream.Create;
result := FReturnStream;
end;
procedure TSctData.Reset;
begin
FIsNull := False;
end;
procedure TSctData.SetValue( var Value );
begin
end;
procedure TSctData.SetData( data: TSctData );
begin
end;
function TSctData.AsFormat(format: TSctFormat): String;
begin
result := Format.FormatAsString(self);
end;
function TSctData.GetAsBoolean: Boolean;
begin
Result := False;
end;
function TSctData.GetAsCurrency: Currency;
begin
Result := 0;
end;
function TSctData.GetAsFloat: Double;
begin
Result := 0;
end;
function TSctData.GetAsStream: TStream;
var
text: array[0..256] of Char;
begin
TMemoryStream(ReturnStream).Clear;
strPCopy(text, AsString);
ReturnStream.Write(text, length(AsString)*Sizeof(Char));
ReturnStream.Position := 0;
result := ReturnStream;
end;
function TSctData.GetAsStrings: TStrings;
begin
FStrings.Clear;
FStrings.Add(AsString);
Result := FStrings;
end;
{ TSctString }
constructor TSctString.Create;
begin
inherited Create;
DataType := dtypeString;
end;
procedure TSctString.Reset;
begin
ValueString := '';
FIsNull := False;
end;
procedure TSctString.SetValue( var Value );
begin
ValueString := String(Value);
end;
procedure TSctString.SetData( data: TSctData );
begin
ValueString := TSctString(data).AsString;
FIsNull := data.IsNull;
end;
function TSctString.GetAsString: String;
begin
result := ValueString;
end;
function TSctString.GetAsInteger: LongInt;
begin
result := StrToInt(ValueString);
end;
function TSctString.GetAsFloat: Double;
begin
try
Result := StrToFloat(ValueString);
except
Result := 0;
end;
end;
function TSctString.GetAsDateTime: TDateTime;
begin
result := StrToDateTime(ValueString);
end;
function TSctString.GetAsBoolean: Boolean;
begin
if Length(ValueString) > 0 then
begin
case ValueString[1] of
'Y','y','T','t': Result := True;
else Result := False;
end;
end else Result := False;
end;
procedure TSctString.SetAsString(Value: String);
begin
ValueString := Value;
end;
procedure TSctString.SetAsInteger(Value: LongInt);
begin
ValueString := IntToStr(Value);
end;
procedure TSctString.SetAsFloat(Value: Double);
begin
ValueString := FloatToStr(Value);
end;
procedure TSctString.SetAsDateTime(Value: TDateTime);
begin
ValueString := DateToStr(Value);
end;
procedure TSctString.SetAsBoolean(Value: Boolean);
begin
if Value then ValueString := 'True'
else ValueString := 'False';
end;
{ TSctInteger }
constructor TSctInteger.Create;
begin
inherited Create;
DataType := dtypeInteger;
end;
procedure TSctInteger.Reset;
begin
ValueInteger := 0;
FIsNull := False;
end;
procedure TSctInteger.SetValue( var Value );
begin
ValueInteger := LongInt(Value);
end;
procedure TSctInteger.SetData( data: TSctData );
begin
ValueInteger := TSctInteger(data).AsInteger;
FIsNull := data.IsNull;
end;
function TSctInteger.GetAsString: String;
begin
result := IntToStr(ValueInteger);
end;
function TSctInteger.GetAsInteger: LongInt;
begin
result := ValueInteger;
end;
function TSctInteger.GetAsFloat: Double;
begin
result := ValueInteger;
end;
function TSctInteger.GetAsBoolean: Boolean;
begin
result := ValueInteger <> 0;
end;
procedure TSctInteger.SetAsString(Value: String);
begin
ValueInteger := StrToInt(Value);
end;
procedure TSctInteger.SetAsInteger(Value: LongInt);
begin
ValueInteger := Value;
end;
procedure TSctInteger.SetAsFloat(Value: Double);
begin
ValueInteger := Trunc(Value);
end;
procedure TSctInteger.SetAsBoolean(Value: Boolean);
begin
if Value then ValueInteger := 1
else ValueInteger := 0;
end;
{ TSctDateTime }
constructor TSctDateTime.Create;
begin
inherited Create;
DataType := dtypeDateTime;
end;
procedure TSctDateTime.Reset;
begin
ValueDateTime := 0;
FIsNull := False;
end;
procedure TSctDateTime.SetValue( var Value );
begin
ValueDateTime := TDateTime(Value);
end;
procedure TSctDateTime.SetData( data: TSctData );
begin
ValueDateTime := TSctDateTime(data).AsDateTime;
FIsNull := data.IsNull;
end;
function TSctDateTime.GetAsString: String;
begin
if (ValueDateTime = 0) or (FIsNull) then result := ''
else result := DatetoStr(ValueDateTime);
end;
function TSctDateTime.GetAsDateTime: TDateTime;
begin
result := ValueDateTime;
end;
function TSctDateTime.GetAsFloat: Double;
begin
result := ValueDateTime;
end;
procedure TSctDateTime.SetAsString(Value: String);
begin
ValueDateTime := StrToDateTime(Value);
end;
procedure TSctDateTime.SetAsDateTime( Value: TDateTime);
begin
ValueDateTime := Value;
end;
procedure TSctDateTime.SetAsFloat( Value: Double );
begin
ValueDateTime := TDateTime( Value );
end;
{ TSctBoolean }
constructor TSctBoolean.Create;
begin
inherited Create;
DataType := dtypeBoolean;
end;
procedure TSctBoolean.Reset;
begin
ValueBoolean := False;
FIsNull := False;
end;
procedure TSctBoolean.SetValue( var Value );
begin
ValueBoolean := Boolean(Value);
end;
procedure TSctBoolean.SetData( data: TSctData );
begin
ValueBoolean := TSctBoolean(data).AsBoolean;
FIsNull := data.IsNull;
end;
function TSctBoolean.GetAsString: String;
begin
if ValueBoolean Then result := 'True'
else result := 'False';
end;
function TSctBoolean.GetAsInteger: LongInt;
begin
if ValueBoolean then result := 1
else result := 0;
end;
function TSctBoolean.GetAsFloat: Double;
begin
if ValueBoolean then result := 1
else result := 0;
end;
function TSctBoolean.GetAsBoolean: Boolean;
begin
result := ValueBoolean;
end;
procedure TSctBoolean.SetAsString(Value: String);
begin
if CompareText(Value, 'True') = 0 then ValueBoolean := True
else ValueBoolean := False;
end;
procedure TSctBoolean.SetAsInteger(Value: LongInt);
begin
ValueBoolean := Value <> 0;
end;
procedure TSctBoolean.SetAsFloat(Value: Double);
begin
ValueBoolean := Value <> 0;
end;
procedure TSctBoolean.SetAsBoolean(Value: Boolean);
begin
ValueBoolean := Value;
end;
{ TSctBlob }
constructor TSctBlob.Create;
begin
inherited Create;
DataType := dtypeBlob;
ValueStream := TMemoryStream.Create;
end;
destructor TSctBlob.Destroy;
begin
if ValueStream <> nil Then ValueStream.Free;
inherited Destroy;
end;
procedure TSctBlob.Reset;
begin
if ValueStream <> nil Then ValueStream.Clear;
FIsNull := False;
end;
procedure TSctBlob.SetValue( var Value );
begin
ValueStream.LoadFromStream( TStream(Value) );
end;
procedure TSctBlob.SetData( data: TSctData );
begin
ValueStream.LoadFromStream(TSctBlob(data).ValueStream);
FIsNull := data.IsNull;
end;
function TSctBlob.GetAsString: String;
begin
Result := '';
Raise Exception.Create('I am not allowing blob or graphic value AsString.');
end;
procedure TSctBlob.SetAsString(Value: String);
{$ifdef UNICODE}
var
B: TBytes;
{$endif}
begin
ValueStream.Clear;
if Length(Value) > 0 then
begin
{$ifdef UNICODE}
B := TEncoding.Unicode.GetPreamble;
ValueStream.Write(B[0],Length(B));
{$endif}
ValueStream.WriteBuffer(Pointer(Value)^, Length(Value)*SizeOf(Value[1]));
end;
end;
function TSctBlob.GetAsStream: TStream;
begin
ValueStream.Position := 0;
result := ValueStream;
end;
procedure TSctBlob.SetAsStream(stream: TStream);
begin
ValueStream.LoadFromStream( stream );
end;
{ TSctMemo }
constructor TSctMemo.Create;
begin
inherited Create;
DataType := dtypeMemo;
end;
function TSctMemo.GetAsString: String;
begin
Result := '';
if ValueStream.Size > 0 then
begin
ValueStream.Position := 0;
SetString(Result, PChar(nil), ValueStream.Size);
ValueStream.Read(Pointer(Result)^, ValueStream.Size);
end;
end;
function TSctMemo.GetAsStrings: TStrings;
begin
FStrings.Clear;
FStrings.LoadFromStream(AsStream);
Result := FStrings;
end;
procedure TSctMemo.SetAsStrings(Strings: TStrings);
begin
FStrings.Clear;
ValueStream.Clear;
Strings.SaveToStream(ValueStream);
end;
{ TSctGraphic }
constructor TSctGraphic.Create;
begin
inherited Create;
DataType := dtypeGraphic;
end;
{ TSctUnknown }
constructor TSctUnknown.Create;
begin
inherited Create;
DataType := dtypeUnknown;
end;
function TSctUnknown.GetAsString: String;
begin
Result := 'Unknown type, check to see if field exists.';
end;
{$WARNINGS ON}
end.
|
unit main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
System.Contnrs, System.types, System.IOUtils;
type
TLUAObject = class
Name : String; // Имя
Code : String; // Код объекта
end;
TLUAFunction = class
Name : String; // Имя
Code : TStringList; // Код функции
ParamCount: Integer; // число входных параметров
ParamNames : String; // Входные параметры
end;
TForm1 = class(TForm)
mmoObjectCode: TMemo;
lbl1: TLabel;
lstObject: TListBox;
lstFunctions: TListBox;
lblFunction: TLabel;
lbl2: TLabel;
mmoFunctionCode: TMemo;
lbl3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lstObjectClick(Sender: TObject);
procedure lstFunctionsClick(Sender: TObject);
private
{ Private declarations }
OL_Object : TObjectList;
OL_Function : TObjectList;
public
{ Public declarations }
function GetFilesForScan : TStringList;
procedure ScanFileForObject (const Filename: String);
procedure ScanFileForFunction (const FileName : string);
end;
var
Form1: TForm1;
FilesArray : TStringDynArray;
implementation
Uses IdGlobal;
{$R *.dfm}
const
entrylau = 'entry.lua';
objecttypes : array [0..1] of String =
(
('topc_string'),
('topc_string_min_max')
);
procedure TForm1.FormCreate(Sender: TObject);
var
FileNames : TStringList;
i: Integer;
begin
OL_Object := TObjectList.Create (true);
OL_Function := TObjectList.Create (true);
FileNames := GetFilesForScan;
if (FileNames = nil) or (FileNames.Count = 0) then
begin
ShowMessage('Ничего не найдено');
Exit;
end;
for i := 0 to FileNames.Count-1 do
begin
ScanFileForObject(FileNames[i]);
ScanFileForFunction(FileNames[i]);
end;
FileNames.Free;
for i := 0 to OL_Object.Count-1 do
lstObject.AddItem(TLUAObject(OL_Object[i]).Name,nil);
for i := 0 to OL_Function.Count-1 do
lstFunctions.AddItem(TLUAFunction(OL_Function[i]).Name,nil);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
OL_Object.Free;
OL_Function.Free;
end;
//****************************************************************************************
function TForm1.GetFilesForScan: TStringList;
var
ssList : TStringList;
fPath, nameTemp, lTemp : string;
i, posishen : Integer;
begin
// Функция должна получить список файлов для дальнейшего анализа
fPath := ExtractFilePath(Application.ExeName) + 'scripts\' ;
if FileExists(fPath + entrylau) then // Исправлено
begin
Result := TStringList.Create;
ssList := TStringList.Create;
ssList.LoadFromFile(fPath + entrylau);
for I := 0 to ssList.Count -1 do
begin
lTemp := ssList[i];
if ltemp.IndexOf('dofile2') > -1 then
begin
Fetch(lTemp,'"'); // лучше так а не ("
lTemp := Fetch(lTemp, '"');
Result.Add(fpath + lTemp);
end;
end;
Result.Insert(0,fpath + entrylau);
ssList.Free;
end else
Result := nil;
end;
//****************************************************************************************
//****************** Выбор из TListBox ***************************************************
procedure TForm1.lstFunctionsClick(Sender: TObject);
var
i : integer;
begin
if lstFunctions.ItemIndex < 0 then
Exit;
mmoFunctionCode.Clear;
mmoFunctionCode.Lines[0] := 'Name : ' + TLUAFunction (OL_Function[lstFunctions.ItemIndex]).Name;
mmoFunctionCode.Lines.Add('Code : ');
mmoFunctionCode.Lines.Add('******************************************************');
for I := 0 to TLUAFunction (OL_Function[lstFunctions.ItemIndex]).Code.Count -1 do
mmoFunctionCode.Lines.Add(TLUAFunction (OL_Function[lstFunctions.ItemIndex]).Code.Strings[i]);
mmoFunctionCode.Lines.Add('******************************************************');
mmoFunctionCode.Lines.Add('ParametrCount : ' + IntToStr(TLUAFunction (OL_Function[lstFunctions.ItemIndex]).ParamCount));
mmoFunctionCode.Lines.Add('ParametrNames : ' + TLUAFunction (OL_Function[lstFunctions.ItemIndex]).ParamNames);
end;
procedure TForm1.lstObjectClick(Sender: TObject);
begin
// выбрано ли что-то ?
if lstObject.ItemIndex < 0 then
Exit;
mmoObjectCode.Text := TLUAObject (OL_Object[lstObject.ItemIndex]).Code;
end;
//****************************************************************************************
//*************************** Процедура поиска функций ***********************************
procedure TForm1.ScanFileForFunction(const FileName: string);
var
sl : TStringList;
i, indexBegin, indexEnd : Integer;
LF : TLUAFunction;
tmp : String;
begin
// сканирование файла для поиска функций и заполнение OL_Function
sl := TStringList.Create;
sl.LoadFromFile(FileName);
i:= 0;
indexBegin := 0;
indexEnd := 0;
// ищем строку с заголовком "function"
while I < sl.Count - 1 do
begin
if not(sl.Strings[i].IndexOf('function') > -1) then
begin
Inc(i);
Continue
end
else if
// исключаем функцию 'function main_custom', не хотелось в первом "if" городить
// сложное условие
sl.Strings[i].IndexOf('function main_custom') > -1 then
begin
Inc(i);
Continue ;
end;
LF := TLUAFunction.Create;
LF.Code := TStringList.Create(True);
indexBegin := i;
tmp := sl.Strings[i];
LF.ParamCount :=0;
Fetch(tmp,'function');
LF.Name := Trim(Fetch(tmp,'('));
LF.ParamNames := '(' + tmp;
tmp := Trim(Fetch(tmp, ')'));
while tmp <> '' do
begin
Trim(Fetch(tmp, ','));
Inc(LF.ParamCount);
end;
inc(i);
//************** Вырезаю тело функции ****************************************************
while i < sl.Count do
if sl.Strings[i].IndexOf('end') > -1 then
begin
indexEnd := i;
if i = sl.Count -1 then
begin
while indexBegin <= indexEnd do
begin
LF.Code.add(sl.Strings[indexBegin]);
Inc(indexBegin);
end;
OL_Function.Add(LF);
end;
inc(i);
Continue
end
else if
(sl.Strings[i].IndexOf('function') > -1) or (i = sl.Count -1) then
begin
while indexBegin <= indexEnd do
begin
LF.Code.add(sl.Strings[indexBegin]);
Inc(indexBegin);
end;
OL_Function.Add(LF);
Break;
end
else inc(i);
end;
sl.Free;
end;
//****************************************************************************************
//*************************** Процедура поиска объектов **********************************
procedure TForm1.ScanFileForObject(const Filename: String);
var
sl : TStringList;
i, j : Integer;
LO : TLUAObject;
tmp : String;
begin
// сканирование файла для поиска объектов и заполнение OL_Object
sl := TStringList.Create;
sl.LoadFromFile(FileName);
i := 0;
while (i < sl.Count) do
begin
// сравниваем строку с возможным перечнем объектов
for j := 0 to High (objecttypes) do
begin
if pos (objecttypes[j], sl.Strings[i]) > 0 then
begin
// Это объект
tmp := sl.Strings[i];
LO := TLUAObject.Create;
// Trim - удалит все пробелы
LO.Name := Trim (Fetch(tmp,'=',False));
LO.Code := sl.Strings[i];
OL_Object.Add (LO);
break; // выход из цикла
end;
end;
// берем следующую строку
inc (i);
end;
sl.Free;
end;
//****************************************************************************************
end.
|
unit uSceneGame;
interface
uses uScene, Types, uScript, uSceneInfo;
type
TScrollDir = (sdNone, sdCenter, sdLeft, sdRight, sdTop, sdDown);
TSceneGame = class(TScene)
private
M: TPoint;
FL, FT: Word;
Script: TScript;
ScrollDir: TScrollDir;
SceneInfo: TSceneInfo;
function CellCoord(X, Y: Integer): TPoint;
public
procedure Render; override;
procedure KeyDown(var Key: Word); override;
constructor Create;
destructor Destroy; override;
procedure Timer; override;
procedure EditMap(X, Y, Z: Integer);
procedure MouseMove(X, Y: Integer); override;
procedure MouseUp(Button: TMouseBtn); override;
procedure MouseDn(Button: TMouseBtn); override;
procedure Scroll(AX, AY: Byte; AScrollDir: TScrollDir);
procedure RenderPanel;
procedure Cursor(X, Y: Integer);
function IsMapCreature(X, Y: Integer): ShortInt;
end;
var
SceneGame: TSceneGame;
implementation
uses Graphics, Windows, Forms, SysUtils, uGraph, uBox, uMap, uTile, uUtils,
uSprites, uEnemy, uEdit, uHero, uMain, uScenes;
{ TSceneGame }
procedure TSceneGame.MouseUp(Button: TMouseBtn);
var
ID: ShortInt;
X, Y, Z: Byte;
Pt: TPoint;
begin
Z := 0;
// Minimap
if PointInRect(M.X, M.Y, FL - 2, FT - 2,
Map.Width + 3, Map.Height + 3) then
begin
Scroll(M.X - FL, M.Y - FT, sdCenter);
Render;
Exit;
end;
//
if PointInRect(M.X, M.Y, 0, 0,
ScreenWidth * TileSize, Graph.Surface.Height) then
begin
Pt := CellCoord(M.X, M.Y);
X := Pt.X;
Y := Pt.Y;
if IsEdit then
begin
EditMap(X, Y, Z);
Exit;
end;
//
for Z := lrCrt downto lrObj do
begin
case Z of
lrCrt:
begin
ID := IsMapCreature(X, Y);
if (ID >= 0) then
begin
Script.Run(X, Y);
Box('Enemy ID: ' + IntToStr(ID));
//Exit;
end;
end;
lrObj:
begin
ID := Map.FMap[Y][X][Z];
if (ID >= 0) then
begin
if (Button = mbRight) then
begin
// Info
Screen.Cursor := 1;
SceneInfo.Back.Assign(Graph.Surface);
SceneInfo.ObjID := ID;
Scenes.Scene := SceneInfo;
end else begin
// Use
Script.Run(X, Y);
Box('Object ID: ' + IntToStr(ID));
end;
//Exit;
end;
end;
end;
end;
// Hero
begin
Hero.ProceedPath(Pt);
Render;
end;
end;
end;
procedure TSceneGame.MouseDn(Button: TMouseBtn);
begin
inherited;
end;
function TSceneGame.CellCoord(X, Y: Integer): TPoint;
begin
Result.X := MapLeft + (X div TileSize);
Result.Y := MapTop + (Y div TileSize);
end;
constructor TSceneGame.Create;
begin
ScrollDir := sdCenter;
Script := TScript.Create;
SceneInfo := TSceneInfo.Create;
end;
destructor TSceneGame.Destroy;
begin
SceneInfo.Free;
Script.Free;
inherited;
end;
procedure TSceneGame.KeyDown(var Key: Word);
begin
case Key of
ord('E'): fEdit.ShowModal;
37: begin
Scroll(0, 0, sdLeft);
Render;
end;
38: begin
Scroll(0, 0, sdTop);
Render;
end;
39: begin
Scroll(0, 0, sdRight);
Render;
end;
40: begin
Scroll(0, 0, sdDown);
Render;
end;
end;
end;
procedure TSceneGame.MouseMove(X, Y: Integer);
begin
Self.Cursor(X, Y);
M.X := X;
M.Y := Y;
end;
procedure TSceneGame.Render;
const
ofs = 13 + TileSize;
var
T: Cardinal;
H: ShortInt;
X, Y, Z, DX, DY: Integer;
begin
with Graph.Surface.Canvas do
begin
FT := 24;
FL := (ScreenWidth * TileSize) + FT;
T := GetTickCount;
begin
// Terrain
for Y := 0 to ScreenHeight - 1 do
for X := 0 to ScreenWidth - 1 do
Draw(X * TileSize, Y * TileSize,
Tile[Map.FMap[MapTop + Y][MapLeft + X][lrTerrain]]);
// Grid
if IsEdit and IsGrid then
begin
Pen.Color := clYellow;
for Y := 0 to ScreenHeight - 1 do
begin
MoveTo(0, Y * TileSize);
LineTo(ScreenWidth * TileSize, Y * TileSize);
end;
for X := 0 to ScreenWidth - 1 do
begin
MoveTo(X * TileSize, 0);
LineTo(X * TileSize, ScreenHeight * TileSize);
end;
end;
// Buildings, Enemies
for Z := lrObj to lrPath do
for Y := 0 to ScreenHeight do
for X := 0 to ScreenWidth do
begin
DX := (X - 1) * TileSize;
DY := (Y - 1) * TileSize;
if (Map.FMap[MapTop + Y][MapLeft + X][Z] >= 0) then
case Z of
lrObj:
Graph.Surface.Canvas.Draw(DX, DY,
Sprite[spObj][Map.FMap[MapTop + Y][MapLeft + X][Z]]);
lrCrt:
Graph.Surface.Canvas.Draw(DX, DY,
Sprite[spCrt][Map.FMap[MapTop + Y][MapLeft + X][Z]]);
lrPath:
begin
Pen.Color := Random($FFFFFF);
Graph.Surface.Canvas.Ellipse(DX + ofs, DY + ofs, DX + ofs + 6, DY + ofs + 6);
end;
end;
end;
// Hero
Graph.Surface.Canvas.Draw((Hero.Pos.X - MapLeft - 1) * TileSize,
(Hero.Pos.Y - MapTop - 1) * TileSize, Sprite[spCrt][8]);
//
if IsEdit and not IsMove then
begin
Brush.Style := bsBDiagonal;
for Z := lrObj to lrCrt do
for Y := 0 to ScreenHeight - 1 do
for X := 0 to ScreenWidth - 1 do
begin
DX := X * TileSize;
DY := Y * TileSize;
H := Map.FMap[MapTop + Y][MapLeft + X][Z];
if (H >= lrStop) then
begin
if (H = lrStop) then Pen.Color := clRed;
if (H >= 0) then
begin
Pen.Color := clYellow;
if (Z = lrCrt) then
begin
Rectangle(DX - 30, DY - 30, DX + 63, DY + 63);
Continue;
end;
end;
Rectangle(DX + 3, DY + 3, DX + 30, DY + 30);
end;
end;
end;
Brush.Style := bsClear;
{ // Render creatures
with Creatures do if (Length(Enemy) > 0) then
for I := 0 to Length(Enemy) - 1 do
begin
if PointInRect(Enemy[I].X, Enemy[I].Y, MapLeft - 1, MapTop - 1,
MapLeft + ScreenWidth, MapTop + ScreenHeight) then
Graph.Surface.Canvas.Draw(((Enemy[I].X - 1) - MapLeft) * TileSize,
((Enemy[I].Y - 1) - MapTop) * TileSize, Creature[Enemy[I].ID]);
end; }
end;
RenderPanel;
TextOut(32, 32, IntToStr(GetTickCount - T));
end;
Graph.Render;
end;
procedure TSceneGame.RenderPanel;
var
Pt: TPoint;
begin
with Graph.Surface.Canvas do
begin
Brush.Color := 0;
FillRect(Rect(FL - 24, 0, Graph.Surface.Width, Graph.Surface.Height));
Draw(FL, FT, Map.Minimap);
Pen.Color := clYellow;
Brush.Style := bsClear;
Rectangle(FL - 1, FT - 1, FL + Map.Width, FT + Map.Height);
Rectangle(FL + MapLeft - 1, FT + MapTop - 1,
FL + MapLeft + ScreenWidth + 1,
FT + MapTop + ScreenHeight + 1);
Font.Color := clWhite;
Pt := CellCoord(M.X, M.Y);
TextOut(1100, 300, Format('%d %d', [Pt.X, Pt.Y]));
end;
end;
procedure TSceneGame.Timer;
begin
Hero.Update;
Render;
if (M.X < ScrollPadding) and (M.Y < ScrollPadding) then
begin
Scroll(0, 0, sdLeft);
Scroll(0, 0, sdTop);
Render;
Exit;
end;
if (M.X < ScrollPadding)
and (M.Y > (Graph.Surface.Height - ScrollPadding)) then
begin
Scroll(0, 0, sdLeft);
Scroll(0, 0, sdDown);
Render;
Exit;
end;
if (M.X > (Graph.Surface.Width - ScrollPadding))
and (M.Y < ScrollPadding) then
begin
Scroll(0, 0, sdRight);
Scroll(0, 0, sdTop);
Render;
Exit;
end;
if (M.X > (Graph.Surface.Width - ScrollPadding))
and (M.Y > (Graph.Surface.Height - ScrollPadding)) then
begin
Scroll(0, 0, sdRight);
Scroll(0, 0, sdDown);
Render;
Exit;
end;
if (M.X < ScrollPadding) then
begin
Scroll(0, 0, sdLeft);
Render;
Exit;
end;
if (M.Y < ScrollPadding) then
begin
Scroll(0, 0, sdTop);
Render;
Exit;
end;
if (M.X > (Graph.Surface.Width - ScrollPadding)) then
begin
Scroll(0, 0, sdRight);
Render;
Exit;
end;
if (M.Y > (Graph.Surface.Height - ScrollPadding)) then
begin
Scroll(0, 0, sdDown);
Render;
Exit;
end;
end;
procedure TSceneGame.Scroll(AX, AY: Byte; AScrollDir: TScrollDir);
var
I: Integer;
begin
case AScrollDir of
sdCenter:
begin
MapLeft := AX - (ScreenWidth div 2);
MapTop := AY - (ScreenHeight div 2);
I := Map.Height - ScreenHeight - 1;
if (MapTop > I) then MapTop := I;
if (MapTop < 0) then MapTop := 0;
I := Map.Width - ScreenWidth - 1;
if (MapLeft > I) then MapLeft := I;
if (MapLeft < 0) then MapLeft := 0;
end;
sdLeft:
begin
Dec(MapLeft);
if (MapLeft < 0) then MapLeft := 0;
end;
sdRight:
begin
Inc(MapLeft);
I := Map.Width - ScreenWidth - 1;
if (MapLeft > I) then MapLeft := I;
end;
sdTop:
begin
Dec(MapTop);
if (MapTop < 0) then MapTop := 0;
end;
sdDown:
begin
Inc(MapTop);
I := Map.Height - ScreenHeight - 1;
if (MapTop > I) then MapTop := I;
end;
end;
ScrollDir := AScrollDir;
end;
procedure TSceneGame.EditMap(X, Y, Z: Integer);
procedure Clear;
begin
Map.FMap[Y][X][lrObj] := lrNone;
Map.FMap[Y][X][lrCrt] := lrNone;
end;
begin
case fEdit.PageControl1.TabIndex of
0:
begin
if fEdit.sbNone.Down then Exit;
if fEdit.sbWater.Down then Map.FMap[Y][X][Z] := -1;
if fEdit.sbGround.Down then Map.FMap[Y][X][Z] := Map.GetGroundSet;
Map.MakeMap;
Map.Terrain;
Map.MakeMiniMap;
Render;
Exit;
end;
1:
begin
// Delete
if (MapObjectID = lrNone) and (MapEnemyID = lrNone)
and (Map.FMap[Y][X][lrTerrain] in GroundSet) then
begin
Clear;
Render;
Exit;
end;
// Add Object
if (Map.FMap[Y][X][lrObj] = lrNone)
and (Map.FMap[Y][X][lrCrt] = lrNone)
and (Map.FMap[Y][X][lrTerrain] in GroundSet) then
begin
Clear;
case MapSellectID of
lrObj: Map.FMap[Y][X][lrObj] := MapObjectID;
lrCrt: Map.FMap[Y][X][lrCrt] := MapEnemyID;
end;
Render;
Exit;
end;
end;
end;
end;
function TSceneGame.IsMapCreature(X, Y: Integer): ShortInt;
var
I, J: Word;
begin
Result := lrNone;
for I := Y - AggrZone to Y + AggrZone do
for J := X - AggrZone to X + AggrZone do
if Map.CellInMap(J , I) and (Map.FMap[I][J][lrCrt] >= 0) then
begin
Result := Map.FMap[I][J][lrCrt];
Exit;
end;
end;
procedure TSceneGame.Cursor(X, Y: Integer);
var
Pt: TPoint;
begin
if PointInRect(X, Y, 0, 0,
ScreenWidth * TileSize, Graph.Surface.Height) then
begin
Pt := CellCoord(X, Y);
if (IsMapCreature(Pt.X, Pt.Y) >= 0) then
Screen.Cursor := 2
else if (Map.FMap[Pt.Y][Pt.X][lrObj] >= 0) then
Screen.Cursor := 3 else Screen.Cursor := 1;
end else Screen.Cursor := 1;
end;
initialization
SceneGame := TSceneGame.Create;
finalization
SceneGame.Free;
end.
|
unit SctRtf;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995-2004 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses classes, sysutils, graphics, windows, psetup;
{$B-}
type
TSctRtfFile = class;
TSctRtfBorderType = (rbtBox, rbtBottom);
{ TSctRtfFont }
TSctRtfFont = class(TObject)
private
FNumber: Integer;
FPitchAndFamily, FCharSet: Byte;
FName: String;
FFont: TFont;
protected
procedure SetFont(f: TFont); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(f: TObject); virtual;
property Number: Integer read FNumber write FNumber;
property PitchAndFamily: Byte read FPitchAndFamily write FPitchAndFamily;
property CharSet: Byte read FCharSet write FCharSet;
property Name: String read FName write FName;
property Font: TFont read FFont write SetFont;
procedure WriteFont(RtfFile: TSctRtfFile);
function FontSame(f: TFont): Boolean; virtual;
function DefinitionSame(f: TFont): Boolean; virtual;
procedure WriteHeader(Stream: TStream); virtual;
end;
{ TSctTabAlignment }
TSctTabAlignment = (taLeft, taCenter, taRight);
{ TSctRtfFile }
TSctRtfFile = class(TObject)
private
FWriteStream, FStream: TStream;
FFont: TFont;
FRtfFont: TSctRtfFont;
FFontList: TList;
FBraceCount: LongInt;
FPageSetup: TSctPageSetup;
FBorder: Boolean;
FBorderType: TSctRtfBorderType;
FPageBreak: Boolean;
protected
procedure SetRtfFont(f: TSctRtfFont); virtual;
procedure SetFont(f: TFont);
procedure SetPageSetup(ps: TSctPageSetup);
public
constructor Create(FileName: String); virtual;
destructor Destroy; override;
procedure AddFont(f: TSctRtfFont); virtual;
procedure StartBorder; virtual;
procedure EndBorder; virtual;
procedure TextOut(Text: String); virtual;
procedure TextOutStream(s: TStream); virtual;
property Stream: TStream read FStream write FStream;
property WriteStream: TStream read FWriteStream write FWriteStream;
procedure WriteFile; virtual;
procedure Write(Text: String);
procedure NewParagraph; virtual;
property FontList: TList read FFontList write FFontList;
property RtfFont: TSctRtfFont read FRtfFont write SetRtfFont;
property Font: TFont read FFont write SetFont;
procedure StartFrame(x,y,w,h: Integer);
procedure EndFrame;
procedure ParagraphDefault;
procedure PushBrace; virtual;
procedure PopBrace; virtual;
property BraceCount: LongInt read FBraceCount write FBraceCount;
procedure DefineTab(xPos: Integer; t: TSctTabAlignment); virtual;
procedure Tab; virtual;
property PageSetup: TSctPageSetup read FPageSetup write SetPageSetup;
property Border: Boolean read FBorder write FBorder;
property BorderType: TSctRtfBorderType read FBorderType write FBorderType;
property PageBreak: Boolean read FPageBreak write FPageBreak;
end;
implementation
uses aceutil, dialogs;
procedure SendStream(Stream: TStream; text: String);
var
str: array[0..256] of Char;
begin
StrPCopy(str, text);
Stream.Write(str, Length(text));
end;
{ TSctRtfFont }
constructor TSctRtfFont.Create;
begin
inherited Create;
FFont := TFont.Create;
end;
destructor TSctRtfFont.Destroy;
begin
if FFont <> nil then FFont.free;
inherited destroy;
end;
procedure TSctRtfFont.Assign(f: TObject);
begin
if f is TSctRtfFont then Font := TSctRtfFont(f).Font;
end;
procedure TSctRtfFont.SetFont(f: TFont);
var
LogRec: TLOGFONT;
begin
FFont.Assign(f);
AceGetObject(FFont.Handle,SizeOf(LogRec),Addr(LogRec));
PitchAndFamily := LogRec.lfPitchAndFamily;
CharSet := LogRec.lfCharSet;
Name := StrPas(LogRec.lfFaceName);
end;
procedure TSctRtfFont.WriteFont(rtfFile: TSctRtfFile);
begin
rtfFile.Write('\f' + AceIntToStr(Number));
rtfFile.Write('\fs' + AceIntToStr(Font.Size * 2));
if fsBold in Font.Style then rtfFile.Write('\b');
if fsItalic in Font.Style then rtfFile.Write('\i');
if fsUnderline in Font.Style then rtfFile.Write('\ul');
{ if fsStrikeOut in Font.Style then rtfFile.Write('\so');}
rtfFile.Write(' ');
end;
procedure TSctRtfFont.WriteHeader(stream: TStream);
var
pitch: Integer;
family: String;
fam: Byte;
begin
SendStream(Stream, '{\f' + AceIntToStr(Number));
fam := PitchAndFamily And (15 shl 4);
case fam of
FF_DONTCARE: family := 'nil';
FF_ROMAN: family := 'roman';
FF_SWISS: family := 'swiss';
FF_MODERN: family := 'modern';
FF_SCRIPT: family := 'script';
FF_DECORATIVE: family := 'decor';
else
family := 'nil';
end;
SendStream(Stream, '\f' + family);
SendStream(Stream, '\fcharset0');
Pitch := 0;
case font.Pitch of
fpDefault: Pitch := 0;
fpFixed: Pitch := 1;
fpVariable: Pitch := 2;
end;
SendStream(Stream, '\fprq' + AceIntToStr(Pitch));
SendStream(Stream, ' ' + name + ';}');
end;
function TSctRtfFont.FontSame(f: TFont): Boolean;
var
LogRec: TLOGFONT;
begin
result := True;
if Font.Style <> f.style then result := False
else if Font.Size <> f.size then result := False
else if Font.Color <> f.color then result := False
else if Font.Pitch <> f.Pitch then result := False
else if Font.Name <> f.Name then result := False
else
begin
AceGetObject(FFont.Handle,SizeOf(LogRec),Addr(LogRec));
if PitchAndFamily <> LogRec.lfPitchAndFamily then result := False
else if CharSet <> LogRec.lfCharSet then result := False;
end;
end;
function TSctRtfFont.DefinitionSame(f: TFont): Boolean;
var
LogRec: TLOGFONT;
begin
result := True;
if Font.Pitch <> f.Pitch then result := False
else if Font.Name <> f.Name then result := False
else
begin
AceGetObject(FFont.Handle,SizeOf(LogRec),Addr(LogRec));
if PitchAndFamily <> LogRec.lfPitchAndFamily then result := False
else if CharSet <> LogRec.lfCharSet then result := False;
end;
end;
{ TSctRtfFile }
constructor TSctRtfFile.Create(filename: String);
begin
inherited create;
FPageBreak := False;
FBorder := False;
FPageSetup := TSctPageSetup.Create;
FBraceCount := 0;
FFontList := TList.Create;
FRtfFont := TSctRtfFont.Create;
AddFont(FRtfFont);
FFont := TFont.Create;
FRtfFont.Font := FFont;
FWriteStream := TFileStream.Create(filename, fmCreate);
FStream := TMemoryStream.Create;
Write('\pard\plain ');
RtfFont.WriteFont(self);
end;
destructor TSctRtfFile.Destroy;
var
pos: Integer;
begin
while BraceCount > 0 do
begin
BraceCount := BraceCount - 1;
Write('}');
end;
Write('}');
WriteFile;
if FPageSetup <> nil then FPageSetup.Free;
if FStream <> nil then FStream.Free;
if FWriteStream <> nil then FWriteStream.Free;
if FFontList <> nil then
begin
for pos := 0 to FFontList.Count - 1 do
begin
TSctRtfFont(FFontList.items[pos]).Free;
end;
FFontList.Free;
end;
if FFont <> nil then FFont.Free;
inherited destroy;
end;
procedure TSctRtfFile.SetPageSetup(ps: TSctPageSetup);
begin
FPageSetup.Assign(ps);
end;
procedure TSctRtfFile.SetRtfFont(f: TSctRtfFont);
begin
FRtfFont := f;
end;
procedure TSctRtfFile.SetFont(f: TFont);
var
pos: Integer;
spot: Integer;
begin
if Not RtfFont.FontSame(f) then
begin
{ find if any of the other fonts are the same }
pos := 0;
spot := -1;
while (spot = -1) And (pos < FontList.Count) do
begin
if TSctRtfFont(FontList.items[pos]).DefinitionSame(f) then spot := pos;
Inc(pos);
end;
if spot = -1 then
begin
AddFont( TSctRtfFont.Create );
end else RtfFont := TSctRtfFont(FontList.items[spot]);
FFont.Assign(f);
RtfFont.Font := f;
PopBrace;
PushBrace;
RtfFont.WriteFont(self);
end;
end;
procedure TSctRtfFile.PushBrace;
begin
BraceCount := BraceCount + 1;
Write('{');
end;
procedure TSctRtfFile.PopBrace;
begin
if BraceCount > 0 then
begin
BraceCount := BraceCount - 1;
Write('}');
end;
end;
procedure TSctRtfFile.AddFont(f: TSctRtfFont);
begin
FontList.Add(f);
f.Number := FontList.Count;
RtfFont := f;
end;
procedure TSctRtfFile.Write(text: String);
begin
SendStream(Stream, text);
end;
procedure TSctRtfFile.WriteFile;
var
pos: Integer;
function AceRoundToStr(Value: Extended): String;
var
Error: Boolean;
IntVal: LongInt;
begin
Error := False;
if Value = 0 then Error := True
else
begin
IntVal := Round(Value);
if IntVal = 0 then Error := True
else
begin
Result := AceIntToStr(IntVal);
end;
end;
if Error then
begin
{ ShowMessage('Value: ' + FloatToStr(Value));
ShowMessage('Width: ' + FloatToStr(PageSetup.Width));
ShowMessage('Height: ' + FloatToStr(PageSetup.Height));}
end;
end;
begin
SendStream(WriteStream, '{\rtf1\ansi ');
SendStream(WriteStream, '{\fonttbl');
for pos := 0 to FontList.Count - 1 do TSctRtfFont(FontList.items[pos]).WriteHeader(WriteStream);
SendStream(WriteStream, '}');
case PageSetup.Size of
psUseCurrent:;
psCustom:
begin
SendStream(WriteStream, '\paperw' + AceIntToStr(round(PageSetup.Width * 1440)) );
SendStream(WriteStream, '\paperh' + AceIntToStr(round(PageSetup.Height * 1440)) );
SendStream(WriteStream, '\psz' + AceIntToStr(PageSetup.AcePrinterSetup.PaperSize ));
end;
else
begin
SendStream(WriteStream, '\paperh' + AceRoundToStr(PageSetup.Height * 1440));
SendStream(WriteStream, '\paperw' + AceRoundToStr(PageSetup.Width * 1440));
SendStream(WriteStream, '\psz' + AceIntToStr(PageSetup.AcePrinterSetup.PaperSize));
end;
end;
SendStream(WriteStream, '\margl' + AceRoundToStr(PageSetup.LeftMargin * 1440));
SendStream(WriteStream, '\margr' + AceRoundToStr(PageSetup.RightMargin * 1440));
SendStream(WriteStream, '\margt' + AceRoundToStr(PageSetup.TopMargin * 1440) );
SendStream(WriteStream, '\margb' + AceRoundToStr(PageSetup.BottomMargin * 1440));
if PageSetup.Orientation = poLandScape then SendStream(WriteStream, '\landscape');
SendStream(WriteStream, ' ');
Stream.Position := 0;
WriteStream.CopyFrom( Stream, Stream.Size );
end;
procedure TSctRtfFile.StartBorder;
begin
Border := True;
end;
procedure TSctRtfFile.EndBorder;
begin
Border := False;
if BorderType <> rbtBottom then
begin
ParagraphDefault;
NewParagraph;
end;
end;
procedure TsctRtfFile.NewParagraph;
begin
Write('\par ');
end;
procedure TSctRtfFile.ParagraphDefault;
begin
PopBrace;
Write('\pard');
if FPageBreak then Write(' \page');
if Border then
begin
case BorderType of
rbtBottom: Write('\brdrb\brdrs ');
rbtBox: Write('\box\brdrs ');
end;
end;
RtfFont := fontlist.items[0];
RtfFont.WriteFont(self);
end;
procedure TSctRtfFile.StartFrame(x,y,w,h: Integer);
begin
ParagraphDefault;
Write('\posyt\phmrg');
Write('\posx' + AceIntToStr(x));
Write('\posy' + AceIntToStr(y));
if w > 0 then Write('\absw' + AceIntToStr(w));
if h > 0 then Write('\absh' + AceIntToStr(h));
Write('\dxfrtext180\dfrmtxtx180\dfrmtxty0 ');
end;
procedure TsctRtfFile.EndFrame;
begin
NewParagraph;
ParagraphDefault;
end;
procedure TSctRtfFile.TextOut(text: String);
begin
Write(text);
end;
procedure TSctRtfFile.TextOutStream(s: TStream);
begin
s.Position := 0;
Stream.CopyFrom( S, S.Size );
end;
procedure TSctRtfFile.DefineTab(xPos: Integer; t: TSctTabAlignment);
begin
case t of
taLeft:;
taCenter: Write('\tqc');
taRight: Write('\tqr');
end;
Write('\tx' + AceIntToStr(xPos) + ' ');
end;
procedure TSctRtfFile.Tab;
begin
Write('\tab ');
end;
end.
|
unit ChangePasswordDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TCWODT;
type
TChangePasswordDialog = class(TComponent)
private
FOldPassword: string;
FNewPassword: string;
FHelpContext: integer;
procedure SetHelpContext(const Value: integer);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
procedure Execute(ADaapi:IDaapiGlobal; AUserName:string);
published
{ Published declarations }
property HelpContext:integer read FHelpContext write SetHelpContext;
end;
procedure Register;
implementation
uses ChangePasswordForm, FFSUtils;
procedure Register;
begin
RegisterComponents('FFS Common', [TChangePasswordDialog]);
end;
{ TChangePasswordDialog }
{ TChangePasswordDialog }
procedure TChangePasswordDialog.Execute(ADaapi:IDaapiGlobal; AUserName:string);
var Dialog : TfrmChangePassword;
begin
if AUserName = SysAdmin then
begin
MsgAsterisk('Internal SysAdmin may not change password.');
exit;
end;
//try to get user table info
if not assigned(ADaapi) then raise exception.create('Daapi Not Assigned');
Dialog := TfrmChangePassword.create(self);
Dialog.HelpContext := FHelpContext;
try
if Dialog.showmodal = mrOk then
try
ADaapi.UserChangePassword(AUsername, Dialog.edtOldPassword.text, Dialog.edtNewPassword1.text);
MsgInformation('Password Changed');
except
MsgAsterisk('Password Not Changed - Make sure the old password is correct.');
end;
finally
Dialog.free;
end;
end;
procedure TChangePasswordDialog.SetHelpContext(const Value: integer);
begin
FHelpContext := Value;
end;
end.
|
{----------------------------------------------------------------------------
|
| Library: Envision
|
| Module: EnIcoGr
|
| Description: TDibGraphic descendant for ICO files.
|
| History: Dec 24, 1998. Michel Brazeau, first version
|
|---------------------------------------------------------------------------}
unit EnIcoGr;
{$I Envision.Inc}
interface
uses
Classes, { for TStream }
EnDiGrph; { for TDibGraphic }
type
TIconGraphic = class(TDibGraphic)
public
procedure SingleLoadFromStream( const Stream : TStream;
const ImageToLoad : LongInt
); override;
procedure SaveToStream(Stream: TStream); override;
end;
{--------------------------------------------------------------------------}
implementation
uses
Windows, { for TRect }
Graphics, { for TIcon }
EnMisc; { for TImageFormat }
{--------------------------------------------------------------------------}
type
TProtectedIcon = class(TIcon);
procedure TIconGraphic.SingleLoadFromStream(
const Stream : TStream;
const ImageToLoad : LongInt
);
var
Icon : TIcon;
Rect : TRect;
begin
Icon := TIcon.Create;
try
Icon.LoadFromStream(Stream);
Self.NewImage( Icon.Width, Icon.Height,
ifTrueColor, nil, 0, 0 );
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := Icon.Width;
Rect.Bottom := Icon.Height;
FillChar( Self.Bits^, Icon.Height * Self.ScanLineSize, 0);
TProtectedIcon(Icon).Draw(Self.Canvas, Rect);
finally
Icon.Free;
end;
end;
{--------------------------------------------------------------------------}
{ original Icon conversion code from internet newsgroup by:
George H. Silva 1997 snappy@global2000.net }
procedure TIconGraphic.SaveToStream(Stream: TStream);
var
Mask : Graphics.TBitmap;
Color : Graphics.TBitmap;
IconInfo : TIconInfo;
Icon : Graphics.TIcon;
begin
Icon := nil;
Mask := nil;
Color := nil;
try
FillChar(IconInfo,SizeOf(TIconInfo),0);
IconInfo.fIcon := True;
Color := Graphics.TBitmap.Create;
Mask := Graphics.TBitmap.Create;
Icon := Graphics.TIcon.Create;
Color.Height := GetSystemMetrics(SM_CYICON);
Color.Width := GetSystemMetrics(SM_CXICON);
Mask.Height := Color.Height;
Mask.Width := Color.Width;
Mask.Canvas.Brush.Color := clBlack;
Mask.Canvas.FillRect(Bounds(0,0,Mask.Width,Mask.Height));
IconInfo.hbmMask := Mask.Handle;
{ using StretchDraw the entire original is stretched
Color.Canvas.StretchDraw(Bounds(0,0,Color.Width,Color.Height),Self);
}
Color.Canvas.Draw(0, 0, Self);
IconInfo.hbmColor := Color.Handle;
Icon.Handle := CreateIconIndirect(IconInfo);
Icon.SaveToStream(Stream);
finally
Mask.Free;
Color.Free;
Icon.Free;
end;
end;
{--------------------------------------------------------------------------}
initialization
{$ifdef __RegisterEnvisionIco}
RegisterDibGraphic('ICO', 'Windows icon', TIconGraphic);
{$endif}
finalization
end.
|
Unit MatrixTools;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
{$macro on}
{$inline on}
interface
uses
CoreTypes, Math;
//General ----------->
function NewMatrix(W,H:Integer): T2DIntArray;
function NewMatrixEx(W,H,Init:Integer): T2DIntArray;
function TPAToMatrix(const TPA:TPointArray; Value:Integer; Align:Boolean): T2DIntArray;
function TPAToMatrixEx(const TPA:TPointArray; Init, Value:Integer; Align:Boolean): T2DIntArray;
function MatFromTIA(const TIA:TIntArray; Width,Height:Integer): T2DIntArray;
procedure PadMatrix(var Matrix:T2DIntArray; HPad, WPad:Integer);
function FloodFillMatrix(ImgArr:T2DIntArray; const Start:TPoint; EightWay:Boolean): TPointArray;
procedure DrawMatrixLine(var Mat:T2DIntArray; P1, P2: TPoint; Val:Integer); Inline;
//--------------------------------------------------
implementation
uses
PointTools, PointList;
{*
Create a integer matrix of the size given W,H.
*}
function NewMatrix(W,H:Integer): T2DIntArray;
begin
SetLength(Result, H, W);
end;
{*
Integer matrix of the size given my W,H, and initalize it with `init`.
*}
function NewMatrixEx(W,H,Init:Integer): T2DIntArray;
var X,Y:Integer;
begin
SetLength(Result, H, W);
for Y:=0 to H-1 do
for X:=0 to W-1 do
Result[Y][X] := Init;
end;
{*
Create a integer matrix filled with the points given by TPA, align the points to [0][0] if needed.
*}
function TPAToMatrix(const TPA:TPointArray; Value:Integer; Align:Boolean): T2DIntArray;
var
Y,Width,Height,H,i:Integer;
Area:TBox;
begin
H := High(TPA);
Area := TPABounds(TPA);
Width := (Area.X2 - Area.X1) + 1; //Width
Height := (Area.Y2 - Area.Y1) + 1; //Height
case Align of
True:
begin
SetLength(Result, Height, Width);
for i:=0 to H do
Result[TPA[i].y-Area.y1][TPA[i].x-Area.x1] := Value;
end;
False:
begin
SetLength(Result, Area.Y2+1);
for Y:=0 to Area.Y2 do
SetLength(Result[Y], Area.X2+1);
for i:=0 to H do
Result[TPA[i].y][TPA[i].x] := Value;
end;
end;
end;
{*
Create integer matrix filled with the points given by TPA, align the points to [0][0] if needed.
Initalizes it with the given initalizer.
*}
function TPAToMatrixEx(const TPA:TPointArray; Init, Value:Integer; Align:Boolean): T2DIntArray;
var
X,Y,Width,Height,H,i:Integer;
Area:TBox;
begin
H := High(TPA);
Area := TPABounds(TPA);
Width := (Area.X2 - Area.X1) + 1; //Width
Height := (Area.Y2 - Area.Y1) + 1; //Height
case Align of
True:
begin
SetLength(Result, Height, Width);
for Y:=0 to Height-1 do
for X:=0 to Width-1 do
Result[Y][X] := Init;
for i:=0 to H do
Result[TPA[i].y-Area.y1][TPA[i].x-Area.x1] := Value;
end;
False:
begin
SetLength(Result, Area.Y2+1, Area.X2+1);
for Y:=0 to Area.Y2 do
for X:=0 to Area.X2 do
Result[Y][X] := Init;
for i:=0 to H do
Result[TPA[i].y][TPA[i].x] := Value;
end;
end;
end;
{*
...
*}
function MatFromTIA(const TIA:TIntArray; Width,Height:Integer): T2DIntArray;
var y:Integer;
begin
SetLength(Result, Height,Width);
for y:=0 to Height-1 do
Move(TIA[y*width], Result[y][0], Width*SizeOf(Integer));
end;
{*
Pads the matrix with "empty" from all sides.
*}
procedure PadMatrix(var Matrix:T2DIntArray; HPad, WPad:Integer);
var
y,oldw,oldh,w,h:Integer;
Temp:T2DIntArray;
begin
OldW := Length(Matrix[0]);
OldH := Length(Matrix);
H := HPad+OldH+HPad;
W := WPad+OldW+WPad;
SetLength(Temp, H, W);
for y:=0 to OldH-1 do
Move(Matrix[y][0], Temp[y+HPad][WPad], OldW*SizeOf(Integer));
SetLength(Matrix, 0);
Matrix := Temp;
end;
{*
FloodFills the ImgArr, and returns the floodfilled points.
*}
function FloodFillMatrix(ImgArr:T2DIntArray; const Start:TPoint; EightWay:Boolean): TPointArray;
var
color,i,x,y,W,H,fj:Integer;
face:TPointArray;
Queue,Res: TPointList;
begin
W := High(ImgArr[0]);
H := High(ImgArr);
fj := 3;
if EightWay then fj := 7;
SetLength(Face, fj+1);
Queue.Init;
Res.Init;
Color := ImgArr[Start.y][Start.x];
Queue.Append(Start);
Res.Append(Start);
while Queue.NotEmpty do
begin
GetAdjacent(Face, Queue.FastPop, EightWay);
for i:=0 to fj do
begin
x := face[i].x;
y := face[i].y;
if ((x >= 0) and (y >= 0) and (x <= W) and (y <= H)) then
begin
if ImgArr[y][x] = color then
begin
ImgArr[y][x] := -1;
Queue.Append(face[i]);
Res.Append(face[i]);
end;
end;
end;
end;
Queue.Free;
SetLength(Face, 0);
Result := Res.Clone;
Res.Free;
end;
{*
Creates a line from P1 to P2.
Algorithm is based on Bresenham's line algorithm.
@note, it draws the line to a 2D Integer Matrix. Used internally.
*}
procedure DrawMatrixLine(var Mat:T2DIntArray; P1, P2: TPoint; Val:Integer); Inline;
var
dx,dy,step,I: Integer;
rx,ry,x,y: Extended;
begin
Mat[P1.y][P1.x] := Val;
if (p1.x = p2.x) and (p2.y = p1.y) then
Exit;
dx := (P2.x - P1.x);
dy := (P2.y - P1.y);
if (Abs(dx) > Abs(dy)) then step := Abs(dx)
else step := Abs(dy);
rx := dx / step;
ry := dy / step;
x := P1.x;
y := P1.y;
for I:=1 to step do
begin
x := x + rx;
y := y + ry;
Mat[Round(y)][Round(x)] := Val;
end;
end;
end.
|
unit save_lit_dialog;
interface
uses Messages, Windows, SysUtils, Classes, Controls, StdCtrls, Graphics,
ExtCtrls, Buttons, Dialogs;
type
TOpenPictureDialog = class(TSaveDialog)
private
SkipImages:TCheckBox;
TOCDepthEdit:TEdit;
FChecksPanel: TPanel;
TocDepVar:Integer;
function GetSkipImages:boolean;
protected
procedure DoClose; override;
procedure DoShow; override;
Procedure TOCDepthChange(Sender: TObject);
public
property DoSkipImages:boolean read GetSkipImages;
property TocDepth:Integer read TocDepVar;
constructor Create(AOwner: TComponent); override;
function Execute: Boolean; override;
end;
const
RegistryKey='Software\Grib Soft\FB to LIT\1.0';
implementation
uses Consts, Math, Forms, CommDlg, Dlgs,Registry;
{$R MyExtdlg.res}
function TOpenPictureDialog.GetSkipImages;
Begin
result:= SkipImages.checked;
end;
Procedure TOpenPictureDialog.TOCDepthChange;
Begin
try
StrToInt(TOCDepthEdit.Text);
except
TOCDepthEdit.Text:='2';
end;
TocDepVar:=StrToInt(TOCDepthEdit.Text)
end;
constructor TOpenPictureDialog.Create(AOwner: TComponent);
Var
Reg:TRegistry;
begin
inherited Create(AOwner);
Options:=[ofOverwritePrompt,ofEnableSizing];
FChecksPanel:=TPanel.Create(Self);
with FChecksPanel do
Begin
Name := 'PicturePanel';
Caption := '';
SetBounds(10, 150, 200, 200);
BevelOuter := bvNone;
BorderWidth := 6;
TabOrder := 1;
SkipImages:=TCheckBox.Create(Self);
With SkipImages do Begin
Name := 'SkipImages';
Caption := 'No images';
Left:=126;
Top:=3;
TabOrder := 1;
Width:=94;
Parent:=FChecksPanel;
end;
TOCDepthEdit:=TEdit.Create(Self);
With TOCDepthEdit do Begin
Name := 'TocEdit';
Left:=355;
Top:=0;
TabOrder := 2;
Width:=30;
Text:='2';
TocDepVar:=2;
Parent:=FChecksPanel;
TOCDepthEdit.OnChange:=TOCDepthChange;
end;
with TLabel.Create(Self)do
Begin
Name := 'TocDepthL';
Caption := 'TOC depth';
Left:=280;
Top:=3;
Width:=120;
Parent:=FChecksPanel;
FocusControl:=TOCDepthEdit;
end;
end;
Reg:=TRegistry.Create(KEY_READ);
Try
Try
if Reg.OpenKeyReadOnly(RegistryKey) then
Begin
SkipImages.Checked:=Reg.ReadBool('Skip images');
TocDepVar:=Reg.ReadInteger('TOC deepness');
TOCDepthEdit.Text:=IntToStr(TocDepVar);
end;
Finally
Reg.Free;
end;
Except
end;
Filter:='LIT books (*.lit)|*.lit|All files (*.*)|*.*';
Title:='FB2 to lit v0.14 by GribUser';
DefaultExt:='lit';
end;
procedure TOpenPictureDialog.DoShow;
var
PreviewRect, StaticRect: TRect;
begin
GetClientRect(Handle, PreviewRect);
StaticRect := GetStaticRect;
{ Move preview area to right of static area }
PreviewRect.Top:= StaticRect.Top + (StaticRect.Bottom - StaticRect.Top);
Inc(PreviewRect.Left, 10);
FChecksPanel.BoundsRect := PreviewRect;
FChecksPanel.ParentWindow := Handle;
inherited DoShow;
end;
procedure TOpenPictureDialog.DoClose;
begin
inherited DoClose;
{ Hide any hint windows left behind }
Application.HideHint;
end;
function TOpenPictureDialog.Execute;
Var
Reg:TRegistry;
begin
Template := 'DLGTEMPLATE2';
Options:=[ofOverwritePrompt,ofEnableSizing];
Result := inherited Execute;
if Result then
Begin
Reg:=TRegistry.Create(KEY_ALL_ACCESS);
Try
if Reg.OpenKey(RegistryKey,True) then
Begin
Reg.WriteBool('Skip images',SkipImages.Checked);
Reg.WriteInteger('TOC deepness',TocDepVar);
end;
Finally
Reg.Free;
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2017 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Net.HttpClientComponent;
interface
{$IFDEF MSWINDOWS}
{$HPPEMIT '#pragma comment(lib, "winhttp")'}
{$HPPEMIT '#pragma comment(lib, "crypt32")'}
{$ENDIF}
{$SCOPEDENUMS ON}
uses
System.Sysutils, System.Classes, System.Generics.Collections, System.Types,
System.Net.URLClient, System.Net.HttpClient, System.Net.Mime;
type
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
/// <summary> Request completion Event signature</summary>
/// <param name="Sender"> HTTPClientComponent that invoked the Event</param>
/// <param name="AResponse">Response generated by the request</param>
TRequestCompletedEvent = procedure(const Sender: TObject; const AResponse: IHTTPResponse) of object;
/// <summary> Request error Event signature</summary>
/// <param name="Sender"> HTTPClientComponent that invoked the Event</param>
/// <param name="AError">Error generated by the request</param>
TRequestErrorEvent = procedure(const Sender: TObject; const AError: string) of object;
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
/// <summary>Component to Manage an HTTPClient</summary>
TNetHTTPClient = class(TComponent)
private
FHttpClient: THTTPClient;
FOnRequestCompleted: TRequestCompletedEvent;
FOnRequestError: TRequestErrorEvent;
FOnReceiveData: TReceiveDataEvent;
FAsynchronous: Boolean;
procedure DoOnRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
procedure DoOnRequestError(const Sender: TObject; const AError: string);
procedure DoOnReceiveData(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
procedure DoOnAsyncRequestCompleted(const AAsyncResult: IAsyncResult);
function GetMaxRedirects: Integer;
procedure SetMaxRedirects(const Value: Integer);
procedure SetAuthEvent(const Value: TCredentialsStorage.TCredentialAuthevent);
procedure SetOnNeedClientCertificate(const Value: TNeedClientCertificateEvent);
procedure SetOnValidateServerCertificate(const Value: TValidateCertificateEvent);
function GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
function GetOnNeedClientCertificate: TNeedClientCertificateEvent;
function GetOnValidateServerCertificate: TValidateCertificateEvent;
function GetProxySettings: TProxySettings;
procedure SetProxySettings(const Value: TProxySettings);
function GetAllowCookies: Boolean;
procedure SetAllowCookies(const Value: Boolean);
function GetCookieManager: TCookieManager;
procedure SetCookieManager(const Value: TCookieManager);
function GetHandleRedirects: Boolean;
procedure SetHandleRedirects(const Value: Boolean);
function GetCustomHeaderValue(const AName: string): string;
procedure SetCustomHeaderValue(const AName, Value: string);
function GetAccept: string;
function GetAcceptCharSet: string;
function GetAcceptEncoding: string;
function GetAcceptLanguage: string;
function GetContentType: string;
procedure SetAccept(const Value: string);
procedure SetAcceptCharSet(const Value: string);
procedure SetAcceptEncoding(const Value: string);
procedure SetAcceptLanguage(const Value: string);
procedure SetContentType(const Value: string);
function GetCredentialsStorage: TCredentialsStorage;
procedure SetCredentialsStorage(const Value: TCredentialsStorage);
function GetUserAgent: string;
procedure SetUserAgent(const Value: string);
function GetConnectionTimeout: Integer;
function GetResponseTimeout: Integer;
procedure SetConnectionTimeout(const Value: Integer);
procedure SetResponseTimeout(const Value: Integer);
public
/// <summary> Initializes the HTTPComponent </summary>
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// ------------------------------------------- //
// Standard HTTP Methods
// ------------------------------------------- //
/// <summary>Send 'DELETE' command to url</summary>
function Delete(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'OPTIONS' command to url</summary>
function Options(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'GET' command to url</summary>
function Get(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'TRACE' command to url</summary>
function Trace(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'HEAD' command to url</summary>
function Head(const AURL: string; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'GET' command to url adding Range header</summary>
/// <remarks>It's used for resume downloads</remarks>
function GetRange(const AURL: string; AStart: Int64; AnEnd: Int64 = -1; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Post a raw file without multipart info</summary>
function Post(const AURL: string; const ASourceFile: string; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post TStrings values adding multipart info</summary>
function Post(const AURL: string; const ASource: TStrings; const AResponseContent: TStream = nil;
const AEncoding: TEncoding = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post a stream without multipart info</summary>
function Post(const AURL: string; const ASource: TStream; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post a multipart form data object</summary>
function Post(const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Send 'PUT' command to url</summary>
function Put(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
// Non standard command procedures ...
/// <summary>Send 'MERGE' command to url</summary>
function Merge(const AURL: string; const ASource: TStream; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send a special 'MERGE' command to url. Command based on a 'PUT' + 'x-method-override' </summary>
function MergeAlternative(const AURL: string; const ASource: TStream;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'PATCH' command to url</summary>
function Patch(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Send a special 'PATCH' command to url. Command based on a 'PUT' + 'x-method-override' </summary>
function PatchAlternative(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>You have to use this function to Execute a given Request</summary>
/// <param name="ARequest">The request that is going to be Executed</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interfaced object and
/// It's released automatically.</returns>
function Execute(const ARequest: IHTTPRequest; const AContentStream: TStream = nil): IHTTPResponse; overload;
/// <summary>You have to use this function to Execute a Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURI">The URI that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additions headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function Execute(const ARequestMethod: string; const AURI: TURI; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>You have to use this function to Execute a given Request</summary>
/// <remarks></remarks>
/// <param name="ARequestMethod">The request method that is going to be Executed</param>
/// <param name="AURIStr">The URI string that contains the information for the request that is going to be Executed</param>
/// <param name="ASourceStream">The stream to provide the request data.</param>
/// <param name="AContentStream">The stream to store the response data. If provided the user is responsible
/// of releasing it. If not provided will be created internally and released when not needed.</param>
/// <param name="AHeaders">Additions headers to be passed to the request that is going to be Executed</param>
/// <returns>The platform dependant response object associated to the given request. It's an Interface and It's
/// released automatically.</returns>
function Execute(const ARequestMethod: string; const AURIStr: string; const ASourceStream: TStream = nil;
const AContentStream: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload; inline;
/// <summary> Cookie manager object to be used by the client.</summary>
property CookieManager: TCookieManager read GetCookieManager write SetCookieManager;
/// <summary> CustomHeaders to be used by the client.</summary>
property CustomHeaders[const AName: string]: string read GetCustomHeaderValue write SetCustomHeaderValue;
/// <summary> Credentials Storage to be used by the client</summary>
property CredentialsStorage: TCredentialsStorage read GetCredentialsStorage write SetCredentialsStorage;
/// <summary> Proxy Settings to be used by the client.</summary>
property ProxySettings: TProxySettings read GetProxySettings write SetProxySettings;
published
/// <summary>Property to indicate if the requests are going to be Synchronous or Asynchronous</summary>
property Asynchronous: Boolean read FAsynchronous write FAsynchronous;
/// <summary> Property to set the ConnectionTimeout</summary>
property ConnectionTimeout: Integer read GetConnectionTimeout write SetConnectionTimeout;
/// <summary> Property to set the ResponseTimeout</summary>
property ResponseTimeout: Integer read GetResponseTimeout write SetResponseTimeout;
/// <summary> Cookies policy to be used by the client.</summary>
/// <remarks>If false the cookies from server will not be accepted,
/// but the cookies in the cookie manager will be sent.</remarks>
property AllowCookies: Boolean read GetAllowCookies write SetAllowCookies;
/// <summary> Redirection policy to be used by the client.</summary>
property HandleRedirects: Boolean read GetHandleRedirects write SetHandleRedirects;
/// <summary> Maximum number of redirects</summary>
property MaxRedirects: Integer read GetMaxRedirects write SetMaxRedirects default 5;
/// <summary>Property to manage the 'Accept' header</summary>
property Accept: string read GetAccept write SetAccept;
/// <summary>Property to manage the 'Accept-CharSet' header</summary>
property AcceptCharSet: string read GetAcceptCharSet write SetAcceptCharSet;
/// <summary>Property to manage the 'Accept-Encoding' header</summary>
property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding;
/// <summary>Property to manage the 'Accept-Language' header</summary>
property AcceptLanguage: string read GetAcceptLanguage write SetAcceptLanguage;
/// <summary>Property to manage the 'Content-Type' header</summary>
property ContentType: string read GetContentType write SetContentType;
/// <summary> Property to set the UserAgent sent with the request </summary>
property UserAgent: string read GetUserAgent write SetUserAgent;
/// <summary> Event fired when a ClientCertificate is needed</summary>
property OnNeedClientCertificate: TNeedClientCertificateEvent read GetOnNeedClientCertificate write SetOnNeedClientCertificate;
/// <summary> Event fired when checking the validity of a Server Certificate</summary>
property OnValidateServerCertificate: TValidateCertificateEvent read GetOnValidateServerCertificate write SetOnValidateServerCertificate;
/// <summary> UserName needed to be authenticated to the proxy</summary>
property OnAuthEvent: TCredentialsStorage.TCredentialAuthevent read GetAuthEvent write SetAuthEvent;
/// <summary> Event fired when a request finishes</summary>
property OnRequestCompleted: TRequestCompletedEvent read FOnRequestCompleted write FOnRequestCompleted;
/// <summary> Event fired when a request has an error</summary>
property OnRequestError: TRequestErrorEvent read FOnRequestError write FOnRequestError;
/// <summary>Property to manage the ReceiveData Event</summary>
property OnReceiveData: TReceiveDataEvent read FOnReceiveData write FOnReceiveData;
end;
TNetHTTPClientHelper = class helper for TNetHTTPClient
private
function GetRedirectsWithGET: THTTPRedirectsWithGET;
function GetSecureProtocols: THTTPSecureProtocols;
procedure SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
procedure SetSecureProtocols(const AValue: THTTPSecureProtocols);
public
property RedirectsWithGET: THTTPRedirectsWithGET read GetRedirectsWithGET write SetRedirectsWithGET default CHTTPDefRedirectsWithGET;
property SecureProtocols: THTTPSecureProtocols read GetSecureProtocols write SetSecureProtocols default CHTTPDefSecureProtocols;
end;
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
/// <summary>Component to handle HTTP Requests</summary>
TNetHTTPRequest = class(TComponent)
private
FClient: TNetHTTPClient;
FContentStream: TStream;
FSourceStream: TStream;
FURL: string;
FMethodString: string;
FHttpRequest: IHTTPRequest;
FHttpResponse: IHTTPResponse;
FOnNeedClientCertificate: TNeedClientCertificateEvent;
FOnValidateServerCertificate: TValidateCertificateEvent;
FOnRequestCompleted: TRequestCompletedEvent;
FOnRequestError: TRequestErrorEvent;
FOnReceiveData: TReceiveDataEvent;
FCustomHeaders: TNetHeaders;
FAsynchronous: Boolean;
FConnectionTimeout: Integer;
FResponseTimeout: Integer;
procedure DoOnRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
procedure DoOnRequestError(const Sender: TObject; const AError: string);
procedure DoOnReceiveData(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
procedure DoOnAsyncRequestCompleted(const AAsyncResult: IAsyncResult);
function GetMethodString: string;
procedure SetMethodString(const Value: string);
function GetURL: string;
procedure SetURL(const Value: string);
function GetClient: TNetHTTPClient;
procedure SetClient(const Value: TNetHTTPClient);
procedure SetOnNeedClientCertificate(const Value: TNeedClientCertificateEvent);
procedure SetOnValidateServerCertificate(const Value: TValidateCertificateEvent);
function GetOnReceiveData: TReceiveDataEvent;
procedure SetOnReceiveData(const Value: TReceiveDataEvent);
function GetRequest(const AMethod: string; const AURL: string; const ASourceStream: TStream;
AOwnsSourceStream: Boolean = False): IHTTPRequest;
function GetAccept: string;
function GetAcceptCharSet: string;
function GetAcceptEncoding: string;
function GetAcceptLanguage: string;
procedure SetAccept(const Value: string);
procedure SetAcceptCharSet(const Value: string);
procedure SetAcceptEncoding(const Value: string);
procedure SetAcceptLanguage(const Value: string);
function GetCustomHeaderValue(const AName: string): string;
procedure SetCustomHeaderValue(const AName, Value: string);
protected
/// <summary> Notification method to process component adding or removal from a form/datamodule</summary>
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
/// <summary>You have to use this function to Execute the internal Request</summary>
function DoExecute(const ARequest: IHTTPRequest; const AResponseContent: TStream; const AHeaders: TNetHeaders;
AOwnsSourceStream: Boolean = False): IHTTPResponse;
public
constructor Create(AOwner: TComponent); override;
// ------------------------------------------- //
// Standard HTTP Methods
// ------------------------------------------- //
/// <summary>Send 'DELETE' command to url</summary>
function Delete(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'OPTIONS' command to url</summary>
function Options(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'GET' command to url</summary>
function Get(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'TRACE' command to url</summary>
function Trace(const AURL: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'HEAD' command to url</summary>
function Head(const AURL: string; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'GET' command to url adding Range header</summary>
/// <remarks>It's used for resume downloads</remarks>
function GetRange(const AURL: string; AStart: Int64; AnEnd: Int64 = -1; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Post a raw file without multipart info</summary>
function Post(const AURL: string; const ASourceFile: string; AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post TStrings values adding multipart info</summary>
function Post(const AURL: string; const ASource: TStrings; const AResponseContent: TStream = nil;
const AEncoding: TEncoding = nil; const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post a stream without multipart info</summary>
function Post(const AURL: string; const ASource: TStream; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Post a multipart form data object</summary>
function Post(const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse; overload;
/// <summary>Send 'PUT' command to url</summary>
function Put(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
// Non standard command procedures ...
/// <summary>Send 'MERGE' command to url</summary>
function Merge(const AURL: string; const ASource: TStream; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'MERGE' command to url</summary>
function MergeAlternative(const AURL: string; const ASource: TStream; const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'PATCH' command to url</summary>
function Patch(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>Send 'PATCH' command to url</summary>
function PatchAlternative(const AURL: string; const ASource: TStream = nil; const AResponseContent: TStream = nil;
const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary>You have to use this function to Execute the internal Request</summary>
function Execute(const AHeaders: TNetHeaders = nil): IHTTPResponse;
/// <summary> CustomHeaders to be used by the client.</summary>
property CustomHeaders[const AName: string]: string read GetCustomHeaderValue write SetCustomHeaderValue;
/// <summary> Content stream associated with the request component</summary>
property ContentStream: TStream read FContentStream write FContentStream;
/// <summary> Source stream associated with the request component</summary>
property SourceStream: TStream read FSourceStream write FSourceStream;
published
/// <summary>Property to indicate if the requests are going to be Synchronous or Asynchronous</summary>
property Asynchronous: Boolean read FAsynchronous write FAsynchronous;
/// <summary> Property to set/get the ConnectionTimeout. Value is in milliseconds</summary>
property ConnectionTimeout: Integer read FConnectionTimeout write FConnectionTimeout;
/// <summary> Property to set/get the ResponseTimeout. Value is in milliseconds</summary>
property ResponseTimeout: Integer read FResponseTimeout write FResponseTimeout;
/// <summary>Property to manage the 'Accept' header</summary>
property Accept: string read GetAccept write SetAccept;
/// <summary>Property to manage the 'Accept-CharSet' header</summary>
property AcceptCharSet: string read GetAcceptCharSet write SetAcceptCharSet;
/// <summary>Property to manage the 'Accept-Encoding' header</summary>
property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding;
/// <summary>Property to manage the 'Accept-Language' header</summary>
property AcceptLanguage: string read GetAcceptLanguage write SetAcceptLanguage;
/// <summary> Property to access the MethodString from the request</summary>
property MethodString: string read GetMethodString write SetMethodString;
/// <summary> URL to be accessed</summary>
property URL: string read GetURL write SetURL;
/// <summary> Client component associated with the request component</summary>
property Client: TNetHTTPClient read GetClient write SetClient;
/// <summary> Event fired when a ClientCertificate is needed</summary>
property OnNeedClientCertificate: TNeedClientCertificateEvent read FOnNeedClientCertificate write SetOnNeedClientCertificate;
/// <summary> Event fired when checking the validity of a Server Certificate</summary>
property OnValidateServerCertificate: TValidateCertificateEvent read FOnValidateServerCertificate write SetOnValidateServerCertificate;
/// <summary> Event fired when a request finishes</summary>
property OnRequestCompleted: TRequestCompletedEvent read FOnRequestCompleted write FOnRequestCompleted;
/// <summary> Event fired when a request has an error</summary>
property OnRequestError: TRequestErrorEvent read FOnRequestError write FOnRequestError;
/// <summary>Property to manage the ReceiveData Event</summary>
property OnReceiveData: TReceiveDataEvent read GetOnReceiveData write SetOnReceiveData;
end;
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
implementation
uses
System.NetEncoding,
System.NetConsts;
{ TNetHTTPClient }
constructor TNetHTTPClient.Create(AOwner: TComponent);
begin
inherited;
FHttpClient := THTTPClient.Create;
FHttpClient.OnReceiveData := DoOnReceiveData;
end;
destructor TNetHTTPClient.Destroy;
begin
FHttpClient.Free;
inherited;
end;
function TNetHTTPClient.Delete(const AURL: string; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginDelete(DoOnAsyncRequestCompleted, AURL, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Delete(AURL, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
procedure TNetHTTPClient.DoOnAsyncRequestCompleted(const AAsyncResult: IAsyncResult);
begin
try
DoOnRequestCompleted(Self, THTTPClient.EndAsyncHTTP(AAsyncResult));
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
procedure TNetHTTPClient.DoOnReceiveData(const Sender: TObject; AContentLength, AReadCount: Int64; var Abort: Boolean);
var
LAbort: Boolean;
begin
if Assigned(FOnReceiveData) then
begin
LAbort := Abort;
TThread.Synchronize(nil, procedure
begin
FOnReceiveData(Sender, AContentLength, AReadCount, LAbort);
end);
Abort := LAbort;
end;
end;
procedure TNetHTTPClient.DoOnRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
begin
if Assigned(FOnRequestCompleted) then
TThread.Synchronize(nil, procedure
begin
FOnRequestCompleted(Sender, AResponse);
end);
end;
procedure TNetHTTPClient.DoOnRequestError(const Sender: TObject; const AError: string);
begin
if Assigned(FOnRequestError) then
TThread.Synchronize(nil, procedure
begin
FOnRequestError(Sender, AError);
end)
else
raise ENetHTTPClientException.Create(AError);
end;
function TNetHTTPClient.Execute(const ARequestMethod: string; const AURI: TURI; const ASourceStream,
AContentStream: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := IHTTPResponse(FHttpClient.BeginExecute(DoOnAsyncRequestCompleted, ARequestMethod, AURI, ASourceStream,
AContentStream, AHeaders))
else
begin
Result := IHTTPResponse(FHttpClient.Execute(ARequestMethod, AURI, ASourceStream, AContentStream, AHeaders));
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Execute(const ARequestMethod, AURIStr: string; const ASourceStream, AContentStream: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
Result := Execute(ARequestMethod, TURI.Create(AURIStr), ASourceStream, AContentStream, AHeaders);
end;
function TNetHTTPClient.Execute(const ARequest: IHTTPRequest; const AContentStream: TStream): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginExecute(DoOnAsyncRequestCompleted, ARequest, AContentStream) as IHTTPResponse
else
begin
Result := FHttpClient.Execute(ARequest, AContentStream);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Get(const AURL: string; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginGet(DoOnAsyncRequestCompleted, AURL, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Get(AURL, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.GetAccept: string;
begin
Result := FHttpClient.Accept;
end;
function TNetHTTPClient.GetAcceptCharSet: string;
begin
Result := FHttpClient.AcceptCharSet;
end;
function TNetHTTPClient.GetAcceptEncoding: string;
begin
Result := FHttpClient.AcceptEncoding;
end;
function TNetHTTPClient.GetAcceptLanguage: string;
begin
Result := FHttpClient.AcceptLanguage;
end;
function TNetHTTPClient.GetAllowCookies: Boolean;
begin
Result := FHttpClient.AllowCookies;
end;
function TNetHTTPClient.GetAuthEvent: TCredentialsStorage.TCredentialAuthevent;
begin
Result := FHttpClient.AuthEvent;
end;
function TNetHTTPClient.GetConnectionTimeout: Integer;
begin
Result := FHttpClient.ConnectionTimeout;
end;
function TNetHTTPClient.GetContentType: string;
begin
Result := FHttpClient.ContentType;
end;
function TNetHTTPClient.GetCookieManager: TCookieManager;
begin
Result := FHttpClient.CookieManager;
end;
function TNetHTTPClient.GetCustomHeaderValue(const AName: string): string;
begin
Result := FHttpClient.CustomHeaders[AName];
end;
function TNetHTTPClient.GetHandleRedirects: Boolean;
begin
Result := FHttpClient.HandleRedirects;
end;
function TNetHTTPClient.GetCredentialsStorage: TCredentialsStorage;
begin
Result := FHttpClient.CredentialsStorage;
end;
function TNetHTTPClient.GetMaxRedirects: Integer;
begin
Result := FHttpClient.MaxRedirects;
end;
function TNetHTTPClient.GetOnNeedClientCertificate: TNeedClientCertificateEvent;
begin
Result := FHttpClient.OnNeedClientCertificate;
end;
function TNetHTTPClient.GetOnValidateServerCertificate: TValidateCertificateEvent;
begin
Result := FHttpClient.OnValidateServerCertificate;
end;
function TNetHTTPClient.GetProxySettings: TProxySettings;
begin
Result := FHttpClient.ProxySettings;
end;
function TNetHTTPClient.GetRange(const AURL: string; AStart, AnEnd: Int64; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginGetRange(DoOnAsyncRequestCompleted, AURL, AStart, AnEnd, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.GetRange(AURL, AStart, AnEnd, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.GetResponseTimeout: Integer;
begin
Result := FHttpClient.ResponseTimeout;
end;
function TNetHTTPClient.GetUserAgent: string;
begin
Result := FHttpClient.UserAgent;
end;
function TNetHTTPClient.Head(const AURL: string; const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginHead(DoOnAsyncRequestCompleted, AURL, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Head(AURL, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Merge(const AURL: string; const ASource: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginMerge(DoOnAsyncRequestCompleted, AURL, ASource, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Merge(AURL, ASource, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.MergeAlternative(const AURL: string; const ASource: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginMergeAlternative(DoOnAsyncRequestCompleted, AURL, ASource, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.MergeAlternative(AURL, ASource, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Options(const AURL: string; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginOptions(DoOnAsyncRequestCompleted, AURL, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Options(AURL, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Patch(const AURL: string; const ASource, AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPatch(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Patch(AURL, ASource, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.PatchAlternative(const AURL: string; const ASource, AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPatchAlternative(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.PatchAlternative(AURL, ASource, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Post(const AURL: string; const ASource: TStrings; const AResponseContent: TStream;
const AEncoding: TEncoding; const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPost(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AEncoding, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Post(AURL, ASource, AResponseContent, AEncoding, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Post(const AURL: string; const ASource, AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPost(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Post(AURL, ASource, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Post(const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPost(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Post(AURL, ASource, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Post(const AURL, ASourceFile: string; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPost(DoOnAsyncRequestCompleted, AURL, ASourceFile, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Post(AURL, ASourceFile, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
function TNetHTTPClient.Put(const AURL: string; const ASource, AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginPut(DoOnAsyncRequestCompleted, AURL, ASource, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Put(AURL, ASource, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
procedure TNetHTTPClient.SetAccept(const Value: string);
begin
FHttpClient.Accept := Value;
end;
procedure TNetHTTPClient.SetAcceptCharSet(const Value: string);
begin
FHttpClient.AcceptCharSet := Value;
end;
procedure TNetHTTPClient.SetAcceptEncoding(const Value: string);
begin
FHttpClient.AcceptEncoding := Value;
end;
procedure TNetHTTPClient.SetAcceptLanguage(const Value: string);
begin
FHttpClient.AcceptLanguage := Value;
end;
procedure TNetHTTPClient.SetAllowCookies(const Value: Boolean);
begin
FHttpClient.AllowCookies := Value;
end;
procedure TNetHTTPClient.SetAuthEvent(const Value: TCredentialsStorage.TCredentialAuthevent);
begin
FHttpClient.AuthEvent := Value;
end;
procedure TNetHTTPClient.SetConnectionTimeout(const Value: Integer);
begin
FHttpClient.ConnectionTimeout := Value;
end;
procedure TNetHTTPClient.SetContentType(const Value: string);
begin
FHttpClient.ContentType := Value;
end;
procedure TNetHTTPClient.SetCookieManager(const Value: TCookieManager);
begin
FHttpClient.CookieManager := Value;
end;
procedure TNetHTTPClient.SetCredentialsStorage(const Value: TCredentialsStorage);
begin
FHttpClient.CredentialsStorage := Value;
end;
procedure TNetHTTPClient.SetCustomHeaderValue(const AName, Value: string);
begin
FHttpClient.CustomHeaders[AName] := Value;
end;
procedure TNetHTTPClient.SetHandleRedirects(const Value: Boolean);
begin
FHttpClient.HandleRedirects := Value;
end;
procedure TNetHTTPClient.SetMaxRedirects(const Value: Integer);
begin
FHttpClient.MaxRedirects := Value;
end;
procedure TNetHTTPClient.SetOnNeedClientCertificate(const Value: TNeedClientCertificateEvent);
begin
FHttpClient.OnNeedClientCertificate := Value;
end;
procedure TNetHTTPClient.SetOnValidateServerCertificate(const Value: TValidateCertificateEvent);
begin
FHttpClient.OnValidateServerCertificate := Value;
end;
procedure TNetHTTPClient.SetProxySettings(const Value: TProxySettings);
begin
FHttpClient.ProxySettings := Value;
end;
procedure TNetHTTPClient.SetResponseTimeout(const Value: Integer);
begin
FHttpClient.ResponseTimeout := Value;
end;
procedure TNetHTTPClient.SetUserAgent(const Value: string);
begin
FHttpClient.UserAgent := Value;
end;
function TNetHTTPClient.Trace(const AURL: string; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
begin
try
if FAsynchronous then
Result := FHttpClient.BeginTrace(DoOnAsyncRequestCompleted, AURL, AResponseContent, AHeaders) as IHTTPResponse
else
begin
Result := FHttpClient.Trace(AURL, AResponseContent, AHeaders);
DoOnRequestCompleted(Self, Result);
end;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
{ TNetHTTPClientHelper }
function TNetHTTPClientHelper.GetRedirectsWithGET: THTTPRedirectsWithGET;
begin
Result := FHttpClient.RedirectsWithGET;
end;
function TNetHTTPClientHelper.GetSecureProtocols: THTTPSecureProtocols;
begin
Result := FHttpClient.SecureProtocols;
end;
procedure TNetHTTPClientHelper.SetRedirectsWithGET(const AValue: THTTPRedirectsWithGET);
begin
FHttpClient.RedirectsWithGET := AValue;
end;
procedure TNetHTTPClientHelper.SetSecureProtocols(const AValue: THTTPSecureProtocols);
begin
FHttpClient.SecureProtocols := AValue;
end;
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------------------------------ //
{ TNetHTTPRequest }
constructor TNetHTTPRequest.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TNetHTTPRequest.DoOnAsyncRequestCompleted(const AAsyncResult: IAsyncResult);
begin
try
FHttpResponse := THTTPClient.EndAsyncHTTP(AAsyncResult);
DoOnRequestCompleted(Self, FHttpResponse);
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
procedure TNetHTTPRequest.DoOnReceiveData(const Sender: TObject; AContentLength, AReadCount: Int64; var Abort: Boolean);
var
LAbort: Boolean;
begin
if Assigned(FOnReceiveData) then
begin
LAbort := Abort;
TThread.Synchronize(nil, procedure
begin
FOnReceiveData(Sender, AContentLength, AReadCount, LAbort);
end);
Abort := LAbort;
end
else
FClient.DoOnReceiveData(Self, AContentLength, AReadCount, Abort);
end;
procedure TNetHTTPRequest.DoOnRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
begin
if Assigned(FOnRequestCompleted) then
TThread.Synchronize(nil, procedure
begin
FOnRequestCompleted(Sender, AResponse);
end)
else
FClient.DoOnRequestCompleted(Self, AResponse);
end;
procedure TNetHTTPRequest.DoOnRequestError(const Sender: TObject; const AError: string);
begin
if Assigned(FOnRequestError) then
TThread.Synchronize(nil, procedure
begin
FOnRequestError(Sender, AError);
end)
else
FClient.DoOnRequestError(Self, AError);
end;
function TNetHTTPRequest.Delete(const AURL: string; const AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodDelete, AURL, nil);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.Execute(const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(FMethodString, FURL, nil);
Result := DoExecute(FHttpRequest, FContentStream, AHeaders);
end;
type
TDummyHTTPClient = class(THTTPClient);
function TNetHTTPRequest.DoExecute(const ARequest: IHTTPRequest; const AResponseContent: TStream;
const AHeaders: TNetHeaders; AOwnsSourceStream: Boolean): IHTTPResponse;
var
LHeaders: TNetHeaders;
begin
Result := nil;
FHttpResponse := nil;
if ARequest <> nil then
begin
try
LHeaders := FCustomHeaders + AHeaders;
if FAsynchronous then
begin
if AOwnsSourceStream then
Result := TDummyHTTPClient(FClient.FHttpClient).InternalExecuteAsync(nil, DoOnAsyncRequestCompleted, ARequest,
AResponseContent, LHeaders, AOwnsSourceStream) as IHTTPResponse
else
Result := FClient.FHttpClient.BeginExecute(DoOnAsyncRequestCompleted, ARequest, AResponseContent, LHeaders) as IHTTPResponse;
end
else
begin
Result := FClient.FHttpClient.Execute(ARequest, AResponseContent, LHeaders);
DoOnRequestCompleted(Self, Result);
end;
FHttpResponse := Result;
except
on E: Exception do
DoOnRequestError(Self, E.Message);
end;
end;
end;
function TNetHTTPRequest.Get(const AURL: string; const AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodGet, AURL, nil);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.GetAccept: string;
begin
Result := CustomHeaders[sAccept];
end;
function TNetHTTPRequest.GetAcceptCharSet: string;
begin
Result := CustomHeaders[sAcceptCharSet];
end;
function TNetHTTPRequest.GetAcceptEncoding: string;
begin
Result := CustomHeaders[sAcceptEncoding];
end;
function TNetHTTPRequest.GetAcceptLanguage: string;
begin
Result := CustomHeaders[sAcceptLanguage];
end;
function TNetHTTPRequest.GetClient: TNetHTTPClient;
begin
Result := FClient;
end;
function TNetHTTPRequest.GetCustomHeaderValue(const AName: string): string;
var
I, Max: Integer;
begin
Result := '';
I := 0;
Max := Length(FCustomHeaders);
while I < Max do
begin
if string.CompareText(FCustomHeaders[I].Name, AName) = 0 then
begin
Result := FCustomHeaders[I].Value;
Break;
end;
Inc(I);
end;
end;
function TNetHTTPRequest.GetMethodString: string;
begin
Result := FMethodString;
end;
function TNetHTTPRequest.GetOnReceiveData: TReceiveDataEvent;
begin
Result := FOnReceiveData;
end;
function TNetHTTPRequest.GetRange(const AURL: string; AStart, AnEnd: Int64; const AResponseContent: TStream;
const AHeaders: TNetHeaders): IHTTPResponse;
var
LHeaders: TNetHeaders;
LRange: string;
begin
LRange := 'bytes=';
if AStart > -1 then
LRange := LRange + AStart.ToString;
LRange := LRange + '-';
if AnEnd > -1 then
LRange := LRange + AnEnd.ToString;
LHeaders := AHeaders + [TNetHeader.Create('Range', LRange)]; // do not translate
Result := Get(AURL, AResponseContent, LHeaders);
end;
function TNetHTTPRequest.GetRequest(const AMethod, AURL: string; const ASourceStream: TStream; AOwnsSourceStream: Boolean): IHTTPRequest;
var
LRequest: THTTPRequest;
begin
if FClient = nil then
raise ENetHTTPRequestException.CreateRes(@SNetHttpComponentRequestClient);
try
Result := nil;
Result := FClient.FHttpClient.GetRequest(AMethod, AURL);
LRequest := Result as THTTPRequest;
LRequest.ConnectionTimeout := FConnectionTimeout;
LRequest.ResponseTimeout := FResponseTimeout;
Result.OnReceiveData := DoOnReceiveData;
if ASourceStream = nil then
Result.SourceStream := FSourceStream
else
Result.SourceStream := ASourceStream;
except
on E: Exception do
begin
{$IFNDEF AUTOREFCOUNT}
if AOwnsSourceStream then
ASourceStream.Free;
{$ENDIF AUTOREFCOUNT}
DoOnRequestError(Self, E.Message);
end;
end;
end;
function TNetHTTPRequest.GetURL: string;
begin
Result := FURL;
end;
function TNetHTTPRequest.Head(const AURL: string; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodHead, AURL, nil);
Result := DoExecute(FHttpRequest, nil, AHeaders);
end;
function TNetHTTPRequest.Merge(const AURL: string; const ASource: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodMerge, AURL, ASource);
Result := DoExecute(FHttpRequest, nil, AHeaders);
end;
function TNetHTTPRequest.MergeAlternative(const AURL: string; const ASource: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
var
LHeaders: TNetHeaders;
begin
FHttpRequest := GetRequest(sHTTPMethodPut, AURL, ASource);
LHeaders := [TNetHeader.Create(sXMethodOverride, sHTTPMethodPatch), TNetHeader.Create('PATCHTYPE', sHTTPMethodMerge)] + AHeaders; // Do not translate
Result := DoExecute(FHttpRequest, nil, LHeaders);
end;
procedure TNetHTTPRequest.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent = FClient) and (Operation = opRemove) then
SetClient(nil);
end;
function TNetHTTPRequest.Options(const AURL: string; const AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodOptions, AURL, nil);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.Patch(const AURL: string; const ASource, AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodPatch, AURL, ASource);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.PatchAlternative(const AURL: string; const ASource, AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
var
LHeaders: TNetHeaders;
begin
FHttpRequest := GetRequest(sHTTPMethodPut, AURL, ASource);
LHeaders := [TNetHeader.Create(sXMethodOverride, sHTTPMethodPatch)] + AHeaders;
Result := DoExecute(FHttpRequest, AResponseContent, LHeaders);
end;
function TNetHTTPRequest.Post(const AURL: string; const ASource: TStrings;
const AResponseContent: TStream; const AEncoding: TEncoding; const AHeaders: TNetHeaders): IHTTPResponse;
var
I, Pos: Integer;
LSourceStream: TStringStream;
LParams: string;
LHeaders: TNetHeaders;
LEncoding: TEncoding;
begin
LParams := '';
for I := 0 to ASource.Count - 1 do
begin
Pos := ASource[I].IndexOf('=');
if Pos > 0 then
LParams := LParams + TNetEncoding.URL.EncodeForm(ASource[I].Substring(0, Pos)) + '=' + TNetEncoding.URL.EncodeForm(ASource[I].Substring(Pos + 1)) + '&';
end;
if (LParams <> '') and (LParams[High(LParams)] = '&') then
LParams := LParams.Substring(0, LParams.Length - 1); // Remove last &
if AEncoding = nil then
LEncoding := TEncoding.UTF8
else
LEncoding := AEncoding;
LSourceStream := TStringStream.Create(LParams, LEncoding, False);
try
FHttpRequest := GetRequest(sHTTPMethodPost, AURL, LSourceStream, FAsynchronous);
LHeaders := [TNetHeader.Create(sContentType, 'application/x-www-form-urlencoded; charset=urf-8')] + AHeaders; // do not translate
Result := DoExecute(FHttpRequest, AResponseContent, LHeaders, FAsynchronous);
finally
if not FAsynchronous then
LSourceStream.Free;
end;
end;
function TNetHTTPRequest.Post(const AURL: string; const ASource, AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodPost, AURL, ASource);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.Post(const AURL: string; const ASource: TMultipartFormData;
const AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodPost, AURL, ASource.Stream);
if FHttpRequest <> nil then
begin
FHttpRequest.SourceStream.Position := 0;
FHttpRequest.AddHeader(sContentType, ASource.MimeTypeHeader);
end;
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
function TNetHTTPRequest.Post(const AURL, ASourceFile: string; AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
var
LSourceStream: TStream;
begin
LSourceStream := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite);
try
FHttpRequest := GetRequest(sHTTPMethodPost, AURL, LSourceStream, FAsynchronous);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders, FAsynchronous);
finally
if not FAsynchronous then
LSourceStream.Free;
end;
end;
function TNetHTTPRequest.Put(const AURL: string; const ASource, AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodPut, AURL, ASource);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
procedure TNetHTTPRequest.SetAccept(const Value: string);
begin
CustomHeaders[sAccept] := Value
end;
procedure TNetHTTPRequest.SetAcceptCharSet(const Value: string);
begin
CustomHeaders[sAcceptCharSet] := Value
end;
procedure TNetHTTPRequest.SetAcceptEncoding(const Value: string);
begin
CustomHeaders[sAcceptEncoding] := Value
end;
procedure TNetHTTPRequest.SetAcceptLanguage(const Value: string);
begin
CustomHeaders[sAcceptLanguage] := Value
end;
procedure TNetHTTPRequest.SetClient(const Value: TNetHTTPClient);
begin
FClient := Value;
if FClient <> nil then
begin
FConnectionTimeout := FClient.ConnectionTimeout;
FResponseTimeout := FClient.ResponseTimeout;
end;
end;
procedure TNetHTTPRequest.SetCustomHeaderValue(const AName, Value: string);
var
I, Max: Integer;
begin
I := 0;
Max := Length(FCustomHeaders);
while I < Max do
begin
if string.CompareText(FCustomHeaders[I].Name, AName) = 0 then
Break;
Inc(I);
end;
if I = Max then
begin
SetLength(FCustomHeaders, Max + 1);
FCustomHeaders[I].Name := AName;
end;
FCustomHeaders[I].Value := Value;
end;
procedure TNetHTTPRequest.SetMethodString(const Value: string);
begin
FMethodString := Value;
end;
procedure TNetHTTPRequest.SetOnNeedClientCertificate(const Value: TNeedClientCertificateEvent);
begin
FOnNeedClientCertificate := Value;
end;
procedure TNetHTTPRequest.SetOnReceiveData(const Value: TReceiveDataEvent);
begin
FOnReceiveData := Value;
end;
procedure TNetHTTPRequest.SetOnValidateServerCertificate(const Value: TValidateCertificateEvent);
begin
FOnValidateServerCertificate := Value;
end;
procedure TNetHTTPRequest.SetURL(const Value: string);
begin
FURL := Value;
end;
function TNetHTTPRequest.Trace(const AURL: string; const AResponseContent: TStream; const AHeaders: TNetHeaders): IHTTPResponse;
begin
FHttpRequest := GetRequest(sHTTPMethodTrace, AURL, nil);
Result := DoExecute(FHttpRequest, AResponseContent, AHeaders);
end;
end.
|
unit TextLoad_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Forms"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/Daily/Forms/TextLoad_Form.pas"
// Начат: 22.12.2009 16:32
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::Everest::TextLoad
//
// Форма для загрузки документа
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
vcmInterfaces,
evTextSource,
evEditor,
vcmUserControls,
l3StringIDEx,
PrimTextLoad_Form
{$If not defined(NoScripts)}
,
tfwScriptingInterfaces
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwInteger
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
kwBynameControlPush
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
TextLoad_ut_TextLoad_UserType,
evCustomTextSource,
evCustomEditor,
evLoadDocumentManager,
Classes {a},
l3InterfacedComponent {a},
vcmComponent {a},
vcmBaseEntities {a},
vcmEntities {a},
vcmExternalInterfaces {a},
vcmEntityForm {a}
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
const
{ TextLoadIDs }
fm_TextLoadForm : TvcmFormDescriptor = (rFormID : (rName : 'TextLoadForm'; rID : 0); rFactory : nil);
{ Идентификатор формы TTextLoadForm }
type
TextLoadFormDef = interface(IUnknown)
{* Идентификатор формы TextLoad }
['{0D52D59A-6EBD-46A6-AA44-2467ABBFDC5C}']
end;//TextLoadFormDef
TTextLoadForm = {final form} class(TvcmEntityFormRef, TextLoadFormDef)
{* Форма для загрузки документа }
Entities : TvcmEntities;
private
// private fields
f_Text : TevEditor;
{* Поле для свойства Text}
f_TextSource : TevTextSource;
{* Поле для свойства TextSource}
protected
procedure MakeControls; override;
protected
// realized methods
function pm_GetTextSource: TevCustomTextSource; override;
function pm_GetText: TevCustomEditor; override;
public
// public properties
property Text: TevEditor
read f_Text;
property TextSource: TevTextSource
read f_TextSource;
end;//TTextLoadForm
{$IfEnd} //nsTest AND not NoVCM
implementation
{$R *.DFM}
{$If defined(nsTest) AND not defined(NoVCM)}
uses
Controls,
Forms,
vcmStringIDExHelper
{$If not defined(NoScripts)}
,
tfwScriptEngine
{$IfEnd} //not NoScripts
,
l3MessageID
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
var
{ Локализуемые строки ut_TextLoadLocalConstants }
str_ut_TextLoadCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_TextLoadCaption'; rValue : 'Форма для загрузки документа');
{ Заголовок пользовательского типа "Форма для загрузки документа" }
type
Tkw_TextLoad_Control_Text = class(TtfwControlString)
{* Слово словаря для идентификатора контрола Text
----
*Пример использования*:
[code]
контрол::Text TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_Control_Text
// start class Tkw_TextLoad_Control_Text
{$If not defined(NoScripts)}
function Tkw_TextLoad_Control_Text.GetString: AnsiString;
{-}
begin
Result := 'Text';
end;//Tkw_TextLoad_Control_Text.GetString
{$IfEnd} //not NoScripts
type
Tkw_TextLoad_Control_Text_Push = class(TkwBynameControlPush)
{* Слово словаря для контрола Text
----
*Пример использования*:
[code]
контрол::Text:push pop:control:SetFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_Control_Text_Push
// start class Tkw_TextLoad_Control_Text_Push
{$If not defined(NoScripts)}
procedure Tkw_TextLoad_Control_Text_Push.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushString('Text');
inherited;
end;//Tkw_TextLoad_Control_Text_Push.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_TextLoad_Component_TextSource = class(TtfwControlString)
{* Слово словаря для идентификатора компонента TextSource
----
*Пример использования*:
[code]
компонент::TextSource TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_Component_TextSource
// start class Tkw_TextLoad_Component_TextSource
{$If not defined(NoScripts)}
function Tkw_TextLoad_Component_TextSource.GetString: AnsiString;
{-}
begin
Result := 'TextSource';
end;//Tkw_TextLoad_Component_TextSource.GetString
{$IfEnd} //not NoScripts
type
Tkw_Form_TextLoad = class(TtfwControlString)
{* Слово словаря для идентификатора формы TextLoad
----
*Пример использования*:
[code]
'aControl' форма::TextLoad TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_Form_TextLoad
// start class Tkw_Form_TextLoad
{$If not defined(NoScripts)}
function Tkw_Form_TextLoad.GetString: AnsiString;
{-}
begin
Result := 'TextLoadForm';
end;//Tkw_Form_TextLoad.GetString
{$IfEnd} //not NoScripts
type
Tkw_TextLoad_Text_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола Text формы TextLoad }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_Text_ControlInstance
// start class Tkw_TextLoad_Text_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_TextLoad_Text_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TTextLoadForm).Text);
end;//Tkw_TextLoad_Text_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_TextLoad_TextSource_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола TextSource формы TextLoad }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_TextSource_ControlInstance
// start class Tkw_TextLoad_TextSource_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_TextLoad_TextSource_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TTextLoadForm).TextSource);
end;//Tkw_TextLoad_TextSource_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
type
Tkw_TextLoad_LoadManager_ControlInstance = class(TtfwWord)
{* Слово словаря для доступа к экземпляру контрола LoadManager формы TextLoad }
protected
// realized methods
{$If not defined(NoScripts)}
procedure DoDoIt(const aCtx: TtfwContext); override;
{$IfEnd} //not NoScripts
end;//Tkw_TextLoad_LoadManager_ControlInstance
// start class Tkw_TextLoad_LoadManager_ControlInstance
{$If not defined(NoScripts)}
procedure Tkw_TextLoad_LoadManager_ControlInstance.DoDoIt(const aCtx: TtfwContext);
{-}
begin
aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TTextLoadForm).LoadManager);
end;//Tkw_TextLoad_LoadManager_ControlInstance.DoDoIt
{$IfEnd} //not NoScripts
function TTextLoadForm.pm_GetTextSource: TevCustomTextSource;
//#UC START# *4C9B21D20187_4B30C7E800EEget_var*
//#UC END# *4C9B21D20187_4B30C7E800EEget_var*
begin
//#UC START# *4C9B21D20187_4B30C7E800EEget_impl*
Result := Self.TextSource;
//#UC END# *4C9B21D20187_4B30C7E800EEget_impl*
end;//TTextLoadForm.pm_GetTextSource
function TTextLoadForm.pm_GetText: TevCustomEditor;
//#UC START# *4C9B21E400A4_4B30C7E800EEget_var*
//#UC END# *4C9B21E400A4_4B30C7E800EEget_var*
begin
//#UC START# *4C9B21E400A4_4B30C7E800EEget_impl*
Result := Self.Text;
//#UC END# *4C9B21E400A4_4B30C7E800EEget_impl*
end;//TTextLoadForm.pm_GetText
procedure TTextLoadForm.MakeControls;
begin
inherited;
f_Text := TevEditor.Create(Self);
f_Text.Name := 'Text';
f_Text.Parent := Self;
f_TextSource := TevTextSource.Create(Self);
f_TextSource.Name := 'TextSource';
with AddUsertype(ut_TextLoadName,
str_ut_TextLoadCaption,
str_ut_TextLoadCaption,
false,
-1,
-1,
'',
nil,
nil,
nil,
vcm_ccNone) do
begin
end;//with AddUsertype(ut_TextLoadName
end;
{$IfEnd} //nsTest AND not NoVCM
initialization
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_Control_Text
Tkw_TextLoad_Control_Text.Register('контрол::Text', TevEditor);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_Control_Text_Push
Tkw_TextLoad_Control_Text_Push.Register('контрол::Text:push');
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_Component_TextSource
Tkw_TextLoad_Component_TextSource.Register('компонент::TextSource', TevTextSource);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация фабрики формы TextLoad
fm_TextLoadForm.SetFactory(TTextLoadForm.Make);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_Form_TextLoad
Tkw_Form_TextLoad.Register('форма::TextLoad', TTextLoadForm);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_Text_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TTextLoadForm.Text', Tkw_TextLoad_Text_ControlInstance);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_TextSource_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TTextLoadForm.TextSource', Tkw_TextLoad_TextSource_ControlInstance);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_TextLoad_LoadManager_ControlInstance
TtfwScriptEngine.GlobalAddWord('.TTextLoadForm.LoadManager', Tkw_TextLoad_LoadManager_ControlInstance);
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// Инициализация str_ut_TextLoadCaption
str_ut_TextLoadCaption.Init;
{$IfEnd} //nsTest AND not NoVCM
end. |
unit BaseRuleData;
interface
const
cNodeDataSize = 64;
cArrayType_Double = 1;
cArrayType_Int64 = 2;
type
PArrayNodeHead = ^TArrayNodeHead;
TArrayNodeHead = packed record
Size : Byte;
Length : Byte;
NodeIndex : Byte;
Status : Byte;
PrevSibling : PArrayNodeHead;
NextSibling : PArrayNodeHead;
end;
PArrayDoubleNode = ^TArrayDoubleNode;
TArrayDoubleNode = packed record
Head : TArrayNodeHead;
Value : array[0..cNodeDataSize - 1] of double;
end;
PArrayInt64Node = ^TArrayInt64Node;
TArrayInt64Node = packed record
Head : TArrayNodeHead;
Value : array[0..cNodeDataSize - 1] of int64;
end;
PArrayNodeAccess = ^TArrayNodeAccess;
TArrayNodeAccess = packed record
Node : PArrayNodeHead;
NodeIndex : Byte;
ArrayIndex : integer;
end;
PArray = ^TArray;
TArray = packed record
Size : integer;
Length : integer;
NodeDataSize : Byte;
ArrayType : Byte;
MaxValueDouble : double;
MinValueDouble : double;
MaxValueInt64 : Int64;
MinValueInt64 : Int64;
DefaultAccess : TArrayNodeAccess;
FirstValueNode : PArrayNodeHead;
LastValueNode : PArrayNodeHead;
end;
function CheckOutArrayDouble(ADataLength: integer = 0): PArray;
function CheckOutArrayInt64(ADataLength: integer = 0): PArray;
procedure CheckInArray(var AArray: PArray);
procedure SetArrayLength(AArray: PArray; ALength: integer);
function GetArrayNode(AArray: PArray; AIndex: integer; ArrayNodeAccess: PArrayNodeAccess = nil): PArrayNodeHead;
procedure SetArrayDoubleValue(ArrayDouble: PArray; AIndex: integer; AValue: double);
function GetArrayDoubleValue(ArrayDouble: PArray; AIndex: integer): double;
//procedure SetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer; AValue: double);
//function GetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer): double;
procedure SetArrayInt64Value(ArrayInt64: PArray; AIndex: integer; AValue: Int64);
function GetArrayInt64Value(ArrayInt64: PArray; AIndex: integer): Int64;
//procedure SetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer; AValue: Int64);
//function GetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer): Int64;
implementation
function CheckOutArrayDouble(ADataLength: integer = 0): PArray;
begin
Result := System.New(PArray);
FillChar(Result^, SizeOf(TArray), 0);
Result.NodeDataSize := cNodeDataSize;
Result.ArrayType := cArrayType_Double;
if 0 < ADataLength then
SetArrayLength(Result, ADataLength);
end;
function CheckOutArrayInt64(ADataLength: integer = 0): PArray;
begin
Result := System.New(PArray);
FillChar(Result^, SizeOf(TArray), 0);
Result.NodeDataSize := cNodeDataSize;
Result.ArrayType := cArrayType_Int64;
if 0 < ADataLength then
SetArrayLength(Result, ADataLength);
end;
procedure CheckInArray(var AArray: PArray);
begin
if nil = AArray then
exit;
SetArrayLength(AArray, 0);
FreeMem(AArray);
AArray := nil;
end;
function CheckOutArrayNode(AArray: PArray): PArrayNodeHead;
begin
Result := nil;
if nil = AArray then
exit;
if cArrayType_Double = AArray.ArrayType then
begin
Result := PArrayNodeHead(System.New(PArrayDoubleNode));
FillChar(Result^, SizeOf(TArrayDoubleNode), 0);
end;
if cArrayType_Int64 = AArray.ArrayType then
begin
Result := PArrayNodeHead(System.New(PArrayInt64Node));
FillChar(Result^, SizeOf(TArrayInt64Node), 0);
end;
if nil = AArray.FirstValueNode then
AArray.FirstValueNode := Result;
if nil <> AArray.LastValueNode then
begin
Result.PrevSibling := AArray.LastValueNode;
AArray.LastValueNode.NextSibling := Result;
end;
AArray.LastValueNode := Result;
AArray.Size := AArray.Size + AArray.NodeDataSize;
end;
procedure CheckInArrayNode(AArray: PArray; var ANode: PArrayNodeHead);
begin
end;
procedure SetArrayLength(AArray: PArray; ALength: integer);
begin
if nil = AArray then
exit;
if AArray.Size < ALength then
begin
while AArray.Size < ALength do
begin
CheckOutArrayNode(AArray);
end;
AArray.Length := ALength;
end else
begin
if 0 = ALength then
begin
end else
begin
end;
end;
end;
function GetArrayNode(AArray: PArray; AIndex: integer; ArrayNodeAccess: PArrayNodeAccess = nil): PArrayNodeHead;
var
tmpNode: PArrayNodeHead;
tmpIndex: Integer;
begin
Result := nil;
tmpNode := AArray.FirstValueNode;
tmpIndex := AIndex;
while nil <> tmpNode do
begin
if tmpIndex < AArray.NodeDataSize then
begin
if 0 <= tmpIndex then
begin
Result := tmpNode;
//Result.NodeIndex := tmpIndex;
if nil <> ArrayNodeAccess then
begin
ArrayNodeAccess.Node := Result;
ArrayNodeAccess.ArrayIndex := AIndex;
ArrayNodeAccess.NodeIndex := Result.NodeIndex;
end;
end;
exit;
end;
tmpNode := tmpNode.NextSibling;
tmpIndex := tmpIndex - AArray.NodeDataSize;
end;
end;
function GetArrayDoubleValue(ArrayDouble: PArray; AIndex: integer): double;
var
tmpNode: PArrayNodeHead;
begin
Result := 0;
tmpNode := GetArrayNode(ArrayDouble, AIndex, @ArrayDouble.DefaultAccess);
if nil <> tmpNode then
Result := PArrayDoubleNode(tmpNode).value[tmpNode.NodeIndex];
end;
procedure SetArrayDoubleValue(ArrayDouble: PArray; AIndex: integer; AValue: double);
var
tmpNode: PArrayNodeHead;
begin
tmpNode := GetArrayNode(ArrayDouble, AIndex, @ArrayDouble.DefaultAccess);
if nil <> tmpNode then
PArrayDoubleNode(tmpNode).Value[tmpNode.NodeIndex] := AValue;
end;
function GetArrayInt64Value(ArrayInt64: PArray; AIndex: integer): Int64;
var
tmpNode: PArrayNodeHead;
begin
// Result := ArrayInt64.value[AIndex];
Result := 0;
tmpNode := GetArrayNode(ArrayInt64, AIndex, @ArrayInt64.DefaultAccess);
if nil <> tmpNode then
Result := PArrayInt64Node(tmpNode).value[tmpNode.NodeIndex];
end;
procedure SetArrayInt64Value(ArrayInt64: PArray; AIndex: integer; AValue: Int64);
var
tmpNode: PArrayNodeHead;
begin
// ArrayInt64.value[AIndex] := AValue;
tmpNode := GetArrayNode(ArrayInt64, AIndex, @ArrayInt64.DefaultAccess);
if nil <> tmpNode then
PArrayInt64Node(tmpNode).Value[tmpNode.NodeIndex] := AValue;
end;
function GetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer): double;
begin
Result := ArrayDoubleNode.value[ANodeIndex];
end;
procedure SetArrayDoubleNodeValue(ArrayDoubleNode: PArrayDoubleNode; ANodeIndex: integer; AValue: double);
begin
ArrayDoubleNode.value[ANodeIndex] := AValue;
end;
function GetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer): Int64;
begin
Result := ArrayInt64Node.value[ANodeIndex];
end;
procedure SetArrayInt64NodeValue(ArrayInt64Node: PArrayInt64Node; ANodeIndex: integer; AValue: Int64);
begin
ArrayInt64Node.value[ANodeIndex] := AValue;
end;
end.
|
unit GX_FavNewFolder;
interface
uses
Windows, Classes, Controls, Forms, StdCtrls, GX_BaseForm;
type
TfmFavNewFolder = class(TfmBaseForm)
gbxNewFolder: TGroupBox;
lblFolderName: TLabel;
edtFolderName: TEdit;
lblFolderType: TLabel;
cbxFolderType: TComboBox;
btnCancel: TButton;
btnOK: TButton;
procedure edtFolderNameChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbxFolderTypeDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cbxFolderTypeMeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
private
FFavoriteFilesForm: TForm;
public
property FavoriteFilesForm: TForm write FFavoriteFilesForm;
end;
implementation
{$R *.dfm}
uses
SysUtils, Graphics, GX_FavUtil, GX_FavFiles;
procedure TfmFavNewFolder.edtFolderNameChange(Sender: TObject);
begin
btnOK.Enabled := (Length(edtFolderName.Text) > 0);
end;
procedure TfmFavNewFolder.FormCreate(Sender: TObject);
var
i: TFolderType;
begin
for i := Low(TFolderType) to High(TFolderType) do
cbxFolderType.Items.AddObject(FolderNames[i], Pointer(i));
cbxFolderType.ItemIndex := 0;
end;
procedure TfmFavNewFolder.cbxFolderTypeDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
try
with cbxFolderType.Canvas do
begin
if odSelected in State then
Brush.Color := clHighlight
else
Brush.Color := clWindow;
FillRect(Rect);
(FFavoriteFilesForm as TfmFavFiles).ilFolders.Draw(cbxFolderType.Canvas,
Rect.Left+3, Rect.Top+1, Index*2);
TextOut(Rect.Left+22, Rect.Top+3, cbxFolderType.Items[Index]);
end;
except
on E: Exception do
begin
// ignore
end;
end;
end;
procedure TfmFavNewFolder.cbxFolderTypeMeasureItem(Control: TWinControl;
Index: Integer; var Height: Integer);
begin
Height := 18;
end;
end.
|
{$include lem_directives.inc}
unit LemInteractiveObject;
interface
uses
Classes,
LemPiece;
const
// Object Drawing Flags
odf_OnlyOnTerrain = 1; // bit 0
odf_UpsideDown = 2; // bit 1
odf_NoOverwrite = 4; // bit 2
type
TInteractiveObjectClass = class of TInteractiveObject;
TInteractiveObject = class(TIdentifiedPiece)
private
protected
fDrawingFlags: Byte; // odf_xxxx
fFake: Boolean;
public
procedure Assign(Source: TPersistent); override;
published
property DrawingFlags: Byte read fDrawingFlags write fDrawingFlags;
property IsFake: Boolean read fFake write fFake;
end;
type
TInteractiveObjects = class(TPieces)
private
function GetItem(Index: Integer): TInteractiveObject;
procedure SetItem(Index: Integer; const Value: TInteractiveObject);
protected
public
constructor Create(aItemClass: TInteractiveObjectClass);
function Add: TInteractiveObject;
function Insert(Index: Integer): TInteractiveObject;
property Items[Index: Integer]: TInteractiveObject read GetItem write SetItem; default;
published
end;
implementation
{ TInteractiveObjects }
function TInteractiveObjects.Add: TInteractiveObject;
begin
Result := TInteractiveObject(inherited Add);
end;
constructor TInteractiveObjects.Create(aItemClass: TInteractiveObjectClass);
begin
inherited Create(aItemClass);
end;
function TInteractiveObjects.GetItem(Index: Integer): TInteractiveObject;
begin
Result := TInteractiveObject(inherited GetItem(Index))
end;
function TInteractiveObjects.Insert(Index: Integer): TInteractiveObject;
begin
Result := TInteractiveObject(inherited Insert(Index))
end;
procedure TInteractiveObjects.SetItem(Index: Integer; const Value: TInteractiveObject);
begin
inherited SetItem(Index, Value);
end;
{ TInteractiveObject }
procedure TInteractiveObject.Assign(Source: TPersistent);
var
O: TInteractiveObject absolute Source;
begin
if Source is TInteractiveObject then
begin
inherited Assign(Source);
DrawingFlags := O.DrawingFlags;
end
else inherited Assign(Source);
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.SysInfo
Description : System Info functions
Author : Kike Pérez
Version : 1.2
Created : 17/05/2018
Modified : 05/12/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.SysInfo;
{$i QuickLib.inc}
interface
{$IFDEF FPC}
{$modeSwitch advancedRecords}
{$ENDIF}
uses
SysUtils,
Types,
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$IFNDEF FPC}
{$IFDEF NEXTGEN}
System.IOUtils,
{$IFDEF ANDROID}
Androidapi.Helpers,
{$IFDEF DELPHIRX103_UP}
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.App,
{$ENDIF}
{$ENDIF}
{$IFDEF IOS}
Macapi.CoreFoundation,
iOSApi.Foundation,
{$ENDIF}
{$ENDIF}
{$ENDIF}
Quick.Commons;
type
TSystemInfo = record
private
fAppName : string;
fAppVersion : string;
fAppPath : string;
fHostName : string;
fUserName : string;
fOSVersion : string;
fCPUCores : Integer;
fProcessId : DWORD;
function GetOSVersion : string;
public
procedure GetInfo;
property AppName : string read fAppName;
property AppVersion : string read fAppVersion;
property AppPath : string read fAppPath;
property HostName : string read fHostName;
property UserName : string read fUserName;
property OsVersion : string read fOSVersion;
property CPUCores : Integer read fCPUCores;
property ProcessId : DWORD read fProcessId;
end;
var
SystemInfo : TSystemInfo;
implementation
{ TSystemInfo }
procedure TSystemInfo.GetInfo;
begin
{$IFNDEF NEXTGEN}
if IsLibrary then fAppName := ExtractFileNameWithoutExt(GetModuleName(0))
else fAppName := ExtractFilenameWithoutExt(ParamStr(0));
{$ELSE}
{$IFDEF ANDROID}
{$IFDEF DELPHIRX103_UP}
fAppName := JStringToString(TAndroidHelper.Context.getPackageName);
{$ELSE}
fAppName := JStringToString(SharedActivityContext.getPackageName);
{$ENDIF}
{$ELSE}
fAppName := TNSString.Wrap(CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle, kCFBundleIdentifierKey)).UTF8String;
{$ENDIF}
{$ENDIF}
fAppVersion := GetAppVersionFullStr;
{$IFNDEF NEXTGEN}
if IsLibrary then fAppPath := ExtractFilePath(GetModuleName(0))
else fAppPath := ExtractFilePath(ParamStr(0));
{$ELSE}
fAppPath := TPath.GetDocumentsPath;
{$ENDIf}
{$IFDEF DELPHILINUX}
fUserName := GetLoggedUserName;
{$ELSE}
fUserName := Trim(GetLoggedUserName);
{$ENDIF}
fHostName := GetComputerName;
fOSVersion := GetOSVersion;
fCPUCores := CPUCount;
{$IFDEF MSWINDOWS}
fProcessId := GetCurrentProcessID;
{$ELSE}
{$ENDIF}
end;
function TSystemInfo.GetOSVersion: string;
begin
Result := {$IFDEF FPC}
{$I %FPCTARGETOS%}+'-'+{$I %FPCTARGETCPU%}
{$ELSE}
TOSVersion.ToString
{$ENDIF};
end;
initialization
try
SystemInfo.GetInfo;
except
{$IFDEF MSWINDOWS}
on E : Exception do
begin
if (not IsLibrary) and (not IsService) then raise Exception.CreateFmt('Error getting SystemInfo: %s',[e.Message]);
end;
{$ENDIF}
end;
end.
|
unit MazeSolve;
Interface
Uses
MazeMain;
Function SolveBFS(const MazeToSolve: TMaze; const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Function SolveDFS(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Function SolveRightHand(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Function SolveLeftHand(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Implementation
Type
TCource = (Up, Down, Right, Left);
//Algorithm BFS
Function SolveBFS(const MazeToSolve: TMaze; const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Type
TMazeInt = array of array of Integer;
PQueueList = ^TQueueList;
TQueueList = record
Data: TPos;
Next: PQueueList;
end;
TQueue = record
PFirst, PLast: PQueueList;
end;
//Conver from type maze to numeric maze
Procedure ConvertMaze(const Maze1: TMaze; var Maze2: TMazeInt);
Var
I, J: Integer;
Begin
For I := 0 to High(Maze1) do
For J := 0 to High(Maze1[I]) do
If Maze1[I, J] = Wall then
Maze2[I, J] := -1
else
Maze2[I, J] := 0;
End;
Procedure Push(var Queue: TQueue; const Pos: TPos); overload;
Var
NewEl: PQueueList;
Begin
New(NewEl);
NewEl^.Data := Pos;
NewEl^.Next := nil;
If Queue.PFirst = nil then
Queue.PFirst := NewEl
else
Queue.PLast^.Next := NewEl;
Queue.PLast := NewEl;
End;
Function Pop(var Queue: TQueue): TPos;
Var
NewEl: PQueueList;
Begin
If Queue.PFirst <> nil then
Begin
NewEl := Queue.PFirst;
Result := NewEl^.Data;
Queue.PFirst := NewEl^.Next;
If Queue.PFirst = nil then
Queue.PLast := nil;
Dispose(NewEl);
End;
End;
Function IsEmpty(const Queue: TQueue): Boolean;
Begin
Result := False;
If (Queue.PFirst = nil) and (Queue.PLast = nil)then
Result := True;
End;
Procedure QueueUnload(var Queue: TQueue);
Var
FData: TPos;
Begin
While not IsEmpty(Queue) do
FData := Pop(Queue);
End;
Procedure QueueInit(var Queue: TQueue);
Begin
Queue.PFirst := nil;
Queue.PLast := nil;
End;
Procedure Push(var Arr: TRoute; const Pos: TPos); overload;
begin
SetLength(Arr, Length(Arr)+1);
Arr[High(Arr)] := Pos;
end;
//Wave alg fill maze numbers
Procedure FillMazeNumbers(Var MazeToFill: TMazeInt; const PStart, PEnd: TPos; var VisitedCells: TRoute);
//Fill nearest cells numbers? rerurn number of available cels
Function FillNearestCells(var MazeToUse: TMazeInt; CellNow: TPos; WaveNow: Integer; var SetPoints: TQueue; var AllVisitP: TRoute): Integer;
Const
ModifX: array [0 .. 3] of Integer = (0, 0, 1, -1);
ModifY: array [0 .. 3] of Integer = (-1, 1, 0, 0);
Dir: array of TCource = [Up, Down, Right, Left];
Var
CourceNow: TCource;
NewCell: TPos;
Begin
Result := 0;
//Check each side
For CourceNow in Dir do
Begin
NewCell := CellNow;
Inc(NewCell.PosX, ModifX[Ord(CourceNow)]);
Inc(NewCell.PosY, ModifY[Ord(CourceNow)]);
//If available fill numb, push to the queue
If (NewCell.PosX >= 0) and (NewCell.PosY >= 0) and (NewCell.PosY <= High(MazeToUse))
and (NewCell.PosX <= High(MazeToUse[0])) and (MazeToUse[NewCell.PosY, NewCell.PosX] = 0) then
Begin
MazeToUse[NewCell.PosY, NewCell.PosX] := WaveNow;
Push(SetPoints, NewCell);
Push(AllVisitP, NewCell);
Inc(Result);
End;
End;
End;
Var
NumberWave, I: Integer;
NewAmountPoints, AmountPoints: Integer;
Cell: TPos;
PointsToCheck: TQueue;
Begin
QueueInit(PointsToCheck);
MazeToFill[PStart.PosY, PStart.PosX] := 1;
Push(PointsToCheck, PStart);
Push(VisitedCells, PStart);
NumberWave := 1;
AmountPoints := 0;
//While not Finish do
While MazeToFill[PEnd.PosY, PEnd.PosX] = 0 do
Begin
Inc(NumberWave);
NewAmountPoints := 0;
//Check cells from last check? get them from queue
For I := 0 to AmountPoints do
Begin
Cell := Pop(PointsToCheck);
Inc(NewAmountPoints, FillNearestCells(MazeToFill, Cell, NumberWave, PointsToCheck, VisitedCells))
End;
AmountPoints := NewAmountPoints-1;
End;
QueueUnload(PointsToCheck);
End;
//Restore the path
Function GetRoute(const MazeToCheck: TMazeInt; const PStart, PEnd: TPos): TRoute;
Var
NumberCheck, NumberWave: Integer;
Cell: TPos;
Begin
Cell := PEnd;
NumberCheck := 0;
NumberWave := MazeToCheck[PEnd.PosY, PEnd.PosX];
SetLength(Result, 1);
Result[NumberCheck] := Cell;
//The cycle of finding the exit from the maze
While (Cell.PosX <> PStart.PosX) or (Cell.PosY <> PStart.PosY) do
Begin
Dec(NumberWave);
//Check for a wave and go back to the array, enter the path
If (Cell.PosY > 0) and (MazeToCheck[Cell.PosY-1, Cell.PosX] = NumberWave) then
Dec(Cell.PosY)
else If (Cell.PosX > 0) and (MazeToCheck[Cell.PosY, Cell.PosX-1] = NumberWave) then
Dec(Cell.PosX)
else If (Cell.PosY < High(MazeToCheck)) and (MazeToCheck[Cell.PosY+1, Cell.PosX] = NumberWave) then
Inc(Cell.PosY)
else If (Cell.PosX < High(MazeToCheck[0])) and (MazeToCheck[Cell.PosY, Cell.PosX+1] = NumberWave) then
Inc(Cell.PosX);
Inc(NumberCheck);
SetLength(Result, NumberCheck+1);
Result[NumberCheck] := Cell;
End;
end;
Var
ConvertedMaze: TMazeInt;
Begin
SetLength(AllVisitedCells, 0);
SetLength(ConvertedMaze, Length(MazeTosolve), Length(MazeTosolve[0]));
ConvertMaze(MazeTosolve, ConvertedMaze);
FillMazeNumbers(ConvertedMaze, StartP, EndP, AllVisitedCells);
Result := GetRoute(ConvertedMaze, StartP, EndP);
end;
//Algorithm DFS
Function SolveDFS(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
Type
PStack = ^TStack;
TStack= record
Data: TPos;
Next: PStack;
end;
Procedure Push(Var Stack: PStack; const Pos: TPos); overload;
Var
NewEl: PStack;
Begin
New(NewEl);
NewEl^.Data := Pos;
NewEl^.Next := Stack;
Stack := NewEl;
End;
Function Pop(var Stack: PStack): TPos;
Var
BuffEl: PStack;
Begin
If Stack <> nil then
Begin
BuffEl := Stack;
Result := BuffEl^.Data;
Stack := BuffEl^.Next;
Dispose(BuffEl);
End;
End;
Function IsEmpty(const Stack: PStack): Boolean;
Begin
Result := False;
If Stack = Nil then
Result := True;
End;
Procedure ConvertToArr(var Stack: PStack; var ArrToUnload: TRoute);
Begin
While not IsEmpty(Stack) do
Begin
SetLength(ArrToUnload, Length(ArrToUnload)+1);
ArrToUnload[High(ArrToUnload)] := Pop(Stack);
End;
End;
Procedure StackInit(var Stack: PStack);
Begin
Stack := nil;
End;
Procedure StackUnload(var Stack: PStack);
Var
Buff: TPos;
Begin
while not IsEmpty(Stack) do
Buff := Pop(Stack);
End;
Procedure Push(var Arr: TRoute; const Pos: TPos); overload;
begin
SetLength(Arr, Length(Arr)+1);
Arr[High(Arr)] := Pos;
end;
procedure CopyMaze(const Maze1: TMaze; var Maze2: TMaze);
var
I, J: Integer;
begin
SetLength(Maze2, Length(Maze1), Length(Maze1[0]));
for I := Low(Maze1) to High(Maze1) do
for J := Low(Maze1[I]) to High(Maze1[I]) do
Maze2[I, J] := Maze1[I, J];
end;
Var
Cell: TPos;
CellStack: PStack;
MazeSolve: TMaze;
Begin
CopyMaze(MazeToSolve, MazeSolve);
SetLength(AllVisitedCells, 0);
StackInit(CellStack);
Cell := StartP;
MazeSolve[Cell.PosY, Cell.PosX] := Visited;
Push(CellStack, Cell);
Push(AllVisitedCells, Cell);
//While not finish
While MazeSolve[EndP.PosY, EndP.PosX] = Pass do
Begin
//If cell available push to the stack, else return return back
If (Cell.PosY > 0) and (MazeSolve[Cell.PosY-1, Cell.PosX] = Pass) then
begin
Dec(Cell.PosY);
Push(AllVisitedCells, Cell);
end
else If (Cell.PosX > 0) and (MazeSolve[Cell.PosY, Cell.PosX-1] = Pass) then
begin
Dec(Cell.PosX);
Push(AllVisitedCells, Cell);
end
else If (Cell.PosY < High(MazeSolve)) and (MazeSolve[Cell.PosY+1, Cell.PosX] = Pass) then
begin
Inc(Cell.PosY);
Push(AllVisitedCells, Cell);
end
else If (Cell.PosX < High(MazeSolve[0])) and (MazeSolve[Cell.PosY, Cell.PosX+1] = Pass) then
begin
Inc(Cell.PosX);
Push(AllVisitedCells, Cell);
end
else
begin
Cell := Pop(CellStack);
Cell := Pop(CellStack);
end;
MazeSolve[Cell.PosY, Cell.PosX] := Visited;
Push(CellStack, Cell);
End;
ConvertToArr(CellStack, Result);
StackUnload(CellStack);
End;
//Algorithm Right and left hand
Function FindRouteHand(const MazeToFind: TMaze; Const StartP, EndP: TPos; Hand: TCource): TRoute;
//if (Right hand) wall on the right return true
Function IsSideWall(const MazeToCheck: TMaze; Pos: TPos; DirNow, HandNow: TCource): Boolean;
//Get true orientation
Function GetSideDir(CourceNew, HandToUse: TCource): TCource;
Const
LeftConvert: array [0..3] of TCource = (Left, Right, Up, Down);
RightConvert: array [0..3] of TCource = (Right, Left, Down, Up);
Begin
If HandToUse = Left then
Result := LeftConvert[Ord(CourceNew)]
else
Result := RightConvert[Ord(CourceNew)];
End;
Const
ModifX: array [0..3] of Integer = (0, 0, 1, -1);
ModifY: array [0..3] of Integer = (-1, 1, 0, 0);
Var
CheckCource: TCource;
NewPos: TPos;
Begin
CheckCource := GetSideDir(DirNow, HandNow);
NewPos.PosY := Pos.PosY + ModifY[Ord(CheckCource)];
NewPos.PosX := Pos.PosX + ModifX[Ord(CheckCource)];
If (NewPos.PosX < 0) or (NewPos.PosY < 0) or (NewPos.PosX > High(MazeToCheck[0])) or (NewPos.PosY > High(MazeToCheck)) then
Result := True
else If MazeToCheck[NewPos.PosY, NewPos.PosX] = Wall then
Result := True
else
Result := False;
End;
//Check for the front wall
Function IsFrontWall(const MazeToCheck: TMaze; Pos: TPos; DirNow: TCource): Boolean;
Const
ModifX: array [0..3] of Integer = (0, 0, 1, -1);
ModifY: array [0..3] of Integer = (-1, 1, 0, 0);
Var
NewPos: TPos;
Begin
NewPos.PosX := Pos.PosX + ModifX[Ord(DirNow)];
NewPos.PosY := Pos.PosY + ModifY[Ord(DirNow)];
If (NewPos.PosX < 0) or (NewPos.PosY < 0) or (NewPos.PosX > High(MazeToCheck[0])) or (NewPos.PosY > High(MazeToCheck)) then
Result := True
else If MazeToCheck[NewPos.PosY, NewPos.PosX] = Wall then
Result := True
else
Result := False;
end;
//If Hit the wall correct direction
Function CorrectCource(DirNow, HandNow: TCource): TCource;
Const
Sides: array of TCource = [Down, Right, Up, Left];
Var
I, DirPos: Integer;
Begin
For I := Low(Sides) to High(Sides) do
If Sides[I] = DirNow then
DirPos := I;
If HandNow = Left then
If DirNow = Down then
Result := Left
else
Result := Sides[Pred(DirPos)]
else
If DirNow = Left then
Result := Down
else
Result := Sides[Succ(DirPos)];
end;
//Answer
Procedure Push(var Route: TRoute; Pos: TPos);
begin
SetLength(Route, Length(Route)+1);
Route[High(Route)] := Pos;
end;
Const
ModifX: array [0..3] of Integer = (0, 0, 1, -1);
ModifY: array [0..3] of Integer = (-1, 1, 0, 0);
Var
CourceNow: TCource;
PosNow: TPos;
Begin
CourceNow := Right;
PosNow := StartP;
Push(Result, PosNow);
//while not Finish
While (PosNow.PosX <> EndP.PosX) or (PosNow.PosY <> EndP.PosY) do
Begin
//IF right side - Pass -> Rotate
If IsSideWall(MazeToFind, PosNow, CourceNow, Hand) then
If IsFrontWall(MazeToFind, PosNow, CourceNow) then
CourceNow := CorrectCource(CourceNow, Hand)
else
Begin
Inc(PosNow.PosX, ModifX[Ord(CourceNow)]);
Inc(PosNow.PosY, ModifY[Ord(CourceNow)]);
End
else
Begin
If Hand = Right then
CourceNow := CorrectCource(CourceNow, Left)
else
CourceNow := CorrectCource(CourceNow, Right);
Inc(PosNow.PosX, ModifX[Ord(CourceNow)]);
Inc(PosNow.PosY, ModifY[Ord(CourceNow)]);
End;
Push(Result, PosNow);
End;
end;
//Algorithm Right hand
Function SolveRightHand(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
begin
Result := FindRouteHand(MazeToSolve, StartP, EndP, Right);
AllVisitedCells := Result;
end;
//Algorithm Left hand
Function SolveLeftHand(const MazeToSolve: TMaze; Const StartP, EndP: TPos; var AllVisitedCells: TRoute): TRoute;
begin
Result := FindRouteHand(MazeToSolve, StartP, EndP, Left);
AllVisitedCells := Result;
end;
end.
|
unit ufmMain;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls;
type
TForm15 = class(TForm)
lblDescription: TLabel;
btnSaveToPtotoBuf: TButton;
btnLoadFromProtoBuf: TButton;
btnSpeedTest: TButton;
procedure btnSaveToPtotoBufClick(Sender: TObject);
procedure btnLoadFromProtoBufClick(Sender: TObject);
procedure btnSpeedTestClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form15: TForm15;
implementation
uses
System.DateUtils,
TestImport1,
Test1;
{$R *.dfm}
procedure TForm15.btnLoadFromProtoBufClick(Sender: TObject);
var
TestMsg1: TTestMsg1;
TestExtension: TTestMsg1Extension1;
Stream: TStream;
sFileName: string;
begin
// open data container, saved by btnSaveToPtotoBufClick method
sFileName := ExtractFilePath(ParamStr(0)) + 'Msg1.bin';
Stream := TFileStream.Create(sFileName, fmOpenRead);
try
TestMsg1 := TTestMsg1.Create;
try
TestMsg1.LoadFromStream(Stream);
// and now we have saved data
// let`s check, that all properties loaded.
Assert(TestMsg1.DefField1 = 20, 'Wrong value in DefField1');
Assert(TestMsg1.DefField9 = 1.5, 'Wrong value in DefField9');
Assert(TestMsg1.FieldArr1List.Count = 1, 'Wrong count in FieldArr1List');
Assert(TestMsg1.FieldArr1List[0] = 743, 'Wrong value in FieldArr1List[0]');
Assert(TestMsg1.FieldImp1 = gVal1, 'Wrong value in FieldImp1');
finally
TestMsg1.Free;
end;
finally
Stream.Free;
end;
sFileName := ExtractFilePath(ParamStr(0)) + 'ExtendedMsg1.bin';
Stream := TFileStream.Create(sFileName, fmOpenRead);
try
TestExtension := TTestMsg1Extension1.Create;
try
TestExtension.LoadFromStream(Stream);
finally
TestExtension.Free;
end;
finally
Stream.Free;
end;
ShowMessage('Success');
end;
procedure TForm15.btnSaveToPtotoBufClick(Sender: TObject);
var
TestMsg1: TTestMsg1;
TestExtension: TTestMsg1Extension1;
Stream: TStream;
sFileName: string;
begin
// prepare container for output data
// In this example we save objects to file
sFileName := ExtractFilePath(ParamStr(0)) + 'Msg1.bin';
Stream := TFileStream.Create(sFileName, fmCreate);
try
TestMsg1 := TTestMsg1.Create;
try
// prepare data (random fill)
TestMsg1.DefField1 := 20;
TestMsg1.DefField9 := 1.5;
TestMsg1.FieldArr1List.Add(743);
TestMsg1.FieldHasValue[TTestMsg1.tag_FieldArr1List]:= True;
TestMsg1.FieldImp1 := gVal1;
// and now save data
TestMsg1.SaveToStream(Stream);
finally
TestMsg1.Free;
end;
finally
Stream.Free;
end;
sFileName := ExtractFilePath(ParamStr(0)) + 'ExtendedMsg1.bin';
Stream := TFileStream.Create(sFileName, fmCreate);
try
TestExtension := TTestMsg1Extension1.Create;
try
TestExtension.field_name_test_1 := 323;
TestExtension.field_Name_test_2 := 5432;
TestExtension.DefField2 := -3;
TestExtension.DefField1 := 3;
TestExtension.SaveToStream(Stream);
finally
TestExtension.Free;
end;
finally
Stream.Free;
end;
end;
procedure TForm15.btnSpeedTestClick(Sender: TObject);
procedure GenerateData(msg: TTestMsg1);
var
i: Integer;
begin
msg.FieldHasValue[TTestMsg1.tag_FieldArr3List]:= True;
msg.FieldHasValue[TTestMsg1.tag_FieldArr1List]:= True;
for i := 0 to 9999 do
begin
msg.FieldArr3List.Add('foo some long-long value '+IntToStr(i));
msg.FieldArr1List.Add(i);
end;
end;
var
msgOutput, msgInput: TTestMsg1;
Stream: TStream;
dtStartSave: TDateTime;
dtEndLoad: TDateTime;
begin
Stream := TMemoryStream.Create;
try
msgOutput := TTestMsg1.Create;
msgInput := TTestMsg1.Create;
try
GenerateData(msgOutput);
dtStartSave := Now;
msgOutput.SaveToStream(Stream);
Stream.Seek(0, soBeginning);
msgInput.LoadFromStream(Stream);
dtEndLoad := Now;
finally
msgInput.Free;
msgOutput.Free;
end;
finally
Stream.Free;
end;
ShowMessage('ProtoBuf: 10 000 strings and 10 000 integers'#13#10'saved and loaded at ' + IntToStr(MillisecondsBetween(dtStartSave, dtEndLoad))+' milliseconds');
end;
end.
|
unit ConversationListComponent;
interface
uses FMX.Layouts, Fmx.graphics, FMX.Objects, FMX.Types, System.Classes,
System.UITypes, System.Math, System.Types, CommonHeader;
Type
TConversationList = class(TVertScrollBox)
private
fPeople1Name : string;
fPeople2Name : string;
procedure AddMessage(AlignRight : Boolean; AMessage : String);
procedure OnLabelPaintProc(ASender : TObject; Aanvas : TCanvas; const ARect : TRectF);
public
Constructor Create(AOwner : TComponent; APeople1Name, APeople2Name: string);
destructor destroy;override;
procedure AddMessageFromPeople1(AMessage : string);
procedure AddMessageFromPeople2(AMessage : string);
end;
implementation
{ TConversationList }
uses
frmConnect;
procedure TConversationList.AddMessage(AlignRight: Boolean; AMessage : String);
var
wCalloutR: TCalloutRectangle;
wMessage: TText;
wTmpImg: TImage;
wcolor : TColors;
begin
wCalloutR := TCalloutRectangle.Create(Self);
wCalloutR.Parent := Self;
wCalloutR.Align := TAlignLayout.alTop;
wCalloutR.CalloutPosition := TCalloutPosition.cpLeft;
wCalloutR.Margins.Top := 10;
wCalloutR.Margins.Bottom := 10;
wCalloutR.Margins.Right := 5;
wCalloutR.Height := 75;
wCalloutR.Fill.Color := wcolor.White;
wMessage := TText.Create(Self);
wMessage.Parent := wCalloutR;
wMessage.Align := TAlignLayout.alClient;
wMessage.Text := AMessage;
wMessage.Margins.Left := 15;
wMessage.Margins.Right := 5;
wMessage.Width := wCalloutR.Width-20;
wMessage.WordWrap := True;
wMessage.AutoSize := True;
//wCalloutR.Height := 75;
wMessage.OnPaint := OnLabelPaintProc;
wTmpImg := TImage.Create(Self);
wTmpImg.Parent := wCalloutR;
if AlignRight then
begin
wTmpImg.Align := TAlignLayout.alRight;
wTmpImg.Margins.right := 12;
wTmpImg.Bitmap.Assign(FormConnect.HimImage.Bitmap); //LoadFromFile(GetImageFilename('HimAvatar.png'));
end
else begin
wTmpImg.Align := TAlignLayout.alLeft;
wTmpImg.Margins.Left := 12;
wTmpImg.Bitmap.Assign(FormConnect.MeImage.Bitmap); //LoadFromFile(GetImageFilename('MeAvatar.png'));
end;
wTmpImg.Width := 55;
end;
procedure TConversationList.AddMessageFromPeople1(AMessage: string);
begin
AddMessage(False, AMessage);
end;
procedure TConversationList.AddMessageFromPeople2(AMessage: string);
begin
AddMessage(True, AMessage);
end;
constructor TConversationList.Create(AOwner : TComponent; APeople1Name, APeople2Name: string);
begin
inherited Create(AOwner);
fPeople1Name := APeople1Name;
fPeople2Name := APeople2Name;
end;
destructor TConversationList.destroy;
begin
inherited;
end;
procedure TConversationList.OnLabelPaintProc(ASender : TObject; Aanvas : TCanvas; const ARect : TRectF);
begin
TText(ASender).Height := ARect.Height;
TCalloutRectangle(TText(ASender).Parent).height := IFTHEN(Arect.Height < 50,50 ,Arect.Height);
end;
end.
|
unit Tanque;
interface
type
TTanque = class
private
FId: Integer;
FDescricao: String;
function GetId: Integer;
procedure SetId(const Value: Integer);
function GetDescricao: String;
procedure SetDescricao(const Value: String);
public
property Id: Integer read GetId write SetId;
property Descricao: String read GetDescricao write SetDescricao;
end;
implementation
{ TTanque }
function TTanque.GetDescricao: String;
begin
Result := FDescricao;
end;
function TTanque.GetId: Integer;
begin
Result := FId;
end;
procedure TTanque.SetDescricao(const Value: String);
begin
FDescricao := Value;
end;
procedure TTanque.SetId(const Value: Integer);
begin
FId := Value;
end;
end.
|
unit nsOpenOrSaveInternetFileDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, nsDownloaderInterfaces, eeButton, vtButton,
vtRadioButton, vtLabel, vtCtrls, ImgList;
type
TnsOpenOrSaveInternetFileDialog = class(TForm)
btnOpen: TvtButton;
btnSave: TvtButton;
btnCancel: TvtButton;
lblPrompt: TvtLabel;
lblFileNameCaption: TvtLabel;
lblFileTypeCaption: TvtLabel;
lblURLCaption: TvtLabel;
lblFileName: TvtLabel;
lblFileType: TvtLabel;
lblURL: TvtLabel;
imgFileTypeIcon: TvtImage;
procedure btnOpenClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
FParams: Pointer;
FUpdatingParams: Boolean;
procedure UpdateControls;
protected
procedure Loaded; override;
function GetParams: InsDownloadParams;
procedure SetParams(const AParams: InsDownloadParams);
property Params: InsDownloadParams read GetParams write SetParams;
public
class function ChooseParams(const AParams: InsDownloadParams): Boolean;
end;
implementation
uses
nsDownloaderRes,
StrUtils,
ShellApi,
l3Base,
l3String,
vtSaveDialog,
vcmBaseTypes,
vcmBase;
{$R *.dfm}
{ TOpenOrSaveInternetFileDialog }
class function TnsOpenOrSaveInternetFileDialog.ChooseParams(
const AParams: InsDownloadParams): Boolean;
var
l_Form: TnsOpenOrSaveInternetFileDialog;
begin
l_Form := Create(Application);
try
l_Form.Params := AParams;
Result := (l_Form.ShowModal = mrOk);
finally
FreeAndNil(l_Form);
end;
end;
procedure TnsOpenOrSaveInternetFileDialog.UpdateControls;
function lp_GetRoot(const APath: string): string;
var
i: Integer;
begin
i := Pos('//', APath);
if i>0 then
i := PosEx('/', APath, i + 2)
else
i := Pos('/', APath);
if (i = 0) then
i := Length(APath);
Result := Copy(APath, 1, i);
end;
var
l_FileName: String;
begin
l_FileName := ExtractFileName(Params.FileName);
lblFileName.Caption := l_FileName;
lblFileName.Hint := l_FileName;
lblFileType.Caption := Params.FileTypeString;
lblFileType.Hint := Params.FileTypeString;
lblURL.Caption := lp_GetRoot(Params.URL);
lblURL.Hint := lblURL.Caption;
imgFileTypeIcon.Picture.Icon.Handle := Params.FileIcon;
lblPrompt.Caption := l3Str(str_OpenOrDownloadQuestion.AsCStr);
lblFileNameCaption.Caption := l3Str(str_FileName.AsCStr);
lblFileTypeCaption.Caption := l3Str(str_Type.AsCStr);
lblURLCaption.Caption := l3Str(str_From.AsCStr);
btnOpen.Caption := l3Str(str_Open.AsCStr);
btnSave.Caption := l3Str(str_Download.AsCStr);
btnCancel.Caption := l3Str(str_Cancel.AsCStr);
end;
procedure TnsOpenOrSaveInternetFileDialog.Loaded;
begin
inherited;
Caption := l3Str(str_FileDownload.AsCStr);
end;
function TnsOpenOrSaveInternetFileDialog.GetParams: InsDownloadParams;
begin
Result := InsDownloadParams(FParams);
end;
procedure TnsOpenOrSaveInternetFileDialog.SetParams(const AParams: InsDownloadParams);
begin
FParams := Pointer(AParams);
UpdateControls;
end;
procedure TnsOpenOrSaveInternetFileDialog.btnOpenClick(Sender: TObject);
begin
Params.FileAction := dfaOpen;
ModalResult := mrOK;
end;
procedure TnsOpenOrSaveInternetFileDialog.btnSaveClick(Sender: TObject);
var
l_SaveDialog: TvtSaveDialog;
l_FileExt: String;
begin
Params.FileAction := dfaSave;
l_SaveDialog := TvtSaveDialog.Create(Self);
try
l_FileExt := ExtractFileExt(Params.FileName);
l_SaveDialog.DefaultExt := l_FileExt;
l_SaveDialog.Options := l_SaveDialog.Options + [ofOverwritePrompt];
Delete(l_FileExt, 1, 1);
l_SaveDialog.FileName := ExtractFileName(Params.FileName);
l_SaveDialog.Filter := Format('%s|*.%s', [l_FileExt, l_FileExt]);
if l_SaveDialog.Execute then
begin
Params.FileName := l_SaveDialog.FileName;
ModalResult := mrOk;
end
else
ModalResult := mrCancel;
finally
FreeAndNil(l_SaveDialog);
end;
end;
end.
|
unit System.Query.Fluent;
interface
uses System.Classes, System.SysUtils, Data.DB;
type
IFluentQuery = Interface
['{738FDA90-A6E8-4FB0-A65E-6FCD4DF79F4E}']
Function Dataset(ADataset: TDataset):IFluentQuery;overload;
Function Dataset():TDataset;overload;
function Where(AWhere:String):IFluentQuery;
End;
TFluentQueryAttrib = record
Fields:string;
Table:String;
Where:String;
Join:string;
GroupBy:string;
OrderBy:String;
end;
TFluentQuery<T: Class> = class(TInterfacedObject, IFluentQuery)
protected
FDataset: TDataset;
FAttrib:TFluentQueryAttrib;
public
class function QueryBuilder(AAttrib:TFluentQueryAttrib):string;static;
class function New: IFluentQuery; static;
function Dataset(ADataset: TDataset): IFluentQuery;overload;
Function Dataset():TDataset;overload;
function Where(AWhere:String):IFluentQuery;
end;
implementation
uses System.Rtti;
function TFluentQuery<T>.Dataset: TDataset;
begin
result := FDataset;
end;
class function TFluentQuery<T>.New: IFluentQuery;
var
q: TFluentQuery<T>;
begin
q := TFluentQuery<T>.create;
q.Dataset(TDataset(T).create(nil));
result := q;
end;
class function TFluentQuery<T>.QueryBuilder(
AAttrib: TFluentQueryAttrib): string;
begin
end;
function TFluentQuery<T>.Where(AWhere: String): IFluentQuery;
begin
FAttrib.Where := AWhere;
end;
function TFluentQuery<T>.Dataset(ADataset: TDataset): IFluentQuery;
begin
FDataset := ADataset;
result := self;
end;
end.
|
unit RDOMarshalers;
interface
uses
{$IFDEF AutoServer}
RDOClient_TLB,
{$ENDIF}
RDOInterfaces;
function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : variant;
procedure MarshalPropertySet( ObjectId : integer; const PropName : string; const PropValue : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer );
procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer );
function MarshalObjIdGet( ObjectName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : integer;
implementation
uses
Windows, SysUtils, RDOProtocol, RDOUtils, ErrorCodes;
function GetQueryErrorCode( QueryResText : string ) : integer;
var
ScanPos : integer;
QueryResLen : integer;
ErrorKeyWrdPos : integer;
ErrorCodeDigits : string;
begin
ErrorKeyWrdPos := KeyWordPos( ErrorKeyWord, QueryResText );
if ErrorKeyWrdPos <> 0
then
begin
ScanPos := ErrorKeyWrdPos + Length( ErrorKeyWord );
QueryResLen := Length( QueryResText );
while ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] in WhiteSpace ) do
inc( ScanPos );
ErrorCodeDigits := '';
if ScanPos <= QueryResLen
then
begin
while ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] in [ '0' .. '9' ] ) do
begin
ErrorCodeDigits := ErrorCodeDigits + QueryResText[ ScanPos ];
inc( ScanPos )
end;
try
Result := StrToInt( ErrorCodeDigits )
except
Result := errMalformedResult
end
end
else
Result := errMalformedResult
end
else
Result := errNoError
end;
function GetVariableValue( QueryResText, VarName : string; out Error : boolean ) : string;
var
ScanPos : integer;
VarNamePos : integer;
QueryResLen : integer;
VarValueDelimit : char;
EndOfLiteral : boolean;
begin
Result := '';
Error := false;
VarNamePos := KeyWordPos( VarName, QueryResText );
if VarNamePos <> 0
then
begin
ScanPos := VarNamePos + Length( VarName );
QueryResLen := Length( QueryResText );
while ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] in WhiteSpace ) do
inc( ScanPos );
if ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] = NameValueSep )
then
begin
inc( ScanPos );
while ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] in WhiteSpace ) do
inc( ScanPos );
if ScanPos <= QueryResLen
then
begin
VarValueDelimit := QueryResText[ ScanPos ];
if ( VarValueDelimit <> Quote ) and ( VarValueDelimit <> LiteralDelim )
then
VarValueDelimit := Blank;
inc( ScanPos );
repeat
while ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] <> VarValueDelimit ) do
begin
Result := Result + QueryResText[ ScanPos ];
inc( ScanPos )
end;
inc( ScanPos );
if ( ScanPos <= QueryResLen ) and ( QueryResText[ ScanPos ] = VarValueDelimit )
then
begin
EndOfLiteral := false;
Result := Result + VarValueDelimit;
inc( ScanPos )
end
else
EndOfLiteral := true;
until EndOfLiteral
end
else
Error := true
end
else
Error := true
end
else
Error := true
end;
function MarshalPropertyGet( ObjectId : integer; const PropName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : variant;
var
QueryText : string;
QueryResult : string;
VarValue : string;
Error : boolean;
begin
Result := '';
if Priority <> THREAD_PRIORITY_NORMAL
then
QueryText := PriorityToPriorityId( Priority ) + Blank
else
QueryText := '';
QueryText := QueryText + SelObjCmd + Blank + IntToStr( ObjectId ) + Blank + GetPropCmd + Blank + PropName + QueryTerm;
QueryResult := RDOConnection.SendReceive( QueryText, ErrorCode, TimeOut );
if ErrorCode = errNoError
then
begin
ErrorCode := GetQueryErrorCode( QueryResult );
if ErrorCode = errNoError
then
begin
VarValue := GetVariableValue( QueryResult, PropName, Error );
if Error
then
ErrorCode := errMalformedResult
else
try
Result := GetVariantFromStr( VarValue )
except
ErrorCode := errMalformedResult;
Result := ''
end
end
end
end;
procedure MarshalPropertySet( ObjectId : integer; const PropName : string; const PropValue : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer );
var
QueryText : string;
QueryResult : string;
PropValAsStr : string;
IllegalVType : boolean;
begin
PropValAsStr := GetStrFromVariant( PropValue, IllegalVType );
if not IllegalVType
then
begin
if Priority <> THREAD_PRIORITY_NORMAL
then
QueryText := PriorityToPriorityId( Priority ) + Blank
else
QueryText := '';
QueryText := QueryText + SelObjCmd + Blank + IntToStr( ObjectId ) + Blank + SetPropCmd + Blank + PropName + NameValueSep + LiteralDelim + PropValAsStr + LiteralDelim + QueryTerm;
if TimeOut <> 0
then
begin
QueryResult := RDOConnection.SendReceive( QueryText, ErrorCode, TimeOut );
if ErrorCode = errNoError
then
ErrorCode := GetQueryErrorCode( QueryResult )
end
else
begin
RDOConnection.Send( QueryText );
ErrorCode := errNoError
end
end
else
ErrorCode := errIllegalPropValue
end;
procedure MarshalMethodCall( ObjectId : integer; const MethodName : string; var Params : variant; var Res : variant; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer );
var
QueryText : string;
QueryResult : string;
ParamIdx : integer;
ParamCount : integer;
BRefParamIdx : integer;
ParamAsStr : string;
IllegalVType : boolean;
VarValue : string;
Error : boolean;
TmpVariant : variant;
begin
ErrorCode := errNoError;
if Priority <> THREAD_PRIORITY_NORMAL
then
QueryText := PriorityToPriorityId( Priority ) + Blank
else
QueryText := '';
if TVarData( Res ).VType <> varEmpty
then
QueryText := QueryText + SelObjCmd + Blank + IntToStr( ObjectId ) + Blank + CallMethCmd + Blank + MethodName + Blank + LiteralDelim + VariantId + LiteralDelim + Blank
else
QueryText := QueryText + SelObjCmd + Blank + IntToStr( ObjectId ) + Blank + CallMethCmd + Blank + MethodName + Blank + LiteralDelim + VoidId + LiteralDelim + Blank;
ParamCount := 0;
if not IllegalVType
then
begin
ParamIdx := 1;
if TVarData( Params ).VType and varArray <> 0
then
ParamCount := VarArrayHighBound( Params, 1 );
while ( ParamIdx <= ParamCount ) and ( ErrorCode = errNoError ) do
begin
if TVarData( Params[ ParamIdx ] ).VType and varArray = 0
then
begin
if TVarData( Params[ ParamIdx ] ).VType and varTypeMask = varVariant
then
begin
TVarData( TmpVariant ).VType := varVariant;
Params[ ParamIdx ] := TmpVariant;
ParamAsStr := GetTypeIdFromVariant( Params[ ParamIdx ], IllegalVType )
end
else
ParamAsStr := GetStrFromVariant( Params[ ParamIdx ], IllegalVType );
if not IllegalVType
then
begin
QueryText := QueryText + LiteralDelim + ParamAsStr + LiteralDelim;
if ParamIdx <> ParamCount
then
QueryText := QueryText + ParamDelim
end
else
ErrorCode := errIllegalParamList
end
else
ErrorCode := errIllegalParamList;
inc( ParamIdx )
end
end
else
ErrorCode := errUnknownError;
if ErrorCode = errNoError
then
begin
QueryText := QueryText + QueryTerm;
if ( TimeOut <> 0 ) or ( TVarData( Res ).VType <> varEmpty )
then
begin
QueryResult := RDOConnection.SendReceive( QueryText, ErrorCode, TimeOut );
if ErrorCode = errNoError
then
begin
ErrorCode := GetQueryErrorCode( QueryResult );
if ( ErrorCode = errNoError ) and ( TVarData( Res ).VType <> varEmpty )
then
begin
VarValue := GetVariableValue( QueryResult, ResultVarName, Error );
if Error
then
begin
ErrorCode := errMalformedResult;
Res := ''
end
else
try
Res := GetVariantFromStr( VarValue );
except
ErrorCode := errIllegalFunctionRes;
Res := ''
end
end;
if TVarData( Params ).VType <> varEmpty
then
begin
BRefParamIdx := 1;
ParamIdx := 1;
while ParamIdx <= ParamCount do
begin
if TVarData( Params[ ParamIdx ] ).VType and varTypeMask = varVariant
then
begin
VarValue := GetVariableValue( QueryResult, ByRefParName + IntToStr( BRefParamIdx ), Error );
if Error
then
ErrorCode := errMalformedResult
else
try
Params[ ParamIdx ] := GetVariantFromStr( VarValue )
except
ErrorCode := errIllegalFunctionRes
end;
inc( BRefParamIdx )
end;
inc( ParamIdx )
end
end
end
end
else
RDOConnection.Send( QueryText )
end
end;
function MarshalObjIdGet( ObjectName : string; RDOConnection : IRDOConnection; TimeOut, Priority : integer; out ErrorCode : integer ) : integer;
var
QueryText : string;
QueryResult : string;
VarValue : string;
Error : boolean;
begin
Result := 0;
if Priority <> THREAD_PRIORITY_NORMAL
then
QueryText := PriorityToPriorityId( Priority ) + Blank
else
QueryText := '';
QueryText := QueryText + IdOfCmd + Blank + LiteralDelim + ObjectName + LiteralDelim + QueryTerm;
QueryResult := RDOConnection.SendReceive( QueryText, ErrorCode, TimeOut );
if ErrorCode = errNoError
then
begin
ErrorCode := GetQueryErrorCode( QueryResult );
if ErrorCode = errNoError
then
begin
VarValue := GetVariableValue( QueryResult, ObjIdVarName, Error );
if not Error
then
try
Result := StrToInt( VarValue )
except
ErrorCode := errMalformedResult
end
else
ErrorCode := errMalformedResult
end
end
end;
end.
|
(*
Challenge 119
TASK #2 - Sequence without 1-on-1
Submitted by: Cheok-Yin Fung
Write a script to generate sequence starting at 1. Consider the increasing
sequence of integers which contain only 1's, 2's and 3's, and do not have any
doublets of 1's like below. Please accept a positive integer $N and print the
$Nth term in the generated sequence.
1, 2, 3, 12, 13, 21, 22, 23, 31, 32, 33, 121, 122, 123, 131, ...
Example
Input: $N = 5
Output: 13
Input: $N = 10
Output: 32
Input: $N = 60
Output: 2223
*)
program ch2(input, output);
uses sysutils;
function nextSeq(n: Integer): Integer;
function numOk(n: Integer): Boolean;
var
lastDigit, digit: Integer;
begin
if n <= 0 then
numOk := False
else begin
numOk := True;
digit := 0;
while n > 0 do begin
lastDigit := digit;
digit := n mod 10;
n := n div 10;
if (digit < 1) or (digit > 3)
or ((digit = 1) and (lastDigit = 1)) then
numOk := False;
end;
end;
end;
begin
repeat
n := n + 1;
until numOk(n);
nextSeq := n;
end;
var
num, i, n: Integer;
begin
num := StrToInt(paramStr(1));
n := 0;
for i := 1 to num do
n := nextSeq(n);
WriteLn(n);
end.
|
program Lab13_Var9;
uses
Crt, Cthreads, Sysutils, Math, Ptcgraph;
type GraphFunc = function(x :Real) :Real;
type GraphInfo = record
w0, w1, h0, h1 :SmallInt; { Graph rectangle }
ymin, ymax :Real;
fromx, tox :Real;
sx, sy :Real; { Scale }
end;
procedure procgraphinfo(
var info :GraphInfo;
w0, w1, h0, h1 :Integer;
ymin, ymax :Real;
fromx, tox :Real);
begin
info.w0 := w0;
info.w1 := w1;
info.h0 := h0;
info.h1 := h1;
info.ymin := ymin;
info.ymax := ymax;
info.fromx := fromx;
info.tox := tox;
info.sx := abs(w1 - w0)/abs(tox - fromx);
info.sy := abs(h1 - h0)/abs(ymax - ymin);
end;
procedure detminmax(
func :GraphFunc;
var ymin :Real; var ymax :Real;
fromx, tox, dx :Real);
var x, y :Real;
begin
x := fromx;
ymin := INFINITY;
ymax := -INFINITY;
while x < tox do
begin
y := func(x);
if y > ymax then
begin
ymax := y;
end;
if y < ymin then
begin
ymin := y;
end;
x := x + dx;
end;
end;
procedure drawgraph(func :GraphFunc; var info :GraphInfo; dx :Real);
var x, y :Real; px0, py0, px1, py1 :Integer; first :Boolean;
begin
x := info.fromx;
first := true;
px0 := 0;
py0 := 0;
while x < info.tox do
begin
y := func(x);
px1 := info.w0 + round(abs(x - info.fromx)*info.sx);
py1 := info.h0 - round(abs(y - info.ymin)*info.sy);
if first then
begin
first := false
end
else
line(px0, py0, px1, py1);
px0 := px1;
py0 := py1;
x := x + dx;
end;
end;
procedure drawdiv(
var info :GraphInfo;
ishoriz :Boolean;
startx, starty :Integer;
divsize, divcount, divprec :Integer);
var ddiv, divpos :Integer;
ddivval, divval, divpow :Extended;
len, i :Integer;
begin
divpow := power(10, divprec);
if ishoriz then
begin
len := abs(info.w1 - info.w0);
divval := round(info.fromx*divpow);
ddivval := round(abs(info.tox - info.fromx)/divcount*divpow);
end
else
begin
len := abs(info.h0 - info.h1);
divval := round(info.ymin*divpow);
ddivval := round(abs(info.ymax - info.ymin)/divcount*divpow);
end;
ddiv := len div divcount;
for i := 0 to divcount do
begin
divpos := i*ddiv;
if ishoriz then
begin
divpos := info.w0 + divpos;
line(divpos, starty + divsize, divpos, starty - divsize);
outtextxy(divpos, starty + round(divsize*1.5), floattostrf(divval/divpow, FFFIXED, divprec, divprec));
end
else
begin
divpos := info.h0 - divpos;
line(startx + divsize, divpos, startx - divsize, divpos);
outtextxy(startx - round(divsize*1.5), divpos, floattostrf(divval/divpow, FFFIXED, divprec, divprec));
end;
divval := divval + ddivval;
end;
end;
procedure drawframe(var info :GraphInfo;
mleft, mright, mtop, mbottom :Integer;
arrowsize :Integer;
divsize, divx, divy, divprec :Integer;
fontsize :Integer);
var startx, starty, topend, rightend :Integer;
begin
startx := info.w0 - mleft;
rightend := info.w1 + mright;
starty := info.h0 + mbottom;
topend := info.h1 - mtop;
settextstyle(DEFAULTFONT, HORIZDIR, fontsize);
{ X axis }
line(startx, starty, rightend, starty);
settextjustify(LEFTTEXT, TOPTEXT);
outtextxy(rightend + 5, starty, 'X');
{ Y axis }
line(startx, starty, startx, topend);
settextjustify(RIGHTTEXT, BOTTOMTEXT);
outtextxy(startx, topend - 5, 'Y');
{ Arrow }
line(startx, topend, startx - arrowsize, topend + arrowsize);
line(startx, topend, startx + arrowsize, topend + arrowsize);
line(rightend, starty, rightend - arrowsize, starty + arrowsize);
line(rightend, starty, rightend - arrowsize, starty - arrowsize);
{=}
{ Division }
settextjustify(RIGHTTEXT, TOPTEXT);
drawdiv(info, true, startx, starty, divsize, divx, divprec);
drawdiv(info, false, startx, starty, divsize, divy, divprec);
{=}
end;
function f1(x :Real) :Real;
begin
f1 := cos(sqrt(x));
end;
function f2(x :Real) :Real;
begin
f2 := tan(sqrt(x));
end;
const w0 = 110; w1 = 950; h0 = 700; h1 = 50; startx = 0.2; endx = 2; dx = 0.001; { Graph }
mleft = 50; mright = 50; mtop = 25; mbottom = 25; arrowsize = 10; divsize = 5; divx = 12;
divy = 18; divprec = 3; fontsize = 1; { Frame }
titlex = 500; titley1 = 30; titley2 = 60; titlefontsize = 2;
var graphics, mode :Integer;
yminf1, ymaxf1, yminf2, ymaxf2, ymin, ymax :Real;
graph :GraphInfo;
begin
graphics := D4BIT;
mode := M1024x768;
initgraph(graphics, mode, '');
setbkcolor(BLACK);
detminmax(@f1, yminf1, ymaxf1, startx, endx, dx);
detminmax(@f2, yminf2, ymaxf2, startx, endx, dx);
writeln('f1 ymin ymax: ', yminf1:0:6, ' ', ymaxf1:0:6);
writeln('f2 ymin ymax: ', yminf2:0:6, ' ', ymaxf2:0:6);
ymin := min(yminf1, yminf2);
ymax := max(ymaxf1, ymaxf2);
writeln('ymin ymax: ', ymin:0:6, ' ', ymax:0:6);
procgraphinfo(graph, w0, w1, h0, h1, ymin, ymax, startx, endx);
setcolor(WHITE);
drawframe(graph, mleft, mright, mtop, mbottom,
arrowsize, divsize, divx, divy, divprec, fontsize);
settextstyle(DEFAULTFONT, HORIZDIR, titlefontsize);
settextjustify(CENTERTEXT, CENTERTEXT);
setlinestyle(SOLIDLN, 0, THICKWIDTH);
setcolor(RED);
drawgraph(@f1, graph, dx);
outtextxy(titlex, titley1, 'f1(x) = cos(sqrt(x))');
setcolor(GREEN);
drawgraph(@f2, graph, dx);
outtextxy(titlex, titley2, 'f2(x) = tan(sqrt(x))');
readkey();
end.
|
unit InputSearchHandlerViewer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, PDTabControl, InfoBook, VisualControls, SHDocVw, CustomWebBrowser,
VoyagerInterfaces, VoyagerServerInterfaces, ObjectInspectorInterfaces,
StdCtrls, VisualClassesHandler, InternationalizerComponent, ComCtrls,
FramedButton;
const
tidHandlerName_ClientFinder = 'ClientFinder';
type
TInputSearchViewer =
class(TVisualControl)
SearchPanel: TPanel;
Panel1: TPanel;
LeftLine: TShape;
eCompany: TEdit;
eTown: TEdit;
Label1: TLabel;
Label3: TLabel;
cbInportWarehouses: TCheckBox;
cbRegWarehouses: TCheckBox;
cbStores: TCheckBox;
cbFactories: TCheckBox;
btnSearch: TFramedButton;
Panel2: TPanel;
lvResults: TListView;
Panel4: TPanel;
fbSelectAll: TFramedButton;
fbUnselectAll: TFramedButton;
fbBuyFrom: TFramedButton;
btnClose: TFramedButton;
Label2: TLabel;
eMaxLinks: TEdit;
InternationalizerComponent1: TInternationalizerComponent;
procedure fbSelectAllClick(Sender: TObject);
procedure fbUnselectAllClick(Sender: TObject);
procedure fbBuyFromClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnSearchClick(Sender: TObject);
procedure lvResultsDeletion(Sender: TObject; Item: TListItem);
procedure lvResultsDblClick(Sender: TObject);
procedure lvResultsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure eMaxLinksKeyPress(Sender: TObject; var Key: Char);
procedure lvResultsColumnClick(Sender: TObject; Column: TListColumn);
procedure lvResultsCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
private
fMasterURLHandler : IMasterURLHandler;
fClientView : IClientView;
fXPos : integer;
fYPos : integer;
fWorld : string;
fFluid : string;
public
property MasterURLHandler : IMasterURLHandler read fMasterURLHandler write fMasterURLHandler;
public
procedure InitViewer(ClientView : IClientView; x, y : integer; world, fluid : string);
private
function GetLinkCoord(const text : string; var p : integer) : TPoint;
procedure RenderResult(const text : string);
public
procedure RenderResults(const fluid, text : string);
private
function GetRoles : integer;
public
property Roles : integer read GetRoles;
Private
{Private Declarations}
SortColumn: Integer;
SortDescending: Boolean;
procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED;
private
procedure threadedOffered( const parms : array of const );
procedure SetParent(which : TWinControl); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
end;
var
InputSearchViewer: TInputSearchViewer;
implementation
uses
CompStringsParser, SpecialChars, ServerCnxEvents, CacheCommon, Literals, Threads, CoolSB;
{$R *.DFM}
procedure TInputSearchViewer.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
sum : integer;
i : integer;
dwStyles : DWORD;
begin
inherited;
if (lvResults <> nil) //and (lvResults.Items <> nil)
then
begin
sum := 0;
for i := 0 to pred(lvResults.Columns.Count-1) do
inc(sum, lvResults.Columns[i].Width);
dwStyles := GetWindowLong(lvResults.Handle, GWL_STYLE);
if (dwStyles and WS_VSCROLL) <> 0
then Inc(sum, GetSystemMetrics(SM_CXVSCROLL));
lvResults.Columns[lvResults.Columns.Count-1].Width := lvResults.Width-sum-2;
end;
end;
procedure TInputSearchViewer.fbSelectAllClick(Sender: TObject);
var
i : integer;
begin
lvResults.SetFocus;
for i := 0 to pred(lvResults.Items.Count) do
lvResults.Items[i].Selected := true;
end;
procedure TInputSearchViewer.fbUnselectAllClick(Sender: TObject);
var
i : integer;
begin
for i := 0 to pred(lvResults.Items.Count) do
lvResults.Items[i].Selected := false;
end;
procedure TInputSearchViewer.fbBuyFromClick(Sender: TObject);
var
Item : TListItem;
i : integer;
pP : PPoint;
aux : string;
url : string;
begin
aux := '';
for i := 0 to pred(lvResults.Items.Count) do
begin
Item := lvResults.Items[i];
if Item.Selected
then
begin
pP := PPoint(lvResults.Items[i].Data);
if pP <> nil
then aux := aux + IntToStr(pP.x) + ',' + IntToStr(pP.y) + ',';
end;
end;
for i := pred(lvResults.Items.Count) to 0 do
begin
Item := lvResults.Items[i];
if Item.Selected
then lvResults.Items.Delete(i);
end;
if aux <> ''
then
begin
url := 'http://local.asp?frame_Id=ObjectInspector&Cnxs=' + aux + '&frame_Action=Connect';
fMasterURLHandler.HandleURL(url);
Fork(threadedOffered, priNormal, [0]);
end;
end;
procedure TInputSearchViewer.btnCloseClick(Sender: TObject);
var
url : string;
begin
url := '?frame_Id=' + tidHandlerName_ClientFinder + '&frame_Close=YES';
fMasterURLHandler.HandleURL(url);
end;
procedure TInputSearchViewer.btnSearchClick(Sender: TObject);
var
url : string;
sum : integer;
i : integer;
begin
lvResults.Items.BeginUpdate;
try
lvResults.Items.Clear;
with lvResults.Items.Add do
begin
Caption := GetLiteral('literal482');
Data := nil;
end;
finally
SetBounds(Left,Top,Width,Height);
lvResults.Items.EndUpdate;
end;
url := '?frame_Id=ObjectInspector' +
'&Fluid=' + fFluid +
'&Owner=' + eCompany.Text +
'&Town=' + eTown.Text +
'&Count=' + eMaxLinks.Text +
'&Roles=' + IntToStr(Roles) +
'&frame_Action=FINDCLIENTS';
fMasterURLHandler.HandleURL(url);
end;
procedure TInputSearchViewer.InitViewer(ClientView : IClientView; x, y : integer; world, fluid : string);
var
keepResults : boolean;
begin
try
keepResults := (fXPos = x) and (fYPos = y) and (fWorld = world) and (fFluid = fluid);
fClientView := ClientView;
fXPos := x;
fYPos := y;
fWorld := world;
fFluid := fluid;
cbInportWarehouses.Checked := true;
cbRegWarehouses.Checked := true;
cbStores.Checked := true;
cbFactories.Checked := true;
eCompany.Text := '';
eTown.Text := '';
if not keepResults
then
begin
lvResults.Items.BeginUpdate;
try
lvResults.Items.Clear;
finally
lvResults.Items.EndUpdate;
end;
end;
except
end;
end;
function TInputSearchViewer.GetLinkCoord(const text : string; var p : integer) : TPoint;
var
aux : string;
begin
FillChar(result, sizeof(result), 0);
aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar);
if aux <> ''
then
begin
result.x := StrToInt(aux);
inc(p);
aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar);
if aux <> ''
then result.y := StrToInt(aux)
else result.y := 0;
end
else result.x := 0;
end;
procedure TInputSearchViewer.RenderResult(const text : string);
var
Item : TListItem;
p : integer;
aux : string;
coord : TPoint;
pt : PPoint;
begin
p := 1;
coord := GetLinkCoord(text, p);
inc(p);
aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar);
if aux <> ''
then
begin
Item := lvResults.Items.Add;
Item.Caption := aux;
new(pt);
pt^ := coord;
Item.Data := pt;
inc(p);
aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar);
while aux <> '' do
begin
Item.SubItems.Add(aux);
aux := CompStringsParser.GetNextStringUpTo(text, p, BackslashChar);
end;
end;
SetBounds(Left,Top,Width,Height);
end;
procedure TInputSearchViewer.RenderResults(const fluid, text : string);
var
List : TStringList;
i : integer;
sum : integer;
begin
if fFluid = fluid
then
begin
lvResults.Items.Clear;
List := TStringList.Create;
try
List.Text := text;
if List.Count = 0
then
with lvResults.Items.Add do
begin
Caption := GetLiteral('Literal70');
Data := nil;
end
else
for i := 0 to pred(List.Count) do
RenderResult(List[i]);
finally
SetBounds(Left,Top,Width,Height);
List.Free;
end;
end;
end;
function TInputSearchViewer.GetRoles : integer;
var
rl : TFacilityRoleSet;
begin
rl := [];
if cbInportWarehouses.Checked
then rl := rl + [rolCompInport]; // result := result or cbExportWarehouses.Tag;
if cbRegWarehouses.Checked
then rl := rl + [rolDistributer]; // result := result or cbRegWarehouses.Tag;
if cbStores.Checked
then rl := rl + [rolBuyer]; // result := result or cbTradeCenter.Tag;
if cbFactories.Checked
then rl := rl + [rolProducer]; // result := result or cbFactories.Tag;
result := byte(rl);
end;
procedure TInputSearchViewer.lvResultsDeletion(Sender: TObject; Item: TListItem);
begin
try
if Item.Data <> nil
then dispose(Item.Data);
finally
Item.Data := nil;
end;
end;
procedure TInputSearchViewer.lvResultsDblClick(Sender: TObject);
begin
fbBuyFromClick(Sender);
end;
procedure TInputSearchViewer.lvResultsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
i : integer;
begin
if Key = VK_DELETE
then
for i := pred(lvResults.Items.Count) downto 0 do
if lvResults.Items[i].Selected
then lvResults.Items.Delete(i);
end;
procedure TInputSearchViewer.eMaxLinksKeyPress(Sender: TObject; var Key: Char);
begin
if not(key in ['0'..'9'])
then Key := #0;
end;
procedure TInputSearchViewer.CMVisibleChanged(var Message: TMessage);
begin // esto era para solucionar el problema de que en algunas maquinas sale arriva y otras veces abajo
// este Frame
// Height := 169;
// Left := 231;
// Width := 796;
// top := 200;
inherited;
end;
procedure TInputSearchViewer.threadedOffered( const parms : array of const );
var
ErrorCode : integer;
begin
try
fClientView.SetCookie('Offered', '1', ErrorCode );
except
end;
end;
procedure TInputSearchViewer.lvResultsColumnClick(Sender: TObject; Column: TListColumn);
begin
with Column do
if SortColumn = Index
then SortDescending := not SortDescending
else
begin
SortDescending := False;
SortColumn := Index
end;
lvResults.AlphaSort;
end;
procedure TInputSearchViewer.lvResultsCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
begin
try
if SortColumn = 0
then Compare := CompareStr(Item1.Caption, Item2.Caption)
else Compare := CompareStr(Item1.SubItems[Pred(SortColumn)], Item2.SubItems[Pred(SortColumn)]);
if SortDescending
then Compare := - Compare;
except
end;
end;
procedure TInputSearchViewer.SetParent(which: TWinControl);
begin
inherited;
if InitSkinImage and (which<>nil)
then
begin
InitializeCoolSB(lvResults.Handle);
if hThemeLib <> 0
then
SetWindowTheme(lvResults.Handle, ' ', ' ');
CoolSBEnableBar(lvResults.Handle, FALSE, TRUE);
CustomizeListViewHeader( lvResults );
end;
end;
end.
|
unit fcOutlookBar;
{
//
// Components : TfcOutlookBar
//
// Copyright (c) 1999 by Woll2Woll Software
//
// 5/12/99 - RSW - Repaint current selection if its a non-rectangular button
}
interface
uses Messages, Windows, Graphics, Classes, Forms, Controls, SysUtils, fcCommon, fcButtonGroup,
ExtCtrls, fcCollection, Dialogs, fcClearPanel, ComCtrls, fcOutlookList, fcImgBtn, fcButton,
fcImager, fcChangeLink, fcShapeBtn;
{$i fcIfDef.pas}
type
TfcOutlookPage = class;
TfcCustomOutlookBar = class;
TfcAnimation = class(TPersistent)
private
FEnabled: Boolean;
FInterval: Integer;
FSteps: Integer;
public
constructor Create;
published
property Enabled: Boolean read FEnabled write FEnabled;
property Interval: Integer read FInterval write FInterval;
property Steps: Integer read FSteps write FSteps;
end;
TfcOutlookPage = class(TfcButtonGroupItem)
private
FPanel: TfcOutlookPanel;
FOutlookList: TfcOutlookList;
protected
function GetOutlookBar: TfcCustomOutlookBar; virtual;
procedure SetIndex(Value: Integer); override;
procedure Loaded; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure CreateOutlookList; virtual;
procedure GotSelected; override;
property OutlookBar: TfcCustomOutlookBar read GetOutlookBar;
property OutlookList: TfcOutlookList read FOutlookList;
property Panel: TfcOutlookPanel read FPanel write FPanel;
end;
TfcOutlookPages = class(TfcButtonGroupItems)
protected
function GetOutlookBar: TfcCustomOutlookBar; virtual;
function GetItems(Index: Integer): TfcOutlookPage;
procedure AnimateSetBounds(Control: TWinControl; Rect: TRect); virtual;
public
constructor Create(AButtonGroup: TfcCustomButtonGroup; ACollectionItemClass: TfcButtonGroupItemClass); override;
procedure ArrangeControls; override;
function Add: TfcOutlookPage;
function AddItem: TfcCollectionItem; override;
property OutlookBar: TfcCustomOutlookBar read GetOutlookBar;
property Items[Index: Integer]: TfcOutlookPage read GetItems; default;
end;
TfcCustomOutlookBarOption = (cboAutoCreateOutlookList, cboTransparentPanels);
TfcCustomOutlookBarOptions = set of TfcCustomOutlookBarOption;
TfcPanelAlignment = (paDynamic, paTop, paBottom);
TfcCustomOutlookBar = class(TfcCustomButtonGroup)
private
// Property Storage Variables
FAnimation: TfcAnimation;
FAnimatingControls: Boolean;
FAnimationLock: Integer;
FButtonSize: Integer;
FImager: TfcCustomImager;
FOptions: TfcCustomOutlookBarOptions;
FPanelAlignment: TfcPanelAlignment;
FShowButtons: Boolean;
FChangeLink: TfcChangeLink;
// Property Access Methods
function GetActivePage: TfcCustomBitBtn;
function GetItems: TfcOutlookPages;
procedure SetActivePage(Value: TfcCustomBitBtn);
procedure SetAnimatingControls(Value: Boolean);
procedure SetButtonSize(Value: Integer);
procedure SetImager(Value: TfcCustomImager);
procedure SetItems(Value: TfcOutlookPages);
procedure SetOptions(Value: TfcCustomOutlookBarOptions); virtual;
procedure SetPanelAlignment(Value: TfcPanelAlignment); virtual;
procedure SetShowButtons(Value: Boolean);
procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE;
procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE;
procedure WMEraseBkgnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND; { 3/12/99 RSW - Need to prevent flicker }
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
protected
function GetCollectionClass: TfcButtonGroupItemsClass; override;
procedure WndProc(var Message: TMessage); override;
// Overridden methods
function ResizeToControl(Control: TControl; DoResize: Boolean): TSize; override;
procedure ButtonPressed(Sender: TObject); override;
procedure CreateWnd; override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure ImagerChange(Sender: TObject);
procedure Loaded; override;
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure Paint; override;
// Overridden property access methods
procedure SetName(const NewName: TComponentName); override;
function IsNonRectangularButton(Control: TControl): boolean; virtual;
public
Patch: Variant;
// InPaste: boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function InAnimation: Boolean; virtual; { Button presses so begin animation, include 1 step }
procedure EnableAnimation;
procedure DisableAnimation;
property ActivePage: TfcCustomBitBtn read GetActivePage write SetActivePage;
property Animation: TfcAnimation read FAnimation write FAnimation;
property AnimatingControls: Boolean read FAnimatingControls write SetAnimatingControls;
property ButtonSize: Integer read FButtonSize write SetButtonSize;
property Canvas;
property Color;
property Imager: TfcCustomImager read FImager write SetImager;
property OutlookItems: TfcOutlookPages read GetItems write SetItems stored False;
property Options: TfcCustomOutlookBarOptions read FOptions write SetOptions;
property PanelAlignment: TfcPanelAlignment read FPanelAlignment write SetPanelAlignment;
property ShowButtons: Boolean read FShowButtons write SetShowButtons;
end;
TfcOutlookBar = class(TfcCustomOutlookBar)
published
{$ifdef fcDelphi4Up}
property Anchors;
property Constraints;
{$endif}
property ActivePage;
property Align;
property Animation;
property AutoBold;
property BevelInner;
property BevelOuter;
property BorderStyle nodefault;
property ButtonSize;
property ButtonClassName;
property Color;
property Font;
property ParentFont;
property Imager;
property OutlookItems;
property Layout;
property Options;
property PanelAlignment;
property ShowButtons;
property TabOrder;
property TabStop default True; //7/30/99 - Support TabStop = False
property Visible;
// property Transparent; { 3/13/99 - RSW - Not supported}
property OnChange;
property OnChanging;
property OnEnter;
property OnExit;
property OnResize;
property OnKeyDown;
property OnKeyUp;
property OnKeyPress;
end;
implementation
constructor TfcAnimation.Create;
begin
inherited;
FEnabled := True;
FInterval := 1;
FSteps := 7;
end;
constructor TfcOutlookPage.Create(Collection: TCollection);
begin
inherited;
if not (csLoading in ButtonGroup.ComponentState) then
begin
ButtonGroup.ButtonItems.ArrangingControls := True;
FPanel := TfcOutlookPanel.Create(ButtonGroup);
// FPanel.Name := fcGenerateName(FPanel.Owner, ButtonGroup.Name + 'Panel');
FPanel.Parent := ButtonGroup;
FPanel.Visible := False;
FPanel.SendToBack;
FPanel.Top := -FPanel.Height - 10;
FPanel.OutlookPage := self;
// FPanel.BevelOuter := bvNone;
if cboAutoCreateOutlookList in OutlookBar.Options then
CreateOutlookList;
ButtonGroup.ButtonItems.ArrangingControls := False;
end;
end;
destructor TfcOutlookPage.Destroy;
begin
OutlookBar.FItems.DeletingControl := True;
FPanel.Free;
OutlookBar.FItems.DeletingControl := False;
inherited;
end;
procedure TfcOutlookPage.SetIndex(Value: Integer);
begin
inherited;
if not (csLoading in ButtonGroup.ComponentState) then OutlookBar.SetChildOrder(Panel, Value);
end;
function TfcOutlookPage.GetOutlookBar: TfcCustomOutlookBar;
begin
result := TfcCustomOutlookBar(ButtonGroup);
end;
procedure TfcOutlookPage.Loaded;
begin
Panel.Owner.RemoveComponent(Panel);
ButtonGroup.InsertComponent(Panel);
Panel.OutlookPage := self;
if FOutlookList <> nil then FOutlookList.OutlookPage := self;
end;
procedure TfcOutlookPage.CreateOutlookList;
begin
if FOutlookList <> nil then Exit;
FOutlookList := TfcOutlookList.Create(GetParentForm(OutlookBar));
with FOutlookList do
begin
Parent := FPanel;
Align := alClient;
BorderStyle := bsNone;
Name := fcGenerateName(GetParentForm(self.OutlookBar), self.OutlookBar.Name + 'OutlookList');
OutlookPage := self;
end;
end;
procedure TfcOutlookPage.GotSelected;
begin
Selected := True;
TfcButtonGroupItems(Collection).ArrangeControls;
end;
constructor TfcOutlookPages.Create(AButtonGroup: TfcCustomButtonGroup; ACollectionItemClass: TfcButtonGroupItemClass);
begin
inherited Create(AButtonGroup, TfcOutlookPage);
end;
function TfcOutlookPages.GetOutlookBar: TfcCustomOutlookBar;
begin
result := TfcCustomOutlookBar(ButtonGroup);
end;
function TfcOutlookPages.GetItems(Index: Integer): TfcOutlookPage;
begin
result := TfcOutlookPage(inherited Items[Index]);
end;
procedure TfcOutlookPages.AnimateSetBounds(Control: TWinControl; Rect: TRect);
begin
if Control is TfcOutlookPanel then
begin
if Control is TfcOutlookPanel then TfcOutlookPanel(Control).FPreventUpdate := True;
Control.BoundsRect := Rect;
if Control is TfcOutlookPanel then TfcOutlookPanel(Control).FPreventUpdate := False;
end else begin
with Rect do SetWindowPos(Control.Handle, 0, Left, Top, Right - Left, Bottom - Top, SWP_NOZORDER or SWP_NOREDRAW);
InvalidateRect(Control.Handle, nil, False);
end;
end;
type TfcOutlookButton = class(TfcCustomBitBtn);
procedure TfcOutlookPages.ArrangeControls;
var i: Integer;
ControlTop: Integer;
List: TList;
Item: TfcGroupAnimateItem;
CurItem: TfcOutlookPage;
PanelHeight: Integer;
OldPanel: TfcOutlookPanel;
OldPanelIndex: integer;
ASteps, AInterval: Integer;
ButtonRect: TRect;
InvalidButton: TWinControl;
//4/15/99 - PYW - Check to see if any child of one of the Outlookpages has a control with the
// align property not set to alNone.
function ChildHasAlignmentSet: boolean;
var alignset:boolean;
i,j:integer;
begin
alignset := False;
for i := 0 to Count - 1 do
with TfcOutlookPage(Items[i]), Panel do
begin
if OutlookList = nil then
begin
for j:=0 to ControlCount - 1 do
begin
if Controls[j].Align <> alNone then begin
alignset := True;
break;
end;
end;
end;
end;
result := alignset;
end;
{ function IsNonRectangularButton(Control: TControl): boolean;
var button: TfcCustomImageBtn;
begin
result:= False;
if (Control is TfcCustomImageBtn) then
begin
button:= TfcCustomImageBtn(control);
if ((Control is TfcCustomShapeBtn) and
((Control as TfcCustomShapeBtn).Shape <> bsRect)) then result:= True
else if (not (Control is TfcCustomShapeBtn) and
(button.TransparentColor <> clNullColor)) then result:= True
end
end;
}
procedure CleanUp;
var i:integer;
begin
ArrangingControls := False;
OutlookBar.AnimatingControls := False;
List.Free;
for i := 0 to Count - 1 do
with TfcOutlookPage(Items[i]) do
if OutlookList <> nil then OutlookList.ScrollButtonsVisible := True;
end;
begin
if ArrangingControls or AddingControls then Exit;
ArrangingControls := True;
// OutlookBar.AnimatingControls := True; { Don't use this flag, RSW }
if OutlookBar.Layout = loVertical then PanelHeight := ButtonGroup.ClientHeight
else PanelHeight := ButtonGroup.ClientWidth;
PanelHeight := PanelHeight - VisibleCount * OutlookBar.ButtonSize;
List := TList.Create;
ControlTop := 0;
if OutlookBar.PanelAlignment = paTop then inc(ControlTop, PanelHeight);
OldPanel := nil;
OldPanelIndex:= -1;
for i := 0 to Count - 1 do
with TfcOutlookPage(Items[i]), Panel do
begin
if OutlookList <> nil then OutlookList.ScrollButtonsVisible := False;
if Visible then begin
OldPanel := TfcOutlookPage(Items[i]).Panel;
OldPanelIndex:= i;
end
else begin
Visible := False;
Top := -Height;
end;
end;
if not OutlookBar.ShowButtons then
begin
if OldPanel <> nil then OldPanel.Visible := False;
if OutlookBar.Selected <> nil then with (OutlookBar.Selected as TfcOutlookPage).Panel do
begin
BoundsRect := OutlookBar.ClientRect;
Visible := True;
end;
CleanUp;
exit;
end;
for i := 0 to VisibleCount - 1 do with OutlookBar do
begin
CurItem := TfcOutlookPage(VisibleItems[i]);
Item := TfcGroupAnimateItem.Create;
Item.MainItem := TfcAnimateListItem.Create;
Item.MainItem.Control := CurItem.Button;
Item.MainItem.OrigRect := CurItem.Button.BoundsRect;
Item.SecondItem := nil;
if Layout = loVertical then
Item.MainItem.FinalRect := Rect(0, ControlTop, ClientWidth, ControlTop + ButtonSize)
else Item.MainItem.FinalRect := Rect(ControlTop, 0, ControlTop + ButtonSize, ClientHeight);
if CurItem.Selected or ((OldPanel <> nil) and (OldPanel = CurItem.Panel)) then
begin
with CurItem.Button.BoundsRect do
if CurItem.Selected then case PanelAlignment of
paDynamic: if Layout = loVertical then CurItem.Panel.BoundsRect := Rect(Left, Bottom, Right, Bottom)
else CurItem.Panel.BoundsRect := Rect(Right, Top, Right, Bottom);
paTop: if Layout = loVertical then CurItem.Panel.BoundsRect := Rect(Left, 0, Right, 0)
else CurItem.Panel.BoundsRect := Rect(0, Top, 0, Bottom);
paBottom: if Layout= loVertical then CurItem.Panel.BoundsRect := Rect(Left, ClientHeight - PanelHeight, Right, ClientHeight - PanelHeight)
else CurItem.Panel.BoundsRect := Rect(ClientWidth - PanelHeight, Top, ClientWidth - PanelHeight, Bottom);
end;
CurItem.Panel.Visible := True;
Item.SecondItem := TfcAnimateListItem.Create;
Item.SecondItem.Control := CurItem.Panel;
Item.SecondItem.OrigRect := CurItem.Panel.BoundsRect;
if CurItem.Selected then
begin
with Item.MainItem.FinalRect do case OutlookBar.PanelAlignment of
paDynamic: begin
if Layout = loVertical then Item.SecondItem.FinalRect := Rect(Left, Bottom, Right, Bottom + PanelHeight)
else Item.SecondItem.FinalRect := Rect(Right, Top, Right + PanelHeight, Bottom);
inc(ControlTop, PanelHeight);
end;
paTop: if Layout = loVertical then Item.SecondItem.FinalRect := Rect(Left, 0, Right, PanelHeight)
else Item.SecondItem.FinalRect := Rect(0, Top, PanelHeight, Bottom);
paBottom: if Layout = loVertical then Item.SecondItem.FinalRect := Rect(Left, OutlookBar.ClientHeight - PanelHeight, Right, OutlookBar.ClientHeight)
else Item.SecondItem.FinalRect := Rect(OutlookBar.ClientWidth - PanelHeight, Top, OutlookBar.ClientWidth, Bottom);
end;
end else with Item.MainItem.FinalRect do begin
if Layout = loVertical then Item.SecondItem.FinalRect := Rect(Left, Bottom, Right, Bottom)
else Item.SecondItem.FinalRect := Rect(Right, Top, Right, Bottom);
end;
end;
inc(ControlTop, OutlookBar.ButtonSize);
List.Add(Item);
end;
ASteps := OutlookBar.Animation.Steps;
AInterval := OutlookBar.Animation.Interval;
//4/15/99 - PYW - Check to see if any child of one of the Outlookpages has a control with the
// align property not set to alNone.
if not OutlookBar.InAnimation or (csDesigning in OutlookBar.ComponentState) or
not OutlookBar.Animation.Enabled or ChildHasAlignmentSet then
begin
OutlookBar.AnimatingControls := False;
ASteps := 1;
AInterval := 0;
end;
for i:= 0 to count-1 do
TfcOutlookButton(Items[i].Button).DisableButton:= True;
fcAnimateControls(OutlookBar, OutlookBar.Canvas, List, AInterval, ASteps, AnimateSetBounds);
if (OldPanel <> nil) and (OutlookBar.Selected <> nil) and ((OutlookBar.Selected as TfcOutlookPage).Panel <> OldPanel) then
begin
OldPanel.Visible := False;
OldPanel.Top := -OutlookBar.Height;
end;
for i := 0 to List.Count - 1 do
with TfcGroupAnimateItem(List[i]) do
begin
if SecondItem <> nil then
begin
{ if SecondItem.Control.Visible then with SecondItem.Control do
begin
for j := 0 to ControlCount - 1 do
if IsNonRectangularButton(Controls[j]) then
begin
r := SecondItem.Control.Controls[j].BoundsRect;
InvalidateRect(SecondItem.Control.Handle, @r, False);
end;
end;}
SecondItem.Free;
end;
MainItem.Free;
Free;
end;
CleanUp;
for i:= 0 to count-1 do
TfcOutlookButton(Items[i].Button).DisableButton:= False;
{ if (ASteps=1) and (Outlookbar.Selected<>nil) and
(OldPanelIndex<OutlookBar.Selected.Index) then
begin
InvalidButton:= OutlookBar.Selected.Button;
if (InvalidButton<>nil) and
OutlookBar.IsNonRectangularButton(InvalidButton) then
begin
ButtonRect:= InvalidButton.BoundsRect;
InvalidateRect(OutlookBar.Handle, @ButtonRect, True);
end
end;
}
{ 5/12/99 - RSW - Clear background for any background area of image shaped buttons,
and execute code even for steps=1 }
{ Repaint current selection if its a non-rectangular button}
if (ASteps>=1) and (OldPanelIndex>=0) and (OutlookBar.Selected<>nil) then
begin
{ This button needs to be repainted if its a shape button }
if OldPanelIndex<OutlookBar.Selected.index then
begin
{ Repaint OldPanelIndex + 1 to Seleccted.Index }
for i:= OldPanelIndex+1 to OutlookBar.Selected.Index do
begin
InvalidButton:= TfcOutlookPage(Items[i]).Button;
if not OutlookBar.IsNonRectangularButton(InvalidButton) then continue;
ButtonRect:= InvalidButton.BoundsRect;
InvalidateRect(OutlookBar.Handle, @ButtonRect, True);
end
end
else begin
{ Repaint SelectedIndex + 1 to OldPanelIndex }
for i:= OutlookBar.Selected.Index+1 to OldPanelIndex do
begin
InvalidButton:= TfcOutlookPage(Items[i]).Button;
if not OutlookBar.IsNonRectangularButton(InvalidButton) then continue;
ButtonRect:= InvalidButton.BoundsRect;
InvalidateRect(OutlookBar.Handle, @ButtonRect, True);
end
end
end
end;
function TfcOutlookPages.Add: TfcOutlookPage;
begin
result := TfcOutlookPage(inherited Add);
if Count = 1 then result.GotSelected;
end;
function TfcOutlookPages.AddItem: TfcCollectionItem;
begin
result := Add;
end;
constructor TfcCustomOutlookBar.Create(AOwner: TComponent);
begin
inherited;
FOptions := [cboAutoCreateOutlookList];
FAnimation := TfcAnimation.Create;
FButtonSize := 20;
FShowButtons := True;
FChangeLink := TfcChangeLink.Create;
FChangeLink.OnChange := ImagerChange;
AutoBold := False;
BorderStyle := bsSingle;
end;
destructor TfcCustomOutlookBar.Destroy;
begin
FAnimation.Free;
FChangeLink.Free;
inherited;
end;
procedure TfcCustomOutlookBar.EnableAnimation;
begin
inc(FAnimationLock);
end;
procedure TfcCustomOutlookBar.DisableAnimation;
begin
dec(FAnimationLock);
end;
function TfcCustomOutlookBar.GetCollectionClass: TfcButtonGroupItemsClass;
begin
result := TfcOutlookPages;
end;
function TfcCustomOutlookBar.ResizeToControl(Control: TControl; DoResize: Boolean): TSize;
begin
result := fcSize(Width, Height);
end;
procedure TfcCustomOutlookBar.ButtonPressed;
begin
EnableAnimation;
if FItems.ArrangingControls then
begin
if OldSelected <> nil then OldSelected.Button.Down := True;
end else inherited;
DisableAnimation;
end;
procedure TfcCustomOutlookBar.CreateWnd;
begin
inherited;
end;
procedure TfcCustomOutlookBar.GetChildren(Proc: TGetChildProc; Root: TComponent);
var i: Integer;
begin
inherited;
for i := 0 to FItems.Count - 1 do
Proc(TfcOutlookPage(FItems[i]).Panel);
end;
procedure TfcCustomOutlookBar.ImagerChange(Sender: TObject);
begin
invalidate;
// inherited;
end;
procedure TfcCustomOutlookBar.Loaded;
var i, j, k: Integer;
begin
for i := 0 to ControlCount - 1 do
if Controls[i] is TfcOutlookPanel then
for j := 0 to FItems.Count - 1 do
if TfcOutlookPage(FItems[j]).Panel = nil then
with TfcOutlookPage(FItems[j]) do
begin
Panel := Controls[i] as TfcOutlookPanel;
for k := 0 to Panel.ControlCount - 1 do
if Panel.Controls[k] is TfcOutlookList then
begin
FOutlookList := Panel.Controls[k] as TfcOutlookList;
Break;
end;
Break;
end;
inherited;
FItems.ArrangingControls := True;
for i := 0 to FItems.Count - 1 do OutlookItems[i].Panel.Visible := False;
FItems.ArrangingControls := False;
FItems.ArrangeControls;
end;
procedure TfcCustomOutlookBar.Notification(AComponent: TComponent; AOperation: TOperation);
var i: Integer;
begin
inherited;
if (AOperation = opRemove) and (AComponent = FImager) then
begin
FImager := nil;
if not (csDestroying in ComponentState) then Invalidate;
end
else if (AOperation = opRemove) and not (csDestroying in ComponentState) then
for i := 0 to FItems.Count - 1 do
if AComponent = OutlookItems[i].OutlookList then
begin
OutlookItems[i].FOutlookList := nil;
Break;
end;
end;
procedure TfcCustomOutlookBar.Paint;
var i, j: Integer;
TmpRgn, ClipRgn: HRGN;
ir, r, r1: TRect;
curPanel: TfcOutlookPanel;
function HaveNonRectangularOutlookButton: boolean;
var i: integer;
begin
result:= False;
for i := 0 to OutlookItems.Count - 1 do
begin
if IsNonRectangularButton(OutlookItems[i].Button) then
begin
result:= True;
break;
end
end
end;
begin
if (OutlookItems.Count = 0) and (Imager = nil) then
begin
inherited;
Exit;
end;
if (FImager <> nil) or
{ 5/2/99 - RSW - Go into this path if contain non-rectangular outlook button
Can likely go into this path even in rectangular case, but this would
require more testing }
HaveNonRectangularOutlookButton then
begin
if not AnimatingControls then
begin
{ Clip out outlookbuttons and visible panel's child controls from imager's area to paint }
ClipRgn := CreateRectRgn(0, 0, 0, 0);
for i := 0 to OutlookItems.Count - 1 do
begin
// 4/19/99 Changed to get button's region, instead of just its rectangle
with OutlookItems[i].Button do
begin
TmpRgn := TfcOutlookButton(OutlookItems[i].Button).CreateRegion(False, Down);
OffsetRgn(TmpRgn, Left, Top);
end;
CombineRgn(ClipRgn, ClipRgn, TmpRgn, RGN_OR);
DeleteObject(TmpRgn);
with OutlookItems[i], Panel do
if Visible then
begin
if FImager=nil then
begin
TmpRgn := CreateRectRgn(Panel.Left, Panel.Top, Panel.Left + Panel.Width, Panel.Top + Panel.Height);
CombineRgn(ClipRgn, ClipRgn, TmpRgn, RGN_OR); { Only paint button area }
DeleteObject(TmpRgn);
end;
fcGetChildRegions(Panel, False, ClipRgn, Point(Left, Top), RGN_OR);
end;
end;
TmpRgn := CreateRectRgn(0, 0, ClientWidth, ClientHeight);
CombineRgn(ClipRgn, TmpRgn, ClipRgn, RGN_DIFF);
DeleteObject(TmpRgn);
SelectClipRgn(Canvas.Handle, ClipRgn);
DeleteObject(ClipRgn); //4/2/99 - Does not seem neccesary
end;
if (FImager <> nil) then
begin
if FImager.WorkBitmap.Empty then FImager.UpdateWorkBitmap;
if FImager.DrawStyle=dsTile then
FImager.WorkBitmap.TileDraw(Canvas, ClientRect)
else
Canvas.StretchDraw(ClientRect, FImager.WorkBitmap);
end
else begin
Canvas.Brush.Color:= Color;
Canvas.FillRect(ClientRect);
end;
SelectClipRgn(Canvas.Handle, 0);
end else if (csDesigning in ComponentState) then inherited;
if (csDesigning in ComponentState) or (csDestroying in ComponentState) or (FItems = nil) then Exit;
// Code in here to prevent the Child controls in the panel from going invisible
// exit;
for i := 0 to FItems.Count - 1 do
if TfcOutlookPage(FItems[i]).Panel.Visible then
begin
with TfcOutlookPage(FItems[i]).Panel do
begin
curPanel:= TfcOutlookPage(FItems[i]).Panel;
for j := 0 to ControlCount - 1 do if Controls[j] is TWinControl then
begin
r := Controls[j].BoundsRect;
offsetRect(r, left, top); { Adjust to outlookbar coordinates }
with self.Canvas.ClipRect do
begin
r1:= self.canvas.cliprect;
if IntersectRect(ir, r1, r) then {or
// if fcRectInRect(r, self.Canvas.ClipRect) then
// if PtInRect(r, TopLeft) or PtInRect(r, BottomRight) or
// PtInRect(r, Point(Right, Top)) or PtInRect(r, Point(Left, Bottom)) then}
begin
IntersectRect(r, self.Canvas.ClipRect, r);
offsetRect(r, -curPanel.left, -curPanel.top); { Adjust to outlookbar coordinates }
offsetRect(r, -Controls[j].BoundsRect.Left, -Controls[j].BoundsRect.top);
InvalidateRect((Controls[j] as TWinControl).Handle, @r, False);
end
end
end;
end;
Break;
end;
end;
function TfcCustomOutlookBar.InAnimation: Boolean;
begin
result := not (FAnimationLock = 0);
end;
function TfcCustomOutlookBar.GetActivePage: TfcCustomBitBtn;
begin
result := nil;
if Selected <> nil then result := Selected.Button;
end;
function TfcCustomOutlookBar.GetItems: TfcOutlookPages;
begin
result := TfcOutlookPages(inherited ButtonItems);
end;
procedure TfcCustomOutlookBar.SetActivePage(Value: TfcCustomBitBtn);
begin
Selected := FItems.FindButton(Value);
end;
procedure TfcCustomOutlookBar.SetAnimatingControls(Value: Boolean);
var i: Integer;
begin
FAnimatingControls := Value;
for i := 0 to OutlookItems.Count - 1 do
OutlookItems[i].Panel.Animating := Value;
end;
procedure TfcCustomOutlookBar.SetButtonSize(Value: Integer);
begin
if FButtonSize <> Value then
begin
FButtonSize := Value;
FItems.ArrangeControls;
end;
end;
procedure TfcCustomOutlookBar.SetImager(Value: TfcCustomImager);
begin
if FImager <> nil then FImager.UnRegisterChanges(FChangeLink);
if Value<>FImager then
begin
FImager := Value;
if Value <> nil then
begin
Value.FreeNotification(self);
Value.RegisterChanges(FChangeLink);
Value.Parent := self;
Value.Align := alNone;
// if Value.DrawStyle <> dsStretch then
Value.DrawStyle := dsTile;
Value.Left:= 0;
Value.Top:= 0;
Value.Width:= 25;
Value.Height:= 25;
Value.Transparent:= False; { 4/30/99 }
Value.Visible := False;
end;
Invalidate; { 4/20/99 RSW }
end
end;
procedure TfcCustomOutlookBar.SetItems(Value: TfcOutlookPages);
begin
inherited ButtonItems := Value;
end;
procedure TfcCustomOutlookBar.SetName(const NewName: TComponentName);
var i: Integer;
begin
for i := 0 to FItems.Count - 1 do
begin
if Copy(OutlookItems[i].Panel.Name, 1, Length(Name)) = Name then
OutlookItems[i].Panel.Name := NewName + fcSubstring(OutlookItems[i].Panel.Name, Length(Name) + 1, 0);
if (cboAutoCreateOutlookList in Options) and
(OutlookItems[i].Panel.ControlCount > 0) and (OutlookItems[i].Panel.Controls[0] is TListView) and
(Copy(OutlookItems[i].Panel.Controls[0].Name, 1, Length(Name)) = Name) then
OutlookItems[i].Panel.Controls[0].Name := NewName + fcSubstring(OutlookItems[i].Panel.Controls[0].Name, Length(Name) + 1, 0);
end;
inherited;
end;
procedure TfcCustomOutlookBar.SetOptions(Value: TfcCustomOutlookBarOptions);
var ChangedOptions: TfcCustomOutlookBarOptions;
begin
if FOptions <> Value then
begin
ChangedOptions := (FOptions - Value) + (Value - FOptions);
FOptions := Value;
{ if not (csLoading in ComponentState) and (cboTransparentPanels in ChangedOptions) then
for i := 0 to FItems.Count - 1 do OutlookItems[i].Panel.Transparent := cboTransparentPanels in FOptions;}
end;
end;
procedure TfcCustomOutlookBar.SetPanelAlignment(Value: TfcPanelAlignment);
begin
if FPanelAlignment <> Value then
begin
FPanelAlignment := Value;
if not (csLoading in ComponentState) then FItems.ArrangeControls;
end;
end;
procedure TfcCustomOutlookBar.SetShowButtons(Value: Boolean);
var i: Integer;
begin
if FShowButtons <> Value then
begin
FShowButtons := Value;
if not (csLoading in ComponentState) then
for i := 0 to FItems.Count - 1 do with FItems[i].Button do
begin
Visible := Value;
if Value then BringToFront else SendToBack;
end;
if not (csLoading in ComponentState) then
begin
FItems.ArrangingControls := False;
FItems.ArrangeControls;
end;
end;
end;
procedure TfcCustomOutlookBar.CMControlListChange(var Message: TCMControlListChange);
begin
inherited;
end;
procedure TfcCustomOutlookBar.CMControlChange(var Message: TCMControlChange);
begin
inherited;
if Message.Control is TfcCustomImager then
begin
if Message.Inserting then
begin
if Imager<>FImager then { RSW }
Imager := Message.Control as TfcCustomImager;
end
else Imager := nil;
end;
end;
{ 3/12/99 - RSW - Prevent flicker }
procedure TfcCustomOutlookBar.WMEraseBkgnd(var Message: TWMEraseBkGnd);
begin
Message.result := 1;
end;
procedure TfcCustomOutlookBar.WMPaint(var Message: TWMPaint);
begin
inherited;
end;
procedure TfcCustomOutlookBar.CMFontChanged(var Message: TMessage);
begin
inherited;
Invalidate; { 4/27/99 }
Update;
end;
function TfcCustomOutlookBar.IsNonRectangularButton(Control: TControl): boolean;
var button: TfcCustomImageBtn;
begin
result:= False;
if (Control is TfcCustomImageBtn) then
begin
button:= TfcCustomImageBtn(control);
if ((Control is TfcCustomShapeBtn) and
((Control as TfcCustomShapeBtn).Shape <> bsRect)) then result:= True
else if (not (Control is TfcCustomShapeBtn) and
(button.TransparentColor <> clNullColor)) then result:= True
end
end;
procedure TfcCustomOutlookBar.WndProc(var Message: TMessage);
begin
inherited;
end;
initialization
RegisterClasses([TfcOutlookPanel]);
end.
|
unit fBackupManagement;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Menus, math, strutils;
type
TfrmBackupManagement = class(TForm)
lvwBackups: TListView;
cmdOK: TButton;
PopupMenu: TPopupMenu;
mnuDelete: TMenuItem;
lblOverallSize: TLabel;
procedure FormShow(Sender: TObject);
procedure mnuDeleteClick(Sender: TObject);
private
procedure PopulateListview;
{ Private declarations }
public
{ Public declarations }
end;
var
frmBackupManagement: TfrmBackupManagement;
implementation
{$R *.dfm}
procedure TfrmBackupManagement.FormShow(Sender: TObject);
begin
PopulateListView;
end;
procedure TfrmBackupManagement.PopulateListview;
var
sr: TSearchRec;
OverallSize : Integer;
begin
lvwBackups.Items.BeginUpdate;
lvwBackups.Items.Clear;
OverallSize := 0;
if FindFirst(ExtractFileDir(Application.ExeName)+ '\Backups\*.zip', faAnyFile, sr) = 0 then
begin
repeat
if Length(sr.Name) = 26 then
begin
with lvwBackups.Items.Add do
begin
// 'MM 01-06-2004 12-59-55.zip'
Caption := Copy(sr.Name,4,10);
SubItems.Add(AnsiReplaceText(Copy(sr.Name,15,8),'-',':'));
SubItems.Add(FloatToStr(SimpleRoundTo(sr.Size / 1024,-2)) + 'kb');
OverallSize := OverallSize + sr.Size;
end;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
lvwBackups.Items.EndUpdate;
lblOverallSize.Caption := 'Overall Size: ' + FloatToStr(SimpleRoundTo(OverallSize / 1024,-2)) + 'kb';
end;
procedure TfrmBackupManagement.mnuDeleteClick(Sender: TObject);
var
Filename : String;
begin
if messagedlg('Do you wish to delete this backup?',mtConfirmation,[mbYes, mbNo],0) = mrYes then
begin
Filename := ExtractFileDir(Application.ExeName) + '\Backups\' + 'MM ' + lvwBackups.Selected.Caption + ' ' + AnsiReplaceText(lvwBackups.Selected.SubItems[0],':','-') + '.zip';
if FileExists(Filename) then
begin
DeleteFile(Filename);
PopulateListview;
end;
end;
end;
end.
|
unit Support.Factory;
interface
uses
SysUtils,
Support,
//General//
Support.Crucial, Support.Liteon, Support.Plextor, Support.Sandisk,
Support.Seagate, Support.Toshiba, Support.Samsung, Support.Sandisk.USB,
Support.MachXtreme, Support.Phison, Support.ADATA, Support.Transcend,
//Sandforce//
Support.Sandforce.Toshiba, Support.Sandforce.Hynix,
Support.Sandforce.OCZ, Support.Sandforce.Patriot,
Support.Sandforce.MachXtreme,
Support.Sandforce.ADATA,
//NVMe//
Support.NVMe.Samsung, Support.NVMe.Intel;
type
TMetaNSTSupport = class of TNSTSupport;
TNSTSupportFactory = class
public
function GetSuitableNSTSupport(const Model, Firmware: String):
TNSTSupport;
private
FModel: String;
FFirmware: String;
function TryNSTSupportAndGetRightNSTSupport: TNSTSupport;
function TestNSTSupportCompatibility(
TNSTSupportToTry: TMetaNSTSupport; LastResult: TNSTSupport): TNSTSupport;
end;
implementation
{ TNSTSupportFactory }
function TNSTSupportFactory.GetSuitableNSTSupport(
const Model, Firmware: String): TNSTSupport;
begin
FModel := Model;
FFirmware := Firmware;
result := TryNSTSupportAndGetRightNSTSupport;
end;
function TNSTSupportFactory.TryNSTSupportAndGetRightNSTSupport: TNSTSupport;
begin
result := nil;
result := TestNSTSupportCompatibility(TCrucialNSTSupport, result);
result := TestNSTSupportCompatibility(TLiteonNSTSupport, result);
result := TestNSTSupportCompatibility(TPlextorNSTSupport, result);
result := TestNSTSupportCompatibility(TSandiskNSTSupport, result);
result := TestNSTSupportCompatibility(TSeagateNSTSupport, result);
result := TestNSTSupportCompatibility(TToshibaNSTSupport, result);
result := TestNSTSupportCompatibility(TTranscendNSTSupport, result);
result := TestNSTSupportCompatibility(TSamsungNSTSupport, result);
result := TestNSTSupportCompatibility(TMachXtremeNSTSupport, result);
result := TestNSTSupportCompatibility(TPhisonNSTSupport, result);
result := TestNSTSupportCompatibility(TADATANSTSupport, result);
result := TestNSTSupportCompatibility(TSandiskUSBNSTSupport, result);
result := TestNSTSupportCompatibility(TToshibaSandforceNSTSupport, result);
result := TestNSTSupportCompatibility(THynixSandforceNSTSupport, result);
result := TestNSTSupportCompatibility(TOCZSandforceNSTSupport, result);
result := TestNSTSupportCompatibility(TPatriotSandforceNSTSupport, result);
result := TestNSTSupportCompatibility(TMachXtremeSandforceNSTSupport, result);
result := TestNSTSupportCompatibility(TADATASandforceNSTSupport, result);
result := TestNSTSupportCompatibility(TSamsungNVMeSupport, result);
result := TestNSTSupportCompatibility(TIntelNVMeSupport, result);
end;
function TNSTSupportFactory.TestNSTSupportCompatibility(
TNSTSupportToTry: TMetaNSTSupport; LastResult: TNSTSupport): TNSTSupport;
begin
if LastResult <> nil then
exit(LastResult);
result := TNSTSupportToTry.Create(FModel, FFirmware);
if not result.GetSupportStatus.Supported then
FreeAndNil(result);
end;
end.
|
unit RestartManager;
{
Basic RestartManager API interface Unit for Delphi 2 and higher
by Martijn Laan
}
{$IFNDEF VER90}
{$IFNDEF VER93}
{$DEFINE Delphi3orHigher}
{$ENDIF}
{$ENDIF}
interface
uses
{$IFNDEF Delphi3orHigher} OLE2, {$ELSE} ActiveX, {$ENDIF}
Windows;
procedure FreeRestartManagerLibrary;
function InitRestartManagerLibrary: Boolean;
function UseRestartManager: Boolean;
const
RM_SESSION_KEY_LEN = SizeOf(TGUID);
CCH_RM_SESSION_KEY = RM_SESSION_KEY_LEN*2;
CCH_RM_MAX_APP_NAME = 255;
CCH_RM_MAX_SVC_NAME = 63;
RM_INVALID_TS_SESSION = -1;
RM_INVALID_PROCESS = -1;
type
RM_APP_TYPE = DWORD;
const
RmUnknownApp = 0;
RmMainWindow = 1;
RmOtherWindow = 2;
RmService = 3;
RmExplorer = 4;
RmConsole = 5;
RmCritical = 1000;
type
RM_SHUTDOWN_TYPE = DWORD;
const
RmForceShutdown = $01;
RmShutdownOnlyRegistered = $10;
//RM_APP_STATUS
type
RM_REBOOT_REASON = DWORD;
const
RmRebootReasonNone = $0;
RmRebootReasonPermissionDenied = $1;
RmRebootReasonSessionMismatch = $2;
RmRebootReasonCriticalProcess = $4;
RmRebootReasonCriticalService = $8;
RmRebootReasonDetectedSelf = $10;
type
RM_UNIQUE_PROCESS = record
dwProcessId: DWORD;
ProcessStartTime: TFileTime;
end;
RM_PROCESS_INFO = record
Process: RM_UNIQUE_PROCESS;
strAppName: array[0..CCH_RM_MAX_APP_NAME] of WideChar;
strServiceShortName: array[0..CCH_RM_MAX_SVC_NAME] of WideChar;
ApplicationType: RM_APP_TYPE;
AppStatus: ULONG;
TSSessionId: DWORD;
bRestartable: BOOL;
end;
//RM_FILTER_TRIGGER
//RM_FILTER_ACTION
//RM_FILTER_INFO
//RM_WRITE_STATUS_CALLBACK
var
RmStartSession: function (pSessionHandle: LPDWORD; dwSessionFlags: DWORD; strSessionKey: LPWSTR): DWORD; stdcall;
RmRegisterResources: function (dwSessionHandle: DWORD; nFiles: UINT; rgsFilenames: Pointer; nApplications: UINT; rgApplications: Pointer; nServices: UINT; rgsServiceNames: Pointer): DWORD; stdcall;
RmGetList: function (dwSessionHandle: DWORD; pnProcInfoNeeded, pnProcInfo: PUINT; rgAffectedApps: Pointer; lpdwRebootReasons: LPDWORD): DWORD; stdcall;
RmShutdown: function (dwSessionHandle: DWORD; lActionFlags: ULONG; fnStatus: Pointer): DWORD; stdcall;
RmRestart: function (dwSessionHandle: DWORD; dwRestartFlags: DWORD; fnStatus: Pointer): DWORD; stdcall;
RmEndSession: function (dwSessionHandle: DWORD): DWORD; stdcall;
implementation
//----------------------------------------------------------------------------------------------------------------------
const
restartmanagerlib = 'Rstrtmgr.dll';
var
RestartManagerLibrary: THandle;
ReferenceCount: Integer; // We have to keep track of several load/unload calls.
procedure FreeRestartManagerLibrary;
begin
if ReferenceCount > 0 then
Dec(ReferenceCount);
if (RestartManagerLibrary <> 0) and (ReferenceCount = 0) then
begin
FreeLibrary(RestartManagerLibrary);
RestartManagerLibrary := 0;
RmStartSession := nil;
RmRegisterResources := nil;
RmGetList := nil;
RmShutdown := nil;
RmRestart := nil;
RmEndSession := nil;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function InitRestartManagerLibrary: Boolean;
begin
Inc(ReferenceCount);
{ Only attempt to load rstrtmgr.dll if running Windows Vista or later }
if (RestartManagerLibrary = 0) and (Lo(GetVersion) >= 6) then
begin
RestartManagerLibrary := LoadLibrary(restartmanagerlib);
if RestartManagerLibrary <> 0 then
begin
RmStartSession := GetProcAddress(RestartManagerLibrary, 'RmStartSession');
RmRegisterResources := GetProcAddress(RestartManagerLibrary, 'RmRegisterResources');
RmGetList := GetProcAddress(RestartManagerLibrary, 'RmGetList');
RmShutdown := GetProcAddress(RestartManagerLibrary, 'RmShutdown');
RmRestart := GetProcAddress(RestartManagerLibrary, 'RmRestart');
RmEndSession := GetProcAddress(RestartManagerLibrary, 'RmEndSession');
end;
end;
Result := RestartManagerLibrary <> 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function UseRestartManager: Boolean;
begin
Result := RestartManagerLibrary <> 0;
end;
//----------------------------------------------------------------------------------------------------------------------
initialization
finalization
while ReferenceCount > 0 do
FreeRestartManagerLibrary;
end.
|
{ Subroutine SST_R_PAS_VARIABLE (VAR_P)
*
* Process VARIABLE syntax. The result is compiled into a VAR descriptor, and
* VAR_P is returned pointing to it.
}
module sst_r_pas_VARIABLE;
define sst_r_pas_variable;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_variable ( {process VARIABLE syntax}
out var_p: sst_var_p_t); {returned pointer to VAR descriptor}
const
max_msg_parms = 2; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {syntax tag ID}
str_h: syo_string_t; {handle to string associated with TAG}
str2_h: syo_string_t; {saved copy of STR_H}
mod_p: sst_var_mod_p_t; {points to current modifier descriptor}
name: string_var80_t; {scratch field name}
dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor}
dt_base_p: sst_dtype_p_t; {points to base accumulated dtype descriptor}
mod_allowed: boolean; {TRUE if modifiers may be allowed}
first: boolean; {TRUE if working on first array subscript}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {completion status code}
label
next_mod, loop_subscr;
begin
name.max := sizeof(name.str); {init local var string}
sst_mem_alloc_namesp ( {allocate memory for root variable descriptor}
sizeof(var_p^), var_p);
syo_level_down; {down into VARIABLE syntax level}
syo_get_tag_msg ( {get tag for top level variable name}
tag, str_h, 'sst_pas_read', 'symbol_syntax_bad', nil, 0);
if tag <> 1 then syo_error_tag_unexp (tag, str_h);
sst_symbol_lookup (str_h, var_p^.mod1.top_sym_p, stat); {get pointer to symbol descr}
syo_error_abort (stat, str_h, '', '', nil, 0);
var_p^.mod1.next_p := nil; {init to no following modifiers}
var_p^.mod1.modtyp := sst_var_modtyp_top_k; {indicate this is top level name}
var_p^.mod1.top_str_h := str_h; {save string handle to top level symbol name}
var_p^.dtype_p := nil; {init to data type does not apply here}
var_p^.rwflag := []; {init to not allowed to read or write var}
mod_allowed := false; {init to no modifiers allowed to top name}
with var_p^.mod1.top_sym_p^: sym do begin {SYM is symbol for top level name}
case sym.symtype of {what kind of symbol is top level name ?}
sst_symtype_const_k: begin {top symbol is a named constant}
var_p^.dtype_p := sym.const_exp_p^.dtype_p;
var_p^.rwflag := [sst_rwflag_read_k];
var_p^.vtype := sst_vtype_const_k;
var_p^.const_val_p := addr(sym.const_exp_p^.val);
end;
sst_symtype_enum_k: begin {top symbol is enumerated constant name}
var_p^.dtype_p := sym.enum_dtype_p;
var_p^.rwflag := [sst_rwflag_read_k];
var_p^.vtype := sst_vtype_const_k;
sst_mem_alloc_scope ( {allocate mem for constant value descriptor}
sizeof(var_p^.const_val_p^), var_p^.const_val_p);
var_p^.const_val_p^.dtype := sst_dtype_enum_k;
var_p^.const_val_p^.enum_p := addr(sym);
end;
sst_symtype_dtype_k: begin {top symbol is name of a data type}
var_p^.dtype_p := sym.dtype_dtype_p;
var_p^.vtype := sst_vtype_dtype_k;
mod_allowed := true;
end;
sst_symtype_var_k: begin {top symbol is simple variable name}
var_p^.dtype_p := sym.var_dtype_p;
if sym.var_proc_p = nil
then begin {symbol is not dummy arg or func return val}
var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
end
else begin {symbol is related to a routine}
if sym.var_arg_p = nil
then begin {symbol is "variable" for stuffing func val}
var_p^.rwflag := [sst_rwflag_write_k]; {access is write-only}
end
else begin {symbol is a dummy argument}
var_p^.rwflag := sym.var_arg_p^.rwflag_ext;
if sst_rwflag_write_k in var_p^.rwflag then begin {declared at least OUT}
var_p^.rwflag := {allow writing to OUT dummy arguments}
var_p^.rwflag + [sst_rwflag_read_k];
end;
end
;
end
;
var_p^.vtype := sst_vtype_var_k;
mod_allowed := true;
end;
sst_symtype_abbrev_k: begin {top symbol is an abbreviation}
var_p^.dtype_p := sym.abbrev_var_p^.dtype_p;
var_p^.rwflag := sym.abbrev_var_p^.rwflag;
var_p^.vtype := sym.abbrev_var_p^.vtype;
case sym.abbrev_var_p^.vtype of {what type of "var" is being abbreviated ?}
sst_vtype_var_k: begin
mod_allowed := true;
end;
sst_vtype_dtype_k: begin
mod_allowed := true;
end;
sst_vtype_rout_k: begin
var_p^.rout_proc_p := sym.abbrev_var_p^.rout_proc_p;
end;
sst_vtype_const_k: begin
var_p^.const_val_p := sym.abbrev_var_p^.const_val_p;
end;
otherwise
sys_msg_parm_int (msg_parm[1], ord(sym.abbrev_var_p^.vtype));
sys_message_bomb ('sst', 'vtype_unexpected', msg_parm, 1);
end;
end;
sst_symtype_proc_k: begin {top symbol is routine name}
if (sym.proc.dtype_func_p = nil) or addr_of
then begin {var refers to routine directly}
var_p^.dtype_p := sym.proc_dtype_p;
var_p^.rwflag := [];
end
else begin {var refers to value returned by function}
var_p^.dtype_p := sym.proc.dtype_func_p;
var_p^.rwflag := [sst_rwflag_read_k];
end
;
var_p^.vtype := sst_vtype_rout_k;
var_p^.rout_proc_p := addr(sym.proc);
end;
sst_symtype_com_k: begin {top symbol is common block name}
var_p^.dtype_p := nil;
var_p^.vtype := sst_vtype_com_k;
end;
otherwise {illegal symbol type for this usage}
sys_msg_parm_vstr (msg_parm[1], sym.name_in_p^);
syo_error (str_h, 'sst_pas_read', 'symbol_bad_type', msg_parm, 1);
end; {end of symbol type cases}
end; {done with SYM abbreviation}
mod_p := addr(var_p^.mod1); {init pointer to current modifier block}
{
* Jump back here for each new modifier to the exising variable descriptor.
* VAR_P points to the top variable descriptor, and MOD_P points to the last
* modifier descriptor.
}
next_mod:
dt_base_p := var_p^.dtype_p; {init pointer to base data type descriptor}
if dt_base_p <> nil then begin {pointing to a data type block ?}
while dt_base_p^.dtype = sst_dtype_copy_k do begin {pointing to a copy ?}
dt_base_p := dt_base_p^.copy_dtype_p; {point to copied data type}
end; {back and check for for copy again}
end; {VAR_P^.DTYPE_P all set}
if {variable has become procedure ?}
(var_p^.vtype = sst_vtype_var_k) and {is a variable ?}
(dt_base_p^.dtype = sst_dtype_proc_k) {data type is procedure ?}
then begin
var_p^.vtype := sst_vtype_rout_k; {var descriptor now stands for routine}
var_p^.rout_proc_p := dt_base_p^.proc_p; {get pointer to routine descriptor}
if var_p^.rout_proc_p^.dtype_func_p = nil
then begin {routine is a function}
var_p^.rwflag := [sst_rwflag_read_k];
end
else begin {routine is not a function}
var_p^.rwflag := [];
end
;
mod_allowed := false; {no further modifiers allowed now}
end;
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'symbol_syntax_bad', nil, 0);
if tag = syo_tag_end_k then begin {done processing VARIABLE syntax ?}
syo_level_up; {back up from VARIABLE syntax}
return;
end;
sst_mem_alloc_namesp (sizeof(mod_p^.next_p^), mod_p^.next_p); {get mem for new mod}
mod_p := mod_p^.next_p; {make new modifier the current modifier}
with mod_p^: modf do begin {MODF is abbreviation for this modifier}
modf.next_p := nil; {this modifier is now new end of chain}
case tag of
{
* Tag is for field name of record.
}
1: begin
if {parent not a record ?}
(not mod_allowed) or
(dt_base_p^.dtype <> sst_dtype_rec_k)
then begin
syo_error (str_h, 'sst_pas_read', 'parent_not_record', nil, 0);
end;
syo_get_tag_string (str_h, name); {get field name}
string_downcase (name); {make lower case for name matching}
modf.modtyp := sst_var_modtyp_field_k; {set type for this modifier}
modf.field_str_h := str_h; {save handle to source file characters}
modf.field_sym_p := dt_base_p^.rec_first_p; {init to first field in chain}
while not string_equal(modf.field_sym_p^.name_in_p^, name) do begin {not this sym ?}
modf.field_sym_p := modf.field_sym_p^.field_next_p; {to next field in chain}
if modf.field_sym_p = nil then begin {hit end of field names chain ?}
sys_msg_parm_vstr (msg_parm[1], name);
sys_msg_parm_vstr (msg_parm[2], dt_base_p^.symbol_p^.name_in_p^);
syo_error (str_h, 'sst_pas_read', 'field_name_not_found', msg_parm, 2);
end;
end; {back and check for found named field}
var_p^.dtype_p := modf.field_sym_p^.field_dtype_p; {update new data type so far}
end;
{
* Tag indicates pointer dereference.
}
2: begin
if {parent not a pointer ?}
(not mod_allowed) or
(dt_base_p^.dtype <> sst_dtype_pnt_k)
then begin
syo_error (str_h, 'sst_pas_read', 'symbol_not_pointer', nil, 0);
end;
if dt_base_p^.pnt_dtype_p = nil then begin
syo_error (str_h, 'sst_pas_read', 'pointer_dereference_bad', nil, 0);
end;
modf.modtyp := sst_var_modtyp_unpnt_k; {this modifier is pointer dereference}
case var_p^.vtype of {what kind of "variable" do we have ?}
sst_vtype_var_k: begin {regular variable}
if sst_rwflag_read_k in var_p^.rwflag
then begin {pointer is readable}
var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
end
else begin
var_p^.rwflag := []; {can't touch data thru non-readable pointer}
end
;
end;
sst_vtype_dtype_k: ;
otherwise
sys_msg_parm_int (msg_parm[1], ord(var_p^.vtype));
syo_error (str_h, 'sst', 'vtype_unexpected', msg_parm, 1);
end;
var_p^.dtype_p := dt_base_p^.pnt_dtype_p; {data type of dereferenced pointer}
end;
{
* Tag indicates a new array subscript.
}
3: begin
if {parent not an array ?}
(not mod_allowed) or
(dt_base_p^.dtype <> sst_dtype_array_k)
then begin
syo_error (str_h, 'sst_pas_read', 'symbol_not_array', nil, 0);
end;
first := true; {init to next subscript if first in array}
dt_p := dt_base_p; {init to "rest" of array is whole array}
syo_level_down; {down into ARRAY_SUBSCRIPTS syntax}
str2_h := str_h; {save string handle to all the subscripts}
loop_subscr: {back here for each new ARRAY_SUBSCRIPTS tag}
syo_get_tag_msg ( {get tag for next subscript expression}
tag, str_h, 'sst_pas_read', 'symbol_syntax_bad', nil, 0);
case tag of
1: begin {tag is for another subscript}
if dt_p = nil then begin {too many subscripts ?}
sys_msg_parm_int (msg_parm[1], dt_base_p^.ar_n_subscr);
syo_error (str2_h, 'sst_pas_read', 'subscripts_too_many', msg_parm, 1);
end;
if not first then begin {not first subscript in this array ?}
sst_mem_alloc_scope ( {grab memory for this new var modifier}
sizeof(mod_p^.next_p^), mod_p^.next_p);
mod_p := mod_p^.next_p; {make new modifier the current modifier}
mod_p^.next_p := nil; {init to this is last modifier in chain}
end;
mod_p^.modtyp := sst_var_modtyp_subscr_k; {this modifier is for a subscript}
mod_p^.subscr_first := first; {set first/subsequent subscript in array flag}
first := false; {next subscript will no longer be the first}
sst_r_pas_exp ( {get subscript expression value}
str_h, false, mod_p^.subscr_exp_p);
sst_exp_useage_check ( {check expression attributes for this useage}
mod_p^.subscr_exp_p^, {expression to check}
[sst_rwflag_read_k], {read/write access needed to expression value}
dt_base_p^.ar_ind_first_p^.dtype_p^); {data type value must be compatible with}
dt_p := dt_p^.ar_dtype_rem_p; {point to data type for "rest" of array}
mod_p^.subscr_last := dt_p = nil; {TRUE if this is last subscript in array}
goto loop_subscr; {back for next ARRAY_SUBSCRIPTS syntax tag}
end;
syo_tag_end_k: begin {tag is end of ARRAY_SUBSCRIPTS syntax}
syo_level_up; {back up from ARRAY_SUBSCRIPTS syntax}
if dt_p <> nil then begin {no more subscripts, but not end of array ?}
sys_msg_parm_int (msg_parm[1], dt_base_p^.ar_n_subscr);
syo_error (str2_h, 'sst_pas_read', 'subscripts_too_few', msg_parm, 1);
end;
var_p^.dtype_p := dt_base_p^.ar_dtype_ele_p; {dtype is now array elements}
end;
otherwise {unexpected syntax tag value}
syo_error_tag_unexp (tag, str_h);
end; {end of ARRAY_SUBSCRIPTS tag cases}
end;
{
* Unexpected tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of tag cases}
goto next_mod; {back for new tag with new data type block}
end; {done with MODF abbreviation}
end;
|
unit Unit_Example_Data;
interface
uses
{System.}UITypes, Tee.Grid.Data;
type
TVehicle=(None,Bicycle,MotorBike,Car,Caravan,Truck,Boat,Plane);
TPerson=record
public
ID : Integer;
Name : String;
Height : Single;
BirthDate : TDateTime;
Vehicle : TVehicle;
EyeColor : TColor;
Happiness : Double;
Holidays : Boolean;
end;
function SampleData:TVirtualData;
implementation
uses
Tee.Grid.Data.Rtti, {System.}SysUtils;
var
Persons : TArray<TPerson>;
procedure RandomPerson(var APerson:TPerson);
const
RandomNames:Array[0..4] of String=('John','Anne','Paul','Mary','Mike');
RandomColors:Array[0..3] of TColor=(TColors.Black,TColors.Brown,TColors.Green,TColors.Blue);
begin
APerson.Name:=RandomNames[Random(High(RandomNames))];
APerson.Height:=5+(Random(100)*0.01);
APerson.BirthDate:=EncodeDate(1930+Random(80),1+Random(12),1+Random(28));
APerson.Vehicle:=TVehicle(Random(Ord(High(TVehicle))));
APerson.EyeColor:=RandomColors[Random(High(RandomColors))];
APerson.Happiness:=Random(100)*0.01;
APerson.Holidays:=Random(100)<50;
end;
procedure CreatePersons;
var t : Integer;
begin
SetLength(Persons,10);
for t:=0 to High(Persons) do
begin
Persons[t].ID:=100+t;
RandomPerson(Persons[t]);
end;
end;
function SampleData:TVirtualData;
begin
CreatePersons;
result:=TVirtualArrayData<TPerson>.Create(Persons);
end;
end.
|
unit l3BaseRefInterfacedList;
{* Список Tl3Base с интерфейсным представлением }
// Модуль: "w:\common\components\rtl\Garant\L3\l3BaseRefInterfacedList.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tl3BaseRefInterfacedList" MUID: (4A6D66010286)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3ProtoDataContainer
, l3ProtoObject
, l3Memory
, l3Types
, l3Interfaces
, l3Core
, l3Except
, Classes
, l3PureMixIns
;
type
//_ItemType_ = Tl3ProtoObject;
Il3CBaseList = interface
['{08465E92-C901-4CD1-81C0-9927BCCA72F1}']
function pm_GetEmpty: Boolean;
function pm_GetFirst: Tl3ProtoObject;
function pm_GetLast: Tl3ProtoObject;
function pm_GetItems(anIndex: Integer): Tl3ProtoObject;
function pm_GetCount: Integer;
property Empty: Boolean
read pm_GetEmpty;
property First: Tl3ProtoObject
read pm_GetFirst;
{* Первый элемент. }
property Last: Tl3ProtoObject
read pm_GetLast;
{* Последний элемент. }
property Items[anIndex: Integer]: Tl3ProtoObject
read pm_GetItems;
default;
property Count: Integer
read pm_GetCount;
{* Число элементов. }
end;//Il3CBaseList
{$Define l3Items_NeedsSort}
_ItemType_ = Tl3ProtoObject;
_l3UncomparabeObjectRefList_Parent_ = Tl3ProtoDataContainer;
{$Define l3Items_IsProto}
{$Include w:\common\components\rtl\Garant\L3\l3UncomparabeObjectRefList.imp.pas}
Tl3BaseRefInterfacedList = class(_l3UncomparabeObjectRefList_, Il3CBaseList)
{* Список Tl3Base с интерфейсным представлением }
protected
function pm_GetCount: Integer;
procedure InitFields; override;
public
class function MakeI: Il3CBaseList; reintroduce;
end;//Tl3BaseRefInterfacedList
implementation
uses
l3ImplUses
, l3Base
, l3MinMax
, RTLConsts
, SysUtils
//#UC START# *4A6D66010286impl_uses*
//#UC END# *4A6D66010286impl_uses*
;
function CompareExistingItems(const CI: CompareItemsRec): Integer; forward;
{$If Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)}
procedure AssignItem(const aTo: Tl3ProtoObject;
const aFrom: Tl3ProtoObject);
//#UC START# *47B2C42A0163_4A6D66010286_var*
//#UC END# *47B2C42A0163_4A6D66010286_var*
begin
//#UC START# *47B2C42A0163_4A6D66010286_impl*
Assert(false);
//#UC END# *47B2C42A0163_4A6D66010286_impl*
end;//AssignItem
{$IfEnd} // Defined(l3Items_NeedsAssignItem) AND NOT Defined(l3Items_NoSort)
function CompareExistingItems(const CI: CompareItemsRec): Integer;
{* Сравнивает два существующих элемента. }
//#UC START# *47B99D4503A2_4A6D66010286_var*
//#UC END# *47B99D4503A2_4A6D66010286_var*
begin
//#UC START# *47B99D4503A2_4A6D66010286_impl*
{$IfDef l3Items_HasCustomSort}
Assert(CI.rSortIndex = l3_siNative);
{$EndIf l3Items_HasCustomSort}
Result := Integer(CI.rA^) - Integer(CI.rB^);
//#UC END# *47B99D4503A2_4A6D66010286_impl*
end;//CompareExistingItems
type _Instance_R_ = Tl3BaseRefInterfacedList;
{$Include w:\common\components\rtl\Garant\L3\l3UncomparabeObjectRefList.imp.pas}
class function Tl3BaseRefInterfacedList.MakeI: Il3CBaseList;
var
l_Inst : Tl3BaseRefInterfacedList;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//Tl3BaseRefInterfacedList.MakeI
function Tl3BaseRefInterfacedList.pm_GetCount: Integer;
//#UC START# *4BB08B8902F2_4A6D66010286get_var*
//#UC END# *4BB08B8902F2_4A6D66010286get_var*
begin
//#UC START# *4BB08B8902F2_4A6D66010286get_impl*
Result := Count;
//#UC END# *4BB08B8902F2_4A6D66010286get_impl*
end;//Tl3BaseRefInterfacedList.pm_GetCount
procedure Tl3BaseRefInterfacedList.InitFields;
//#UC START# *47A042E100E2_4A6D66010286_var*
//#UC END# *47A042E100E2_4A6D66010286_var*
begin
//#UC START# *47A042E100E2_4A6D66010286_impl*
inherited;
Sorted := true;
//#UC END# *47A042E100E2_4A6D66010286_impl*
end;//Tl3BaseRefInterfacedList.InitFields
end.
|
unit MdiChilds.UnloadResourcesFromBase;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, JvComponentBase,
JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, GsDocument,
JvBaseDlg, JvSelectDirectory, MdiChilds.Reg, ActionHandler;
type
TDocuments = array [TGsResourceKind] of TGsDocument;
TFmUnloadResources = class(TFmProcess)
lbFiles: TListBox;
rgOptions: TRadioGroup;
chkMachines: TCheckBox;
chkMaterials: TCheckBox;
chkWorkers: TCheckBox;
chkMachinist: TCheckBox;
JvDragDrop: TJvDragDrop;
edtOutDir: TLabeledEdit;
btnSelectDir: TButton;
JvSelectDirectory: TJvSelectDirectory;
procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
procedure btnSelectDirClick(Sender: TObject);
private
FResources: set of TGsResourceKind;
procedure ExtractResources(Source: TGsDocument; Documents: TDocuments);
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean); override;
class function GetDataProcessorKind: TDataProcessorKind; override;
procedure BeforeExecute; override;
procedure AfterExecute; override;
public
{ Public declarations }
end;
TUnloadResourcesActionHandler = class (TAbstractActionHandler)
public
procedure ExecuteAction(UserData: Pointer = nil); override;
end;
var
FmUnloadResources: TFmUnloadResources;
Documents: TDocuments;
const
DocNames: array [TGsResourceKind] of string =
('Материалы.xml',
'Рабочие.xml',
'Машинисты.xml',
'Механизмы.xml'
);
implementation
{$R *.dfm}
procedure TFmUnloadResources.AfterExecute;
var
I: TGsResourceKind;
begin
for I := Low(TGsResourceKind) to High(TGsResourceKind) do
if Documents[I] <> nil then
begin
Documents[I].SaveToFile(edtOutDir.Text + DocNames[I]);
Documents[I].Free;
end;
end;
procedure TFmUnloadResources.BeforeExecute;
var
Chapter: TGsChapter;
begin
if not DirectoryExists(edtOutDir.Text) then
raise Exception.CreateFmt('Путь %s не найден',[edtOutDir.Text]);
FResources := [];
if chkMachines.Checked then
begin
FResources := FResources + [GsDocument.rkMashine];
Documents[rkMashine] := NewGsDocument;
Documents[rkMashine].DocumentType := dtBaseData;
Documents[rkMashine].BaseDataType := bdtMachine;
Documents[rkMashine].TypeName := 'ТСЭМ';
Chapter := Documents[rkMashine].CreateChapter(Documents[rkMashine].Chapters);
Chapter.Caption := 'Машины и механизмы';
end;
if chkMaterials.Checked then
begin
FResources := FResources + [GsDocument.rkMaterial];
Documents[rkMaterial] := NewGsDocument;
Documents[rkMaterial].DocumentType := dtBaseData;
Documents[rkMaterial].BaseDataType := bdtMaterial;
Documents[rkMaterial].TypeName := 'ТССЦ';
Chapter := Documents[rkMaterial].CreateChapter(Documents[rkMaterial].Chapters);
Chapter.Caption := 'Материалы';
end;
if chkWorkers.Checked then
begin
FResources := FResources + [GsDocument.rkWorker];
Documents[rkWorker] := NewGsDocument;
Documents[rkWorker].DocumentType := dtBaseData;
Documents[rkWorker].BaseDataType := bdtWorkerScale;
Documents[rkWorker].TypeName := 'ТС';
Chapter := Documents[rkWorker].CreateChapter(Documents[rkWorker].Chapters);
Chapter.Caption := 'Рабочие';
end;
if chkMachinist.Checked then
begin
FResources := FResources + [GsDocument.rkMashinist];
Documents[rkMashinist] := NewGsDocument;
Documents[rkMashinist].DocumentType := dtBaseData;
Documents[rkMashinist].BaseDataType := bdtWorkerScale;
Documents[rkMashinist].TypeName := '';
Chapter := Documents[rkMashinist].CreateChapter(Documents[rkMashinist].Chapters);
Chapter.Caption := 'Машинисты';
end;
end;
procedure TFmUnloadResources.btnSelectDirClick(Sender: TObject);
begin
if JvSelectDirectory.Execute then
edtOutDir.Text := IncludeTrailingPathDelimiter(JvSelectDirectory.Directory);
end;
procedure TFmUnloadResources.DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean);
var
I: Integer;
D: TGsDocument;
begin
ProgressForm.InitPB(lbFiles.Count);
ProgressForm.Show;
ShowMessage := True;
for I := 0 to lbFiles.Count - 1 do
begin
D := TGsDocument.Create;
try
D.LoadFromFile(lbFiles.Items[I]);
ExtractResources(D, Documents);
finally
D.Free;
end;
ProgressForm.StepIt(ExtractFileName(lbFiles.Items[I]));
end;
end;
procedure TFmUnloadResources.ExtractResources(Source: TGsDocument; Documents: TDocuments);
var
L: TList;
J: TGsCostKind;
I: Integer;
Resource: TGsResource;
TargetDocument: TGsDocument;
Chapter: TGsChapter;
Item: TGsRow;
begin
L := TList.Create;
try
Source.ResourceBulletin.EnumItems(L, TGsResource, True);
for I := 0 to L.Count - 1 do
begin
Resource := TGsResource(L[I]);
if (Resource.Kind in FResources) and (Documents[Resource.Kind] <> nil) then
begin
TargetDocument := Documents[Resource.Kind];
Chapter := TargetDocument.Chapters.Items[0] as TGsChapter;
Item := Chapter.ItemByAttribute(Ord(eaNumber), Resource.Code, TGsRow) as TGsRow;
if Item = nil then
begin
Item := TGsRow.Create(TargetDocument);
Chapter.Add(Item);
Item.Code := Resource.Code;
Item.Caption := Resource.Caption;
Item.Measure := Resource.Measure;
if Resource.Kind = rkWorker then
Item.Attributes[Ord(eaWorkCode)] := Resource.Attributes[Ord(raWorkerClass)];
for J := Low(TGsCostKind) to High(TGsCostKind) do
Item.AssignCost(J, Resource);
end;
end;
end;
finally
L.Free;
end;
end;
class function TFmUnloadResources.GetDataProcessorKind: TDataProcessorKind;
begin
Result := dpkCustom;
end;
procedure TFmUnloadResources.JvDragDropDrop(Sender: TObject; Pos: TPoint;
Value: TStrings);
begin
lbFiles.Items.Assign(Value);
end;
{ TUnloadResourcesActionHandler }
procedure TUnloadResourcesActionHandler.ExecuteAction;
begin
TFmUnloadResources.Create(Application).Show;
end;
begin
ActionHandlerManager.RegisterActionHandler('Выгрузка ресурсов из базы', hkDefault, TUnloadResourcesActionHandler);
end.
|
unit taitosj_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,main_engine,controls_engine,ay_8910,gfx_engine,rom_engine,
pal_engine,sound_engine,timer_engine,dac,m6805;
function taitosj_iniciar:boolean;
implementation
const
//Elevator Action
elevator_rom:array[0..3] of tipo_roms=(
(n:'ba3__01.2764.ic1';l:$2000;p:0;crc:$da775a24),(n:'ba3__02.2764.ic2';l:$2000;p:$2000;crc:$fbfd8b3a),
(n:'ba3__03-1.2764.ic3';l:$2000;p:$4000;crc:$a2e69833),(n:'ba3__04-1.2764.ic6';l:$2000;p:$6000;crc:$2b78c462));
elevator_sonido:array[0..1] of tipo_roms=(
(n:'ba3__09.2732.ic70';l:$1000;p:0;crc:$6d5f57cb),(n:'ba3__10.2732.ic71';l:$1000;p:$1000;crc:$f0a769a1));
elevator_mcu:tipo_roms=(n:'ba3__11.mc68705p3.ic24';l:$800;p:0;crc:$9ce75afc);
elevator_char:array[0..3] of tipo_roms=(
(n:'ba3__05.2764.ic4';l:$2000;p:0;crc:$6c4ee58f),(n:'ba3__06.2764.ic5';l:$2000;p:$2000;crc:$41ab0afc),
(n:'ba3__07.2764.ic9';l:$2000;p:$4000;crc:$efe43731),(n:'ba3__08.2764.ic10';l:$2000;p:$6000;crc:$3ca20696));
elevator_prom:tipo_roms=(n:'eb16.22';l:$100;p:0;crc:$b833b5ea);
elevator_dip_a:array [0..5] of def_dip=(
(mask:$3;name:'Bonus Life';number:4;dip:((dip_val:$3;dip_name:'10000'),(dip_val:$2;dip_name:'15000'),(dip_val:$1;dip_name:'20000'),(dip_val:$0;dip_name:'25000'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Free Play';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$8;dip_name:'5'),(dip_val:$0;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
elevator_dip_c:array [0..5] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$3;dip_name:'Easiest'),(dip_val:$2;dip_name:'Easy'),(dip_val:$1;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'Coinage Display';number:2;dip:((dip_val:$10;dip_name:'Coins/Credits'),(dip_val:$0;dip_name:'Insert Coin'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Year Display';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$20;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Hit Detection';number:2;dip:((dip_val:$40;dip_name:'Normal Game'),(dip_val:$0;dip_name:'No Hit'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Coin Slots';number:2;dip:((dip_val:$80;dip_name:'A and B'),(dip_val:$0;dip_name:'A only'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
//Jungle King
junglek_rom:array[0..8] of tipo_roms=(
(n:'kn21-1.bin';l:$1000;p:0;crc:$45f55d30),(n:'kn22-1.bin';l:$1000;p:$1000;crc:$07cc9a21),
(n:'kn43.bin';l:$1000;p:$2000;crc:$a20e5a48),(n:'kn24.bin';l:$1000;p:$3000;crc:$19ea7f83),
(n:'kn25.bin';l:$1000;p:$4000;crc:$844365ea),(n:'kn46.bin';l:$1000;p:$5000;crc:$27a95fd5),
(n:'kn47.bin';l:$1000;p:$6000;crc:$5c3199e0),(n:'kn28.bin';l:$1000;p:$7000;crc:$194a2d09),
(n:'kn60.bin';l:$1000;p:$8000;crc:$1a9c0a26));
junglek_sonido:array[0..2] of tipo_roms=(
(n:'kn37.bin';l:$1000;p:0;crc:$dee7f5d4),(n:'kn38.bin';l:$1000;p:$1000;crc:$bffd3d21),
(n:'kn59-1.bin';l:$1000;p:$2000;crc:$cee485fc));
junglek_char:array[0..7] of tipo_roms=(
(n:'kn29.bin';l:$1000;p:0;crc:$8f83c290),(n:'kn30.bin';l:$1000;p:$1000;crc:$89fd19f1),
(n:'kn51.bin';l:$1000;p:$2000;crc:$70e8fc12),(n:'kn52.bin';l:$1000;p:$3000;crc:$bcbac1a3),
(n:'kn53.bin';l:$1000;p:$4000;crc:$b946c87d),(n:'kn34.bin';l:$1000;p:$5000;crc:$320db2e1),
(n:'kn55.bin';l:$1000;p:$6000;crc:$70aef58f),(n:'kn56.bin';l:$1000;p:$7000;crc:$932eb667));
junglek_prom:tipo_roms=(n:'eb16.22';l:$100;p:0;crc:$b833b5ea);
junglek_dip_a:array [0..4] of def_dip=(
(mask:$3;name:'Finish Bonus';number:4;dip:((dip_val:$3;dip_name:'None'),(dip_val:$2;dip_name:'Timer x1'),(dip_val:$1;dip_name:'Timer x2'),(dip_val:$0;dip_name:'Timer x3'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Lives';number:4;dip:((dip_val:$18;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$8;dip_name:'5'),(dip_val:$0;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
junglek_dip_c:array [0..4] of def_dip=(
(mask:$3;name:'Bonus Life';number:4;dip:((dip_val:$2;dip_name:'10000'),(dip_val:$1;dip_name:'20000'),(dip_val:$0;dip_name:'30000'),(dip_val:$3;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Year Display';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$20;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Infinite Lives';number:2;dip:((dip_val:$40;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Coin Slots';number:2;dip:((dip_val:$80;dip_name:'A and B'),(dip_val:$0;dip_name:'A only'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
//General
coin_dip:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';number:16;dip:((dip_val:$0f;dip_name:'9C 1C'),(dip_val:$0e;dip_name:'8C 1C'),(dip_val:$0d;dip_name:'7C 1C'),(dip_val:$0c;dip_name:'6C 1C'),(dip_val:$0b;dip_name:'5C 1C'),(dip_val:$0a;dip_name:'4C 1C'),(dip_val:$09;dip_name:'3C 1C'),(dip_val:$08;dip_name:'2C 1C'),(dip_val:$00;dip_name:'1C 1C'),(dip_val:$01;dip_name:'1C 2C'),(dip_val:$02;dip_name:'1C 3C'),(dip_val:$03;dip_name:'1C 4C'),(dip_val:$04;dip_name:'1C 5C'),(dip_val:$05;dip_name:'1C 6C'),(dip_val:$06;dip_name:'1C 7C'),(dip_val:$07;dip_name:'1C 8C'))),
(mask:$f0;name:'Coin B';number:16;dip:((dip_val:$f0;dip_name:'9C 1C'),(dip_val:$e0;dip_name:'8C 1C'),(dip_val:$d0;dip_name:'7C 1C'),(dip_val:$c0;dip_name:'6C 1C'),(dip_val:$b0;dip_name:'5C 1C'),(dip_val:$a0;dip_name:'4C 1C'),(dip_val:$90;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$00;dip_name:'1C 1C'),(dip_val:$10;dip_name:'1C 2C'),(dip_val:$20;dip_name:'1C 3C'),(dip_val:$30;dip_name:'1C 4C'),(dip_val:$40;dip_name:'1C 5C'),(dip_val:$50;dip_name:'1C 6C'),(dip_val:$60;dip_name:'1C 7C'),(dip_val:$70;dip_name:'1C 8C'))),());
var
memoria_rom:array[0..1,0..$1fff] of byte;
gfx_rom:array[0..$7fff] of byte;
rweights,gweights,bweights:array[0..2] of single;
collision_reg:array[0..3] of byte;
scroll:array[0..5] of byte;
colorbank:array[0..1] of byte;
scroll_y:array[0..$5f] of word;
draw_order:array[0..31,0..3] of byte;
gfx_pos:word;
video_priority,soundlatch,rom_bank,video_mode,dac_out,dac_vol:byte;
sound_semaphore,rechars1,rechars2:boolean;
sound_nmi:array[0..1] of boolean;
pos_x:array[0..4] of shortint;
//mcu
mcu_mem:array[0..$7ff] of byte;
mcu_toz80,mcu_address,mcu_fromz80,mcu_portA_in,mcu_portA_out:byte;
mcu_zaccept,mcu_zready,mcu_busreq:boolean;
procedure update_video_taitosj;
const
ps_x:array[0..15] of dword=(7, 6, 5, 4, 3, 2, 1, 0,
8*8+7, 8*8+6, 8*8+5, 8*8+4, 8*8+3, 8*8+2, 8*8+1, 8*8+0);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8);
procedure conv_chars1;
begin
gfx_set_desc_data(3,0,8*8,512*8*8,256*8*8,0);
convert_gfx(0,0,@memoria[$9000],@ps_x,@ps_y,false,false);
//sprites
gfx_set_desc_data(3,0,32*8,128*16*16,64*16*16,0);
convert_gfx(1,0,@memoria[$9000],@ps_x,@ps_y,false,false);
end;
procedure conv_chars2;
begin
//Chars 2
gfx_set_desc_data(3,0,8*8,512*8*8,256*8*8,0);
convert_gfx(2,0,@memoria[$a800],@ps_x,@ps_y,false,false);
//sprites
gfx_set_desc_data(3,0,32*8,128*16*16,64*16*16,0);
convert_gfx(3,0,@memoria[$a800],@ps_x,@ps_y,false,false);
end;
procedure taitosj_putsprites(sprite_offset:byte);
var
f,sx,sy,nchar,which,atrib,ngfx,offs,color:byte;
begin
// drawing order is a bit strange. The last sprite has to be moved at the start of the list
for f:=$1f downto 0 do begin
which:=(f-1) and $1f; // move last sprite at the head of the list
offs:=which*4;
if ((which>=$10) and (which<=$17)) then continue; // no sprites here
sx:=memoria[$d100+sprite_offset+offs+0]+pos_x[3];
sy:=240-memoria[$d100+sprite_offset+offs+1]+pos_x[4];
if (sy<240) then begin
atrib:=memoria[$d100+sprite_offset+offs+2];
nchar:=memoria[$d100+sprite_offset+offs+3] and $3f;
ngfx:=((memoria[$d100+sprite_offset+offs+3] and $40) shr 5) or 1;
color:=2*((colorbank[1] shr 4) and $03)+((atrib shr 2) and $01);
put_gfx_sprite(nchar,color shl 3,(atrib and $01)<>0,(atrib and $02)<>0,ngfx);
actualiza_gfx_sprite(sx,sy,4,ngfx);
end;
end;
end;
var
color_back,color_mid,color_front,gfx_back,gfx_mid,gfx_front,nchar,layer:byte;
f,x,y:word;
scroll_def:array[0..31] of word;
begin
if rechars1 then begin
conv_chars1;
rechars1:=false;
end;
if rechars2 then begin
conv_chars2;
rechars2:=false;
end;
color_back:=(colorbank[0] and $07) shl 3;
color_mid:=((colorbank[0] shr 4) and $07) shl 3;
color_front:=(colorbank[1] and $07) shl 3;
gfx_back:=(colorbank[0] and $08) shr 2;
gfx_mid:=(colorbank[0] and $80) shr 6;
gfx_front:=(colorbank[1] and $08) shr 2;
for f:=$0 to $3ff do begin
//back
x:=f mod 32;
y:=f div 32;
if (video_mode and $10)<>0 then begin
if gfx[0].buffer[f] then begin
nchar:=memoria[$c400+f];
put_gfx_trans(x*8,y*8,nchar,color_back,1,gfx_back);
gfx[0].buffer[f]:=false;
end;
end;
//mid
if (video_mode and $20)<>0 then begin
if gfx[0].buffer[f+$400] then begin
nchar:=memoria[$c800+f];
put_gfx_trans(x*8,y*8,nchar,color_mid,2,gfx_mid);
gfx[0].buffer[f+$400]:=false;
end;
end;
//front
if (video_mode and $40)<>0 then begin
if gfx[0].buffer[f+$800] then begin
nchar:=memoria[$cc00+f];
put_gfx_trans(x*8,y*8,nchar,color_front,3,gfx_front);
gfx[0].buffer[f+$800]:=false;
end;
end;
end;
fill_full_screen(4,(colorbank[1] and $07) shl 3);
for f:=0 to 3 do begin
layer:=draw_order[video_priority and $1f,f];
case layer of
0:if (video_mode and $80)<>0 then taitosj_putsprites((video_mode and $4) shl 5);
1:if (video_mode and $10)<>0 then begin
x:=scroll[0];
x:=(x and $f8)+((x+3) and 7)+pos_x[0];
//Ordena los scrolls de la Y!!!
for y:=0 to $1f do scroll_def[y]:=scroll_y[(y+(x div 8)) and $1f];
scroll__y_part2(1,4,8,@scroll_def,x,scroll[1]);
end;
2:if (video_mode and $20)<>0 then begin
x:=scroll[2];
x:=(x and $f8)+((x+1) and 7)+pos_x[1];
//Ordena los scrolls de la Y!!!
for y:=0 to $1f do scroll_def[y]:=scroll_y[32+((y+(x div 8)) and $1f)];
scroll__y_part2(2,4,8,@scroll_def,x,scroll[3]);
end;
3:if (video_mode and $40)<>0 then begin
x:=scroll[4];
x:=(x and $f8)+((x-1) and 7)+pos_x[2];
//Ordena los scrolls de la Y!!!
for y:=0 to $1f do scroll_def[y]:=scroll_y[64+((y+(x div 8)) and $1f)];
scroll__y_part2(3,4,8,@scroll_def,x,scroll[5]);
end;
end;
end;
actualiza_trozo_final(0,16,256,224,4);
end;
procedure eventos_taitosj;
begin
if event.arcade then begin
//p1
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or 4);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or 8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20);
//p2
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or 1);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or 2);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or 4);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or 8);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
//System
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40);
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $7f) else marcade.in2:=(marcade.in2 or $80);
end;
end;
procedure taitosj_nomcu_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_s:=z80_1.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//Main CPU
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//Sound
z80_1.run(frame_s);
frame_s:=frame_s+z80_1.tframes-z80_1.contador;
if f=239 then begin
z80_0.change_irq(HOLD_LINE);
update_video_taitosj;
end;
end;
eventos_taitosj;
video_sync;
end;
end;
function taitosj_nomcu_getbyte(direccion:word):byte;
begin
case direccion of
0..$5fff,$8000..$87ff,$c000..$cfff,$e000..$ffff:taitosj_nomcu_getbyte:=memoria[direccion];
$6000..$7fff:taitosj_nomcu_getbyte:=memoria_rom[rom_bank,direccion and $1fff];
$8800..$8fff:taitosj_nomcu_getbyte:=0; //Fake MCU
$d000..$d05f:taitosj_nomcu_getbyte:=scroll_y[direccion and $7f];
$d200..$d2ff:taitosj_nomcu_getbyte:=buffer_paleta[direccion and $7f];
$d400..$d4ff:case (direccion and $f) of
$0..$3:taitosj_nomcu_getbyte:=collision_reg[direccion and $f];
$4..$7:begin
if gfx_pos<$8000 then taitosj_nomcu_getbyte:=gfx_rom[gfx_pos]
else taitosj_nomcu_getbyte:=0;
gfx_pos:=gfx_pos+1;
end;
$8:taitosj_nomcu_getbyte:=marcade.in0;
$9:taitosj_nomcu_getbyte:=marcade.in1;
$a:taitosj_nomcu_getbyte:=marcade.dswa;
$b:taitosj_nomcu_getbyte:=marcade.in2;
$c:taitosj_nomcu_getbyte:=$ef;
$d:taitosj_nomcu_getbyte:=marcade.in4 or $f;
$f:taitosj_nomcu_getbyte:=ay8910_0.Read;
end;
end;
end;
procedure taitosj_nomcu_putbyte(direccion:word;valor:byte);
procedure cambiar_color(dir:word);
var
val,bit0,bit1,bit2:byte;
color:tcolor;
begin
dir:=dir and $fe;
// blue component */
val:=not(buffer_paleta[dir or 1]);
bit0:=(val shr 0) and $01;
bit1:=(val shr 1) and $01;
bit2:=(val shr 2) and $01;
color.b:=combine_3_weights(@bweights,bit0,bit1,bit2);
// green component */
bit0:=(val shr 3) and $01;
bit1:=(val shr 4) and $01;
bit2:=(val shr 5) and $01;
color.g:=combine_3_weights(@gweights,bit0,bit1,bit2);
// red component
bit0:=(val shr 6) and $01;
bit1:=(val shr 7) and $01;
val:=not(buffer_paleta[dir]);
bit2:=(val shr 0) and $01;
color.r:=combine_3_weights(@rweights,bit0,bit1,bit2);
set_pal_color(color,dir shr 1);
end;
begin
case direccion of
0..$7fff,$d700..$ffff:;
$8000..$87ff,$c000..$c3ff,$d100..$d1ff:memoria[direccion]:=valor;
$8800..$8fff:; //Fake MCU
$9000..$a7ff:if memoria[direccion]<>valor then begin
rechars1:=true;
memoria[direccion]:=valor;
end;
$a800..$bfff:if memoria[direccion]<>valor then begin
rechars2:=true;
memoria[direccion]:=valor;
end;
$c400..$cfff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion-$c400]:=true;
memoria[direccion]:=valor;
end;
$d000..$d05f:scroll_y[direccion and $7f]:=valor;
$d200..$d2ff:if buffer_paleta[direccion and $7f]<>valor then begin
buffer_paleta[direccion and $7f]:=valor;
cambiar_color(direccion and $7f);
end;
$d300..$d3ff:video_priority:=valor;
$d400..$d4ff:case (direccion and $f) of
$e:ay8910_0.Control(valor);
$f:ay8910_0.Write(valor);
end;
$d500..$d5ff:case (direccion and $f) of
$0..$5:scroll[direccion and $f]:=valor;
$6,$7:if colorbank[direccion and 1]<>valor then begin
colorbank[direccion and 1]:=valor;
fillchar(gfx[0].buffer,$c00,1);
end;
$8:fillchar(collision_reg,4,0);
$9:gfx_pos:=(gfx_pos and $ff00) or valor;
$a:gfx_pos:=(gfx_pos and $ff) or (valor shl 8);
$b:begin
soundlatch:=valor;
sound_nmi[1]:=true;
if (sound_nmi[0] and sound_nmi[1]) then z80_1.change_nmi(PULSE_LINE);
end;
$c:begin
sound_semaphore:=(valor and 1)<>0;
if sound_semaphore then z80_1.change_nmi(PULSE_LINE);
end;
$d:; //WD
$e:rom_bank:=valor shr 7;
end;
$d600..$d6ff:if video_mode<>valor then begin
video_mode:=valor;
fillchar(gfx[0].buffer,$c00,1);
main_screen.flip_main_x:=(valor and 1)<>0;
main_screen.flip_main_y:=(valor and 2)<>0;
end;
end;
end;
procedure taitosj_mcu_principal;
var
frame_m,frame_s,frame_mcu:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_s:=z80_1.tframes;
frame_mcu:=m6805_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//Main CPU
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//Sound
z80_1.run(frame_s);
frame_s:=frame_s+z80_1.tframes-z80_1.contador;
//mcu
m6805_0.run(frame_mcu);
frame_mcu:=frame_mcu+m6805_0.tframes-m6805_0.contador;
if f=239 then begin
z80_0.change_irq(HOLD_LINE);
update_video_taitosj;
end;
end;
eventos_taitosj;
video_sync;
end;
end;
function taitosj_mcu_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff,$9000..$ffff:taitosj_mcu_getbyte:=taitosj_nomcu_getbyte(direccion);
$8800..$8fff:if (direccion and 1)=0 then begin
taitosj_mcu_getbyte:=mcu_toz80;
mcu_zaccept:=true;
end else begin
taitosj_mcu_getbyte:=not(byte(mcu_zready) or (byte(mcu_zaccept)*2));
end;
end;
end;
procedure taitosj_mcu_putbyte(direccion:word;valor:byte);
begin
case direccion of
$0..$7fff:;
$8000..$87ff,$9000..$ffff:taitosj_nomcu_putbyte(direccion,valor);
$8800..$8fff:if (direccion and 1)=0 then begin
mcu_zready:=true;
m6805_0.irq_request(0,ASSERT_LINE);
mcu_fromz80:=valor;
end;
end;
end;
function mcu_taitosj_getbyte(direccion:word):byte;
begin
direccion:=direccion and $7ff;
case direccion of
0:mcu_taitosj_getbyte:=mcu_portA_in;
1:mcu_taitosj_getbyte:=$ff;
2:mcu_taitosj_getbyte:=byte(mcu_zready) or byte(mcu_zaccept)*2 or byte(not(mcu_busreq))*4;
3..$7ff:mcu_taitosj_getbyte:=mcu_mem[direccion];
end;
end;
procedure mcu_taitosj_putbyte(direccion:word;valor:byte);
begin
direccion:=direccion and $7ff;
case direccion of
0:mcu_portA_out:=valor;
1:begin
if (not(valor) and $01)<>0 then exit;
if (not(valor) and $02)<>0 then begin
// 68705 is going to read data from the Z80
mcu_zready:=false;
m6805_0.irq_request(0,CLEAR_LINE);
mcu_portA_in:=mcu_fromz80;
end;
mcu_busreq:=(not(valor) and $08)<>0;
if (not(valor) and $04)<>0 then begin
// 68705 is writing data for the Z80
mcu_toz80:=mcu_portA_out;
mcu_zaccept:=false;
end;
if (not(valor) and $10)<>0 then begin
memoria[mcu_address]:=mcu_portA_out;
// increase low 8 bits of latched address for burst writes
mcu_address:= (mcu_address and $ff00) or ((mcu_address+1) and $ff);
end;
if (not(valor) and $20)<>0 then mcu_portA_in:=memoria[mcu_address];
if (not(valor) and $40)<>0 then mcu_address:=(mcu_address and $ff00) or mcu_portA_out;
if (not(valor) and $80)<>0 then mcu_address:=(mcu_address and $00ff) or (mcu_portA_out shl 8);
end;
2:;
3..$7f:mcu_mem[direccion]:=valor;
end;
end;
function taitosj_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$43ff:taitosj_snd_getbyte:=mem_snd[direccion];
$4801:taitosj_snd_getbyte:=ay8910_1.Read;
$4803:taitosj_snd_getbyte:=ay8910_2.Read;
$4805:taitosj_snd_getbyte:=ay8910_3.Read;
$5000:begin
sound_nmi[1]:=false;
taitosj_snd_getbyte:=soundlatch;
end;
$5001:taitosj_snd_getbyte:=byte(sound_nmi[1])*8 or byte(sound_semaphore)*4 or 3;
end;
end;
procedure taitosj_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$3fff:;
$4000..$43ff:mem_snd[direccion]:=valor;
$4800:ay8910_1.Control(valor);
$4801:ay8910_1.Write(valor);
$4802:ay8910_2.Control(valor);
$4803:ay8910_2.Write(valor);
$4804:ay8910_3.Control(valor);
$4805:ay8910_3.Write(valor);
$5000:soundlatch:=soundlatch and $7f;
$5001:sound_semaphore:=false;
end;
end;
function ay0_porta_read:byte;
begin
ay0_porta_read:=marcade.dswb;
end;
function ay0_portb_read:byte;
begin
ay0_portb_read:=marcade.dswc;
end;
procedure ay1_porta_write(valor:byte);
begin
dac_out:=not(valor);
dac_0.signed_data16_w(dac_out*dac_vol);
end;
procedure ay1_portb_write(valor:byte);
const
voltable:array[0..$ff] of byte=(
$ff,$fe,$fc,$fb,$f9,$f7,$f6,$f4,$f3,$f2,$f1,$ef,$ee,$ec,$eb,$ea,
$e8,$e7,$e5,$e4,$e2,$e1,$e0,$df,$de,$dd,$dc,$db,$d9,$d8,$d7,$d6,
$d5,$d4,$d3,$d2,$d1,$d0,$cf,$ce,$cd,$cc,$cb,$ca,$c9,$c8,$c7,$c6,
$c5,$c4,$c3,$c2,$c1,$c0,$bf,$bf,$be,$bd,$bc,$bb,$ba,$ba,$b9,$b8,
$b7,$b7,$b6,$b5,$b4,$b3,$b3,$b2,$b1,$b1,$b0,$af,$ae,$ae,$ad,$ac,
$ab,$aa,$aa,$a9,$a8,$a8,$a7,$a6,$a6,$a5,$a5,$a4,$a3,$a2,$a2,$a1,
$a1,$a0,$a0,$9f,$9e,$9e,$9d,$9d,$9c,$9c,$9b,$9b,$9a,$99,$99,$98,
$97,$97,$96,$96,$95,$95,$94,$94,$93,$93,$92,$92,$91,$91,$90,$90,
$8b,$8b,$8a,$8a,$89,$89,$89,$88,$88,$87,$87,$87,$86,$86,$85,$85,
$84,$84,$83,$83,$82,$82,$82,$81,$81,$81,$80,$80,$7f,$7f,$7f,$7e,
$7e,$7e,$7d,$7d,$7c,$7c,$7c,$7b,$7b,$7b,$7a,$7a,$7a,$79,$79,$79,
$78,$78,$77,$77,$77,$76,$76,$76,$75,$75,$75,$74,$74,$74,$73,$73,
$73,$73,$72,$72,$72,$71,$71,$71,$70,$70,$70,$70,$6f,$6f,$6f,$6e,
$6e,$6e,$6d,$6d,$6d,$6c,$6c,$6c,$6c,$6b,$6b,$6b,$6b,$6a,$6a,$6a,
$6a,$69,$69,$69,$68,$68,$68,$68,$68,$67,$67,$67,$66,$66,$66,$66,
$65,$65,$65,$65,$64,$64,$64,$64,$64,$63,$63,$63,$63,$62,$62,$62);
begin
dac_vol:=voltable[valor];
dac_0.signed_data16_w(dac_out*dac_vol);
end;
procedure ay2_porta_write(valor:byte);
begin
marcade.in4:=valor and $f0;
end;
procedure ay3_portb_write(valor:byte);
begin
sound_nmi[0]:=(not(valor) and 1)<>0;
if (sound_nmi[0] and sound_nmi[1]) then z80_1.change_nmi(PULSE_LINE);
end;
procedure taitosj_snd_irq;
begin
z80_1.change_irq(HOLD_LINE);
end;
procedure taitosj_sound_update;
begin
ay8910_0.update;
ay8910_1.update;
ay8910_2.update;
ay8910_3.update;
dac_0.update;
end;
//Main
procedure taitosj_reset;
begin
z80_0.reset;
z80_1.reset;
if main_vars.tipo_maquina=185 then m6805_0.reset;
ay8910_0.reset;
ay8910_1.reset;
ay8910_2.reset;
ay8910_3.reset;
dac_0.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
marcade.in4:=0;
fillchar(collision_reg,4,0);
gfx_pos:=0;
video_priority:=0;
fillchar(scroll[0],6,0);
colorbank[0]:=0;
colorbank[1]:=0;
rechars1:=false;
rechars2:=false;
rom_bank:=0;
video_mode:=0;
dac_vol:=0;
sound_semaphore:=false;
sound_nmi[0]:=false;
sound_nmi[1]:=false;
//mcu
mcu_zaccept:=true;
mcu_zready:=false;
mcu_busreq:=false;
end;
function taitosj_iniciar:boolean;
const
resistances:array[0..2] of integer=(1000,470,270);
var
memoria_temp:array[0..$8fff] of byte;
i,j,mask,data:byte;
begin
taitosj_iniciar:=false;
case main_vars.tipo_maquina of
185:llamadas_maquina.bucle_general:=taitosj_mcu_principal;
189:llamadas_maquina.bucle_general:=taitosj_nomcu_principal;
end;
llamadas_maquina.reset:=taitosj_reset;
iniciar_audio(false);
//Back
screen_init(1,256,256,true);
screen_mod_scroll(1,256,256,255,256,256,255);
//Mid
screen_init(2,256,256,true);
screen_mod_scroll(2,256,256,255,256,256,255);
//Front
screen_init(3,256,256,true);
screen_mod_scroll(3,256,256,255,256,256,255);
screen_init(4,256,256,false,true); //Final
iniciar_video(256,224);
//Main CPU
z80_0:=cpu_z80.create(4000000,256);
//Sound CPU
z80_1:=cpu_z80.create(3000000,256);
z80_1.change_ram_calls(taitosj_snd_getbyte,taitosj_snd_putbyte);
z80_1.init_sound(taitosj_sound_update);
//IRQ sonido
timers.init(z80_1.numero_cpu,3000000/(6000000/(4*16*16*10*16)),taitosj_snd_irq,nil,true);
//Sound Chip
ay8910_0:=ay8910_chip.create(1500000,AY8910,0.15);
ay8910_0.change_io_calls(ay0_porta_read,ay0_portb_read,nil,nil);
ay8910_1:=ay8910_chip.create(1500000,AY8910,0.5);
ay8910_1.change_io_calls(nil,nil,ay1_porta_write,ay1_portb_write);
ay8910_2:=ay8910_chip.create(1500000,AY8910,0.5);
ay8910_2.change_io_calls(nil,nil,ay2_porta_write,nil);
ay8910_3:=ay8910_chip.create(1500000,AY8910,1);
ay8910_3.change_io_calls(nil,nil,nil,ay3_portb_write);
dac_0:=dac_chip.create(0.15);
case main_vars.tipo_maquina of
185:begin //Elevator Action
z80_0.change_ram_calls(taitosj_mcu_getbyte,taitosj_mcu_putbyte);
//cargar roms
if not(roms_load(@memoria_temp,elevator_rom)) then exit;
//Poner roms en sus bancos
copymemory(@memoria[0],@memoria_temp[0],$6000);
copymemory(@memoria_rom[0,0],@memoria_temp[$6000],$2000);
copymemory(@memoria_rom[1,0],@memoria_temp[$6000],$1000);
copymemory(@memoria_rom[1,$1000],@memoria_temp[$8000],$1000);
//cargar roms sonido
if not(roms_load(@mem_snd,elevator_sonido)) then exit;
//MCU CPU
if not(roms_load(@mcu_mem,elevator_mcu)) then exit;
m6805_0:=cpu_m6805.create(3000000,256,tipo_m68705);
m6805_0.change_ram_calls(mcu_taitosj_getbyte,mcu_taitosj_putbyte);
//cargar chars
if not(roms_load(@gfx_rom,elevator_char)) then exit;
//Calculo de prioridades
if not(roms_load(@memoria_temp,elevator_prom)) then exit;
marcade.dswa:=$7f;
marcade.dswa_val:=@elevator_dip_a;
marcade.dswc:=$ff;
marcade.dswc_val:=@elevator_dip_c;
pos_x[0]:=-8;
pos_x[1]:=-23;
pos_x[2]:=-21;
pos_x[3]:=-2;
pos_x[4]:=0;
end;
189:begin //Jungle King
main_screen.rot180_screen:=true;
z80_0.change_ram_calls(taitosj_nomcu_getbyte,taitosj_nomcu_putbyte);
//cargar roms
if not(roms_load(@memoria_temp,junglek_rom)) then exit;
//Poner roms en sus bancos
copymemory(@memoria[0],@memoria_temp[0],$6000);
copymemory(@memoria_rom[0,0],@memoria_temp[$6000],$2000);
copymemory(@memoria_rom[1,0],@memoria_temp[$6000],$1000);
copymemory(@memoria_rom[1,$1000],@memoria_temp[$8000],$1000);
//cargar roms sonido
if not(roms_load(@mem_snd,junglek_sonido)) then exit;
//cargar chars
if not(roms_load(@gfx_rom,junglek_char)) then exit;
//Calculo de prioridades
if not(roms_load(@memoria_temp,junglek_prom)) then exit;
marcade.dswa:=$3f;
marcade.dswa_val:=@junglek_dip_a;
marcade.dswc:=$ff;
marcade.dswc_val:=@junglek_dip_c;
pos_x[0]:=8;
pos_x[1]:=10;
pos_x[2]:=12;
pos_x[3]:=1;
pos_x[4]:=-2;
end;
end;
//crear gfx
init_gfx(0,8,8,256);
gfx[0].trans[0]:=true;
init_gfx(1,16,16,64);
gfx[1].trans[0]:=true;
init_gfx(2,8,8,256);
gfx[2].trans[0]:=true;
init_gfx(3,16,16,64);
gfx[3].trans[0]:=true;
marcade.dswb:=$0;
marcade.dswb_val:=@coin_dip;
for i:=0 to $1f do begin
mask:=0;
// start with all four layers active, so we'll get the highest
// priority one in the first loop
for j:=3 downto 0 do begin
data:=memoria_temp[$10*(i and $0f)+mask] and $0f;
if (i and $10)<>0 then data:=data shr 2
else data:=data and $03;
mask:=mask or (1 shl data);
// in next loop, we'll see which of the remaining
// layers has top priority when this one is transparent
draw_order[i,j]:=data;
end;
end;
//precalculo de la paleta
compute_resistor_weights(0,255,-1.0,
3,@resistances[0],@rweights[0],0,0,
3,@resistances[0],@gweights[0],0,0,
3,@resistances[0],@bweights[0],0,0);
//final
taitosj_reset;
taitosj_iniciar:=true;
end;
end.
|
unit ufind;
{$MODE Delphi}
interface
uses
SysUtils, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms;
type
// search record
TFindRec = record
StrText, // textual format
StrData: string; // real data to find
BoolIgnoreCase, // ignore upper/lower case
BoolFindText: Boolean; // find text or hex data
end;
TdlgFind = class(TForm)
Button1: TButton;
Button2: TButton;
Label1: TLabel;
edFind: TEdit;
cbText: TCheckBox;
cbNoCase: TCheckBox;
procedure edFindChange(Sender: TObject);
end;
var
dlgFind: TdlgFind;
// create a find dialog and get options
function FindGetOptions(var Options: TFindRec): Boolean;
implementation
{$R *.lfm}
// determine if a text contains only hex chars and ' '
function IsHex(const Str: string): Boolean;
var
LIntLoop: Integer;
begin
Result := Trim(Str) <> '';
if Result
then
for LIntLoop := 1 to Length(Str)
do
if not (Str[LIntLoop] in ['0'..'9',' ','a'..'f','A'..'F']) then
begin
Result := False;
Break;
end;
end;
// create a find dialog and get options
function FindGetOptions(var Options: TFindRec): Boolean;
begin
with TdlgFind.Create(Application) do
try
edFind.Text := Options.StrText;
// if no previous search, gray "find text" to auto determine text/hex
if Options.StrText <> ''
then
cbText.Checked := Options.BoolFindText;
cbNoCase.Checked := Options.BoolIgnoreCase;
Result := ShowModal = mrOK;
if Result
then
with Options do
begin
StrText := edFind.Text;
BoolFindText := cbText.Checked;
// eventually find out whether text or hex values (0..9,a..f,' ') are entered
if cbText.State = cbGrayed
then
BoolFindText := not IsHex(edFind.Text);
StrData := StrText;
BoolIgnoreCase := cbNoCase.Checked;
end;
finally
Free;
end;
end;
procedure TdlgFind.edFindChange(Sender: TObject);
begin
Button1.Enabled := edFind.Text <> '';
end;
end.
|
unit uGeraSQL;
interface
uses System.Classes, System.Generics.Collections, System.SysUtils;
type
IColuna = interface
['{DA7AD0D2-64B8-49F9-A1B9-0DA4350C69A8}']
function AdicionarColuna(AcColuna: String): IColuna;
function RetornarColuna: String;
end;
ITabela = interface
['{D66BF235-2EB2-460B-BA39-D431D183CEF1}']
function AdicionarTabela(AcTabela: String): ITabela;
function RetornarTabela: String;
end;
ICondicao = interface
['{28275C47-8362-44AA-9928-460422342D21}']
function AdicionarCondicao(AcCondicao: String): ICondicao;
function RetornarCondicao: String;
end;
IGeradorSQL = interface
['{7CDEB602-A8D8-4A8D-A18C-52E50A7CFBC7}']
function GerarSQL: String;
end;
TColuna = Class(TInterfacedObject, IColuna)
private
FColuna: String;
procedure SetColuna(const Value: String);
function AdicionarColuna(AcColuna: String): IColuna;
function RetornarColuna: String;
public
property Coluna: String read FColuna write SetColuna;
class function New: IColuna;
End;
TTabela = Class(TInterfacedObject, ITabela)
private
FTabela: String;
procedure SetTabela(const Value: String);
function AdicionarTabela(AcTabela: String): ITabela;
function RetornarTabela: String;
public
property Tabela: String read FTabela write SetTabela;
class function New: ITabela;
End;
TCondicao = Class(TInterfacedObject, ICondicao)
private
FCondicao: String;
procedure SetCondicao(const Value: String);
function AdicionarCondicao(AcCondicao: String): ICondicao;
function RetornarCondicao: String;
public
property Condicao: String read FCondicao write SetCondicao;
class function New: ICondicao;
End;
TGeradorSQL = Class(TInterfacedObject, IGeradorSQL)
private
FTabelas: TList<ITabela>;
FCondicao: TList<ICondicao>;
FColunas: TList<IColuna>;
function RetornarColuas: String;
function RetornarTabelas: String;
function RetornarWhere: String;
procedure SetColunas(const Value: TList<IColuna>);
procedure SetTabelas(const Value: TList<ITabela>);
procedure SetCondicao(const Value: TList<ICondicao>);
public
constructor Create;
Destructor Destroy; Override;
function GerarSQL: String;
property Colunas: TList<IColuna> read FColunas write SetColunas;
property Tabelas: TList<ITabela> read FTabelas write SetTabelas;
property Condicao: TList<ICondicao> read FCondicao write SetCondicao;
End;
implementation
{ TGeradorSQL }
constructor TGeradorSQL.Create;
begin
Colunas := TList<IColuna>.Create;
Tabelas := TList<ITabela>.Create;
Condicao:= TList<ICondicao>.Create;
end;
destructor TGeradorSQL.Destroy;
begin
FreeAndNil(FColunas);
FreeAndNil(FTabelas);
FreeAndNil(FCondicao);
inherited;
end;
function TGeradorSQL.GerarSQL: String;
begin
Result := Format('SELECT %S FROM %S WHERE %S', [RetornarColuas , RetornarTabelas, RetornarWhere]);
end;
function TGeradorSQL.RetornarColuas: String;
var
I: Integer;
begin
for I := 0 to Colunas.Count-1 do
if I = Colunas.Count-1 then
Result := Result + Colunas[i].RetornarColuna + sLineBreak
else
Result := Result + Colunas[i].RetornarColuna + ', ';
end;
function TGeradorSQL.RetornarTabelas: String;
var
I: Integer;
begin
for I := 0 to Tabelas.Count-1 do
if I = Tabelas.Count-1 then
Result := Result + Tabelas[i].RetornarTabela + sLineBreak
else
Result := Result + Tabelas[i].RetornarTabela + ', ';
end;
function TGeradorSQL.RetornarWhere: String;
var
I: Integer;
begin
for I := 0 to Condicao.Count-1 do
if I = Condicao.Count-1 then
Result := Result + Condicao[i].RetornarCondicao + sLineBreak
else
Result := Result + Condicao[i].RetornarCondicao + ' AND ';
end;
procedure TGeradorSQL.SetColunas(const Value: TList<IColuna>);
begin
FColunas := Value;
end;
procedure TGeradorSQL.SetTabelas(const Value: TList<ITabela>);
begin
FTabelas := Value;
end;
procedure TGeradorSQL.SetCondicao(const Value: TList<ICondicao>);
begin
FCondicao := Value;
end;
{ TColuna }
function TColuna.AdicionarColuna(AcColuna: String): IColuna;
begin
SetColuna(AcColuna);
Result := Self;
end;
class function TColuna.New: IColuna;
begin
Result := TColuna.Create;
end;
function TColuna.RetornarColuna: String;
begin
Exit(FColuna);
end;
procedure TColuna.SetColuna(const Value: String);
begin
FColuna := Value;
end;
{ TTabela }
function TTabela.AdicionarTabela(AcTabela: String): ITabela;
begin
SetTabela(AcTabela);
Result := Self;
end;
class function TTabela.New: ITabela;
begin
Result := TTabela.Create;
end;
function TTabela.RetornarTabela: String;
begin
Exit(FTabela);
end;
procedure TTabela.SetTabela(const Value: String);
begin
FTabela := Value;
end;
{ TCondicao }
function TCondicao.AdicionarCondicao(AcCondicao: String): ICondicao;
begin
SetCondicao(AcCondicao);
Result := Self;
end;
class function TCondicao.New: ICondicao;
begin
Result := TCondicao.Create;
end;
function TCondicao.RetornarCondicao: String;
begin
Exit(FCondicao);
end;
procedure TCondicao.SetCondicao(const Value: String);
begin
FCondicao := Value;
end;
end.
|
unit ChangeChannelForma;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Mask, DBCtrlsEh, Buttons, DB, FIBDataSet, pFIBDataSet,
DBLookupEh, DBGridEh, FIBQuery, pFIBQuery;
type
TfrmChangeChannelForm = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Panel2: TPanel;
dsChannels: TpFIBDataSet;
srcChannels: TDataSource;
lcbSlave: TDBLookupComboboxEh;
bbOk: TBitBtn;
bbCancel: TBitBtn;
lbl1: TLabel;
lblMaster: TLabel;
chkAnalog: TDBCheckBoxEh;
lbl2: TLabel;
chkDVB: TDBCheckBoxEh;
qryChange: TpFIBQuery;
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
function ChangeChannel(const CH_from: Integer; const FromName: String): Integer;
implementation
uses DM, AtrCommon, System.Variants;
{$R *.DFM}
function ChangeChannel(const CH_from: Integer; const FromName: String): Integer;
var
frmChange: TfrmChangeChannelForm;
begin
Result := -1;
try
Application.CreateForm(TfrmChangeChannelForm, frmChange);
frmChange.lblMaster.Caption := FromName;
frmChange.dsChannels.ParamByName('from_id').AsInteger := CH_from;
frmChange.dsChannels.Open;
frmChange.ShowModal;
if frmChange.ModalResult = mrOk then
if not frmChange.dsChannels.FieldByName('CH_ID').IsNull then
begin
try
Result := frmChange.dsChannels['CH_ID'];
frmChange.qryChange.ParamByName('From_Ch').AsInteger := CH_from;
frmChange.qryChange.ParamByName('To_Ch').AsInteger := Result;
if frmChange.chkAnalog.Checked then
frmChange.qryChange.ParamByName('Analog').AsInteger := 1
else
frmChange.qryChange.ParamByName('Analog').AsInteger := 0;
if frmChange.chkDVB.Checked then
frmChange.qryChange.ParamByName('Dvb').AsInteger := 1
else
frmChange.qryChange.ParamByName('Dvb').AsInteger := 0;
frmChange.qryChange.ExecProc;
except
Result := -1;
end;
end;
finally
frmChange.dsChannels.Close;
FreeAndNil(frmChange);
end;
end;
procedure TfrmChangeChannelForm.FormCreate(Sender: TObject);
begin
UpdateFonts(self);
end;
procedure TfrmChangeChannelForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
ModalResult := mrOk;
end;
end.
|
unit nsDownloaderRes;
// Модуль: "w:\common\components\gui\Garant\Nemesis\nsDownloaderRes.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "nsDownloaderRes" MUID: (57BD790600B0)
{$Include w:\common\components\gui\Garant\Nemesis\nscDefine.inc}
interface
{$If Defined(Nemesis)}
uses
l3IntfUses
, l3StringIDEx
;
const
{* Локализуемые строки nsDownloaderLocalConst }
str_UnknownFile: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'UnknownFile'; rValue : 'Неизвестный');
{* 'Неизвестный' }
str_FileDownload: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'FileDownload'; rValue : 'Загрузка файла');
{* 'Загрузка файла' }
str_OpenOrDownloadQuestion: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'OpenOrDownloadQuestion'; rValue : 'Вы хотите открыть или сохранить этот файл?');
{* 'Вы хотите открыть или сохранить этот файл?' }
str_FileName: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'FileName'; rValue : 'Имя:');
{* 'Имя:' }
str_Type: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'Type'; rValue : 'Тип:');
{* 'Тип:' }
str_From: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'From'; rValue : 'Из:');
{* 'Из:' }
str_Open: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'Open'; rValue : 'Открыть');
{* 'Открыть' }
str_Download: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'Download'; rValue : 'Сохранить');
{* 'Сохранить' }
str_Cancel: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'Cancel'; rValue : 'Отмена');
{* 'Отмена' }
{$IfEnd} // Defined(Nemesis)
implementation
{$If Defined(Nemesis)}
uses
l3ImplUses
//#UC START# *57BD790600B0impl_uses*
//#UC END# *57BD790600B0impl_uses*
;
initialization
str_UnknownFile.Init;
{* Инициализация str_UnknownFile }
str_FileDownload.Init;
{* Инициализация str_FileDownload }
str_OpenOrDownloadQuestion.Init;
{* Инициализация str_OpenOrDownloadQuestion }
str_FileName.Init;
{* Инициализация str_FileName }
str_Type.Init;
{* Инициализация str_Type }
str_From.Init;
{* Инициализация str_From }
str_Open.Init;
{* Инициализация str_Open }
str_Download.Init;
{* Инициализация str_Download }
str_Cancel.Init;
{* Инициализация str_Cancel }
{$IfEnd} // Defined(Nemesis)
end.
|
{ Full Unit Code.
--------------------------------------------------
Must be stored in a unit called Unit1 with a form called Form1 that has an OnCreate event called
FormCreate.
}
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Variants;
type
{ define a ball class }
TBall = class
protected
ballSize: Byte;
ballSpeed: Byte;
public
procedure Kick(power: Byte); virtual;
function GetSpeed: Byte;
constructor Create(size: Byte);
end;
{ define a specialized ball }
TFootball = class(TBall)
private
ballPanels: Byte;
public
{ override of the TBall Kick method to take into account the number of panels of the ball }
procedure Kick(power: Byte); virtual;
{ different constructor needed to include panels }
constructor Create(size: Byte; panels: Byte);
end;
{ TForm1 }
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ ball method implementations }
procedure TBall.Kick(power: Byte);
begin
ballSpeed := (power * ballSize) DIV 4;
end;
function TBall.GetSpeed: Byte;
begin
Result := ballSpeed;
end;
constructor TBall.Create(size: Byte);
begin
ballSize := size;
ballSpeed := 0;
end;
{ football method implementation }
procedure TFootball.Kick(power: Byte);
begin
{ Now take the number of panels into account }
ballSpeed := (power * ballSize * ballPanels) DIV 24;
end;
constructor TFootball.Create(size: Byte; panels: Byte);
begin
Inherited Create(size); { call the parent constructor first }
ballPanels := panels;
end;
{ the form OnCreate implementation }
procedure TForm1.FormCreate(Sender: TObject);
var
beachBall: TBall;
soccerBall: TFootball;
begin
{ create the two balls }
beachBall := TBall.Create(5);
soccerBall := TFootball.Create(5, 12);
{ how fast are they at the moment? }
ShowMessageFmt('Beach ball is moving at speed: %d', [beachBall.GetSpeed]);
ShowMessageFmt('Soccer ball is moving at speed: %d', [soccerBall.GetSpeed]);
{ now kick each bakk with a power of 10 }
beachBall.Kick(10);
soccerBall.Kick(10);
{ how fast are they moving now? }
ShowMessageFmt('Beach ball is moving at speed: %d', [beachBall.GetSpeed]);
ShowMessageFmt('Soccer ball is moving at speed: %d', [soccerBall.GetSpeed]);
end;
end.
|
unit GX_GenericClasses;
{$I GX_CondDefine.inc}
interface
uses
Classes, Contnrs;
type
// We use the NoRefCount type to assign interface instances without invoking
// reference-counting. Only use this if you have a very good reason.
NoRefCount = Pointer;
TSingletonInterfacedObject = class(TInterfacedObject)
protected
// IUnknown overrides for private life-time management.
// Enforce singleton semantics for interfaces.
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{ TGxObjectDictionary
List of objects that can be found by a specified code
Code can be specified by overriding GetObjectCode or
by using AddWithCode.
Objects are owned by this list - it means that it frees
object if the object is deleted.
}
TGxListEntryHandler = procedure(Sender: TObject; AIndex: Integer; AData: TObject) of object;
TGxObjectDictionary = class
private
FOwnsObjects: Boolean;
function GetItem(Index: Integer): TObject;
function GetCode(Index: Integer): string;
protected
FList: TStringList;
function GetObjectCode(AObject: TObject): string; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Clear; virtual;
procedure Delete(AIndex: Integer);
procedure Remove(AObject: TObject);
procedure Extract(Item: Pointer);
function Add(AObject: TObject): Integer;
function AddWithCode(const ACode: string; AObject: TObject): Integer;
function IndexOf(const ACode: string): Integer;
function FindObject(const ACode: string): TObject;
function Count: Integer;
function ObjectByCode(const ACode: string): TObject;
procedure ForEach(AHandler: TGxListEntryHandler; AData: TObject = nil); virtual;
property Items[Index: Integer]: TObject read GetItem; default;
property Codes[Index: Integer]: string read GetCode;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
end;
implementation
uses
SysUtils;
{ TGxObjectList }
{ TSingletonInterfacedObject }
function TSingletonInterfacedObject._AddRef: Integer;
begin
Result := 1;
end;
function TSingletonInterfacedObject._Release: Integer;
begin
Result := 1;
end;
{ TGxObjectDictionary }
constructor TGxObjectDictionary.Create;
begin
inherited;
FList := TStringList.Create;
FList.Sorted := True;
FList.Duplicates := dupError;
FOwnsObjects := True;
end;
destructor TGxObjectDictionary.Destroy;
begin
Clear;
FreeAndNil(FList);
inherited;
end;
procedure TGxObjectDictionary.Clear;
begin
while Count>0 do
Delete(Count-1);
end;
function TGxObjectDictionary.Add(AObject: TObject): Integer;
begin
Result := AddWithCode(GetObjectCode(AObject), AObject);
end;
function TGxObjectDictionary.AddWithCode(const ACode: string; AObject: TObject): Integer;
begin
Result := FList.AddObject(ACode, AObject);
end;
function TGxObjectDictionary.Count: Integer;
begin
Result := FList.Count;
end;
procedure TGxObjectDictionary.Delete(AIndex: Integer);
var
Obj: TObject;
begin
Obj := FList.Objects[AIndex];
FList.Delete(AIndex);
if OwnsObjects then
FreeAndNil(Obj);
end;
// remove but do not free
procedure TGxObjectDictionary.Extract(Item: Pointer);
var
Idx: Integer;
begin
Idx := FList.IndexOfObject(Item);
if Idx >= 0 then
FList.Delete(Idx);
end;
function TGxObjectDictionary.GetObjectCode(AObject: TObject): string;
resourcestring
SCodeReadNotImp = 'Object code reader not implemented';
begin
raise Exception.Create(SCodeReadNotImp);
Result := '';
end;
function TGxObjectDictionary.IndexOf(const ACode: string): Integer;
begin
Result := FList.IndexOf(ACode);
end;
procedure TGxObjectDictionary.Remove(AObject: TObject);
var
Idx: Integer;
begin
Idx := FList.IndexOfObject(AObject);
if Idx >= 0 then
Delete(Idx);
end;
function TGxObjectDictionary.GetItem(Index: Integer): TObject;
begin
Result := FList.Objects[Index];
end;
function TGxObjectDictionary.ObjectByCode(const ACode: string): TObject;
resourcestring
SObjNF = 'Object with code "%s" not found';
var
Idx: Integer;
begin
Idx := IndexOf(ACode);
if Idx < 0 then
raise Exception.Create(Format(SObjNF, [ACode]));
Result := FList.Objects[Idx];
end;
function TGxObjectDictionary.FindObject(const ACode: string): TObject;
var
Idx: Integer;
begin
Idx := IndexOf(ACode);
if Idx < 0 then
Result := nil
else
Result := FList.Objects[Idx];
end;
procedure TGxObjectDictionary.ForEach(AHandler: TGxListEntryHandler; AData: TObject);
var
i: Integer;
begin
for i := 0 to Count-1 do
AHandler(Self, i, AData);
end;
function TGxObjectDictionary.GetCode(Index: Integer): string;
begin
Result := FList[Index];
end;
end.
|
unit Dates;
interface
uses
SysUtils;
type
TDate = class
private
fDate: TDateTime;
procedure SetDay(const Value: Integer);
procedure SetMonth(const Value: Integer);
procedure SetYear(const Value: Integer);
function GetDay: Integer;
function GetMonth: Integer;
function GetYear: Integer;
public
procedure SetValue (y, m, d: Integer); overload;
procedure SetValue (NewDate: TDateTime); overload;
function LeapYear: Boolean;
function GetText: string;
procedure Increase;
property Year: Integer read GetYear write SetYear;
property Month: Integer read GetMonth write SetMonth;
property Day: Integer read GetDay write SetDay;
end;
implementation
uses
DateUtils;
procedure TDate.SetValue (y, m, d: Integer);
begin
fDate := EncodeDate (y, m, d);
end;
function TDate.GetText: string;
begin
Result := DateToStr (fDate);
end;
procedure TDate.Increase;
begin
fDate := fDate + 1;
end;
function TDate.LeapYear: Boolean;
begin
// from DateUtils
Result := IsInLeapYear(fDate);
end;
procedure TDate.SetValue(NewDate: TDateTime);
begin
fDate := NewDate;
end;
procedure TDate.SetDay(const Value: Integer);
begin
fDate := RecodeDay (fDate, Value);
end;
procedure TDate.SetMonth(const Value: Integer);
begin
fDate := RecodeMonth (fDate, Value);
end;
procedure TDate.SetYear(const Value: Integer);
begin
fDate := RecodeYear (fDate, Value);
end;
function TDate.GetDay: Integer;
begin
Result := DayOf (fDate);
end;
function TDate.GetMonth: Integer;
begin
Result := MonthOf (fDate);
end;
function TDate.GetYear: Integer;
begin
Result := YearOf (fDate);
end;
end.
|
unit uDV_Users;
interface
uses
Data.Win.ADODB, System.Classes, uMainDataSet;
type
TDV_Users = class
private
class function GetId: string; static;
class function GetPersonalNumber: string; static;
class function GetSurname: string; static;
class function GetName: string; static;
class function GetUserName: string; static;
class function GetIdWorkStation: string; static;
class function GetPosition: string; static;
class function GetDescription: string; static;
class function GetDateOfBirth: string; static;
class function GetPassword: string; static;
class function GetBackupPassword: string; static;
class function GetPhotoFile: string; static;
class function GetPhotoName: string; static;
class function GetNumberOfAuthorization: string; static;
class function GetPhoneNumber: string; static;
class function GetEmail: string; static;
public
class function CreateDV_Users(AOwner: TComponent): TMainDataSet; static;
class function GetTabName: string;
class property Id: string read GetId;
class property PersonalNumber: string read GetPersonalNumber;
class property Surname: string read GetSUrname;
class property Name: string read GetName;
class property UserName: string read GetUserName;
class property IdWorkStation: string read GetIdWorkStation;
class property Position: string read GetPosition;
class property Description: string read GetDescription;
class property DateOfBirth: string read GetDateOfBirth;
class property Password: string read GetPassword;
class property BackuPassword: string read GetBackupPassword;
class property PhotoFile: string read GetPhotoFile;
class property PhotoName: string read GetPhotoName;
class property NumberOfAutohrization: string read GetNumberOfAuthorization;
class property PhoneNumber: string read GetPhoneNumber;
class property Email: string read GetEmail;
end;
implementation
uses
uDMConnection;
{ TDV_Work }
class function TDV_Users.CreateDV_Users(AOwner: TComponent): TMainDataSet;
begin
Result := TMainDataSet.Create(AOwner);
Result.CommandText := 'SELECT * FROM ' + TDV_Users.GetTabName;
end;
class function TDV_Users.GetBackupPassword: string;
begin
Result := 'backupPassword';
end;
class function TDV_Users.GetDateOfBirth: string;
begin
Result := 'dateOfBirth';
end;
class function TDV_Users.GetDescription: string;
begin
Result := 'description';
end;
class function TDV_Users.GetEmail: string;
begin
Result := 'email';
end;
class function TDV_Users.GetId: string;
begin
Result := 'id';
end;
class function TDV_Users.GetIdWorkStation: string;
begin
Result := 'idWorkstation';
end;
class function TDV_Users.GetName: string;
begin
Result := 'name';
end;
class function TDV_Users.GetNumberOfAuthorization: string;
begin
Result := 'numberOfAuthorization';
end;
class function TDV_Users.GetPassword: string;
begin
Result := 'password';
end;
class function TDV_Users.GetPersonalNumber: string;
begin
Result := 'personalNumber';
end;
class function TDV_Users.GetPhoneNumber: string;
begin
Result := 'phoneNumber';
end;
class function TDV_Users.GetPhotoFile: string;
begin
Result := 'photoFile';
end;
class function TDV_Users.GetPhotoName: string;
begin
Result := 'photoName';
end;
class function TDV_Users.GetPosition: string;
begin
Result := 'position';
end;
class function TDV_Users.GetSurname: string;
begin
Result := 'surname';
end;
class function TDV_Users.GetTabName: string;
begin
Result := 'tabUsers';
end;
class function TDV_Users.GetUserName: string;
begin
Result := 'userName';
end;
end.
|
unit dcMemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, datacontroller, db, ffsException, ffsutils;
type
TdcMemo = class(TMemo)
private
Fclearing: boolean;
FOptLineDivide: string;
procedure Setclearing(const Value: boolean);
function GetDatabufIndex: integer;
procedure SetDataBufIndex(const Value: integer);
procedure SetOptLineDivide(const Value: string);
private
{ Private declarations }
fdcLink : TdcLink;
fTranData : String;
OldReadOnly : boolean;
property clearing : boolean read Fclearing write Setclearing;
protected
{ Protected declarations }
// std data awareness
function GetDataField:string;
procedure SetDataField(value:string);
// data controller
function GetDataController:TDataController;
procedure SetDataController(value:TDataController);
function GetDataSource:TDataSource;
procedure SetDataSource(value:TDataSource);
procedure ReadData(sender:TObject);
procedure WriteData(sender:TObject);
procedure ClearData(sender:TObject);
procedure Change;override;
procedure DoEnter;override;
procedure DoExit;override;
public
{ Public declarations }
constructor Create(AOwner:Tcomponent);override;
destructor Destroy;override;
property TranData : String read fTranData;
published
{ Published declarations }
property DataController : TDataController read GetDataController write setDataController;
property DataField : String read GetDataField write SetDataField;
property DataSource : TDataSource read getDataSource write SetDataSource;
property DatabufIndex:integer read GetDatabufIndex write SetDataBufIndex;
property OptLineDivide:string read FOptLineDivide write SetOptLineDivide;
end;
procedure Register;
implementation
constructor TdcMemo.Create(AOwner:Tcomponent);
begin
inherited;
fdclink := tdclink.create(self);
fdclink.OnReadData := ReadData;
fdclink.OnWriteData := WriteData;
fdclink.OnClearData := ClearData;
end;
destructor TdcMemo.Destroy;
begin
fdclink.Free;
inherited;
end;
function TdcMemo.getdatasource;
begin
result := fdclink.DataSource;
end;
procedure TdcMemo.SetDatasource(value:TDataSource);
begin
end;
procedure TdcMemo.SetDataController(value:TDataController);
begin
fdcLink.datacontroller := value;
end;
function TdcMemo.GetDataController:TDataController;
begin
result := fdcLink.DataController;
end;
function TdcMemo.GetDataField:string;
begin
result := fdcLink.FieldName;
end;
procedure TdcMemo.SetDataField(value:string);
begin
fdcLink.FieldName := value;
end;
procedure TdcMemo.ReadData;
var s : string;
p : integer;
begin
if not assigned(fdclink.DataController) then exit;
if not assigned(fdclink.datacontroller.databuf) then exit;
if not assigned(fdclink.DataController) then exit;
s := fdclink.datacontroller.databuf.AsString[DataBufIndex];
if not empty(FOptLineDivide) then begin
p := pos(FOptLineDivide, s);
while p > 0 do begin
delete(s,p,length(FOptLineDivide));
insert(crlf,s,p);
p := pos(FOptLineDivide, s);
end;
end;
Text := s;
Modified := false;
end;
procedure TdcMemo.ClearData;
begin
clearing := true;
lines.Clear;
clearing := false;
end;
procedure TdcMemo.WriteData;
var s : string;
x : integer;
begin
if ReadOnly then exit;
if not assigned(fdclink.DataController) then exit;
if not assigned(fdclink.datacontroller.databuf) then exit;
if not empty(FOptLineDivide) then begin
s := '';
for x := 0 to Lines.Count - 1 do s := s + Lines[x] + FOptLineDivide;
fdclink.datacontroller.databuf.asString[DataBufIndex] := s;
end
else fdclink.datacontroller.databuf.asString[DataBufIndex] := text;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcMemo]);
end;
procedure TdcMemo.Change;
begin
if not clearing then fdclink.BeginEdit;
inherited;
end;
procedure TdcMemo.DoEnter;
begin
OldReadOnly := ReadOnly;
if DataController <> nil then
begin
if datacontroller.ReadOnly then ReadOnly := true;
end;
inherited;
end;
procedure TdcMemo.DoExit;
begin
ReadOnly := OldReadOnly;
inherited;
end;
procedure TdcMemo.Setclearing(const Value: boolean);
begin
Fclearing := Value;
end;
function TdcMemo.GetDatabufIndex: integer;
begin
result := 0;
if assigned(fdclink.Datacontroller) then
if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName);
end;
procedure TdcMemo.SetDataBufIndex(const Value: integer);
begin
// intentionally empty
end;
procedure TdcMemo.SetOptLineDivide(const Value: string);
begin
FOptLineDivide := Value;
end;
end.
|
unit ufmSplash;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ExtCtrls,
Vcl.StdCtrls;
type
TfmSplash = class(TForm)
SplashImage: TImage;
VersionLabel: TLabel;
MessageLabel: TLabel;
RegistrationLabel: TLabel;
ExpirationDateLabel: TLabel;
ExpirationDateCaptionLabel: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure ShowMessage(const AMessage: string);
procedure UpdateRegistrationInformation;
end;
var
fmSplash: TfmSplash;
resourcestring
Str_Registered = 'Registered';
Str_UnRegistered = 'Unegistered';
const
RegisterFlipFlop : array[False..True] of string = (Str_UnRegistered, Str_Registered);
implementation
uses fileinfo, uLicenseDM;
{$R *.dfm}
procedure TfmSplash.FormCreate(Sender: TObject);
var V1, V2, V3, V4: Word;
begin
GetBuildInfo(V1, V2, V3, V4);
VersionLabel.Caption:='v.'+IntToStr(V1)+'.'+IntToStr(V2)+'.'+IntToStr(V3)+'.'+IntToStr(V4);
end;
procedure TfmSplash.ShowMessage(const AMessage: string);
begin
MessageLabel.Caption := AMessage;
MessageLabel.Update;
end;
procedure TfmSplash.UpdateRegistrationInformation;
begin
RegistrationLabel.Caption := RegisterFlipFlop[LicenseDataModule.IsRegistered];
ExpirationDateLabel.Caption := DateToStr(LicenseDataModule.ExpireDate);
end;
end.
|
unit Unit3;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts, System.Rtti,
FMX.Edit, Plan.DBTools, Generics.Collections;
type
TProcClick = procedure(Sender: TObject) of object;
TDomainItem = record
panel: TPanel;
domain: TDomain;
end;
TDomainItemList = TList<TDomainItem>;
TPeriodItem = record
checkbox: TCheckBox;
period: TPeriod;
end;
TPeriodItemList = TList<TPeriodItem>;
TfrmSettings = class(TForm)
tc: TTabControl;
tiDomains: TTabItem;
tiPeriods: TTabItem;
pBtns: TPanel;
btnSave: TButton;
btnCancel: TButton;
btnDomainCreate: TButton;
sbDomains: TScrollBar;
pDomains: TPanel;
pPeriodsInner: TPanel;
sbPeriods: TScrollBar;
pPeriods: TPanel;
function findDomainItemBy(const panel: TPanel): integer;
function findPeriodItemBy(const checkbox: TCheckBox): integer;
procedure addDomainItem(const domain: TDomain);
procedure addPeriodItem(const period: TPeriod);
procedure updateDomainsPositions();
procedure updatePeriodsPositions();
procedure changeColsPos(Sender: TObject; const Step: Integer);
procedure btnCancelClick(Sender: TObject);
procedure btnDomainCreateClick(Sender: TObject);
procedure btnColDeleteClick(Sender: TObject);
procedure btnColUpClick(Sender: TObject);
procedure btnColDownClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure sbDomainsChange(Sender: TObject);
procedure sbPeriodsChange(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSaveClick(Sender: TObject);
procedure edColChange(Sender: TObject);
procedure cbPeriodChange(Sender: TObject);
private
{ Private declarations }
domainItems: TDomainItemList;
deletedDomains: TDomainList;
periodItems: TPeriodItemList;
public
{ Public declarations }
end;
const
panelHeight: Integer = 30;
btnUpName: string = 'Up';
btnDownName: string = 'Down';
btnDeleteName: string = 'Delete';
var
frmSettings: TfrmSettings;
implementation
{$R *.fmx}
{$R *.LgXhdpiTb.fmx ANDROID}
{$R *.SmXhdpiPh.fmx ANDROID}
{$R *.Windows.fmx MSWINDOWS}
{$R *.LgXhdpiPh.fmx ANDROID}
function TfrmSettings.findDomainItemBy(const panel: TPanel): integer;
var
i, k: integer;
begin
k := domainItems.Count - 1;
for i := 0 to k do
begin
if domainItems.Items[i].panel = panel then
begin
result := i;
exit;
end;
end;
raise Exception.Create('Can''t find domain item by panel');
end;
function TfrmSettings.findPeriodItemBy(const checkbox: TCheckBox): integer;
var
i, k: integer;
begin
k := periodItems.Count - 1;
for i := 0 to k do
begin
if periodItems.Items[i].checkbox = checkbox then
begin
result := i;
exit;
end;
end;
raise Exception.Create('Can''t find period item by checkbox');
end;
procedure TfrmSettings.addDomainItem(const domain: TDomain);
var
domainItem: TDomainItem;
p: TPanel;
e: TEdit;
procedure createButton(const name: string; procClick: TProcClick);
var
b: TButton;
begin
b := TButton.Create(self);
b.Text := name;
b.Visible := true;
b.Align := TAlignLayout.MostRight;
b.Parent := p;
b.Height := p.Height;
b.Width := 56;
b.OnClick := procClick;
b.TagString := name;
end;
begin
p := TPanel.Create(self);
p.Align := TAlignLayout.Horizontal;
p.Visible := true;
p.Parent := pDomains;
p.Height := panelHeight;
createButton(btnDeleteName, btnColDeleteClick);
createButton(btnDownName, btnColDownClick);
createButton(btnUpName, btnColUpClick);
e := TEdit.Create(self);
e.Visible := true;
e.Align := TAlignLayout.Client;
e.Parent := p;
e.Height := p.Height;
e.Text := domain.name;
e.OnChange := edColChange;
domainItem.domain := domain;
domainItem.panel := p;
domainItems.Add(domainItem);
end;
procedure TfrmSettings.addPeriodItem(const period: TPeriod);
var
periodItem: TPeriodItem;
c: TCheckBox;
begin
c := TCheckBox.Create(self);
c.Align := TAlignLayout.MostTop;
c.Visible := true;
c.Parent := pPeriodsInner;
c.Height := panelHeight;
c.Text := period.name;
c.IsChecked := period.active;
c.OnChange := cbPeriodChange;
periodItem.period := period;
periodItem.checkbox := c;
periodItems.Add(periodItem);
end;
procedure TfrmSettings.updateDomainsPositions();
var
i, colCount: Integer;
p: TPanel;
b: TButton;
j, childCount: Integer;
domainItem: TDomainItem;
begin
colCount := domainItems.Count;
sbDomains.Max := panelHeight * colCount - pDomains.Height;
dec(colCount);
for i:= 0 to colCount do
begin
domainItem := domainItems.Items[i];
p := domainItem.panel;
p.Position.Y := i * panelHeight - sbDomains.Value;
childCount := p.ChildrenCount - 1;
for j:= 0 to childCount do
begin
if p.Children.Items[j].TagString = btnUpName then begin
b := p.Children.Items[j] as TButton;
b.Enabled := i <> 0;
end
else if p.Children.Items[j].TagString = btnDownName then begin
b := p.Children.Items[j] as TButton;
b.Enabled := i <> colCount;
end;
end;
domainItem.domain.num := i + 1;
domainItems.Items[i] := domainItem;
end;
end;
procedure TfrmSettings.updatePeriodsPositions();
var
i, cnt: Integer;
c: TCheckBox;
begin
cnt := periodItems.Count;
pPeriodsInner.Height := panelHeight * cnt;
sbPeriods.Max := pPeriodsInner.Height - pPeriodsInner.Height;
dec(cnt);
for i:= 0 to cnt do
begin
c := periodItems.Items[i].checkbox;
c.Position.Y := i * panelHeight - sbPeriods.Value;
end;
end;
procedure TfrmSettings.cbPeriodChange(Sender: TObject);
var
c: TCheckBox;
i: Integer;
periodItem: TPeriodItem;
begin
c := Sender as TCheckBox;
i := findPeriodItemBy(c);
periodItem := periodItems.Items[i];
periodItem.period.recstate := TRecordState.Updated;
periodItem.period.active := c.IsChecked;
periodItems.Items[i] := periodItem;
end;
procedure TfrmSettings.changeColsPos(Sender: TObject; const step: Integer);
var
b: TButton;
p: TPanel;
i: Integer;
domainItem: TDomainItem;
begin
b := Sender as TButton;
p := b.Parent as TPanel;
i := findDomainItemBy(p);
domainItem := domainItems.Items[i];
domainItem.domain.recstate := TRecordState.Updated;
domainItems.Items[i] := domainItem;
domainItems.Move(i, i + step);
updateDomainsPositions();
end;
procedure TfrmSettings.edColChange(Sender: TObject);
var
e: TEdit;
p: TPanel;
i: Integer;
domainItem: TDomainItem;
begin
e := Sender as TEdit;
p := e.Parent as TPanel;
i := findDomainItemBy(p);
domainItem := domainItems.Items[i];
domainItem.domain.recstate := TRecordState.Updated;
domainItem.domain.name := e.Text;
domainItems.Items[i] := domainItem;
end;
procedure TfrmSettings.FormClose(Sender: TObject; var Action: TCloseAction);
var
i, k: integer;
begin
k := domainItems.Count - 1;
for i := 0 to k do
begin
domainItems.Items[i].panel.Destroy;
end;
deletedDomains.Clear;
domainItems.Clear;
k := periodItems.Count - 1;
for i := 0 to k do
begin
periodItems.Items[i].checkbox.Destroy;
end;
periodItems.Clear;
end;
procedure TfrmSettings.FormCreate(Sender: TObject);
begin
domainItems := TDomainItemList.Create;
deletedDomains := TDomainList.Create;
periodItems := TPeriodItemList.Create;
sbDomains.SmallChange := panelHeight;
sbPeriods.SmallChange := panelHeight;
end;
procedure TfrmSettings.FormResize(Sender: TObject);
var
isInnerBigger: boolean;
begin
isInnerBigger := pPeriodsInner.Height > pPeriodsInner.Height;
sbPeriods.Enabled := isInnerBigger;
sbPeriods.Visible := isInnerBigger;
if isInnerBigger then
begin
sbPeriods.Max := pPeriodsInner.Height - pPeriodsInner.Height;
end
else
begin
sbPeriods.Max := 0;
end;
end;
procedure TfrmSettings.FormShow(Sender: TObject);
var
domainList: TDomainList;
periodList: TPeriodList;
i, k: integer;
begin
domainList := db.loadDomains;
k := domainList.Count - 1;
for i := 0 to k do
begin
addDomainItem(domainList.Items[i]);
end;
updateDomainsPositions();
periodList := db.loadPeriods;
k := periodList.Count - 1;
for i := 0 to k do
begin
addPeriodItem(periodList.Items[i]);
end;
updatePeriodsPositions();
end;
procedure TfrmSettings.sbDomainsChange(Sender: TObject);
begin
updateDomainsPositions();
end;
procedure TfrmSettings.sbPeriodsChange(Sender: TObject);
begin
pPeriodsInner.Position.Y := -sbPeriods.Value;
end;
procedure TfrmSettings.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSettings.btnDomainCreateClick(Sender: TObject);
var
domain: TDomain;
begin
domain := TDomain.Create(TRecordState.New);
addDomainItem(domain);
updateDomainsPositions();
end;
procedure TfrmSettings.btnColDeleteClick(Sender: TObject);
var
b: TButton;
p: TPanel;
i: Integer;
domain: TDomain;
begin
b := Sender as TButton;
p := b.Parent as TPanel;
i := findDomainItemBy(p);
domain := domainItems.Items[i].domain;
if domain.recstate <> TRecordState.New then
begin
domain.active := false;
domain.recstate := TRecordState.Deleted;
deletedDomains.Add(domain);
end;
domainItems.Delete(i);
p.Destroy;
updateDomainsPositions();
end;
procedure TfrmSettings.btnColUpClick(Sender: TObject);
begin
changeColsPos(Sender, -1);
end;
procedure TfrmSettings.btnSaveClick(Sender: TObject);
var
domains: TDomainList;
periods: TPeriodList;
i, k: integer;
begin
domains := TDomainList.Create();
k := deletedDomains.Count - 1;
for i := 0 to k do
begin
domains.Add(deletedDomains.Items[i]);
end;
k := domainItems.Count - 1;
for i := 0 to k do
begin
domains.Add(domainItems.Items[i].domain);
end;
db.saveDomains(domains);
domains.Clear;
periods := TPeriodList.Create();
k := periodItems.Count - 1;
for i := 0 to k do
begin
periods.Add(periodItems.Items[i].period);
end;
db.savePeriods(periods);
periods.Clear;
Close;
end;
procedure TfrmSettings.btnColDownClick(Sender: TObject);
begin
changeColsPos(Sender, 1);
end;
end.
|
unit Unt_FuncaoLog;
interface
uses
System.SyncObjs;
type
/// <summary>
/// Classe responsável pela geração de LOG
/// </summary>
TGeraLog = class
private
/// <summary>
/// Indica o arquivo em que o LOG será gerado, no caso, no mesmo diretório do executável
/// </summary>
const
C_ARQUIVO = '.\arquivo_log.txt';
private
/// <summary>
/// Seção crítica para o acesso ao arquivo de log
/// </summary>
FCritical: TCriticalSection;
/// <summary>
/// Instância única do objeto
/// </summary>
class var FInstance: TGeraLog;
/// <summary>
/// Método responsável por instanciar o objeto singleton
/// </summary>
class function GetInstancia: TGeraLog; static;
public
/// <summary>
/// Deleta o arquivo de LOG caso o mesma exista e cria a seção crítica
/// </summary>
procedure AfterConstruction; override;
/// <summary>
/// Libera a seção crítica
/// </summary>
procedure BeforeDestruction; override;
/// <summary>
/// Método que efetivamente gera o LOG
/// </summary>
/// <param name="AReferencia">Referência à thread chamadora</param>
/// <param name="AData">Date e hora da geração do LOG</param>
/// <param name="ATextoLog">Texto a ser escrito no arquivo de log</param>
procedure GerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string);
/// <summary>
/// Método que TENTA gerar uma nova linha de LOG
/// </summary>
/// <param name="AReferencia">Referência à thread chamadora</param>
/// <param name="AData">Date e hora da geração do LOG</param>
/// <param name="ATextoLog">Texto a ser escrito no arquivo de log</param>
function TryGerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string): Boolean;
/// <summary>
/// Referência à instância singleton
/// </summary>
class property Instancia: TGeraLog read GetInstancia;
end;
implementation
uses
System.SysUtils;
{ TGeraLog }
procedure TGeraLog.AfterConstruction;
begin
inherited;
DeleteFile(Self.C_ARQUIVO);
Self.FCritical := TCriticalSection.Create;
end;
procedure TGeraLog.BeforeDestruction;
begin
inherited;
Self.FCritical.Free;
end;
procedure TGeraLog.GerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string);
var
_arquivo : TextFile;
sNovaLinha: string;
begin
sNovaLinha := Format('%s|%s|%s', [AReferencia, DateTimeToStr(AData), ATextoLog]);
// Entra na seção crítica
Self.FCritical.Enter;
try
AssignFile(_arquivo, Self.C_ARQUIVO);
if (FileExists(Self.C_ARQUIVO)) then
begin
Append(_arquivo);
end else begin
Rewrite(_arquivo);
end;
Writeln(_arquivo, sNovaLinha);
CloseFile(_arquivo);
finally
// Sai da seção crítica
Self.FCritical.Release;
end;
end;
class function TGeraLog.GetInstancia: TGeraLog;
begin
if not(Assigned(FInstance)) then
begin
FInstance := TGeraLog.Create;
end;
Result := FInstance;
end;
function TGeraLog.TryGerarLog(const AReferencia: string; const AData: TDateTime; const ATextoLog: string): Boolean;
var
_arquivo : TextFile;
sNovaLinha: string;
begin
sNovaLinha := Format('%s|%s|%s', [AReferencia, DateTimeToStr(AData), ATextoLog]);
// Tenta entrar na seção crítica
Result := Self.FCritical.TryEnter;
if (Result) then
begin
try
AssignFile(_arquivo, Self.C_ARQUIVO);
if (FileExists(Self.C_ARQUIVO)) then
begin
Append(_arquivo);
end else begin
Rewrite(_arquivo);
end;
Writeln(_arquivo, sNovaLinha);
CloseFile(_arquivo);
finally
// Sai da seção crítica
Self.FCritical.Release;
end;
end;
end;
initialization
finalization
TGeraLog.Instancia.Free;
end.
|
namespace RemObjects.Elements.RTL.Delphi;
uses
RemObjects.Elements.RTL;
type
TObject = public Object;
Object__Delphi = public extension class(Object)
public
method Destroy; empty; // no-op for compatibility
method Free; empty; // no-op for compatibility
class method InitInstance(Instance: Pointer): TObject; empty;
method CleanupInstance; empty;
method ClassType: TClass; empty;
class method ClassName: ShortString;
begin
{$IF ISLAND}
result := typeOf(self).Name;
{$ELSE}
result := '';
{$ENDIF}
end;
method InstanceClassName: String;
begin
{$IF ISLAND}
result := typeOf(self).Name;
{$ELSE}
result := '';
{$ENDIF}
end;
class method ClassNameIs(const Name: String): Boolean; empty;
class method ClassParent: TClass; empty;
class method ClassInfo: Pointer; empty;
class method InstanceSize: LongInt; empty;
class method InheritsFrom(AClass: TClass): Boolean; empty;
class method MethodAddress(const Name: ShortString): Pointer;
begin
raise new NotSupportedException("TObject.MethodAddress");
end;
class method MethodName(Address: Pointer): ShortString;
begin
raise new NotSupportedException("TObject.MethodName");
end;
method FieldAddress(const Name: ShortString): Pointer;
begin
raise new NotSupportedException("TObject.FieldAddress");
end;
method GetInterface(const IID: TGUID; out Obj): Boolean;
begin
raise new NotSupportedException("TObject.GetInterface");
end;
class method GetInterfaceEntry(const IID: TGUID): PInterfaceEntry;
begin
raise new NotSupportedException("TObject.GetInterfaceEntry");
end;
class method GetInterfaceTable: PInterfaceTable;
begin
raise new NotSupportedException("TObject.GetInterfaceTable");
end;
method SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult;
begin
raise new NotSupportedException("TObject.SafeCallException");
end;
procedure AfterConstruction; {virtual;} empty;
procedure BeforeDestruction; {virtual;} empty;
procedure Dispatch(var Message); {virtual;}
begin
raise new NotSupportedException("TObject.Dispatch");
end;
procedure DefaultHandler(var Message); {virtual;}
begin
raise new NotSupportedException("TObject.DefaultHandler");
end;
class method NewInstance: TObject; {virtual;}
begin
result := new self;
end;
procedure FreeInstance; {virtual;}
begin
{$IF ECHOES}
IDisposable(self).Dispose();
{$ELSEIF TOFFEE}
{$ELSEIF COOPER}
{$ELSEIF ISLAND}
{$ENDIF}
end;
end;
{$IF ISLAND AND WINDOWS}
extension method RemObjects.Elements.System.String.ToLPCWSTR: rtl.LPCWSTR;
begin
if String.IsNullOrEmpty(self) then exit nil;
var arr := ToCharArray(true);
exit rtl.LPCWSTR(@arr[0]);
end;
{$ENDIF}
end. |
unit gm_creature;
interface
uses
gm_engine, gm_patterns, gm_item, gm_obj, Spell, Entity, CustomCreature;
type
TSlotRec = record
Item: TItem;
Name: string;
Pos: TPoint;
end;
type
TSlot = (slHead, slAmulet, slBody, slCloak, slRing1, slRing2, slGloves, slRHand, slLHand, slBelt, slBoots);
type
TCreature = class(TCustomCreature)
Pat : TCrPat;
MP : Pointer;
Sp : TPoint;
WalkTo : TPoint;
NextStep : TPoint;
AtT : Integer;
Team : Integer;
Enemy : TCreature;
InFog : Boolean;
NoAtack : Boolean;
LifeTime : Integer;
Spells : array of TSpell;
SpellsCnt : Integer;
UseSpellN : Integer;
Effects : array of TSpell;
EffectsCnt: Integer;
ParamValue: array of Integer;
Items : array of TItem;
ItemsCnt : Integer;
Gold : Cardinal;
Moved : Boolean;
SlotItem : array [TSlot] of TSlotRec;
constructor Create(CrPat : TCrPat);
destructor Destroy; override;
procedure Draw;
procedure Update;
function GetDamageInfo: string;
procedure Walk(dx, dy : Integer);
function CreateItem(ItemPat: TItemPat; Count: Integer; Suffix, Material: string) : Boolean;
function GetParamValue(ParamName: string): Integer;
procedure SetParamValue(ParamName: string; Value: Integer);
procedure AddExp(ExpCnt : Integer);
procedure WalkAway(tx1, ty1 : Integer);
procedure AddSpell(SpellName : String);
procedure UseSpell(SpellN : Integer);
procedure Calculator;
procedure AddEffect(EffectName : String; Time : Integer);
procedure DelEffect(EffectName : String);
function HasEffect(EffectName : String) : Boolean;
procedure UpdateEffects;
end;
var
PC: TCreature;
procedure DrawText(X, Y: Integer; Text: string);
procedure Info(Text: string; B: Boolean = False);
implementation
uses
gm_map, PathFind, Utils, Resources, Stat, SceneFrame, Belt;
{ TCreature }
procedure DrawText(X, Y: Integer; Text: string);
var
W: Integer;
begin
SomeText := Text;
STPos := Point(X, Y);
STTime := Length(Text) * 10;
W := Round(TextWidth(Font[ttFont1], Text));
if STPos.X + w div 2 > ScreenWidth then STPos.X := ScreenWidth - w div 2;
if STPos.X + w div 2 < 0 then STPos.X := w div 2;
end;
procedure Info(Text: string; B: Boolean = False);
begin
if (Text = '') then Exit;
if B then
DrawText(ScreenWidth div 2, ScreenHeight - 60, Text)
else DrawText(ScreenWidth div 2, ScreenHeight div 2 - 32, Text);
end;
constructor TCreature.Create(CrPat : TCrPat);
var
I: Integer;
P: TPoint;
S: TSlot;
N: string;
procedure AddSlot(S: TSlot; V: string; P: TPoint);
begin
if (V = '') then Exit;
SlotItem[S].Name := V;
SlotItem[S].Pos := P;
end;
begin
inherited Create(CrPat.Health, CrPat.Mana, 7);
Pat := CrPat;
WalkTo.X := -1;
NoAtack := True;
SpellsCnt := 0;
UseSpellN := -1;
EffectsCnt:= 0;
LifeTime := 0;
Gold := 0;
SetLength(ParamValue, CrStatsCnt);
for I := 0 to CrStatsCnt - 1 do ParamValue[i] := Pat.ParamValue[i];
ItemsCnt := 0;
//
P := Point(0, 0);
for S := slHead to slBoots do
begin
N := '';
case S of
slBody : N := 'BODY';
slHead : N := 'HEAD';
slBelt : N := 'BELT';
slBoots : N := 'BOOTS';
slGloves : N := 'GLOVES';
slAmulet : N := 'AMULET';
slCloak : N := 'CLOAK';
slRHand : N := 'RHAND';
slLHand : N := 'LHAND';
slRing1 : N := 'RING';
slRing2 : N := 'RING';
end;
AddSlot(S, N, P);
SlotItem[S].Pos := P;
if (S = slRHand) then Continue;
Inc(P.X, (4 * SlotSize));
if (P.X > (4 * SlotSize)) then
begin
Inc(P.Y, SlotSize);
P.X := 0;
end;
end;
end;
destructor TCreature.Destroy;
begin
inherited;
end;
procedure TCreature.Draw;
var
S: TSlot;
I: Integer;
Tex: TTexture;
begin
if (SlotItem[slCloak].Item.Count > 0) then Render2D(SlotItem[slCloak].Item.Pat.Tex, Pos.X * 32 + Sp.X, Pos.Y * 32 + Sp.Y, 32, 32, 0, 2);
RenderSprite2D(Pat.Tex, Pos.X * 32 + Sp.X + Pat.Offset.X, Pos.Y * 32 + Sp.Y + Pat.Offset.Y, Pat.Tex.Width, Pat.Tex.Height, 0);
for S := slHead to slBoots do
if (S <> slCloak) and (SlotItem[S].Item.Count > 0) then
begin
Tex := SlotItem[S].Item.Pat.Tex;
if (Tex.Width > 32) then
Render2D(Tex, Pos.X * 32 + Sp.X, Pos.Y * 32 + Sp.Y, 32, 32, 0, 2);
end;
if HasEffect('Заморозка') then RenderSprite2D(Resource[ttIce], Pos.X * 32, Pos.Y * 32, 32, 32, 0, 150);
// if HasEffect('Отравление') then RenderSprite2D(Resource[ttPoisonEffect], Pos.X * 32, Pos.Y * 32, Resource[ttPoisonEffect].Width, Resource[ttPoisonEffect].Height, 0, 150);
if not Self.Life.IsMax then
begin
i := Round(Life.Cur / Life.Max * 24);
Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 4{ + 26}, 32 - 8, 4, $333333, 255, PR2D_FILL);
if HasEffect('Отравление') then Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 4{ + 26}, i, 4, $33FF33, 255, PR2D_FILL)
else Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 4{ + 26}, i, 4, $FF3333, 255, PR2D_FILL);
Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 4{ + 26}, 32 - 8, 4, $000000, 255);
end;
if not Self.Mana.IsMax then
begin
i := Round(Mana.Cur / Mana.Max * 24);
Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 7{ + 26}, 32 - 8, 4, $333333, 255, PR2D_FILL);
Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 7{ + 26}, i, 4, $3333FF, 255, PR2D_FILL);
Rect2D(Pos.X * 32 + 4, Pos.Y * 32 - 7{ + 26}, 32 - 8, 4, $000000, 255);
end;
end;
procedure TCreature.Update;
var
M : TMap;
p : TPoint;
si : PItem;
begin
if Life.IsMin then Exit;
M := TMap(MP);
if UseSpellN <> -1 then
if Mana.Cur >= Spells[UseSpellN].Mana then
begin
if (Spells[UseSpellN].Name = 'Огненный шар') and (Enemy <> nil) then
if M.LineOfSign(Pos, Enemy.Pos, False) then
begin
M.CreateBullet(TItemPat(GetPattern('ITEM', 'Fireball')), Self, Enemy);
Mana.Cur := Mana.Cur - Spells[UseSpellN].Mana;
UseSpellN := -1;
WalkTo.X := -1;
if Self = PC then
begin
Enemy := nil;
PC.Moved := True;
end;
Exit;
end;
end;
UseSpellN := -1;
if Enemy <> nil then
if not Enemy.Life.IsMin then
begin
si := nil;
if (Self = PC) then
begin
if (PC.Items[GetActBeltSlot].Count > 0) then
if PC.Items[GetActBeltSlot].Pat.Throw then
si := @PC.Items[GetActBeltSlot];
end else begin
if (SlotItem[slRHand].Item.Count > 0) then
if SlotItem[slRHand].Item.Pat.Throw then
si := @SlotItem[slRHand];
end;
if (SlotItem[slRHand].Item.Count > 0) and (SlotItem[slLHand].Item.Count > 0) then
if (SlotItem[slRHand].Item.Pat.Bow) and (SlotItem[slLHand].Item.Pat.Arrow) then si := @SlotItem[slLHand];
if (si <> nil) then
if GetDist(Pos, Enemy.Pos) < 8 then
if M.LineOfSign(Pos, Enemy.Pos, False) = True then
begin
M.CreateBullet(si.Pat, Self, Enemy);
si.Count := si.Count - 1;
WalkTo.X := -1;
if (Self = PC) then
begin
Enemy := nil;
PC.Moved := True;
end;
Exit;
end;
if Pat.Name = 'NECROMANCER' then
if GetDist(Pos, Enemy.Pos) < 7 then
if M.LineOfSign(Pos, Enemy.Pos, False) = True then
begin
M.CreateBullet(TItemPat(GetPattern('ITEM', 'Iceball')), Self, Enemy);
WalkTo.X := -1;
Exit;
end;
WalkTo := Enemy.Pos;
if (si = nil) and (SlotItem[slRHand].Item.Count > 0) then
if SlotItem[slRHand].Item.Pat.Bow then
begin
Enemy := nil;
WalkTo.X := -1;
end;
end;
if (WalkTo.X = Pos.X) and (WalkTo.Y = Pos.Y) then WalkTo.X := -1;
if WalkTo.X <> -1 then
begin
CreateWave(M, WalkTo.X, WalkTo.Y, Pos.X, Pos.Y);
NextStep := GetNextStep(Pos);
if NextStep.X = -1 then
begin
WalkTo.X := -1;
if Self = PC then Enemy := nil;
end;
P := Pos;
if WalkTo.X <> -1 then Walk(NextStep.X - Pos.X, NextStep.Y - Pos.Y);
if (Pos.X = p.X) and (Pos.Y = p.Y) then WalkTo.X := -1;
end;
end;
procedure TCreature.Walk(dx, dy : Integer);
var
i, j, Dmg, s: Integer;
M: TMap;
P: TPoint;
Cr: TCreature;
si: Single;
begin
LookAtObj := nil;
M := TMap(MP);
P.X := Pos.X + dx;
P.Y := Pos.Y + dy;
if (P.X < 0) or (P.Y < 0) or (P.X >= M.Width) or (P.Y >= M.Height) then Exit;
if M.Objects.Obj[P.X, P.Y] <> nil then
begin
if (Self = PC) and (M.Objects.Obj[P.X, P.Y].Pat.Container) then LookAtObj := M.Objects.Obj[P.X, P.Y];
if M.Objects.Obj[P.X, P.Y].Pat.Name = 'DOOR' then
if M.Objects.Obj[P.X, P.Y].FrameN = 0 then
begin
if Self = PC then PC.Moved := True;
M.Objects.Obj[P.X, P.Y].FrameN := 1;
M.Objects.Obj[P.X, P.Y].BlockLook := False;
M.Objects.Obj[P.X, P.Y].BlockWalk := False;
M.UpdateFog(Pos, 7);
Exit;
end;
if (M.Objects.Obj[P.X, P.Y].Pat.Name = 'CHEST') then
if M.Objects.Obj[P.X, P.Y].FrameN = 0 then
begin
M.Objects.Obj[P.X, P.Y].FrameN := 1;
Exit;
end;
if (M.Objects.Obj[P.X, P.Y].Pat.Name = 'PORTAL') then
begin
Info('(((*)))');
Exit;
end;
if (M.Objects.Obj[P.X, P.Y].Pat.Name = 'SHRINE') then
if M.Objects.Obj[P.X, P.Y].FrameN = 0 then
begin
if not Life.IsMax then
begin
M.Objects.Obj[P.X, P.Y].FrameN := 1;
Info('Полное исцеление');
Life.SetToMax;
end;
Exit;
end;
if M.Objects.Obj[P.X, P.Y].BlockWalk then Exit;
end;
for i := 0 to M.Creatures.Count - 1 do
begin
Cr := TCreature(M.Creatures[i]);
if Cr = Self then Continue;
if (Cr.Pos.X = P.X) and (Cr.Pos.Y = P.Y) then
begin
if Team = Cr.Team then Exit;
if SlotItem[slRHand].Item.Count > 0 then
if SlotItem[slRHand].Item.Pat.Bow then Exit;
if Self = PC then
begin
PC.Moved := True;
Enemy := nil;
end;
if Cr.HasEffect('Заморозка') then Cr.AddEffect('Заморозка', 1);
Dmg := 0;
if SlotItem[slRHand].Item.Count = 0 then
begin
s := GetParamValue('Сила');
Dmg := GetParamValue('Без оружия');
Dmg := Round((s + 5) * 0.2 + (Dmg + 5) * 0.3);
end else
begin
if SlotItem[slRHand].Item.Pat.Sword = True then
begin
s := GetParamValue('Сила');
Dmg := GetParamValue('Меч');
Dmg := Round((s + 5) * 0.2 + (Dmg + 5) * 0.3 + SlotItem[slRHand].Item.Pat.Damage.Min * 0.3);
end;
if SlotItem[slRHand].Item.Pat.Axe = True then
begin
s := GetParamValue('Сила');
Dmg := GetParamValue('Топор');
Dmg := Round((s + 5) * 0.2 + (Dmg + 5) * 0.3 + SlotItem[slRHand].Item.Pat.Damage.Min * 0.3);
end;
end;
if Random(20) < Cr.GetParamValue('Agility') then Dmg := Dmg div 2;
si := 1;
if SlotItem[slHead].Item.Count > 0 then si := si - 0.1;
if SlotItem[slLHand].Item.Count > 0 then
if SlotItem[slLHand].Item.Pat.Shield then si := si - 0.2;
Dmg := Round(Dmg * si);
Cr.Life.Dec(Dmg);
if Cr.Life.IsMin then AddExp(Cr.Pat.Exp);
Sp.X := (Cr.Pos.X - Pos.X) * 5;
Sp.Y := (Cr.Pos.Y - Pos.Y) * 5;
AtT := 10;
if HasEffect('Вампиризм') then
begin
Life.Inc(3 + GetParamValue('Магия'));
end;
// Отравление
{ if ((Pat.Name = 'SCORPION') or (Pat.Name = 'SNAKE')) and (Random(10) = 0)
and not HasEffect('Сопротивление яду') then
begin
Cr.AddEffect('Отравление', 41);
if (Cr = PC) then Info('Отравление ядом');
end; }
Cr.WalkTo.X := -1;
if (Cr = PC) then Cr.Enemy := nil;
Exit;
end;
end;
Self.SetPosition(P);
// Автоподнятие предметов с пола
if Self = PC then
begin
i := 0;
while i < M.ItemsCnt do
begin
if (M.Items[i].Pos.X = Pos.X) and (M.Items[i].Pos.Y = Pos.Y) then
begin
if CreateItem(M.Items[i].Pat, M.Items[i].Count, M.Items[i].Suffix, M.Items[i].Material) = False then Break;
for j := i to M.ItemsCnt - 2 do M.Items[j] := M.Items[j + 1];
M.ItemsCnt := M.ItemsCnt - 1;
SetLength(M.Items, M.ItemsCnt);
WalkTo.X := -1;
i := i - 1;
end;
i := i + 1;
end;
end;
end;
function TCreature.CreateItem(ItemPat: TItemPat; Count: Integer; Suffix, Material: string): Boolean;
var
i : Integer;
begin
Result := True;
if ItemPat.CanGroup then
for i := 0 to ItemsCnt - 1 do
if Items[i].Count > 0 then
if Items[i].Pat = ItemPat then
begin
Items[i].Count := Items[i].Count + Count;
Exit;
end;
for i := 0 to ItemsCnt - 1 do
if Items[i].Count = 0 then
begin
Items[i].Pat := ItemPat;
Items[i].Count := Count;
Items[I].Suffix := Suffix;
Items[I].Material := Material;
Exit;
end;
if ItemsCnt = InvCapacity then
begin
Result := False;
Exit;
end;
ItemsCnt := ItemsCnt + 1; {I}
SetLength(Items, ItemsCnt);
Items[ItemsCnt - 1].Pat := ItemPat;
Items[ItemsCnt - 1].Count := Count;
Items[ItemsCnt - 1].Left := Rand(0, 16);
Items[ItemsCnt - 1].Top := Rand(-ITEM_AMP, ITEM_AMP);
Items[ItemsCnt - 1].Dir := (Rand(0, 1) = 0);
Items[ItemsCnt - 1].Suffix := Suffix;
Items[ItemsCnt - 1].Material := Material;
end;
procedure TCreature.SetParamValue(ParamName: string; Value: Integer);
var
I: Integer;
begin
for I := 0 to CrStatsCnt - 1 do
if (CrStats[I].RuName = ParamName) or (CrStats[I].Name = ParamName) then
begin
ParamValue[I] := Value;
Exit;
end;
end;
function TCreature.GetParamValue(ParamName: string): Integer;
var
I: Integer;
begin
Result := 0;
for i := 0 to CrStatsCnt - 1 do
if CrStats[i].RuName = ParamName then
begin
Result := ParamValue[i];
Exit;
end;
for i := 0 to CrStatsCnt - 1 do
if CrStats[i].Name = ParamName then
begin
Result := ParamValue[i];
Exit;
end;
end;
procedure TCreature.AddExp(ExpCnt : Integer);
var
V: Integer;
begin
V := Exp.Cur + ExpCnt;
Exp.Cur := V;
if (V >= Exp.Max) then
begin
Exp.Cur := V - Exp.Max;
Exp.SetMax(Exp.Max + Round(Exp.Max * 0.8));
if Self = PC then
begin
StatPoints := StatPoints + 1;
SkillPoints := SkillPoints + 1;
Info('Повышение уровня');
end;
end;
end;
procedure TCreature.WalkAway(tx1, ty1 : Integer);
var
M: TMap;
P: TPoint;
I: Integer;
B: Boolean;
begin
M := TMap(MP);
for i := 0 to 8 do
begin
P := Pos;
if i = 0 then
begin
P.X := Pos.X + (Pos.X - tx1);
P.Y := Pos.Y + (Pos.Y - ty1);
end;
if i = 1 then P.X := P.X - 1;
if i = 2 then P.X := P.X + 1;
if i = 3 then P.Y := P.Y - 1;
if i = 4 then P.Y := P.Y + 1;
if (i = 5) or (i = 6) then P.X := P.X - 1;
if (i = 7) or (i = 8) then P.X := P.X + 1;
if (i = 5) or (i = 7) then P.Y := P.Y - 1;
if (i = 6) or (i = 8) then P.Y := P.Y + 1;
if (P.X < 0) or (P.Y < 0) or (P.X >= Map.Width) or (P.Y >= Map.Height) then Continue;
B := True;
if M.Objects.Obj[P.X, P.Y] <> nil then
if M.Objects.Obj[P.X, P.Y].BlockWalk = True then B := False;
if M.GetCreature(P) <> nil then B := False;
if B then
begin
Walk(P.X - Pos.X, P.Y - Pos.Y);
PC.Moved := True;
Exit;
end;
end;
end;
procedure TCreature.AddSpell(SpellName : String);
var
i, n : Integer;
begin
n := -1;
for i := 0 to AllSpellsCnt - 1 do
if AllSpells[i].Name = SpellName then
begin
n := i;
Break;
end;
if n = -1 then Exit;
SpellsCnt := SpellsCnt + 1;
Setlength(Spells, SpellsCnt);
Spells[SpellsCnt - 1] := AllSpells[n];
end;
procedure TCreature.UseSpell(SpellN : Integer);
var
i, j, k : Integer;
M : TMap;
begin
if Spells[SpellN].Name = 'Лечение' then
begin
Life.Inc(10 + GetParamValue('Магия') * 2);
Mana.Cur := Mana.Cur - Spells[SpellN].Mana;
SellSpellN := -1;
PC.Moved := True;
Exit;
end;
if Spells[SpellN].Name = 'Противоядие' then
begin
DelEffect('Отравление');
Mana.Cur := Mana.Cur - Spells[SpellN].Mana;
SellSpellN := -1;
PC.Moved := True;
Exit;
end;
if Spells[SpellN].Name = 'Сопротивление яду' then
begin
AddEffect('Сопротивление яду', 51);
Mana.Cur := Mana.Cur - Spells[SpellN].Mana;
SellSpellN := -1;
PC.Moved := True;
Exit;
end;
if Spells[SpellN].Name = 'Вампиризм' then
begin
AddEffect('Вампиризм', 21);
Mana.Cur := Mana.Cur - Spells[SpellN].Mana;
SellSpellN := -1;
PC.Moved := True;
Exit;
end;
if Spells[SpellN].Name = 'Армагеддон' then
begin
M := TMap(MP);
for k := 0 to 50 do
begin
i := Random(M.Width);
j := Random(M.Height);
//if (ABS(PC.TX - i) < 3) and (ABS(PC.TY - j) < 3) then Continue;
M.Explosive(i, j);
end;
Mana.Cur := Mana.Cur - Spells[SpellN].Mana;
SellSpellN := -1;
PC.Moved := True;
Exit;
end;
end;
procedure TCreature.AddEffect(EffectName: string; Time: Integer);
var
i: Integer;
begin
if (Pat.Name = 'GOLEM') and (EffectName = 'Отравление') then Exit;
for i := 0 to EffectsCnt - 1 do
if Effects[i].Name = EffectName then
begin
Effects[i].Int := Time;
Exit;
end;
EffectsCnt := EffectsCnt + 1;
Setlength(Effects, EffectsCnt);
Effects[EffectsCnt - 1].Name := EffectName;
Effects[EffectsCnt - 1].Int := Time;
end;
procedure TCreature.DelEffect(EffectName: string);
var
i, j: Integer;
begin
for i := 0 to EffectsCnt - 1 do
if Effects[i].Name = EffectName then
begin
for j := i to EffectsCnt - 2 do
Effects[j] := Effects[j + 1];
EffectsCnt := EffectsCnt - 1;
Exit;
end;
end;
function TCreature.HasEffect(EffectName: string) : Boolean;
var
I: Integer;
begin
Result := True;
for i := 0 to EffectsCnt - 1 do
if Effects[i].Name = EffectName then Exit;
Result := False;
end;
procedure TCreature.UpdateEffects;
var
I, J: Integer;
begin
J := 0;
for I := 0 to EffectsCnt - 1 do
begin
if Effects[I].Name = 'Отравление' then Life.Dec;
if (Effects[i].Int = 1) and (Effects[i].Name = 'Гипноз') then Team := 1;
if (Effects[i].Int < 100) then Effects[i].Int := Effects[i].Int - 1;
if (Effects[i].Int = 0) then Continue;
if (i <> j) then Effects[j] := Effects[i];
j := j + 1;
end;
EffectsCnt := j;
end;
procedure TCreature.Calculator;
var
S: TSlot;
Bow, Arrow: Boolean;
function IsNSlot(S: TSlot): Boolean;
begin
Result := (SlotItem[S].Item.Pat = nil) or (SlotItem[S].Item.Count <= 0)
end;
procedure Add(ParamName: string; Value: Integer);
begin
if (Value > 0) then SetParamValue(ParamName, GetParamValue(ParamName) + Value);
end;
begin
SetParamValue('MinDamage', 0);
SetParamValue('MaxDamage', 0);
SetParamValue('Defense', 0);
SetParamValue('Block', 0);
SetParamValue('BStrength', 0);
Bow := not IsNSlot(slRHand) and SlotItem[slRHand].Item.Pat.Bow;
Arrow := not IsNSlot(slLHand) and SlotItem[slLHand].Item.Pat.Arrow;
for S := slHead to slBoots do
begin
if IsNSlot(S) then Continue;
if not (((S = slRHand) and Bow and not Arrow) or ((S = slLHand) and Arrow and not Bow)) then
begin
Add('MinDamage', SlotItem[S].Item.Pat.Damage.Min);
Add('MaxDamage', SlotItem[S].Item.Pat.Damage.Max);
end;
Add('Defense', SlotItem[S].Item.Pat.Defense);
Add('Block', SlotItem[S].Item.Pat.Block);
end;
end;
function TCreature.GetDamageInfo: string;
begin
if (GetParamValue('MinDamage') > 0) and (GetParamValue('MaxDamage') > 0) then
Result := IntToStr(GetParamValue('MinDamage')) + '-' + IntToStr(GetParamValue('MaxDamage')) else Result := '0';
end;
end.
|
unit ufrmCadastroTitulos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask, RxToolEdit, RxCurrEdit,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin, RxLookup, uTitulos,
uTitulosControl, System.ImageList, Vcl.ImgList, PngImageList;
type
TfrmCadastroTitulos = class(TForm)
ToolBar: TToolBar;
btnSalvar: TToolButton;
btnCancelar: TToolButton;
gbxCadastro: TGroupBox;
pnBottom: TPanel;
Label1: TLabel;
edtDescricao: TEdit;
Label2: TLabel;
cedValor: TCurrencyEdit;
Label3: TLabel;
dtpDataVencimento: TDateTimePicker;
dblStatus: TRxDBLookupCombo;
Label4: TLabel;
Label5: TLabel;
mmObservacoes: TMemo;
icones: TPngImageList;
procedure FormCreate(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
tituloControl: TTitulosControl;
public
tituloID: integer;
editar: boolean;
procedure clear;
end;
var
frmCadastroTitulos: TfrmCadastroTitulos;
implementation
{$R *.dfm}
procedure TfrmCadastroTitulos.btnCancelarClick(Sender: TObject);
begin
frmCadastroTitulos.Close;
end;
procedure TfrmCadastroTitulos.btnSalvarClick(Sender: TObject);
begin
tituloControl.setNovoTitulo(editar);
end;
procedure TfrmCadastroTitulos.clear;
begin
edtDescricao.Clear;
dtpDataVencimento.Date := Date;
cedValor.Clear;
dblStatus.ResetField;
mmObservacoes.Clear;
end;
procedure TfrmCadastroTitulos.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
try
tituloControl.Free;
finally
Action := caFree;
frmCadastroTitulos := nil;
end;
end;
procedure TfrmCadastroTitulos.FormCreate(Sender: TObject);
begin
tituloControl := TTitulosControl.create;
dblStatus.LookupField := 'id';
dblStatus.LookupDisplay := 'descricao';
dblStatus.LookupSource := tituloControl.getStatus;
dblStatus.DisplayEmpty := ' ';
dtpDataVencimento.MinDate := Date;
dtpDataVencimento.Date := Date;
editar := false;
cedValor.MaxLength := 9;
end;
end.
|
//Exercicio 67: Armazenar 250 elementos numéricos num arranjo de dados e verificar se existe(m) algum(ns) elemento(s)
//igual(is) ao número 14. Em caso afirmativo, exibir as posições em que estão armazenados.
{ Solução em Portugol
Algoritmo Exercicio 67;
Var
N: vetor[1..250] de inteiro;
i, quantidade_14: inteiro;
Inicio
quantidade_14 <- 0;
exiba("Programa que armazena 250 números e diz quais/quantos deles são iguais a 14.");
para i <- 1 até 250 faça
exiba("Digite o ",i,"º número:");
leia(N[i]);
se(N[i] = 14)
então quantidade_14 <- quantidade_14 + 1;
fimse;
fimpara;
exiba("A quantidade de 14 que aparecem entre os 250 é: ", quantidade_14," e eles são:);
para i <- 1 até 250 faça
se(N[i] = 14)
então exiba(i," ");
fimse;
fimpara;
Fim.
}
// Solução em Pascal
Program Exercicio67;
uses crt;
var
N: array[1..250] of integer;
i, quantidade_14: integer;
begin
clrscr;
quantidade_14 := 0;
writeln('Programa que armazena 250 números e diz quais/quantos deles são iguais a 14.');
for i := 1 to 250 do
Begin
writeln('Digite o ',i,'º número:');
readln(N[i]);
if(N[i] = 14)
then quantidade_14 := quantidade_14 + 1;
End;
writeln('A quantidade de 14 que aparecem entre os 250 é: ', quantidade_14,' e eles estão nas posições: ');
for i := 1 to 250 do
if(N[i] = 14)
then write(i,' ');
repeat until keypressed;
end. |
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerT61String;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
ClpDerStringBase,
ClpAsn1Tags,
ClpAsn1OctetString,
ClpAsn1Object,
ClpIProxiedInterface,
ClpDerOutputStream,
ClpCryptoLibTypes,
ClpIAsn1TaggedObject,
ClpIDerT61String,
ClpConverters;
resourcestring
SIllegalObject = 'Illegal Object in GetInstance: %s';
SStrNil = '"str"';
type
/// <summary>
/// Der T61String (also the teletex string) - 8-bit characters
/// </summary>
TDerT61String = class(TDerStringBase, IDerT61String)
strict private
class var
FEncoding: TEncoding;
var
FStr: String;
function GetStr: String; inline;
property Str: String read GetStr;
class constructor CreateDerT61String();
class destructor DestroyDerT61String();
strict protected
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
public
/// <summary>
/// basic constructor - with bytes.
/// </summary>
constructor Create(const Str: TCryptoLibByteArray); overload;
/// <summary>
/// basic constructor
/// </summary>
constructor Create(const Str: String); overload;
function GetString(): String; override;
function GetOctets(): TCryptoLibByteArray; inline;
procedure Encode(const derOut: TStream); override;
/// <summary>
/// return a T61 string from the passed in object.
/// </summary>
/// <param name="obj">
/// a Der T61 string or an object that can be converted into one.
/// </param>
/// <returns>
/// return a Der T61 string instance, or null.
/// </returns>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TObject): IDerT61String; overload;
static; inline;
/// <summary>
/// return a Der T61 string from a tagged object.
/// </summary>
/// <param name="obj">
/// the tagged object holding the object we want
/// </param>
/// <param name="isExplicit">
/// true if the object is meant to be explicitly tagged false otherwise.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the tagged object cannot be converted.
/// </exception>
class function GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerT61String; overload; static; inline;
end;
implementation
{ TDerT61String }
function TDerT61String.GetStr: String;
begin
result := FStr;
end;
function TDerT61String.GetOctets: TCryptoLibByteArray;
begin
result := TConverters.ConvertStringToBytes(Str, FEncoding);
end;
function TDerT61String.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IDerT61String;
begin
if (not Supports(asn1Object, IDerT61String, other)) then
begin
result := false;
Exit;
end;
result := Str = other.Str;
end;
constructor TDerT61String.Create(const Str: TCryptoLibByteArray);
begin
Inherited Create();
Create(TConverters.ConvertBytesToString(Str, FEncoding));
end;
constructor TDerT61String.Create(const Str: String);
begin
Inherited Create();
if (Str = '') then
begin
raise EArgumentNilCryptoLibException.CreateRes(@SStrNil);
end;
FStr := Str;
end;
class constructor TDerT61String.CreateDerT61String;
begin
FEncoding := TEncoding.GetEncoding('iso-8859-1');
end;
class destructor TDerT61String.DestroyDerT61String;
begin
FEncoding.Free;
end;
procedure TDerT61String.Encode(const derOut: TStream);
begin
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.T61String, GetOctets());
end;
class function TDerT61String.GetInstance(const obj: TObject): IDerT61String;
begin
if ((obj = Nil) or (obj is TDerT61String)) then
begin
result := obj as TDerT61String;
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject,
[obj.ClassName]);
end;
class function TDerT61String.GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerT61String;
var
o: IAsn1Object;
begin
o := obj.GetObject();
if ((isExplicit) or (Supports(o, IDerT61String))) then
begin
result := GetInstance(o as TAsn1Object);
Exit;
end;
result := TDerT61String.Create(TAsn1OctetString.GetInstance(o as TAsn1Object)
.GetOctets());
end;
function TDerT61String.GetString: String;
begin
result := Str;
end;
end.
|
unit UInstructionDialog;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.UIConsts,
System.Variants, System.Generics.Collections, UGridUtility,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
UDialog, FMX.TabControl, FMX.Layouts, FMX.Objects, FMX.StdActns,
Model_Instruction, UMyStringGrid;
type
TCookInstructionDialog = class(TDialogFrame)
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
TabItem3: TTabItem;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Button7: TButton;
Button8: TButton;
Button9: TButton;
Button10: TButton;
Button11: TButton;
Button12: TButton;
Button13: TButton;
Button14: TButton;
Button15: TButton;
Button16: TButton;
Button17: TButton;
Button18: TButton;
Button19: TButton;
Button20: TButton;
Button21: TButton;
ConvertBtn: TButton;
PriorPageBtn: TButton;
NextPageBtn: TButton;
InstructionBtn: TButton;
DeleteBtn: TButton;
Okbtn: TButton;
Cancelbtn: TButton;
StringgridLayout: TLayout;
Layout5: TLayout;
Layout4: TLayout;
Layout6: TLayout;
Rectangle2: TRectangle;
Rectangle3: TRectangle;
procedure PriorPageBtnClick(Sender: TObject);
procedure NextPageBtnClick(Sender: TObject);
procedure TabItem2Click(Sender: TObject);
procedure TabItem1Click(Sender: TObject);
procedure TabItem3Click(Sender: TObject);
procedure ConvertBtnClick(Sender: TObject);
procedure ButtonClick(Sender: TObject);
procedure DeleteBtnClick(Sender: TObject);
procedure CancelbtnClick(Sender: TObject);
procedure InstructionBtnClick(Sender: TObject);
procedure OkbtnClick(Sender: TObject);
const
ColID = 0;
ColCode = 1;
ColDesc = 2;
ColCondition = 3;
private
{ Private declarations }
MyItemCode: String;
TotalPageCount: Integer;
CurrentpageCount: Integer;
DescriptionFlag: Integer;
StartIndex, EndIndex: Integer;
ButtonList: TList<TButton>;
TempInstructionList: TList<TInstructionLink>;
IDColumn, CodeColumn, DescriptionColumn, ConditionColumn: TMyStringColumn;
Procedure FillARow(InstructionCode: String);
public
{ Public declarations }
MyInstructionList: TList<TInstructionLink>;
InstructionGrid: TMyStringGrid;
SelectedInstruction: Integer;
ReturnInstructionList: TList<TInstructionLink>;
Constructor Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult);
procedure InitialData(InstructionList: TList<TInstructionLink>;
ItemCode: String);
function GetMaxCount(ButtonCounter, Kind: Integer): Integer;
procedure ShowCurrentPage(TabNumber, PageNumber: Integer);
procedure CaculateIdxRange;
procedure CaculateMaxPage;
procedure ChangeInstruction(newCondition: Integer);
end;
var
CookInstructionDialog: TCookInstructionDialog;
implementation
uses OrderFm, UInstructionChoiceDialog;
{$R *.fmx}
{ TCookInstructionDialog }
constructor TCookInstructionDialog.Create(ParentForm: TForm;
ParentPanel: TPanel; CallBackProc: IProcessDialogResult);
var
i, MarginX, MarginY: Integer;
h: TRectangle;
begin
inherited;
MarginX := 2;
MarginY := 2;
ButtonList := TList<TButton>.Create;
ButtonList.Add(Button1);
ButtonList.Add(Button2);
ButtonList.Add(Button3);
ButtonList.Add(Button4);
ButtonList.Add(Button5);
ButtonList.Add(Button6);
ButtonList.Add(Button7);
ButtonList.Add(Button8);
ButtonList.Add(Button9);
ButtonList.Add(Button10);
ButtonList.Add(Button11);
ButtonList.Add(Button12);
ButtonList.Add(Button13);
ButtonList.Add(Button14);
ButtonList.Add(Button15);
ButtonList.Add(Button16);
ButtonList.Add(Button17);
ButtonList.Add(Button18);
ButtonList.Add(Button19);
ButtonList.Add(Button20);
ButtonList.Add(Button21);
for i := 0 to ButtonList.Count - 1 do
begin
ButtonList.items[i].width := (TabControl1.width - 4 * MarginX) / 3;
ButtonList.items[i].Height := (TabControl1.Height - MarginY - 5) / 8;
ButtonList.items[i].WordWrap := True;
ButtonList.items[i].Position.X := (i mod 3) *
(MarginX + ButtonList.items[i].width) + MarginX;
ButtonList.items[i].Position.Y := (i div 3) *
(MarginY + ButtonList.items[i].Height) + MarginY;
ButtonList.items[i].StyleLookup := 'CookButtonStyle';
// Tabitem1.StyleLookup := 'instructiondialogbuttonstyle';
// h := Tabitem1.FindStyleResource('background') as TRectangle;
// h.Fill.Color := $FFE6E7E8;
end;
ConvertBtn.StyleLookup := 'InstructionDialogButtonStyle';
h := ConvertBtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
ConvertBtn.width := (Layout6.width - 3 * MarginX) / 3;
ConvertBtn.Height := (Layout6.Height - 2 * MarginY - 10);
ConvertBtn.Position.X := 0;
ConvertBtn.Position.Y := MarginY + 5;
PriorPageBtn.StyleLookup := 'InstructionDialogButtonStyle';
h := PriorPageBtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
PriorPageBtn.width := (Layout6.width - 3 * MarginX) / 3;
PriorPageBtn.Height := (Layout6.Height - 2 * MarginY - 10);
PriorPageBtn.Position.X := MarginX + PriorPageBtn.width;
PriorPageBtn.Position.Y := MarginY + 5;
NextPageBtn.StyleLookup := 'InstructionDialogButtonStyle';
h := NextPageBtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
NextPageBtn.width := (Layout6.width - 3 * MarginX) / 3;
NextPageBtn.Height := (Layout6.Height - 2 * MarginY - 10);
NextPageBtn.Position.X := 2 * MarginX + 2 * NextPageBtn.width;
NextPageBtn.Position.Y := MarginY + 5;
InstructionBtn.StyleLookup := 'InstructionDialogButtonStyle';
h := InstructionBtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
InstructionBtn.width := (Layout5.width - 4 * MarginX) / 4;
InstructionBtn.Height := Layout5.Height - 2 * MarginY - 9;
InstructionBtn.Position.X := 1;
InstructionBtn.Position.Y := MarginY + 4;
DeleteBtn.StyleLookup := 'InstructionDialogButtonStyle';
h := DeleteBtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
DeleteBtn.width := (Layout5.width - 4 * MarginX) / 4 ;
DeleteBtn.Height := Layout5.Height - 2 * MarginY - 9;
DeleteBtn.Position.X := MarginX + DeleteBtn.width + 1;
DeleteBtn.Position.Y := MarginY + 4;
Okbtn.StyleLookup := 'InstructionDialogButtonStyle';
h := Okbtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
Okbtn.width := (Layout5.width - 4 * MarginX) / 4;
Okbtn.Height := Layout5.Height - 2 * MarginY - 9;
Okbtn.Position.X := 2 * MarginX + 2 * Okbtn.width + 1;
Okbtn.Position.Y := MarginY + 4;
Cancelbtn.StyleLookup := 'InstructionDialogButtonStyle';
h := Cancelbtn.FindStyleResource('background') as TRectangle;
if Assigned(h) then
h.Fill.Color := $FFBFE6EE;
Cancelbtn.width := (Layout5.width - 4 * MarginX) / 4;
Cancelbtn.Height := Layout5.Height - 2 * MarginY - 9;
Cancelbtn.Position.X := 3 * MarginX + 3 * Cancelbtn.width + 1;
Cancelbtn.Position.Y := MarginY + 4;
TempInstructionList := TList<TInstructionLink>.Create;
ReturnInstructionList := TList<TInstructionLink>.Create;
InstructionGrid := TMyStringGrid.Create(self);
InstructionGrid.Align := TAlignLayout.alContents;
InstructionGrid.Parent := StringgridLayout;
InstructionGrid.RowHeight := 35;
InstructionGrid.RowCount := 0;
InstructionGrid.ReadOnly := True;
IDColumn := TMyStringColumn.Create(self);
CodeColumn := TMyStringColumn.Create(self);
DescriptionColumn := TMyStringColumn.Create(self);
ConditionColumn := TMyStringColumn.Create(self);
InstructionGrid.AddObject(IDColumn);
InstructionGrid.AddObject(CodeColumn);
InstructionGrid.AddObject(DescriptionColumn);
InstructionGrid.AddObject(ConditionColumn);
IDColumn.Parent := InstructionGrid;
CodeColumn.Parent := InstructionGrid;
DescriptionColumn.Parent := InstructionGrid;
ConditionColumn.Parent := InstructionGrid;
CodeColumn.width := 80;
DescriptionColumn.width := InstructionGrid.width - CodeColumn.width - 20;
CodeColumn.Header := 'Code';
DescriptionColumn.Header := 'Description';
IDColumn.Visible := False;
ConditionColumn.Visible := False;
ReturnInstructionList := TList<TInstructionLink>.Create;
end;
procedure TCookInstructionDialog.FillARow(InstructionCode: String);
var
AInstructionLink: TInstructionLink;
i: Integer;
ConditionString: String;
begin
AInstructionLink := TInstructionLink.Create;
for i := 0 to TempInstructionList.Count - 1 do
begin
if TempInstructionList.items[i].InstructionCode = InstructionCode then
begin
AInstructionLink := TempInstructionList.items[i];
break;
end;
end;
i := InstructionGrid.RowCount;
InstructionGrid.RowCount := InstructionGrid.RowCount + 1;
InstructionGrid.Cells[ColCode, i] := AInstructionLink.InstructionCode;
case AInstructionLink.Condition of
0:
ConditionString := '';
1:
ConditionString := '[*]';
2:
ConditionString := '[A]';
3:
ConditionString := '[C]';
4:
ConditionString := '[M]';
5:
ConditionString := '[L]';
end;
InstructionGrid.Cells[ColDesc, i] := ConditionString + ' ' +
AInstructionLink.GetDescription(DescriptionFlag);
InstructionGrid.Cells[ColCondition, i] :=
IntToStr(AInstructionLink.Condition);
InstructionGrid.Selected := i;
end;
function TCookInstructionDialog.GetMaxCount(ButtonCounter,
Kind: Integer): Integer;
var
i: Integer;
InstructionCounter: Integer;
begin
InstructionCounter := 0;
for i := 0 to MyInstructionList.Count - 1 do
begin
if (MyInstructionList.items[i].Kind = Kind) then
Inc(InstructionCounter);
end;
if ButtonCounter > InstructionCounter then
result := InstructionCounter
else
result := ButtonCounter;
end;
procedure TCookInstructionDialog.InitialData(InstructionList
: TList<TInstructionLink>; ItemCode: String);
begin
MyInstructionList := InstructionList;
MyItemCode := ItemCode;
CurrentpageCount := 1;
DescriptionFlag := 1;
TabItem1.StyleLookup := 'InstructiontabitemStyle';
TabItem1.StyledSettings := [];
TabItem1.Font.Size := 13;
TabItem1.FontColor := TAlphaColors.White;
TabItem1.Parent := TabControl1;
TabItem2.StyleLookup := 'InstructiontabitemStyle';
TabItem2.StyledSettings := [];
TabItem2.Font.Size := 13;
TabItem2.FontColor := $FF929292;
TabItem2.Parent := TabControl1;
TabItem3.StyleLookup := 'InstructiontabitemStyle';
TabItem3.StyledSettings := [];
TabItem3.Font.Size := 13;
TabItem3.Parent := TabControl1;
TabItem3.FontColor := $FF929292;
ShowCurrentPage(0, CurrentpageCount);
end;
procedure TCookInstructionDialog.InstructionBtnClick(Sender: TObject);
begin
OrderFm.OrderForm.InstructionChoiceBtnClick(Sender);
end;
procedure TCookInstructionDialog.ShowCurrentPage(TabNumber,
PageNumber: Integer);
var
i: Integer;
begin
TempInstructionList.Clear;
TabControl1.ActiveTab := TabControl1.Tabs[TabNumber];
for i := 0 to MyInstructionList.Count - 1 do
if (MyInstructionList.items[i].Kind = TabNumber) and
(MyInstructionList.items[i].MenuItemCode = MyItemCode) then
TempInstructionList.Add(MyInstructionList.items[i]);
CaculateMaxPage;
CaculateIdxRange;
for i := 0 to ButtonList.Count - 1 do
begin
case TabNumber of
0:
ButtonList.items[i].Parent := TabItem1;
1:
ButtonList.items[i].Parent := TabItem2;
2:
ButtonList.items[i].Parent := TabItem3;
end;
end;
if TempInstructionList.Count <> 0 then
begin
for i := 0 to (EndIndex - StartIndex) do
begin
ButtonList.items[i].Text := TempInstructionList.items[StartIndex + i]
.GetDescription(DescriptionFlag);
ButtonList.items[i].TagString := TempInstructionList.items[StartIndex + i]
.InstructionCode;
end;
for i := (EndIndex - StartIndex) + 1 to ButtonList.Count - 1 do
begin
ButtonList.items[i].Text := '';
ButtonList.items[i].TagString := '';
end;
end
else
begin
for i := 0 to ButtonList.Count - 1 do
begin
ButtonList.items[i].Text := '';
ButtonList.items[i].TagString := '';
end;
end;
end;
procedure TCookInstructionDialog.TabItem1Click(Sender: TObject);
var
i: Integer;
begin
CurrentpageCount := 1;
CaculateMaxPage;
TabItem1.StyleLookup := 'ClickedtabitemStyle';
TabItem1.StyledSettings := [];
TabItem1.Font.Size := 13;
TabItem1.FontColor := TAlphaColors.White;
TabItem2.StyleLookup := 'InstructionTabItemStyle';
TabItem3.StyleLookup := 'InstructionTabItemStyle';
for i := 0 to ButtonList.Count - 1 do
begin
ButtonList.items[i].StyleLookup := 'cookbuttonstyle';
end;
ShowCurrentPage(0, CurrentpageCount);
end;
procedure TCookInstructionDialog.TabItem2Click(Sender: TObject);
var
i: Integer;
begin
CurrentpageCount := 1;
CaculateMaxPage;
// CaculateIdxRange;
TabItem2.StyleLookup := 'ClickedtabitemStyle';
TabItem2.StyledSettings := [];
TabItem2.Font.Size := 13;
TabItem2.FontColor := TAlphaColors.White;
TabItem1.StyleLookup := 'InstructionTabItemStyle';
TabItem3.StyleLookup := 'InstructionTabItemStyle';
for I := 0 to ButtonList.Count - 1 do
begin
ButtonList.Items[i].StyleLookup := 'materialbuttonstyle';
end;
ShowCurrentPage(1, CurrentpageCount);
end;
procedure TCookInstructionDialog.TabItem3Click(Sender: TObject);
var
i: Integer;
begin
TabItem3.StyleLookup := 'ClickedtabitemStyle';
TabItem3.StyledSettings := [];
TabItem3.Font.Size := 13;
TabItem3.FontColor := TAlphaColors.White;
TabItem2.StyleLookup := 'InstructionTabItemStyle';
TabItem1.StyleLookup := 'InstructionTabItemStyle';
for i := 0 to ButtonList.Count - 1 do
begin
ButtonList.items[i].StyleLookup := 'notesbuttonstyle';
end;
CurrentpageCount := 1;
CaculateMaxPage;
// CaculateIdxRange;
ShowCurrentPage(2, CurrentpageCount);
end;
procedure TCookInstructionDialog.CaculateMaxPage;
begin
if (TempInstructionList.Count mod ButtonList.Count) = 0 then
TotalPageCount := TempInstructionList.Count div ButtonList.Count
else
TotalPageCount := TempInstructionList.Count div ButtonList.Count + 1;
end;
procedure TCookInstructionDialog.CancelbtnClick(Sender: TObject);
begin
OrderFm.OrderForm.CloseInstructionDialog(Sender);
end;
procedure TCookInstructionDialog.ChangeInstruction(newCondition: Integer);
var
AInstructionLink: TInstructionLink;
i: Integer;
ConditionString: String;
begin
AInstructionLink := TInstructionLink.Create;
for i := 0 to TempInstructionList.Count - 1 do
begin
if TempInstructionList.items[i].InstructionCode = InstructionGrid.Cells
[ColCode, InstructionGrid.Selected] then
begin
AInstructionLink := TempInstructionList.items[i];
break;
end;
end;
case newCondition of
0:
ConditionString := '';
1:
ConditionString := '[*] ';
2:
ConditionString := '[A] ';
3:
ConditionString := '[C] ';
4:
ConditionString := '[M] ';
5:
ConditionString := '[L] ';
end;
InstructionGrid.Cells[ColDesc, InstructionGrid.Selected] := ConditionString +
AInstructionLink.GetDescription(DescriptionFlag);
InstructionGrid.Cells[ColCondition, InstructionGrid.Selected] :=
IntToStr(newCondition);
end;
procedure TCookInstructionDialog.NextPageBtnClick(Sender: TObject);
begin
if CurrentpageCount < TotalPageCount then
begin
Inc(CurrentpageCount);
ShowCurrentPage(TabControl1.ActiveTab.Index, CurrentpageCount);
end;
end;
procedure TCookInstructionDialog.OkbtnClick(Sender: TObject);
var
i, j: Integer;
begin
ReturnInstructionList.Clear;
for i := 0 to InstructionGrid.RowCount - 1 do
begin
for j := 0 to TempInstructionList.Count - 1 do
begin
if InstructionGrid.Cells[ColCode, i] = TempInstructionList.items[j].InstructionCode
then
begin
ReturnInstructionList.Add(TempInstructionList.items[j]);
ReturnInstructionList.items[ReturnInstructionList.Count - 1].Condition
:= StrToInt(InstructionGrid.Cells[ColCondition, i]);
end;
end;
end;
OrderFm.OrderForm.InstructionChoiceOKBtnClick(Sender);
OrderFm.OrderForm.CalcOrderSummaries;
end;
procedure TCookInstructionDialog.PriorPageBtnClick(Sender: TObject);
begin
if CurrentpageCount > 1 then
begin
Dec(CurrentpageCount);
ShowCurrentPage(TabControl1.ActiveTab.Index, CurrentpageCount);
end;
end;
procedure TCookInstructionDialog.ConvertBtnClick(Sender: TObject);
var
i,j : Integer;
TempDescription : String;
ConditionString : String;
begin
if DescriptionFlag = 1 then
DescriptionFlag := 2
else
DescriptionFlag := 1;
ShowCurrentPage(TabControl1.ActiveTab.Index, CurrentpageCount);
for i := 0 to InstructionGrid.RowCount - 1 do
begin
for j := 0 to MyInstructionList.Count - 1 do
begin
if MyInstructionList.Items[j].InstructionCode = InstructionGrid.Cells[1,i] then
TempDescription := MyInstructionList.Items[j].GetDescription(DescriptionFlag);
end;
case StrToInt(InstructionGrid.Cells[3,i]) of
0:
ConditionString := '';
1:
ConditionString := '[*] ';
2:
ConditionString := '[A] ';
3:
ConditionString := '[C] ';
4:
ConditionString := '[M] ';
5:
ConditionString := '[L] ';
end;
InstructionGrid.Cells[2,i] := ConditionString + TempDescription;
end;
end;
procedure TCookInstructionDialog.DeleteBtnClick(Sender: TObject);
begin
TGridUtility.RemoveRows(InstructionGrid, InstructionGrid.Selected, 1);
end;
procedure TCookInstructionDialog.ButtonClick(Sender: TObject);
begin
if (Sender as TButton).TagString <> '' then
FillARow((Sender as TButton).TagString);
end;
procedure TCookInstructionDialog.CaculateIdxRange;
var
IsLastPage: Boolean;
begin
IsLastPage := (CurrentpageCount = TotalPageCount);
if IsLastPage then
begin
StartIndex := (TotalPageCount - 1) * ButtonList.Count;
EndIndex := TempInstructionList.Count - 1
end
else
begin
StartIndex := (CurrentpageCount - 1) * ButtonList.Count;
EndIndex := CurrentpageCount * ButtonList.Count - 1;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.