text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.LoggingService;
{$HPPEMIT LINKUNIT}
interface
uses
System.SysUtils, System.Classes, EMS.Services,
System.Generics.Collections, System.JSON;
type
TEMSLoggingService = class(TInterfacedObject, IEMSLoggingService)
public type
TLogProc = reference to procedure(const ACategory: string; const AJSON: TJSONObject);
private
class var FLogProc: TLogProc;
class var FLoggingEnabledProc: TFunc<Boolean>;
public
function GetLoggingEnabled: Boolean;
procedure Log(const ACategory: string; const AJSON: TJSONObject);
class property OnLog: TLogProc read FLogProc write FLogProc;
class property OnLoggingEnabled: TFunc<Boolean> read FLoggingEnabledProc write FLoggingEnabledProc;
end;
implementation
uses EMSHosting.ExtensionsServices, EMSHosting.Helpers;
{ TEMSLoggingService }
function TEMSLoggingService.GetLoggingEnabled: Boolean;
begin
Result := Assigned(FLogProc);
if Result then
if Assigned(FLoggingEnabledProc) then
Result := FLoggingEnabledProc
end;
procedure TEMSLoggingService.Log(const ACategory: string;
const AJSON: TJSONObject);
var
LJSON: TJSONObject;
begin
if Assigned(FLogProc) then
begin
LJSON := AJSON.Clone as TJSONObject;
try
LJSON.AddPair(TLogObjectNames.Thread, TJSONNumber.Create(TThread.CurrentThread.ThreadID));
FLogProc(ACategory, AJSON);
finally
LJSON.Free;
end;
end;
end;
var
LIndex: Integer;
initialization
LIndex := AddService(TEMSLoggingService.Create as IEMSLoggingService);
finalization
RemoveService(LIndex);
end.
|
unit TTSNOTICEPTTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSNOTICEPTRecord = record
PLenderNum: String[8];
PType: Integer;
PDescription: String[100];
PNoticeScanDate: String[10];
PLetterDate: String[10];
PNoticeType: String[1];
PReprint: Boolean;
PLimit1: Boolean;
PLimitNo1: Integer;
PLimit2: Boolean;
PLimitNo2: Integer;
PLimit3: Boolean;
PLimitNo3: Integer;
PLimit4: Boolean;
PLimitNo4: Integer;
PLimit5: Boolean;
PLimitNo5: Integer;
PSortOrder: String[10];
PLoanCif: Integer;
PCifs: Integer;
PBalanceFrom: Currency;
PBalanceTo: Currency;
PSeperateNotice: Integer;
PPaidouts: Boolean;
PMatureFrom: String[10];
PMatureTo: String[10];
POpenFrom: String[10];
POpenTo: String[10];
PReportTitle: String[40];
PPaidDatesFrom: String[10];
PPaidDatesTo: String[10];
PSelectTIDate: Boolean;
PSelectTICont: Boolean;
PSelectTIWaived: Boolean;
PSelectTIHistory: Boolean;
PSelectTISatisfied: Boolean;
PSelectTINA: Boolean;
PExpireDateFrom: String[10];
PExpireDateTo: String[10];
PIncludeTI: Boolean;
PNoticeItems: Boolean;
PNoticeItemFrom: String[10];
PNoticeItemTo: String[10];
PLoanNotes: Boolean;
PTINotes: Boolean;
PCoMaker: Boolean;
PGuarantor: Boolean;
PGroupBy: Integer;
PItemCollDesc: Boolean;
PItemOfficer: Boolean;
PItemBalance: Boolean;
PItemBranch: Boolean;
PItemDivision: Boolean;
PItemOpenDate: Boolean;
PItemMatDate: Boolean;
PItemAddress: Boolean;
PItemCategory: Boolean;
PItemPhone: Boolean;
PItemStatus: Boolean;
PItemDescription: Boolean;
PLeadTimeOfficer: Boolean;
PLeadTimeNotice: Boolean;
PLeadTimeYouPick: Boolean;
PLeadTime: Integer;
PIncLoans: Boolean;
PIncActiveCifs: Boolean;
PIncInactiveCifs: Boolean;
PIncNotPaidOut: Boolean;
PIncPaidOut: Boolean;
PIncLoanWithNotes: Boolean;
PIncLoanWONotes: Boolean;
PIncWithTracked: Boolean;
PIncWOTracked: Boolean;
PIncWithNoticeItems: Boolean;
PIncWONoticeItems: Boolean;
PIncLoanNotes: Boolean;
PIncCifs: Boolean;
PELRecapOnly: Boolean;
PExpLoanCif: Boolean;
PExpLoanCifNotes: Boolean;
PExpTracked: Boolean;
PExpTrackedNotes: Boolean;
PExpTrackedExtend: Boolean;
PExpFormat: Integer;
PExpOpt1: Boolean;
PExpOpt2: Boolean;
PExpOpt3: Boolean;
PItemEntryFrom: String[10];
PItemEntryTo: String[10];
PItemEntryBy: String[100];
PShowTIUser: Boolean;
PShowTIEntryDate: Boolean;
PExcludeCats: Boolean;
End;
TTTSNOTICEPTBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSNOTICEPTRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSNOTICEPT = (TTSNOTICEPTPrimaryKey);
TTTSNOTICEPTTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFType: TIntegerField;
FDFDescription: TStringField;
FDFNoticeScanDate: TStringField;
FDFLetterDate: TStringField;
FDFNoticeType: TStringField;
FDFReprint: TBooleanField;
FDFLimit1: TBooleanField;
FDFLimitNo1: TIntegerField;
FDFLimit2: TBooleanField;
FDFLimitNo2: TIntegerField;
FDFLimit3: TBooleanField;
FDFLimitNo3: TIntegerField;
FDFLimit4: TBooleanField;
FDFLimitNo4: TIntegerField;
FDFLimit5: TBooleanField;
FDFLimitNo5: TIntegerField;
FDFSortOrder: TStringField;
FDFLoanCif: TIntegerField;
FDFCifs: TIntegerField;
FDFBalanceFrom: TCurrencyField;
FDFBalanceTo: TCurrencyField;
FDFSeperateNotice: TIntegerField;
FDFPaidouts: TBooleanField;
FDFMatureFrom: TStringField;
FDFMatureTo: TStringField;
FDFOpenFrom: TStringField;
FDFOpenTo: TStringField;
FDFCats: TBlobField;
FDFCollCodes: TBlobField;
FDFOfficers: TBlobField;
FDFBranchs: TBlobField;
FDFDivisions: TBlobField;
FDFReportTitle: TStringField;
FDFPaidDatesFrom: TStringField;
FDFPaidDatesTo: TStringField;
FDFSelectTIDate: TBooleanField;
FDFSelectTICont: TBooleanField;
FDFSelectTIWaived: TBooleanField;
FDFSelectTIHistory: TBooleanField;
FDFSelectTISatisfied: TBooleanField;
FDFSelectTINA: TBooleanField;
FDFExpireDateFrom: TStringField;
FDFExpireDateTo: TStringField;
FDFIncludeTI: TBooleanField;
FDFNoticeItems: TBooleanField;
FDFNoticeItemFrom: TStringField;
FDFNoticeItemTo: TStringField;
FDFLoanNotes: TBooleanField;
FDFTINotes: TBooleanField;
FDFCoMaker: TBooleanField;
FDFGuarantor: TBooleanField;
FDFGroupBy: TIntegerField;
FDFItemCollDesc: TBooleanField;
FDFItemOfficer: TBooleanField;
FDFItemBalance: TBooleanField;
FDFItemBranch: TBooleanField;
FDFItemDivision: TBooleanField;
FDFItemOpenDate: TBooleanField;
FDFItemMatDate: TBooleanField;
FDFItemAddress: TBooleanField;
FDFItemCategory: TBooleanField;
FDFItemPhone: TBooleanField;
FDFItemStatus: TBooleanField;
FDFItemDescription: TBooleanField;
FDFLeadTimeOfficer: TBooleanField;
FDFLeadTimeNotice: TBooleanField;
FDFLeadTimeYouPick: TBooleanField;
FDFLeadTime: TIntegerField;
FDFIncLoans: TBooleanField;
FDFIncActiveCifs: TBooleanField;
FDFIncInactiveCifs: TBooleanField;
FDFIncNotPaidOut: TBooleanField;
FDFIncPaidOut: TBooleanField;
FDFIncLoanWithNotes: TBooleanField;
FDFIncLoanWONotes: TBooleanField;
FDFIncWithTracked: TBooleanField;
FDFIncWOTracked: TBooleanField;
FDFIncWithNoticeItems: TBooleanField;
FDFIncWONoticeItems: TBooleanField;
FDFIncLoanNotes: TBooleanField;
FDFIncCifs: TBooleanField;
FDFELRecapOnly: TBooleanField;
FDFExpLoanCif: TBooleanField;
FDFExpLoanCifNotes: TBooleanField;
FDFExpTracked: TBooleanField;
FDFExpTrackedNotes: TBooleanField;
FDFExpTrackedExtend: TBooleanField;
FDFExpFormat: TIntegerField;
FDFExpOpt1: TBooleanField;
FDFExpOpt2: TBooleanField;
FDFExpOpt3: TBooleanField;
FDFItemEntryFrom: TStringField;
FDFItemEntryTo: TStringField;
FDFItemEntryBy: TStringField;
FDFShowTIUser: TBooleanField;
FDFShowTIEntryDate: TBooleanField;
FDFExcludeCats: TBooleanField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPType(const Value: Integer);
function GetPType:Integer;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPNoticeScanDate(const Value: String);
function GetPNoticeScanDate:String;
procedure SetPLetterDate(const Value: String);
function GetPLetterDate:String;
procedure SetPNoticeType(const Value: String);
function GetPNoticeType:String;
procedure SetPReprint(const Value: Boolean);
function GetPReprint:Boolean;
procedure SetPLimit1(const Value: Boolean);
function GetPLimit1:Boolean;
procedure SetPLimitNo1(const Value: Integer);
function GetPLimitNo1:Integer;
procedure SetPLimit2(const Value: Boolean);
function GetPLimit2:Boolean;
procedure SetPLimitNo2(const Value: Integer);
function GetPLimitNo2:Integer;
procedure SetPLimit3(const Value: Boolean);
function GetPLimit3:Boolean;
procedure SetPLimitNo3(const Value: Integer);
function GetPLimitNo3:Integer;
procedure SetPLimit4(const Value: Boolean);
function GetPLimit4:Boolean;
procedure SetPLimitNo4(const Value: Integer);
function GetPLimitNo4:Integer;
procedure SetPLimit5(const Value: Boolean);
function GetPLimit5:Boolean;
procedure SetPLimitNo5(const Value: Integer);
function GetPLimitNo5:Integer;
procedure SetPSortOrder(const Value: String);
function GetPSortOrder:String;
procedure SetPLoanCif(const Value: Integer);
function GetPLoanCif:Integer;
procedure SetPCifs(const Value: Integer);
function GetPCifs:Integer;
procedure SetPBalanceFrom(const Value: Currency);
function GetPBalanceFrom:Currency;
procedure SetPBalanceTo(const Value: Currency);
function GetPBalanceTo:Currency;
procedure SetPSeperateNotice(const Value: Integer);
function GetPSeperateNotice:Integer;
procedure SetPPaidouts(const Value: Boolean);
function GetPPaidouts:Boolean;
procedure SetPMatureFrom(const Value: String);
function GetPMatureFrom:String;
procedure SetPMatureTo(const Value: String);
function GetPMatureTo:String;
procedure SetPOpenFrom(const Value: String);
function GetPOpenFrom:String;
procedure SetPOpenTo(const Value: String);
function GetPOpenTo:String;
procedure SetPReportTitle(const Value: String);
function GetPReportTitle:String;
procedure SetPPaidDatesFrom(const Value: String);
function GetPPaidDatesFrom:String;
procedure SetPPaidDatesTo(const Value: String);
function GetPPaidDatesTo:String;
procedure SetPSelectTIDate(const Value: Boolean);
function GetPSelectTIDate:Boolean;
procedure SetPSelectTICont(const Value: Boolean);
function GetPSelectTICont:Boolean;
procedure SetPSelectTIWaived(const Value: Boolean);
function GetPSelectTIWaived:Boolean;
procedure SetPSelectTIHistory(const Value: Boolean);
function GetPSelectTIHistory:Boolean;
procedure SetPSelectTISatisfied(const Value: Boolean);
function GetPSelectTISatisfied:Boolean;
procedure SetPSelectTINA(const Value: Boolean);
function GetPSelectTINA:Boolean;
procedure SetPExpireDateFrom(const Value: String);
function GetPExpireDateFrom:String;
procedure SetPExpireDateTo(const Value: String);
function GetPExpireDateTo:String;
procedure SetPIncludeTI(const Value: Boolean);
function GetPIncludeTI:Boolean;
procedure SetPNoticeItems(const Value: Boolean);
function GetPNoticeItems:Boolean;
procedure SetPNoticeItemFrom(const Value: String);
function GetPNoticeItemFrom:String;
procedure SetPNoticeItemTo(const Value: String);
function GetPNoticeItemTo:String;
procedure SetPLoanNotes(const Value: Boolean);
function GetPLoanNotes:Boolean;
procedure SetPTINotes(const Value: Boolean);
function GetPTINotes:Boolean;
procedure SetPCoMaker(const Value: Boolean);
function GetPCoMaker:Boolean;
procedure SetPGuarantor(const Value: Boolean);
function GetPGuarantor:Boolean;
procedure SetPGroupBy(const Value: Integer);
function GetPGroupBy:Integer;
procedure SetPItemCollDesc(const Value: Boolean);
function GetPItemCollDesc:Boolean;
procedure SetPItemOfficer(const Value: Boolean);
function GetPItemOfficer:Boolean;
procedure SetPItemBalance(const Value: Boolean);
function GetPItemBalance:Boolean;
procedure SetPItemBranch(const Value: Boolean);
function GetPItemBranch:Boolean;
procedure SetPItemDivision(const Value: Boolean);
function GetPItemDivision:Boolean;
procedure SetPItemOpenDate(const Value: Boolean);
function GetPItemOpenDate:Boolean;
procedure SetPItemMatDate(const Value: Boolean);
function GetPItemMatDate:Boolean;
procedure SetPItemAddress(const Value: Boolean);
function GetPItemAddress:Boolean;
procedure SetPItemCategory(const Value: Boolean);
function GetPItemCategory:Boolean;
procedure SetPItemPhone(const Value: Boolean);
function GetPItemPhone:Boolean;
procedure SetPItemStatus(const Value: Boolean);
function GetPItemStatus:Boolean;
procedure SetPItemDescription(const Value: Boolean);
function GetPItemDescription:Boolean;
procedure SetPLeadTimeOfficer(const Value: Boolean);
function GetPLeadTimeOfficer:Boolean;
procedure SetPLeadTimeNotice(const Value: Boolean);
function GetPLeadTimeNotice:Boolean;
procedure SetPLeadTimeYouPick(const Value: Boolean);
function GetPLeadTimeYouPick:Boolean;
procedure SetPLeadTime(const Value: Integer);
function GetPLeadTime:Integer;
procedure SetPIncLoans(const Value: Boolean);
function GetPIncLoans:Boolean;
procedure SetPIncActiveCifs(const Value: Boolean);
function GetPIncActiveCifs:Boolean;
procedure SetPIncInactiveCifs(const Value: Boolean);
function GetPIncInactiveCifs:Boolean;
procedure SetPIncNotPaidOut(const Value: Boolean);
function GetPIncNotPaidOut:Boolean;
procedure SetPIncPaidOut(const Value: Boolean);
function GetPIncPaidOut:Boolean;
procedure SetPIncLoanWithNotes(const Value: Boolean);
function GetPIncLoanWithNotes:Boolean;
procedure SetPIncLoanWONotes(const Value: Boolean);
function GetPIncLoanWONotes:Boolean;
procedure SetPIncWithTracked(const Value: Boolean);
function GetPIncWithTracked:Boolean;
procedure SetPIncWOTracked(const Value: Boolean);
function GetPIncWOTracked:Boolean;
procedure SetPIncWithNoticeItems(const Value: Boolean);
function GetPIncWithNoticeItems:Boolean;
procedure SetPIncWONoticeItems(const Value: Boolean);
function GetPIncWONoticeItems:Boolean;
procedure SetPIncLoanNotes(const Value: Boolean);
function GetPIncLoanNotes:Boolean;
procedure SetPIncCifs(const Value: Boolean);
function GetPIncCifs:Boolean;
procedure SetPELRecapOnly(const Value: Boolean);
function GetPELRecapOnly:Boolean;
procedure SetPExpLoanCif(const Value: Boolean);
function GetPExpLoanCif:Boolean;
procedure SetPExpLoanCifNotes(const Value: Boolean);
function GetPExpLoanCifNotes:Boolean;
procedure SetPExpTracked(const Value: Boolean);
function GetPExpTracked:Boolean;
procedure SetPExpTrackedNotes(const Value: Boolean);
function GetPExpTrackedNotes:Boolean;
procedure SetPExpTrackedExtend(const Value: Boolean);
function GetPExpTrackedExtend:Boolean;
procedure SetPExpFormat(const Value: Integer);
function GetPExpFormat:Integer;
procedure SetPExpOpt1(const Value: Boolean);
function GetPExpOpt1:Boolean;
procedure SetPExpOpt2(const Value: Boolean);
function GetPExpOpt2:Boolean;
procedure SetPExpOpt3(const Value: Boolean);
function GetPExpOpt3:Boolean;
procedure SetPItemEntryFrom(const Value: String);
function GetPItemEntryFrom:String;
procedure SetPItemEntryTo(const Value: String);
function GetPItemEntryTo:String;
procedure SetPItemEntryBy(const Value: String);
function GetPItemEntryBy:String;
procedure SetPShowTIUser(const Value: Boolean);
function GetPShowTIUser:Boolean;
procedure SetPShowTIEntryDate(const Value: Boolean);
function GetPShowTIEntryDate:Boolean;
procedure SetPExcludeCats(const Value: Boolean);
function GetPExcludeCats:Boolean;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSNOTICEPT);
function GetEnumIndex: TEITTSNOTICEPT;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSNOTICEPTRecord;
procedure StoreDataBuffer(ABuffer:TTTSNOTICEPTRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFType: TIntegerField read FDFType;
property DFDescription: TStringField read FDFDescription;
property DFNoticeScanDate: TStringField read FDFNoticeScanDate;
property DFLetterDate: TStringField read FDFLetterDate;
property DFNoticeType: TStringField read FDFNoticeType;
property DFReprint: TBooleanField read FDFReprint;
property DFLimit1: TBooleanField read FDFLimit1;
property DFLimitNo1: TIntegerField read FDFLimitNo1;
property DFLimit2: TBooleanField read FDFLimit2;
property DFLimitNo2: TIntegerField read FDFLimitNo2;
property DFLimit3: TBooleanField read FDFLimit3;
property DFLimitNo3: TIntegerField read FDFLimitNo3;
property DFLimit4: TBooleanField read FDFLimit4;
property DFLimitNo4: TIntegerField read FDFLimitNo4;
property DFLimit5: TBooleanField read FDFLimit5;
property DFLimitNo5: TIntegerField read FDFLimitNo5;
property DFSortOrder: TStringField read FDFSortOrder;
property DFLoanCif: TIntegerField read FDFLoanCif;
property DFCifs: TIntegerField read FDFCifs;
property DFBalanceFrom: TCurrencyField read FDFBalanceFrom;
property DFBalanceTo: TCurrencyField read FDFBalanceTo;
property DFSeperateNotice: TIntegerField read FDFSeperateNotice;
property DFPaidouts: TBooleanField read FDFPaidouts;
property DFMatureFrom: TStringField read FDFMatureFrom;
property DFMatureTo: TStringField read FDFMatureTo;
property DFOpenFrom: TStringField read FDFOpenFrom;
property DFOpenTo: TStringField read FDFOpenTo;
property DFCats: TBlobField read FDFCats;
property DFCollCodes: TBlobField read FDFCollCodes;
property DFOfficers: TBlobField read FDFOfficers;
property DFBranchs: TBlobField read FDFBranchs;
property DFDivisions: TBlobField read FDFDivisions;
property DFReportTitle: TStringField read FDFReportTitle;
property DFPaidDatesFrom: TStringField read FDFPaidDatesFrom;
property DFPaidDatesTo: TStringField read FDFPaidDatesTo;
property DFSelectTIDate: TBooleanField read FDFSelectTIDate;
property DFSelectTICont: TBooleanField read FDFSelectTICont;
property DFSelectTIWaived: TBooleanField read FDFSelectTIWaived;
property DFSelectTIHistory: TBooleanField read FDFSelectTIHistory;
property DFSelectTISatisfied: TBooleanField read FDFSelectTISatisfied;
property DFSelectTINA: TBooleanField read FDFSelectTINA;
property DFExpireDateFrom: TStringField read FDFExpireDateFrom;
property DFExpireDateTo: TStringField read FDFExpireDateTo;
property DFIncludeTI: TBooleanField read FDFIncludeTI;
property DFNoticeItems: TBooleanField read FDFNoticeItems;
property DFNoticeItemFrom: TStringField read FDFNoticeItemFrom;
property DFNoticeItemTo: TStringField read FDFNoticeItemTo;
property DFLoanNotes: TBooleanField read FDFLoanNotes;
property DFTINotes: TBooleanField read FDFTINotes;
property DFCoMaker: TBooleanField read FDFCoMaker;
property DFGuarantor: TBooleanField read FDFGuarantor;
property DFGroupBy: TIntegerField read FDFGroupBy;
property DFItemCollDesc: TBooleanField read FDFItemCollDesc;
property DFItemOfficer: TBooleanField read FDFItemOfficer;
property DFItemBalance: TBooleanField read FDFItemBalance;
property DFItemBranch: TBooleanField read FDFItemBranch;
property DFItemDivision: TBooleanField read FDFItemDivision;
property DFItemOpenDate: TBooleanField read FDFItemOpenDate;
property DFItemMatDate: TBooleanField read FDFItemMatDate;
property DFItemAddress: TBooleanField read FDFItemAddress;
property DFItemCategory: TBooleanField read FDFItemCategory;
property DFItemPhone: TBooleanField read FDFItemPhone;
property DFItemStatus: TBooleanField read FDFItemStatus;
property DFItemDescription: TBooleanField read FDFItemDescription;
property DFLeadTimeOfficer: TBooleanField read FDFLeadTimeOfficer;
property DFLeadTimeNotice: TBooleanField read FDFLeadTimeNotice;
property DFLeadTimeYouPick: TBooleanField read FDFLeadTimeYouPick;
property DFLeadTime: TIntegerField read FDFLeadTime;
property DFIncLoans: TBooleanField read FDFIncLoans;
property DFIncActiveCifs: TBooleanField read FDFIncActiveCifs;
property DFIncInactiveCifs: TBooleanField read FDFIncInactiveCifs;
property DFIncNotPaidOut: TBooleanField read FDFIncNotPaidOut;
property DFIncPaidOut: TBooleanField read FDFIncPaidOut;
property DFIncLoanWithNotes: TBooleanField read FDFIncLoanWithNotes;
property DFIncLoanWONotes: TBooleanField read FDFIncLoanWONotes;
property DFIncWithTracked: TBooleanField read FDFIncWithTracked;
property DFIncWOTracked: TBooleanField read FDFIncWOTracked;
property DFIncWithNoticeItems: TBooleanField read FDFIncWithNoticeItems;
property DFIncWONoticeItems: TBooleanField read FDFIncWONoticeItems;
property DFIncLoanNotes: TBooleanField read FDFIncLoanNotes;
property DFIncCifs: TBooleanField read FDFIncCifs;
property DFELRecapOnly: TBooleanField read FDFELRecapOnly;
property DFExpLoanCif: TBooleanField read FDFExpLoanCif;
property DFExpLoanCifNotes: TBooleanField read FDFExpLoanCifNotes;
property DFExpTracked: TBooleanField read FDFExpTracked;
property DFExpTrackedNotes: TBooleanField read FDFExpTrackedNotes;
property DFExpTrackedExtend: TBooleanField read FDFExpTrackedExtend;
property DFExpFormat: TIntegerField read FDFExpFormat;
property DFExpOpt1: TBooleanField read FDFExpOpt1;
property DFExpOpt2: TBooleanField read FDFExpOpt2;
property DFExpOpt3: TBooleanField read FDFExpOpt3;
property DFItemEntryFrom: TStringField read FDFItemEntryFrom;
property DFItemEntryTo: TStringField read FDFItemEntryTo;
property DFItemEntryBy: TStringField read FDFItemEntryBy;
property DFShowTIUser: TBooleanField read FDFShowTIUser;
property DFShowTIEntryDate: TBooleanField read FDFShowTIEntryDate;
property DFExcludeCats: TBooleanField read FDFExcludeCats;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PType: Integer read GetPType write SetPType;
property PDescription: String read GetPDescription write SetPDescription;
property PNoticeScanDate: String read GetPNoticeScanDate write SetPNoticeScanDate;
property PLetterDate: String read GetPLetterDate write SetPLetterDate;
property PNoticeType: String read GetPNoticeType write SetPNoticeType;
property PReprint: Boolean read GetPReprint write SetPReprint;
property PLimit1: Boolean read GetPLimit1 write SetPLimit1;
property PLimitNo1: Integer read GetPLimitNo1 write SetPLimitNo1;
property PLimit2: Boolean read GetPLimit2 write SetPLimit2;
property PLimitNo2: Integer read GetPLimitNo2 write SetPLimitNo2;
property PLimit3: Boolean read GetPLimit3 write SetPLimit3;
property PLimitNo3: Integer read GetPLimitNo3 write SetPLimitNo3;
property PLimit4: Boolean read GetPLimit4 write SetPLimit4;
property PLimitNo4: Integer read GetPLimitNo4 write SetPLimitNo4;
property PLimit5: Boolean read GetPLimit5 write SetPLimit5;
property PLimitNo5: Integer read GetPLimitNo5 write SetPLimitNo5;
property PSortOrder: String read GetPSortOrder write SetPSortOrder;
property PLoanCif: Integer read GetPLoanCif write SetPLoanCif;
property PCifs: Integer read GetPCifs write SetPCifs;
property PBalanceFrom: Currency read GetPBalanceFrom write SetPBalanceFrom;
property PBalanceTo: Currency read GetPBalanceTo write SetPBalanceTo;
property PSeperateNotice: Integer read GetPSeperateNotice write SetPSeperateNotice;
property PPaidouts: Boolean read GetPPaidouts write SetPPaidouts;
property PMatureFrom: String read GetPMatureFrom write SetPMatureFrom;
property PMatureTo: String read GetPMatureTo write SetPMatureTo;
property POpenFrom: String read GetPOpenFrom write SetPOpenFrom;
property POpenTo: String read GetPOpenTo write SetPOpenTo;
property PReportTitle: String read GetPReportTitle write SetPReportTitle;
property PPaidDatesFrom: String read GetPPaidDatesFrom write SetPPaidDatesFrom;
property PPaidDatesTo: String read GetPPaidDatesTo write SetPPaidDatesTo;
property PSelectTIDate: Boolean read GetPSelectTIDate write SetPSelectTIDate;
property PSelectTICont: Boolean read GetPSelectTICont write SetPSelectTICont;
property PSelectTIWaived: Boolean read GetPSelectTIWaived write SetPSelectTIWaived;
property PSelectTIHistory: Boolean read GetPSelectTIHistory write SetPSelectTIHistory;
property PSelectTISatisfied: Boolean read GetPSelectTISatisfied write SetPSelectTISatisfied;
property PSelectTINA: Boolean read GetPSelectTINA write SetPSelectTINA;
property PExpireDateFrom: String read GetPExpireDateFrom write SetPExpireDateFrom;
property PExpireDateTo: String read GetPExpireDateTo write SetPExpireDateTo;
property PIncludeTI: Boolean read GetPIncludeTI write SetPIncludeTI;
property PNoticeItems: Boolean read GetPNoticeItems write SetPNoticeItems;
property PNoticeItemFrom: String read GetPNoticeItemFrom write SetPNoticeItemFrom;
property PNoticeItemTo: String read GetPNoticeItemTo write SetPNoticeItemTo;
property PLoanNotes: Boolean read GetPLoanNotes write SetPLoanNotes;
property PTINotes: Boolean read GetPTINotes write SetPTINotes;
property PCoMaker: Boolean read GetPCoMaker write SetPCoMaker;
property PGuarantor: Boolean read GetPGuarantor write SetPGuarantor;
property PGroupBy: Integer read GetPGroupBy write SetPGroupBy;
property PItemCollDesc: Boolean read GetPItemCollDesc write SetPItemCollDesc;
property PItemOfficer: Boolean read GetPItemOfficer write SetPItemOfficer;
property PItemBalance: Boolean read GetPItemBalance write SetPItemBalance;
property PItemBranch: Boolean read GetPItemBranch write SetPItemBranch;
property PItemDivision: Boolean read GetPItemDivision write SetPItemDivision;
property PItemOpenDate: Boolean read GetPItemOpenDate write SetPItemOpenDate;
property PItemMatDate: Boolean read GetPItemMatDate write SetPItemMatDate;
property PItemAddress: Boolean read GetPItemAddress write SetPItemAddress;
property PItemCategory: Boolean read GetPItemCategory write SetPItemCategory;
property PItemPhone: Boolean read GetPItemPhone write SetPItemPhone;
property PItemStatus: Boolean read GetPItemStatus write SetPItemStatus;
property PItemDescription: Boolean read GetPItemDescription write SetPItemDescription;
property PLeadTimeOfficer: Boolean read GetPLeadTimeOfficer write SetPLeadTimeOfficer;
property PLeadTimeNotice: Boolean read GetPLeadTimeNotice write SetPLeadTimeNotice;
property PLeadTimeYouPick: Boolean read GetPLeadTimeYouPick write SetPLeadTimeYouPick;
property PLeadTime: Integer read GetPLeadTime write SetPLeadTime;
property PIncLoans: Boolean read GetPIncLoans write SetPIncLoans;
property PIncActiveCifs: Boolean read GetPIncActiveCifs write SetPIncActiveCifs;
property PIncInactiveCifs: Boolean read GetPIncInactiveCifs write SetPIncInactiveCifs;
property PIncNotPaidOut: Boolean read GetPIncNotPaidOut write SetPIncNotPaidOut;
property PIncPaidOut: Boolean read GetPIncPaidOut write SetPIncPaidOut;
property PIncLoanWithNotes: Boolean read GetPIncLoanWithNotes write SetPIncLoanWithNotes;
property PIncLoanWONotes: Boolean read GetPIncLoanWONotes write SetPIncLoanWONotes;
property PIncWithTracked: Boolean read GetPIncWithTracked write SetPIncWithTracked;
property PIncWOTracked: Boolean read GetPIncWOTracked write SetPIncWOTracked;
property PIncWithNoticeItems: Boolean read GetPIncWithNoticeItems write SetPIncWithNoticeItems;
property PIncWONoticeItems: Boolean read GetPIncWONoticeItems write SetPIncWONoticeItems;
property PIncLoanNotes: Boolean read GetPIncLoanNotes write SetPIncLoanNotes;
property PIncCifs: Boolean read GetPIncCifs write SetPIncCifs;
property PELRecapOnly: Boolean read GetPELRecapOnly write SetPELRecapOnly;
property PExpLoanCif: Boolean read GetPExpLoanCif write SetPExpLoanCif;
property PExpLoanCifNotes: Boolean read GetPExpLoanCifNotes write SetPExpLoanCifNotes;
property PExpTracked: Boolean read GetPExpTracked write SetPExpTracked;
property PExpTrackedNotes: Boolean read GetPExpTrackedNotes write SetPExpTrackedNotes;
property PExpTrackedExtend: Boolean read GetPExpTrackedExtend write SetPExpTrackedExtend;
property PExpFormat: Integer read GetPExpFormat write SetPExpFormat;
property PExpOpt1: Boolean read GetPExpOpt1 write SetPExpOpt1;
property PExpOpt2: Boolean read GetPExpOpt2 write SetPExpOpt2;
property PExpOpt3: Boolean read GetPExpOpt3 write SetPExpOpt3;
property PItemEntryFrom: String read GetPItemEntryFrom write SetPItemEntryFrom;
property PItemEntryTo: String read GetPItemEntryTo write SetPItemEntryTo;
property PItemEntryBy: String read GetPItemEntryBy write SetPItemEntryBy;
property PShowTIUser: Boolean read GetPShowTIUser write SetPShowTIUser;
property PShowTIEntryDate: Boolean read GetPShowTIEntryDate write SetPShowTIEntryDate;
property PExcludeCats: Boolean read GetPExcludeCats write SetPExcludeCats;
published
property Active write SetActive;
property EnumIndex: TEITTSNOTICEPT read GetEnumIndex write SetEnumIndex;
end; { TTTSNOTICEPTTable }
procedure Register;
implementation
function TTTSNOTICEPTTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSNOTICEPTTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSNOTICEPTTable.GenerateNewFieldName }
function TTTSNOTICEPTTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSNOTICEPTTable.CreateField }
procedure TTTSNOTICEPTTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFType := CreateField( 'Type' ) as TIntegerField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFNoticeScanDate := CreateField( 'NoticeScanDate' ) as TStringField;
FDFLetterDate := CreateField( 'LetterDate' ) as TStringField;
FDFNoticeType := CreateField( 'NoticeType' ) as TStringField;
FDFReprint := CreateField( 'Reprint' ) as TBooleanField;
FDFLimit1 := CreateField( 'Limit1' ) as TBooleanField;
FDFLimitNo1 := CreateField( 'LimitNo1' ) as TIntegerField;
FDFLimit2 := CreateField( 'Limit2' ) as TBooleanField;
FDFLimitNo2 := CreateField( 'LimitNo2' ) as TIntegerField;
FDFLimit3 := CreateField( 'Limit3' ) as TBooleanField;
FDFLimitNo3 := CreateField( 'LimitNo3' ) as TIntegerField;
FDFLimit4 := CreateField( 'Limit4' ) as TBooleanField;
FDFLimitNo4 := CreateField( 'LimitNo4' ) as TIntegerField;
FDFLimit5 := CreateField( 'Limit5' ) as TBooleanField;
FDFLimitNo5 := CreateField( 'LimitNo5' ) as TIntegerField;
FDFSortOrder := CreateField( 'SortOrder' ) as TStringField;
FDFLoanCif := CreateField( 'LoanCif' ) as TIntegerField;
FDFCifs := CreateField( 'Cifs' ) as TIntegerField;
FDFBalanceFrom := CreateField( 'BalanceFrom' ) as TCurrencyField;
FDFBalanceTo := CreateField( 'BalanceTo' ) as TCurrencyField;
FDFSeperateNotice := CreateField( 'SeperateNotice' ) as TIntegerField;
FDFPaidouts := CreateField( 'Paidouts' ) as TBooleanField;
FDFMatureFrom := CreateField( 'MatureFrom' ) as TStringField;
FDFMatureTo := CreateField( 'MatureTo' ) as TStringField;
FDFOpenFrom := CreateField( 'OpenFrom' ) as TStringField;
FDFOpenTo := CreateField( 'OpenTo' ) as TStringField;
FDFCats := CreateField( 'Cats' ) as TBlobField;
FDFCollCodes := CreateField( 'CollCodes' ) as TBlobField;
FDFOfficers := CreateField( 'Officers' ) as TBlobField;
FDFBranchs := CreateField( 'Branchs' ) as TBlobField;
FDFDivisions := CreateField( 'Divisions' ) as TBlobField;
FDFReportTitle := CreateField( 'ReportTitle' ) as TStringField;
FDFPaidDatesFrom := CreateField( 'PaidDatesFrom' ) as TStringField;
FDFPaidDatesTo := CreateField( 'PaidDatesTo' ) as TStringField;
FDFSelectTIDate := CreateField( 'SelectTIDate' ) as TBooleanField;
FDFSelectTICont := CreateField( 'SelectTICont' ) as TBooleanField;
FDFSelectTIWaived := CreateField( 'SelectTIWaived' ) as TBooleanField;
FDFSelectTIHistory := CreateField( 'SelectTIHistory' ) as TBooleanField;
FDFSelectTISatisfied := CreateField( 'SelectTISatisfied' ) as TBooleanField;
FDFSelectTINA := CreateField( 'SelectTINA' ) as TBooleanField;
FDFExpireDateFrom := CreateField( 'ExpireDateFrom' ) as TStringField;
FDFExpireDateTo := CreateField( 'ExpireDateTo' ) as TStringField;
FDFIncludeTI := CreateField( 'IncludeTI' ) as TBooleanField;
FDFNoticeItems := CreateField( 'NoticeItems' ) as TBooleanField;
FDFNoticeItemFrom := CreateField( 'NoticeItemFrom' ) as TStringField;
FDFNoticeItemTo := CreateField( 'NoticeItemTo' ) as TStringField;
FDFLoanNotes := CreateField( 'LoanNotes' ) as TBooleanField;
FDFTINotes := CreateField( 'TINotes' ) as TBooleanField;
FDFCoMaker := CreateField( 'CoMaker' ) as TBooleanField;
FDFGuarantor := CreateField( 'Guarantor' ) as TBooleanField;
FDFGroupBy := CreateField( 'GroupBy' ) as TIntegerField;
FDFItemCollDesc := CreateField( 'ItemCollDesc' ) as TBooleanField;
FDFItemOfficer := CreateField( 'ItemOfficer' ) as TBooleanField;
FDFItemBalance := CreateField( 'ItemBalance' ) as TBooleanField;
FDFItemBranch := CreateField( 'ItemBranch' ) as TBooleanField;
FDFItemDivision := CreateField( 'ItemDivision' ) as TBooleanField;
FDFItemOpenDate := CreateField( 'ItemOpenDate' ) as TBooleanField;
FDFItemMatDate := CreateField( 'ItemMatDate' ) as TBooleanField;
FDFItemAddress := CreateField( 'ItemAddress' ) as TBooleanField;
FDFItemCategory := CreateField( 'ItemCategory' ) as TBooleanField;
FDFItemPhone := CreateField( 'ItemPhone' ) as TBooleanField;
FDFItemStatus := CreateField( 'ItemStatus' ) as TBooleanField;
FDFItemDescription := CreateField( 'ItemDescription' ) as TBooleanField;
FDFLeadTimeOfficer := CreateField( 'LeadTimeOfficer' ) as TBooleanField;
FDFLeadTimeNotice := CreateField( 'LeadTimeNotice' ) as TBooleanField;
FDFLeadTimeYouPick := CreateField( 'LeadTimeYouPick' ) as TBooleanField;
FDFLeadTime := CreateField( 'LeadTime' ) as TIntegerField;
FDFIncLoans := CreateField( 'IncLoans' ) as TBooleanField;
FDFIncActiveCifs := CreateField( 'IncActiveCifs' ) as TBooleanField;
FDFIncInactiveCifs := CreateField( 'IncInactiveCifs' ) as TBooleanField;
FDFIncNotPaidOut := CreateField( 'IncNotPaidOut' ) as TBooleanField;
FDFIncPaidOut := CreateField( 'IncPaidOut' ) as TBooleanField;
FDFIncLoanWithNotes := CreateField( 'IncLoanWithNotes' ) as TBooleanField;
FDFIncLoanWONotes := CreateField( 'IncLoanWONotes' ) as TBooleanField;
FDFIncWithTracked := CreateField( 'IncWithTracked' ) as TBooleanField;
FDFIncWOTracked := CreateField( 'IncWOTracked' ) as TBooleanField;
FDFIncWithNoticeItems := CreateField( 'IncWithNoticeItems' ) as TBooleanField;
FDFIncWONoticeItems := CreateField( 'IncWONoticeItems' ) as TBooleanField;
FDFIncLoanNotes := CreateField( 'IncLoanNotes' ) as TBooleanField;
FDFIncCifs := CreateField( 'IncCifs' ) as TBooleanField;
FDFELRecapOnly := CreateField( 'ELRecapOnly' ) as TBooleanField;
FDFExpLoanCif := CreateField( 'ExpLoanCif' ) as TBooleanField;
FDFExpLoanCifNotes := CreateField( 'ExpLoanCifNotes' ) as TBooleanField;
FDFExpTracked := CreateField( 'ExpTracked' ) as TBooleanField;
FDFExpTrackedNotes := CreateField( 'ExpTrackedNotes' ) as TBooleanField;
FDFExpTrackedExtend := CreateField( 'ExpTrackedExtend' ) as TBooleanField;
FDFExpFormat := CreateField( 'ExpFormat' ) as TIntegerField;
FDFExpOpt1 := CreateField( 'ExpOpt1' ) as TBooleanField;
FDFExpOpt2 := CreateField( 'ExpOpt2' ) as TBooleanField;
FDFExpOpt3 := CreateField( 'ExpOpt3' ) as TBooleanField;
FDFItemEntryFrom := CreateField( 'ItemEntryFrom' ) as TStringField;
FDFItemEntryTo := CreateField( 'ItemEntryTo' ) as TStringField;
FDFItemEntryBy := CreateField( 'ItemEntryBy' ) as TStringField;
FDFShowTIUser := CreateField( 'ShowTIUser' ) as TBooleanField;
FDFShowTIEntryDate := CreateField( 'ShowTIEntryDate' ) as TBooleanField;
FDFExcludeCats := CreateField( 'ExcludeCats' ) as TBooleanField;
end; { TTTSNOTICEPTTable.CreateFields }
procedure TTTSNOTICEPTTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSNOTICEPTTable.SetActive }
procedure TTTSNOTICEPTTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSNOTICEPTTable.SetPType(const Value: Integer);
begin
DFType.Value := Value;
end;
function TTTSNOTICEPTTable.GetPType:Integer;
begin
result := DFType.Value;
end;
procedure TTTSNOTICEPTTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TTTSNOTICEPTTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TTTSNOTICEPTTable.SetPNoticeScanDate(const Value: String);
begin
DFNoticeScanDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPNoticeScanDate:String;
begin
result := DFNoticeScanDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPLetterDate(const Value: String);
begin
DFLetterDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLetterDate:String;
begin
result := DFLetterDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPNoticeType(const Value: String);
begin
DFNoticeType.Value := Value;
end;
function TTTSNOTICEPTTable.GetPNoticeType:String;
begin
result := DFNoticeType.Value;
end;
procedure TTTSNOTICEPTTable.SetPReprint(const Value: Boolean);
begin
DFReprint.Value := Value;
end;
function TTTSNOTICEPTTable.GetPReprint:Boolean;
begin
result := DFReprint.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimit1(const Value: Boolean);
begin
DFLimit1.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimit1:Boolean;
begin
result := DFLimit1.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimitNo1(const Value: Integer);
begin
DFLimitNo1.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimitNo1:Integer;
begin
result := DFLimitNo1.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimit2(const Value: Boolean);
begin
DFLimit2.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimit2:Boolean;
begin
result := DFLimit2.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimitNo2(const Value: Integer);
begin
DFLimitNo2.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimitNo2:Integer;
begin
result := DFLimitNo2.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimit3(const Value: Boolean);
begin
DFLimit3.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimit3:Boolean;
begin
result := DFLimit3.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimitNo3(const Value: Integer);
begin
DFLimitNo3.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimitNo3:Integer;
begin
result := DFLimitNo3.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimit4(const Value: Boolean);
begin
DFLimit4.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimit4:Boolean;
begin
result := DFLimit4.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimitNo4(const Value: Integer);
begin
DFLimitNo4.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimitNo4:Integer;
begin
result := DFLimitNo4.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimit5(const Value: Boolean);
begin
DFLimit5.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimit5:Boolean;
begin
result := DFLimit5.Value;
end;
procedure TTTSNOTICEPTTable.SetPLimitNo5(const Value: Integer);
begin
DFLimitNo5.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLimitNo5:Integer;
begin
result := DFLimitNo5.Value;
end;
procedure TTTSNOTICEPTTable.SetPSortOrder(const Value: String);
begin
DFSortOrder.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSortOrder:String;
begin
result := DFSortOrder.Value;
end;
procedure TTTSNOTICEPTTable.SetPLoanCif(const Value: Integer);
begin
DFLoanCif.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLoanCif:Integer;
begin
result := DFLoanCif.Value;
end;
procedure TTTSNOTICEPTTable.SetPCifs(const Value: Integer);
begin
DFCifs.Value := Value;
end;
function TTTSNOTICEPTTable.GetPCifs:Integer;
begin
result := DFCifs.Value;
end;
procedure TTTSNOTICEPTTable.SetPBalanceFrom(const Value: Currency);
begin
DFBalanceFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPBalanceFrom:Currency;
begin
result := DFBalanceFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPBalanceTo(const Value: Currency);
begin
DFBalanceTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPBalanceTo:Currency;
begin
result := DFBalanceTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPSeperateNotice(const Value: Integer);
begin
DFSeperateNotice.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSeperateNotice:Integer;
begin
result := DFSeperateNotice.Value;
end;
procedure TTTSNOTICEPTTable.SetPPaidouts(const Value: Boolean);
begin
DFPaidouts.Value := Value;
end;
function TTTSNOTICEPTTable.GetPPaidouts:Boolean;
begin
result := DFPaidouts.Value;
end;
procedure TTTSNOTICEPTTable.SetPMatureFrom(const Value: String);
begin
DFMatureFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPMatureFrom:String;
begin
result := DFMatureFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPMatureTo(const Value: String);
begin
DFMatureTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPMatureTo:String;
begin
result := DFMatureTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPOpenFrom(const Value: String);
begin
DFOpenFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPOpenFrom:String;
begin
result := DFOpenFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPOpenTo(const Value: String);
begin
DFOpenTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPOpenTo:String;
begin
result := DFOpenTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPReportTitle(const Value: String);
begin
DFReportTitle.Value := Value;
end;
function TTTSNOTICEPTTable.GetPReportTitle:String;
begin
result := DFReportTitle.Value;
end;
procedure TTTSNOTICEPTTable.SetPPaidDatesFrom(const Value: String);
begin
DFPaidDatesFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPPaidDatesFrom:String;
begin
result := DFPaidDatesFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPPaidDatesTo(const Value: String);
begin
DFPaidDatesTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPPaidDatesTo:String;
begin
result := DFPaidDatesTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTIDate(const Value: Boolean);
begin
DFSelectTIDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTIDate:Boolean;
begin
result := DFSelectTIDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTICont(const Value: Boolean);
begin
DFSelectTICont.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTICont:Boolean;
begin
result := DFSelectTICont.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTIWaived(const Value: Boolean);
begin
DFSelectTIWaived.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTIWaived:Boolean;
begin
result := DFSelectTIWaived.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTIHistory(const Value: Boolean);
begin
DFSelectTIHistory.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTIHistory:Boolean;
begin
result := DFSelectTIHistory.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTISatisfied(const Value: Boolean);
begin
DFSelectTISatisfied.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTISatisfied:Boolean;
begin
result := DFSelectTISatisfied.Value;
end;
procedure TTTSNOTICEPTTable.SetPSelectTINA(const Value: Boolean);
begin
DFSelectTINA.Value := Value;
end;
function TTTSNOTICEPTTable.GetPSelectTINA:Boolean;
begin
result := DFSelectTINA.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpireDateFrom(const Value: String);
begin
DFExpireDateFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpireDateFrom:String;
begin
result := DFExpireDateFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpireDateTo(const Value: String);
begin
DFExpireDateTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpireDateTo:String;
begin
result := DFExpireDateTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncludeTI(const Value: Boolean);
begin
DFIncludeTI.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncludeTI:Boolean;
begin
result := DFIncludeTI.Value;
end;
procedure TTTSNOTICEPTTable.SetPNoticeItems(const Value: Boolean);
begin
DFNoticeItems.Value := Value;
end;
function TTTSNOTICEPTTable.GetPNoticeItems:Boolean;
begin
result := DFNoticeItems.Value;
end;
procedure TTTSNOTICEPTTable.SetPNoticeItemFrom(const Value: String);
begin
DFNoticeItemFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPNoticeItemFrom:String;
begin
result := DFNoticeItemFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPNoticeItemTo(const Value: String);
begin
DFNoticeItemTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPNoticeItemTo:String;
begin
result := DFNoticeItemTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPLoanNotes(const Value: Boolean);
begin
DFLoanNotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLoanNotes:Boolean;
begin
result := DFLoanNotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPTINotes(const Value: Boolean);
begin
DFTINotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPTINotes:Boolean;
begin
result := DFTINotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPCoMaker(const Value: Boolean);
begin
DFCoMaker.Value := Value;
end;
function TTTSNOTICEPTTable.GetPCoMaker:Boolean;
begin
result := DFCoMaker.Value;
end;
procedure TTTSNOTICEPTTable.SetPGuarantor(const Value: Boolean);
begin
DFGuarantor.Value := Value;
end;
function TTTSNOTICEPTTable.GetPGuarantor:Boolean;
begin
result := DFGuarantor.Value;
end;
procedure TTTSNOTICEPTTable.SetPGroupBy(const Value: Integer);
begin
DFGroupBy.Value := Value;
end;
function TTTSNOTICEPTTable.GetPGroupBy:Integer;
begin
result := DFGroupBy.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemCollDesc(const Value: Boolean);
begin
DFItemCollDesc.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemCollDesc:Boolean;
begin
result := DFItemCollDesc.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemOfficer(const Value: Boolean);
begin
DFItemOfficer.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemOfficer:Boolean;
begin
result := DFItemOfficer.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemBalance(const Value: Boolean);
begin
DFItemBalance.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemBalance:Boolean;
begin
result := DFItemBalance.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemBranch(const Value: Boolean);
begin
DFItemBranch.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemBranch:Boolean;
begin
result := DFItemBranch.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemDivision(const Value: Boolean);
begin
DFItemDivision.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemDivision:Boolean;
begin
result := DFItemDivision.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemOpenDate(const Value: Boolean);
begin
DFItemOpenDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemOpenDate:Boolean;
begin
result := DFItemOpenDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemMatDate(const Value: Boolean);
begin
DFItemMatDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemMatDate:Boolean;
begin
result := DFItemMatDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemAddress(const Value: Boolean);
begin
DFItemAddress.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemAddress:Boolean;
begin
result := DFItemAddress.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemCategory(const Value: Boolean);
begin
DFItemCategory.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemCategory:Boolean;
begin
result := DFItemCategory.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemPhone(const Value: Boolean);
begin
DFItemPhone.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemPhone:Boolean;
begin
result := DFItemPhone.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemStatus(const Value: Boolean);
begin
DFItemStatus.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemStatus:Boolean;
begin
result := DFItemStatus.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemDescription(const Value: Boolean);
begin
DFItemDescription.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemDescription:Boolean;
begin
result := DFItemDescription.Value;
end;
procedure TTTSNOTICEPTTable.SetPLeadTimeOfficer(const Value: Boolean);
begin
DFLeadTimeOfficer.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLeadTimeOfficer:Boolean;
begin
result := DFLeadTimeOfficer.Value;
end;
procedure TTTSNOTICEPTTable.SetPLeadTimeNotice(const Value: Boolean);
begin
DFLeadTimeNotice.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLeadTimeNotice:Boolean;
begin
result := DFLeadTimeNotice.Value;
end;
procedure TTTSNOTICEPTTable.SetPLeadTimeYouPick(const Value: Boolean);
begin
DFLeadTimeYouPick.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLeadTimeYouPick:Boolean;
begin
result := DFLeadTimeYouPick.Value;
end;
procedure TTTSNOTICEPTTable.SetPLeadTime(const Value: Integer);
begin
DFLeadTime.Value := Value;
end;
function TTTSNOTICEPTTable.GetPLeadTime:Integer;
begin
result := DFLeadTime.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncLoans(const Value: Boolean);
begin
DFIncLoans.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncLoans:Boolean;
begin
result := DFIncLoans.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncActiveCifs(const Value: Boolean);
begin
DFIncActiveCifs.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncActiveCifs:Boolean;
begin
result := DFIncActiveCifs.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncInactiveCifs(const Value: Boolean);
begin
DFIncInactiveCifs.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncInactiveCifs:Boolean;
begin
result := DFIncInactiveCifs.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncNotPaidOut(const Value: Boolean);
begin
DFIncNotPaidOut.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncNotPaidOut:Boolean;
begin
result := DFIncNotPaidOut.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncPaidOut(const Value: Boolean);
begin
DFIncPaidOut.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncPaidOut:Boolean;
begin
result := DFIncPaidOut.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncLoanWithNotes(const Value: Boolean);
begin
DFIncLoanWithNotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncLoanWithNotes:Boolean;
begin
result := DFIncLoanWithNotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncLoanWONotes(const Value: Boolean);
begin
DFIncLoanWONotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncLoanWONotes:Boolean;
begin
result := DFIncLoanWONotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncWithTracked(const Value: Boolean);
begin
DFIncWithTracked.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncWithTracked:Boolean;
begin
result := DFIncWithTracked.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncWOTracked(const Value: Boolean);
begin
DFIncWOTracked.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncWOTracked:Boolean;
begin
result := DFIncWOTracked.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncWithNoticeItems(const Value: Boolean);
begin
DFIncWithNoticeItems.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncWithNoticeItems:Boolean;
begin
result := DFIncWithNoticeItems.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncWONoticeItems(const Value: Boolean);
begin
DFIncWONoticeItems.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncWONoticeItems:Boolean;
begin
result := DFIncWONoticeItems.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncLoanNotes(const Value: Boolean);
begin
DFIncLoanNotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncLoanNotes:Boolean;
begin
result := DFIncLoanNotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPIncCifs(const Value: Boolean);
begin
DFIncCifs.Value := Value;
end;
function TTTSNOTICEPTTable.GetPIncCifs:Boolean;
begin
result := DFIncCifs.Value;
end;
procedure TTTSNOTICEPTTable.SetPELRecapOnly(const Value: Boolean);
begin
DFELRecapOnly.Value := Value;
end;
function TTTSNOTICEPTTable.GetPELRecapOnly:Boolean;
begin
result := DFELRecapOnly.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpLoanCif(const Value: Boolean);
begin
DFExpLoanCif.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpLoanCif:Boolean;
begin
result := DFExpLoanCif.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpLoanCifNotes(const Value: Boolean);
begin
DFExpLoanCifNotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpLoanCifNotes:Boolean;
begin
result := DFExpLoanCifNotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpTracked(const Value: Boolean);
begin
DFExpTracked.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpTracked:Boolean;
begin
result := DFExpTracked.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpTrackedNotes(const Value: Boolean);
begin
DFExpTrackedNotes.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpTrackedNotes:Boolean;
begin
result := DFExpTrackedNotes.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpTrackedExtend(const Value: Boolean);
begin
DFExpTrackedExtend.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpTrackedExtend:Boolean;
begin
result := DFExpTrackedExtend.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpFormat(const Value: Integer);
begin
DFExpFormat.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpFormat:Integer;
begin
result := DFExpFormat.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpOpt1(const Value: Boolean);
begin
DFExpOpt1.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpOpt1:Boolean;
begin
result := DFExpOpt1.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpOpt2(const Value: Boolean);
begin
DFExpOpt2.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpOpt2:Boolean;
begin
result := DFExpOpt2.Value;
end;
procedure TTTSNOTICEPTTable.SetPExpOpt3(const Value: Boolean);
begin
DFExpOpt3.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExpOpt3:Boolean;
begin
result := DFExpOpt3.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemEntryFrom(const Value: String);
begin
DFItemEntryFrom.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemEntryFrom:String;
begin
result := DFItemEntryFrom.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemEntryTo(const Value: String);
begin
DFItemEntryTo.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemEntryTo:String;
begin
result := DFItemEntryTo.Value;
end;
procedure TTTSNOTICEPTTable.SetPItemEntryBy(const Value: String);
begin
DFItemEntryBy.Value := Value;
end;
function TTTSNOTICEPTTable.GetPItemEntryBy:String;
begin
result := DFItemEntryBy.Value;
end;
procedure TTTSNOTICEPTTable.SetPShowTIUser(const Value: Boolean);
begin
DFShowTIUser.Value := Value;
end;
function TTTSNOTICEPTTable.GetPShowTIUser:Boolean;
begin
result := DFShowTIUser.Value;
end;
procedure TTTSNOTICEPTTable.SetPShowTIEntryDate(const Value: Boolean);
begin
DFShowTIEntryDate.Value := Value;
end;
function TTTSNOTICEPTTable.GetPShowTIEntryDate:Boolean;
begin
result := DFShowTIEntryDate.Value;
end;
procedure TTTSNOTICEPTTable.SetPExcludeCats(const Value: Boolean);
begin
DFExcludeCats.Value := Value;
end;
function TTTSNOTICEPTTable.GetPExcludeCats:Boolean;
begin
result := DFExcludeCats.Value;
end;
procedure TTTSNOTICEPTTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 8, N');
Add('Type, Integer, 0, N');
Add('Description, String, 100, N');
Add('NoticeScanDate, String, 10, N');
Add('LetterDate, String, 10, N');
Add('NoticeType, String, 1, N');
Add('Reprint, Boolean, 0, N');
Add('Limit1, Boolean, 0, N');
Add('LimitNo1, Integer, 0, N');
Add('Limit2, Boolean, 0, N');
Add('LimitNo2, Integer, 0, N');
Add('Limit3, Boolean, 0, N');
Add('LimitNo3, Integer, 0, N');
Add('Limit4, Boolean, 0, N');
Add('LimitNo4, Integer, 0, N');
Add('Limit5, Boolean, 0, N');
Add('LimitNo5, Integer, 0, N');
Add('SortOrder, String, 10, N');
Add('LoanCif, Integer, 0, N');
Add('Cifs, Integer, 0, N');
Add('BalanceFrom, Currency, 0, N');
Add('BalanceTo, Currency, 0, N');
Add('SeperateNotice, Integer, 0, N');
Add('Paidouts, Boolean, 0, N');
Add('MatureFrom, String, 10, N');
Add('MatureTo, String, 10, N');
Add('OpenFrom, String, 10, N');
Add('OpenTo, String, 10, N');
Add('Cats, Memo, 0, N');
Add('CollCodes, Memo, 0, N');
Add('Officers, Memo, 0, N');
Add('Branchs, Memo, 0, N');
Add('Divisions, Memo, 0, N');
Add('ReportTitle, String, 40, N');
Add('PaidDatesFrom, String, 10, N');
Add('PaidDatesTo, String, 10, N');
Add('SelectTIDate, Boolean, 0, N');
Add('SelectTICont, Boolean, 0, N');
Add('SelectTIWaived, Boolean, 0, N');
Add('SelectTIHistory, Boolean, 0, N');
Add('SelectTISatisfied, Boolean, 0, N');
Add('SelectTINA, Boolean, 0, N');
Add('ExpireDateFrom, String, 10, N');
Add('ExpireDateTo, String, 10, N');
Add('IncludeTI, Boolean, 0, N');
Add('NoticeItems, Boolean, 0, N');
Add('NoticeItemFrom, String, 10, N');
Add('NoticeItemTo, String, 10, N');
Add('LoanNotes, Boolean, 0, N');
Add('TINotes, Boolean, 0, N');
Add('CoMaker, Boolean, 0, N');
Add('Guarantor, Boolean, 0, N');
Add('GroupBy, Integer, 0, N');
Add('ItemCollDesc, Boolean, 0, N');
Add('ItemOfficer, Boolean, 0, N');
Add('ItemBalance, Boolean, 0, N');
Add('ItemBranch, Boolean, 0, N');
Add('ItemDivision, Boolean, 0, N');
Add('ItemOpenDate, Boolean, 0, N');
Add('ItemMatDate, Boolean, 0, N');
Add('ItemAddress, Boolean, 0, N');
Add('ItemCategory, Boolean, 0, N');
Add('ItemPhone, Boolean, 0, N');
Add('ItemStatus, Boolean, 0, N');
Add('ItemDescription, Boolean, 0, N');
Add('LeadTimeOfficer, Boolean, 0, N');
Add('LeadTimeNotice, Boolean, 0, N');
Add('LeadTimeYouPick, Boolean, 0, N');
Add('LeadTime, Integer, 0, N');
Add('IncLoans, Boolean, 0, N');
Add('IncActiveCifs, Boolean, 0, N');
Add('IncInactiveCifs, Boolean, 0, N');
Add('IncNotPaidOut, Boolean, 0, N');
Add('IncPaidOut, Boolean, 0, N');
Add('IncLoanWithNotes, Boolean, 0, N');
Add('IncLoanWONotes, Boolean, 0, N');
Add('IncWithTracked, Boolean, 0, N');
Add('IncWOTracked, Boolean, 0, N');
Add('IncWithNoticeItems, Boolean, 0, N');
Add('IncWONoticeItems, Boolean, 0, N');
Add('IncLoanNotes, Boolean, 0, N');
Add('IncCifs, Boolean, 0, N');
Add('ELRecapOnly, Boolean, 0, N');
Add('ExpLoanCif, Boolean, 0, N');
Add('ExpLoanCifNotes, Boolean, 0, N');
Add('ExpTracked, Boolean, 0, N');
Add('ExpTrackedNotes, Boolean, 0, N');
Add('ExpTrackedExtend, Boolean, 0, N');
Add('ExpFormat, Integer, 0, N');
Add('ExpOpt1, Boolean, 0, N');
Add('ExpOpt2, Boolean, 0, N');
Add('ExpOpt3, Boolean, 0, N');
Add('ItemEntryFrom, String, 10, N');
Add('ItemEntryTo, String, 10, N');
Add('ItemEntryBy, String, 100, N');
Add('ShowTIUser, Boolean, 0, N');
Add('ShowTIEntryDate, Boolean, 0, N');
Add('ExcludeCats, Boolean, 0, N');
end;
end;
procedure TTTSNOTICEPTTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;Type;Description, Y, Y, N, N');
end;
end;
procedure TTTSNOTICEPTTable.SetEnumIndex(Value: TEITTSNOTICEPT);
begin
case Value of
TTSNOTICEPTPrimaryKey : IndexName := '';
end;
end;
function TTTSNOTICEPTTable.GetDataBuffer:TTTSNOTICEPTRecord;
var buf: TTTSNOTICEPTRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PType := DFType.Value;
buf.PDescription := DFDescription.Value;
buf.PNoticeScanDate := DFNoticeScanDate.Value;
buf.PLetterDate := DFLetterDate.Value;
buf.PNoticeType := DFNoticeType.Value;
buf.PReprint := DFReprint.Value;
buf.PLimit1 := DFLimit1.Value;
buf.PLimitNo1 := DFLimitNo1.Value;
buf.PLimit2 := DFLimit2.Value;
buf.PLimitNo2 := DFLimitNo2.Value;
buf.PLimit3 := DFLimit3.Value;
buf.PLimitNo3 := DFLimitNo3.Value;
buf.PLimit4 := DFLimit4.Value;
buf.PLimitNo4 := DFLimitNo4.Value;
buf.PLimit5 := DFLimit5.Value;
buf.PLimitNo5 := DFLimitNo5.Value;
buf.PSortOrder := DFSortOrder.Value;
buf.PLoanCif := DFLoanCif.Value;
buf.PCifs := DFCifs.Value;
buf.PBalanceFrom := DFBalanceFrom.Value;
buf.PBalanceTo := DFBalanceTo.Value;
buf.PSeperateNotice := DFSeperateNotice.Value;
buf.PPaidouts := DFPaidouts.Value;
buf.PMatureFrom := DFMatureFrom.Value;
buf.PMatureTo := DFMatureTo.Value;
buf.POpenFrom := DFOpenFrom.Value;
buf.POpenTo := DFOpenTo.Value;
buf.PReportTitle := DFReportTitle.Value;
buf.PPaidDatesFrom := DFPaidDatesFrom.Value;
buf.PPaidDatesTo := DFPaidDatesTo.Value;
buf.PSelectTIDate := DFSelectTIDate.Value;
buf.PSelectTICont := DFSelectTICont.Value;
buf.PSelectTIWaived := DFSelectTIWaived.Value;
buf.PSelectTIHistory := DFSelectTIHistory.Value;
buf.PSelectTISatisfied := DFSelectTISatisfied.Value;
buf.PSelectTINA := DFSelectTINA.Value;
buf.PExpireDateFrom := DFExpireDateFrom.Value;
buf.PExpireDateTo := DFExpireDateTo.Value;
buf.PIncludeTI := DFIncludeTI.Value;
buf.PNoticeItems := DFNoticeItems.Value;
buf.PNoticeItemFrom := DFNoticeItemFrom.Value;
buf.PNoticeItemTo := DFNoticeItemTo.Value;
buf.PLoanNotes := DFLoanNotes.Value;
buf.PTINotes := DFTINotes.Value;
buf.PCoMaker := DFCoMaker.Value;
buf.PGuarantor := DFGuarantor.Value;
buf.PGroupBy := DFGroupBy.Value;
buf.PItemCollDesc := DFItemCollDesc.Value;
buf.PItemOfficer := DFItemOfficer.Value;
buf.PItemBalance := DFItemBalance.Value;
buf.PItemBranch := DFItemBranch.Value;
buf.PItemDivision := DFItemDivision.Value;
buf.PItemOpenDate := DFItemOpenDate.Value;
buf.PItemMatDate := DFItemMatDate.Value;
buf.PItemAddress := DFItemAddress.Value;
buf.PItemCategory := DFItemCategory.Value;
buf.PItemPhone := DFItemPhone.Value;
buf.PItemStatus := DFItemStatus.Value;
buf.PItemDescription := DFItemDescription.Value;
buf.PLeadTimeOfficer := DFLeadTimeOfficer.Value;
buf.PLeadTimeNotice := DFLeadTimeNotice.Value;
buf.PLeadTimeYouPick := DFLeadTimeYouPick.Value;
buf.PLeadTime := DFLeadTime.Value;
buf.PIncLoans := DFIncLoans.Value;
buf.PIncActiveCifs := DFIncActiveCifs.Value;
buf.PIncInactiveCifs := DFIncInactiveCifs.Value;
buf.PIncNotPaidOut := DFIncNotPaidOut.Value;
buf.PIncPaidOut := DFIncPaidOut.Value;
buf.PIncLoanWithNotes := DFIncLoanWithNotes.Value;
buf.PIncLoanWONotes := DFIncLoanWONotes.Value;
buf.PIncWithTracked := DFIncWithTracked.Value;
buf.PIncWOTracked := DFIncWOTracked.Value;
buf.PIncWithNoticeItems := DFIncWithNoticeItems.Value;
buf.PIncWONoticeItems := DFIncWONoticeItems.Value;
buf.PIncLoanNotes := DFIncLoanNotes.Value;
buf.PIncCifs := DFIncCifs.Value;
buf.PELRecapOnly := DFELRecapOnly.Value;
buf.PExpLoanCif := DFExpLoanCif.Value;
buf.PExpLoanCifNotes := DFExpLoanCifNotes.Value;
buf.PExpTracked := DFExpTracked.Value;
buf.PExpTrackedNotes := DFExpTrackedNotes.Value;
buf.PExpTrackedExtend := DFExpTrackedExtend.Value;
buf.PExpFormat := DFExpFormat.Value;
buf.PExpOpt1 := DFExpOpt1.Value;
buf.PExpOpt2 := DFExpOpt2.Value;
buf.PExpOpt3 := DFExpOpt3.Value;
buf.PItemEntryFrom := DFItemEntryFrom.Value;
buf.PItemEntryTo := DFItemEntryTo.Value;
buf.PItemEntryBy := DFItemEntryBy.Value;
buf.PShowTIUser := DFShowTIUser.Value;
buf.PShowTIEntryDate := DFShowTIEntryDate.Value;
buf.PExcludeCats := DFExcludeCats.Value;
result := buf;
end;
procedure TTTSNOTICEPTTable.StoreDataBuffer(ABuffer:TTTSNOTICEPTRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFType.Value := ABuffer.PType;
DFDescription.Value := ABuffer.PDescription;
DFNoticeScanDate.Value := ABuffer.PNoticeScanDate;
DFLetterDate.Value := ABuffer.PLetterDate;
DFNoticeType.Value := ABuffer.PNoticeType;
DFReprint.Value := ABuffer.PReprint;
DFLimit1.Value := ABuffer.PLimit1;
DFLimitNo1.Value := ABuffer.PLimitNo1;
DFLimit2.Value := ABuffer.PLimit2;
DFLimitNo2.Value := ABuffer.PLimitNo2;
DFLimit3.Value := ABuffer.PLimit3;
DFLimitNo3.Value := ABuffer.PLimitNo3;
DFLimit4.Value := ABuffer.PLimit4;
DFLimitNo4.Value := ABuffer.PLimitNo4;
DFLimit5.Value := ABuffer.PLimit5;
DFLimitNo5.Value := ABuffer.PLimitNo5;
DFSortOrder.Value := ABuffer.PSortOrder;
DFLoanCif.Value := ABuffer.PLoanCif;
DFCifs.Value := ABuffer.PCifs;
DFBalanceFrom.Value := ABuffer.PBalanceFrom;
DFBalanceTo.Value := ABuffer.PBalanceTo;
DFSeperateNotice.Value := ABuffer.PSeperateNotice;
DFPaidouts.Value := ABuffer.PPaidouts;
DFMatureFrom.Value := ABuffer.PMatureFrom;
DFMatureTo.Value := ABuffer.PMatureTo;
DFOpenFrom.Value := ABuffer.POpenFrom;
DFOpenTo.Value := ABuffer.POpenTo;
DFReportTitle.Value := ABuffer.PReportTitle;
DFPaidDatesFrom.Value := ABuffer.PPaidDatesFrom;
DFPaidDatesTo.Value := ABuffer.PPaidDatesTo;
DFSelectTIDate.Value := ABuffer.PSelectTIDate;
DFSelectTICont.Value := ABuffer.PSelectTICont;
DFSelectTIWaived.Value := ABuffer.PSelectTIWaived;
DFSelectTIHistory.Value := ABuffer.PSelectTIHistory;
DFSelectTISatisfied.Value := ABuffer.PSelectTISatisfied;
DFSelectTINA.Value := ABuffer.PSelectTINA;
DFExpireDateFrom.Value := ABuffer.PExpireDateFrom;
DFExpireDateTo.Value := ABuffer.PExpireDateTo;
DFIncludeTI.Value := ABuffer.PIncludeTI;
DFNoticeItems.Value := ABuffer.PNoticeItems;
DFNoticeItemFrom.Value := ABuffer.PNoticeItemFrom;
DFNoticeItemTo.Value := ABuffer.PNoticeItemTo;
DFLoanNotes.Value := ABuffer.PLoanNotes;
DFTINotes.Value := ABuffer.PTINotes;
DFCoMaker.Value := ABuffer.PCoMaker;
DFGuarantor.Value := ABuffer.PGuarantor;
DFGroupBy.Value := ABuffer.PGroupBy;
DFItemCollDesc.Value := ABuffer.PItemCollDesc;
DFItemOfficer.Value := ABuffer.PItemOfficer;
DFItemBalance.Value := ABuffer.PItemBalance;
DFItemBranch.Value := ABuffer.PItemBranch;
DFItemDivision.Value := ABuffer.PItemDivision;
DFItemOpenDate.Value := ABuffer.PItemOpenDate;
DFItemMatDate.Value := ABuffer.PItemMatDate;
DFItemAddress.Value := ABuffer.PItemAddress;
DFItemCategory.Value := ABuffer.PItemCategory;
DFItemPhone.Value := ABuffer.PItemPhone;
DFItemStatus.Value := ABuffer.PItemStatus;
DFItemDescription.Value := ABuffer.PItemDescription;
DFLeadTimeOfficer.Value := ABuffer.PLeadTimeOfficer;
DFLeadTimeNotice.Value := ABuffer.PLeadTimeNotice;
DFLeadTimeYouPick.Value := ABuffer.PLeadTimeYouPick;
DFLeadTime.Value := ABuffer.PLeadTime;
DFIncLoans.Value := ABuffer.PIncLoans;
DFIncActiveCifs.Value := ABuffer.PIncActiveCifs;
DFIncInactiveCifs.Value := ABuffer.PIncInactiveCifs;
DFIncNotPaidOut.Value := ABuffer.PIncNotPaidOut;
DFIncPaidOut.Value := ABuffer.PIncPaidOut;
DFIncLoanWithNotes.Value := ABuffer.PIncLoanWithNotes;
DFIncLoanWONotes.Value := ABuffer.PIncLoanWONotes;
DFIncWithTracked.Value := ABuffer.PIncWithTracked;
DFIncWOTracked.Value := ABuffer.PIncWOTracked;
DFIncWithNoticeItems.Value := ABuffer.PIncWithNoticeItems;
DFIncWONoticeItems.Value := ABuffer.PIncWONoticeItems;
DFIncLoanNotes.Value := ABuffer.PIncLoanNotes;
DFIncCifs.Value := ABuffer.PIncCifs;
DFELRecapOnly.Value := ABuffer.PELRecapOnly;
DFExpLoanCif.Value := ABuffer.PExpLoanCif;
DFExpLoanCifNotes.Value := ABuffer.PExpLoanCifNotes;
DFExpTracked.Value := ABuffer.PExpTracked;
DFExpTrackedNotes.Value := ABuffer.PExpTrackedNotes;
DFExpTrackedExtend.Value := ABuffer.PExpTrackedExtend;
DFExpFormat.Value := ABuffer.PExpFormat;
DFExpOpt1.Value := ABuffer.PExpOpt1;
DFExpOpt2.Value := ABuffer.PExpOpt2;
DFExpOpt3.Value := ABuffer.PExpOpt3;
DFItemEntryFrom.Value := ABuffer.PItemEntryFrom;
DFItemEntryTo.Value := ABuffer.PItemEntryTo;
DFItemEntryBy.Value := ABuffer.PItemEntryBy;
DFShowTIUser.Value := ABuffer.PShowTIUser;
DFShowTIEntryDate.Value := ABuffer.PShowTIEntryDate;
DFExcludeCats.Value := ABuffer.PExcludeCats;
end;
function TTTSNOTICEPTTable.GetEnumIndex: TEITTSNOTICEPT;
var iname : string;
begin
result := TTSNOTICEPTPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSNOTICEPTPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSNOTICEPTTable, TTTSNOTICEPTBuffer ] );
end; { Register }
function TTTSNOTICEPTBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..93] of string = ('LENDERNUM','TYPE','DESCRIPTION','NOTICESCANDATE','LETTERDATE','NOTICETYPE'
,'REPRINT','LIMIT1','LIMITNO1','LIMIT2','LIMITNO2'
,'LIMIT3','LIMITNO3','LIMIT4','LIMITNO4','LIMIT5'
,'LIMITNO5','SORTORDER','LOANCIF','CIFS','BALANCEFROM'
,'BALANCETO','SEPERATENOTICE','PAIDOUTS','MATUREFROM','MATURETO'
,'OPENFROM','OPENTO','REPORTTITLE','PAIDDATESFROM','PAIDDATESTO'
,'SELECTTIDATE','SELECTTICONT','SELECTTIWAIVED','SELECTTIHISTORY','SELECTTISATISFIED'
,'SELECTTINA','EXPIREDATEFROM','EXPIREDATETO','INCLUDETI','NOTICEITEMS'
,'NOTICEITEMFROM','NOTICEITEMTO','LOANNOTES','TINOTES','COMAKER'
,'GUARANTOR','GROUPBY','ITEMCOLLDESC','ITEMOFFICER','ITEMBALANCE'
,'ITEMBRANCH','ITEMDIVISION','ITEMOPENDATE','ITEMMATDATE','ITEMADDRESS'
,'ITEMCATEGORY','ITEMPHONE','ITEMSTATUS','ITEMDESCRIPTION','LEADTIMEOFFICER'
,'LEADTIMENOTICE','LEADTIMEYOUPICK','LEADTIME','INCLOANS','INCACTIVECIFS'
,'INCINACTIVECIFS','INCNOTPAIDOUT','INCPAIDOUT','INCLOANWITHNOTES','INCLOANWONOTES'
,'INCWITHTRACKED','INCWOTRACKED','INCWITHNOTICEITEMS','INCWONOTICEITEMS','INCLOANNOTES'
,'INCCIFS','ELRECAPONLY','EXPLOANCIF','EXPLOANCIFNOTES','EXPTRACKED'
,'EXPTRACKEDNOTES','EXPTRACKEDEXTEND','EXPFORMAT','EXPOPT1','EXPOPT2'
,'EXPOPT3','ITEMENTRYFROM','ITEMENTRYTO','ITEMENTRYBY','SHOWTIUSER'
,'SHOWTIENTRYDATE','EXCLUDECATS' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 93) and (flist[x] <> s) do inc(x);
if x <= 93 then result := x else result := 0;
end;
function TTTSNOTICEPTBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftInteger;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftBoolean;
8 : result := ftBoolean;
9 : result := ftInteger;
10 : result := ftBoolean;
11 : result := ftInteger;
12 : result := ftBoolean;
13 : result := ftInteger;
14 : result := ftBoolean;
15 : result := ftInteger;
16 : result := ftBoolean;
17 : result := ftInteger;
18 : result := ftString;
19 : result := ftInteger;
20 : result := ftInteger;
21 : result := ftCurrency;
22 : result := ftCurrency;
23 : result := ftInteger;
24 : result := ftBoolean;
25 : result := ftString;
26 : result := ftString;
27 : result := ftString;
28 : result := ftString;
29 : result := ftString;
30 : result := ftString;
31 : result := ftString;
32 : result := ftBoolean;
33 : result := ftBoolean;
34 : result := ftBoolean;
35 : result := ftBoolean;
36 : result := ftBoolean;
37 : result := ftBoolean;
38 : result := ftString;
39 : result := ftString;
40 : result := ftBoolean;
41 : result := ftBoolean;
42 : result := ftString;
43 : result := ftString;
44 : result := ftBoolean;
45 : result := ftBoolean;
46 : result := ftBoolean;
47 : result := ftBoolean;
48 : result := ftInteger;
49 : result := ftBoolean;
50 : result := ftBoolean;
51 : result := ftBoolean;
52 : result := ftBoolean;
53 : result := ftBoolean;
54 : result := ftBoolean;
55 : result := ftBoolean;
56 : result := ftBoolean;
57 : result := ftBoolean;
58 : result := ftBoolean;
59 : result := ftBoolean;
60 : result := ftBoolean;
61 : result := ftBoolean;
62 : result := ftBoolean;
63 : result := ftBoolean;
64 : result := ftInteger;
65 : result := ftBoolean;
66 : result := ftBoolean;
67 : result := ftBoolean;
68 : result := ftBoolean;
69 : result := ftBoolean;
70 : result := ftBoolean;
71 : result := ftBoolean;
72 : result := ftBoolean;
73 : result := ftBoolean;
74 : result := ftBoolean;
75 : result := ftBoolean;
76 : result := ftBoolean;
77 : result := ftBoolean;
78 : result := ftBoolean;
79 : result := ftBoolean;
80 : result := ftBoolean;
81 : result := ftBoolean;
82 : result := ftBoolean;
83 : result := ftBoolean;
84 : result := ftInteger;
85 : result := ftBoolean;
86 : result := ftBoolean;
87 : result := ftBoolean;
88 : result := ftString;
89 : result := ftString;
90 : result := ftString;
91 : result := ftBoolean;
92 : result := ftBoolean;
93 : result := ftBoolean;
end;
end;
function TTTSNOTICEPTBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PType;
3 : result := @Data.PDescription;
4 : result := @Data.PNoticeScanDate;
5 : result := @Data.PLetterDate;
6 : result := @Data.PNoticeType;
7 : result := @Data.PReprint;
8 : result := @Data.PLimit1;
9 : result := @Data.PLimitNo1;
10 : result := @Data.PLimit2;
11 : result := @Data.PLimitNo2;
12 : result := @Data.PLimit3;
13 : result := @Data.PLimitNo3;
14 : result := @Data.PLimit4;
15 : result := @Data.PLimitNo4;
16 : result := @Data.PLimit5;
17 : result := @Data.PLimitNo5;
18 : result := @Data.PSortOrder;
19 : result := @Data.PLoanCif;
20 : result := @Data.PCifs;
21 : result := @Data.PBalanceFrom;
22 : result := @Data.PBalanceTo;
23 : result := @Data.PSeperateNotice;
24 : result := @Data.PPaidouts;
25 : result := @Data.PMatureFrom;
26 : result := @Data.PMatureTo;
27 : result := @Data.POpenFrom;
28 : result := @Data.POpenTo;
29 : result := @Data.PReportTitle;
30 : result := @Data.PPaidDatesFrom;
31 : result := @Data.PPaidDatesTo;
32 : result := @Data.PSelectTIDate;
33 : result := @Data.PSelectTICont;
34 : result := @Data.PSelectTIWaived;
35 : result := @Data.PSelectTIHistory;
36 : result := @Data.PSelectTISatisfied;
37 : result := @Data.PSelectTINA;
38 : result := @Data.PExpireDateFrom;
39 : result := @Data.PExpireDateTo;
40 : result := @Data.PIncludeTI;
41 : result := @Data.PNoticeItems;
42 : result := @Data.PNoticeItemFrom;
43 : result := @Data.PNoticeItemTo;
44 : result := @Data.PLoanNotes;
45 : result := @Data.PTINotes;
46 : result := @Data.PCoMaker;
47 : result := @Data.PGuarantor;
48 : result := @Data.PGroupBy;
49 : result := @Data.PItemCollDesc;
50 : result := @Data.PItemOfficer;
51 : result := @Data.PItemBalance;
52 : result := @Data.PItemBranch;
53 : result := @Data.PItemDivision;
54 : result := @Data.PItemOpenDate;
55 : result := @Data.PItemMatDate;
56 : result := @Data.PItemAddress;
57 : result := @Data.PItemCategory;
58 : result := @Data.PItemPhone;
59 : result := @Data.PItemStatus;
60 : result := @Data.PItemDescription;
61 : result := @Data.PLeadTimeOfficer;
62 : result := @Data.PLeadTimeNotice;
63 : result := @Data.PLeadTimeYouPick;
64 : result := @Data.PLeadTime;
65 : result := @Data.PIncLoans;
66 : result := @Data.PIncActiveCifs;
67 : result := @Data.PIncInactiveCifs;
68 : result := @Data.PIncNotPaidOut;
69 : result := @Data.PIncPaidOut;
70 : result := @Data.PIncLoanWithNotes;
71 : result := @Data.PIncLoanWONotes;
72 : result := @Data.PIncWithTracked;
73 : result := @Data.PIncWOTracked;
74 : result := @Data.PIncWithNoticeItems;
75 : result := @Data.PIncWONoticeItems;
76 : result := @Data.PIncLoanNotes;
77 : result := @Data.PIncCifs;
78 : result := @Data.PELRecapOnly;
79 : result := @Data.PExpLoanCif;
80 : result := @Data.PExpLoanCifNotes;
81 : result := @Data.PExpTracked;
82 : result := @Data.PExpTrackedNotes;
83 : result := @Data.PExpTrackedExtend;
84 : result := @Data.PExpFormat;
85 : result := @Data.PExpOpt1;
86 : result := @Data.PExpOpt2;
87 : result := @Data.PExpOpt3;
88 : result := @Data.PItemEntryFrom;
89 : result := @Data.PItemEntryTo;
90 : result := @Data.PItemEntryBy;
91 : result := @Data.PShowTIUser;
92 : result := @Data.PShowTIEntryDate;
93 : result := @Data.PExcludeCats;
end;
end;
end.
|
{
Модуль компонента работы с набором записей файла с разделителем
Версия: 0.0.0.2
}
unit ICSdfDataset;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, sdfdata;
const
{ Расширение имени файла блокировки }
LOCK_FILENAME_EXT = '.lck';
type
{ Компонент работы с набором записей файла с разделителем }
TICSdfDataset = class(TSdfDataSet)
private
//{ Имя файла данных}
//FFileName: TFileName;
//
//{ Переопределенная процедура установки имени файла данных }
//procedure SetFileName(Value: TFileName); // override;
{
Функция определения блокировки файла данных
@return True - Файл данных заблокирован.
False - Файл данных НЕ заблокирован.
Файл данных считается заблокированным, если рядом с ним находится
файл с такми же именем, но с расширением *.lck.
}
function GetIsLocked(): Boolean;
protected
public
constructor Create(AOwner: TComponent); override;
{ Обновление набора записей из файла }
procedure UpdateDataset;
{
Функция ожидания разблокировки файла данных.
@param iTimeOut: Дополнительный таймаут (в секундах) для возможности продолжить
работу программы в случаях не снятия блокировки
@return True - Блокировка снята.
False - Сработал таймаут. Блокировка не снята.
}
function WaitUnLock(iTimeOut: Integer=1): Boolean;
{ Признак заблокированного файла данных. Свойство }
property IsLocked: Boolean read GetIsLocked;
published
//{ Переопределяем свойство для автоматического заполнения полей в режиме дизайнера }
//property FileName : TFileName read FFileName write SetFileName;
end;
procedure Register;
implementation
uses
logfunc;
procedure Register;
begin
{$I icsdfdataset_icon.lrs}
RegisterComponents('IC Tools',[TICSdfDataset]);
end;
constructor TICSdfDataset.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Delimiter := ';';
FirstLineAsSchema := True;
//MultiLine := True;
end;
{ Обновление набора записей из файла }
procedure TICSdfDataset.UpdateDataset;
var
wait_result: Boolean;
begin
wait_result := WaitUnLock();
// Если блокировка успешно снята, то можно произвести обновление
if wait_result then
begin
Close;
Open;
// Актуальной считается последняя запись. Поэтому переходм на нее
Last;
end;
end;
{ Функция определения блокировки файла данных }
function TICSdfDataset.GetIsLocked(): Boolean;
var
lck_filename: AnsiString;
begin
if FileName = '' then
begin
logfunc.WarningMsgFmt('Не определен файл данных в объекте <%s : %s>', [Name, ClassName]);
Result := False;
Exit;
end;
if not FileExists(FileName) then
begin
logfunc.WarningMsgFmt('Не найден файл данных объекта <%s : %s>', [Name, ClassName]);
Result := False;
Exit;
end;
lck_filename := ChangeFileExt(FileName, LOCK_FILENAME_EXT);
Result := FileExists(lck_filename);
end;
{ Функция ожидания разблокировки файла данных. }
function TICSdfDataset.WaitUnLock(iTimeOut: Integer): Boolean;
var
timeout: TDateTime;
begin
// Если файл данных не заблокирован, то просто выйти
if not IsLocked then
begin
Result := True;
Exit;
end;
timeout := Now + iTimeOut;
Result := True;
while IsLocked do
if Now >= timeout then
begin
Result := False;
Break;
end;
end;
//{ Переопределенная процедура установки имени файла данных }
//procedure TICSdfDataset.SetFileName(Value: TFileName);
//var
// txt_file: Text;
//begin
// if csDesigning in ComponentState then
// begin
// //... код, работающий только в дизайне ...
// if FileExists(Value) and FirstLineAsSchema then
// begin
// // Загрузить схему по первой линии файла
// Assign(txt_file, Value);
// //rewrite(f);
// ReadLn(txt_file, b, k1, k2);
// for j:=1 to 10 do
// begin
// writeln(a,j:4,j*2:4);
//
// (f,a,j:4,j*2:4);
// end;
//
// close(txt_file);
// end;
// end;
//
// // Блок из функции родительского класса
// CheckInactive;
// FFileName := Value;
//end;
end.
|
unit MFichas.Model.Usuario.TipoDeUsuario.Fiscal;
interface
uses
MFichas.Model.Usuario.Interfaces,
MFichas.Controller.Usuario.Operacoes.Interfaces,
MFichas.Controller.Types;
type
TModelUsuarioTipoDeUsuarioFiscal = class(TInterfacedObject, iModelUsuarioMetodos)
private
[weak]
FParent : iModelUsuario;
FNextResponsibility: iModelUsuarioMetodos;
FOperacoes : iControllerUsuarioOperacoes;
constructor Create(AParent: iModelUsuario);
procedure PedirSenha;
public
destructor Destroy; override;
class function New(AParent: iModelUsuario): iModelUsuarioMetodos;
function SetOperacoes(AOperacoes: iControllerUsuarioOperacoes): iModelUsuarioMetodos;
function NextReponsibility(AValue: iModelUsuarioMetodos): iModelUsuarioMetodos;
function LogoENomeDaFesta : iModelUsuarioMetodos;
function AbrirCaixa : iModelUsuarioMetodos;
function FecharCaixa : iModelUsuarioMetodos;
function Suprimento : iModelUsuarioMetodos;
function Sangria : iModelUsuarioMetodos;
function CadastrarProdutos : iModelUsuarioMetodos;
function CadastrarGrupos : iModelUsuarioMetodos;
function CadastrarUsuarios : iModelUsuarioMetodos;
function AcessarRelatorios : iModelUsuarioMetodos;
function AcessarConfiguracoes : iModelUsuarioMetodos;
function ExcluirProdutosPosImpressao: iModelUsuarioMetodos;
function &End : iModelUsuario;
end;
implementation
{ TModelUsuarioTipoDeUsuarioFiscal }
function TModelUsuarioTipoDeUsuarioFiscal.&End: iModelUsuario;
begin
Result := FParent;
end;
function TModelUsuarioTipoDeUsuarioFiscal.AbrirCaixa: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.AcessarConfiguracoes: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.AcessarRelatorios: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.CadastrarGrupos: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.CadastrarProdutos: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.CadastrarUsuarios: iModelUsuarioMetodos;
begin
Result := Self;
FNextResponsibility.CadastrarUsuarios;
end;
constructor TModelUsuarioTipoDeUsuarioFiscal.Create(AParent: iModelUsuario);
begin
FParent := AParent;
end;
destructor TModelUsuarioTipoDeUsuarioFiscal.Destroy;
begin
inherited;
end;
function TModelUsuarioTipoDeUsuarioFiscal.ExcluirProdutosPosImpressao: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.FecharCaixa: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.LogoENomeDaFesta: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
class function TModelUsuarioTipoDeUsuarioFiscal.New(AParent: iModelUsuario): iModelUsuarioMetodos;
begin
Result := Self.Create(AParent);
end;
function TModelUsuarioTipoDeUsuarioFiscal.NextReponsibility(
AValue: iModelUsuarioMetodos): iModelUsuarioMetodos;
begin
Result := Self;
FNextResponsibility := AValue;
end;
procedure TModelUsuarioTipoDeUsuarioFiscal.PedirSenha;
begin
FOperacoes
.PedirSenha
.SetTitle('Entre com a senha de FISCAL')
.SetTextConfirm('Confirmar')
.SetTextCancel('Cancelar')
.SetChamada(tuFiscal)
.&End;
end;
function TModelUsuarioTipoDeUsuarioFiscal.Sangria: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
function TModelUsuarioTipoDeUsuarioFiscal.SetOperacoes(
AOperacoes: iControllerUsuarioOperacoes): iModelUsuarioMetodos;
begin
Result := Self;
FOperacoes := AOperacoes;
end;
function TModelUsuarioTipoDeUsuarioFiscal.Suprimento: iModelUsuarioMetodos;
begin
Result := Self;
PedirSenha;
end;
end.
|
// **************************************************************************************************
//
// Unit uSettings
// unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler
//
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either express or implied. See the License for the specific language governing rights
// and limitations under the License.
//
// The Original Code is uSettings.pas.
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
// Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V.
// All Rights Reserved.
//
// *************************************************************************************************
unit uSettings;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, SynEditTypes, SynEdit;
const
sThemesExt = '.theme.xml';
sDefaultThemeName = 'mustang.theme.xml';
type
TSettings = class
private
FSyntaxHighlightTheme: string;
FFontSize: Integer;
FStyleName: string;
FFontName: string;
FSynSelectionMode: TSynSelectionMode;
class function GetPathThemes: string; static;
class function GetSettingsPath: string; static;
class function GetSettingsFileName: string; static;
public
constructor Create;
property SyntaxHighlightTheme: string read FSyntaxHighlightTheme write FSyntaxHighlightTheme;
property FontSize: Integer read FFontSize write FFontSize;
property FontName: string read FFontName write FFontName;
property StyleName: string read FStyleName write FStyleName;
property SelectionMode: TSynSelectionMode read FSynSelectionMode write FSynSelectionMode;
class property PathThemes: string read GetPathThemes;
class property SettingsFileName: string read GetSettingsFileName;
class property SettingsPath: string read GetSettingsPath;
class function GetThemeNameFromFile(const FileName: string): string;
procedure ReadSettings;
procedure WriteSettings;
end;
TFrmSettings = class(TForm)
Label1: TLabel;
CbFont: TComboBox;
EditFontSize: TEdit;
Label2: TLabel;
UpDown1: TUpDown;
CbVCLStyles: TComboBox;
Label3: TLabel;
CbSelectionMode: TComboBox;
Label4: TLabel;
ButtonSave: TButton;
cbSyntaxTheme: TComboBox;
Label5: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FSettings: TSettings;
FSettingsChanged: Boolean;
FOldStyle: string;
procedure FillData;
public
procedure LoadCurrentValues(SynEdit: TSynEdit; const ThemeName: string);
property SettingsChanged: Boolean read FSettingsChanged;
property Settings: TSettings read FSettings;
end;
implementation
{$R *.dfm}
uses
IniFiles,
System.Types,
System.TypInfo,
System.Rtti,
System.StrUtils,
System.IOUtils,
Winapi.ShlObj,
Vcl.Themes,
uMisc, uLogExcept;
function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; stdcall;
var
List: TStrings;
begin
List := TStrings(Data);
if ((LogFont.lfPitchAndFamily and FIXED_PITCH) <> 0) then
if not StartsText('@', LogFont.lfFaceName) and (List.IndexOf(LogFont.lfFaceName) < 0) then
List.Add(LogFont.lfFaceName);
Result := 1;
end;
{ TSettings }
constructor TSettings.Create;
begin
inherited;
ReadSettings;
end;
class function TSettings.GetPathThemes: string;
begin
Result := ExtractFilePath(GetModuleLocation()) + 'Themes\';
end;
class function TSettings.GetSettingsFileName: string;
begin
Result := IncludeTrailingPathDelimiter(GetSettingsPath) + 'Settings.ini';
end;
class function TSettings.GetSettingsPath: string;
begin
Result := IncludeTrailingPathDelimiter(GetSpecialFolder(CSIDL_APPDATA)) + 'DelphiPreviewHandler\';
System.SysUtils.ForceDirectories(Result);
end;
class function TSettings.GetThemeNameFromFile(const FileName: string): string;
begin
Result := Copy(ExtractFileName(FileName), 1, Pos('.theme', ExtractFileName(FileName)) - 1);
end;
procedure TSettings.ReadSettings;
var
Settings: TIniFile;
begin
try
TLogPreview.Add('ReadSettings '+SettingsFileName);
Settings := TIniFile.Create(SettingsFileName);
try
FSyntaxHighlightTheme := Settings.ReadString('Global', 'ThemeFile', sDefaultThemeName);
FFontSize := Settings.ReadInteger('Global', 'FontSize', 10);
FFontName := Settings.ReadString('Global', 'FontName', 'Consolas');
FStyleName := Settings.ReadString('Global', 'StyleName', 'Glow');
FSynSelectionMode := TSynSelectionMode(Settings.ReadInteger('Global', 'SelectionMode', Ord(smNormal)));
finally
Settings.Free;
end;
except
on E: Exception do
TLogPreview.Add(Format('Error in TSettings.ReadSettings - Message: %s: Trace %s', [E.Message, E.StackTrace]));
end;
end;
procedure TSettings.WriteSettings;
var
Settings: TIniFile;
begin
try
TLogPreview.Add('WriteSettings '+SettingsFileName);
Settings := TIniFile.Create(SettingsFileName);
try
Settings.WriteString('Global', 'ThemeFile', FSyntaxHighlightTheme);
Settings.WriteInteger('Global', 'FontSize', FFontSize);
Settings.WriteString('Global', 'FontName', FFontName);
Settings.WriteString('Global', 'StyleName', FStyleName);
Settings.WriteInteger('Global', 'SelectionMode', Ord(FSynSelectionMode));
finally
Settings.Free;
end;
except
on E: Exception do
TLogPreview.Add(Format('Error in TSettings.WriteSettings - Message: %s: Trace %s', [E.Message, E.StackTrace]));
end;
end;
procedure TFrmSettings.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TFrmSettings.ButtonSaveClick(Sender: TObject);
var
s: string;
begin
s:= Format('Do you want save the current settings? %s', ['']);
if not SameText(FOldStyle, CbVCLStyles.Text) then
s := s + sLineBreak + 'Note: Some settings will be aplied when the explorer is restarted';
if Application.MessageBox(PChar(s), 'Confirmation', MB_YESNO + MB_ICONQUESTION)= IDYES then
begin
FSettings.FontName := CbFont.Text;
FSettings.FontSize := UpDown1.Position;
FSettings.SyntaxHighlightTheme := cbSyntaxTheme.Text + sThemesExt;
FSettings.StyleName := CbVCLStyles.Text;
FSettings.SelectionMode := TSynSelectionMode(GetENumValue(TypeInfo(TSynSelectionMode), CbSelectionMode.Text));
FSettings.WriteSettings;
FSettingsChanged := True;
Close;
end;
end;
procedure TFrmSettings.FillData;
var
s, Theme: string;
sDC: Integer;
LogFont: TLogFont;
LSelectionMode: TSynSelectionMode;
begin
if not TDirectory.Exists(TSettings.PathThemes) then
exit;
for Theme in TDirectory.GetFiles(TSettings.PathThemes, '*.theme.xml') do
begin
s := TSettings.GetThemeNameFromFile(Theme);
cbSyntaxTheme.Items.Add(s);
end;
CbFont.Items.Clear;
sDC := GetDC(0);
try
ZeroMemory(@LogFont, sizeof(LogFont));
LogFont.lfCharset := DEFAULT_CHARSET;
EnumFontFamiliesEx(sDC, LogFont, @EnumFontsProc, Winapi.Windows.LPARAM(CbFont.Items), 0);
finally
ReleaseDC(0, sDC);
end;
for LSelectionMode := smNormal to smColumn do
CbSelectionMode.Items.Add(GetEnumName(TypeInfo(TSynSelectionMode), Ord(LSelectionMode)));
for s in TStyleManager.StyleNames do
CbVCLStyles.Items.Add(s);
end;
procedure TFrmSettings.FormCreate(Sender: TObject);
begin
FSettingsChanged := False;
FSettings := TSettings.Create;
FillData;
end;
procedure TFrmSettings.FormDestroy(Sender: TObject);
begin
FSettings.Free;
end;
procedure TFrmSettings.LoadCurrentValues(SynEdit: TSynEdit; const ThemeName: string);
begin
FOldStyle := TStyleManager.ActiveStyle.Name;
FSettings.SyntaxHighlightTheme := ThemeName;
FSettings.FontSize := SynEdit.Font.Size;
FSettings.FontName := SynEdit.Font.Name;
FSettings.SelectionMode := SynEdit.SelectionMode;
FSettings.StyleName := TStyleManager.ActiveStyle.Name;
CbFont.ItemIndex := CbFont.Items.IndexOf(FSettings.FontName);
UpDown1.Position := FSettings.FontSize;
cbSyntaxTheme.ItemIndex := cbSyntaxTheme.Items.IndexOf(TSettings.GetThemeNameFromFile(FSettings.SyntaxHighlightTheme));
CbVCLStyles.ItemIndex := CbVCLStyles.Items.IndexOf(FSettings.StyleName);
CbSelectionMode.ItemIndex := CbSelectionMode.Items.IndexOf(GetEnumName(TypeInfo(TSynSelectionMode), Ord(FSettings.SelectionMode)));
end;
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooFactory.ClassItem;
interface
uses
{$IFNDEF FPC AND (CompilerVersion > 21)}
RTTI,
{$ENDIF}
ooFactory.Item.Intf;
type
TFactoryItem<TClassType> = class(TInterfacedObject, IFactoryItem<TClassType>)
strict private
_ClassType: TClassType;
private
{$IFNDEF FPC AND (CompilerVersion > 21)}
function GetClassName: string;
{$ENDIF}
public
function Key: TFactoryKey;
function ClassType: TClassType;
constructor Create(const ClassType: TClassType);
class function New(const ClassType: TClassType): IFactoryItem<TClassType>;
end;
implementation
{$IFNDEF FPC AND (CompilerVersion > 21)}
function TFactoryItem<TClassType>.GetClassName: string;
begin
Result := TValue.From<TClassType>(_ClassType).AsClass.ClassName;
end;
{$ENDIF}
function TFactoryItem<TClassType>.ClassType: TClassType;
begin
Result := _ClassType;
end;
function TFactoryItem<TClassType>.Key: TFactoryKey;
begin
{$IFNDEF FPC AND (CompilerVersion > 21)}
Result := GetClassName;
{$ELSE}
Result := TClass(_ClassType).ClassName;
{$ENDIF}
end;
constructor TFactoryItem<TClassType>.Create(const ClassType: TClassType);
begin
_ClassType := ClassType;
end;
class function TFactoryItem<TClassType>.New(const ClassType: TClassType): IFactoryItem<TClassType>;
begin
Result := Create(ClassType);
end;
end.
|
{ Date Created: 5/25/00 5:01:02 PM }
unit InfoLOSSCODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoLOSSCODERecord = record
PCode: String[3];
PDescription: String[30];
PActive: Boolean;
End;
TInfoLOSSCODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoLOSSCODERecord
end;
TEIInfoLOSSCODE = (InfoLOSSCODEPrimaryKey);
TInfoLOSSCODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFActive: TBooleanField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPActive(const Value: Boolean);
function GetPActive:Boolean;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoLOSSCODE);
function GetEnumIndex: TEIInfoLOSSCODE;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoLOSSCODERecord;
procedure StoreDataBuffer(ABuffer:TInfoLOSSCODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFActive: TBooleanField read FDFActive;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PActive: Boolean read GetPActive write SetPActive;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoLOSSCODE read GetEnumIndex write SetEnumIndex;
end; { TInfoLOSSCODETable }
procedure Register;
implementation
function TInfoLOSSCODETable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoLOSSCODETable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoLOSSCODETable.GenerateNewFieldName }
function TInfoLOSSCODETable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoLOSSCODETable.CreateField }
procedure TInfoLOSSCODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFActive := CreateField( 'Active' ) as TBooleanField;
end; { TInfoLOSSCODETable.CreateFields }
procedure TInfoLOSSCODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLOSSCODETable.SetActive }
procedure TInfoLOSSCODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoLOSSCODETable.Validate }
procedure TInfoLOSSCODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoLOSSCODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoLOSSCODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoLOSSCODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoLOSSCODETable.SetPActive(const Value: Boolean);
begin
DFActive.Value := Value;
end;
function TInfoLOSSCODETable.GetPActive:Boolean;
begin
result := DFActive.Value;
end;
procedure TInfoLOSSCODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 3, N');
Add('Description, String, 30, N');
Add('Active, Boolean, 0, N');
end;
end;
procedure TInfoLOSSCODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoLOSSCODETable.SetEnumIndex(Value: TEIInfoLOSSCODE);
begin
case Value of
InfoLOSSCODEPrimaryKey : IndexName := '';
end;
end;
function TInfoLOSSCODETable.GetDataBuffer:TInfoLOSSCODERecord;
var buf: TInfoLOSSCODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PActive := DFActive.Value;
result := buf;
end;
procedure TInfoLOSSCODETable.StoreDataBuffer(ABuffer:TInfoLOSSCODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFActive.Value := ABuffer.PActive;
end;
function TInfoLOSSCODETable.GetEnumIndex: TEIInfoLOSSCODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoLOSSCODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoLOSSCODETable, TInfoLOSSCODEBuffer ] );
end; { Register }
function TInfoLOSSCODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PActive;
end;
end;
end. { InfoLOSSCODETable }
|
program controlWhile;
var x, y : integer;
begin
x := 0;
writeln('initial value of x:', x);
while x < 10 do
begin
x := x + 3;
writeln('value of x are x + 3 =', x);
end;
writeln('final value of x:', x);
end.
|
unit arabian_hw;
interface
uses nz80,main_engine,controls_engine,gfx_engine,rom_engine,ay_8910,
pal_engine,sound_engine,mb88xx;
function iniciar_arabian:boolean;
implementation
const
arabian_rom:array[0..3] of tipo_roms=(
(n:'ic1rev2.87';l:$2000;p:0;crc:$5e1c98b8),(n:'ic2rev2.88';l:$2000;p:$2000;crc:$092f587e),
(n:'ic3rev2.89';l:$2000;p:$4000;crc:$15145f23),(n:'ic4rev2.90';l:$2000;p:$6000;crc:$32b77b44));
arabian_gfx:array[0..3] of tipo_roms=(
(n:'tvg-91.ic84';l:$2000;p:0;crc:$c4637822),(n:'tvg-92.ic85';l:$2000;p:$2000;crc:$f7c6866d),
(n:'tvg-93.ic86';l:$2000;p:$4000;crc:$71acd48d),(n:'tvg-94.ic87';l:$2000;p:$6000;crc:$82160b9a));
arabian_mcu:tipo_roms=(n:'sun-8212.ic3';l:$800;p:0;crc:$8869611e);
//Dip
arabian_dip_a:array [0..5] of def_dip=(
(mask:$1;name:'Lives';number:2;dip:((dip_val:$0;dip_name:'3'),(dip_val:$1;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Cabinet';number:2;dip:((dip_val:$2;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Flip Screen';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Difficulty';number:2;dip:((dip_val:$8;dip_name:'Hard'),(dip_val:$0;dip_name:'Easy'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$f0;name:'Coinage';number:16;dip:((dip_val:$10;dip_name:'A 2/1 B 2/1'),(dip_val:$20;dip_name:'A 2/1 B 1/3'),(dip_val:$0;dip_name:'A 1/1 B 1/1'),(dip_val:$30;dip_name:'A 1/1 B 1/2'),(dip_val:$40;dip_name:'A 1/1 B 1/3'),(dip_val:$50;dip_name:'A 1/1 B 1/4'),(dip_val:$60;dip_name:'A 1/1 B 1/5'),(dip_val:$70;dip_name:'A 1/1 B 1/6'),(dip_val:$80;dip_name:'A 1/2 B 1/2'),(dip_val:$90;dip_name:'A 1/2 B 1/4'),(dip_val:$a0;dip_name:'A 1/2 B 1/5'),(dip_val:$e0;dip_name:'A 1/2 B 1/6'),(dip_val:$b0;dip_name:'A 1/2 B 1/10'),(dip_val:$c0;dip_name:'A 1/2 B 1/11'),(dip_val:$d0;dip_name:'A 1/2 B 1/12'),(dip_val:$f0;dip_name:'Free Play'))),());
arabian_dip_b:array [0..3] of def_dip=(
(mask:$1;name:'Coin Counters';number:2;dip:((dip_val:$1;dip_name:'1'),(dip_val:$0;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Demo Sounds';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$c;dip_name:'30k 70k 40+'),(dip_val:$4;dip_name:'20k Only'),(dip_val:$8;dip_name:'40k Only'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),());
var
blitter:array[0..7] of byte;
video_ram,converted_gfx:array[0..$ffff] of byte;
video_control,mcu_port_p,mcu_port_o:byte;
mcu_port_r:array[0..3] of byte;
procedure update_video_arabian;
var
x,y:byte;
punt:array[0..$ffff] of word;
begin
for x:=0 to 255 do
for y:=0 to 255 do
punt[y+((255-x)*256)]:=paleta[(video_ram[y*256+x]+(video_control shl 8))];
putpixel(0,0,$10000,@punt,1);
actualiza_trozo(11,0,234,256,1,0,0,234,256,PANT_TEMP);
end;
procedure eventos_arabian;
begin
if event.arcade then begin
//in1
if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7);
//in2
if arcade_input.but0[0] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fe);
//in3
if arcade_input.coin[0] then marcade.in3:=(marcade.in3 or $1) else marcade.in3:=(marcade.in3 and $fe);
if arcade_input.coin[1] then marcade.in3:=(marcade.in3 or $2) else marcade.in3:=(marcade.in3 and $fd);
//in0
if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb);
end;
end;
procedure arabian_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_s:=mb88xx_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 255 do begin
//Main
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//MCU
mb88xx_0.run(frame_s);
frame_s:=frame_s+mb88xx_0.tframes-mb88xx_0.contador;
if f=244 then begin
update_video_arabian;
z80_0.change_irq(HOLD_LINE);
end;
end;
eventos_arabian;
video_sync;
end;
end;
function arabian_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff:arabian_getbyte:=memoria[direccion];
$c000..$c1ff:arabian_getbyte:=marcade.in3;
$c200..$c3ff:arabian_getbyte:=marcade.dswa;
$d000..$dfff:arabian_getbyte:=memoria[$d000+(direccion and $7ff)];
end;
end;
procedure arabian_putbyte(direccion:word;valor:byte);
procedure video_ram_w(pos:word;valor:byte);
var
x,y:byte;
base:word;
begin
x:=(pos shr 8) shl 2;
y:=pos;
// get a pointer to the pixels
base:=y*256+x;
// enable writes to AZ/AR
if (blitter[0] and $08)<>0 then begin
video_ram[base+0]:=(video_ram[base+0] and $fc) or ((valor and $10) shr 3) or ((valor and $01) shr 0);
video_ram[base+1]:=(video_ram[base+1] and $fc) or ((valor and $20) shr 4) or ((valor and $02) shr 1);
video_ram[base+2]:=(video_ram[base+2] and $fc) or ((valor and $40) shr 5) or ((valor and $04) shr 2);
video_ram[base+3]:=(video_ram[base+3] and $fc) or ((valor and $80) shr 6) or ((valor and $08) shr 3);
end;
// enable writes to AG/AB
if (blitter[0] and $04)<>0 then begin
video_ram[base+0]:=(video_ram[base+0] and $f3) or ((valor and $10) shr 1) or ((valor and $01) shl 2);
video_ram[base+1]:=(video_ram[base+1] and $f3) or ((valor and $20) shr 2) or ((valor and $02) shl 1);
video_ram[base+2]:=(video_ram[base+2] and $f3) or ((valor and $40) shr 3) or ((valor and $04) shl 0);
video_ram[base+3]:=(video_ram[base+3] and $f3) or ((valor and $80) shr 4) or ((valor and $08) shr 1);
end;
// enable writes to BZ/BR
if (blitter[0] and $02)<>0 then begin
video_ram[base+0]:=(video_ram[base+0] and $cf) or ((valor and $10) shl 1) or ((valor and $01) shl 4);
video_ram[base+1]:=(video_ram[base+1] and $cf) or ((valor and $20) shl 0) or ((valor and $02) shl 3);
video_ram[base+2]:=(video_ram[base+2] and $cf) or ((valor and $40) shr 1) or ((valor and $04) shl 2);
video_ram[base+3]:=(video_ram[base+3] and $cf) or ((valor and $80) shr 2) or ((valor and $08) shl 1);
end;
// enable writes to BG/BB
if (blitter[0] and $01)<>0 then begin
video_ram[base+0]:=(video_ram[base+0] and $3f) or ((valor and $10) shl 3) or ((valor and $01) shl 6);
video_ram[base+1]:=(video_ram[base+1] and $3f) or ((valor and $20) shl 2) or ((valor and $02) shl 5);
video_ram[base+2]:=(video_ram[base+2] and $3f) or ((valor and $40) shl 1) or ((valor and $04) shl 4);
video_ram[base+3]:=(video_ram[base+3] and $3f) or ((valor and $80) shl 0) or ((valor and $08) shl 3);
end;
end;
procedure blit_area(plane:byte;src:word;x,y,sx,sy:byte);
var
srcdata,base:word;
i,j,p1,p2,p3,p4:byte;
begin
srcdata:=src*4;
// loop over X, then Y
for i:=0 to sx do begin
for j:=0 to sy do begin
p1:=converted_gfx[srcdata];
srcdata:=srcdata+1;
p2:=converted_gfx[srcdata];
srcdata:=srcdata+1;
p3:=converted_gfx[srcdata];
srcdata:=srcdata+1;
p4:=converted_gfx[srcdata];
srcdata:=srcdata+1;
// get a pointer to the bitmap
base:=((y+j) and $ff)*256+(x and $ff);
// bit 0 means write to upper plane (upper 4 bits of our bitmap)
if (plane and $01)<>0 then begin
if (p4<>8) then video_ram[base+0]:=(video_ram[base+0] and $0f) or (p4 shl 4);
if (p3<>8) then video_ram[base+1]:=(video_ram[base+1] and $0f) or (p3 shl 4);
if (p2<>8) then video_ram[base+2]:=(video_ram[base+2] and $0f) or (p2 shl 4);
if (p1<>8) then video_ram[base+3]:=(video_ram[base+3] and $0f) or (p1 shl 4);
end;
// bit 2 means write to lower plane (lower 4 bits of our bitmap)
if (plane and $04)<>0 then begin
if (p4<>8) then video_ram[base+0]:=(video_ram[base+0] and $f0) or p4;
if (p3<>8) then video_ram[base+1]:=(video_ram[base+1] and $f0) or p3;
if (p2<>8) then video_ram[base+2]:=(video_ram[base+2] and $f0) or p2;
if (p1<>8) then video_ram[base+3]:=(video_ram[base+3] and $f0) or p1;
end;
end; //for j
x:=x+4;
end; //for i
end;
begin
case direccion of
0..$7fff:; //ROM
$8000..$bfff:video_ram_w(direccion,valor); //pant
$d000..$dfff:memoria[$d000+(direccion and $7ff)]:=valor;
$e000..$efff:begin //blitter
blitter[direccion and $7]:=valor;
if (direccion and $7)=6 then blit_area(blitter[0],blitter[1] or (blitter[2] shl 8),blitter[4] shl 2,blitter[3],blitter[6],blitter[5]);
end;
end;
end;
procedure arabian_outbyte(puerto:word;valor:byte);
begin
case puerto of
$c800..$c9ff:ay8910_0.control(valor);
$ca00..$cbff:ay8910_0.write(valor);
end;
end;
procedure arabian_portaw(valor:byte);
begin
video_control:=valor shr 3;
end;
procedure arabian_portbw(valor:byte);
begin
//reset mcu + irq mcu
if (valor and $20)=0 then mb88xx_0.set_irq_line(ASSERT_LINE)
else mb88xx_0.set_irq_line(CLEAR_LINE);
if (valor and $10)<>0 then mb88xx_0.change_reset(CLEAR_LINE)
else mb88xx_0.change_reset(ASSERT_LINE);
end;
procedure arabian_sound_update;
begin
ay8910_0.update;
end;
//MCU
function mcu_port_r_r(port:byte):byte;
var
val:byte;
begin
val:=mcu_port_r[port];
// RAM mode is enabled
if (port=0) then val:=val or 4;
mcu_port_r_r:=val;
end;
procedure mcu_port_r_w(port,valor:byte);
var
ram_addr:word;
begin
if (port=0) then begin
ram_addr:=((mcu_port_p and 7) shl 8) or mcu_port_o;
if (not(valor) and 2)<>0 then memoria[$d000+ram_addr]:=$f0 or mcu_port_r[3];
main_screen.flip_main_screen:=(valor and 8)<>0;
end;
mcu_port_r[port]:=valor and $0f;
end;
function mcu_port_k_r:byte;
var
val,sel,i:byte;
ram_addr:word;
begin
val:=$f;
if (not(mcu_port_r[0]) and 1)<>0 then begin
ram_addr:=((mcu_port_p and 7) shl 8) or mcu_port_o;
val:=memoria[$d000+ram_addr];
end else begin
sel:=((mcu_port_r[2] shl 4) or mcu_port_r[1]) and $3f;
for i:=0 to 5 do begin
if (not(sel) and (1 shl i))<>0 then begin
case i of
0:val:=marcade.in0;
1:val:=marcade.in1;
2:val:=marcade.in2;
3:val:=0; //Cocktail
4:val:=0; //Cocktail
5:val:=marcade.dswb;
end;
break;
end;
end;
end;
mcu_port_k_r:=val and $f;
end;
procedure mcu_port_o_w(valor:byte);
var
res:byte;
begin
res:=valor and $0f;
if (valor and $10)<>0 then mcu_port_o:=(mcu_port_o and $0f) or (res shl 4)
else mcu_port_o:=(mcu_port_o and $f0) or res;
end;
procedure mcu_port_p_w(valor:byte);
begin
mcu_port_p:=valor and $0f;
end;
//Main
procedure reset_arabian;
begin
z80_0.reset;
mb88xx_0.reset;
ay8910_0.reset;
reset_audio;
video_control:=0;
mcu_port_p:=0;
mcu_port_o:=0;
mcu_port_r[0]:=0;
mcu_port_r[1]:=0;
mcu_port_r[2]:=0;
mcu_port_r[3]:=0;
marcade.in0:=1;
marcade.in1:=0;
marcade.in2:=0;
marcade.in3:=0;
end;
procedure create_palette;
var
colores:tpaleta;
i:word;
planea,enb:boolean;
ena,abhf,aghf,arhf,az,ar,ag,ab,bz,br,bg,bb:byte;
rhi,rlo,ghi,glo,bhi,bbase:byte;
begin
for i:=0 to $1fff do begin
ena:=(i shr 12 )and 1;
enb:=(i and $200)<>0;
abhf:=((i shr 10) and 1) xor 1;
aghf:=((i shr 9) and 1) xor 1;
arhf:=((i shr 8) and 1) xor 1;
az:=(i shr 7) and 1;
ar:=(i shr 6) and 1;
ag:=(i shr 5) and 1;
ab:=(i shr 4) and 1;
bz:=(i shr 3) and 1;
br:=(i shr 2) and 1;
bg:=(i shr 1) and 1;
bb:=(i shr 0) and 1;
planea:=((az or ar or ag or ab) and ena)<>0;
if planea then begin
//Red derivation
rhi:=ar;
if ((arhf xor 1) and az)<>0 then rlo:=0
else rlo:=ar;
//Green Derivation
ghi:=ag;
if ((aghf xor 1) and az)<>0 then glo:=0
else glo:=ag;
end else begin
//Red derivation
rhi:=bz*byte(enb);
rlo:=br*byte(enb);
//Green Derivation
ghi:=bb*byte(enb);
glo:=bg*byte(enb);
end;
//Blue derivation
bhi:=ab;
if ((abhf xor 1) and az)<>0 then bbase:=0
else bbase:=ab;
//Paleta
if (rhi or rlo)<>0 then colores[i].r:=round((rhi*115.7)+(rlo*77.3)+62)
else colores[i].r:=round((rhi*115.7)+(rlo*77.3));
if (ghi or glo)<>0 then colores[i].g:=round((ghi*117.9588)+(glo*75.0411)+62)
else colores[i].g:=round((ghi*117.9588)+(glo*75.0411));
colores[i].b:=(bhi*192)+(bbase*63);
end;
set_pal(colores,$2000);
end;
function iniciar_arabian:boolean;
var
memoria_temp:array[0..$ffff] of byte;
procedure convert_gfx_arabian;
var
f:word;
v1,v2:byte;
begin
for f:=0 to $3fff do begin
v1:=memoria_temp[f];
v2:=memoria_temp[f+$4000];
converted_gfx[f*4+3]:=(v1 and $01) or ((v1 and $10) shr 3) or ((v2 and $01) shl 2) or ((v2 and $10) shr 1);
v1:=v1 shr 1;
v2:=v2 shr 1;
converted_gfx[f*4+2]:=(v1 and $01) or ((v1 and $10) shr 3) or ((v2 and $01) shl 2) or ((v2 and $10) shr 1);
v1:=v1 shr 1;
v2:=v2 shr 1;
converted_gfx[f*4+1]:=(v1 and $01) or ((v1 and $10) shr 3) or ((v2 and $01) shl 2) or ((v2 and $10) shr 1);
v1:=v1 shr 1;
v2:=v2 shr 1;
converted_gfx[f*4+0]:=(v1 and $01) or ((v1 and $10) shr 3) or ((v2 and $01) shl 2) or ((v2 and $10) shr 1);
end;
end;
begin
llamadas_maquina.bucle_general:=arabian_principal;
llamadas_maquina.reset:=reset_arabian;
iniciar_arabian:=false;
iniciar_audio(false);
screen_init(1,256,256);
iniciar_video(234,256);
//Main CPU
z80_0:=cpu_z80.create(3000000,256);
z80_0.change_ram_calls(arabian_getbyte,arabian_putbyte);
z80_0.change_io_calls(nil,arabian_outbyte);
z80_0.init_sound(arabian_sound_update);
//MCU
mb88xx_0:=cpu_mb88xx.Create(2000000,256);
mb88xx_0.change_io_calls(mcu_port_k_r,mcu_port_o_w,nil,mcu_port_p_w,mcu_port_r_r,mcu_port_r_w);
//Audio chips
ay8910_0:=ay8910_chip.create(1500000,AY8910,0.5);
ay8910_0.change_io_calls(nil,nil,arabian_portaw,arabian_portbw);
//cargar roms
if not(roms_load(@memoria,arabian_rom)) then exit;
//Cargar MCU
if not(roms_load(mb88xx_0.get_rom_addr,arabian_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,arabian_gfx)) then exit;
convert_gfx_arabian;
create_palette;
marcade.dswa:=$06;
marcade.dswb:=$0f;
marcade.dswa_val:=@arabian_dip_a;
marcade.dswb_val:=@arabian_dip_b;
//final
reset_arabian;
iniciar_arabian:=true;
end;
end.
|
unit GX_FavFileProp;
interface
uses
Classes, Controls, Forms, ExtCtrls, StdCtrls, ComCtrls, GX_BaseForm;
type
TfmFavFileProp = class(TfmBaseForm)
pgeProperties: TPageControl;
tabProperties: TTabSheet;
lblFile: TLabel;
lblName: TLabel;
lblDescription: TLabel;
btnCancel: TButton;
btnOK: TButton;
edtName: TEdit;
edtDescription: TEdit;
imgFileIcon: TImage;
lblIcon: TLabel;
lblExecuteType: TLabel;
cbxExecuteType: TComboBox;
edtFilename: TEdit;
sbnFile: TButton;
lblExecuteUsing: TLabel;
edtExecuteUsing: TEdit;
sbnExecute: TButton;
procedure sbnFileClick(Sender: TObject);
procedure edtFilenameExit(Sender: TObject);
procedure sbnExecuteClick(Sender: TObject);
procedure cbxExecuteTypeClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FFavoriteFilesForm: TForm;
public
property FavoriteFilesForm: TForm write FFavoriteFilesForm;
end;
implementation
{$R *.dfm}
uses
SysUtils, Graphics, Dialogs, GX_FavFiles, GX_FavUtil;
procedure TfmFavFileProp.sbnFileClick(Sender: TObject);
var
TheForm: TfmFavFiles;
FileName: string;
begin
TheForm := (FFavoriteFilesForm as TfmFavFiles);
TheForm.SetFilter;
FileName := TheForm.MakeFileNameAbsolute(edtFileName.Text);
if FileExists(FileName) then
begin
TheForm.dlgGetFiles.FileName := ExtractFileName(FileName);
TheForm.dlgGetFiles.InitialDir := ExtractFilePath(FileName);
end
else
TheForm.dlgGetFiles.FileName := '';
if TheForm.dlgGetFiles.Execute then
begin
edtFilename.Text := TheForm.MakeFileNameRelative(TheForm.dlgGetFiles.FileName);
TheForm.AssignIconImage(imgFileIcon, TheForm.dlgGetFiles.FileName);
end;
end;
procedure TfmFavFileProp.edtFilenameExit(Sender: TObject);
var
TheForm: TfmFavFiles;
begin
TheForm := (FFavoriteFilesForm as TfmFavFiles);
TheForm.AssignIconImage(imgFileIcon, TheForm.MakeFileNameAbsolute(edtFileName.Text));
end;
procedure TfmFavFileProp.sbnExecuteClick(Sender: TObject);
var
TheForm: TfmFavFiles;
begin
TheForm := FFavoriteFilesForm as TfmFavFiles;
TheForm.dlgGetFiles.FilterIndex := 7;
if FileExists(edtExecuteUsing.Text) then
TheForm.dlgGetFiles.FileName := edtExecuteUsing.Text;
if TheForm.dlgGetFiles.Execute then
edtExecuteUsing.Text := TheForm.dlgGetFiles.FileName;
end;
procedure TfmFavFileProp.cbxExecuteTypeClick(Sender: TObject);
var
ItemEnabled: Boolean;
begin
ItemEnabled := (cbxExecuteType.ItemIndex = 2);
sbnExecute.Enabled := ItemEnabled;
edtExecuteUsing.Enabled := ItemEnabled;
if ItemEnabled then
edtExecuteUsing.Color := clWindow
else
edtExecuteUsing.Color := clBtnFace;
end;
procedure TfmFavFileProp.FormActivate(Sender: TObject);
begin
cbxExecuteTypeClick(cbxExecuteType);
end;
procedure TfmFavFileProp.FormCreate(Sender: TObject);
var
ExecType: TExecType;
begin
cbxExecuteType.Items.Clear;
for ExecType := Low(TExecType) to High(TExecType) do
cbxExecuteType.Items.AddObject(ExecTypeNames[ExecType], TObject(Ord(ExecType)));
end;
end.
|
unit uGameUtils;
interface
uses Generics.Collections, FMX.Objects3D, FMX.Types3d, System.Math.Vectors, System.UITypes, FMX.Controls3D,
System.SysUtils, System.Math, FMX.Ani, system.classes;
type
TSceneJeu = (intro, menu, jeu, options, gameover, victoire, aide, highScores);
TEnnemi = class(TDummy)
private
fCorps, fBrasG, fBrasD, fJambeG, fJambeD : TCube;
fTete : TSphere;
fAniJambeD, fAniJambeG : TFloatAnimation;
fPointDeVie : integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure demarrerAnimationJambes;
procedure arreterAnimationJambes;
property Corps : TCube read fCorps write fCorps;
property BrasGauche : TCube read fBrasG write fBrasG;
property BrasDroit : TCube read fBrasD write fBrasD;
property JambeGauche : TCube read fJambeG write fJambeG;
property JambeDroite : TCube read fJambeD write fJambeD;
property Tete : TSphere read fTete write fTete;
property PointDeVie : integer read fPointDeVie write fPointDeVie;
end;
TBonus = record
boite : TCube;
tag : integer;
end;
TTir = record
porteeTir, vitesseTir : single;
balle : TSphere;
light: TLight;
direction, positionDepart : TPoint3D;
end;
function KeyRandom(const aLen: integer): string;
const
tailleJoueur = 1.5;
accelerationTouche = 0.1;
maxAccelerationTouche = 2;
vitesseMax = 0.4;
maxBalles = 10;
vitesseTir = 1.7;
porteeTir = 130;
maxEnnemis = 10;
MaxArbres = 100;
distanceAffichageHerbe = 40;
maxVie = 100;
tailleEnnemi = 3;
maxEnnemiPointDeVie = 3;
nbBonusMunition = 7;
taileBonus = 2;
nbBonusPointDeVie = 4;
dureeJeu = 5;
musique = 'tgfcoder-FrozenJam-SeamlessLoop.mp3';
ambianceCricket = 'cricketsounds090613.mp3';
ambianceMer = 'vagues.mp3';
collisionArbre = 'zap1.mp3';
sonTir = 'laser5.mp3';
sonChargeurVide = 'Blip.mp3';
sonEnnemiTouche = 'phaserUp4.mp3';
sonEnnemiMort = 'spaceTrash1.mp3';
sonBonusEnergie = 'lowRandom.mp3';
sonBonusMunition = 'powerUp7.mp3';
sonBonusCode = 'powerUp8.mp3';
var
maxHerbe : integer;
implementation
function KeyRandom(const aLen: integer): string;
begin
result := EmptyStr;
if aLen < 1 then
Exit;
repeat
result := result + Chr(RandomRange(Ord('A'), Ord('Z') + 1));
until Length(result) = aLen;
end;
{ TEnnemi }
constructor TEnnemi.Create(AOwner: TComponent);
begin
inherited;
Depth := 0.5;
Height := 3;
Width := 1.5;
HitTest := false;
fCorps := TCube.Create(nil);
fCorps.Parent := self;
fCorps.Depth := 0.5;
fCorps.Height := 1;
fCorps.width := 1;
fCorps.HitTest := false;
fBrasD := TCube.Create(nil);
fBrasD.Parent := fCorps;
fBrasD.depth := 0.25;
fBrasD.Height := 1;
fBrasD.width := 0.25;
fBrasD.position.X := 0.5;
fBrasD.position.Y := -0.35;
fBrasD.position.Z := 0.5;
fBrasD.RotationAngle.X := 90;
fBrasD.HitTest := false;
fBrasG := TCube.Create(nil);
fBrasG.Parent := fCorps;
fBrasG.depth := 0.25;
fBrasG.Height := 1;
fBrasG.width := 0.25;
fBrasG.position.X := -0.5;
fBrasG.position.Y := -0.35;
fBrasG.position.Z := 0.5;
fBrasG.RotationAngle.X := 90;
fBrasG.HitTest := false;
fJambeD := TCube.Create(nil);
fJambeD.Parent := fCorps;
fJambeD.depth := 0.35;
fJambeD.Height := 1;
fJambeD.width := 0.35;
fJambeD.position.X := 0.35;
fJambeD.position.Y := 1;
fJambeD.position.Z := 0;
fJambeD.HitTest := false;
fJambeD.RotationCenter.Y := -1;
fAniJambeD := TFloatAnimation.Create(nil);
fAniJambeD.Parent := fJambeD;
fAniJambeD.AutoReverse := true;
fAniJambeD.Duration := 0.5;
fAniJambeD.Loop := true;
fAniJambeD.PropertyName := 'RotationAngle.X';
fAniJambeD.StartValue := -15;
fAniJambeD.StopValue := 15;
fJambeG := TCube.Create(nil);
fJambeG.Parent := fCorps;
fJambeG.depth := 0.35;
fJambeG.Height := 1;
fJambeG.width := 0.35;
fJambeG.position.X := -0.35;
fJambeG.position.Y := 1;
fJambeG.position.Z := 0;
fJambeG.HitTest := false;
fJambeG.RotationCenter.Y := -1;
fAniJambeG := TFloatAnimation.Create(nil);
fAniJambeG.Parent := fJambeG;
fAniJambeG.AutoReverse := true;
fAniJambeG.Duration := 0.5;
fAniJambeG.Loop := true;
fAniJambeG.Inverse := true;
fAniJambeG.PropertyName := 'RotationAngle.X';
fAniJambeG.StartValue := -15;
fAniJambeG.StopValue := 15;
fTete := TSphere.Create(nil);
fTete.Parent :=fCorps;
fTete.depth := 1;
fTete.height := 1;
fTete.width := 1;
fTete.position.Y := -1;
fTete.rotationAngle.Y := 90;
fTete.HitTest := false;
fPointDeVie := 0;
end;
procedure TEnnemi.demarrerAnimationJambes;
begin
fAniJambeD.Start;
fAniJambeG.Start;
end;
procedure TEnnemi.arreterAnimationJambes;
begin
fAniJambeD.Stop;
fAniJambeG.Stop;
end;
destructor TEnnemi.Destroy;
begin
fAniJambeD.Stop;
fAniJambeG.Stop;
inherited;
end;
end.
|
unit k2OpMisc;
{* Утилитные методы для работы с пачками операций }
// Модуль: "w:\common\components\rtl\Garant\K2\k2OpMisc.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "k2OpMisc" MUID: (48CF8F160109)
{$Include w:\common\components\rtl\Garant\K2\k2Define.inc}
interface
uses
l3IntfUses
, l3Variant
;
function k2StartOp(const aProcessorSource: IUnknown;
anOpCode: Integer = 0): Il3OpPack; overload;
{* открывает пачку операций. aProcessorSource может поддерживать Il3Processor }
function k2StartOp(const aProcessor: Ik2Processor;
anOpCode: Integer = 0): Il3OpPack; overload;
{* открывает пачку операций. aProcessorSource может поддерживать Il3Processor }
function k2Proc(const anOp: Il3OpPack): Ik2Processor;
{* возвращает процессор операций в контексте которого выполняется данная пачка или nil - если пачка = nil }
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *48CF8F160109impl_uses*
//#UC END# *48CF8F160109impl_uses*
;
function k2StartOp(const aProcessorSource: IUnknown;
anOpCode: Integer = 0): Il3OpPack;
{* открывает пачку операций. aProcessorSource может поддерживать Il3Processor }
//#UC START# *48CF8F3C02C9_48CF8F160109_var*
var
l_Processor : Ik2Processor;
//#UC END# *48CF8F3C02C9_48CF8F160109_var*
begin
//#UC START# *48CF8F3C02C9_48CF8F160109_impl*
if Supports(aProcessorSource, Ik2Processor, l_Processor) then
try
Result := l_Processor.StartOp(anOpCode);
finally
l_Processor := nil;
end
else
Result := nil;
//#UC END# *48CF8F3C02C9_48CF8F160109_impl*
end;//k2StartOp
function k2StartOp(const aProcessor: Ik2Processor;
anOpCode: Integer = 0): Il3OpPack;
{* открывает пачку операций. aProcessorSource может поддерживать Il3Processor }
//#UC START# *48CF8F6103E5_48CF8F160109_var*
//#UC END# *48CF8F6103E5_48CF8F160109_var*
begin
//#UC START# *48CF8F6103E5_48CF8F160109_impl*
if (aProcessor = nil) then
Result := nil
else
Result := aProcessor.StartOp(anOpCode);
//#UC END# *48CF8F6103E5_48CF8F160109_impl*
end;//k2StartOp
function k2Proc(const anOp: Il3OpPack): Ik2Processor;
{* возвращает процессор операций в контексте которого выполняется данная пачка или nil - если пачка = nil }
//#UC START# *48CF8F8B0388_48CF8F160109_var*
//#UC END# *48CF8F8B0388_48CF8F160109_var*
begin
//#UC START# *48CF8F8B0388_48CF8F160109_impl*
if (anOp = nil) then
Result := nil
else
Result := anOp.Processor;
//#UC END# *48CF8F8B0388_48CF8F160109_impl*
end;//k2Proc
end.
|
unit Client1C;
interface
uses XSuperObject, System.SysUtils, System.DateUtils, GlobalTypes, IBX.IBDatabase, Data.DB, IBX.IBCustomDataSet,
IBX.IBEvents, IBX.IBQuery, Variants, IdGlobal, ProtocolCommon, EventUnit;
type TFriServer = class(TObject)
DevID : integer;
DevClass : byte;
DevUID : string;
Name : string;
Host : string;
UdpPort : word; // для устройств
DB_TYPE : byte;
DB_HOST : string;
DB_PORT : word;
DB_BASE : string;
DB_USER : string;
DB_PASS : string;
ClientJSON : ISuperArray;
LastConTime : TDateTime;
OnWork : boolean;
SrvEvent : TAEvent;
NeedReload : boolean;
function BufferIO(JSON: ISuperObject): ISuperArray;
function OnPing(JSON: ISuperObject): string;
function OnDisconnect: string;
function OnSetData: string;
function GetResponse: string;
procedure AddErrorPacket(ErrText: string);
procedure OnEvent(Item: ISuperObject);
procedure GenEvent(DevID: integer; DevClass: byte; CodeID: integer; AddInfo: string = ''; CustID: integer = -1);
constructor Create;
end;
type TClient1C = class(TObject)
private
public
User : TUser1С;
DevID : integer;
DevClass : byte;
DevUID : string;
Name : string;
ClientJSON : ISuperArray;
LastConTime : TDateTime;
OnWork : boolean;
// ClientBuffer : ISuperArray;
// Commands : ISuperArray;
// ClientData : ISuperArray;
// UserBuffer : ISuperArray;
// UserCommands : ISuperArray;
// procedure SetPacket(MesType: byte; AddInfo: string = ''; AddID: integer = -1);
// procedure SetDataPacket(Data: ISuperArray);
// procedure SetHistoryPacket(Data: ISuperArray);
// procedure OnConnect;
// procedure OnDisConnect;
// procedure IncSessionID;
constructor Create; // inherited;
procedure DropClient;
procedure AddErrorPacket(ErrText: string);
function BufferIO(JSON: ISuperObject): ISuperArray;
function OnDisconnect: string;
// function CommandsIO(JSON: ISuperObject): ISuperArray;
// function UserBufferIO(JSON: ISuperObject): ISuperArray;
// function UserCommandsIO(JSON: ISuperObject): ISuperArray;
procedure OnHello(AUid: string);
// function OnGetResetCmd: string;
function OnGetCommand(JSON: ISuperObject): string;
function HistoryPacket(DevID: integer; DevClass: byte; CustID: integer = -1): ISuperArray;
function GetResponse: string;
function GetCommandPacket(CmdID: Integer): TIdBytes;
function PacketOfAlarms(ZonesOnly: boolean = False): ISuperArray;
function PacketOfDevStates: ISuperArray;
end;
var Clients: array of TClient1C;
Servers : array of TFriServer;
procedure AddToClientBuffers(JSON: ISuperObject);
implementation
uses Constants, Service, DataUnit, ProtocolLib, ProtocolKOP, UDPClient, HttpServer, FirebirdTools;
procedure AddToClientBuffers(JSON: ISuperObject);
var i: integer;
begin
for i := 0 to High(Clients) do
begin
if (Clients[i].OnWork = False) and (Clients[i].DevClass <> Byte(DevClassARM_DPCO)) then
Continue;
Clients[i].BufferIO(JSON);
end;
end;
function SetResponseText(MesType: string; MesText: string): string;
var JSON: ISuperObject;
begin
JSON := SO();
JSON.S[KEY_MES_TYPE] := MesType;
JSON.S[KEY_MES_TEXT] := MesText;
Result := JSON.AsJSON;
end;
constructor TClient1C.Create;
begin
inherited;
ClientJSON := SA();
User := nil;
DevUID := INVALID_UID;
DevID := InvalidID;
DevClass := 0;
LastConTime := IncYear(Now, 20);
Name := 'АРМ дежурного ПЦО';
OnWork := False;
end;
procedure TClient1C.AddErrorPacket(ErrText: string);
var JSON: ISuperObject;
begin
JSON :=SO();
JSON.S[KEY_MES_TYPE] := MESSAGE_ERROR;
JSON.S[KEY_MES_TEXT] := ErrText;
BufferIO(JSON);
end;
procedure TClient1C.DropClient;
begin
ClientJSON := SA();
OnWork := False;
LastConTime := IncYear(Now, 20);
if DevClass = Byte(DevClassARM_DPCO) then
begin
User := nil;
DevUID := INVALID_UID;
DevID := InvalidID;
DevClass := Byte(DevClassARM_DPCO);
end;
end;
function TClient1C.BufferIO(JSON: ISuperObject): ISuperArray;
begin
Result := nil;
if JSON = nil then
begin
Result := ClientJSON.Clone;
ClientJSON.Clear;
Exit;
end;
ClientJSON.Add(JSON);
end;
procedure TClient1C.OnHello(AUid: string);
var RespJSON: ISuperObject;
AddInfo: string;
CodeID: integer;
begin
RespJSON := SO();
RespJSON.S[KEY_MES_TYPE] := MESSAGE_ACCEPT;
RespJSON.B['query_data'] := False;
RespJSON.A['alarms'] := PacketOfAlarms;
RespJSON.A['states'] := PacketOfDevStates;
BufferIO(RespJSON);
CodeID := Byte(EventTypeConnectPC);
AddInfo := Name;
MCore.GenerateEvent(DevID, DevClass, CodeID, AddInfo);
end;
function TClient1C.OnDisconnect: string;
var AddInfo: string; CodeID: integer;
begin
LogOut('Клиент ' + Name + '. Завершил работу, отправив сообщение "GOODBYE"');
CodeID := Byte(EventTypeDisConnectPC);
MCore.GenerateEvent(DevID, DevClass, CodeID, AddInfo);
end;
function TClient1C.OnGetCommand(JSON: ISuperObject): string;
var RespJSON: ISuperObject; CmdDevID, CmdDevClass, CmdCustID, XoID, CodeID, CmdID: integer;
AlarmType: byte;
i: integer;
Controls, Zones, ZoneNums: ISuperArray;
Server: TFriServer;
Item: ISuperObject;
Ppk : TPpk; Zone: TZone;
AddInfo: string;
ZoneBuf: array of TZone;
IdBytes: TIdBytes;
begin
RespJSON := SO();
RespJSON.S[KEY_MES_TYPE] := MESSAGE_CONFIRM;
Result := RespJSON.AsJSON;
LogOut(JSON.AsJSON());
CmdDevID := JSON.I['cmd_dev_id'];
CmdDevClass := JSON.I['cmd_dev_class'];
CmdCustID := JSON.I['cmd_cust_id'];
CmdID := JSON.I['cmd_id'];
XoID := JSON.I['cmd_xo_id'];
CodeID := JSON.I['cmd_code_id'];
AlarmType := JSON.I['cmd_alarm_type'];
Controls := JSON.A['cmd_controls']; //"cmd_pult_id", "cmd_pult_type", "cmd_pult_class",
Zones := JSON.A['cmd_zones'];
LogOut('CmdID = ' + IntToStr(CmdID) + '' + '') ;
AddInfo := '';
ZoneNums := SA();
if Zones.Length > 0 then
begin
SetLength(ZoneBuf, Zones.Length);
for i := 0 to High(ZoneBuf) do
begin
ZoneBuf[i] := HttpLink.HttpData.ZoneUO(Zones.I[i], nil, AGet);
if ZoneBuf[i] <> nil then ZoneNums.Add(ZoneBuf[i].NUM);
end;
AddInfo := 'Зоны - ' + ZoneNums.AsJSON();
end;
if ((CmdID = Byte(EventTypeCmdArmGroup)) or (CmdID = Byte(EventTypeCmdDisArmGroup))) then
begin
if Zones.Length = 1 then
begin
if CmdID = Byte(EventTypeCmdArmGroup) then
i := Byte(EventTypeCmdArm)
else if CmdID = Byte(EventTypeCmdDisArmGroup) then
i := Byte(EventTypeCmdDisArm);
MCore.GenerateEvent(CmdDevID, CmdDevClass, i, AddInfo, XoID); // отражение команды событием
end
else
MCore.GenerateEvent(CmdDevID, CmdDevClass, CmdID, AddInfo, XoID); // отражение команды событием
end;
if (CmdID = Byte(EventTypeCmdQueryHistory)) or (CmdID = Byte(EventTypeCmdQueryHistoryObject)) then
begin
RespJSON := SO();
RespJSON.S[KEY_MES_TYPE] := MESSAGE_HISTORY;
RespJSON.I[KEY_DEV_ID] := CmdDevID;
RespJSON.I[KEY_DEV_CLASS] := CmdDevClass;
if CmdID = Byte(EventTypeCmdQueryHistory) then
CmdCustID := InvalidID;
RespJSON.A['records'] := HistoryPacket(CmdDevID, CmdDevClass, CmdCustID);
BufferIO(RespJSON);
end;
if CmdID = Byte(EventTypeCmdAlarmDrop) then
begin
CodeID := JSON.I['cmd_code_id'];
MCore.GenerateEvent(CmdDevID, CmdDevClass, CodeID, '', InvalidID);
Exit;
end;
// у устройства не обратной связи, делаем виртуальное взятие/снятие
if ((CmdID = Byte(EventTypeCmdArmGroup)) or (CmdID = Byte(EventTypeCmdDisArmGroup))) and (Controls.Length = 0) then
begin
if CmdID = Byte(EventTypeCmdArmGroup) then
CodeID := Byte(EventTypeArmedByDuty);
if CmdID = Byte(EventTypeCmdDisArmGroup) then
CodeID := Byte(EventTypeDisArmedByDuty);
for i := 0 to High(ZoneBuf) do
begin
MCore.GenerateEvent(Zones.I[i], Byte(DevClassZone), CodeID, '', InvalidID);
end;
Exit;
end;
//распределяем команды по контроллерам
// for i := 0 to Controls.Length - 1 do
// begin
// Item := Controls.O[i];
// Server := GetServer(Item.S['cmd_pult_uid']);
// if Server = nil then
// begin
// LogOut('Не найден сервер УИД = ' + Item.S['cmd_pult_uid']);
// Continue;
// end;
// Server.BufferIO(JSON); //запись команды в буфер исходящих сообщений
IdBytes := GetCommandPacket(Byte(EventTypeServiceMessage)); //команда выполнить запрос на сервер
// UdpLink.SendToServer(Server, IdBytes);
// end;
end;
function TClient1C.HistoryPacket(DevID: integer; DevClass: byte; CustID: integer = -1): ISuperArray;
var Sql: string; JSON : ISuperObject; FbTool: TFBTool;
begin
Result := SA();
if CustID <> InvalidID then
Sql := 'select * from EVENTS where CUST_ID = ' + IntToStr(CustID) + ' and DATE_TIME > dateadd(-5 day to current_date)' +
' order by ID DESC'
else
Sql := 'select * from EVENTS where DEV_ID = ' + IntToStr(DevID) + ' and DEV_CLASS = ' + IntToStr(DevClass) +
' and DATE_TIME > dateadd(-5 day to current_date) order by ID DESC';
LogOut(Sql);
FbTool := TFBTool.Create;
FbTool.Select(Sql);
while not FbTool.FbDS.Eof do
begin
JSON := SO();
JSON.I['ID'] := FbTool.FbDS.FieldValues['ID'];
JSON.I['DEV_ID'] := FbTool.FbDS.FieldValues['DEV_ID'];
JSON.I['DEV_CLASS'] := FbTool.FbDS.FieldValues['DEV_CLASS'];
JSON.I['CUST_ID'] := FbTool.FbDS.FieldValues['CUST_ID'];
JSON.I['CODE_ID'] := FbTool.FbDS.FieldValues['CODE_ID'];
JSON.I['XO_ID'] := FbTool.FbDS.FieldValues['XO_ID'];
JSON.S['ADD_INFO'] := VarToStr(FbTool.FbDS.FieldValues['ADD_INFO']);
JSON.S['SIGNAL'] := VarToStr(FbTool.FbDS.FieldValues['SIGNAL']);
JSON.S['DATE_TIME'] := VarToStr(FbTool.FbDS.FieldValues['DATE_TIME']);
Result.Add(JSON);
FbTool.FbDS.Next;
end;
FbTool.Drop;
end;
function TClient1C.GetResponse: string;
var Buf: ISuperArray;
begin
Buf := BufferIO(nil);
Result := Buf.AsJSON();
// LogOut('TX = ' + Result);
end;
function TClient1C.GetCommandPacket(CmdID: Integer): TIdBytes;
var TxLen: word; OutData: TServerPacketDriverCommand; EncData: TBuf500;
i: byte;
begin
MCore.IncPacketID;
OutData.CmdID := Byte(EventTypeServiceMessage);
TxLen := protocolBuildPacket(@OutData, SizeOf(OutData), @EncData, Byte(ServerPacketTypeDriverCommand), MCore.PacketID, 0, 0, @AppEncKey);
SetLength(Result, TxLen);
LogOut('TxLen = ' + IntToStr(TxLen));
for i := 0 to High(Result) do Result[i] := EncData[i];
end;
function TClient1C.PacketOfAlarms(ZonesOnly: boolean = False): ISuperArray;
var JSON : ISuperObject; Sql: string; FbTool: TFBTool;
begin
Result := SA();
if ZonesOnly then
Sql := 'select DEV_ID from ALARMS where DEV_CLASS = ' + IntToStr(Byte(DevClassZone))
else
Sql := 'select * from ALARMS';
FbTool := TFBTool.Create();
FbTool.Select(Sql);
while not FbTool.FbDS.Eof do
begin
if ZonesOnly then
begin
Result.Add(FbTool.FbDS.FieldValues['DEV_ID']);
end else
begin
JSON := SO();
JSON.S['RR'] := 'ALARMS';
JSON.I['ID'] := FbTool.FbDS.FieldValues['ID'];
JSON.I['DEV_ID'] := FbTool.FbDS.FieldValues['DEV_ID'];
JSON.I['DEV_CLASS'] := FbTool.FbDS.FieldValues['DEV_CLASS'];
JSON.I['CUST_ID'] := FbTool.FbDS.FieldValues['CUST_ID'];
JSON.I['CODE_ID'] := FbTool.FbDS.FieldValues['CODE_ID'];
JSON.I['LONG_TERM'] := FbTool.FbDS.FieldValues['LONG_TERM'];
JSON.S['DATE_TIME'] := VarToStr(FbTool.FbDS.FieldValues['DATE_TIME']);
Result.Add(JSON);
end;
FbTool.FbDS.Next;
end;
FbTool.Drop;
end;
function TClient1C.PacketOfDevStates: ISuperArray;
var tDS: TIBDataSet; JSON : ISuperObject; FbTool: TFBTool; Sql: string;
begin
Result := SA();
Sql := 'select * from DEV_STATES';
FbTool := TFBTool.Create();
tDS := FbTool.Select(Sql);
while not tDS.Eof do
begin
JSON := SO();
JSON.S['RR'] := 'DEV_STATES';
JSON.I['ID'] := tDS.FieldValues['ID'];
JSON.I['DEV_ID'] := tDS.FieldValues['DEV_ID'];
JSON.I['DEV_CLASS'] := tDS.FieldValues['DEV_CLASS'];
JSON.I['CODE_ID'] := tDS.FieldValues['CODE_ID'];
JSON.I['STATE'] := tDS.FieldValues['STATE'];
JSON.S['DATE_TIME'] := VarToStr(tDS.FieldValues['DATE_TIME']);
Result.Add(JSON);
tDS.Next;
end;
tDS := nil;
FbTool.Drop;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor TFriServer.Create;
begin
SrvEvent := TAEvent.Create;
NeedReload := False;
end;
function TFriServer.BufferIO(JSON: ISuperObject): ISuperArray;
begin
Result := nil;
if JSON = nil then
begin
Result := ClientJSON.Clone;
ClientJSON.Clear;
Exit;
end;
ClientJSON.Add(JSON);
end;
function TFriServer.OnPing(JSON: ISuperObject): string;
var Buf: ISuperArray;
begin
Buf := BufferIO(nil);
Result := Buf.AsJSON;
end;
function TFriServer.OnDisconnect: string;
var RespJSON: ISuperObject; AddInfo: string; CodeID: integer;
begin
LogOut('Клиент ' + Name + '. Завершил работу, отправив сообщение "GOODBYE"');
CodeID := Byte(EventTypeDamageLink);
AddInfo := 'Корректное завершение работы пользователем';
GenEvent(DevID, DevClass, CodeID, AddInfo);
RespJSON := SO();
RespJSON.S[KEY_MES_TYPE] := MESSAGE_CONFIRM;
Result := RespJSON.AsJSON;
end;
function TFriServer.OnSetData: string;
var JSON: ISuperObject; AddInfo: string; DataFileName: string; Tests: ISuperArray; Ref: ISuperObject;
begin
DataFileName := 'Data\' + DevUID + '.txt';
if FileExists(DataFileName) then
begin
JSON := TSuperObject.ParseFile(DataFileName);
// if DevClass = Byte(DevClassDriverRadio) then
// begin
// Tests := AData.PacketOfTests;
// Ref := SO();
// Ref.S['ref_name'] := 'TESTS';
// Ref.A['records'] := Tests;
// JSON.A['refs'].Add(Ref);
// end;
BufferIO(JSON);
end
else
begin
AddInfo := 'Не найден файл: ' + DataFileName;
LogOut(AddInfo);
AddErrorPacket(AddInfo);
Exit;
end;
end;
function TFriServer.GetResponse: string;
var Buf: ISuperArray; JSON: ISuperObject;
begin
if NeedReload then
begin
JSON := SO();
JSON.B['reload'] := True;
BufferIO(JSON);
NeedReload := False;
end;
Buf := BufferIO(nil);
Result := Buf.AsJSON();
end;
procedure TFriServer.AddErrorPacket(ErrText: string);
var JSON: ISuperObject;
begin
JSON :=SO();
JSON.S[KEY_MES_TYPE] := MESSAGE_ERROR;
JSON.S[KEY_MES_TEXT] := ErrText;
BufferIO(JSON);
end;
procedure TFriServer.OnEvent(Item: ISuperObject);
var JSON: ISuperObject; i: integer;
Title, NoteText: string; Topics: ISuperArray; FcmObj: ISuperObject;
EventCode: TEventCode; Zone: TZone; Obj: TFObject;
begin
SrvEvent.ID := 0;
SrvEvent.DevID := Item.I['DEV_ID'];
SrvEvent.DevClass := Item.I['DEV_CLASS'];
SrvEvent.CustID := Item.I['CUST_ID'];
SrvEvent.CodeID := Item.I['CODE_ID'];
SrvEvent.XoID := Item.I['XO_ID'];
SrvEvent.AddInfo := Item.S['ADD_INFO'];
SrvEvent.Signal := Item.S['SIGNAL'];
SrvEvent.DateTime := StrToDateTime(Item.S['DATE_TIME']);
SrvEvent.Write;
end;
procedure TFriServer.GenEvent(DevID: integer; DevClass: byte; CodeID: integer; AddInfo: string = ''; CustID: integer = -1);
begin
SrvEvent.ID := 0;
SrvEvent.DevID := DevID;
SrvEvent.DevClass := DevClass;
SrvEvent.CustID := CustID;
SrvEvent.CodeID := CodeID;
SrvEvent.XoID := InvalidID;
SrvEvent.AddInfo := AddInfo;
SrvEvent.Signal := '';
SrvEvent.DateTime := Now;
SrvEvent.Write;
end;
end.
|
{ > P2ada test - Example coming from Steven H Don's tools, http://shd.cjb.net
{ in Ada: see SVGA-IO.adb, DOS_Paqs.zip. }
{****************************************************************************
** Demonstration of loading a GIF file and displaying it on screen **
** by Steven H Don **
** **
** This support Compuserve 256 colour GIF87a and GIF89a image up to **
** 320x200 in size. **
** **
** For questions, feel free to e-mail me. **
** **
** shd@earthling.net **
** http://shd.cjb.net **
** **
****************************************************************************}
{This program requires a stack of at least 19.5K}
{$M 19500,0,655360}
program GIFLoad;
uses Crt;
type
GIFHeader = record
Signature : String [6];
ScreenWidth,
ScreenHeight : Word;
Depth,
Background,
Zero : Byte;
end;
GIFDescriptor = record
Separator : Char;
ImageLeft,
ImageTop,
ImageWidth,
ImageHeight : Word;
Depth : Byte;
end;
{This sets the display to VGA 320x200 in 256 colours}
procedure VGAScreen; assembler;
asm
mov ax, 13h
int 10h
end;
{This resets the display to text mode}
procedure TextScreen; assembler;
asm
mov ax, 3h
int 10h
end;
{This sets a DAC register to a specific Red Green Blue-value}
procedure SetDAC(DAC, R, G, B : Byte);
begin
Port[$3C8] := DAC;
Port[$3C9] := R;
Port[$3C9] := G;
Port[$3C9] := B;
end;
{This sets one pixel on the screen}
procedure PutPixel (x, y : Word; c : Byte);
begin
Mem [$A000:y shl 8 + y shl 6 + x] := c;
end;
{This actually loads the GIF}
procedure LoadGIF (Filename : String);
var
{For loading from the GIF file}
Header : GIFHeader;
Descriptor : GIFDescriptor;
GIFFile : File;
Temp : Byte;
BPointer : Word;
Buffer : Array [0..256] of Byte;
{Colour information}
BitsPerPixel,
NumOfColours,
DAC : Byte;
Palette : Array [0..255, 0..2] of Byte;
{Coordinates}
X, Y,
tlX, tlY,
brX, brY : Word;
{GIF data is stored in blocks of a certain size}
BlockSize : Byte;
{The string table}
Prefix : Array [0..4096] Of Word;
Suffix : Array [0..4096] Of Byte;
OutCode : Array [0..1024] Of Byte;
FirstFree,
FreeCode : Word;
{All the code information}
InitCodeSize,
CodeSize : Byte;
Code,
OldCode,
MaxCode : Word;
{Special codes}
ClearCode,
EOICode : Word;
{Used while reading the codes}
BitsIn : Byte;
{Local function to read from the buffer}
function LoadByte : Byte;
begin
{Read next block}
if (BPointer = BlockSize) then begin
{$I-}
BlockRead (GIFFile, Buffer, BlockSize + 1);
if IOResult <> 0 then;
{$I+}
BPointer := 0;
end;
{Return byte}
LoadByte := Buffer [BPointer];
inc (BPointer);
end;
{Local procedure to read the next code from the file}
procedure ReadCode;
var
Counter : Integer;
begin
Code := 0;
{Read the code, bit by bit}
for Counter := 0 To CodeSize - 1 do begin
{Next bit}
inc (BitsIn);
{Maybe, a new byte needs to be loaded with a further 8 bits}
if (BitsIn = 9) then begin
Temp := LoadByte;
BitsIn := 1;
end;
{Add the current bit to the code}
if ((Temp and 1) > 0) then inc (Code, 1 shl Counter);
Temp := Temp shr 1;
end;
end;
{Local procedure to draw a pixel}
procedure NextPixel (c : Word);
begin
{Actually draw the pixel on screen}
PutPixel (X, Y, c and 255);
{Move on to next pixel}
inc (X);
{Or next row, if necessary}
if (X = brX) then begin
X := tlX;
inc (Y);
end;
end;
{Local function to output a string. Returns the first character.}
function OutString (CurCode : Word) : Byte;
var
OutCount : Word;
begin
{If it's a single character, output that}
if CurCode < 256 then begin
NextPixel (CurCode);
end else begin
OutCount := 0;
{Store the string, which ends up in reverse order}
repeat
OutCode [OutCount] := Suffix [CurCode];
inc (OutCount);
CurCode := Prefix [CurCode];
until (CurCode < 256);
{Add the last character}
OutCode [OutCount] := CurCode;
inc (OutCount);
{Output all the string, in the correct order}
repeat
dec (OutCount);
NextPixel (OutCode [OutCount]);
until OutCount = 0;
end;
{Return 1st character}
OutString := CurCode;
end;
begin
{Check whether the GIF file exists, and open it}
{$I-}
Assign (GIFFile, Filename);
Reset (GIFFile, 1);
if IOResult <> 0 then begin
TextScreen;
Writeln ('Could not open file ', FileName);
Exit;
end;
{$I+}
{Read header}
Header.Signature [0] := Chr (6);
Blockread (GIFFile, Header.Signature [1], sizeof (Header) - 1);
{Check signature and terminator}
if ((Header.Signature <> 'GIF87a') and (Header.Signature <> 'GIF89a'))
or (Header.Zero <> 0) then begin
TextScreen;
Writeln ('Not a valid GIF file');
Exit;
end;
{Get amount of colours in image}
BitsPerPixel := 1 + (Header.Depth and 7);
NumOfColours := (1 shl BitsPerPixel) - 1;
{Load global colour map}
BlockRead (GIFFile, Palette, 3 * (NumOfColours + 1));
for DAC := 0 to NumOfColours do begin
SetDAC(DAC, Palette [DAC, 0] shr 2,
Palette [DAC, 1] shr 2,
Palette [DAC, 2] shr 2);
end;
{Load the image descriptor}
BlockRead (GIFFile, Descriptor, sizeof (Descriptor));
if (Descriptor.Separator <> ',') then begin
TextScreen;
Writeln ('Incorrect image descriptor.');
Exit;
end;
{Get image corner coordinates}
tlX := Descriptor.ImageLeft;
tlY := Descriptor.ImageTop;
brX := tlX + Descriptor.ImageWidth;
brY := tlY + Descriptor.ImageHeight;
{Some restrictions apply}
if (Descriptor.Depth and 128 = 128) then begin
TextScreen;
Writeln ('Local colour maps not supported');
Exit;
end;
if (Descriptor.Depth and 64 = 64) then begin
TextScreen;
Writeln ('Interlaced images not supported');
Exit;
end;
{Get initial code size}
BlockRead (GIFFile, CodeSize, 1);
{GIF data is stored in blocks, so it's necessary to know the size}
BlockRead (GIFFile, BlockSize, 1);
{Start loader}
BPointer := BlockSize;
{Special codes used in the GIF spec}
ClearCode := 1 shl CodeSize; {Code to reset}
EOICode := ClearCode + 1; {End of file}
{Initialize the string table}
FirstFree := ClearCode + 2; {Strings start here}
FreeCode := FirstFree; {Strings can be added here}
{Initial size of the code and its maximum value}
inc (CodeSize);
InitCodeSize := CodeSize;
MaxCode := 1 shl CodeSize;
BitsIn := 8;
{Start at top left of image}
X := Descriptor.ImageLeft;
Y := Descriptor.ImageTop;
repeat
{Read next code}
ReadCode;
{If it's an End-Of-Information code, stop processing}
if Code = EOICode then break
{If it's a clear code...}
else if Code = ClearCode then begin
{Clear the string table}
FreeCode := FirstFree;
{Set the code size to initial values}
CodeSize := InitCodeSize;
MaxCode := 1 shl CodeSize;
{The next code may be read}
ReadCode;
OldCode := Code;
{Set pixel}
NextPixel (Code);
{Other codes}
end else begin
{If the code is already in the string table, it's string is displayed,
and the old string followed by the new string's first character is
added to the string table.}
if (Code < FreeCode) then
Suffix [FreeCode] := OutString (Code)
else begin
{If it is not already in the string table, the old string followed by
the old string's first character is added to the string table and
displayed.}
Suffix [FreeCode] := OutString (OldCode);
NextPixel (Suffix [FreeCode]);
end;
{Finish adding to string table}
Prefix [FreeCode] := OldCode;
inc (FreeCode);
{If the code size needs to be adjusted, do so}
if (FreeCode >= MaxCode) and (CodeSize < 12) then begin
inc (CodeSize);
MaxCode := MaxCode shl 1;
end;
{The current code is now old}
OldCode := Code;
end;
until Code = EOICode;
{Close the GIF file}
Close (GIFFile);
end;
var
FileName : String;
begin
{Check if a filename was passed as a parameter, otherwise ask for one}
if ParamCount > 0 then
FileName := ParamStr (1)
else begin
Write ('Enter filename:');
ReadLn (FileName);
end;
{Switch to graphics screen}
VGAScreen;
{Load GIF file}
LoadGIF (FileName);
{Wait for keypress}
ReadKey;
{Switch back to text mode}
TextScreen;
end.
{--- end of file ---}
|
unit vcmMenuManager;
{* Менеджер меню. }
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmMenuManager - }
{ Начат: 14.03.2003 17:06 }
{ $Id: vcmMenuManager.pas,v 1.513 2013/07/26 10:32:44 morozov Exp $ }
// $Log: vcmMenuManager.pas,v $
// Revision 1.513 2013/07/26 10:32:44 morozov
// {RequestLink: 471774401}
//
// Revision 1.512 2013/07/05 14:34:52 lulin
// - переименовал свойство про возможность редактирования тулбара и немного переделал правки Виктора касательно редактирования тулбаров во внутренней версии.
//
// Revision 1.511 2013/07/01 12:28:52 morozov
// {RequestLink:382416588}
//
// Revision 1.510 2013/05/17 13:47:00 lulin
// - ищем странную ошибку в пачке тестов.
//
// Revision 1.509 2013/04/05 12:02:37 lulin
// - портируем.
//
// Revision 1.508 2013/03/14 16:09:28 kostitsin
// [$432571670]
//
// Revision 1.507 2013/02/08 15:22:56 kostitsin
// [$427755666]
//
// Revision 1.506 2013/01/28 11:27:27 lulin
// - разборки с некомпиляцией бибилиотек.
//
// Revision 1.505 2013/01/28 09:22:45 kostitsin
// [$425042879]
//
// Revision 1.504 2012/11/02 11:01:10 lulin
// - выкидываем лишнее.
//
// Revision 1.503 2012/11/02 08:27:26 lulin
// - правим за собой.
//
// Revision 1.502 2012/11/02 07:48:04 lulin
// - не цепляем лишние файлы.
//
// Revision 1.501 2012/11/01 09:42:22 lulin
// - забыл точку с запятой.
//
// Revision 1.500 2012/11/01 07:44:07 lulin
// - делаем возможность логирования процесса загрузки модулей.
//
// Revision 1.499 2012/11/01 07:00:32 lulin
// - не цепляем лишнее в тестах.
//
// Revision 1.498 2012/11/01 06:48:18 lulin
// - переносим заплатку в другое место, чтобы не перетёрлась при генерации модели.
//
// Revision 1.497 2012/10/22 14:20:47 lulin
// {RequestLink:405474881}
//
// Revision 1.496 2012/10/18 16:51:05 lulin
// {RequestLink:404363289}
//
// Revision 1.495 2012/08/29 09:42:45 kostitsin
// [$378542059]
//
// Revision 1.494 2012/08/16 14:55:01 kostitsin
// [$378542059]
//
// Revision 1.493 2012/07/18 13:18:04 lulin
// {RequestLink:378550793}
//
// Revision 1.492 2012/07/18 08:59:39 lulin
// {RequestLink:378550015}
//
// Revision 1.491 2012/07/17 12:01:29 lulin
// {RequestLink:378541134}
//
// Revision 1.490 2012/07/17 11:52:46 lulin
// {RequestLink:378541134}
//
// Revision 1.489 2012/07/17 11:12:09 lulin
// {RequestLink:378541134}
//
// Revision 1.488 2012/07/12 10:21:20 lulin
// {RequestLink:237994598}
//
// Revision 1.487 2012/05/31 09:52:24 lulin
// {RequestLink:358352284}
//
// Revision 1.486 2012/05/31 09:36:58 lulin
// {RequestLink:358352284}
//
// Revision 1.485 2012/05/30 17:12:01 lulin
// - выделяем класс в отдельный файл.
//
// Revision 1.484 2012/05/30 16:34:14 lulin
// {RequestLink:358352284}
//
// Revision 1.483 2012/04/13 19:00:43 lulin
// {RequestLink:237994598}
//
// Revision 1.482 2012/04/13 14:37:56 lulin
// {RequestLink:237994598}
//
// Revision 1.481 2012/04/09 08:38:58 lulin
// {RequestLink:237994598}
// - думаем о VGScene.
//
// Revision 1.480 2012/04/06 15:57:38 lulin
// {RequestLink:237994598}
//
// Revision 1.479 2012/04/06 08:20:18 lulin
// {RequestLink:237994598}
//
// Revision 1.478 2012/04/04 17:55:41 lulin
// {RequestLink:237994598}
// - разбираемся с упавшими тестами.
//
// Revision 1.477 2012/03/22 06:40:09 lulin
// - чистим код от мусора.
//
// Revision 1.476 2012/03/22 06:04:22 dinishev
// Bug fix: не компилировался АрчиТест
//
// Revision 1.475 2012/03/21 18:08:39 lulin
// {RequestLink:349116364}
//
// Revision 1.474 2012/03/21 17:22:15 lulin
// {RequestLink:349116364}
//
// Revision 1.473 2012/03/15 10:55:27 lulin
// {RequestLink:344754050}
//
// Revision 1.472 2012/03/15 07:27:27 lulin
// {RequestLink:344754050}
// - чистим код.
//
// Revision 1.471 2012/01/20 15:02:36 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=278854646
//
// Revision 1.470 2012/01/12 08:54:47 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=293277808
//
// опечатка..
//
// Revision 1.469 2012/01/11 11:04:35 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=253667544&focusedCommentId=326771397#comment-326771397
//
// Revision 1.468 2012/01/11 08:53:26 kostitsin
// не учел возможность "дочить" тулбары к разным краям окна.
// Исправил.
//
// http://mdp.garant.ru/pages/viewpage.action?pageId=319489610&focusedCommentId=326769863#comment-326769863
//
// Revision 1.467 2012/01/10 14:19:22 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=319489610&focusedCommentId=326767909#comment-326767909
//
// Revision 1.466 2012/01/10 12:21:40 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=319489610
//
// Revision 1.465 2011/12/27 13:03:14 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=319489610
//
// проверяем гипотезу с invalidate
//
// Revision 1.464 2011/12/26 15:58:48 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=296098743
//
// Revision 1.463 2011/12/23 11:45:52 kostitsin
// http://mdp.garant.ru/pages/viewpage.action?pageId=296098743
//
// Revision 1.462 2011/12/21 11:38:13 gensnet
// http://mdp.garant.ru/pages/viewpage.action?pageId=287214455
//
// Revision 1.461 2011/07/21 14:17:07 vkuprovich
// {RequestLink:272668827}
// реализация менюшных цветовых настроек переносится на уровеньTvcmPopupMenuPrim
//
// Revision 1.460 2011/07/19 18:59:27 vkuprovich
// {RequestLink:271758721}
// переносим освобождение кисти из FreeInstance в деструктор
//
// Revision 1.459 2011/07/19 18:10:33 vkuprovich
// {RequestLink:271758721}
// Фиксим цвет фона для выпадающего меню тулбара
//
// Revision 1.458 2011/07/18 18:26:45 vkuprovich
// {RequestLink:271757829}
// Фиксим цвет фона для тулбара
//
// Revision 1.457 2011/07/18 13:35:03 vkuprovich
// {RequestLink:271757851}
//
// Revision 1.456 2011/05/24 15:21:52 lulin
// {RequestLink:266425290}.
//
// Revision 1.455 2011/05/19 12:21:15 lulin
// {RequestLink:266409354}.
//
// Revision 1.454 2011/05/18 17:45:38 lulin
// {RequestLink:266409354}.
//
// Revision 1.453 2011/03/28 17:20:20 lulin
// {RequestLink:257393788}.
//
// Revision 1.452 2011/01/29 16:35:03 lulin
// {RequestLink:228688602}.
// - вычищаем мусор.
//
// Revision 1.451 2010/10/18 15:19:28 lulin
// {RequestLink:235876230}.
//
// Revision 1.450 2010/09/29 09:19:56 oman
// - fix: {RequestLink:235061704}
//
// Revision 1.449 2010/09/23 09:27:05 oman
// - fix: {RequestLink:235047754}
//
// Revision 1.448 2010/09/17 05:58:39 oman
// - fix: {RequestLink:235047754}
//
// Revision 1.447 2010/09/15 15:11:07 lulin
// {RequestLink:235047275}.
//
// Revision 1.446 2010/09/13 14:49:47 lulin
// {RequestLink:235047275}.
//
// Revision 1.445 2010/09/13 09:51:11 lulin
// {RequestLink:197496539}.
// - №2.
//
// Revision 1.444 2010/07/16 13:50:03 lulin
// {RequestLink:226005144}.
// [$226006522].
//
// Revision 1.443 2010/04/30 15:15:44 lulin
// {RequestLink:207389954}.
// - чистка комментариев.
//
// Revision 1.442 2010/04/27 18:02:24 lulin
// {RequestLink:159352361}.
// - признак возможности закрытия формы переносим на модель.
//
// Revision 1.441 2010/04/15 13:54:06 oman
// - new: Очепятка {RequestLink:203131454}
//
// Revision 1.440 2010/04/15 13:33:16 oman
// - new: Разрешаем PopupMenu для главной формы {RequestLink:203131454}
//
// Revision 1.439 2010/03/10 12:48:43 lulin
// {RequestLink:193826739}.
//
// Revision 1.438 2010/03/09 11:14:55 oman
// - new: {RequestLink:190678009}
//
// Revision 1.437 2010/03/03 17:28:16 lulin
// {RequestLink:193826739}.
//
// Revision 1.436 2010/02/11 10:09:29 oman
// - fix: {RequestLink:190677990}
//
// Revision 1.435 2010/02/11 09:35:18 oman
// - fix: {RequestLink:190677990}
//
// Revision 1.434 2009/11/20 10:27:40 oman
// - fix: {RequestLink:171970140}
//
// Revision 1.433 2009/11/19 12:59:03 oman
// - fix: {RequestLink:171968647}
//
// Revision 1.432 2009/10/19 13:07:56 lulin
// {RequestLink:159360578}. №7.
//
// Revision 1.431 2009/10/16 17:00:44 lulin
// {RequestLink:159360578}. №52.
//
// Revision 1.430 2009/10/15 17:21:57 lulin
// {RequestLink:166856141}. Попытки ещё что-нибудь полечить.
//
// Revision 1.429 2009/10/15 14:42:06 lulin
// {RequestLink:166856141}.
//
// Revision 1.428 2009/10/13 16:02:40 lulin
// - чистка кода.
//
// Revision 1.427 2009/10/05 06:46:07 lulin
// {RequestLink:159360578}. №51.
//
// Revision 1.426 2009/10/01 14:58:30 lulin
// - убираем сферического коня в вакууме.
//
// Revision 1.425 2009/09/30 15:23:00 lulin
// - убираем ненужное приведение ко вполне понятным интерфейсам.
//
// Revision 1.424 2009/09/28 17:12:48 lulin
// {RequestLink:159360578}. №31.
//
// Revision 1.423 2009/09/16 18:06:41 lulin
// {RequestLink:163061744}.
//
// Revision 1.422 2009/09/16 11:27:27 lulin
// - избавляемся от дублирования модулей.
//
// Revision 1.421 2009/08/31 15:40:45 lulin
// - убираем лишний метод.
// - убираем необходимость знать идентификатор сборки - если есть её класс.
// - убираем ненужную связь между раализациями прецедентов.
// - ссылаемся из реализаций прецедентов на используемые прецеденты.
//
// Revision 1.420 2009/08/11 14:24:03 lulin
// {RequestLink:129240934}. №16.
//
// Revision 1.419 2009/02/20 15:19:00 lulin
// - <K>: 136941122.
//
// Revision 1.418 2009/02/19 14:16:33 lulin
// - <K>: 136941122. Убираем локальные интерфейсы.
//
// Revision 1.417 2009/02/12 17:09:15 lulin
// - <K>: 135604584. Выделен модуль с внутренними константами.
//
// Revision 1.416 2009/02/12 16:06:49 lulin
// - <K>: 135604584. Выделен модуль локализации.
//
// Revision 1.415 2009/01/27 13:30:08 oman
// - fix: Не влезали служебные кнопки (К-136252192)
//
// Revision 1.414 2009/01/12 09:41:56 oman
// - new: Готовим интерфейсы для дочерней зоны (К-113508400)
//
// Revision 1.413 2008/09/02 12:38:14 lulin
// - <K>: 88080895.
//
// Revision 1.412 2008/07/14 13:11:51 lulin
// - <K>: 100958843.
//
// Revision 1.411 2008/07/10 11:19:13 lulin
// - <K>: 100958687.
//
// Revision 1.410 2008/07/08 11:26:27 lulin
// - избавился от хранения и выставления свойства IsList.
// - починил выбор в списке пользователей.
//
// Revision 1.409 2008/07/07 14:27:06 lulin
// - подготавливаемся к переименованию.
//
// Revision 1.408 2008/07/02 10:51:05 lulin
// - <K>: 95486333.
//
// Revision 1.407 2008/06/03 07:30:36 lulin
// - <K>: 93260300.
//
// Revision 1.406 2008/05/29 12:26:54 mmorozov
// - new: возможность определить от какого типа использовать панель инструментов (CQ: OIT5-28281).
//
// Revision 1.405 2008/05/15 20:15:21 lulin
// - тотальная чистка.
//
// Revision 1.404 2008/04/07 07:59:47 lulin
// - <K>: 88641266.
//
// Revision 1.403 2008/03/24 14:04:12 lulin
// - <K>: 87591840.
//
// Revision 1.402 2008/03/24 08:48:43 lulin
// - <K>: 87591840.
//
// Revision 1.401 2008/03/24 06:41:48 oman
// - Не собирались
//
// Revision 1.400 2008/03/21 08:01:51 mmorozov
// - фиксируем, что TvcmDockDef не должен существовать без TvcmDockPanel;
//
// Revision 1.399 2008/03/21 07:05:43 mmorozov
// - change: комментарий для TvcmDockPanel;
//
// Revision 1.398 2008/03/20 09:48:19 lulin
// - cleanup.
//
// Revision 1.397 2008/03/19 14:23:44 lulin
// - cleanup.
//
// Revision 1.396 2008/03/18 15:14:36 mmorozov
// - bugfix: панель создавалась по требованию, а должна всегда, т.к. выполняет функции корректировки размера формы (CQ: OIT5-28614);
//
// Revision 1.395 2008/03/11 13:47:06 oman
// - fix: Делаем DockContainer только по необходимости (cq28605)
//
// Revision 1.394 2008/03/11 13:05:39 oman
// - fix: Пряталась медалька (cq28605)
//
// Revision 1.393 2008/03/07 13:18:06 lulin
// - <K>: 86477737.
//
// Revision 1.392 2008/03/07 10:51:29 mmorozov
// - интерфейс в параметрах передаём с ключевым словом const (CQ: OIT5-28340);
//
// Revision 1.391 2008/03/07 09:36:04 mmorozov
// - изменения при работе с обработчиками формы (в рамках CQ: OIT5-28340);
//
// Revision 1.390 2008/02/21 10:55:08 lulin
// - упрощаем наследование.
//
// Revision 1.389 2008/02/20 08:31:05 oman
// - fix: Некорректно подгоняли высоту тулбаров
//
// Revision 1.388 2008/02/19 13:59:13 oman
// - new: Логика с количеством строк в иконках вынесена в тулбарные кнопки (cq10920)
//
// Revision 1.387 2008/02/18 13:46:24 oman
// - new: средний размер кнопок в тулбаре и автопобдор оного размера -
// предварительный вариант (cq10920)
//
// Revision 1.386 2008/01/31 20:38:03 lulin
// - избавляемся от излишней универсальности списков.
//
// Revision 1.385 2007/12/07 16:22:44 lulin
// - переименовываем файл, чтобы не путать с другой библиотекой.
//
// Revision 1.384 2007/10/15 11:28:14 lulin
// - вычищено устаревшее свойство.
//
// Revision 1.383 2007/09/26 06:18:11 mmorozov
// - change: вместо использования TvcmAction используем IvcmAction + правки ошибок при переходе на использование _SelectedString вместо Caption (в рамках работы над CQ: OIT5-26741 + K<50758978>);
//
// Revision 1.382 2007/09/25 04:51:34 mmorozov
// - библиотека не собиралась;
//
// Revision 1.381 2007/09/25 03:55:35 mmorozov
// - new behaviour: для чтения\изменения текущего выбранного значения для операций типа vcm_otDate, vcm_otCombo, vcm_otEditCombo используем свойство параметров _SelectedString, раньше Caption. Тем самым Caption для этих типов операций стал изменяемым (в рамках работы CQ: OIT5-26741);
//
// Revision 1.380 2007/08/31 11:25:13 mmorozov
// - warning fix;
//
// Revision 1.379 2007/06/28 14:56:13 lulin
// - cleanup.
//
// Revision 1.378 2007/06/06 12:01:29 lulin
// - избавляемся от вредоносного параметра по-умолчанию (<K>-16352239).
//
// Revision 1.377 2007/05/25 14:52:14 mmorozov
// - change: изменения связанные с использованием операции типа дата (vcm_otDate) в панели задач (CQ: OIT5-25342);
//
// Revision 1.376 2007/04/24 07:36:02 oman
// - fix: Не срабатывало условие
//
// Revision 1.375 2007/04/20 12:04:32 lulin
// - bug fix: при хождении по истории опять кнопки не нарезались в несколько строк (CQ OIT5-24967).
//
// Revision 1.374 2007/04/19 11:10:27 lulin
// - если самая краяняя правая кнопка умещается в две строки, то не обрезаем ее текст (CQ OIT5-25091).
//
// Revision 1.373 2007/04/13 15:51:13 lulin
// - для отрисовки используем родную канву.
//
// Revision 1.372 2007/04/12 12:35:06 lulin
// - используем строки с кодировкой.
//
// Revision 1.371 2007/04/12 08:11:51 lulin
// - используем строки с кодировкой.
//
// Revision 1.370 2007/04/12 07:57:09 lulin
// - используем строки с кодировкой.
//
// Revision 1.369 2007/04/12 06:43:43 lulin
// - bug fix: не собиралась библиотека.
//
// Revision 1.368 2007/04/11 12:04:27 lulin
// - для заголовка экшена используем строки с кодировкой.
//
// Revision 1.367 2007/04/11 07:22:10 mmorozov
// - new: выделены методы для создания Action (BuildAction);
//
// Revision 1.366 2007/04/10 13:20:10 lulin
// - используем строки с кодировкой.
//
// Revision 1.365 2007/04/03 11:07:55 lulin
// - убираем ненужную прозрачность кнопок.
//
// Revision 1.364 2007/04/02 05:48:35 lulin
// - теперь длинные заголовки кнопок умеют резаться в несколько строк, если это возможно, а также - обрезаться с многоточием, если в несколько строк не влезают.
//
// Revision 1.363 2007/03/28 19:42:54 lulin
// - ЭлПаковский редактор переводим на строки с кодировкой.
//
// Revision 1.362 2007/03/20 15:26:30 mmorozov
// - hint fix;
//
// Revision 1.361 2007/03/15 12:18:43 lulin
// - cleanup.
//
// Revision 1.360 2007/02/12 16:40:29 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.359 2007/02/07 12:58:11 oman
// - fix: Множество vcm_InternalOperations переименовано в
// vcm_HiddenOperations и из него выделены собственно
// vcm_InternalOperations - иначе не выливались Hidden операции
// (cq24357)
//
// Revision 1.358 2007/01/29 13:50:34 oman
// - fix: Комбобоксы в тулбаре не должны скролироваться в конец
// текста (cq24179)
//
// Revision 1.357 2007/01/26 08:47:07 oman
// - fix: картинку для checked элемента выпадающего у кнопки меню
// обрисовываем так же как и в главном меню.
//
// Revision 1.356 2007/01/22 15:30:08 lulin
// - избавляемся от нефиксированных параметров при выполнении пользовательской операции.
//
// Revision 1.355 2007/01/18 13:54:18 oman
// - new: Локализация библиотек - vcm - избавляемся от значений по
// умолчанию - более радикальный вариант (cq24078)
//
// Revision 1.354 2007/01/16 08:51:07 lulin
// - избавляемся от нефиксированного параметра - текущая нода.
//
// Revision 1.353 2007/01/15 18:33:01 lulin
// - избавляемся от нефиксированного параметра - показывать корень или нет.
//
// Revision 1.352 2007/01/15 17:25:38 lulin
// - cleanup.
//
// Revision 1.351 2007/01/15 17:17:07 lulin
// - cleanup.
//
// Revision 1.350 2007/01/15 14:56:50 lulin
// - при построении меню используем операции модуля из списка строк.
//
// Revision 1.349 2007/01/12 13:14:44 oman
// - fix: Вернул vcm_otMenuButtonCombo - разъехалось меню (cq24113)
//
// Revision 1.348 2007/01/11 12:52:16 lulin
// - теперь список нод создаем только по требованию - когда его реально хотят заполнить.
//
// Revision 1.347 2007/01/11 11:15:06 lulin
// - вводим "родные" ноды.
//
// Revision 1.346 2007/01/10 17:27:41 lulin
// - теперь список строк создаем только по требованию - когда его реально хотят заполнить.
//
// Revision 1.345 2007/01/10 15:56:00 lulin
// - cleanup.
//
// Revision 1.344 2007/01/10 11:57:51 lulin
// - cleanup.
//
// Revision 1.343 2007/01/05 18:17:33 lulin
// - используем базовые ноды для выпадающих списков.
//
// Revision 1.342 2007/01/05 14:14:51 lulin
// - убран лишний тип операции - ибо нечего типом задавать место расположения контрола.
//
// Revision 1.341 2007/01/05 13:53:14 lulin
// - убран лишний тип операции - ибо нечего типом задавать место расположения контрола.
//
// Revision 1.340 2007/01/05 13:32:58 lulin
// - cleanup.
//
// Revision 1.339 2006/12/29 13:09:23 lulin
// - реализуем интерфейс расширенного списка строк.
//
// Revision 1.338 2006/12/27 14:44:59 mmorozov
// - change: механизм объединения панелей инструментов (CQ: OIT5-23903);
//
// Revision 1.337 2006/12/25 09:08:59 mmorozov
// - new behaviour: если у формы определен компонент "строка состояния", то у формы создается контейнер для зон стыковки. Для исключения случая когда панели инструментов попадают под строку состояния (CQ: OIT5-23903);
//
// Revision 1.336 2006/12/19 12:08:27 lulin
// - cleanup.
//
// Revision 1.335 2006/12/15 12:57:33 mmorozov
// - new behaviour: Встраивание панелей навигатора под основной тулбар (CQ: OIT5-21250). Положение главного тулбара определяется директивой vcmUseMainToolbarPanel;
//
// Revision 1.334 2006/12/13 15:13:10 lulin
// - cleanup.
//
// Revision 1.333 2006/12/13 09:22:06 mmorozov
// - new: возможность указывать фиксированный размер для зон стыковки панелей инструментов формы, в рамках работы над CQ: OIT5-13323;
//
// Revision 1.332 2006/11/03 11:00:32 lulin
// - объединил с веткой 6.4.
//
// Revision 1.331.2.3 2006/10/30 11:04:55 oman
// - fix: Блокирование излишней функциональности vcl.
// Выпадающие меню в английской версии "моргало" (cq23319)
//
// Revision 1.331.2.2 2006/10/18 08:00:31 lulin
// - заголовок для настроек приобрел общее название.
//
// Revision 1.331.2.1 2006/10/17 08:13:18 lulin
// - заголовки контролов вычитываем из загруженных ресурсов.
//
// Revision 1.331 2006/09/20 14:59:16 mmorozov
// - new: событие выполения операции пользователем (в рамках работы журнал работы пользователя);
//
// Revision 1.330 2006/09/20 09:12:57 oman
// - fix: В окне настройки тулбаров Восстановить все не
// восстанавливало глубину цвета (cq22660)
//
// Revision 1.329 2006/08/29 08:29:35 oman
// - fix: Неправильно вычислялась ширина кнопки для *ButtomPopup,
// более правильный вариант (cq22390)
//
// Revision 1.328 2006/08/29 06:49:45 oman
// - fix: Неправильно вычислялась ширина кнопки для *ButtomPopup (cq22390)
//
// Revision 1.327 2006/08/25 12:34:18 oman
// - new: Новый тип операции _vcm_otMenuButtonPopup - такой же как
// _vcm_otButtonPopup, но умеет еще показываться в меню.
//
// Revision 1.326 2006/06/09 11:09:51 oman
// - fix: Правильно обрабатываем Combo Action - были случаи когда
// обращались к еще некорректному Action.Caption (cq21218)
//
// Revision 1.325 2006/06/08 13:38:00 lulin
// - подготавливаем контролы к обработке числа повторений нажатия клавиши.
//
// Revision 1.324 2006/06/02 12:36:11 oman
// - fix: В настройке тулбара при его смене могли хватать не видимый для пользователя
//
// Revision 1.323 2006/04/14 12:38:11 lulin
// - запрещаем перекрывать деструктор.
//
// Revision 1.322 2006/03/23 14:06:51 lulin
// - добавлена коллекция строковых констант.
//
// Revision 1.321 2006/03/15 12:27:21 lulin
// - cleanup.
//
// Revision 1.320 2006/03/10 18:22:03 lulin
// - работа над заливкой/выливкой строковых ресурсов.
//
// Revision 1.319 2006/01/20 11:33:06 mmorozov
// 1. Нельзя было на панель инструментов положить неколько операций из разных сущностей с одинаковыми именами;
// 2. Если в панели инструментов встречаются операции с одинаковыми названиями, то им автоматически добавляется суффикс в виде названия сущности;
// 3. Появилась возможность указать, что контекстные операции сущности должны показываться в отдельном пункте меню;
// 3.
//
// Revision 1.318 2005/12/20 14:53:17 lulin
// - исправлена ошибка, которую нашел Рома.
//
// Revision 1.317 2005/12/20 11:38:52 oman
// - fix: Докрутил TvcmCustomMenuManager._PostBuild на предмет переезда
// тулбара на другой док.
//
// Revision 1.316 2005/12/08 13:06:05 oman
// - fix: не учитывалось, что в TvcmCustomMenuManager._PostBuild тулбар может
// переехать на другой док
//
// Revision 1.315 2005/11/10 17:59:39 lulin
// - bug fix: не становились доступными стрелочки у кнопок с множественным выбором (CQ OIT5-17940).
//
// Revision 1.314 2005/09/13 13:18:22 mmorozov
// - warning fix;
//
// Revision 1.313 2005/07/28 14:29:45 mmorozov
// new: published _FormSetFactories;
//
// Revision 1.312 2005/06/01 09:14:49 mmorozov
// - warning fix;
// new: реализация и объявление TvcmFakeBox обрамлены _vcmUseComboTree;
//
// Revision 1.311 2005/06/01 08:24:28 mmorozov
// new: class TvcmFakeBox (общая функциональность необходимая vcm при использовании TFakeBox);
// change: TvcmEdit и TvcmComboBox наследники от TvcmFakeBox;
//
// Revision 1.310 2005/05/31 14:39:46 mmorozov
// new: TvcmComboBox поддерживает интерфейс ITB97Ctrl;
//
// Revision 1.309 2005/05/12 14:39:15 lulin
// - cleanup: не ходим вкруголя к своему же экземпляру.
//
// Revision 1.308 2005/05/12 14:33:48 lulin
// - new method: Tafw.IsObjectLocked.
//
// Revision 1.307 2005/04/12 13:43:02 mmorozov
// new behaviour: создаем _vcm_dmToolbarMenu после загрузки ресурсов;
//
// Revision 1.306 2005/03/22 11:57:49 mmorozov
// new behaviour: TvcmEdit при получении фокуса выделяет весь текст;
//
// Revision 1.305 2005/03/21 13:12:51 am
// change: вынес _TvcmPopupMenuPrim в vcmMenus
//
// Revision 1.304 2005/03/11 13:24:54 am
// change: выставляем панелям, на которых лежат доки, правильный TabOrder
//
// Revision 1.303 2005/02/25 14:39:11 mmorozov
// new: реализация TvcmDockDef интерфейса IvcmDock;
// new: ведем список dock-ов формы;
//
// Revision 1.302 2005/02/02 09:14:42 lulin
// - расширен шаблон Unknown.
//
// Revision 1.301 2005/01/25 08:49:43 mmorozov
// bugfix: при перегрузке toolbar-ов не перечитывалась глубина цвета;
//
// Revision 1.300 2005/01/21 15:05:34 mmorozov
// new: реакция на изменение Action.Hint для TvcmComboBox;
//
// Revision 1.299 2005/01/21 14:58:03 am
// change: vcm'ный TvcmDateEdit наследуем от TvtDblClickDateEdi
//
// Revision 1.298 2005/01/20 13:25:18 lulin
// - new consts: _vcm_otModuleInternal, _vcm_otFormConstructor.
//
// Revision 1.297 2005/01/14 17:24:19 lulin
// - в _ProcessCommand добавлен параметр aForce - сигнализирующий, что такого ShortCut'а нету в VCM и что не надо умничать с обработкой комманды.
//
// Revision 1.296 2005/01/14 10:42:30 lulin
// - методы Get*ParentForm переехали в библиотеку AFW.
//
// Revision 1.295 2005/01/12 14:01:16 lulin
// - new methods: Tafw.BeginOp/EndOp.
//
// Revision 1.294 2004/12/16 08:15:55 mmorozov
// - форматирование кода;
// - warnings fix;
//
// Revision 1.293 2004/11/25 08:01:02 mmorozov
// bugfix: в TvcmComboBox не выставляем ItemIndex если Action.Caption = '';
//
// Revision 1.292 2004/11/23 10:29:42 am
// change: при поднятии попап меню подменяем ему WndProc с тем, чтобы нормально поднимался хелп.
//
// Revision 1.291 2004/11/18 16:29:55 lulin
// - отвязываем библиотеки от VCM без использования inc'ов.
//
// Revision 1.290 2004/11/17 17:05:34 mmorozov
// bugfix: если у вновь открытой формы было меньше кнопок чем у предыдущей формы, то кнопка закрыть области dock-а не была видна;
//
// Revision 1.289 2004/11/15 12:50:14 mmorozov
// change: method AdjustIfEmpty -> method UpdateEmpty(aUpdateVisibility : Boolean = True);
//
// Revision 1.288 2004/11/05 14:05:00 am
// change: новый тип - _vcm_otMenuButtonCombo. Полностью такой же, как vcm_otButtonCombo, но умеет показывать себя в меню.
//
// Revision 1.287 2004/10/28 11:17:49 mmorozov
// change: сигнатура TvcmCustomMenuManager.LoadGlyphSize;
// new: method TvcmCustomMenuManager.RestoreGlyphSize;
//
// Revision 1.286 2004/10/26 10:47:21 fireton
// - bug fix: не определялась автоматически глубина цвета для иконок
//
// Revision 1.285 2004/10/21 19:25:23 mmorozov
// new: TvcmDockPanelButton наследник TCustomToolbarButton97;
// new: properties TvcmCustomToolbarButton97 (DockButtonsImageList, BtnCloseImageIndex, BtnOpenImageIndex, BtnOpenNewWindowImageIndex);
// new: иконки области toolbar-а завязаны на новый imagelist;
//
// Revision 1.284 2004/10/21 16:08:56 lulin
// - cleanup: убрана ненужная переменная.
//
// Revision 1.283 2004/10/21 11:46:06 mmorozov
// bugfix: для Ttb97MoreButton размер не определяется;
//
// Revision 1.282 2004/10/21 09:47:29 mmorozov
// bugfix: определение размера toolbar-а и кнопок toolbar-а;
//
// Revision 1.281 2004/10/20 16:41:43 mmorozov
// new behaviour: при входе в компонент (ControlEnter) типа TFakeBox не вызывается TvcmAction(f_FocusControl.Action).LockExecute;
//
// Revision 1.280 2004/10/20 13:44:27 am
// bugfix: при SetFasten на доке дёргаем BeginUpdate\EndUpdate
//
// Revision 1.279 2004/10/20 10:40:43 lulin
// - new behavior: увеличиваем частоту использования пула объектов.
//
// Revision 1.278 2004/10/19 15:04:55 lulin
// - bug fix: не компилировалось.
//
// Revision 1.277 2004/10/19 13:23:27 lulin
// - переделки TvcmCustomMenuManager._f_SaveDockList на _TvcmObjectRefList.
//
// Revision 1.276 2004/10/19 12:04:22 mmorozov
// new: method TvcmCustomMenuManager.ToolbarButtonSize;
// new: устанавливаем TB97Ctls процедуру определения размеров кнопки;
//
// Revision 1.275 2004/10/15 13:39:45 lulin
// - bug fix: не всем кнопкам Toolbar'ов выставлялось свойство AutoSize.
//
// Revision 1.274 2004/10/15 12:39:08 am
// change: Открутил загрузку главного тулбара совместно с текущим
// change: отпала надобность в вычислении "веса" формы в зависимости от её положения в цепочке наследования (GetFormWeight)
//
// Revision 1.273 2004/10/13 16:19:02 mmorozov
// new: published properties _HistoryZones, SaveFormZones (TvcmMenuManager);
//
// Revision 1.272 2004/10/13 15:22:43 am
// bugfix: форма календарика умирала раньше времени
//
// Revision 1.271 2004/10/08 08:10:32 am
// bugfix: при загрузке из настроек иногда неправильно выставлялись индексы операций в тулбаре
//
// Revision 1.270 2004/10/07 11:49:41 lulin
// - не компилировалось без define _Nemesis.
//
// Revision 1.269 2004/10/05 14:42:05 am
// change: при загрузке операций из настроек, те, для которых нет записей в настройках, помещаем в конец тулбара и отбиваем разделителями, группируя по сущностям
//
// Revision 1.268 2004/10/04 15:15:57 am
// change: прикрутил к _TvcmCalendarForm "правильное" поведение с активизацией после потери фокуса, etc в модальном виде.
//
// Revision 1.267 2004/09/30 10:56:04 mmorozov
// bugfix: при изменении состава кнопок области докинга toolbar содержащий эти кнопки не менял размеры;
//
// Revision 1.266 2004/09/28 10:31:07 am
// change: выставляю всем edit'ам RestrictConsSpace (запрет ввода нескольких пробелов подряд)
//
// Revision 1.265 2004/09/27 11:33:08 fireton
// - bug fix: починка фокуса
//
// Revision 1.264 2004/09/24 10:40:04 am
// change: для combo операций, в случае использования в OnTest'ах (aParams._AsIU[_vcm_opItems] _As XIvcmStrings) - выставляем в комбобоксе IsList.
//
// Revision 1.263 2004/09/20 12:02:13 mmorozov
// opt: создаём TvcmDockPanelButtonLink по требованию;
//
// Revision 1.262 2004/09/17 11:22:58 lulin
// - параметр vcm_opStrings переименован в _vcm_opItems, и ему изменен тип с _IvcmHolder на IvcmStrings (!).
//
// Revision 1.261 2004/09/15 13:29:02 lulin
// - TvcmAction и TvcmWinControlActionLink переведен на "шаблон" l3Unknown.
//
// Revision 1.260 2004/09/14 09:14:23 lulin
// - cleanup: редко используемые поля убраны под define'ы.
// - упорядочено наследование.
// - поправлены имена.
//
// Revision 1.259 2004/09/13 15:50:27 lulin
// - cleanup: выкинул лишний модуль из Toolbar 97.
// - bug fix: за Мишей - не компилировался VCM.
//
// Revision 1.258 2004/09/13 14:52:39 lulin
// - bug fix: не компилировалось без L3.
// - bug fix: были перекрыты Destroy, а не Cleanup - из-за этого отьезжали Toolbar'ы.
//
// Revision 1.257 2004/09/13 12:17:42 lulin
// - new unit: vcmControl.
//
// Revision 1.256 2004/09/11 12:29:09 lulin
// - cleanup: избавляемся от прямого использования деструкторов.
// - new unit: vcmComponent.
//
// Revision 1.255 2004/09/10 10:39:29 lulin
// - закомментировал вчерашнюю оптимизацию с убиванием Handle, т.к. пока есть проблемы с фокусом.
//
// Revision 1.254 2004/09/09 16:43:30 mmorozov
// change: TvcmCustomMenuManager._RegisterChildInMenu (Удаляем windows окно, чтобы во время долгосрочных операций построения меню и toolbar-ов окна не прорисовывались. Окно формы восстанавливается в _TvcmEntityForm._Make);
//
// Revision 1.253 2004/09/09 13:56:28 lulin
// - эксперименты с уменьшением количества вызовов оконной процедуры в процессе создания новой формы (пока все закоментированно).
//
// Revision 1.252 2004/09/08 07:54:15 mmorozov
// new behaviour: продолжающую линию рисуем для dock-ов с любым Align;
//
// Revision 1.251 2004/09/08 07:36:10 am
// change: лочим тулбары в _MakeToolbarFromSettings точно так же, как в _MakeToolbar
//
// Revision 1.250 2004/09/07 16:19:45 law
// - перевел VCM на кшированные обьекты.
//
// Revision 1.249 2004/09/06 16:31:41 mmorozov
// change: TvcmDockPanel._CreateBtn;
//
// Revision 1.248 2004/09/06 07:06:28 mmorozov
// - не компилировалось, добавлены дефайны;
//
// Revision 1.247 2004/09/03 15:14:27 mmorozov
// new: class TvcmToolbarDockPanel;
// new: method TvcmDockDef.Paint;
// new: global procedure vcmPaintDockBottomLine;
//
// Revision 1.246 2004/09/03 11:44:20 mmorozov
// new: при построении toolbar-а спрашиваем у формы размер иконок, если маленький, то используем список с фиксированным размером;
//
// Revision 1.245 2004/09/03 10:17:39 am
// change: защитил разлочивание доков переменной _f_UnlockInProgress (проявилась ситуация, когда в процессе вызова EndDock, путём сложных манипуляций мы снова входили в Unlock).
//
// Revision 1.244 2004/09/02 17:17:46 mmorozov
// new: при создании первого toolbar-а вычисляем и запоминаем максимальную высоту toolbar-а с маленькими иконками и компонентами TvcmToolButton97, TvcmDateEdit, TvcmEdit;
// new: устанавливаем глобальную переменную TB97Tlbr.g_ToolbarSize для установки фиксированного размера toolbar-а;
// change: у кнопок в области toolbar-а нет рамки;
// change: MenuImages -> SmallImages;
//
// Revision 1.243 2004/09/01 10:32:36 fireton
// - bug fix: чистим _f_SaveDockList при удалении из _g_DockList (CQ00008981)
//
// Revision 1.242 2004/08/27 07:35:30 am
// change: доп параметр в _UserTypeByCaption - искать по Caption'у или _LongCaption'у.
//
// Revision 1.241 2004/08/25 14:25:30 mmorozov
// - не комплировалась библиотека;
//
// Revision 1.240 2004/08/25 09:17:52 am
// change: отложенное удаление тулбаров в ReloadToolbars
//
// Revision 1.239 2004/08/25 06:58:47 am
// change: дефайны для _TvcmCalendarForm
//
// Revision 1.238 2004/08/24 14:34:38 am
// new: _TvcmCalendarForm
//
// Revision 1.237 2004/08/19 13:36:17 fireton
// - добавление выбора глубины цвета для иконок
//
// Revision 1.236 2004/08/19 06:48:29 mmorozov
// bugfix: в специфическом случае кнопка закрытия окна не была прижата вправо, после запуска приложения (не используем AutoSize, считаем сами);
//
// Revision 1.235 2004/08/11 10:28:54 fireton
// - поддержка размера иконок
//
// Revision 1.234 2004/08/09 11:43:43 mmorozov
// bugfix: OnExecute вызывался на закрытие выпадающего окна календаря (без выбора даты);
//
// Revision 1.233 2004/08/06 16:04:13 mmorozov
// bugfix: не компилировалось с директивой _vcmNotNeedOvc;
//
// Revision 1.232 2004/08/06 13:45:01 mmorozov
// new: method TvcmEdit._ProcessCommand;
//
// Revision 1.231 2004/08/04 16:21:13 demon
// - cleanup: remove warnings and hints
//
// Revision 1.230 2004/08/04 12:00:17 am
// change: выставляю в наследнике TvtDateEdit свойство RestrictInvalidDate
//
// Revision 1.229 2004/08/03 12:37:06 am
// change: реализация UpdateAction в vcm-ном наследнике комбобокса
//
// Revision 1.228 2004/07/30 14:25:56 law
// - bug fix: отвалились иконки в контекстном меню.
//
// Revision 1.227 2004/07/30 09:08:40 law
// - bug fix: в контекстном меню остались "большие" иконки.
//
// Revision 1.226 2004/07/28 10:20:49 law
// - new prop: TvcmBaseMenuManager.MenuImages.
//
// Revision 1.225 2004/07/23 12:42:35 am
// change: при создании тулбара прописываем ему вес.
//
// Revision 1.224 2004/07/21 13:46:01 law
// - new event: TvcmBaseMenuManager.OnInitCommands.
//
// Revision 1.223 2004/07/21 13:02:54 am
// bugfix: TvcmDateEdit.CMTextChanged забыли message CM_TextChanged дописать.
//
// Revision 1.222 2004/07/15 11:46:28 am
// change: вынес SetFasten на уровень дока
//
// Revision 1.221 2004/07/14 14:41:53 law
// - optimization: перед созданием меню убиваем Handle окна - это существенно ускоряет процесс открытия нового окна.
//
// Revision 1.220 2004/07/13 11:25:53 am
// change: поменял логику режима "закрепить тулбары". Плавающие теперь можно таскать и дочить, после дока с тулбаром ничего сделать нельзя
//
// Revision 1.219 2004/07/13 07:22:15 am
// change: при сохранении тулбара, независимо от его состояния, сохраняем плавающие координаты
//
// Revision 1.218 2004/07/12 09:16:14 am
// change: при выборе "закрепить тулбары", автоматически дочим плавающие
//
// Revision 1.217 2004/06/17 12:52:16 am
// change: вытащил vcm-ориентированый код из комбобокса
//
// Revision 1.216 2004/06/16 09:35:57 am
// change: перевод TList на листы с подсчётом ссылок
//
// Revision 1.215 2004/06/02 10:20:43 law
// - удален конструктор Tl3VList.MakeIUnknown - пользуйтесь _Tl3InterfaceList._Make.
//
// Revision 1.214 2004/06/01 15:33:56 law
// - удалены конструкторы Tl3VList.MakeLongint, MakeLongintSorted - пользуйтесь _Tl3LongintList.
// - подчистил VCM, за сегодняшними переделками Маркова.
//
// Revision 1.213 2004/06/01 12:22:58 am
// new: чекнутые элементы с иконами в PopupMenu рисуются "вдавленными".
//
// Revision 1.212 2004/05/22 12:08:18 am
// bugfix: BackupOpStatus/RestoreOpStatus
//
// Revision 1.211 2004/05/21 05:47:15 am
// new: обработка сообщений от тулбара
//
// Revision 1.210 2004/05/19 12:55:44 am
// new _TvcmToolbarDef.LockDock - залочить док
// new TvcmCustomMenuManager.BackupOpStatus/RestoreOpStatus - сохранить/восстановить счётчик лока
// new TvcmCustomMenuManager.LockDocks - парная UnlockDocks скобка
//
// Revision 1.209 2004/04/26 07:25:15 mmorozov
// bugfix: при загрузке позиций toolbar-а проверяем что _TvcmEntityForm._UserTypes > 0;
//
// Revision 1.208 2004/04/22 11:03:46 mmorozov
// new behaviour: если при выходе из компонента редактирования его Text <> TvcmAction.Caption, то устанавливаем Text = TvcmAction.Caption;
//
// Revision 1.207 2004/04/16 14:36:32 am
// change: новый тип TvcmIconTextType - содержит "третье состояние" для IconText - дефолтное. (В этом состоянии операции одного типа соответствуют кнопки с иконками, а другим - с иконками и текстом)
//
// Revision 1.206 2004/04/16 08:49:52 mmorozov
// new: используем hint OnQuery;
//
// Revision 1.205 2004/04/14 12:43:09 mmorozov
// - оформляем код в стиле vcm;
// change: TDockPanel переименован в TvcmDockPanel;
// new: class TvcmDockPanelButtonLink;
// new: class TvcmDockPanelButton;
// new behaviour: при удалении формы с которой связана кнопка сбрасываем обработчики и скрываем кнопку;
//
// Revision 1.204 2004/04/07 06:37:14 am
// change: синтаксис
//
// Revision 1.203 2004/04/02 08:48:24 am
// change: PopupMenu в тулбаре у комбо, edit'ов и т.д.
//
// Revision 1.202 2004/04/01 15:11:34 am
// change: выставляем списковым комбобоксам isList
//
// Revision 1.201 2004/03/30 10:26:02 nikitin75
// не вызываем RefocusEntity из ControlExit - приводило к неправильной обработке _WM_SETFOCUS;
//
// Revision 1.200 2004/03/29 13:06:58 nikitin75
// + для bsDialog и bsSingle форм при изменении размеров TDockPanel ресайзем форму;
//
// Revision 1.199 2004/03/27 13:19:37 am
// bugfix к предыдушему bugfix: рано присваивал Parent'а плавающему тулбару
//
// Revision 1.198 2004/03/26 10:45:17 am
// change: BeginOp\EndOp прокидываются из TvcmDispatcher'а
// new: поддержка операции "закрепить панели инструментов" (кнопка получила доп. параметр - IconText)
// bugfix: правки, связанные с загрузкой позиций тулбаров и созданием "виртуальных" тулбаров (из диалога настройки)
//
// Revision 1.197 2004/03/24 14:16:47 law
// - bug fix: неправильно перенабирались несохраненные Toolbar'ы формы после настройки одного из них.
//
// Revision 1.196 2004/03/24 13:30:04 law
// - bug fix: неправильно определялся тип Toolbar'а (верхний, нижний, правый, левый).
//
// Revision 1.195 2004/03/23 15:05:06 am
// change: _PostBuild. aFollowDocks - при перезагрузке тулбаров, загрузить не только тулбары формы,
// но и все тулбары в тех доках, которые затронуты изменениями.
// bugfix: не грузим тулбары при "виртуальном" создании.
// bugfix: не прописываем parent'а тулбару при "виртуальном" создании
//
// Revision 1.194 2004/03/22 09:28:22 mmorozov
// new behavior: если toolbar создаётся для формы с ZoneType = vcm_ztForToolbarsInfo, то не создаем кнопки для окна (закрытие окна и т.д.);
//
// Revision 1.193 2004/03/17 15:30:38 am
// change: BeginUpdate\EndUpdate
//
// Revision 1.192 2004/03/16 16:56:04 mmorozov
// bugfix: стал возможен ввод двухсимвольного года в компонент даты;
//
// Revision 1.191 2004/03/16 11:33:16 mmorozov
// new: кнопки управления формой могут быть только в верхнем Dock-е;
//
// Revision 1.190 2004/03/16 09:06:27 am
// bugfix:
//
// Revision 1.189 2004/03/16 08:53:04 am
// new: Сохранение формы плавающего тулбара
// new: _g_DockList
//
// Revision 1.188 2004/03/15 10:43:26 mmorozov
// bugfix: несколько кнопок закрыть на форме;
//
// Revision 1.187 2004/03/12 13:57:38 law
// - bug fix: Toolbar'ы вылезали из модальной формы.
//
// Revision 1.186 2004/03/11 13:51:23 am
// change: поменялась логика сброса SmartAlign
//
// Revision 1.185 2004/03/05 10:33:52 am
// New: выставляем тулбару NearestParent
//
// Revision 1.184 2004/03/05 08:39:27 am
// new: TvcmCustomMenuManager.MergedToMainForm - смержены ли тулбары данной формы в главную форму.
//
// Revision 1.183 2004/03/04 08:04:03 am
// new: сохранение(_TvcmEntityForm.SaveToolbars)/восстановление(TvcmCustomMenuManager._PostBuild) положения, доков, etc.. тулбаров
//
// Revision 1.182 2004/03/03 12:25:14 law
// - bug fix: не очищалось Popup-menu - соответственно неправильно обрабатывались ShortCut'ы.
//
// Revision 1.181 2004/03/02 07:51:08 am
// bugfix: IfDef'ы
//
// Revision 1.180 2004/03/01 14:50:22 am
// new: функции-прокси для объектов, наследующихся не от TB97 (pm_getToolbar, ToolbarCount, etc..)
// change: кэширование создаваемых доков в f_DockList (для сброса SmartAlign и для того, чтобы не съезжали тулбары в процессе загрузки из настроек)
// new: сохранение позиций тулбаров
// change: некоторая чистка.
//
// Revision 1.179 2004/02/27 05:25:37 mmorozov
// - метод GetToolbarParent переименован в GetDockParent;
//
// Revision 1.178 2004/02/26 15:47:47 am
// new: _TvcmToolbarDef.AdjustIfEmpty - прячем тулбар, состоящий только из разделителей
//
// Revision 1.177 2004/02/26 15:00:56 mmorozov
// - чиска кода;
//
// Revision 1.176 2004/02/26 14:59:51 mmorozov
// new: класс TvcmMainToolbarPanel;
// new: method TvcmCustomMenuManager.GetToolbarParent;
// new: Dock на главной форме размещается на TvcmMainToolbarPanel;
//
// Revision 1.175 2004/02/24 12:55:52 am
// new: TvcmEdit теперь наследуется и от TFakeBox.
//
// Revision 1.174 2004/02/20 10:29:25 am
// *** empty log message ***
//
// Revision 1.173 2004/02/20 08:07:03 am
// bugfix: если в глубине тулбара возникает исключение при поиске контрола(OrderControls), то, несмотря на то,
// что оно гасится - в ряде случаев возникает непрорисовка.
//
// Revision 1.172 2004/02/19 14:55:23 am
// bugfix: Непрорисовка из-за показа\прятанья контролов в теле _TvcmToolbarDef.CustomArrangeControls
// (обойдено через посылку сообщения)
//
// Revision 1.171 2004/02/19 07:07:23 am
// change: CustomArrangeControls в _TvcmToolbarDef.
//
// Revision 1.170 2004/02/18 13:15:37 am
// *** empty log message ***
//
// Revision 1.168 2004/02/13 14:22:58 law
// - new behavior: убрано требование необходимости иконки у операции для того, чтобы она попадала в Toolbar.
//
// Revision 1.167 2004/02/13 14:04:14 law
// - new behavior: операции типа vcm_otCombo умеют попадать в меню.
//
// Revision 1.166 2004/02/13 08:57:59 law
// - bug fix: AV при показе Popup-меню.
// - extract method: _vcmMakeComboMenu.
//
// Revision 1.165 2004/02/12 12:15:42 law
// - убран ненужный with.
//
// Revision 1.164 2004/02/12 11:08:30 law
// - bug fix: не собирался пакет без _vcmUseTB97.
//
// Revision 1.163 2004/02/11 17:54:34 law
// - new behavior: возможность выбора Toolbar'а верхний/нижний etc.
//
// Revision 1.162 2004/02/11 14:27:55 law
// - change: задел на множественность Toolbar'ов.
//
// Revision 1.161 2004/02/11 12:18:38 law
// - new behavior: пересоздаем Toollbar'ы для всех заинтересованных форм.
//
// Revision 1.160 2004/02/10 17:09:38 law
// - new: в нулевом приближении сделана настройка Toolbar'ов при выборе объекта из списка.
//
// Revision 1.159 2004/02/10 15:55:30 law
// - new method: TvcmCustomMenuManager._UserTypeByCaption.
//
// Revision 1.158 2004/02/10 14:59:10 law
// - change: вместо пары UserType.Name/Caption используем интерфейс IvcmUserTypeDef.
//
// Revision 1.157 2004/02/10 12:59:49 law
// - change: IvcmUserTypesIterator теперь возвращает IvcmUserTypeDef.
//
// Revision 1.156 2004/02/09 15:19:04 law
// - new behavior: учитываем позиции кнопок, сохраненные в настройках.
//
// Revision 1.155 2004/02/09 14:00:29 law
// - new behavior: читаем из настроек и информацию об операциях модулей тоже.
//
// Revision 1.154 2004/02/09 12:14:12 law
// - new methods: TvcmCustomMenuManager._LoadButtonsFromSettings, _MakeToolbarFromSettings.
//
// Revision 1.153 2004/02/06 12:13:44 law
// - new behavior: сохраняем/читаем необходимость наличия разделителя.
//
// Revision 1.152 2004/02/05 19:40:09 law
// - new behavior: строим Toolbar'ы по сохраненным настройкам. Пока не учитываются разделители, операции модулей, порядок операций и неправильно читается первая копия основного окна. Завтра буду добивать это дело.
//
// Revision 1.151 2004/02/05 17:00:34 law
// - new behavior: вычитываем Toolbar'ы из настроек, но пока плюем на то, что прочитали.
//
// Revision 1.150 2004/02/05 14:50:34 mmorozov
// delete: неиспользуемый модуль в _uses;
//
// Revision 1.149 2004/02/05 14:08:26 mmorozov
// new: функциональность из TvcDateEdit перенесена в TvcmDateEdit;
//
// Revision 1.148 2004/02/04 16:49:16 law
// - new method: TvcmCustomMenuManager._BuildFormToolbars.
//
// Revision 1.147 2004/02/04 15:58:57 law
// - new method version: TvcmCustomMenuManager._BuildToolbar - не зависящий от EntityDef или ModuleDef - для "пользовательских" Toolbar'ов.
//
// Revision 1.146 2004/02/04 14:04:07 law
// - bug fix: разделители между кнопками стали выглядеть пристойно.
//
// Revision 1.145 2004/02/04 13:31:08 am
// new: _TvcmToolbarDef - функции для работы с разделителями
//
// Revision 1.144 2004/02/04 10:45:00 law
// - bug fix: не компилировалось без директивы _vcmUseTB97.
//
// Revision 1.143 2004/02/04 10:28:52 law
// - change: убрана "размазанность" класса _TvcmToolbarDef по разным define.
//
// Revision 1.142 2004/02/04 10:02:25 law
// - new behavior: вставляем разделители между группами кнопок.
//
// Revision 1.141 2004/02/03 14:30:07 mmorozov
// bugfix: пакет не компилировался, добавлены директивы компиляции;
//
// Revision 1.140 2004/02/03 11:56:07 mmorozov
// new behaviour: устанавливаем переменные l_QueryClose, l_QueryMaximized, l_QueryOpen в методе GetParentForDock (method TvcmCustomMenuManager._BuildToolbar);
//
// Revision 1.139 2004/02/03 10:10:16 mmorozov
// new: method TvcmDockDef.SetHandlers (создание и определение событий для кнопокна TvcmDockDef);
//
// Revision 1.138 2004/02/02 18:26:47 law
// - change: "задел" на множественность Toolbar'ов в пределах одного дока, одной формы.
//
// Revision 1.137 2004/02/02 18:20:42 law
// - new method: TvcmCustomMenuManager._MakeToolbar.
//
// Revision 1.136 2004/02/02 18:08:29 law
// - new method: TvcmCustomMenuManager._FillToolbar.
//
// Revision 1.135 2004/02/02 17:37:59 law
// - refactoring: "extract method" (в методеTvcmCustomMenuManager._BuildToolbar).
//
// Revision 1.134 2004/02/02 17:05:20 law
// - new param: TvcmCustomMenuManager._BuildToolbar - anIndex: Integer = 0.
//
// Revision 1.133 2004/02/02 16:58:22 law
// - new behavior: в режиме OneToolbarPerForm берем название Toolbar'а из UserType'а/формы.
//
// Revision 1.132 2004/02/02 16:45:28 law
// - new prop: TvcmCustomMenuManager.OneToolbarPerForm.
//
// Revision 1.131 2004/02/02 16:11:37 law
// - new method: TvcmDockDef._Make - фабричный метод учитывающий СЦЕНАРИЙ построения Toolbar'а.
//
// Revision 1.130 2004/02/02 15:37:52 law
// - bug fix: учитываем множественность Toolbar'ов на одной форме.
//
// Revision 1.129 2004/02/02 13:30:26 am
// new: более одного тулбара у формы
//
// Revision 1.128 2004/01/27 17:02:00 law
// - new prop: TevBaseMenuManager.Messages.
//
// Revision 1.127 2004/01/21 16:16:29 nikitin75
// + не прочищаем лишний раз фон: существенно сокращено моргание тулбара;
//
// Revision 1.126 2004/01/21 13:15:25 mmorozov
// new: property TvcmDateEdit.OnSelectDate;
// new: method TvcmDateEdit.DoCloseUp;
// new: при создании TvcmDateEdit связываем TvcmDateEdit.OnSelectDate с TvcmCustomMenuManager.ControlSelect если используемый тип календаря TvtDateEdit;
//
// Revision 1.125 2004/01/17 13:44:00 am
// change: дефолтные установки для TB97 (CloseMode, DisableAutoAlign)
//
// Revision 1.124 2004/01/16 17:49:47 law
// - new behavior: добавляем в Main Toolbar сначала кнопкиот Main формы, а потом только от модулей.
//
// Revision 1.123 2004/01/16 16:12:10 am
// bugfixes: передача фокуса при уходе с TB97
//
// Revision 1.122 2004/01/16 15:13:04 mmorozov
// new: method TvcmDateEditActionLink.IsCaptionLinked (см. комментарии в методе);
// bugfix: при выходе из компонента если не вызывался Action.UnlockExecute, то вызываем его;
//
// Revision 1.121 2004/01/16 13:26:39 law
// - bug fix: в основной Toolbar не попадали операции основной формы.
//
// Revision 1.120 2004/01/16 10:13:04 am
// change: косметические правки ExecuteHandler
//
// Revision 1.119 2004/01/16 08:04:20 am
// *** empty log message ***
//
// Revision 1.118 2004/01/16 07:40:55 am
// bugfix: зависимость TB97 от vcm
//
// Revision 1.117 2004/01/14 12:42:16 law
// - new behavior: вызываем TvcmWinControlActionLink._ParamsChanged для TvcmDateEdit.
//
// Revision 1.116 2004/01/09 14:48:46 mmorozov
// - по умолчанию тип TvcmDateEdit определяется директивой _vcmUseStdDate;
//
// Revision 1.115 2004/01/09 13:03:37 mmorozov
// no message
//
// Revision 1.114 2004/01/09 12:20:35 law
// - bug fix: Для операций типа vcm_otTyper при создании формы сразу вызывается OnExecute - а это не правильно (CQ OIT5-5803).
//
// Revision 1.113 2004/01/08 19:03:00 mmorozov
// new: директива _vcmUseStdDate - использование TDateTimePicker;
// new: директива _vcmUseStdDate - использование TvtDateEdit;
// new: использование TvtDateEdit в качестве предка TvcmDateEdit;
//
// Revision 1.112 2004/01/06 12:40:35 am
// change: выставляем констрейнт combotree после присвоения parent'а
//
// Revision 1.111 2004/01/06 12:32:25 law
// - change: поправлен комментарий.
//
// Revision 1.110 2003/12/30 13:41:53 law
// - bug fix: не переобновляем Action'ы Popup-Menu привязанного к кнопке, когда это меню открыто.
//
// Revision 1.109 2003/12/30 10:03:55 law
// - optimization: при создании второго Mainf-окна не создаем по новой все формы сущностей (CQ OIT5-5628).
//
// Revision 1.108 2003/12/29 14:55:36 mmorozov
// new: собираем события _TvcmEntityForm OnQueryMaximized, OnQueryOpen при MergeToolbarsToContainer = True;
//
// Revision 1.107 2003/12/26 16:51:17 law
// - new behavior: переделана логика обработки BottonCombo - теперь если меню нету, то и стрелки вниз нету.
// - bug fix: иногда при восстановлении из истории портился Caption главного окна.
//
// Revision 1.106 2003/12/26 06:52:29 am
// new: ограничение каждому комбобоксу
//
// Revision 1.105 2003/12/25 12:00:03 mmorozov
// new: кнопка открыть в области докинга;
//
// Revision 1.104 2003/12/25 07:32:15 mmorozov
// - устанавливаем высоту toolbar-а как у Dock97;
//
// Revision 1.103 2003/12/25 06:46:51 mmorozov
// new: TDockPanel - класс создан для того чтобы toolbar-ы в области Dock97 при изменении размеров последнего учитывали находящиеся в нем кнопки;
//
// Revision 1.102 2003/12/24 16:19:53 law
// - new behavior: выставляем свойство AutoWidth.
//
// Revision 1.101 2003/12/24 15:38:59 law
// - new behavior: отключил задержку (CQ OIT5-5524).
//
// Revision 1.100 2003/12/22 14:47:59 am
// new: AutoSize для тулбаров = False
//
// Revision 1.99 2003/12/16 14:18:12 mmorozov
// - интерфейсная настройка toobar-а для TvcmDockDef;
//
// Revision 1.98 2003/12/16 13:01:06 mmorozov
// - поправлен размер TvcmDockDef при отсутствующих toolbar-ах с кнопками "закрыть", "развернуть";
//
// Revision 1.97 2003/12/16 08:41:21 mmorozov
// + иконы на кнопках в области TvcmDockDef;
//
// Revision 1.96 2003/12/15 19:26:40 mmorozov
// - для кнопок в области Dock97 используется _TToolBar;
// - добавлено создание кнопки "развернуть";
// - удален класс TCloseBtn;
//
// Revision 1.95 2003/12/11 17:59:10 law
// - new const: _vcm_opPlainLevel.
// - new behavior: строим меню "отбитое пробелами (как в Гаранте)" начиная с уровня вложенности _vcm_opPlainLevel (CQ OIT5-5467).
//
// Revision 1.94 2003/12/09 17:35:12 law
// - bug fix: из _uses убрана ссылка на ненужный модуль.
//
// Revision 1.93 2003/12/09 16:56:05 law
// - new behavior: присвоение Root'а повесил на _ParamsChanged.
//
// Revision 1.92 2003/12/09 16:28:21 law
// - bug fix: выставляем ShowRoot раньше CuurrentNode.
//
// Revision 1.91 2003/12/09 16:12:47 law
// - new operation param: vcm_opShowRoot.
//
// Revision 1.90 2003/12/09 15:45:56 law
// - bug fix: в OnTest не подавалась корректная CurrentNode.
//
// Revision 1.89 2003/12/09 14:22:59 law
// - new behavior: выставляем CurrentNode в ComboTree.
//
// Revision 1.88 2003/12/09 10:27:54 law
// - change: восстановлен код для запроса дерева для ComboTree, который закомментировал М. Морозов.
//
// Revision 1.87 2003/12/09 06:19:25 mmorozov
// - закоментирована не работающая часть кода в процедуре _SetStringsFromAction;
//
// Revision 1.86 2003/12/08 15:21:13 am
// *** empty log message ***
//
// Revision 1.85 2003/12/08 13:16:05 am
// new: функция установки рута в combotree - vcmSetRoot.
//
// Revision 1.84 2003/12/05 14:57:52 law
// - bug fix: убран странный префикс vcm - ни SetRoot, ни _Il3Node к vcm'му собственно говоря отношения не имеют.
//
// Revision 1.83 2003/12/05 14:48:47 am
// change: для combotree выставление caption не дублируется итемом в Items.
//
// Revision 1.82 2003/12/03 17:42:11 law
// - bug fix: не создаем "псевдо"-строк при подкладывании дерева.
//
// Revision 1.81 2003/12/03 17:14:53 law
// - change: в процессе разборок с ComboTree избавился от дублирующегося кода.
//
// Revision 1.80 2003/12/02 14:53:53 law
// - bug fix: восстановлена функциональность MDI-приложения.
//
// Revision 1.79 2003/12/02 12:10:00 law
// - new behavior: сделано подкладывание дерева в ComboTree.
//
// Revision 1.78 2003/11/30 14:36:43 law
// - new behavior: добавлена генерация констант для операций модуля.
//
// Revision 1.77 2003/11/28 17:05:26 law
// - bug fix: подточил для использования ComboTree.
//
// Revision 1.76 2003/11/28 16:36:18 law
// - new behavior: используем Combo-Tree в VCM.
//
// Revision 1.75 2003/11/27 18:55:57 law
// - new prop: TvcmBaseMenuManager._AppForms - список всех форм приложения.
//
// Revision 1.74 2003/11/27 15:56:22 law
// - new prop: _TvcmEntityForm.OnNeedUpdateStatus.
//
// Revision 1.73 2003/11/27 11:29:12 law
// - bug fix: защищаем TCustomToolbarButton97.Click от уничтожения собственной формы.
//
// Revision 1.72 2003/11/24 16:30:46 law
// - new behavior: Combo-кнопке если нету списка строк, то строим Popup-меню по узлу дерева.
//
// Revision 1.71 2003/11/21 15:34:03 mmorozov
// - если у TvcmDockDef определена кнопка "Закрыть" и нет ни одного Toolbar-а, то при изменении размеров устанавливается константная высота;
//
// Revision 1.70 2003/11/21 13:23:44 mmorozov
// - исправлена ошибка в названии директивы;
//
// Revision 1.69 2003/11/21 13:10:33 mmorozov
// - реализована возможность использовать компонент TElDateTimePicker для vcm операции типа opDate;
//
// Revision 1.68 2003/11/19 11:38:25 law
// - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано.
//
// Revision 1.67 2003/11/18 17:59:42 law
// - new behavior: в параметре _vcm_eopNode передаем выбранный узел дерева.
//
// Revision 1.66 2003/11/18 16:40:31 law
// - new behavior: для Root'а не делаем подменю.
// - bug fix: для компонент связанных в Run-time с сущностями не присваивалось контекстное меню.
//
// Revision 1.65 2003/11/18 15:21:15 law
// - bug fix: не привязываем Action к подменю.
//
// Revision 1.64 2003/11/18 13:40:20 migel
// - bug fix: не учитывалась вложенность нод.
//
// Revision 1.63 2003/11/17 15:27:56 law
// - new behavior: делаем иерархическое меню у кнопки, для которой определены _SubNodes (нажатие пока не работает).
//
// Revision 1.62 2003/11/13 13:49:09 law
// - bug fix: привел тестовый проект в актуальное состояние.
//
// Revision 1.61 2003/11/13 09:17:09 law
// - новый тип операции - vcm_otTyper, то же что и vcm_otEdit, но с непосредственной раакцией на ввод, на не по Esc/Edit.
//
// Revision 1.60 2003/11/12 13:08:28 law
// - new behavior: сделана возможность определять на форме до 4-х областей докинга.
// - new behavior: сделано рекурсивное объединение toolbar'ов child->container->container ...
//
// Revision 1.59 2003/11/05 15:24:08 law
// - new class: TvcmDateEdit.
//
// Revision 1.58 2003/11/05 15:18:09 law
// - new behavior: добавляем в Toolbar операцию типа vcm_otEdit.
//
// Revision 1.57 2003/10/28 09:57:48 law
// - new behavior: пункты основного меню строятся на основе MainMenuItems.
//
// Revision 1.56 2003/10/28 09:07:35 law
// - new prop: TvcmCustomMenuManager.MainMenuItems.
//
// Revision 1.55 2003/10/27 10:46:41 law
// - change: заплатка для Эвереста и Архивариуса.
//
// Revision 1.54 2003/10/22 16:05:52 mmorozov
// - добавлена возможность использования ElToolbar (define _vcmUseElPack);
//
// Revision 1.53 2003/10/17 15:37:34 mmorozov
// - TCloseBtn наследник от TCustomControl;
//
// Revision 1.52 2003/10/16 15:04:43 mmorozov
// no message
//
// Revision 1.51 2003/10/16 12:47:15 mmorozov
// + компонент TCloseSpeedButton который отрисовывает стандартную кнопку закрытия окна;
// + методы в TvcmDockDef (PlaceCloseBtn, Resize, _CreateCloseBtn);
// - в методе TvcmCustomMenuManager._BuildToolbar проверяется являетс я ли форма, для которой создается Toolbar, _TvcmEntityForm и выполняется ли _TvcmEntityForm._CanClose = vcm_ccEnable, если да то в зоне докинга создается кнопка закрытия окна;
//
// Revision 1.50 2003/10/08 11:14:12 law
// - new directive: _vcmUseElCombo.
//
// Revision 1.49 2003/10/03 09:13:59 law
// - bug fix: очищаем PopupMenu в подходящий момент.
//
// Revision 1.48 2003/10/02 17:41:53 law
// - bug fix: убрал очистку меню, т.к. оказалось, что отъехала обработка операций. Будем по новой разбираться.
//
// Revision 1.47 2003/10/02 15:59:14 law
// - new class: _TvcmPopupMenu.
// - bug fix: очищаем Popup-Menu сразу после его вызова.
//
// Revision 1.46 2003/09/05 15:05:01 law
// - new behavior: уменьшен размер поля для ввода даты.
//
// Revision 1.45 2003/09/03 16:00:42 law
// - new operation type: _vcm_otButtonPopup.
//
// Revision 1.44 2003/09/03 07:50:21 law
// - new behavior: для vcm_otButtonCombo в первый параметр OnExecute кладем номер выбранной строки (0 - сама кнопка, 1..N - пункт меню).
//
// Revision 1.43 2003/09/02 17:10:40 law
// - new behavior: для vct_otButtonCombo сделано заполнение выпадающего меню.
//
// Revision 1.42 2003/09/02 16:12:24 law
// - new const: vcm_otButtonCombo.
//
// Revision 1.41 2003/09/01 12:51:16 law
// - new const: vcm_otEditCombo.
// - new behavior: теперь есть возможность разделять редактируемые и нередактируемые выпадающие списки.
//
// Revision 1.40 2003/08/01 11:46:08 law
// - bug fix: не "залипали" кнопки.
//
// Revision 1.39 2003/08/01 09:36:17 law
// - new behavior: при настройке toolbar'ов убраны лишние разделители.
//
// Revision 1.38 2003/07/28 12:27:14 law
// - new behavior: учитывае разделители при настройке Toolbar'ов.
//
// Revision 1.37 2003/07/28 11:42:25 law
// - new behavior: в форму настройки Toolbar'ов выводим список пользовательских типов объектов.
//
// Revision 1.36 2003/07/25 17:51:57 law
// - new behavior: начал получать список UserType'ов.
//
// Revision 1.35 2003/07/25 14:12:26 law
// - new behavior: разрешено пользователю вставлять кнопки без иконок в toolbar.
//
// Revision 1.34 2003/07/25 13:39:24 law
// - new behavior: toolbar'ы обновляются после настройки.
//
// Revision 1.33 2003/07/25 12:11:10 law
// - new behavior: в форму настроек передаем менеджер меню.
//
// Revision 1.32 2003/07/24 16:04:09 law
// - new behavior: набираем список доступных операций.
//
// Revision 1.31 2003/07/24 13:07:15 law
// - new prop: IvcmOperationDef._ExcludeUserTypes.
//
// Revision 1.30 2003/07/24 12:19:02 law
// - new behavior: сделана возможность выводить текст на кнопках (vcm_otTextButton).
//
// Revision 1.29 2003/07/24 11:46:58 law
// - bug fix: били по памяти.
//
// Revision 1.28 2003/07/24 11:35:09 law
// - new prop: _TvcmEntityForm._ToolbarPos.
//
// Revision 1.27 2003/07/23 15:36:31 law
// - new behavior: теперь у toolbar'а вызывается форма настройки (она пока ничего не делает).
//
// Revision 1.26 2003/07/17 14:06:34 law
// - new behavior: при использовании Toolbar 97 восстановлена нормальная логика Docking'а.
//
// Revision 1.25 2003/07/17 12:55:53 law
// - new behavior: избавляемся от дырок между toolbar'ами, при пропадании кнопок.
//
// Revision 1.24 2003/07/17 08:52:38 nikitin75
// _uses ExtCtrls перенес в interface секцию;
//
// Revision 1.23 2003/07/16 18:32:25 law
// - change: вчерне прикрутил Toolbar97 к VCM.
//
// Revision 1.22 2003/07/07 18:02:05 demon
// - bug fix: FormChange дергался уже когда MenuManager был уничтожен - был AV.
//
// Revision 1.21 2003/04/30 12:18:49 law
// - bug fix: объединенные Toolbar'ы не "вдочивались" обратно.
//
// Revision 1.20 2003/04/29 12:00:45 law
// - new prop: _TvcmEntityForm.MergeToolbarsToContainer.
//
// Revision 1.19 2003/04/24 15:47:26 law
// - new behavior: привязал кнопки дочернего окна только к сущностям этого окна, а не к сущностям текущей формы.
//
// Revision 1.18 2003/04/24 14:53:53 law
// - новая сборка dll.
// - изменилися формат вызова eeGetGenerator, eeGetFileGenerator.
//
// Revision 1.17 2003/04/24 14:29:48 law
// - новая сборка dll.
// - изменилися формат вызова eeGetGenerator, eeGetFileGenerator.
//
// Revision 1.16 2003/04/22 19:02:06 law
// - new behavior: отказываемся от MDI форм при включенном флаге _SDI.
//
// Revision 1.15 2003/04/22 18:20:53 law
// - bug fix: оттестировано свойство TvcmMainForm._SDI.
//
// Revision 1.14 2003/04/22 17:33:42 law
// - new prop: TvcmMainForm._SDI.
//
// Revision 1.13 2003/04/22 15:00:30 law
// - bug fix: оттестировал вставку форм в контейнер.
//
// Revision 1.12 2003/04/22 14:03:00 law
// - new behavior: сделана обработка операций, описанных на основной форме.
//
// Revision 1.11 2003/04/09 15:52:34 law
// - new operation type: vcm_otDate.
//
// Revision 1.10 2003/04/09 14:51:33 law
// - new behavior: сделал обработку списка строк у ComboBox'а.
//
// Revision 1.9 2003/04/09 13:08:13 law
// - new behavior: в нулевом приближении сделал обработку операции с типом vcm_otCombo.
//
// Revision 1.8 2003/04/09 08:57:34 law
// - экспериментируем с ComboBox в Toolbar'е.
//
// Revision 1.7 2003/04/08 12:34:46 law
// - new prop: IvcmOperationDef.Options.
// - new prop: TvcmOperationsCollectionItem.Options.
//
// Revision 1.6 2003/04/07 15:10:48 law
// - bug fix: сделано, чтобы компилировалось под Builder'ом.
//
// Revision 1.5 2003/04/07 14:16:15 law
// - new behavior: не показываем Toolbar'ы без кнопок.
//
// Revision 1.4 2003/04/07 14:05:57 law
// - new behavior: сделана возможность иметь Toolbar'ы в дочерних окнах.
//
// Revision 1.3 2003/04/04 15:37:59 law
// - new behavior: сделаны Toolbar'ы.
//
// Revision 1.2 2003/04/04 13:51:04 law
// - new prop: TvcmMenuManger.MenuOptions.
//
// Revision 1.1 2003/04/01 12:54:44 law
// - переименовываем MVC в VCM.
//
// Revision 1.9 2003/03/26 14:58:05 law
// - change: добавляем ActionList по умолчанию для всей библиотеки.
//
// Revision 1.8 2003/03/20 12:30:01 law
// - new behavior: сделана обработка контекстных операций.
//
// Revision 1.7 2003/03/19 17:11:15 law
// - new behavior: операции контекстного меню привязываем именно к сущности того управляющего элемента, над которым меню вызвали.
//
// Revision 1.6 2003/03/19 16:31:51 law
// - new behavior: сделана более интеллектуальная сборка контекстного меню.
//
// Revision 1.5 2003/03/19 12:46:43 law
// - new behavior: более интеллектуальное поведение TvcmCustomMemoryManager.
//
// Revision 1.4 2003/03/18 13:40:41 law
// - new property: TvcmCustomMenuManager.NeedContextEntitiesMenu.
//
// Revision 1.3 2003/03/18 13:31:56 law
// - new behavior: теперь MainForm не надо ставить FormStyle в fsMDIForm.
//
// Revision 1.2 2003/03/17 12:24:50 law
// - new behavior: в нулевом приближении сделана автоматическая сборка контекстного меню.
//
// Revision 1.1 2003/03/14 14:55:46 law
// - new units: vcmBaseMenuManager, vcmMenuManager.
//
{ Объявления:
_vcmUseElPack - использовать компоненты ElPack;
_vcmUseTB97 - использовать компоненты Toolbar97;
_vcmUseStd - использовать стандартные компоненты Delphi;
_vcmUseVTDate - использовать календарь TvtDateEdit;
_vcmUseStdDate - использовать календарь TDateTimePicker; }
{$Include vcmDefine.inc }
interface
uses
vcmToolbar,
Windows,
Classes,
Menus,
ActnList,
Controls,
Forms,
ComCtrls,
ExtCtrls,
Messages,
ImgList,
vcmUtils,
l3Interfaces,
l3SimpleObjectRefList,
l3Types,
l3Base,
afwInterfaces,
IafwMenuUnlockedPostBuildPtrList,
vtDateEdit,
tb97,
tb97ctls,
tb97tlbr,
tb97vt,
TB97ExtInterfaces,
evButton,
vcmExternalInterfaces,
vcmUserControls,
vcmInterfaces,
vcmBase,
vcmBaseMenuManager,
vcmEntityForm,
vcmMenus,
vcmAction,
vcmBaseCollectionItem,
vcmMenuItemsCollection,
vcmLocalInterfaces,
vcmForm,
vcmControl,
vcmToolbarMenuRes,
vcmPopupMenuPrim,
vcmEntitiesDefIteratorForContextMenu
;
type
TvcmDockDef = vcmToolbar.TvcmDockDef;
TvcmDockPanel = vcmToolbar.TvcmDockPanel;
TvcmDockPanelButton = vcmToolbar.TvcmDockPanelButton;
TvcmToolbarDockPanel = vcmToolbar.TvcmToolbarDockPanel;
TvcmToolbar = vcmToolbar.TvcmToolbar;
TvcmToolbarDef = vcmToolbar.TvcmToolbarDef;
TvcmSeparatorDef = vcmToolbar.TvcmSeparatorDef;
TvcmDockContainer = class(TPanel)
{* Панель используемая для размещения главной панели инструментов формы. }
public
// public
constructor Create(AOwner : TComponent);
override;
{-}
end;//TvcmDockContainer
{$IfDef vcmUseSettings}
TvcmButtonDef = record
rPos : Cardinal;
rEn : IvcmOperationalIdentifiedUserFriendlyControl;
rOp : IvcmOperationDef;
rOptions : TvcmOperationOptions;
rNeedSep : Boolean;
rIconText : Boolean;
rLoaded : Boolean;
end;//TvcmButtonDef
TvcmButtonDefs = array of TvcmButtonDef;
{$EndIf vcmUseSettings}
TvcmToolButtonDefActionLink = class(TevCustomButtonActionLink, IvcmActionLink)
protected
// interface methods
// IvcmActionLink
procedure ParamsChanged(const anAction: IvcmAction);
{-}
procedure ParamsChanging(const anAction: IvcmAction);
{-}
public
destructor Destroy;
override;
{-}
end;//TvcmToolButtonDefActionLink
TvcmToolButtonDef = class(TevButton)
protected
// internal methods
function HackCheck: Boolean;
override;
{-}
function NeedAutoDown: Boolean;
override;
{-}
function AutoAllUp: Boolean;
override;
{-}
function GetActionLinkClass: TControlActionLinkClass;
override;
{-}
public
function isIconText: Boolean;
{-}
end;//TvcmToolButtonDef
TvcmMenuOption = (vcm_moEntitiesInMainMenu, vcm_moEntitiesInTopMainMenu,
vcm_moEntitiesInChildMenu, vcm_moEntitesInContextMenu);
{-}
TvcmMenuOptions = set of TvcmMenuOption;
{-}
TvcmToolbarOption = (vcm_toModulesInMainToolbar, vcm_toEntitiesInMainToolbar,
vcm_toEntitiesInChildToolbar);
{-}
TvcmToolbarOptions = set of TvcmToolbarOption;
{-}
const
vcm_DefaultMenuOptions = [vcm_moEntitiesInMainMenu, vcm_moEntitiesInTopMainMenu];
vcm_DefaultToolbarOptions = [vcm_toModulesInMainToolbar, vcm_toEntitiesInMainToolbar];
type
TvcmIconTextType = (vcm_itDefault, vcm_itIcon, vcm_itIconText);
TvcmGlyphColordepth = (vcm_gcAuto, vcm_gc16, vcm_gc256, vcm_gcTrueColor);
TvcmPopupMenu = class(TvcmPopupMenuPrim)
private
// private fields
f_InPopup : Boolean;
public
// public methods
procedure Popup(X, Y: Integer);
override;
{-}
function IsShortCut(var Message: TWMKey): Boolean;
override;
{-}
procedure ClearInPopup;
{-}
end;//TvcmPopupMenu
TvcmButtonPopupMenu = class(TvcmPopupMenuPrim)
end;//TvcmButtonPopupMenu
TvcmCustomMenuManager = class(TvcmBaseMenuManager)
private
// internal fields
f_MenuOptions : TvcmMenuOptions;
f_ToolbarOptions : TvcmToolbarOptions;
f_Popup : TvcmPopupMenu;
f_PopupForm : TvcmEntityForm;
f_Actions : TCustomActionList;
f_FocusControl : TWinControl;
f_InEnter : Boolean;
f_WasDrop : Boolean;
f_UserTypes : TvcmInterfaceList;
f_MainMenuItems : TvcmMenuItemsCollection;
f_TickCount : Cardinal;
f_UserTypesLoaded : Boolean;
f_IsUnlockExecute : Boolean;
f_OneToolbarPerForm : Boolean;
f_SaveDockList : Tl3SimpleObjectRefList;
f_SaveLockCounter : TvcmLongintList;
f_LockCounter : Integer;
f_UnlockInProgress : Integer;
f_FastenToolbars : Integer;
f_GlyphColordepth : TvcmGlyphColordepth;
f_SmallToolbarSize : Integer;
f_MaxControlToolbarSize : Integer;
f_DiffSize : Integer; // К убиению
{* - разница между размером компонента с максимальной высотой и
toolbar-ом. }
f_ButtonHeight : Integer;
f_OnGlyphSizeChanged : TNotifyEvent;
f_OnGlyphColordepthChanged : TNotifyEvent;
f_GlyphSize : TvcmGlyphSize;
f_DockButtonsImageList : TCustomImageList;
f_BtnCloseImageIndex : TImageIndex;
f_BtnOpenImageIndex : TImageIndex;
f_BtnOpenNewWindowImageIndex : TImageIndex;
f_LockList: TIafwMenuUnlockedPostBuildPtrList;
{$IfDef vcmUseSettings}
f_MainToolbarDefs : array [TvcmEffectiveToolBarPos] of record
rVisibleLoaded : Boolean;
rVisible : Boolean;
rButtons : TvcmButtonDefs;
rUserType : IvcmUserTypeDef;
rToolbarName : String;
end;
{$EndIf vcmUseSettings}
private
// private methods
procedure OverridePopupMenu(const aForm: TCustomForm);
{-}
protected
// property methods
procedure pm_SetDockButtonsImageList(const Value : TCustomImageList);
{-}
procedure pm_SetActions(anActions: TCustomActionList);
{-}
procedure pm_SetMainMenuItems(aValue: TvcmMenuItemsCollection);
{-}
procedure pm_SetGlyphSize(const Value: TvcmGlyphSize);
{-}
procedure pm_SetGlyphColordepth(const Value: TvcmGlyphColordepth);
{-}
protected
// internal methods
function ToolbarButtonSize(aToolbarButton : TCustomToolbarButton97;
var aSize : Integer) : Boolean;
overload;
{* - по параметрам кнопки определяет её высоту. }
procedure ToolbarButtonSize(aToolbarButton : TCustomToolbarButton97);
overload;
{* - устанавливает ширину и высоту кнопки. }
procedure ToolbarSize(aToolbar : TCustomToolbar97;
var aSize : Integer);
{* - определяет размер toolbar-а. }
procedure RefocusEntity;
{-}
procedure RestoreControlText(Sender: TObject);
{-}
procedure ChangeEntityText(Sender: TObject);
{-}
procedure ChangeTyperText(Sender: TObject);
{-}
procedure ControlKeyDown(Sender : TObject;
var Key : Word;
Shift : TShiftState);
{-}
procedure ControlEnter(Sender: TObject);
{-}
procedure ControlExit(Sender: TObject);
{-}
procedure ControlDown(Sender: TObject);
{-}
procedure DateDown(Sender: TObject);
{-}
procedure ComboDown(Sender: TObject);
{-}
procedure ControlSelect(Sender: TObject);
{-}
procedure FormChange(Sender: TObject);
{-}
procedure DoPopup(Sender: TObject);
{-}
function CheckPopup(const anEntityDef: IvcmEntityDef): IvcmEntity;
{-}
function GetToolbarName(aForm : TvcmEntityForm;
const aDef : IvcmOperationalIdentifiedUserFriendlyControl;
anIndex : Integer): String;
{-}
{$IfNDef DesignTimeLibrary}
function BuildToolbar(aForm : TvcmEntityForm;
const aDef : IvcmOperationalIdentifiedUserFriendlyControl;
anIndex : Integer
// - порядковый номер Toolbar'а (для огранизации нескольких Toolbar'ов в одном доке)
): TvcmToolbarDef;
overload;
{-}
{$EndIf DesignTimeLibrary}
procedure FillToolbar(aForm : TvcmEntityForm;
var aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOperations : IvcmOperationsDefIterator;
const anOptions : TvcmOperationOptions);
{-}
procedure CheckToolbar(var aToolBar : TvcmToolbarDef);
{-}
{$IfNDef DesignTimeLibrary}
function MakeToolbar(aForm : TvcmEntityForm;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOptions : TvcmOperationOptions;
anExcludePoses : TvcmEffectiveToolBarPoses): Boolean;
{-}
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
procedure BuildEntitiesToolbars(aForm : TvcmEntityForm;
const anEntities : IvcmEntitiesDefIterator;
const anOptions : TvcmOperationOptions;
anExcludePoses : TvcmEffectiveToolBarPoses);
{-}
{$EndIf DesignTimeLibrary}
{$IfDef vcmUseSettings}
function LoadButtonsFromSettings(const aUserType : IvcmUserTypeDef;
const aToolbar : String;
AddUnsavedButton: Boolean;
var theButton : TvcmButtonDef;
var theButtons : TvcmButtonDefs): Boolean;
{-}
procedure MakeToolbarFromSettings(aForm : TvcmEntityForm;
const aToolbarName : String;
aPos : TvcmEffectiveToolBarPos;
const anOptions : TvcmOperationOptions;
const theButtons : TvcmButtonDefs);
{-}
procedure MakeMainToolbarFromSettings(aForm : TvcmEntityForm);
{-}
{$EndIf vcmUseSettings}
{$IfNDef DesignTimeLibrary}
procedure BuildFormToolbars(aForm : TvcmEntityForm;
const anOptions : TvcmOperationOptions);
{-}
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
procedure BuildMainToolbars(aForm : TvcmEntityForm;
const aModuleDef : IvcmModuleDef);
{* - создает Toolbar'ы основной формы. }
{$EndIf DesignTimeLibrary}
procedure CheckUserTypes;
{-}
procedure BuildUserTypes(const aModuleDef : IvcmModuleDef);
{-}
procedure ToolbarsGetSiteInfo(Sender : TObject;
DockClient : TCustomToolWindow97;
var CanDock : Boolean);
{-}
procedure Cleanup;
override;
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
function UnlockInProgress: Boolean; override;
procedure BackupOpStatus;
override;
{-}
procedure RestoreOpStatus;
override;
{-}
procedure FastenToolbars;
override;
{-}
function GetFastenMode: Boolean;
override;
{-}
procedure BeginOp;
override;
{-}
procedure EndOp;
override;
{-}
function GetOpLock: Boolean;
override;
{-}
//function MergedToMainForm(aForm: TvcmEntityForm): Boolean;
//override;
{-}
procedure PostBuild(aForm : TvcmEntityForm;
aFollowDocks : Boolean);
override;
{-}
{$IfNDef DesignTimeLibrary}
procedure RegisterModuleInMenu(aForm : TvcmEntityForm;
const aModuleDef : IvcmModuleDef);
override;
{* - регистрирует модуль в меню, toolbar'ах, etc. }
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
procedure MainCreated(aForm: TvcmEntityForm);
override;
{-}
{$EndIf DesignTimeLibrary}
procedure RegisterMainInMenu(aForm: TvcmEntityForm);
override;
{* - регистрирует основную форму в меню, toolbar'ах, etc. }
{$IfNDef DesignTimeLibrary}
procedure RegisterChildInMenu(aForm: TvcmEntityForm);
override;
{* - регистрирует дочернюю форму в меню, toolbar'ах, etc. Для перекрытия в потомках. }
{$EndIf DesignTimeLibrary}
function BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aModuleDef : IvcmModuleDef;
const anEntityDef : IvcmEntityDef;
const anOp : IvcmOperationDef;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType = vcm_itDefault): TControl;
overload;
{-}
function BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aModuleDef : IvcmModuleDef;
const anEntityDef : IvcmEntityDef;
const anOp : IvcmOperationDef;
const anOpOptions : TvcmOperationOptions;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType = vcm_itDefault): TControl;
overload;
{-}
function BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOp : IvcmOperationDef;
const anOpOptions : TvcmOperationOptions;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType = vcm_itDefault): TControl;
overload;
{-}
function BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOp : IvcmOperationDef;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType = vcm_itDefault): TControl;
overload;
{-}
function BuildAction(const aModuleDef : IvcmModuleDef;
const anOpDef : IvcmOperationDef): TCustomAction;
overload;
{-}
function BuildAction(const anOwner : TComponent;
const anEntity : IvcmEntity;
const anEntityDef : IvcmEntityDef;
const anOpDef : IvcmOperationDef;
anOptions : TvcmOperationOptions): TCustomAction;
overload;
{-}
function BuildSeparator(aToolBar: TvcmToolbarDef): TControl;
{-}
function GetPopupMenu: TPopupMenu;
override;
{-}
function UserTypeByCaption(const aCaption: AnsiString;
aFormClass: TClass = nil): IvcmUserTypeDef;
{-}
function GetOneToolbarPerFormName(aForm : TvcmEntityForm;
aPos : TvcmEffectiveToolBarPos;
anIndex : Integer): String;
{-}
procedure ReloadToolbars(const aForm : IvcmEntityForm);
override;
{-}
{$IfNDef DesignTimeLibrary}
function BuildToolbar(aForm : TvcmEntityForm;
const aName : String;
const aCaption : IvcmCString;
aPos : TvcmEffectiveToolBarPos): TvcmToolbarDef;
overload;
{-}
function BuildToolbar(aForm : TvcmEntityForm;
aPos : TvcmEffectiveToolBarPos): TvcmToolbarDef;
overload;
{-}
{$EndIf DesignTimeLibrary}
procedure CleanupSaveDockList(anItem: TvcmDockDef);
{-}
function GetDockParent(aForm : TCustomForm): TWinControl;
{-}
procedure LoadGlyphSize(aDefault : Boolean = False);
{-}
procedure LoadGlyphColordepth(aDefault : Boolean = False);
{-}
procedure UnlockDocks;
{-}
procedure LockDocks;
{-}
procedure StoreGlyphSize;
{-}
procedure RestoreGlyphSize;
{-}
procedure StoreGlyphColordepth;
{-}
procedure RestoreGlyphColordepth;
{-}
procedure InitToolbarMetrics(const aForm: TCustomForm);
{* - определить метрики панели инструментов. Компоненты, которые могут
быть помещены в панель, могут иметь разные размеры, чтобы высота
панелей была одинаковой, считаем максимальную высоту и используем
её для всех панелей. }
function ObjectByType(anObject : TvcmObject;
const anObjectName : String;
const aSubName : String = '';
ForceCreate : Boolean = False): TvcmBaseCollectionItem;
override;
{-}
procedure AddControlForUnlockPostBuild(const aCOntrol: IafwMenuUnlockedPostBuild);
override;
{-}
procedure ListenerControlDestroying(const aCOntrol: IafwMenuUnlockedPostBuild);
override;
{-}
function FillPopupMenu(aPopupPoint : TPoint;
aPopupComponent : TComponent): TvcmPopupMenu;
{-}
public
// public properties
property DockButtonsImageList : TCustomImageList
read f_DockButtonsImageList
write pm_SetDockButtonsImageList;
{* - imagelist используемый для кнопок области dock-а. }
property BtnCloseImageIndex : TImageIndex
read f_BtnCloseImageIndex
write f_BtnCloseImageIndex
default -1;
{-}
property BtnOpenImageIndex : TImageIndex
read f_BtnOpenImageIndex
write f_BtnOpenImageIndex
default -1;
{-}
property BtnOpenNewWindowImageIndex : TImageIndex
read f_BtnOpenNewWindowImageIndex
write f_BtnOpenNewWindowImageIndex
default -1;
{-}
property Actions: TCustomActionList
read f_Actions
write pm_SetActions;
{-}
property GlyphSize: TvcmGlyphSize
read f_GlyphSize
write pm_SetGlyphSize
default vcm_gs16x16;
{-}
property GlyphColordepth: TvcmGlyphColordepth
read f_GlyphColordepth
write pm_SetGlyphColordepth
default vcm_gcAuto;
{-}
property MainMenuItems: TvcmMenuItemsCollection
read f_MainMenuItems
write pm_SetMainMenuItems;
{-}
property MenuOptions: TvcmMenuOptions
read f_MenuOptions
write f_MenuOptions
default vcm_DefaultMenuOptions;
{-}
property ToolbarOptions: TvcmToolbarOptions
read f_ToolbarOptions
write f_ToolbarOptions
default vcm_DefaultToolbarOptions;
{-}
property UserTypes: TvcmInterfaceList
read f_UserTypes;
{-}
property SmallToolbarSize : Integer
read f_SmallToolbarSize;
{* - размер toolbar-а в котором находятся кнопки с маленькими иконками,
компонентами TvcmEdit и TvcmDateEdit. }
property MaxControlToolbarSize : Integer
read f_MaxControlToolbarSize;
{* - максимальная высота компонента находящегося в toolbar-е }
property OneToolbarPerForm: Boolean
read f_OneToolbarPerForm
write f_OneToolbarPerForm
default true;
{-}
property OnGlyphSizeChanged: TNotifyEvent
read f_OnGlyphSizeChanged
write f_OnGlyphSizeChanged;
{-}
property OnGlyphColordepthChanged: TNotifyEvent
read f_OnGlyphColordepthChanged
write f_OnGlyphColordepthChanged;
{-}
end;//TvcmCustomMenuManager
TvcmMenuManager = class(TvcmCustomMenuManager)
{-}
published
// published properties
property Strings;
{-}
property DockButtonsImageList;
{-}
property BtnCloseImageIndex;
{-}
property BtnOpenImageIndex;
{-}
property BtnOpenNewWindowImageIndex;
{-}
property HistoryZones;
{-}
property SaveFormZones;
{-}
property Actions;
{-}
property SmallImages;
{-}
property LargeImages;
{-}
property MainMenuItems;
{-}
property MenuOptions;
{-}
property ToolbarOptions;
{-}
property Modules;
{-}
property Entities;
{-}
//property AppForms;
{-}
//property FormSetFactories;
{-}
property Messages;
{-}
property OneToolbarPerForm;
{-}
property OnInitCommands;
{-}
property OnGlyphSizeChanged;
{-}
property OnGlyphColordepthChanged;
{-}
property OnOperationExecuteNotify;
{-}
end;//TvcmMenuManager
{$R *.res}
implementation
uses
vcmToolbarUtils,
SysUtils,
TypInfo,
StdCtrls,
Math,
{$IfDef XE}
VCL.ToolWin,
System.Actions,
{$Else}
ToolWin,
{$EndIf}
Graphics,
l3String,
{$IfDef vcmNeedL3}
l3TreeInterfaces,
l3InternalInterfaces,
l3ScreenIC,
{$EndIf vcmNeedL3}
afwFacade,
{$IfDef Nemesis}
l3Defaults,
afwDrawing,
{$EndIf}
//l3String,
ctTypes,
FakeBox,
OvcConst,
vcmMessages,
vcmMainForm,
vcmModuleAction,
vcmEntityAction,
vcmOperationAction,
vcmStyle
{$IfNDef DesignTimeLibrary}
,
vcmFormHandler
{$EndIf DesignTimeLibrary}
,
vcmMenuItemsCollectionItem,
vcmMainMenuAction,
vcmWinControlActionLink,
{$IfDef vcmUseSettings}
vcmSettings,
{$EndIf vcmUseSettings}
vcmInternalConst,
vcmMenuManagerRes
{$IfNDef DesignTimeLibrary}
,
tfwClassRef
{$EndIf DesignTimeLibrary}
{$If (not Defined(nsTest) OR Defined(InsiderTest)) AND not Defined(nsTool) AND Defined(Nemesis) AND not Defined(NewGen)}
,
nscTasksPanelView
{$IfEnd}
;
const
c_vcmCloseBmpName = 'CLOSEBTN_DOCK97';
c_vcmMaximizedBmpName = 'MAXIMIZEDBTN_DOCK97';
c_vcmOpenBmpName = 'OPENBTN_DOCK97';
c_vcmCloseImageIndex = 0;
c_vcmMaximizedImageIndex = 1;
c_vcmOpenImageIndex = 2;
c_vcmDockContainerName = 'vcmDockContainer';
c_GlyphSizeMap: array [TvcmGlyphSize] of Cardinal = (
2, // vcm_gsAutomatic,
0, // vcm_gs16x16,
3, // vcm_gs24x24,
1 // vcm_gs32x32
);
{ TvcmDockContainer }
constructor TvcmDockContainer.Create(AOwner : TComponent);
//override;
begin
inherited Create(AOwner);
Assert(AOwner.FindComponent(c_vcmDockContainerName) = nil,
Format('В ''%s'' уже есть компонент с именем ''%s'';', [AOwner.Name,
c_vcmDockContainerName]));
Name := c_vcmDockContainerName;
Caption := '';
BevelInner := bvNone;
BevelOuter := bvNone;
end;
// start internal ComboBox classes
type
TvcmFakeBox = class(TFakeBox, ITB97Ctrl)
{* - общая функциональность необходимая vcm при использовании TFakeBox. }
private
// private fields ( ITB97Ctrl )
f_MinWidth : Integer;
private
// private methods ( ITB97Ctrl )
function pm_GetFullWidth : Integer;
{-}
function pm_GetIsSizeable : Boolean;
{-}
function pm_GetMinWidth : Integer;
{-}
procedure DoFitToWidth(aWidth: Integer);
{-}
procedure DoUnFitToWidth(aWidth: Integer);
{-}
procedure Expand;
{-}
public
// public methods
constructor Create(AOwner : TComponent);
override;
{-}
end;//TvcmFakeBox
{ TvcmFakeBox }
function TvcmFakeBox.pm_GetFullWidth : Integer;
{-}
begin
Result := FullWidth;
end;
function TvcmFakeBox.pm_GetIsSizeable : Boolean;
{-}
begin
Result := True;
end;
function TvcmFakeBox.pm_GetMinWidth : Integer;
{-}
var
l_CN : Il3InfoCanvas;
begin
if f_MinWidth < 0 then
begin
l_CN := l3CrtIC;
l_CN.Font.AssignFont(Font);
f_MinWidth := ButtonWidth + l_CN.LP2DP(l_CN.TextExtent(vcmWStr('WWW'))).X;
end;
Result := f_MinWidth;
end;
procedure TvcmFakeBox.DoFitToWidth(aWidth: Integer);
{-}
begin
Width := aWidth;
end;
procedure TvcmFakeBox.DoUnFitToWidth(aWidth: Integer);
{-}
begin
Width := aWidth;
end;
procedure TvcmFakeBox.Expand;
{-}
begin
Width := pm_GetFullWidth;
end;
constructor TvcmFakeBox.Create(AOwner : TComponent);
// override;
{-}
begin
inherited;
f_MinWidth := -1;
SmartOnResize:=false;
SetToBeginOnTreeSelect := True;
end;
type
TvcmComboBox = class;
TvcmComboBoxActionLink = class(TvcmWinControlActionLink)
protected
// internal methods
procedure SetCaption(const Value: string);
override;
{-}
procedure ParamsChanged(const anAction: IvcmAction);
override;
{-}
procedure ParamsChanging(const anAction: IvcmAction);
override;
{-}
end;//TvcmComboBoxActionLink
TvcmComboBox = class(TvcmFakeBox)
private
f_InUpdateCation: Boolean;
protected
// internal methods
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean);
override;
{-}
function GetActionLinkClass: TControlActionLinkClass;
override;
{-}
procedure DropDown;
override;
{-}
procedure SetCaptionFromAction(anAction : TvcmOperationAction;
anUpdateIndex : Boolean);
{-}
function SetStringsFromAction(const anAction: IvcmAction): Boolean;
{-}
procedure ActionExecuteHandler;
override;
{-}
procedure LocalUpdateAction;
override;
{-}
procedure CMTBMouseQuery(var Msg: TMessage);
message CM_TBMOUSEQUERY;
{-}
procedure CMTBCheckControl(var Msg: TMessage);
message CM_TBCHECKCONTROL;
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
end;//TvcmComboBox
// start class TvcmComboBoxActionLink
procedure TvcmComboBoxActionLink.SetCaption(const Value: string);
//override;
{-}
begin
inherited;
if (FClient Is TvcmComboBox) AND (Action Is TvcmOperationAction) then
TvcmComboBox(FClient).SetCaptionFromAction(TvcmOperationAction(Action), true);
end;
procedure TvcmComboBoxActionLink.ParamsChanging(const anAction: IvcmAction);
//override;
{-}
begin
inherited;
if (FClient Is TvcmComboBox) then
begin
if (anAction.SubNodes <> nil) then
begin
with anAction.SubNodes do
begin
Current := TvcmComboBox(FClient).CurrentNode;
ShowRoot := TvcmComboBox(FClient).ShowRoot;
end;//anAction.SubNodes
end;//anAction.SubNodes <> nil
end;//FClient Is TvcmComboBox
end;
procedure TvcmComboBoxActionLink.ParamsChanged(const anAction: IvcmAction);
//override;
{-}
begin
inherited;
if (FClient Is TvcmComboBox) then
begin
with TvcmComboBox(FClient) do
begin
if (anAction.SubNodes <> nil) then
ShowRoot := anAction.SubNodes.ShowRoot;
SetStringsFromAction(anAction);
{$IfNDef DesignTimeLibrary}
if (anAction.SubNodes <> nil) then
vcmSetCurrent(anAction.SubNodes.Current);
{$EndIf DesignTimeLibrary}
Hint := vcmStr(anAction.Hint);
end;//with TvcmComboBox(FClient)
end;//FClient Is TvcmComboBox
end;
// start class TvcmComboBox
constructor TvcmComboBox.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
AutoWidth := awCurrent;
end;
procedure TvcmComboBox.ActionChange(Sender: TObject; CheckDefaults: Boolean);
//override;
{-}
begin
if (Sender Is TvcmOperationAction) then
SetCaptionFromAction(TvcmOperationAction(Sender), False);
inherited;
end;
function TvcmComboBox.GetActionLinkClass: TControlActionLinkClass;
//override;
{-}
begin
Result := TvcmComboBoxActionLink;
end;
procedure TvcmComboBox.DropDown;
//override;
{-}
var
l_Action: IvcmAction;
begin
if Supports(Action, IvcmAction, l_Action) then
try
SetStringsFromAction(l_Action);
inherited;
finally
l_Action := nil;
end//try..finally
else
inherited;
end;
function TvcmComboBox.SetStringsFromAction(const anAction: IvcmAction): Boolean;
{-}
var
l_Strings : IvcmStrings;
begin
Result := False;
l_Strings := anAction.SubItems;
if (l_Strings = nil) OR (l_Strings.Count = 0) then
begin
Result := vcmSetRoot(anAction.SubNodes);
if (anAction.SubNodes = nil) or (anAction.SubNodes.Count = 0) then
if anAction.IsSelectedStringChanged then
//if not l3Same(Text, anAction.SelectedString) then
Text := anAction.SelectedString;
end//l_Strings = nil
else
begin
Result := true;
if (Action Is TvcmOperationAction) AND
(TvcmOperationAction(Action).OpDef.OperationType = vcm_otCombo) then
begin
Items.Assign(l_Strings.Items);
if not vcmIsNil(anAction.SelectedString) then
ItemIndex := Items.IndexOf(anAction.SelectedString);
end//anAction Is TvcmOperationAction
else
begin
Items.Assign(l_Strings.Items);
if anAction.IsSelectedStringChanged then
begin
if not l3Same(Text, anAction.SelectedString) then
begin
Text := anAction.SelectedString;
//AdjustWidth;
//// ^ http://mdp.garant.ru/pages/viewpage.action?pageId=100958843
// КОСТЫЛЬ ПЕРЕЕХАЛ В TctButtonEdit.pm_SetText из-за K278854646
end;//not l3Same(Text, anAction.SelectedString)
end;//not vcmSame(f_SelectedString, anAction.SelectedString)
end;//anAction Is TvcmOperationAction
end;//l_Strings = nil..
end;
procedure TvcmComboBox.SetCaptionFromAction(anAction : TvcmOperationAction;
anUpdateIndex : Boolean);
{-}
var
l_Action: IvcmAction;
begin
if not f_InUpdateCation and (anAction.OpDef.OperationType = vcm_otCombo) then
begin
f_InUpdateCation := True;
try
if Supports(anAction, IvcmAction, l_Action) then
try
if not SetStringsFromAction(anAction) then
begin
(* {$IfNDef vcmUseComboTree}
Items.Clear;
Items.Add(vcmStr(l_Action.SelectedString));
if anUpdateIndex then
ItemIndex := Items.IndexOf(vcmStr(l_Action.SelectedString));
{$EndIf vcmUseComboTree}*)
end;//not SetStringsFromAction(anAction)
finally
l_Action := nil;
end;//try..finally
finally
f_InUpdateCation := False;
end;//try..finally
end;//not f_InUpdateCation and (anAction.OpDef.OperationType = vcm_otCombo)
end;//SetCaptionFromAction
procedure TvcmComboBox.ActionExecuteHandler;
var
l_LockCount : Integer;
l_Action : IvcmAction;
procedure lp_SaveLock;
begin
l_LockCount:=0;
while l_Action.IsExecuteLocked do
begin
l_Action.UnlockExecute;
inc(l_LockCount);
end;//while l_Action.IsExecuteLocked do
end;//lp_SaveLock
procedure lp_RestoreLock;
begin
while l_LockCount > 0 do
begin
l_Action.LockExecute;
dec(l_LockCount);
end;//while l_LockCount > 0 do
end;//lp_RestoreLock
begin
if Supports(Action, IvcmAction, l_Action) then
try
Action.ActionComponent := self;
l_Action.SelectedString := Text;
l_Action.LockUpdate;
try
lp_SaveLock;
try
Action.Execute;
finally
lp_RestoreLock;
end;//try..finally
finally
l_Action.UnlockUpdate;
end;//try..finally
finally
l_Action := nil;
end;//try..finally
end;//ActionExecuteHandler
procedure TvcmComboBox.LocalUpdateAction;
var
l_Action: IvcmAction;
begin
if Supports(Action, IvcmAction, l_Action) then
try
l_Action.SelectedString := Text;
finally
l_Action := nil;
end;//try..finally
end;//LocalUpdateAction
procedure TvcmComboBox.CMTBMouseQuery(var Msg: TMessage);
begin
if InnerPoint(Point(Integer(Msg.WParam), Integer(Msg.LParam))) then
Msg.Result := 1
else
Msg.Result := 0;
end;
procedure TvcmComboBox.CMTBCheckControl(var Msg: TMessage);
begin
if IsInnerControl(HWND(Msg.WParam)) then
Msg.Result := 1
else
Msg.Result := 0;
end;
// start class TvcmEditActionLink
type
TvcmEditActionLink = class(TvcmWinControlActionLink)
end;//TvcmEditActionLink
// start class TvcmEdit
type
TvcmEdit = class(TvcmFakeBox)
constructor Create(AOwner: TComponent);
override;
protected
// internal methods
function DoProcessCommand(Cmd : Tl3OperationCode;
aForce : Boolean;
aCount : Integer): Boolean;
override;
{* - вызывается orpheus-ом при обработке shortcut-ов. }
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean);
override;
{-}
function GetActionLinkClass: TControlActionLinkClass;
override;
{-}
end;//TvcmEdit
constructor TvcmEdit.Create(AOwner: TComponent);
begin
inherited;
Width := 121;
// При установке фокуса выделяем весь текст
AutoSelect := True;
end;
function TvcmEdit.DoProcessCommand(Cmd : Tl3OperationCode;
aForce : Boolean;
aCount : Integer): Boolean;
//override
begin
Result := inherited DoProcessCommand(Cmd, aForce, aCount);
if not Result then
begin
Tag := 0;
case Cmd of
ccNewLine:
begin
Tag := Integer(Cmd);
with Action do
begin
ActionComponent := Self;
Execute;
end;
Result := True;
end;
end;
end;
end;
procedure TvcmEdit.ActionChange(Sender: TObject; CheckDefaults: Boolean);
//override;
{-}
var
l_Action: IvcmAction;
begin
if Supports(Sender, IvcmAction, l_Action) then
try
l_Action.LockExecute;
try
inherited;
finally
l_Action.UnlockExecute;
end;//try..finally
finally
l_Action := nil;
end//try..finally
else
inherited;
end;
function TvcmEdit.GetActionLinkClass: TControlActionLinkClass;
//override;
{-}
begin
Result := TvcmEditActionLink;
end;
// start class TvcmDateEdit
type
TvcmDateEdit = class(TvtDblClickDateEdit)
private
f_OnSelectDate : TNotifyEvent;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
protected
procedure DoExecute;
override;
{-}
procedure DoCloseUp(Accept: Boolean);
override;
{-}
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean);
override;
{-}
// internal methods
function GetActionLinkClass: TControlActionLinkClass;
override;
{-}
public
constructor Create(AOwner: TComponent); override;
property OnSelectDate : TNotifyEvent read f_OnSelectDate write f_OnSelectDate;
end;//TvcmDateEdit
TvcmDateEditActionLink = class(TvcmWinControlActionLink)
protected
// protected methods
function IsCaptionLinked: Boolean;
override;
{-}
procedure ParamsChanged(const anAction: IvcmAction);
override;
{-}
end;//TvcmDateEditActionLink
procedure TvcmDateEditActionLink.ParamsChanged(const anAction: IvcmAction);
// override;
{-}
begin
inherited;
if anAction.IsSelectedStringChanged and (FClient is TvcmDateEdit) then
TvcmDateEdit(FClient).Text := vcmStr(anAction.SelectedString);
end;//ParamsChanged
function TvcmDateEditActionLink.IsCaptionLinked: Boolean;
begin
Result :=
False
// - реагировать на изменение Caption мы не можем, потому как он может
// меняться, значение же храниться в параметре SelectedString (K<50758978>);
;
end;
function TvcmDateEdit.GetActionLinkClass: TControlActionLinkClass;
//override;
{-}
begin
Result := TvcmDateEditActionLink;
end;
procedure TvcmDateEdit.DoExecute;
//override;
begin
inherited;
end;
procedure TvcmDateEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
{ Если маска установлена поле не может быть пустым }
if (EditMask <> '') and (EditText = '') then
Clear;
end;
constructor TvcmDateEdit.Create(AOwner: TComponent);
begin
inherited;
RestrictInvalidDate := true;
end;
procedure TvcmDateEdit.ActionChange(Sender: TObject; CheckDefaults: Boolean);
// override;
{-}
var
l_Action: IvcmAction;
begin
inherited;
// После смены Action текст будет равен названию операции поэтому после смены
// нужно установить текущее значение:
if Supports(Action, IvcmAction, l_Action) then
try
l_Action.LockExecute;
try
Text := vcmStr(l_Action.SelectedString);
finally
l_Action.UnlockExecute;
end;//try..finally
finally
l_Action := nil;
end;//try..finally
end;//ActionChange
procedure TvcmDateEdit.DoCloseUp(Accept: Boolean);
//override;
{-}
begin
inherited DoCloseUp(Accept);
if Assigned(f_OnSelectDate) and Accept then
f_OnSelectDate(Self);
end;
// start class TvcmCustomMenuManager
var
g_InternalButton : TvcmToolButtonDef = nil;
constructor TvcmCustomMenuManager.Create(anOwner: TComponent);
//override;
{-}
var
l_Form : TCustomForm;
begin
inherited;
MenuOptions := vcm_DefaultMenuOptions;
ToolbarOptions := vcm_DefaultToolbarOptions;
if not (csDesigning in ComponentState) then begin
l_Form := afw.GetParentForm(Self);
if (l_Form Is TForm) then
if (l_Form Is TvcmMainForm) AND not TvcmMainForm(l_Form).SDI then
TForm(l_Form).FormStyle := fsMDIForm;
Screen.OnActiveFormChange := FormChange;
end;//not (csDesigning in ComponentState)
f_MainMenuItems := TvcmMenuItemsCollection.Create(Self);
f_TickCount := Cardinal(-1);
OneToolbarPerForm := true;
f_FastenToolbars := -1;
f_SaveDockList := Tl3SimpleObjectRefList.Make;
f_BtnCloseImageIndex := -1;
f_BtnOpenImageIndex := -1;
f_BtnOpenNewWindowImageIndex := -1;
f_SaveLockCounter := TvcmLongintList.Make;
f_LockCounter := 0;
f_UnlockInProgress := 0;
f_GlyphSize := vcm_gs16x16;
f_SmallToolbarSize := 0;
end;
function TvcmCustomMenuManager.UnlockInProgress: Boolean;
begin
Result := (f_UnlockInProgress > 0);
end;
procedure TvcmCustomMenuManager.Cleanup;
//override;
{-}
var
l_MyEvent : TNotifyEvent;
l_MyMethod : TMethod absolute l_MyEvent;
l_Event : TNotifyEvent;
l_Method : TMethod absolute l_Event;
begin
TB97Tlbr.g_ToolbarSize := nil;
{$IfDef vcmUseSettings}
Finalize(f_MainToolbarDefs);
{$EndIf vcmUseSettings}
l_Event := Screen.OnActiveFormChange;
l_MyEvent := FormChange;
if (l_Method.Code = l_MyMethod.Code) AND (l_Method.Data = l_MyMethod.Data) then
Screen.OnActiveFormChange := nil;
vcmFree(f_MainMenuItems);
vcmFree(f_Popup);
vcmFree(f_SaveLockCounter);
vcmFree(f_LockList);
vcmFree(f_SaveDockList);
Actions := nil;
vcmFree(f_UserTypes);
inherited;
end;
type
THackWinControl = class(TWinControl);
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.RegisterModuleInMenu(aForm : TvcmEntityForm;
const aModuleDef : IvcmModuleDef);
//override;
{* - регистрирует модуль в меню, toolbar'ах, etc. }
var
l_Main : TMenuItem;
l_Item : TMenuItem;
begin
// if (aForm = Application.MainForm) OR (Application.MainForm = nil) then begin
if (aForm Is TvcmMainForm) then begin
THackWinControl(aForm).DestroyHandle;
// - это здесь ОБЯЗАТЕЛЬНО нужно иначе окно открывается в РАЗЫ медленнее
l_Main := vcmGetMainMenu(aForm);
l_Item := vcmMakeModuleMenu(l_Main, aModuleDef, [vcm_ooShowInMainMenu], true);
if (vcm_moEntitiesInMainMenu in MenuOptions) then begin
if (vcm_moEntitiesInTopMainMenu in MenuOptions) then
vcmMakeEntitiesMenus(l_Main, aModuleDef.EntitiesDefIterator, [vcm_ooShowInMainMenu])
else
vcmMakeEntitiesMenus(l_Item, aModuleDef.EntitiesDefIterator, [vcm_ooShowInMainMenu]);
end else
vcmMakeEntitiesMenus(l_Item, aModuleDef.EntitiesDefIterator, [vcm_ooShowInMainMenu], False, vcm_icSameAsParent);
if (f_UserTypes = nil) then
begin
CheckUserTypes;
aForm.GetUserTypes(f_UserTypes);
end;//f_UserTypes = nil
BuildMainToolbars(aForm, aModuleDef);
BuildUserTypes(aModuleDef);
end;//aForm = Application.MainForm
end;
{$EndIf DesignTimeLibrary}
procedure TvcmCustomMenuManager.CheckUserTypes;
{-}
begin
if (f_UserTypes = nil) then
f_UserTypes := TvcmInterfaceList.Make;
end;
procedure TvcmCustomMenuManager.BuildUserTypes(const aModuleDef : IvcmModuleDef);
{-}
var
l_UserTypes : IvcmUserTypesIterator;
l_UserType : IvcmUserTypeDef;
begin
if not f_UserTypesLoaded then
begin
l_UserTypes := aModuleDef.UserTypesIterator;
if (l_UserTypes <> nil) then
begin
CheckUserTypes;
while true do
begin
l_UserType := l_UserTypes.Next;
if (l_UserType = nil) then
break;
f_UserTypes.Add(l_UserType);
end;//while true
// while DoEntity(l_Entities.Next) do ;
end;//l_UserTypes <> nil
end;//not f_UserTypesLoaded
end;
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.MainCreated(aForm: TvcmEntityForm);
//override;
{-}
var
l_Menu : TMenuItem;
l_Index : Integer;
l_MMI : TvcmMenuItemsCollectionItem;
begin
inherited;
if not (csDesigning in ComponentState) then
begin
OverridePopupMenu(aForm);
if (aForm Is TvcmMainForm) AND not TvcmMainForm(aForm).SDI then
TForm(aForm).FormStyle := fsMDIForm;
l_Menu := vcmGetMainMenu(aForm);
for l_Index := 0 to Pred(MainMenuItems.Count) do
begin
l_MMI := TvcmMenuItemsCollectionItem(MainMenuItems.Items[l_Index]);
TvcmMainMenuAction.MakeForMenu(vcmAddCategoryItem(l_Menu, l_MMI.Caption), l_MMI.OnTest);
end;//for l_Index
if (vcm_toEntitiesInMainToolbar in ToolbarOptions) then
BuildFormToolbars(aForm, [vcm_ooShowInMainToolbar]);
end;//not (csDesigning in ComponentState)
end;
{$EndIf DesignTimeLibrary}
{$IfDef vcmUseSettings}
procedure TvcmCustomMenuManager.MakeMainToolbarFromSettings(aForm : TvcmEntityForm);
{-}
var
l_Pos : TvcmEffectiveToolBarPos;
begin
for l_Pos := Low(TvcmEffectiveToolBarPos) to High(TvcmEffectiveToolBarPos) do
begin
with f_MainToolbarDefs[l_Pos] do
begin
if rVisible AND (rButtons <> nil) then
begin
MakeToolbarFromSettings(aForm, rToolbarName, l_Pos,
[vcm_ooShowInMainToolbar], rButtons);
rButtons := nil;
end;//rButtons <> nil
end;//with f_MainToolbarDefs[l_Pos]
end;//for l_Pos
end;
{$EndIf vcmUseSettings}
procedure TvcmCustomMenuManager.RegisterMainInMenu(aForm: TvcmEntityForm);
//override;
{* - регистрирует основную форму в меню, toolbar'ах, etc. }
var
l_Item : TMenuItem;
l_Child : TMenuItem;
l_Index : Integer;
begin
if not (csDesigning in ComponentState) then
begin
LoadGlyphSize;
LoadGlyphColordepth;
l_Item := vcmGetMainMenu(aForm);
vcmMakeEntitiesMenus(l_Item, aForm.GetEntitiesDefIterator, [vcm_ooShowInMainMenu]);
l_Index := 0;
while (l_Index < l_Item.Count) do
begin
l_Child := l_Item.Items[l_Index];
if (l_Child.Count <= 0) then
l_Item.Remove(l_Child)
else
Inc(l_Index);
end;//while (l_Index < l_Item.Count)
{$IfDef vcmUseSettings}
MakeMainToolbarFromSettings(aForm);
{$EndIf vcmUseSettings}
f_UserTypesLoaded := true;
end;//not (csDesigning in ComponentState)
end;
procedure TvcmCustomMenuManager.RefocusEntity;
{-}
//var
//l_Active : IvcmEntity;
//l_Form : IvcmEntityForm;
begin
// Раньше мы запоминали активную Entity, а теперь она ищется по фокусу (см. vcmDispatcher.ActiveEntity)
// Так что эта процедура теряет весь свой сакральный смысл и по-хорошему ее надо удалить
// оставленные части ждут удаления
if (f_FocusControl <> nil) AND (Application.MainForm <> nil) then
begin
f_InEnter := False;
{
Application.MainForm.DefocusControl(f_FocusControl, true);
f_FocusControl := nil;
l_Active := vcmDispatcher.ActiveEntity;
if (l_Active <> nil) then
if Succeeded(l_Active.QueryInterface(IvcmEntityForm, l_Form)) then
try
with l_Form.VCLForm do begin
Windows.SetFocus(Handle);
if (ActiveControl <> nil) then
Windows.SetFocus(ActiveControl.Handle);
end;//with l_Form.VCLForm
finally
l_Form := nil;
end;//try..finally
}
end;//f_FocusControl <> nil
end;
procedure TvcmCustomMenuManager.RestoreControlText(Sender: TObject);
{-}
var
l_Control : TWinControl;
l_TC : IafwTextControl;
l_Action : IvcmAction;
begin
l_Control := (Sender As TWinControl);
if Supports(l_Control.Action, IvcmAction, l_Action) then
try
if Supports(l_Control, IafwTextControl, l_TC) then
l_TC.CCaption := l_Action.Caption
else
THackWinControl(l_Control).Text := vcmStr(l_Action.Caption);
finally
l_Action := nil;
end;//try..finally
end;//RestoreControlText
procedure TvcmCustomMenuManager.ChangeEntityText(Sender: TObject);
{-}
var
l_Control : TWinControl;
l_TC : IafwTextControl;
l_Action : IvcmAction;
begin
l_Control := (Sender As TWinControl);
if Supports(l_Control.Action, IvcmAction, l_Action) then
try
with l_Action do
begin
if Supports(l_Control, IafwTextControl, l_TC) then
SelectedString := l_TC.CCaption
else
SelectedString := vcmCStr(THackWinControl(l_Control).Text);
LockUpdate;
try
if (f_FocusControl = l_Control) then
begin
UnlockExecute;
f_IsUnlockExecute := True;
end;
l_Control.Action.Execute;
finally
UnLockUpdate;
end;//try..finally
end;//with TCustomAction(l_Control.Action)
finally
l_Action := nil;
end;//try..finally
end;//ChangeEntityText
procedure TvcmCustomMenuManager.ChangeTyperText(Sender: TObject);
{-}
var
l_TickCount : Cardinal;
begin
l_TickCount := GetTickCount;
// if (f_TickCount = Cardinal(-1)) OR (l_TickCount - f_TickCount >= 300) then
ChangeEntityText(Sender);
f_TickCount := l_TickCount;
end;
procedure TvcmCustomMenuManager.ControlKeyDown(Sender : TObject;
var Key : Word;
Shift : TShiftState);
{-}
begin
if (Shift = []) then begin
if (Key = vk_Escape) then begin
RestoreControlText(Sender);
RefocusEntity;
Key := 0;
//Key = vk_Escape
end else if (Key = vk_Return) then begin
ChangeEntityText(Sender);
RefocusEntity;
Key := 0;
end;//Key = vk_Enter
end;//Shift = []
end;
procedure TvcmCustomMenuManager.ControlEnter(Sender: TObject);
{-}
var
l_Action: IvcmAction;
begin
if not (Sender Is TvcmComboBox) then
f_WasDrop := False;
f_InEnter := true;
f_FocusControl := (Sender As TWinControl);
if Supports(f_FocusControl.Action, IvcmAction, l_Action) then
try
(* при входе в обязательном порядке вызываем OnTest *)
// TvcmAction(f_FocusControl.Action).Update;
if not (f_FocusControl is TFakeBox) then
(* Нет необходимости защищать Execute, потому что по TControl.Click
TAction.Execute не вызывается.
Предистория:
1. Находимся в дереве;
2. Нажимаем клавиши, включается быстрый поиск;
3. В TvcmEdit на toolbar-е передаётся текст;
4. Устанавливаем фокус в TvcmEdit, получается что выполнение
TAction.Execute запрещено;
5. Нажимаем Enter, который транслируется в команду и обрабатывается в
TvcmEdit.ProcessCommand в обход ControlKeyDown (в котором
сбрасывается UnlockExecute) и ничего не происходит; *)
l_Action.LockExecute;
(* Это нужно сделать потому, что при входе в компонент по TControl.Click
вызовется TAction.Execute, а в компоненте может быть не валидная
информация *)
f_IsUnlockExecute := False;
(* Устанавливаем флаг чтобы по выходу сбросить блокировку если мы ничего не
вызывали *)
finally
l_Action := nil;
end;//try..finally
end;//ControlEnter
procedure TvcmCustomMenuManager.ControlExit(Sender: TObject);
{-}
var
l_TC : IafwTextControl;
l_Action : IvcmAction;
begin
if not f_IsUnlockExecute then
begin
f_FocusControl := TWinControl(Sender);
if Supports(f_FocusControl.Action, IvcmAction, l_Action) then
try
// если пользователь поредактировал и вышел без нажатия на Enter, то
// возвращаем предыдущее значение
if Supports(f_FocusControl, IafwTextControl, l_TC) then
begin
if not vcmSame(l_TC.CCaption, l_Action.Caption) then
l_TC.CCaption := l_Action.Caption;
end//Supports(f_FocusControl, IafwTextControl, l_TC)
else
with THackWinControl(f_FocusControl) do
if not vcmSame(Text, l_Action.SelectedString) then
Text := vcmStr(l_Action.SelectedString);
l_Action.UnlockExecute;
finally
l_Action := nil;
end;//f_FocusControl.Action Is TvcmAction
end;//not f_IsUnlockExecute
// RefocusEntity; //приходим сюда во время обработки WM_SETFOCUS другого
// контрола; RefocusEntity приводила к повторному WM_SETFOCUS;
// это приводило к тому, что фокус до контрола не доходил;
end;
procedure TvcmCustomMenuManager.ComboDown(Sender: TObject);
{-}
begin
ControlDown(Sender);
end;
procedure TvcmCustomMenuManager.ControlSelect(Sender: TObject);
{-}
begin
if f_WasDrop then begin
f_WasDrop := False;
ChangeEntityText(Sender);
RefocusEntity;
end;//f_WasDrop
end;
procedure TvcmCustomMenuManager.ControlDown(Sender: TObject);
{-}
begin
f_WasDrop := true;
f_InEnter := true;
f_FocusControl := (Sender As TWinControl);
end;
procedure TvcmCustomMenuManager.DateDown(Sender: TObject);
{-}
begin
ControlDown(Sender);
end;
procedure TvcmCustomMenuManager.FormChange(Sender: TObject);
{-}
begin
if f_InEnter then
f_InEnter := False
else
RefocusEntity;
end;
function TvcmCustomMenuManager.BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aModuleDef : IvcmModuleDef;
const anEntityDef : IvcmEntityDef;
const anOp : IvcmOperationDef;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType): TControl;
//overload;
{-}
begin
if (anOp = nil) then
Result := nil
else
Result := BuildButton(aForm, aToolbar, aModuleDef, anEntityDef, anOp,
anOp.Options, anOptions, anIconText);
end;
function TvcmCustomMenuManager.BuildAction(const aModuleDef : IvcmModuleDef;
const anOpDef : IvcmOperationDef): TCustomAction;
//overload;
{-}
begin
Assert(aModuleDef <> nil);
Assert(anOpDef <> nil);
Result := TvcmModuleAction.Make(aModuleDef, anOpDef);
end;//BuildAction
function TvcmCustomMenuManager.BuildAction(const anOwner : TComponent;
const anEntity : IvcmEntity;
const anEntityDef : IvcmEntityDef;
const anOpDef : IvcmOperationDef;
anOptions : TvcmOperationOptions): TCustomAction;
//overload;
{-}
var
l_Form: IafwMainForm;
begin
Assert(anEntityDef <> nil);
Assert(anOpDef <> nil);
if (vcm_ooShowInChildToolbar in anOptions) or (
(vcm_ooShowInMainToolbar in anOptions) and
(anEntity <> nil) and
Supports(anEntity, IafwMainForm, l_Form))
//or: http://mdp.garant.ru/pages/viewpage.action?pageId=296098743
// Actions главной формы не зависят от фокуса
then
begin
if anEntity <> nil then
Result := TvcmActiveEntityActionEx.Create(anOwner,
anEntity,
anEntityDef,
anOpDef)
else
Result := nil;
end
else
Result := TvcmEntityAction.Make(anEntityDef, anOpDef);
end;//BuildAction
function TvcmCustomMenuManager.BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aModuleDef : IvcmModuleDef;
const anEntityDef : IvcmEntityDef;
const anOp : IvcmOperationDef;
const anOpOptions : TvcmOperationOptions;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType): TControl;
//overload;
{-}
function lp_Images: TCustomImageList;
function lp_MakeImages(const aSize: TvcmImageSize): TCustomImageList;
begin
Result := nil;
case aSize of
isSmall:
Result := SmallImages;
isLarge:
Result := LargeImages;
end;//case aSize of
end;//lp_MakeImage
begin
Result := nil;
with aForm.Style.Toolbars do
case aToolbar.Pos of
vcm_tbpTop:
Result := lp_MakeImages(Top.ImageSize);
vcm_tbpBottom:
Result := lp_MakeImages(Bottom.ImageSize);
vcm_tbpLeft:
Result := lp_MakeImages(Left.ImageSize);
vcm_tbpRight:
Result := lp_MakeImages(Right.ImageSize);
end;//case aToolbar.DockPos of
end;//lp_Image
var
l_ButtonName : String;
l_EntityName : String;
l_Entity : IvcmEntity;
begin
Result := nil;
if (anOp <> nil) then
begin
if (anOp.OperationType in vcm_HiddenOperations) OR
(anOpOptions * anOptions = []) OR
((aForm Is TvcmEntityForm) AND
(TvcmEntityForm(aForm).UserType in anOp.ExcludeUserTypes)) then
Result := g_InternalButton
else
begin
// Имя формируется из сущности + имя операции
if Assigned(aModuleDef) then
l_EntityName := aModuleDef.Name
else
if Assigned(anEntityDef) then
l_EntityName := anEntityDef.Name;
// Сформируем имя. Отрежем префикс "op" у операции
l_ButtonName := 'bt_' + l_EntityName + '_' + anOp.Name;
Result := aToolBar.FindComponent(l_ButtonName) As TControl;
if (Result = nil) then
begin
Case anOp.OperationType of
vcm_otButton,
vcm_otButtonCombo,
vcm_otMenuButtonCombo,
vcm_otButtonPopup,
vcm_otTextButton,
vcm_otCheck,
vcm_otRadio :
begin
Result := TvcmToolButtonDef.Create(aToolBar);
TvcmToolButtonDef(Result).DropdownCombo := (anOp.OperationType in
[vcm_otButtonCombo, vcm_otMenuButtonCombo]);
if (anOp.OperationType in [vcm_otButtonPopup]) then
TvcmToolButtonDef(Result).DropDownAlways := True;
end;//vcm_otRadio
vcm_otCombo,
vcm_otEditCombo : begin
Result := TvcmComboBox.Create(aToolbar);
if (anOp.OperationType = vcm_otEditCombo) then
TvcmComboBox(Result).Style := csDropDown
else
TvcmComboBox(Result).Style := csDropDownList;
TvcmComboBox(Result).OnEnter := ControlEnter;
TvcmComboBox(Result).OnExit := ControlExit;
TvcmComboBox(Result).OnDropDown := ComboDown;
TvcmComboBox(Result).OnSelect := ControlSelect;
TvcmComboBox(Result).OnKeyDown := ControlKeyDown;
{$IfDef vcmUseSettings}
TvcmEdit(Result).PopupMenu := Self.ToolbarPopup;
{$EndIf vcmUseSettings}
end;//vcm_otCombo
vcm_otEdit,
vcm_otTyper :
begin
Result := TvcmEdit.Create(aToolbar);
TvcmEdit(Result).OnEnter := ControlEnter;
TvcmEdit(Result).OnExit := ControlExit;
TvcmEdit(Result).OnKeyDown := ControlKeyDown;
TvcmEdit(Result).ComboStyle := ct_cbEdit;
TvcmEdit(Result).CEmptyHint := anOp.Hint;
{$IfDef vcmUseSettings}
TvcmEdit(Result).PopupMenu := Self.ToolbarPopup;
{$EndIf vcmUseSettings}
if (anOp.OperationType = vcm_otTyper) then
TvcmEdit(Result).OnChange := ChangeTyperText;
end;//vcm_otEdit
vcm_otDate : begin
Result := TvcmDateEdit.Create(aToolbar);
TvcmDateEdit(Result).Width := TvcmDateEdit(Result).Width div 2;
TvcmDateEdit(Result).OnEnter := ControlEnter;
TvcmDateEdit(Result).OnExit := ControlExit;
TvcmDateEdit(Result).OnKeyDown := ControlKeyDown;
{ ElDateTimePicker }
{ TDateTimePicker }
TvcmDateEdit(Result).OnSelectDate := ControlSelect;
TvcmDateEdit(Result).OnDropDown := DateDown;
end;//vcm_otDate
else begin
Result := g_InternalButton;
Exit;
end;//else
end;//Case anOpOperationType
Result.Parent := aToolbar;
Result.Name := l_ButtonName;
if Result is TvcmDateEdit then
with TvcmDateEdit(Result) do
AutoResize;
{ проблема в том, что нельзя сделать это(присвоение Constraint)
до присвоения Parent (Handle не существует) }
// Case anOp.OperationType of
// vcm_otCombo, vcm_otEditCombo :
// TvcmComboBox(Result).Constraints.MaxWidth:=200;
// end;
if (aModuleDef <> nil) then
Result.Action := BuildAction(aModuleDef, anOp)
else
if (anEntityDef <> nil) then
begin
Supports(aToolBar.Owner, IvcmEntity, l_Entity);
try
Result.Action := BuildAction(Result,
l_Entity,
anEntityDef,
anOp,
anOptions);
finally
l_Entity := nil;
end;//try..finally
end;//anEntityDef <> nil
// Сформируем уникальное название компоненту, т.к. в разных сущностях
// могут быть операции с одинаковыми названиями. Например форма "Список":
// Печать..., Печать...(Документы), Печать...(Выделенные документы)
with Result do
if vcmSame(anOp.Hint, anOp.Caption) then
Result.Hint := vcmStr(vcmMakeCaption(anEntityDef, anOp));
Result.ShowHint := true;
if (Result Is TvcmToolButtonDef) then
begin
if (Result.Action <> nil) then
begin
with TvcmToolButtonDef(Result) do
begin
Images := lp_Images;
if Images = nil then
Images := ((Result.Action As TContainedAction).Actionlist As TCustomActionList).Images;
end;//with TvcmToolButtonDef(Result) do
end;//if (Result.Action <> nil) then
if ((anOp.OperationType = vcm_otTextButton) and (anIconText = vcm_itDefault)) or
(anIconText = vcm_itIconText) then
begin
TvcmToolButtonDef(Result).DisplayMode := dmBoth;
TvcmToolButtonDef(Result).WordWrap := true;
end//anOp.OperationType = vcm_otTextButton
else
if (anOp.ImageIndex >= 0) then
// раньше был dmGlyph, но из-за http://mdp.garant.ru/pages/viewpage.action?pageId=287214455
// пришлось добавить новый тип dmGlyphAndFakeText, чтобы в других проектах не отъехал dmGlyph
TvcmToolButtonDef(Result).DisplayMode := dmGlyphAndFakeText
else
begin
TvcmToolButtonDef(Result).DisplayMode := dmTextOnly;
TvcmToolButtonDef(Result).WordWrap := true;
end;//anOp.ImageIndex >= 0
TvcmToolButtonDef(Result).AutoSize := true;
TvcmToolButtonDef(Result).Opaque := false;
end;//Result Is TvcmToolButtonDef
aToolBar.Width := aToolBar.Width + Result.Width;
end;//Result = nil
end;//anOp.OperationType in vcm_HiddenOperations..
end;//anOp <> nil
end;
function TvcmCustomMenuManager.BuildSeparator(aToolBar: TvcmToolbarDef): TControl;
{-}
begin
if aToolbar.CanAddSeparator then
begin
Result := TvcmSeparatorDef.Create(aToolbar);
with Result do
Parent := aToolbar;
end//aToolbar.CanAddSeparator
else
Result := nil;
end;
function TvcmCustomMenuManager.GetPopupMenu: TPopupMenu;
//override;
{-}
begin
Result := f_Popup;
end;
function TvcmCustomMenuManager.UserTypeByCaption(const aCaption: AnsiString;
aFormClass: TClass = nil): IvcmUserTypeDef;
var
l_Index : Integer;
l_UserType : IvcmUserTypeDef;
l_UTCaption : IvcmCString;
begin
Result := nil;
if (f_UserTypes <> nil) then
with f_UserTypes do
for l_Index := Lo to Hi do
begin
l_UserType := IvcmUserTypeDef(Items[l_Index]);
l_UTCaption := vcmCStr(l_UserType.SettingsCaption);
if vcmSame(l_UTCaption, aCaption, true) AND
// http://mdp.garant.ru/pages/viewpage.action?pageId=471774401
((l_UserType.FormClass = aFormClass) OR (aFormClass = nil)) then
if TvcmUserTypeInfo.AllowCustomizeToolbars(l_UserType) then
begin
Result := l_UserType;
break;
end;//ANSISameText
end;//for l_Index
end;
procedure TvcmCustomMenuManager.ToolbarsGetSiteInfo(Sender : TObject;
DockClient : TCustomToolWindow97;
var CanDock : Boolean);
{-}
begin
if not (DockClient Is TvcmToolbar) OR not (Sender Is TvcmDockDef) then
CanDock := False
else
if (TvcmDockDef(Sender).Parent <> TvcmToolbar(DockClient).DockDef.Parent) then
CanDock := False;
end;
procedure TvcmCustomMenuManager.LockDocks;
begin
inc(f_LockCounter);
end;
procedure TvcmCustomMenuManager.UnlockDocks;
var
l_Index: Integer;
l_Dock: TvcmDockDef;
l_DockList: TvcmObjectList;
begin
Dec(f_LockCounter);
Assert(f_LockCounter >= 0);
if TvcmToolbarDockListManager.Exists
then l_DockList := TvcmToolbarDockListManager.Instance.DockList
else l_DockList := nil;
if Assigned(l_DockList) and
(l_DockList.Count > 0) and
(f_LockCounter = 0) and
(f_UnlockInProgress = 0) then
begin
Inc(f_UnlockInProgress);
try
for l_Index := l_DockList.Count - 1 downto 0 do
begin
l_Dock := TvcmDockDef(l_DockList[l_Index]);
l_Dock.EndUpdate;
l_Dock.SmartAlign := False;
end;//for l_Index
l_DockList.Clear;
finally
Dec(f_UnlockInProgress);
end;
if (f_UnlockInProgress = 0) and Assigned(f_LockList) then
begin
for l_Index := f_LockList.Count - 1 downto 0 do
f_LockList[l_Index].MenuUnlockedFixUp;
f_LockList.Clear;
end;
end;
end;
procedure TvcmCustomMenuManager.AddControlForUnlockPostBuild(const aCOntrol: IafwMenuUnlockedPostBuild);
begin
if f_LockList = nil then
f_LockList := TIafwMenuUnlockedPostBuildPtrList.MakeSorted;
f_LockList.Add(aControl);
end;
procedure TvcmCustomMenuManager.ListenerControlDestroying(const aCOntrol: IafwMenuUnlockedPostBuild);
begin
if Assigned(f_LockList) then
f_LockList.Remove(aCOntrol);
end;
function TvcmCustomMenuManager.ObjectByType(anObject : TvcmObject;
const anObjectName : String;
const aSubName : String = '';
ForceCreate : Boolean = False): TvcmBaseCollectionItem;
//override;
{-}
begin
Result := nil;
Case anObject of
vcm_objMainMenuItem :
if (MainMenuItems <> nil) then
Result := MainMenuItems.FindItemByName(anObjectName);
else
Result := inherited ObjectByType(anObject, anObjectName, aSubName, ForceCreate);
end;//Case anObject
end;
const
cTBName : array [TvcmEffectiveToolBarPos] of string =
('Top', 'Bottom', 'Left', 'Right');
function TvcmCustomMenuManager.ToolbarButtonSize(aToolbarButton : TCustomToolbarButton97;
var aSize : Integer) : Boolean;
// overload;
begin
Result := False;
with aToolbarButton do
begin
if Assigned(Images) then
if Images.Height > 16 then
begin
aSize := Max(aSize, Height);
Result := aToolbarButton.DisplayMode = dmBoth;
end;
end;
end;
procedure TvcmCustomMenuManager.ToolbarButtonSize(aToolbarButton : TCustomToolbarButton97);
// overload;
var
l_Size : Integer;
begin
l_Size := f_MaxControlToolbarSize;
ToolbarButtonSize(aToolbarButton, l_Size);
aToolbarButton.Height := l_Size;
aToolbarButton.Width := Max(l_Size, aToolbarButton.Width);
end;
procedure TvcmCustomMenuManager.ToolbarSize(aToolbar : TCustomToolbar97;
var aSize : Integer);
var
l_Index : Integer;
begin
aSize := f_MaxControlToolbarSize;
for l_Index := 0 to Pred(aToolbar.ControlCount) do
if aToolbar.Controls[l_Index] is TCustomToolbarButton97 then
(* выходим, максимальный размер получен *)
if ToolbarButtonSize(TCustomToolbarButton97(aToolbar.Controls[l_Index]), aSize) then
Break;
end;
procedure TvcmCustomMenuManager.InitToolbarMetrics(const aForm: TCustomForm);
var
l_Toolbar : TvcmToolbar;
l_Dock : TvcmDockDef;
l_Button : TToolbarButton97;
l_Date : TvcmDateEdit;
l_Edit : TvcmEdit;
begin
if (f_MaxControlToolbarSize = 0) and Assigned(SmallImages) and
(SmallImages.Count > 0) then
begin
l_Dock := TvcmDockDef.Create(aForm);
try
l_Dock.Parent := aForm;
l_Toolbar := TvcmToolbar.Create(l_Dock, l_Dock);
try
l_Toolbar.Parent := l_Dock;
l_Toolbar.BevelEdges := [beBottom, beLeft, beRight, beTop];
// TToolbarButton97:
l_Button := TToolbarButton97.Create(l_Toolbar);
with l_Button do
begin
Parent := l_Toolbar;
Images := SmallImages;
ImageIndex := 0;
end;//with l_Button do
// TvcmEdit:
l_Date := TvcmDateEdit.Create(l_Toolbar);
l_Date.Parent := l_Toolbar;
// TvcmDateEdit:
l_Edit := TvcmEdit.Create(l_Toolbar);
l_Edit.Parent := l_Toolbar;
// Вычислим:
l_Dock.ArrangeToolbars(False);
// f_MaxControlToolbarSize:
f_ButtonHeight := l_Button.Height;
f_MaxControlToolbarSize := Max(l_Button.Height, f_MaxControlToolbarSize);
f_MaxControlToolbarSize := Max(l_Date.Height, f_MaxControlToolbarSize);
f_MaxControlToolbarSize := Max(l_Edit.Height, f_MaxControlToolbarSize);
// f_SmallToolbarSize:
f_SmallToolbarSize := l_Toolbar.Height;
// f_DiffSize:
f_DiffSize := f_SmallToolbarSize - f_MaxControlToolbarSize;
// Процедура определения размера toolbar-а:
TB97Tlbr.g_ToolbarSize := ToolbarSize;
TB97Ctls.g_tbToolbarButtonSize := ToolbarButtonSize;
finally//l_Toolbar := TvcmToolbar.Create(l_Panel, nil);
vcmFree(l_Toolbar);
end;{try..finally}
finally//l_Dock := TvcmDockDef.Create(l_Panel);
vcmFree(l_Dock);
end;{try..finally}
end;//if (f_MaxControlToolbarSize = 0)
if aForm is TvcmMainForm then
TvcmMainForm(aForm).SmallToolbarSize(f_SmallToolbarSize);
end;//InitToolbarMetrics
function TvcmCustomMenuManager.GetDockParent(aForm : TCustomForm) : TWinControl;
function lp_FindDockContainer: TvcmDockContainer;
var
l_Component: TComponent;
begin
l_Component := aForm.FindComponent(c_vcmDockContainerName);
if l_Component <> nil then
begin
Assert(l_Component is TvcmDockContainer);
Result := TvcmDockContainer(l_Component);
end//if Assigned(l_Component) then
else
Result := nil;
end;//lp_FindDockContainer
{$IfDef vcmUseMainToolbarPanel}
function lp_MakeMainFormDockParent: TWinControl;
var
l_Index : Integer;
l_FormControl : TWinControl;
begin
Result := lp_FindDockContainer;
if Result <> nil then
Exit;
for l_Index := 0 to Pred(aForm.ControlCount) do
begin
if aForm.Controls[l_Index] is TWinControl then
begin
l_FormControl := TWinControl(aForm.Controls[l_Index]);
if l_FormControl.Align = alClient then
begin
Result := TvcmDockContainer.Create(aForm);
Result.Parent := aForm;
l_FormControl.Parent := Result;
Result.Align := alClient;
Break;
end;//if (l_Component is TWinControl)
end;//if aForm.Controls[l_Index] is TWinControl then
end;//for l_Index := 0 to Pred(aForm.ComponentCount) do
end;//lp_MakeMainFormDockParent
{$EndIf vcmUseMainToolbarPanel}
function lp_HasAlwaysOnTopControl: Boolean;
var
l_Index : Integer;
begin
Result := True;
for l_Index := Pred(aForm.ControlCount) downto 0 do
if Supports(aForm.Controls[l_Index], IafwAlwaysOnTopControl) then
Exit;
Result := False;
end;
function lp_MakeDockContainer: TWinControl;
var
l_Index : Integer;
l_Control : TControl;
begin
Result := nil;
if (aForm is TvcmEntityForm) and lp_HasAlwaysOnTopControl then
begin
Result := lp_FindDockContainer;
if Result = nil then
begin
Result := TvcmDockContainer.Create(aForm);
Result.Parent := aForm;
for l_Index := Pred(aForm.ControlCount) downto 0 do
begin
l_Control := aForm.Controls[l_Index];
if (l_Control <> Result) and not Supports(l_Control, IafwAlwaysOnTopControl) then
l_Control.Parent := Result;
end;//for l_Index :=
Result.Align := alClient;
end;//if Result = nil then
end;//if (aForm is TvcmEntityForm) and
end;//lp_MakeDockContainer
begin
{$IfDef vcmUseMainToolbarPanel}
if aForm is TvcmMainForm then
begin
Result := lp_MakeMainFormDockParent;
// Если контейнер для доков не был создан, то проверим наличие строки
// состояния и создадим контейнер при необходимости:
if Result = nil then
Result := lp_MakeDockContainer;
end;//if aForm is TvcmMainForm then
{$Else vcmUseMainToolbarPanel}
Result := lp_MakeDockContainer;
{$EndIf vcmUseMainToolbarPanel}
if Result = nil then
Result := aForm;
end;//GetDockParent
{$IfNDef DesignTimeLibrary}
function TvcmCustomMenuManager.BuildToolbar(aForm : TvcmEntityForm;
const aName : String;
const aCaption : IvcmCString;
aPos : TvcmEffectiveToolBarPos): TvcmToolbarDef;
//overload;
{-}
var
l_lnkMaximized : IvcmFormHandler;
l_lnkOpen : IvcmFormHandler;
l_lnkClose : IvcmFormHandler;
function lp_GetParentForDock(aForm: TvcmEntityForm): TvcmEntityForm;
function lp_DockButton(var aFormHandler : IvcmFormHandler;
const aForm : TvcmEntityForm;
const aHandler : TNotifyEvent;
const aHint : Il3CString): Boolean;
begin
if Assigned(aHandler) then
begin
aFormHandler := TvcmFormHandler.Make(aForm, aHandler, aHint);
Result := True;
end//Assigned(aHandler)
else
Result := False;
end;//lp_DockButton
begin//lp_GetParentForDock
Result := aForm.DefineDockContainer(aPos);
// Определим обработчики кнопок dock-а формы:
if not (aForm.ZoneType = vcm_ztForToolbarsInfo) then
begin
with TvcmEntityForm(Result) do
begin
// Close:
if (CanClose = vcm_ccEnable) then
begin
lp_DockButton(l_lnkClose, Result, DefaultQueryClose,
str_vcmCloseHint.AsCStr);
end;//CanClose = vcm_ccEnable
// Maximized:
if not lp_DockButton(l_lnkMaximized, Result, OnQueryMaximized,
str_vcmMaximizedHint.AsCStr) and
(TvcmEntityForm(Result) <> aForm) then
lp_DockButton(l_lnkMaximized, aForm, aForm.OnQueryMaximized,
str_vcmMaximizedHint.AsCStr);
// Open:
if not lp_DockButton(l_lnkOpen, Result, OnQueryOpen,
str_vcmOpenHint.AsCStr) and
(TvcmEntityForm(Result) <> aForm) then
lp_DockButton(l_lnkOpen, aForm, aForm.OnQueryOpen,
str_vcmOpenHint.AsCStr);
end;//with TvcmEntityForm(Result) do
end;//if not (aForm.ZoneType = vcm_ztForToolbarsInfo) then
end;//lp_GetParentForDock
function GetFormWeight(aForm : TvcmEntityForm): Integer;
begin//GetFormWeight
if not (aForm is TvcmMainForm) then
Result := 1
else
Result := 0;
end;//GetFormWeight
function lp_FindHandlersPublisher(const aControl: TWinControl): IvcmFormHandlersPublisher;
var
l_Parent: TWinControl;
begin
Result := nil;
l_Parent := aControl;
while (l_Parent <> nil) and
not Supports(l_Parent, IvcmFormHandlersPublisher, Result) do
l_Parent := l_Parent.Parent;
end;//lp_FindHandlersPublisher
function lp_FindHandlerWatcher(const aControl: TWinControl): IvcmCloseFormHandlerWatcher;
var
l_Parent: TWinControl;
begin
Result := nil;
l_Parent := aControl;
while (l_Parent <> nil) and
not Supports(l_Parent, IvcmCloseFormHandlerWatcher, Result) do
l_Parent := l_Parent.Parent;
end;//lp_FindHandlerWatcher
var
l_DockName : String;
l_Dock : TvcmDockDef;
l_NewDock : TvcmDockDef;
l_ParentForm : TCustomForm;
l_Index : TvcmEffectiveToolbarPos;
l_DockParent : TWinControl;
l_HandlersPublisher : IvcmFormHandlersPublisher;
l_HandlerWatcher : IvcmCloseFormHandlerWatcher;
begin
l_lnkMaximized := nil;
l_lnkOpen := nil;
l_lnkClose := nil;
l_ParentForm := lp_GetParentForDock(aForm);
Result := aForm.FindComponent(aName) As TvcmToolbarDef;
if (Result = nil) then
begin
l_Dock := nil;
{ Получим родителя для Dock }
l_DockParent := GetDockParent(l_ParentForm);
for l_Index := Low(TvcmEffectiveToolbarPos) to High(TvcmEffectiveToolbarPos) do
begin
if true{(l_Index in l_Poses)} then
begin
l_DockName := cTBName[l_Index] + 'Dock';
l_NewDock := l_DockParent.FindComponent(l_DockName) As TvcmDockDef;
if (l_NewDock = nil) then
begin
l_NewDock := TvcmDockDef.Make(l_DockParent, l_DockName, l_Index);
l_NewDock.SetFasten(GetFastenMode);
{$IfDef vcmUseSettings}
//{$IfDef vcmCustomizeDock} чьё? зачем?
l_NewDock.PopupMenu := Self.ToolbarPopup;
//{$EndIf vcmCustomizeDock}
{$EndIf vcmUseSettings}
//l_NewDock.OnRequestDock := ToolbarsGetSiteInfo;
aForm.AddDock(l_NewDock);
end;//l_NewDock = nil
if (aPos = l_Index) then
l_Dock := l_NewDock;
end;//l_Index in l_Poses
end;//for l_Index
if (l_Dock <> nil) then
begin
// Установим обработчики кнопок для Dock-а, в случае если не предусмотрен
// публикатор кнопок:
if (l_Dock.Align = alTop) then
begin
l_HandlersPublisher := lp_FindHandlersPublisher(l_DockParent);
if (l_HandlersPublisher = nil) then
l_Dock.SetHandlers(l_lnkMaximized, l_lnkOpen, l_lnkClose)
else
if (l_lnkClose <> nil) then
begin
Assert((l_lnkMaximized = nil) and (l_lnkOpen = nil));
l_HandlersPublisher.Publish(l_lnkClose);
end;//l_lnkClose <> nil
if Assigned(l_lnkClose) then
begin
l_HandlerWatcher := lp_FindHandlerWatcher(l_DockParent);
if Assigned(l_HandlerWatcher) then
l_HandlerWatcher.SetWatch(l_lnkClose);
end;//Assigned(l_lnkClose)
end;//if (l_Dock.Align = alTop) then
l_Dock.BeginUpdate;
try
Result := TvcmToolbar.Create(aForm, l_Dock);
with Result do
begin
if not (aForm.ZoneType = vcm_ztForToolbarsInfo) then
Parent := l_Dock; // может ещё что-то не нужно делать при "виртуальном" создании?
Name := aName;
Caption := vcmStr(aCaption);
Weight := GetFormWeight(aForm);
CloseMode := cmBackOnToolbar;
DockGroup := Integer(l_DockParent);
Collapsible := true;
HideExtraSeparators := true;
NearestParent := true;
//{$IfNDef vcmCustomizeDock}
{$IfDef vcmUseSettings}
PopupMenu := Self.ToolbarPopup;
{$EndIf vcmUseSettings}
//{$EndIf vcmCustomizeDock}
//AutoSize := true;
DragKind := dkDock;
DragMode := dmManual;
end;//with Result
finally
l_Dock.EndUpdate;
end;//try..finally
end;//l_Dock <> nil
end;//l_Toolbar = nil
end;
function TvcmCustomMenuManager.BuildToolbar(aForm : TvcmEntityForm;
aPos : TvcmEffectiveToolBarPos): TvcmToolbarDef;
//overload;
{-}
var
l_ToolbarName : String;
begin
Assert(OneToolbarPerForm);
Assert(aForm.CurUserTypeDef <> nil);
if true{(aPos in aForm.Toolbars)} then
begin
l_ToolbarName := GetOneToolbarPerFormName(aForm, aPos, 0);
Result := BuildToolbar(aForm, l_ToolbarName, aForm.CurUserTypeDef.Caption, aPos) ;
end//aPos in aForm.Toolbars
else
Result := nil;
end;
{$EndIf DesignTimeLibrary}
function TvcmCustomMenuManager.GetOneToolbarPerFormName(aForm : TvcmEntityForm;
aPos : TvcmEffectiveToolBarPos;
anIndex : Integer): String;
{-}
begin
Result := 'tb' + aForm.FormID.rName + cTBName[aPos];
if (anIndex > 0) then
Result := Result + IntToStr(anIndex);
end;
procedure TvcmCustomMenuManager.ReloadToolbars(const aForm : IvcmEntityForm);
//override;
{-}
{$IfDef vcmUseSettings}
var
l_Form : TvcmEntityForm;
l_Index : Integer;
{$EndIf vcmUseSettings}
{$IfDef vcmNeedL3}
var
l_List : TvcmLongintList;
{$EndIf vcmNeedL3}
begin
{$IfDef vcmUseSettings}
LockDocks;
try
LoadGlyphSize;
LoadGlyphColordepth;
{$IfDef vcmNeedL3}
l_Form := aForm.VCLWinControl As TvcmEntityForm;
l_List := TvcmLongintList.Create;
try
with l_Form do
begin
for l_Index := 0 to Pred(ComponentCount) do
if (Components[l_Index] Is TvcmToolbarDef) then
begin
TvcmToolbarDef(Components[l_Index]).Hide;
l_List.Add(longint(Components[l_Index]));
end;
for l_Index := 0 to l_List.Count - 1 do
begin
RemoveComponent(TvcmToolbarDef(l_List[l_Index]));
TvcmToolbarDef(l_List[l_Index]).Parent := nil;
if (Application.MainForm <> nil) and Application.MainForm.HandleAllocated then
PostMessage(Application.MainForm.Handle, vcm_msgFreeComponent, 0, LParam(l_List[l_Index]))
else
TvcmToolbarDef(l_List[l_Index]).Free;
end;
end;
finally
vcmFree(l_List);
end;
{$EndIf vcmNeedL3}
if (l_Form Is TvcmMainForm) then
begin
BuildFormToolbars(l_Form, [vcm_ooShowInMainToolbar]);
with vcmDispatcher do
for l_Index := 0 to Pred(ModulesCount) do
BuildMainToolbars(l_Form, Module[l_Index].ModuleDef);
MakeMainToolbarFromSettings(l_Form);
end
else
BuildFormToolbars(l_Form, [vcm_ooShowInChildToolbar]);
if aForm.ZoneType <> vcm_ztForToolbarsInfo then
begin
PostBuild(l_Form, true);
end;
finally
UnlockDocks;
end;
{$EndIf vcmUseSettings}
end;
function TvcmCustomMenuManager.GetToolbarName(aForm : TvcmEntityForm;
const aDef : IvcmOperationalIdentifiedUserFriendlyControl;
anIndex : Integer): String;
{-}
begin//GetToolbarName
if OneToolbarPerForm then
Result := GetOneToolbarPerFormName(aForm, aDef.ToolbarPos, anIndex)
else
begin
Result := aDef.Name;
Result := 'tb' + Result + cTBName[aDef.ToolBarPos];
if (anIndex > 0) then
Result := Result + IntToStr(anIndex);
end;//OneToolbarPerForm
end;//GetToolbarName
{$IfNDef DesignTimeLibrary}
function TvcmCustomMenuManager.BuildToolbar(aForm : TvcmEntityForm;
const aDef : IvcmOperationalIdentifiedUserFriendlyControl;
anIndex : Integer): TvcmToolbarDef;
{-}
var
l_ToolbarName : String;
l_Pos : TvcmEffectiveToolBarPos;
l_Caption : IvcmCString;
begin
if (aDef = nil) then
Result := nil
else
begin
l_Pos := aDef.ToolbarPos;
l_ToolbarName := GetToolbarName(aForm, aDef, anIndex);
if OneToolbarPerForm then
begin
if (aForm.UserTypes <> nil) AND
(aForm.UserTypes.Count > 0) then
l_Caption := vcmCStr(aForm.CurUserType.Caption)
else
l_Caption := aForm.CCaption;
end//OneToolbarPerForm
else
l_Caption := aDef.Caption;
Result := BuildToolbar(aForm, l_ToolbarName, l_Caption, l_Pos);
end;//aDef = nil
end;
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.BuildMainToolbars(aForm : TvcmEntityForm;
const aModuleDef : IvcmModuleDef);
{* - создает Toolbar'ы основной формы. }
var
l_ExcludePoses : TvcmEffectiveToolBarPoses;
{$IfDef vcmUseSettings}
l_Len : Integer;
l_Pos : TvcmEffectiveToolBarPos;
l_BtDef : TvcmButtonDef;
{$EndIf vcmUseSettings}
begin
l_ExcludePoses := [];
{$IfDef vcmUseSettings}
if OneToolbarPerForm AND (vcm_toModulesInMainToolbar in ToolbarOptions)then
begin
for l_Pos := Low(TvcmEffectiveToolBarPos) to High(TvcmEffectiveToolBarPos) do
begin
with f_MainToolbarDefs[l_Pos] do
begin
if rVisibleLoaded then
begin
Include(l_ExcludePoses, l_Pos);
if rVisible then
begin
l_Len := Length(rButtons);
if (l_Len = 0) then
l_BtDef.rPos := 0
else
l_BtDef.rPos := rButtons[Pred(l_Len)].rPos;
l_BtDef.rEn := aModuleDef;
LoadButtonsFromSettings(rUserType, rToolbarName, True, l_BtDef, rButtons);
end;//rVisible
end;//rVisibleLoaded
end;//with f_MainToolbarDefs[l_Pos]
end;//for l_Pos
end;//OneToolbarPerForm
{$EndIf vcmUseSettings}
if (vcm_toModulesInMainToolbar in ToolbarOptions) then
MakeToolbar(aForm, aModuleDef, [vcm_ooShowInMainToolbar], l_ExcludePoses);
if (vcm_toEntitiesInMainToolbar in ToolbarOptions) then
BuildEntitiesToolbars(aForm, aModuleDef.EntitiesDefIterator, [vcm_ooShowInMainToolbar], l_ExcludePoses);
end;
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
function TvcmCustomMenuManager.MakeToolbar(aForm : TvcmEntityForm;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOptions : TvcmOperationOptions;
anExcludePoses : TvcmEffectiveToolBarPoses): Boolean;
{-}
var
l_Toolbar : TvcmToolbarDef;
l_Operations : IvcmOperationsDefIterator;
begin
LockDocks;
try
if (aHolder = nil) then
Result := False
else
begin
//Assert(aForm.CurUserType <> nil);
// - http://mdp.garant.ru/pages/viewpage.action?pageId=378550015
if (aForm.CurUserType <> nil) AND
not aForm.CurUserType.CanHaveToolbars then
begin
Result := false;
Exit;
end;//not aForm.CurUserType.VisibleToUser
Result := true;
// - видимо где-то здесь можно "приструячить" цикл по Toolbar'ам формы
l_Operations := aHolder.OperationsDefIterator;
if (l_Operations <> nil) then begin
l_Toolbar := BuildToolbar(aForm, aHolder, 0);
if GetOpLock and (l_Toolbar <> nil) and (l_Toolbar.DockedTo <> nil) then
begin
if TvcmToolbarDockListManager.Instance.DockList.IndexOf(l_Toolbar.DockedTo) < 0 then
begin
TvcmToolbarDockListManager.Instance.DockList.Add(l_Toolbar.DockedTo);
l_Toolbar.DockedTo.BeginUpdate;
end;
l_Toolbar.DockedTo.SmartAlign := true;
end;
if (l_Toolbar <> nil) AND not (l_Toolbar.Pos in anExcludePoses) then
FillToolbar(aForm, l_Toolbar, aHolder, l_Operations, anOptions);
end;//l_Operations <> nil
end;//aHolder = nil
finally
UnlockDocks;
end;//try..finally
end;
{$EndIf DesignTimeLibrary}
function TvcmCustomMenuManager.BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOp : IvcmOperationDef;
const anOpOptions : TvcmOperationOptions;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType): TControl;
//overload;
{-}
var
l_Module : IvcmModuleDef;
l_Entity : IvcmEntityDef;
begin
Supports(aHolder, IvcmModuleDef, l_Module);
Supports(aHolder, IvcmEntityDef, l_Entity);
Result := BuildButton(aForm, aToolbar, l_Module, l_Entity, anOp, anOpOptions, anOptions, anIconText)
end;
function TvcmCustomMenuManager.BuildButton(aForm : TvcmEntityForm;
aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOp : IvcmOperationDef;
const anOptions : TvcmOperationOptions;
const anIconText : TvcmIconTextType): TControl;
//overload;
{-}
begin
if (anOp = nil) then
Result := nil
else
Result := BuildButton(aForm, aToolbar, aHolder, anOp, anOp.Options, anOptions, anIconText)
end;
procedure TvcmCustomMenuManager.CheckToolbar(var aToolBar: TvcmToolbarDef);
{-}
begin
with aToolbar do
vcmDeleteLastIfSeparator;
// - удаляем лишний разделитель
if (aToolBar.ButtonCount <= 0) then
vcmFree(aToolBar);
end;
//function TvcmCustomMenuManager.MergedToMainForm(aForm: TvcmEntityForm): Boolean;
//override;
{-}
//begin
// Result := GetParentForDock(aForm as TvcmEntityForm) is TvcmMainForm;
//end;//MergedToMainForm
procedure TvcmCustomMenuManager.PostBuild(aForm : TvcmEntityForm;
aFollowDocks : Boolean);
//override;
{-}
{$IfDef vcmUseSettings}
var
l_Index, l_BarIndex : Integer;
l_Toolbar : TvcmToolbarDef;
l_Point : TPoint;
//l_TopDock : TvcmDockDef;
//l_Form : TCustomForm;
l_FollowToolbar : TvcmToolbarDef;
l_List : TList;
function GetDockName(aDockPos: Cardinal): string;
begin
Result:='';
case TDockPosition(aDockPos) of
dpTop: Result := cTBName[vcm_tbpTop];
dpBottom: Result := cTBName[vcm_tbpBottom];
dpLeft: Result := cTBName[vcm_tbpLeft];
dpRight: Result := cTBName[vcm_tbpRight];
end;
Result := Result+'Dock';
end;
{$EndIf vcmUseSettings}
{$IfDef vcmUseSettings}
function LoadAndPlaceToolbar(const aUTName : String;
const aToolbar : TvcmToolbarDef): Boolean;
var
l_ToolbarPos : TvcmToolbarPositions;
l_Dock : TvcmDockDef;
l_DockParent : TWinControl;
begin
Result := vcmLoadToolbarPos(aUTName, aToolbar.Name, l_ToolbarPos);
l_DockParent := GetDockParent(aForm.DefineDockContainer(aToolbar.Pos));
if Result then
begin
l_Dock := l_DockParent.FindComponent(GetDockName(l_ToolbarPos.rDock)) as TvcmDockDef;
if (l_Dock <> nil) then
begin
if l_ToolbarPos.rFloating {and not GetFastenMode} then
begin
l_Point.X := l_ToolbarPos.rFloatX;
l_Point.Y := l_ToolbarPos.rFloatY;
aToolbar.FloatingPosition := l_Point;
aToolbar.DockPos := l_ToolbarPos.rPos;
aToolbar.DockRow := l_ToolbarPos.rRow;
aToolbar.FloatingWidth := l_ToolbarPos.rFloatingWidth;
aToolbar.Parent := l_Dock;
aToolbar.DockedTo := nil;
end//if l_ToolbarPos.rFloating
else
begin
l_Dock.BeginUpdate;
l_Dock.SmartAlign := False;
aToolbar.Parent := l_Dock;
l_Point.X := l_ToolbarPos.rFloatX;
l_Point.Y := l_ToolbarPos.rFloatY;
aToolbar.FloatingPosition := l_Point;
aToolbar.DockPos := l_ToolbarPos.rPos;
aToolbar.DockRow := l_ToolbarPos.rRow;
aToolbar.FloatingWidth := l_ToolbarPos.rFloatingWidth;
l_Dock.EndUpdate;
end;//if l_ToolbarPos.rFloating
end;//if (l_Dock <> nil) then
end;//if Result then
end;//LoadAndPlaceToolbar
{$EndIf vcmUseSettings}
begin
inherited;
{$IfDef vcmUseSettings}
LockDocks;
try
if (aForm.UserTypes.Count > 0) then
begin
l_Index := 0;
while l_Index < aForm.ComponentCount do
begin
if aForm.Components[l_Index] is TvcmToolbarDef then
begin
l_Toolbar := aForm.Components[l_Index] as TvcmToolbarDef;
if GetOpLock and (l_Toolbar.DockedTo <> nil) then
if TvcmToolbarDockListManager.Instance.DockList.IndexOf(l_Toolbar.DockedTo) < 0 then
begin
TvcmToolbarDockListManager.Instance.DockList.Add(l_Toolbar.DockedTo);
l_Toolbar.DockedTo.BeginUpdate;
end;
if aFollowDocks and (l_Toolbar.DockedTo <> nil) then
begin
//for l_BarIndex := 0 to l_Toolbar.DockedTo.ToolbarCount-1 do
//видимо, при установленном BeginUpdate, DockVisibleList(и, как следствие, TOolbarCount)
//не обновляются.
// Делаем через временный список, т.к. в Conotols входят и кнопки, которые
// перекладываются вместе с тулбаром на другой док и изменение ConotolCount
// может быть более чем на 1...
l_List := TList.Create;
try
for l_BarIndex := l_Toolbar.DockedTo.ControlCount-1 downto 0 do
if l_Toolbar.DockedTo.Controls[l_BarIndex] is TvcmToolbarDef then
l_List.Add(l_Toolbar.DockedTo.Controls[l_BarIndex]);
for l_BarIndex := l_List.Count-1 downto 0 do
begin
l_FollowToolbar := TvcmToolbarDef(l_List[l_BarIndex]);
if l_FollowToolbar.Owner is TvcmEntityForm and
(TvcmEntityForm(l_FollowToolbar.Owner).UserTypes.Count > 0) then
LoadAndPlaceToolbar((l_FollowToolbar.Owner as TvcmEntityForm).
UserTypes[(l_FollowToolbar.Owner as TvcmEntityForm).UserType].Name,
l_FollowToolbar);
end;
finally
l_List.Free;
end;
{
//Делаем задом наперед - поскольку тулбар может переехать на другой док
for l_BarIndex := l_Toolbar.DockedTo.ControlCount-1 downto 0 do
if l_Toolbar.DockedTo.Controls[l_BarIndex] is TvcmToolbarDef then
begin
l_FollowToolbar := l_Toolbar.DockedTo.Controls[l_BarIndex] as TvcmToolbarDef;
if l_FollowToolbar.Owner is TvcmEntityForm and
(TvcmEntityForm(l_FollowToolbar.Owner).UserTypes.Count > 0) then
LoadAndPlaceToolbar((l_FollowToolbar.Owner as TvcmEntityForm).
UserTypes[(l_FollowToolbar.Owner as TvcmEntityForm).UserType].Name,
l_DockParent, l_FollowToolbar);
end;}
end
else
LoadAndPlaceToolbar(aForm.UserTypes[aForm.UserType].Name, l_Toolbar);
end;
inc(l_Index);
end;
(*
Открутил пока загрузку главного тулбара совместно с текущим
l_Form := aForm._NativeMainForm.asForm.VCLForm;
// отсекаем формы, тулбары которых не мержатся в главную форму
if MergedToMainForm(aForm as TvcmEntityForm) then
begin
l_DockParent := GetDockParent(GetParentForDock(l_Form as TvcmEntityForm));
for l_Index := 0 to l_Form.ComponentCount - 1 do
begin
if l_Form.Components[l_Index] is TvcmToolbarDef then
begin
l_Toolbar := l_Form.Components[l_Index] as TvcmToolbarDef;
if not LoadAndPlaceToolbar(aForm.UserTypes[aForm.UserType].Name, l_DockParent, l_Toolbar) then
begin
// дефолтное размещение главного тулбара
l_TopDock := l_DockParent.FindComponent(cTBName[vcm_tbpTop]+'Dock') as TvcmDockDef;
if l_TopDock <> nil then
begin
l_TopDock.BeginUpdate;
{$EndIf vcmUseTB97}
l_Toolbar.DockPos := 0;
l_Toolbar.DockRow := 0;
l_Toolbar.Parent := l_TopDock;
{$IfDef vcmUseTB97}
l_TopDock.EndUpdate;
end;
end;
end;
end;
end;
*)
end;
finally
UnlockDocks;
end;
{$EndIf vcmUseSettings}
end;
procedure TvcmCustomMenuManager.RestoreOpStatus;
var
l_Index : Integer;
l_List : TvcmObjectList;
begin
inherited;
BeginOp;
assert((f_SaveLockCounter.Count > 0) and (f_SaveDockList.Count > 0));
f_LockCounter := f_SaveLockCounter[f_SaveLockCounter.Count - 1];
f_SaveLockCounter.Delete(f_SaveLockCounter.Count - 1);
l_List := TvcmObjectList(f_SaveDockList[f_SaveDockList.Count - 1]).Use;
try
f_SaveDockList.Delete(f_SaveDockList.Count - 1);
TvcmToolbarDockListManager.Instance.DockList.Clear;
TvcmToolbarDockListManager.Instance.DockList.JoinWith(l_List);
finally
vcmFree(l_List);
end;//try..finally
for l_Index := 0 to TvcmToolbarDockListManager.Instance.DockList.Count - 1 do
TvcmDockDef(TvcmToolbarDockListManager.Instance.DockList[l_Index]).BeginUpdate;
end;
function TvcmCustomMenuManager.GetOpLock: Boolean;
begin
Result := f_LockCounter > 0;
end;
procedure TvcmCustomMenuManager.BackupOpStatus;
var
l_List: TvcmObjectList;
begin
f_SaveLockCounter.Add(f_LockCounter);
l_List:= TvcmObjectList.Make;
try
l_List.JoinWith(TvcmToolbarDockListManager.Instance.DockList);
f_SaveDockList.Add(l_List);
finally
vcmFree(l_List);
end;//try..finally
f_LockCounter := 1;
EndOp;
inherited;
end;
procedure TvcmCustomMenuManager.BeginOp{(aControl: TObject; aStr: string)};
begin
inherited;
LockDocks;
end;
procedure TvcmCustomMenuManager.EndOp{(aControl: TObject; aStr: string)};
begin
UnlockDocks;
inherited;
end;
function TvcmCustomMenuManager.GetFastenMode: Boolean;
begin
Result := False;
{$IfDef vcmUseSettings}
if f_FastenToolbars = -1 then
vcmLoadFastenMode(Result)
else
Result := f_FastenToolbars = 0;
{$EndIf vcmUseSettings}
if Result then
f_FastenToolbars := 0
else
f_FastenToolbars := 1;
end;
procedure TvcmCustomMenuManager.FastenToolbars;
procedure lp_ChangeToolbarsMode(const aForm : IvcmEntityForm;
const aCheckMain : Boolean = False);
var
l_Count : Integer;
l_Index : Integer;
l_Container : TvcmDockContainer;
begin
//if (aForm.VCLWinControl is TvcmEntityForm) then
for l_Count := 0 to aForm.VCLWinControl.ComponentCount - 1 do
begin
if aForm.VCLWinControl.Components[l_Count] is TvcmDockDef then
(aForm.VCLWinControl.Components[l_Count] as TvcmDockDef).SetFasten(GetFastenMode)
else
if aCheckMain and (aForm.VCLWinControl.Components[l_Count] is TvcmDockContainer) then
begin
l_Container := aForm.VCLWinControl.Components[l_Count] as TvcmDockContainer;
for l_Index := 0 to l_Container.ComponentCount - 1 do
if l_Container.Components[l_Index] is TvcmDockDef then
(l_Container.Components[l_Index] as TvcmDockDef).SetFasten(GetFastenMode)
end;//if aCheckMain
end;//for l_Count := 0
end;//lp_ChangeToolbarsMode
procedure lp_InvertFastenMode;
begin//lp_InvertFastenMode
if f_FastenToolbars = -1 then
GetFastenMode;
if f_FastenToolbars = 0 then
f_FastenToolbars := 1
else
f_FastenToolbars := 0;
end;//lp_InvertFastenMode
var
l_Index : Integer;
l_Form : IvcmEntityForm;
begin
lp_InvertFastenMode;
with vcmDispatcher do
for l_Index := 0 to EntitiesCount - 1 do
if Supports(Entity[l_Index], IvcmEntityForm, l_Form) then
lp_ChangeToolbarsMode(l_Form);
with vcmDispatcher do
for l_Index := 0 to FormDispatcher.MainFormsCount - 1 do
if Supports(FormDispatcher.MainForm[l_Index], IvcmEntityForm, l_Form) then
lp_ChangeToolbarsMode(l_Form, True);
{$IfDef vcmUseSettings}
vcmSaveFastenMode(GetFastenMode);
{$EndIf vcmUseSettings}
end;
procedure TvcmCustomMenuManager.FillToolbar(aForm : TvcmEntityForm;
var aToolBar : TvcmToolbarDef;
const aHolder : IvcmOperationalIdentifiedUserFriendlyControl;
const anOperations : IvcmOperationsDefIterator;
const anOptions : TvcmOperationOptions);
{-}
begin
if (aToolBar <> nil) then
begin
if OneToolbarPerForm then
BuildSeparator(aToolbar);
aToolbar.BeginUpdate;
try
while (BuildButton(aForm, aToolbar, aHolder, anOperations.Next, anOptions) <> nil) do ;
finally
aToolbar.EndUpdate;
end;//try..finally
CheckToolbar(aToolbar);
end;//aToolBar <> nil
end;
{$IfDef vcmUseSettings}
function TvcmCustomMenuManager.LoadButtonsFromSettings(const aUserType : IvcmUserTypeDef;
const aToolbar : String;
AddUnsavedButton: Boolean;
var theButton : TvcmButtonDef;
var theButtons : TvcmButtonDefs): Boolean;
procedure l_AddButton;
var
l_Len : Integer;
procedure l_InsertButton(anIndex: Integer);
var
l_Index : Integer;
l_NewButtons : TvcmButtonDefs;
l_MaxPos : Integer;
begin//l_InsertButton
if not theButtons[anIndex].rLoaded then
l_MaxPos := theButton.rPos
else
l_MaxPos := -1;
SetLength(l_NewButtons, Succ(l_Len));
for l_Index := 0 to Pred(anIndex) do
l_NewButtons[l_Index] := theButtons[l_Index];
for l_Index := anIndex to Pred(l_Len) do
begin
l_NewButtons[l_Index + 1] := theButtons[l_Index];
if l_MaxPos > -1 then
l_NewButtons[l_Index + 1].rPos := l_MaxPos + l_Index - anIndex + 1;
end;
l_NewButtons[anIndex] := theButton;
theButtons := l_NewButtons;
end;//l_InsertButton
var
l_Index : Integer;
begin//l_AddButton
l_Len := Length(theButtons);
if theButton.rLoaded then
for l_Index := 0 to Pred(l_Len) do
if (theButtons[l_Index].rPos > theButton.rPos) or
(not theButtons[l_Index].rLoaded) then
begin
l_InsertButton(l_Index);
Exit;
end;//theButtons[l_Index].rPos > theButton.rPos
SetLength(theButtons, Succ(l_Len));
theButtons[l_Len] := theButton;
if (not theButton.rLoaded) and
(l_Len > 0) then
theButtons[l_Len].rPos := theButtons[l_Len - 1].rPos + 1;
end;//l_AddButton
var
l_Operations : IvcmOperationsDefIterator;
l_Bt : TvcmButtonParams;
l_NotLoadedNeedSep : Boolean;
begin
if (theButton.rEn = nil) then
Result := False
else
begin
Result := true;
l_NotLoadedNeedSep := true;
theButton.rNeedSep := true;
theButton.rIconText := False;
// - каждая сущность по умолчанию открывает группу
l_Operations := theButton.rEn.OperationsDefIterator;
if (l_Operations <> nil) then
begin
while true do
begin
theButton.rOp := l_Operations.Next;
if (theButton.rOp = nil) then
break;
if (theButton.rOp.OperationType in vcmToolbarOpTypes) then
begin
if vcmLoadButtonParams(aUserType.Name, aToolbar,
theButton.rEn.Name, theButton.rOp.Name, l_Bt) then
begin
if l_Bt.rVisible then
begin
if (l_Bt.rPos = High(Cardinal)) then
theButton.rPos := Succ(theButton.rPos)
else
theButton.rPos := l_Bt.rPos;
theButton.rOptions := vcm_AllOperationOptions;
// - показываем независимо от настроек по умолчанию
theButton.rNeedSep := l_Bt.rNeedSep;
theButton.rIconText := l_Bt.rIconText;
theButton.rLoaded := True;
// - это тоже надо из настроек читать
end//l_Bt.rVisible
else
continue;
end//vcmLoadButtonParams
else
begin
if not AddUnsavedButton then
Continue;
if l_NotLoadedNeedSep then
begin
theButton.rNeedSep := True;
l_NotLoadedNeedSep := False;
end;
theButton.rPos := Succ(theButton.rPos);
theButton.rOptions := theButton.rOp.Options;
theButton.rIconText := theButton.rOp.OperationType = vcm_otTextButton;
theButton.rLoaded := False;
end;//vcmLoadButtonParams
l_AddButton;
theButton.rNeedSep := False;
// - скидываем флаг по умолчанию
end;//theButton.rOp.OperationType in vcmToolbarOpTypes
end;//while true
end;//l_Operations <> nil
end;//theButton.rEn = nil
end;
procedure TvcmCustomMenuManager.MakeToolbarFromSettings(aForm : TvcmEntityForm;
const aToolbarName : String;
aPos : TvcmEffectiveToolBarPos;
const anOptions : TvcmOperationOptions;
const theButtons : TvcmButtonDefs);
{-}
var
l_Index: Integer;
l_Toolbar: TvcmToolbarDef;
begin
if (Length(theButtons) > 0) then
// http://mdp.garant.ru/pages/viewpage.action?pageId=235876230&focusedCommentId=236718542#comment-236718542
begin
l_Toolbar := BuildToolbar(aForm, aToolbarName, aForm.CurUserTypeDef.Caption, aPos);
if (l_Toolbar <> nil) and
(l_Toolbar.DockedTo <> nil) and
GetOpLock and
(TvcmToolbarDockListManager.Instance.DockList.IndexOf(l_Toolbar.DockedTo) < 0) then
begin
TvcmToolbarDockListManager.Instance.DockList.Add(l_Toolbar.DockedTo);
l_Toolbar.DockedTo.BeginUpdate;
end;
for l_Index := Low(theButtons) to High(theButtons) do
begin
with theButtons[l_Index] do
begin
if rNeedSep then
BuildSeparator(l_Toolbar);
if rIconText then
BuildButton(aForm, l_Toolbar, rEn, rOp, rOptions, anOptions, vcm_itIconText)
else
BuildButton(aForm, l_Toolbar, rEn, rOp, rOptions, anOptions, vcm_itIcon)
end;//with theButtons[l_Index]
end;//for l_Index
CheckToolbar(l_Toolbar);
end;//Length(l_BtDefs) > 0
end;
{$EndIf vcmUseSettings}
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.BuildFormToolbars(aForm : TvcmEntityForm;
const anOptions : TvcmOperationOptions);
{-}
var
l_ExcludePoses : TvcmEffectiveToolBarPoses;
{$IfDef vcmUseSettings}
l_ToolbarName : String;
l_UserType : IvcmUserTypeDef;
l_Pos : TvcmEffectiveToolBarPos;
//l_Poses : TvcmToolbarPoses;
l_Entities : IvcmEntitiesDefIterator;
l_BtDef : TvcmButtonDef;
l_BtDefs : TvcmButtonDefs;
l_ToolbarVis : Boolean;
{$EndIf vcmUseSettings}
begin
LockDocks;
try
l_ExcludePoses := [];
{$IfDef vcmUseSettings}
if OneToolbarPerForm then
begin
// - проверка бредовая, просто я пока не понимаю как грузить несколько Toolbar'ов
l_UserType := aForm.CurUseToolbarOfUserType;
if (l_UserType <> nil) then
begin
if not vcmIsNil(l_UserType.Caption) then
begin
//l_Poses := aForm.Toolbars;
for l_Pos := Low(TvcmEffectiveToolBarPos) to High(TvcmEffectiveToolBarPos) do
begin
if (aForm Is TvcmMainForm) then
begin
with f_MainToolbarDefs[l_Pos] do
begin
rVisibleLoaded := False;
rVisible := False;
rUserType := l_UserType;
end;//with f_MainToolbarDefs[l_Pos]
end;
if true{(l_Pos in l_Poses)} then
begin
l_ToolbarName := GetOneToolbarPerFormName(aForm, l_Pos, 0);
if (aForm Is TvcmMainForm) then
begin
with f_MainToolbarDefs[l_Pos] do
begin
rToolbarName := l_ToolbarName;
end;//with f_MainToolbarDefs[l_Pos]
end;//aForm Is TvcmMainForm
if vcmLoadToolbarVisible(l_UserType.Name, l_ToolbarName, l_ToolbarVis) then
begin
if (aForm Is TvcmMainForm) then
begin
with f_MainToolbarDefs[l_Pos] do
begin
rVisibleLoaded := true;
rVisible := l_ToolbarVis;
end;//with f_MainToolbarDefs[l_Pos]
end;//aForm Is TvcmMainForm
Include(l_ExcludePoses, l_Pos);
if l_ToolbarVis then
begin
l_BtDef.rPos := 0;
l_Entities := aForm.GetEntitiesDefIterator;
if (l_Entities <> nil) then
begin
while true do
begin
l_BtDef.rEn := l_Entities.Next;
if not LoadButtonsFromSettings(l_UserType,
l_ToolbarName,
Assigned(l_BtDef.rEn) and (l_Pos = l_BtDef.rEn.ToolBarPos),
l_BtDef,
l_BtDefs) then
break;
end;//while true
if (aForm Is TvcmMainForm) then
f_MainToolbarDefs[l_Pos].rButtons := l_BtDefs
else
MakeToolbarFromSettings(aForm, l_ToolbarName, l_Pos, anOptions, l_BtDefs);
l_BtDefs := nil;
end;//l_Entities <> nil
end;//l_ToolbarVis
end;//vcmToolbarVisible
end;//l_Pos in l_Poses
end;//for l_Pos
end;//not vcmIsNil(l_UserType.Caption)
end;//l_UserType <> nil
end;//OneToolbarPerForm
{$EndIf vcmUseSettings}
BuildEntitiesToolbars(aForm, aForm.GetEntitiesDefIterator, anOptions, l_ExcludePoses);
finally
UnlockDocks;
end;//try..finally
end;
{$EndIf DesignTimeLibrary}
procedure TvcmCustomMenuManager.OverridePopupMenu(const aForm: TCustomForm);
procedure lp_SetComponentPopup(aComponent: TComponent);
var
l_PropInfo : PPropInfo;
begin//SetComponentPopup
l_PropInfo := GetPropInfo(aComponent, 'PopupMenu');
if (l_PropInfo <> nil) then begin
if (GetObjectProp(aComponent, l_PropInfo) = nil) then begin
// - не затираем чужое меню
if (f_Popup = nil) then begin
f_Popup := TvcmPopupMenu.Create(Self);
f_Popup.AutoHotkeys := maManual;
{$IfNDef DesignTimeLibrary}
{$IfDef l3HackedVCL}
f_Popup.DrawGraphicChecks := true;
{$EndIf l3HackedVCL}
{$EndIf DesignTimeLibrary}
f_Popup.OnPopup := DoPopup;
f_Popup.AutoLineReduction := maAutomatic;
if (Self.SmallImages <> nil) then
f_Popup.Images := Self.SmallImages
else
if (Actions <> nil) then
f_Popup.Images := Actions.Images;
end;//f_Popup = nil
SetObjectProp(aComponent, l_PropInfo, f_Popup);
l_PropInfo := GetPropInfo(aComponent, 'AutoPopup');
if (l_PropInfo <> nil) then
SetOrdProp(aComponent, l_PropInfo, Ord(true));
end;//GetObjectProp(aComponent, l_PropInfo) = nil
end;//l_PropInfo <> nil
end;//SetComponentPopup
var
l_Index : Integer;
begin
with aForm do
for l_Index := 0 to Pred(ComponentCount) do
lp_SetComponentPopup(Components[l_Index]);
end;
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.BuildEntitiesToolbars(aForm : TvcmEntityForm;
const anEntities : IvcmEntitiesDefIterator;
const anOptions : TvcmOperationOptions;
anExcludePoses : TvcmEffectiveToolBarPoses);
{-}
begin
if (anEntities <> nil) then
while MakeToolbar(aForm, anEntities.Next, anOptions, anExcludePoses) do ;
end;
{$EndIf DesignTimeLibrary}
{$IfNDef DesignTimeLibrary}
procedure TvcmCustomMenuManager.RegisterChildInMenu(aForm: TvcmEntityForm);
//override;
{* - регистрирует дочернюю форму в меню, toolbar'ах, etc. Для перекрытия в потомках. }
procedure BuildMainMenu;
var
l_Item : TMenuItem;
l_Main : TMenuItem;
l_GroupIndex : Integer;
begin//BuildMainMenu
if not (vcm_moEntitiesInMainMenu in MenuOptions) AND
(vcm_moEntitiesInChildMenu in MenuOptions) then begin
l_Main := vcmGetMainMenu(Application.MainForm);
with l_Main do
l_GroupIndex := Items[Pred(Count)].GroupIndex;
l_Item := vcmGetMainMenu(aForm);
vcmMakeEntitiesMenus(l_Item, aForm.GetEntitiesDefIterator, [vcm_ooShowInChildMenu], False, vcm_icNotFound, l_Main);
l_Item.Items[0].GroupIndex := Succ(l_GroupIndex);
end;//not NeedMainEntitiesMenu
end;//BuildMainMenu
begin
(* Удаляем windows окно, чтобы во время долгосрочных операций построения меню и
toolbar-ов окна не прорисовывались. Окно формы восстанавливается в
TvcmEntityForm.Make *)
//THackWinControl(aForm).DestroyHandle;
OverridePopupMenu(aForm);
BuildMainMenu;
if (vcm_toEntitiesInChildToolbar in ToolbarOptions) then
BuildFormToolbars(aForm, [vcm_ooShowInChildToolbar]);
end;
{$EndIf DesignTimeLibrary}
procedure TvcmCustomMenuManager.pm_SetActions(anActions: TCustomActionList);
{-}
begin
if (f_Actions <> anActions) then begin
f_Actions := anActions;
vcmMenus.vcmSetActionList(f_Actions);
end;//f_Actions <> anActions
end;
procedure TvcmCustomMenuManager.pm_SetDockButtonsImageList(const Value : TCustomImageList);
begin
f_DockButtonsImageList := Value;
end;
procedure TvcmCustomMenuManager.pm_SetMainMenuItems(aValue: TvcmMenuItemsCollection);
{-}
begin
f_MainMenuItems.Assign(aValue);
end;
procedure TvcmCustomMenuManager.DoPopup(Sender: TObject);
{-}
var
l_Form : TCustomForm;
begin
l_Form := afw.GetParentForm(f_Popup.PopupComponent);
if (l_Form Is TvcmEntityForm) then
begin
f_PopupForm := TvcmEntityForm(l_Form);
f_Popup.Items.Clear;
vcmMakeEntitiesMenus(f_Popup.Items,
TvcmEntitiesDefIteratorForContextMenu.Make(f_PopupForm.GetEntitiesDefIterator),
[vcm_ooShowInContextMenu],
not (vcm_moEntitesInContextMenu in MenuOptions),
vcm_icExternal,
nil,
CheckPopup);
end;//l_Form Is TvcmEntityForm
end;
type
THackPopupMenu = class(TMenu)
private
FPopupPoint: TPoint;
end;//THackPopupMenu
THackControl = class(TControl);
function TvcmCustomMenuManager.FillPopupMenu(aPopupPoint : TPoint;
aPopupComponent : TComponent): TvcmPopupMenu;
{-}
begin
Result := f_Popup;
if (aPopupComponent is TControl) then
if PtInRect(TControl(aPopupComponent).ClientRect, aPopupPoint) then
THackPopupMenu(Result).FPopupPoint := TControl(aPopupComponent).ClientToScreen(aPopupPoint)
else
begin
repeat
with aPopupPoint, TControl(aPopupComponent) do
begin
X := X + Left;
Y := Y + Top;
aPopupComponent := Parent;
end;
until Assigned(aPopupComponent) and (aPopupComponent is TControl) and (THackControl(aPopupComponent).GetPopupMenu <> nil);
FillPopupMenu(aPopupPoint, aPopupComponent);
Exit;
end
else
THackPopupMenu(Result).FPopupPoint := aPopupPoint;
f_Popup.PopupComponent := aPopupComponent;
DoPopup(f_Popup);
{$IfNDef DesignTimeLibrary}
{$IfDef l3HackedVCL}
f_Popup.Items.CallInitiateActions;
{$EndIf l3HackedVCL}
{$EndIf DesignTimeLibrary}
f_Popup.Items.RethinkHotkeys;
f_Popup.Items.RethinkLines;
end;
function TvcmCustomMenuManager.CheckPopup(const anEntityDef: IvcmEntityDef): IvcmEntity;
{-}
begin
with f_Popup, f_PopupForm do
if (PopupComponent Is TControl) then
with TControl(PopupComponent).ScreenToClient(PopupPoint) do
Result := GetInnerForControl(anEntityDef.ID, PopupComponent, X, Y)
else
Result := GetInnerForControl(anEntityDef.ID, PopupComponent);
end;
procedure TvcmCustomMenuManager.CleanupSaveDockList(anItem: TvcmDockDef);
var
I: Integer;
lList: TvcmObjectList;
begin
for I := 0 to f_SaveDockList.Count-1 do
begin
if f_SaveDockList[I] is TvcmObjectList then
begin
lList := TvcmObjectList(f_SaveDockList[I]);
lList.Remove(anItem);
end;
end;
end;
procedure TvcmCustomMenuManager.LoadGlyphSize(aDefault : Boolean = False);
var
l_Size: Cardinal;
l_IDX: TvcmGlyphSize;
begin
{$IfDef vcmUseSettings}
if vcmLoadCardinalParam([vcmPathPair('GlyphSize')], l_Size, aDefault) then
for l_IDX := Low(TvcmGlyphSize) to High(TvcmGlyphSize) do
if c_GlyphSizeMap[l_IDX] = l_Size then
begin
GlyphSize := l_IDX;
Break;
end;
{$EndIf}
end;
procedure TvcmCustomMenuManager.LoadGlyphColordepth(aDefault : Boolean = False);
var
l_Size: Cardinal;
begin
{$IfDef vcmUseSettings}
if vcmLoadCardinalParam([vcmPathPair('GlyphColordepth')], l_Size, aDefault) then
GlyphColordepth := TvcmGlyphColordepth(l_Size);
{$EndIf}
end;
procedure TvcmCustomMenuManager.pm_SetGlyphSize(const Value: TvcmGlyphSize);
begin
if f_GlyphSize <> Value then
begin
f_GlyphSize := Value;
if Assigned(f_OnGlyphSizeChanged) then
f_OnGlyphSizeChanged(Self);
end;
end;
procedure TvcmCustomMenuManager.pm_SetGlyphColordepth(const Value: TvcmGlyphColordepth);
begin
// Присваиваем всегда. Это делается для того, чтобы работало автоопределение.
f_GlyphColordepth := Value;
if Assigned(f_OnGlyphColordepthChanged) then
f_OnGlyphColordepthChanged(Self);
end;
procedure TvcmCustomMenuManager.RestoreGlyphSize;
begin
LoadGlyphSize(True);
end;
procedure TvcmCustomMenuManager.RestoreGlyphColordepth;
begin
LoadGlyphColordepth(True);
end;
procedure TvcmCustomMenuManager.StoreGlyphSize;
begin
{$IfDef vcmUseSettings}
vcmSaveCardinalParam([vcmPathPair('GlyphSize')], c_GlyphSizeMap[GlyphSize]);
{$EndIf}
end;
procedure TvcmCustomMenuManager.StoreGlyphColordepth;
begin
{$IfDef vcmUseSettings}
vcmSaveCardinalParam([vcmPathPair('GlyphColordepth')], Ord(GlyphColordepth));
{$EndIf}
end;
// start class TvcmToolButtonDef
function TvcmToolButtonDef.HackCheck: Boolean;
//override;
{-}
begin
Result := False;
end;
function TvcmToolButtonDef.NeedAutoDown: Boolean;
//override;
{-}
begin
Result := False;
end;
function TvcmToolButtonDef.AutoAllUp: Boolean;
//override;
{-}
begin
Result := true;
end;
function TvcmToolButtonDef.GetActionLinkClass: TControlActionLinkClass;
//override;
{-}
begin
Result := TvcmToolButtonDefActionLink;
end;
function TvcmToolButtonDef.IsIconText: Boolean;
{-}
begin
Result := DisplayMode= dmBoth;
end;
// start class TvcmToolButtonDefActionLink
destructor TvcmToolButtonDefActionLink.Destroy;
//override;
begin
inherited;
end;
procedure RequestClearPopup(aPopup : TPopupMenu);
begin
if (Application.MainForm <> nil) then
PostMessage(Application.MainForm.Handle, vcm_msgClearPopup, 0, LParam(aPopup));
end;
procedure TvcmToolButtonDefActionLink.ParamsChanged(const anAction: IvcmAction);
{-}
procedure DoButtonPopup(aButton: TvcmToolButtonDef);
{-}
var
l_Popup : TPopupMenu;
begin
with aButton do
begin
l_Popup := DropdownMenu;
if not anAction.HasInfoForCombo then
begin
if (l_Popup <> nil) then
begin
DropdownMenu := nil;
if (l_Popup.Owner <> nil) then
l_Popup.Owner.RemoveComponent(l_Popup);
RequestClearPopup(l_Popup);
end;//l_Popup <> nil
Exit;
end;//not anAction.HasInfoForCombo
if (l_Popup = nil) then
begin
l_Popup := TvcmButtonPopupMenu.Create(aButton);
{$IfNDef DesignTimeLibrary}
{$IfDef l3HackedVCL}
l_Popup.DrawGraphicChecks := true;
{$EndIf l3HackedVCL}
{$EndIf DesignTimeLibrary}
DropdownMenu := l_Popup;
end;//l_Popup = nil
end;//with aButton
l_Popup.Items.Clear;
vcmMakeComboMenu(TvcmAction(Action), l_Popup.Items);
end;
var
l_Form : TafwCustomForm;
l_MF : IvcmEntityForm;
begin
if not vcmDispatcher.InOp(true) AND
(Action Is TvcmOperationAction) AND
(TvcmOperationAction(Action).OpDef.OperationType in vcm_ComboOperations) AND
(Action.ActionComponent = nil) then
begin
l_Form := afw.GetTopParentForm(FClient);
if (l_Form <> nil) then
begin
l_MF := vcmDispatcher.FormDispatcher.CurrentMainForm;
if (l_MF.VCLWinControl = l_Form) then
try
DoButtonPopup(FClient As TvcmToolButtonDef);
except
FClient := nil;
try
l3System.Msg2Log('TvcmToolButtonDefActionLink.ParamsChanged fail');
l3System.Msg2Log(TvcmOperationAction(Self.Action).Caption);
l3System.Msg2Log(Self.Action.Name);
except
l3System.Msg2Log('TvcmToolButtonDefActionLink.ParamsChanged info fail');
end;//try..except
end;//try..except
end;//l_Form <> nil
end;//not vcmDispatcher.InOp(true)
end;
procedure TvcmToolButtonDefActionLink.ParamsChanging(const anAction: IvcmAction);
{-}
begin
end;
// start class TvcmPopupMenu
procedure TvcmPopupMenu.ClearInPopup;
{-}
begin
f_InPopup := false;
end;
procedure TvcmPopupMenu.Popup(X, Y: Integer);
//override;
{-}
begin
f_InPopup := true;
inherited;
RequestClearPopup(Self);
end;
function TvcmPopupMenu.IsShortCut(var Message: TWMKey): Boolean;
//override;
{-}
begin
if f_InPopup then
Result := inherited IsShortCut(Message)
else
begin
Result := false;
RequestClearPopup(Self);
end;//f_InPopup
end;
initialization
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VCM\implementation\Components\vcmMenuManager.pas initialization enter'); {$EndIf}
{$IfNDef DesignTimeLibrary}
TtfwClassRef.Register(TvcmToolbar);
TtfwClassRef.Register(Ttb97MoreButton);
TtfwClassRef.Register(TvcmComboBox);
{$If (not Defined(nsTest) OR Defined(InsiderTest)) AND not Defined(nsTool) AND Defined(Nemesis) AND not Defined(NewGen)}
TtfwClassRef.Register(TnscTasksPanelTreeView);
{$IfEnd}
{$EndIf DesignTimeLibrary}
g_InternalButton := TvcmToolButtonDef.Create(nil);
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VCM\implementation\Components\vcmMenuManager.pas initialization leave'); {$EndIf}
finalization
vcmFree(g_InternalButton);
end.
|
unit UNetProtocolConst;
interface
Const
CT_MagicRequest = $0001;
CT_MagicResponse = $0002;
CT_MagicAutoSend = $0003;
CT_NetOp_Hello = $0001; // Sends my last operationblock + servers. Receive last operationblock + servers + same operationblock number of sender
CT_NetOp_Error = $0002;
CT_NetOp_Message = $0003;
CT_NetOp_GetBlockHeaders = $0005; // Sends from and to. Receive a number of OperationsBlock to check
CT_NetOp_GetBlocks = $0010;
CT_NetOp_NewBlock = $0011;
CT_NetOp_AddOperations = $0020;
CT_NetOp_GetSafeBox = $0021; // V2 Protocol: Allows to send/receive Safebox in chunk parts
CT_NetOp_GetPendingOperations = $0030; // Obtain pending operations
CT_NetOp_GetAccount = $0031; // Obtain account info
CT_NetOp_Reserved_Start = $1000; // This will provide a reserved area
CT_NetOp_Reserved_End = $1FFF; // End of reserved area
CT_NetOp_ERRORCODE_NOT_IMPLEMENTED = $00FF;// This will be error code returned when using Reserved area and Op is not implemented
CT_NetError_InvalidProtocolVersion = $0001;
CT_NetError_IPBlackListed = $0002;
CT_NetError_InvalidDataBufferInfo = $0010;
CT_NetError_InternalServerError = $0011;
CT_NetError_InvalidNewAccount = $0012;
CT_NetError_SafeboxNotFound = $00020;
CT_LAST_CONNECTION_BY_SERVER_MAX_MINUTES = 60*60*3;
CT_LAST_CONNECTION_MAX_MINUTES = 60*60;
CT_MAX_NODESERVERS_ON_HELLO = 10;
CT_MIN_NODESERVERS_BUFFER = 50;
CT_MAX_NODESERVERS_BUFFER = 300;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Win32 Synchronization objects }
{ }
{ Copyright (c) 1997 Borland International }
{ }
{*******************************************************}
unit SyncObjs;
interface
uses Sysutils, Windows, Messages, Classes;
type
TSynchroObject =
class(TObject)
public
procedure Acquire; virtual;
procedure Release; virtual;
end;
THandleObject =
class(TSynchroObject)
private
FHandle: THandle;
FLastError: Integer;
public
destructor Destroy; override;
property LastError: Integer read FLastError;
property Handle: THandle read FHandle;
end;
TWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError);
TEvent =
class(THandleObject)
public
constructor Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string);
function WaitFor(Timeout: Longint): TWaitResult;
procedure SetEvent;
procedure ResetEvent;
end;
TSimpleEvent =
class(TEvent)
public
constructor Create;
end;
TCriticalSection =
class(TSynchroObject)
private
FSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Acquire; override;
procedure Release; override;
procedure Enter;
procedure Leave;
function Taken : boolean;
end;
implementation
{ TSynchroObject }
procedure TSynchroObject.Acquire;
begin
end;
procedure TSynchroObject.Release;
begin
end;
{ THandleObject }
destructor THandleObject.Destroy;
begin
CloseHandle(FHandle);
inherited Destroy;
end;
{ TEvent }
constructor TEvent.Create(EventAttributes: PSecurityAttributes; ManualReset, InitialState: Boolean; const Name: string);
begin
FHandle := CreateEvent(EventAttributes, ManualReset, InitialState, PChar(Name));
end;
function TEvent.WaitFor(Timeout: Longint): TWaitResult;
begin
case WaitForSingleObject(Handle, Timeout) of
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_OBJECT_0: Result := wrSignaled;
WAIT_TIMEOUT: Result := wrTimeout;
WAIT_FAILED:
begin
Result := wrError;
FLastError := GetLastError;
end;
else
Result := wrError;
end;
end;
procedure TEvent.SetEvent;
begin
Windows.SetEvent(Handle);
end;
procedure TEvent.ResetEvent;
begin
Windows.ResetEvent(Handle);
end;
{ TSimpleEvent }
constructor TSimpleEvent.Create;
begin
FHandle := CreateEvent(nil, True, False, nil);
end;
{ TCriticalSection }
constructor TCriticalSection.Create;
begin
inherited Create;
InitializeCriticalSection(FSection);
end;
destructor TCriticalSection.Destroy;
begin
DeleteCriticalSection(FSection);
inherited Destroy;
end;
procedure TCriticalSection.Acquire;
begin
EnterCriticalSection(FSection);
end;
procedure TCriticalSection.Release;
begin
LeaveCriticalSection(FSection);
end;
procedure TCriticalSection.Enter;
begin
Acquire;
end;
procedure TCriticalSection.Leave;
begin
Release;
end;
function TCriticalSection.Taken : boolean;
begin
if TryEnterCriticalSection(FSection)
then
begin
LeaveCriticalSection(FSection);
result := true;
end
else result := false;
end;
end.
|
unit BBoard;
interface
uses
{$IFNDEF TEST}
ComObj, ActiveX, commmunity_TLB, StdVcl, Classes, Windows;
{$ELSE}
ComObj, ActiveX, Classes, Windows;
{$ENDIF}
type
TBBoard = class(TAutoObject, IBBoard)
public
destructor Destroy; override;
public
procedure Open(const Id: WideString; IsForum: WordBool); safecall;
function Count: SYSINT; safecall;
procedure NewItem(const Author, Title, ParentUId, Body: WideString; Topic: WordBool); safecall;
procedure NewItemEx(const Author, Title, AttchName, ParentUId, Body: WideString; Topic: WordBool); safecall;
function GetAuthor(index: Integer): WideString; safecall;
function GetTitle(index: Integer): WideString; safecall;
function GetId(index: Integer): WideString; safecall;
function GetRepliesCount(index: Integer): SYSINT; safecall;
procedure NewPoll(const Author, Title, ParentUId, Body, PollItems: WideString); safecall;
function PollItemsCount: SYSINT; safecall;
function VotesCount: SYSINT; safecall;
function GetPollItem(index: Integer): WideString; safecall;
function GetVotes(index: Integer): SYSINT; safecall;
procedure AddVote(const Author, ParentUId, Body: WideString; PollItemIdx: Integer); safecall;
{ Protected declarations }
private
fId : string;
fItems : TStringList;
fIndex : TStringList;
fCount : integer;
fIsForum : boolean;
fPollItems : TStringList;
fVotesCount : integer;
fVotes : TStringList;
fUploadDir : string;
public
function GetBody(index: Integer): WideString; safecall;
function GetDate(index: Integer): TDateTime; safecall;
function GetHTMLBody(index: Integer): WideString; safecall;
function GetAttachment(index : integer): WideString; safecall;
private
function GetPCount(folder: string): integer; safecall;
protected
function Get_ThreadFolder: WideString; safecall;
function Get_UploadDir: WideString; safecall;
end;
implementation
uses
ComServ, SysUtils, CompStringsParser, BaseUtils, FileCtrl, StrUtils;
const
Separator = '}';
CodeChar = '{';
const
CodeEqv : array[0..9] of char = ('\', '/', ':', '"', '?', '*', '|', '<', '>', CodeChar);
function EncodeStr( str : string ) : string;
var
i : integer;
c : string;
begin
result := '';
for i := 1 to length(str) do
begin
c := str[i];
case c[1] of
'\' : c := CodeChar + '00';
'/' : c := CodeChar + '01';
':' : c := CodeChar + '02';
'"' : c := CodeChar + '03';
'?' : c := CodeChar + '04';
'*' : c := CodeChar + '05';
'|' : c := CodeChar + '06';
'<' : c := CodeChar + '07';
'>' : c := CodeChar + '08';
CodeChar : c := CodeChar + '09';
end;
result := result + c;
end
end;
function DecodeStr( str : string ) : string;
var
p1, p2 : integer;
s : string;
c : string;
x : integer;
begin
result := '';
p1 := 1;
repeat
p2 := p1;
p1 := pos( CodeChar, str, p2 );
if p1 = 0
then p1 := length(str) + 1;
s := copy( str, p2, p1 - p2 );
result := result + s;
if p1 < length(str)
then
begin
c := copy( str, p1 + 1, 2 );
x := StrToInt( c );
result := result + CodeEqv[x];
inc( p1, 3 );
end;
until p1 >= length(str);
end;
const
tidPrefix_Author = 'Author';
tidPrefix_Subject = 'Subject';
tidPrefix_Id = 'Id';
tidPrefix_UId = 'UId';
tidPrefix_TimeStamp = 'TimeStamp';
tidPrefix_Kind = 'Kind';
tidPrefix_AttchName = 'AttchName';
tidFileExt_Topic = '.topic';
tidFileExt_Post = '.post';
tidProperty_Modified = 'Modified';
tidProperty_PostCount = 'PostCount';
tidProperty_VotesCount = 'VotesCount';
tidProperty_PollItemsCount = 'PollItemCount';
tidProperty_PollItemDesc = 'PollItemDesc';
tidProperty_PollItemVotes = 'PollItemVotes';
tidFileName_TopicIdx = 'topic.index';
type
TItemData =
record
Author : string;
Subject : string;
Id : string;
UId : string;
TimeStamp : string;
Kind : integer;
AttchName : string;
end;
function GetItemData( path : string ) : TItemData;
var
Name : string;
kind : string;
p : integer;
begin
Name := ExtractFileName( path );
p := 1;
result.Id := path;
result.Author := GetNextStringUpTo( Name, p, Separator );
result.Subject := GetNextStringUpTo( Name, p, Separator );
result.UId := GetNextStringUpTo( Name, p, Separator );
kind := GetNextStringUpTo( Name, p, Separator );
if kind <> ''
then result.Kind := StrToInt(kind)
else result.Kind := 0;
if result.Kind <> 0
then result.AttchName := GetNextStringUpTo(Name, p, Separator)
else result.AttchName := '';
end;
procedure RenderItemDataToList( const Data : TItemData; index : integer; List : TSTringList );
var
postfix : string;
begin
postfix := IntToStr( index );
List.Values[tidPrefix_Author + postfix] := Data.Author;
List.Values[tidPrefix_Subject + postfix] := Data.Subject;
List.Values[tidPrefix_Id + postfix] := Data.Id;
List.Values[tidPrefix_UId + postfix] := Data.UId;
List.Values[tidPrefix_Kind + postfix] := IntToStr(Data.Kind);
List.Values[tidPrefix_AttchName + postfix] := Data.AttchName;
end;
function CreateItemName( Author, Subject, UId : string ) : string;
begin
result :=
Author + Separator +
Subject + Separator +
UId;
end;
function CreateItemNameEx( Author, Subject, UId, AttchName : string ) : string;
begin
result :=
Author + Separator +
Subject + Separator +
UId + Separator +
'99' + Separator +
AttchName + Separator;
end;
destructor TBBoard.Destroy;
begin
fItems.Free;
fIndex.Free;
inherited;
end;
procedure TBBoard.Open(const Id: WideString; IsForum: WordBool);
var
SearchRec : TSearchRec;
found : integer;
Data : TItemData;
path : string;
systime : TSystemTime;
pattern : string;
TopicIdx : TStringList;
DateStamp : string;
itemCount : integer;
i : integer;
begin
try
if fItems <> nil
then fItems.Free;
if fIndex <> nil
then fIndex.Free;
if fPollItems <> nil
then fPollItems.Free;
if fVotes <> nil
then fVotes.Free;
fItems := TStringList.Create;
fIndex := TStringList.Create;
fIndex.Sorted := true;
fIndex.Duplicates := dupIgnore;
fIsForum := IsForum;
fPollItems := TStringList.Create;
fVotes := TStringList.Create;
fId := Id;
path := fId + '\';
fCount := 0;
if fIsForum
then pattern := tidFileExt_Topic
else
begin
TopicIdx := TStringList.Create;
try
TopicIdx.LoadFromFile( path + tidFileName_TopicIdx );
try
fVotesCount := StrToInt( TopicIdx.Values[tidProperty_VotesCount] );
except
fVotesCount := 0;
end;
if TopicIdx.Values[tidProperty_PollItemsCount] <> '' then
begin
itemCount := StrToInt( TopicIdx.Values[tidProperty_PollItemsCount] );
for i := 0 to itemCount - 1 do
begin
fPollItems.Add( TopicIdx.Values[tidProperty_PollItemDesc + IntToStr(i+1)] );
fVotes.Add( TopicIdx.Values[tidProperty_PollItemVotes + IntToStr(i+1)] );
end;
end;
finally
TopicIdx.Free;
end;
pattern := tidFileExt_Post;
end;
found := FindFirst( path + '*' + pattern, faAnyFile, SearchRec );
try
while found = 0 do
begin
Data := GetItemData( path + SearchRec.Name );
RenderItemDataToList( Data, fCount, fItems );
if fIsForum
then
begin
TopicIdx := TStringList.Create;
try
TopicIdx.LoadFromFile( path + SearchRec.Name + '\' + tidFileName_TopicIdx );
DateStamp := TopicIdx.Values[tidProperty_Modified];
finally
TopicIdx.Free;
end;
end
else
begin
FileTimeToSystemTime( SearchRec.FindData.ftLastWriteTime, systime );
SystemTimeToTzSpecificLocalTime( nil, systime, systime );
DateStamp := FloatToStr(SystemTimeToDateTime( systime ));
end;
fIndex.Add( DateStamp + '=' + IntToStr(fCount) );
fItems.Values[tidPrefix_TimeStamp + IntToStr(fCount)] := DateStamp;
inc( fCount );
found := FindNext( SearchRec );
end;
finally
FindClose( SearchRec );
end;
except
end;
end;
function TBBoard.Count: SYSINT;
begin
try
result := fIndex.Count;
except
result := 0;
end;
end;
procedure TBBoard.NewItem(const Author, Title, ParentUId, Body: WideString; Topic: WordBool);
var
name : string;
MsgFile : TStringList;
Folder : string;
RepCount : integer;
begin
try
name := CreateItemName( Author, EncodeStr( Title ), Author + DateTimeToAbc( Now ) );
folder := ParentUId;
if folder <> '\'
then folder := folder + '\';
if Topic
then
begin
folder := folder + name + tidFileExt_Topic + '\';
ForceDirectories( folder );
end;
fUploadDir := folder;
RepCount := GetPCount( folder );
MsgFile := TStringList.Create;
try
if FileExists( folder + tidFileName_TopicIdx )
then MsgFile.LoadFromFile( folder + tidFileName_TopicIdx );
MsgFile.Values[tidProperty_Modified] := FloatToStr( Now );
MsgFile.Values[tidProperty_PostCount] := IntToStr( RepCount + 1 );
MsgFile.SaveToFile( folder + tidFileName_TopicIdx );
finally
MsgFile.Free;
end;
MsgFile := TStringList.Create;
try
MsgFile.Text := Body;
MsgFile.SaveToFile( folder + name + tidFileExt_Post );
finally
MsgFile.Free;
end;
except
end;
end;
procedure TBBoard.NewItemEx(const Author, Title, AttchName, ParentUId, Body: WideString; Topic: WordBool);
var
name : string;
MsgFile : TStringList;
Folder : string;
RepCount : integer;
begin
try
name := CreateItemNameEx(Author, EncodeStr(Title), Author + DateTimeToAbc(Now), AttchName);
folder := ParentUId;
if folder <> '\'
then folder := folder + '\';
if Topic
then
begin
folder := folder + name + tidFileExt_Topic + '\';
ForceDirectories( folder );
end;
fUploadDir := folder;
RepCount := GetPCount( folder );
MsgFile := TStringList.Create;
try
if FileExists( folder + tidFileName_TopicIdx )
then MsgFile.LoadFromFile( folder + tidFileName_TopicIdx );
MsgFile.Values[tidProperty_Modified] := FloatToStr( Now );
MsgFile.Values[tidProperty_PostCount] := IntToStr( RepCount + 1 );
MsgFile.SaveToFile( folder + tidFileName_TopicIdx );
finally
MsgFile.Free;
end;
MsgFile := TStringList.Create;
try
MsgFile.Text := Body;
MsgFile.SaveToFile( folder + name + tidFileExt_Post );
finally
MsgFile.Free;
end;
except
end;
end;
function GetIndex( indexstr : string ) : string;
begin
result := copy( indexstr, system.pos( '=', indexstr ) + 1, length(indexstr) );
end;
function TBBoard.GetAuthor(index: Integer): WideString;
begin
try
if fIsForum
then index := fIndex.Count - 1 - index;
result := fItems.Values[tidPrefix_Author + GetIndex(fIndex[index])];
except
result := '';
end;
end;
function TBBoard.GetTitle(index: Integer): WideString;
begin
try
if fIsForum
then index := fIndex.Count - 1 - index;
result := DecodeStr( fItems.Values[tidPrefix_Subject + GetIndex(fIndex[index])] );
except
result := '';
end;
end;
function TBBoard.GetId(index: Integer): WideString;
begin
try
if fIsForum
then index := fIndex.Count - 1 - index;
result := fItems.Values[tidPrefix_Id + GetIndex(fIndex[index])];
except
result := '';
end;
end;
function TBBoard.GetRepliesCount(index: Integer): SYSINT;
var
folder : string;
begin
try
folder := GetId( index ) + '\';
result := GetPCount( folder );
except
result := -1;
end;
end;
function TBBoard.GetAttachment(index: Integer): WideString;
begin
try
if fIsForum
then index := fIndex.Count - 1 - index;
result := DecodeStr( fItems.Values[tidPrefix_AttchName + GetIndex(fIndex[index])] );
except
result := '';
end;
end;
procedure TBBoard.NewPoll(const Author, Title, ParentUId, Body, PollItems: WideString);
var
name : string;
MsgFile : TStringList;
Items : TStringList;
Folder : string;
i : integer;
begin
try
name := CreateItemName( Author, EncodeStr( Title ), Author + DateTimeToAbc( Now ) );
folder := ParentUId;
if folder <> '\'
then folder := folder + '\';
folder := folder + name + tidFileExt_Topic + '\';
ForceDirectories( folder );
MsgFile := TStringList.Create;
try
MsgFile.Values[tidProperty_Modified] := FloatToStr( Now );
MsgFile.Values[tidProperty_PostCount] := '1';
Items := TStringList.Create;
try
Items.Text := PollItems;
MsgFile.Values[tidProperty_VotesCount] := '0';
MsgFile.Values[tidProperty_PollItemsCount] := IntToStr( Items.Count );
if Items.Count > 0 then
for i := 0 to Items.Count - 1 do
begin
MsgFile.Values[tidProperty_PollItemDesc + IntToStr(i+1)] := Items[i];
MsgFile.Values[tidProperty_PollItemVotes + IntToStr(i+1)] := '0';
end;
finally
Items.Free;
end;
MsgFile.SaveToFile( folder + tidFileName_TopicIdx );
finally
MsgFile.Free;
end;
MsgFile := TStringList.Create;
try
MsgFile.Text := Body;
MsgFile.SaveToFile( folder + name + tidFileExt_Post );
finally
MsgFile.Free;
end;
except
end;
end;
function TBBoard.PollItemsCount: SYSINT;
begin
try
result := fPollItems.Count;
except
result := -1;
end;
end;
function TBBoard.VotesCount: SYSINT;
begin
result := fVotesCount;
end;
function TBBoard.GetPollItem(index: Integer): WideString;
begin
try
result := fPollItems[index];
except
result := '';
end;
end;
function TBBoard.GetVotes(index: Integer): SYSINT;
begin
try
result := StrToInt( fVotes[index] );
except
result := -1;
end;
end;
procedure TBBoard.AddVote(const Author, ParentUId, Body: WideString; PollItemIdx: Integer);
var
name : string;
MsgFile : TStringList;
Folder : string;
HaveComm : boolean;
begin
try
name := CreateItemName( Author, '', Author + DateTimeToAbc( Now ) );
folder := ParentUId;
if folder <> '\'
then folder := folder + '\';
HaveComm := Trim( Body ) <> '';
MsgFile := TStringList.Create;
try
MsgFile.LoadFromFile( folder + tidFileName_TopicIdx );
MsgFile.Values[tidProperty_Modified] := FloatToStr( Now );
MsgFile.Values[tidProperty_VotesCount] := IntToStr( StrToInt( MsgFile.Values[tidProperty_VotesCount] ) + 1 );
if HaveComm
then MsgFile.Values[tidProperty_PostCount] := IntToStr( StrToInt( MsgFile.Values[tidProperty_PostCount] ) + 1 );
if (PollItemIdx > 0) and (PollItemIdx <= StrToInt( MsgFile.Values[tidProperty_PollItemsCount] )) then
MsgFile.Values[tidProperty_PollItemVotes + IntToStr(PollItemIdx)] := IntToStr( StrToInt( MsgFile.Values[tidProperty_PollItemVotes + IntToStr(PollItemIdx)] ) + 1 );
MsgFile.SaveToFile( folder + tidFileName_TopicIdx );
finally
MsgFile.Free;
end;
if HaveComm then
begin
MsgFile := TStringList.Create;
try
MsgFile.Text := Body;
MsgFile.SaveToFile( folder + name + tidFileExt_Post );
finally
MsgFile.Free;
end;
end;
except
end;
end;
function TBBoard.GetBody(index: Integer): WideString;
var
path : string;
body : TStringList;
begin
try
if not fIsForum
then
begin
path := fItems.Values[tidPrefix_Id + GetIndex(fIndex[index])];
if path <> ''
then
begin
body := TStringList.Create;
try
body.LoadFromFile( path );
result := body.Text;
finally
body.Free;
end;
end
else result := '';
end
else result := '';
except
result := '';
end;
end;
function TBBoard.GetDate(index: Integer): TDateTime;
var
datestamp : string;
numdate : double;
begin
try
if fIsForum
then index := fIndex.Count - 1 - index;
datestamp := fItems.Values[tidPrefix_TimeStamp + GetIndex(fIndex[index])];
if datestamp <> ''
then
begin
numdate := StrToFloat( datestamp );
result := TDateTime(numdate);
end
else result := Now;
except
result := Now;
end;
end;
function TBBoard.GetHTMLBody(index: Integer): WideString;
var
rawbody : TStringList;
i : integer;
begin
try
rawbody := TStringList.Create;
try
rawbody.Text := GetBody( index );
result := '';
for i := 0 to pred(rawbody.Count) do
result := result + rawbody[i] + '<br>';
finally
rawbody.Free;
end;
except
result := '';
end;
end;
function TBBoard.GetPCount(folder: string): integer; safecall;
var
MsgFile : TStringList;
begin
result := 0;
if FileExists( folder + tidFileName_TopicIdx )
then
begin
MsgFile := TStringList.Create;
try
MsgFile.LoadFromFile( folder + tidFileName_TopicIdx );
if MsgFile.Values[tidProperty_PostCount] <> ''
then
try
result := StrToInt( MsgFile.Values[tidProperty_PostCount] );
except
end;
finally
MsgFile.Free;
end;
end;
end;
function TBBoard.Get_ThreadFolder : WideString;
begin
result := ExtractFileName(fId);
end;
function TBBoard.Get_UploadDir: WideString;
begin
result := fUploadDir;
end;
initialization
{$IFNDEF TEST}
TAutoObjectFactory.Create(ComServer, TBBoard, Class_BBoard, ciMultiInstance, tmApartment);
{$ENDIF}
end.
|
unit nscTreeViewRes;
{* Ресурсы для TnscTreeView }
// Модуль: "w:\common\components\gui\Garant\Nemesis\nscTreeViewRes.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "nscTreeViewRes" MUID: (4B97DC630378)
{$Include w:\common\components\gui\Garant\Nemesis\nscDefine.inc}
interface
{$If Defined(Nemesis)}
uses
l3IntfUses
, l3StringIDEx
;
const
{* Локализуемые строки nscMultiStroke }
str_nsc_WrapHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_WrapHint'; rValue : 'Включить перенос по словам');
{* 'Включить перенос по словам' }
str_nsc_UnwrapHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_UnwrapHint'; rValue : 'Выключить перенос по словам');
{* 'Выключить перенос по словам' }
{* Карта преобразования локализованных строк nscMultiStroke }
nscMultiStrokeMap: array [Boolean] of Pl3StringIDEx = (
@str_nsc_WrapHint
, @str_nsc_UnwrapHint
);
{$IfEnd} // Defined(Nemesis)
implementation
{$If Defined(Nemesis)}
uses
l3ImplUses
, l3MessageID
//#UC START# *4B97DC630378impl_uses*
//#UC END# *4B97DC630378impl_uses*
;
initialization
str_nsc_WrapHint.Init;
{* Инициализация str_nsc_WrapHint }
str_nsc_UnwrapHint.Init;
{* Инициализация str_nsc_UnwrapHint }
{$IfEnd} // Defined(Nemesis)
end.
|
//******************************************************************************
//*** Cactus Jukebox ***
//*** ***
//*** (c) 2006-2009 ***
//*** ***
//*** Sebastian Kraft, sebastian_kraft@gmx.de ***
//*** Massimo Magnano, maxm.dev@gmail.com ***
//*** ***
//******************************************************************************
// File : global_vars.pas
//
// Description : Common Global Vars of the project.
//
//******************************************************************************
unit global_vars;
{$mode delphi}{$H+}
interface
uses Controls, menus, ExtCtrls;
Const
INI_PLUGINS ='plugins.ini';
Var
AppMainMenu :TMainMenu =Nil;
AppTrayIcon :TTrayIcon =Nil;
ImageListNormal :TImageList;
PluginsSeparatorItem :TMenuItem=Nil;
PATH_Home,
PATH_Data,
PATH_Config,
PATH_Plugins :String;
procedure RegisterPlugin(Name, DLLFileName :String);
implementation
uses SysUtils, Forms, inifiles;
procedure RegisterPlugin(Name, DLLFileName :String);
Var
theINI :TIniFile;
begin
theINI :=TIniFile.Create(PATH_Config+INI_PLUGINS);
theINI.WriteString(Name, 'DLL', DLLFileName);
theINI.Free;
end;
procedure CalcPathValues;
begin
PATH_Home :=IncludeTrailingPathDelimiter(GetEnvironmentVariable('HOME'));
{$ifdef CactusRPM}
PATH_Data :='/usr/share/cactusjukebox/';
PATH_Config :=IncludeTrailingPathDelimiter(PATH_Home+'.cactusjukebox');
{$else}
PATH_Data :=IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
SetCurrentDir(PATH_Data);
PATH_Config :=PATH_Data;
{$endif}
PATH_Plugins :=IncludeTrailingPathDelimiter(PATH_Config+'plugings');
end;
initialization
CalcPathValues;
end.
|
namespace Sugar;
interface
{$IF NETFX_CORE}
uses
System.Linq;
{$ENDIF}
type
UserSettings = public class {$IF COOPER}{$IF NOT ANDROID}mapped to java.util.prefs.Preferences{$ENDIF}
{$ELSEIF ECHOES}
mapped to {$IF WINDOWS_PHONE}System.IO.IsolatedStorage.IsolatedStorageSettings{$ELSEIF NETFX_CORE}Windows.Storage.ApplicationDataContainer{$ELSE}System.Configuration.Configuration{$ENDIF}
{$ELSEIF TOFFEE}
mapped to Foundation.NSUserDefaults
{$ENDIF}
private
method GetKeys: array of String;
{$IF ANDROID}
property Instance: android.content.SharedPreferences read write;
constructor;
constructor(anInstance: android.content.SharedPreferences);
{$ELSEIF TOFFEE}
method Exists(Key: String): Boolean;
{$ENDIF}
public
method &Read(Key: String; DefaultValue: String): String;
method &Read(Key: String; DefaultValue: Integer): Integer;
method &Read(Key: String; DefaultValue: Boolean): Boolean;
method &Read(Key: String; DefaultValue: Double): Double;
method &Write(Key: String; Value: String);
method &Write(Key: String; Value: Integer);
method &Write(Key: String; Value: Boolean);
method &Write(Key: String; Value: Double);
method Save;
method Clear;
method &Remove(Key: String);
property Keys: array of String read GetKeys;
class method &Default: UserSettings;
end;
{$IF ECHOES AND NOT (WINDOWS_PHONE OR NETFX_CORE)}
UserSettingsHelper = public static class
private
class property Instance: System.Configuration.Configuration read write;
public
method GetConfiguration: System.Configuration.Configuration;
end;
{$ELSEIF TOFFEE}
UserSettingsHelper = public static class
public
method GetBundleIdentifier: String;
end;
{$ENDIF}
implementation
method UserSettings.Clear;
begin
{$IF ANDROID}
Instance.edit.clear.apply;
{$ELSEIF COOPER}
mapped.clear;
{$ELSEIF WINDOWS_PHONE}
mapped.Clear;
{$ELSEIF NETFX_CORE}
mapped.Values.Clear;
{$ELSEIF ECHOES}
mapped.AppSettings.Settings.Clear;
{$ELSEIF TOFFEE}
mapped.removePersistentDomainForName(UserSettingsHelper.GetBundleIdentifier);
mapped.synchronize;
{$ENDIF}
end;
class method UserSettings.&Default: UserSettings;
begin
{$IF ANDROID}
SugarAppContextMissingException.RaiseIfMissing;
exit new UserSettings(Environment.ApplicationContext.getSharedPreferences("Sugar", android.content.Context.MODE_PRIVATE));
{$ELSEIF COOPER}
exit mapped.userRoot;
{$ELSEIF WINDOWS_PHONE}
exit mapped.ApplicationSettings;
{$ELSEIF NETFX_CORE}
exit Windows.Storage.ApplicationData.Current.LocalSettings;
{$ELSEIF ECHOES}
exit UserSettingsHelper.GetConfiguration;
{$ELSEIF TOFFEE}
exit mapped.standardUserDefaults;
{$ENDIF}
end;
method UserSettings.GetKeys: array of String;
begin
{$IF ANDROID}
exit Instance.All.keySet.toArray(new String[0]);
{$ELSEIF COOPER}
exit mapped.keys;
{$ELSEIF WINDOWS_PHONE}
result := new String[mapped.ApplicationSettings.Keys.Count];
var Count := 0;
var Enumerator := mapped.ApplicationSettings.Keys.GetEnumerator;
while Enumerator.MoveNext do begin
result[Count] := String(Enumerator.Current);
inc(Count);
end;
{$ELSEIF NETFX_CORE}
exit mapped.Values.Keys.ToArray;
{$ELSEIF ECHOES}
exit mapped.AppSettings.Settings.AllKeys;
{$ELSEIF TOFFEE}
mapped.synchronize;
var lValues := mapped.persistentDomainForName(UserSettingsHelper.GetBundleIdentifier):allKeys;
if lValues = nil then
exit [];
result := new String[lValues.count];
for i: Integer := 0 to lValues.count - 1 do
result[i] := lValues.objectAtIndex(i);
{$ENDIF}
end;
method UserSettings.&Read(Key: String; DefaultValue: Boolean): Boolean;
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
exit Instance.getBoolean(Key, DefaultValue);
{$ELSEIF COOPER}
exit mapped.getBoolean(Key, DefaultValue);
{$ELSEIF WINDOWS_PHONE}
if not mapped.TryGetValue<Boolean>(Key, out result) then
exit DefaultValue;
{$ELSEIF NETFX_CORE}
if not mapped.Values.ContainsKey(Key) then
exit DefaultValue;
exit Boolean(mapped.Values[Key]);
{$ELSEIF ECHOES}
if not Boolean.TryParse(mapped.AppSettings.Settings[Key]:Value, out Result) then
exit DefaultValue;
{$ELSEIF TOFFEE}
result := iif(Exists(Key), mapped.boolForKey(Key), DefaultValue);
{$ENDIF}
end;
method UserSettings.&Read(Key: String; DefaultValue: Double): Double;
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
exit Double.longBitsToDouble(Instance.getLong(Key, Double.doubleToRawLongBits(DefaultValue)));
{$ELSEIF COOPER}
exit mapped.getDouble(Key, DefaultValue);
{$ELSEIF WINDOWS_PHONE}
if not mapped.TryGetValue<Double>(Key, out result) then
exit DefaultValue;
{$ELSEIF NETFX_CORE}
if not mapped.Values.ContainsKey(Key) then
exit DefaultValue;
exit Double(mapped.Values[Key]);
{$ELSEIF ECHOES}
if not Double.TryParse(mapped.AppSettings.Settings[Key]:Value, out Result) then
exit DefaultValue;
{$ELSEIF TOFFEE}
result := iif(Exists(Key), mapped.doubleForKey(Key), DefaultValue);
{$ENDIF}
end;
method UserSettings.&Read(Key: String; DefaultValue: Integer): Integer;
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
exit Instance.getInt(Key, DefaultValue);
{$ELSEIF COOPER}
exit mapped.getInt(Key, DefaultValue);
{$ELSEIF WINDOWS_PHONE}
if not mapped.TryGetValue<Integer>(Key, out result) then
exit DefaultValue;
{$ELSEIF NETFX_CORE}
if not mapped.Values.ContainsKey(Key) then
exit DefaultValue;
exit Integer(mapped.Values[Key]);
{$ELSEIF ECHOES}
if not Integer.TryParse(mapped.AppSettings.Settings[Key]:Value, out Result) then
exit DefaultValue;
{$ELSEIF TOFFEE}
result := iif(Exists(Key), mapped.integerForKey(Key), DefaultValue);
{$ENDIF}
end;
method UserSettings.&Read(Key: String; DefaultValue: String): String;
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
exit Instance.getString(Key, DefaultValue);
{$ELSEIF COOPER}
exit mapped.get(Key, DefaultValue);
{$ELSEIF WINDOWS_PHONE}
if not mapped.TryGetValue<String>(Key, out result) then
exit DefaultValue;
{$ELSEIF NETFX_CORE}
if not mapped.Values.ContainsKey(Key) then
exit DefaultValue;
exit String(mapped.Values[Key]);
{$ELSEIF ECHOES}
if mapped.AppSettings.Settings[Key] = nil then
exit DefaultValue;
exit mapped.AppSettings.Settings[Key].Value;
{$ELSEIF TOFFEE}
if Exists(Key) then
exit mapped.stringForKey(Key)
else
exit DefaultValue;
{$ENDIF}
end;
method UserSettings.&Remove(Key: String);
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
Instance.edit.remove(Key).apply;
{$ELSEIF COOPER}
mapped.remove(Key);
{$ELSEIF WINDOWS_PHONE}
mapped.Remove(Key);
{$ELSEIF NETFX_CORE}
mapped.Values.Remove(key);
{$ELSEIF ECHOES}
mapped.AppSettings.Settings.Remove(Key);
{$ELSEIF TOFFEE}
mapped.removeObjectForKey(Key);
{$ENDIF}
end;
method UserSettings.Save;
begin
{$IF ANDROID}
{$ELSEIF COOPER}
mapped.flush;
{$ELSEIF WINDOWS_PHONE}
mapped.Save;
{$ELSEIF NETFX_CORE}
{$ELSEIF ECHOES}
mapped.Save(System.Configuration.ConfigurationSaveMode.Modified);
{$ELSEIF TOFFEE}
mapped.synchronize;
{$ENDIF}
end;
method UserSettings.&Write(Key: String; Value: Boolean);
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
Instance.edit.putBoolean(Key, Value).apply;
{$ELSEIF COOPER}
mapped.putBoolean(Key, Value);
{$ELSEIF WINDOWS_PHONE}
mapped[Key] := Value;
{$ELSEIF NETFX_CORE}
mapped.Values[Key] := Value;
{$ELSEIF ECHOES}
&Write(Key, Value.ToString);
{$ELSEIF TOFFEE}
mapped.setBool(Value) forKey(Key);
{$ENDIF}
end;
method UserSettings.&Write(Key: String; Value: Double);
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
Instance.edit.putLong(Key, Double.doubleToRawLongBits(Value)).apply;
{$ELSEIF COOPER}
mapped.putDouble(Key, Value);
{$ELSEIF WINDOWS_PHONE}
mapped[Key] := Value;
{$ELSEIF NETFX_CORE}
mapped.Values[Key] := Value;
{$ELSEIF ECHOES}
&Write(Key, Value.ToString);
{$ELSEIF TOFFEE}
mapped.setDouble(Value) forKey(Key);
{$ENDIF}
end;
method UserSettings.&Write(Key: String; Value: Integer);
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
Instance.edit.putInt(Key, Value).apply;
{$ELSEIF COOPER}
mapped.putInt(Key, Value);
{$ELSEIF WINDOWS_PHONE}
mapped[Key] := Value;
{$ELSEIF NETFX_CORE}
mapped.Values[Key] := Value;
{$ELSEIF ECHOES}
&Write(Key, Value.ToString);
{$ELSEIF TOFFEE}
mapped.setInteger(Value) forKey(Key);
{$ENDIF}
end;
method UserSettings.&Write(Key: String; Value: String);
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
{$IF ANDROID}
Instance.edit.putString(Key, Value).apply;
{$ELSEIF COOPER}
mapped.put(Key, Value);
{$ELSEIF WINDOWS_PHONE}
mapped[Key] := Value;
{$ELSEIF NETFX_CORE}
mapped.Values[Key] := Value;
{$ELSEIF ECHOES}
if mapped.AppSettings.Settings[Key] = nil then
mapped.AppSettings.Settings.Add(Key, Value)
else
mapped.AppSettings.Settings[Key].Value := Value.ToString;
{$ELSEIF TOFFEE}
mapped.setObject(Value) forKey(Key);
{$ENDIF}
end;
{$IF ECHOES AND NOT (WINDOWS_PHONE OR NETFX_CORE)}
class method UserSettingsHelper.GetConfiguration: System.Configuration.Configuration;
begin
if Instance = nil then
Instance := System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
exit Instance;
end;
{$ELSEIF TOFFEE}
method UserSettings.Exists(Key: String): Boolean;
begin
SugarArgumentNullException.RaiseIfNil(Key, "Key");
exit mapped.objectForKey(Key) <> nil;
end;
class method UserSettingsHelper.GetBundleIdentifier: String;
begin
result := Foundation.NSBundle.mainBundle.bundleIdentifier;
if result = nil then
result := Foundation.NSBundle.mainBundle.executablePath.lastPathComponent.stringByDeletingPathExtension;
end;
{$ELSEIF ANDROID}
constructor UserSettings;
begin
constructor(nil);
end;
constructor UserSettings(anInstance: android.content.SharedPreferences);
begin
SugarArgumentNullException.RaiseIfNil(anInstance, "Instance");
Instance := anInstance;
end;
{$ENDIF}
end. |
{ Subroutine SST_DTYPE_SIZE (DTYPE)
*
* Set the SIZE_USED and SIZE_ALIGN fields in the data type descriptor DTYPE.
* The BITS_MIN and ALIGN fields must be previously set.
}
module sst_DTYPE_SIZE;
define sst_dtype_size;
%include 'sst2.ins.pas';
procedure sst_dtype_size ( {set all the size fields given basic info}
in out dtype: sst_dtype_t); {data type to set sizes for}
begin
dtype.size_used := {minimum machine addresses needed}
(dtype.bits_min + sst_config.bits_adr - 1) div sst_config.bits_adr;
dtype.size_align := {size when padded to own alignment rule}
(dtype.size_used + dtype.align - 1) div dtype.align;
end;
|
unit UDownloader;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, MSXML2_TLB;
{
Hinweis zum Import der Unit MSXML2_TLB
1.) Datei -> alle schliesen
2.) Projekt -> Typbibliothek importieren...
3.) Auswählen: Microsoft XML (Version 4)
4.) Unit anlegen klicken
}
type
TForm1 = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
Label1: TLabel;
CboURL: TComboBox;
BtnGet: TButton;
BtnHead: TButton;
procedure BtnGetClick(Sender: TObject);
procedure BtnHeadClick(Sender: TObject);
private
{ Private-Deklarationen }
function CreateRequestObject: IXMLHTTPRequest;
procedure CallHttpMethod(const method:string);
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses ComObj, VariantUtils2;
function TForm1.CreateRequestObject: IXMLHTTPRequest;
begin
// Hinweis:
// alle XMLHTTP - Objekte von MSXML 1.0 bis 3.0 haben Bugs
// erst ab Version 4.0 funktioniert das richtig
// man sollte MSXML SP3 auf dem Rechner installiert haben
try
// result := CoXMLHTTP.Create; // Interface erzeugen
Result := Createoleobject('Msxml2.XMLHTTP.6.0') as IXMLHTTPRequest;
except
on E:Exception do
begin
E.Message := 'MSXML 4.0 or higher required!'#13#10+E.Message;
raise;
end;
end;
end;
procedure TForm1.BtnGetClick(Sender: TObject);
begin
CallHttpMethod('GET');
end;
procedure TForm1.BtnHeadClick(Sender: TObject);
var
req : IXMLHTTPRequest;
URL : string;
user, pw : string;
data : OleVariant;
begin
req := CreateRequestObject;
URL := CboURL.Text;
req.open('HEAD', URL, False, user, pw);
req.setRequestHeader('Connection', 'close');
// req.setRequestHeader('Cache-Control', 'No');
req.setRequestHeader('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; powered by Delphi)');
data := '';
req.send(data); // Anfrage an Server senden und Antwort abwarten
// Status auswerten
if not (req.status in [200, 201, 204]) then
raise Exception.CreateFmt('HTTP-Download <%s> failed.'#13#10'%d - %s',
[URL, req.status, req.statusText] );
Memo1.Text := req.getAllResponseHeaders;
Memo1.Lines.Add('----');
Memo1.Lines.Add(Format('%d - %s',[req.status,req.statusText]));
Memo1.Lines.Add(req.responseText);
end;
procedure TForm1.CallHttpMethod(const method: string);
var
req : IXMLHTTPRequest;
URL : string;
user, pw : string;
data : OleVariant;
begin
req := CreateRequestObject;
URL := CboURL.Text;
req.open(method, URL, False, user, pw);
req.setRequestHeader('Cache-Control', 'No');
req.setRequestHeader('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; powered by Delphi)');
data := 'test'{Null}; {leerer Body}
req.send(data); // Anfrage an Server senden und Antwort abwarten
// Status auswerten
if not (req.status in [200, 201, 204]) then
raise Exception.CreateFmt('HTTP-Download <%s> failed.'#13#10'%d - %s',
[URL, req.status, req.statusText] );
Memo1.Text := VarByteArrayToString(req.responseBody);
end;
end.
|
{
File: NameRegistry.p
Contains: NameRegistry Interfaces
Version: Technology: MacOS
Release: Universal Interfaces 3.4.2
Copyright: © 1993-2002 by Apple Computer, Inc., all rights reserved.
Bugs?: For bug reports, consult the following page on
the World Wide Web:
http://www.freepascal.org/bugs.html
}
{ Pascal Translation Updated: Gale R Paeper, <gpaeper@empirenet.com>, 2006 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit NameRegistry;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes;
{$ALIGN POWER}
{******************************************************************************
*
* Foundation Types
*
}
{ Value of a property }
type
RegPropertyValue = Ptr;
{ Length of property value }
RegPropertyValueSize = UInt32;
{ ******************************************************************************
*
* RegEntryID : The Global x-Namespace Entry Identifier
*
}
RegEntryIDPtr = ^RegEntryID;
RegEntryID = record
contents: array [0..3] of UInt32;
end;
{ ******************************************************************************
*
* Root Entry Name Definitions (Applies to all Names in the RootNameSpace)
*
* ¥ Names are a colon-separated list of name components. Name components
* may not themselves contain colons.
* ¥ Names are presented as null-terminated ASCII character strings.
* ¥ Names follow similar parsing rules to Apple file system absolute
* and relative paths. However the '::' parent directory syntax is
* not currently supported.
}
{ Max length of Entry Name }
const
kRegCStrMaxEntryNameLength = 47;
{ Entry Names are single byte ASCII }
type
RegCStrEntryName = char;
RegCStrEntryNamePtr = CStringPtr;
{ length of RegCStrEntryNameBuf = kRegCStrMaxEntryNameLength+1 }
RegCStrEntryNameBuf = packed array [0..47] of char;
RegCStrPathName = char;
RegPathNameSize = UInt32;
RegCStrPathNamePtr = CStringPtr;
const
kRegPathNameSeparator = 58; { 0x3A }
kRegEntryNameTerminator = $00; { '\0' }
kRegPathNameTerminator = $00; { '\0' }
{ ******************************************************************************
*
* Property Name and ID Definitions
* (Applies to all Properties Regardless of NameSpace)
}
kRegMaximumPropertyNameLength = 31; { Max length of Property Name }
kRegPropertyNameTerminator = $00; { '\0' }
type
RegPropertyNameBuf = packed array [0..31] of char;
RegPropertyName = char;
RegPropertyNamePtr = CStringPtr;
{ ******************************************************************************
*
* Iteration Operations
*
* These specify direction when traversing the name relationships
}
RegIterationOp = UInt32;
RegEntryIterationOp = RegIterationOp;
const
{ Absolute locations }
kRegIterRoot = $00000002; { "Upward" Relationships }
kRegIterParents = $00000003; { include all parent(s) of entry }
{ "Downward" Relationships }
kRegIterChildren = $00000004; { include all children }
kRegIterSubTrees = $00000005; { include all sub trees of entry }
kRegIterDescendants = $00000005; { include all descendants of entry }
{ "Horizontal" Relationships }
kRegIterSibling = $00000006; { include all siblings }
{ Keep doing the same thing }
kRegIterContinue = $00000001;
{ ******************************************************************************
*
* Name Entry and Property Modifiers
*
*
*
* Modifiers describe special characteristics of names
* and properties. Modifiers might be supported for
* some names and not others.
*
* Device Drivers should not rely on functionality
* specified as a modifier.
}
type
RegModifiers = UInt32;
RegEntryModifiers = RegModifiers;
RegPropertyModifiers = RegModifiers;
const
kRegNoModifiers = $00000000; { no entry modifiers in place }
kRegUniversalModifierMask = $0000FFFF; { mods to all entries }
kRegNameSpaceModifierMask = $00FF0000; { mods to all entries within namespace }
kRegModifierMask = $FF000000; { mods to just this entry }
{ Universal Property Modifiers }
kRegPropertyValueIsSavedToNVRAM = $00000020; { property is non-volatile (saved in NVRAM) }
kRegPropertyValueIsSavedToDisk = $00000040; { property is non-volatile (saved on disk) }
{ NameRegistry version, Gestalt/PEF-style -- MUST BE KEPT IN SYNC WITH MAKEFILE !! }
LatestNR_PEFVersion = $01030000; { latest NameRegistryLib version (Gestalt/PEF-style) }
{ ///////////////////////
//
// The Registry API
//
/////////////////////// }
{ NameRegistry dispatch indexes }
kSelectRegistryEntryIDInit = 0;
kSelectRegistryEntryIDCompare = 1;
kSelectRegistryEntryIDCopy = 2;
kSelectRegistryEntryIDDispose = 3;
kSelectRegistryCStrEntryCreate = 4;
kSelectRegistryEntryDelete = 5;
kSelectRegistryEntryCopy = 6;
kSelectRegistryEntryIterateCreate = 7;
kSelectRegistryEntryIterateDispose = 8;
kSelectRegistryEntryIterateSet = 9;
kSelectRegistryEntryIterate = 10;
kSelectRegistryEntrySearch = 11;
kSelectRegistryCStrEntryLookup = 12;
kSelectRegistryEntryToPathSize = 13;
kSelectRegistryCStrEntryToPath = 14;
kSelectRegistryCStrEntryToName = 15;
kSelectRegistryPropertyCreate = 16;
kSelectRegistryPropertyDelete = 17;
kSelectRegistryPropertyRename = 18;
kSelectRegistryPropertyIterateCreate = 19;
kSelectRegistryPropertyIterateDispose = 20;
kSelectRegistryPropertyIterate = 21;
kSelectRegistryPropertyGetSize = 22;
kSelectRegistryPropertyGet = 23;
kSelectRegistryPropertySet = 24;
kSelectRegistryEntryGetMod = 25;
kSelectRegistryEntrySetMod = 26;
kSelectRegistryPropertyGetMod = 27;
kSelectRegistryPropertySetMod = 28;
kSelectRegistryEntryMod = 29;
kSelectRegistryEntryPropertyMod = 30; { if you add more selectors here, remember to change 'kSelectRegistryHighestSelector' below }
kSelectRegistryHighestSelector = 30;
{ ///////////////////////
//
// Entry Management
//
/////////////////////// }
{ -------------------------------
* EntryID handling
}
{
* Initialize an EntryID to a known invalid state
* note: invalid != uninitialized
}
{$ifc CALL_NOT_IN_CARBON}
{
* RegistryEntryIDInit()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIDInit(var id: RegEntryID): OSStatus; external name '_RegistryEntryIDInit';
{
* Compare EntryID's for equality or if invalid
*
* If a NULL value is given for either id1 or id2, the other id
* is compared with an invalid ID. If both are NULL, the id's
* are consided equal (result = true).
}
{
* RegistryEntryIDCompare()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIDCompare(const (*var*) id1: RegEntryID; const (*var*) id2: RegEntryID): boolean; external name '_RegistryEntryIDCompare';
{
* Copy an EntryID
}
{
* RegistryEntryIDCopy()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIDCopy(const (*var*) src: RegEntryID; var dst: RegEntryID): OSStatus; external name '_RegistryEntryIDCopy';
{
* Free an ID so it can be reused.
}
{
* RegistryEntryIDDispose()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIDDispose(var id: RegEntryID): OSStatus; external name '_RegistryEntryIDDispose';
{-------------------------------
* Adding and removing entries
*
* If (parentEntry) is NULL, the name is assumed
* to be a rooted path. It is rooted to an anonymous, unnamed root.
}
{
* RegistryCStrEntryCreate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryCStrEntryCreate(const (*var*) parentEntry: RegEntryID; {const} name: {variable-size-array} RegCStrPathNamePtr; var newEntry: RegEntryID): OSStatus; external name '_RegistryCStrEntryCreate';
{
* RegistryEntryDelete()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryDelete(const (*var*) id: RegEntryID): OSStatus; external name '_RegistryEntryDelete';
{
* RegistryEntryCopy()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryCopy(var parentEntryID: RegEntryID; var sourceDevice: RegEntryID; var destDevice: RegEntryID): OSStatus; external name '_RegistryEntryCopy';
{---------------------------
* Traversing the namespace
*
* To support arbitrary namespace implementations in the future,
* I have hidden the form that the place pointer takes. The previous
* interface exposed the place pointer by specifying it as a
* RegEntryID.
*
* I have also removed any notion of returning the entries
* in a particular order, because an implementation might
* return the names in semi-random order. Many name service
* implementations will store the names in a hashed lookup
* table.
*
* Writing code to traverse some set of names consists of
* a call to begin the iteration, the iteration loop, and
* a call to end the iteration. The begin call initializes
* the iteration cookie data structure. The call to end the
* iteration should be called even in the case of error so
* that allocated data structures can be freed.
*
* Create(...)
* do (
* Iterate(...);
* ) while (!done);
* Dispose(...);
*
* This is the basic code structure for callers of the iteration
* interface.
}
{$endc} {CALL_NOT_IN_CARBON}
type
RegEntryIter = ^SInt32; { an opaque 32-bit type }
RegEntryIterPtr = ^RegEntryIter; { when a var xx:RegEntryIter parameter can be nil, it is changed to xx: RegEntryIterPtr }
{
* create/dispose the iterator structure
* defaults to root with relationship = kRegIterDescendants
}
{$ifc CALL_NOT_IN_CARBON}
{
* RegistryEntryIterateCreate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIterateCreate(var cookie: RegEntryIter): OSStatus; external name '_RegistryEntryIterateCreate';
{
* RegistryEntryIterateDispose()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIterateDispose(var cookie: RegEntryIter): OSStatus; external name '_RegistryEntryIterateDispose';
{
* set Entry Iterator to specified entry
}
{
* RegistryEntryIterateSet()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIterateSet(var cookie: RegEntryIter; const (*var*) startEntryID: RegEntryID): OSStatus; external name '_RegistryEntryIterateSet';
{
* Return each value of the iteration
*
* return entries related to the current entry
* with the specified relationship
}
{
* RegistryEntryIterate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryIterate(var cookie: RegEntryIter; relationship: RegEntryIterationOp; var foundEntry: RegEntryID; var done: boolean): OSStatus; external name '_RegistryEntryIterate';
{
* return entries with the specified property
*
* A NULL RegPropertyValue pointer will return an
* entry with the property containing any value.
}
{
* RegistryEntrySearch()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntrySearch(var cookie: RegEntryIter; relationship: RegEntryIterationOp; var foundEntry: RegEntryID; var done: boolean; {const} propertyName: {variable-size-array} RegPropertyNamePtr; propertyValue: UnivPtr; propertySize: RegPropertyValueSize): OSStatus; external name '_RegistryEntrySearch';
{--------------------------------
* Find a name in the namespace
*
* This is the fast lookup mechanism.
* NOTE: A reverse lookup mechanism
* has not been provided because
* some name services may not
* provide a fast, general reverse
* lookup.
}
{
* RegistryCStrEntryLookup()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryCStrEntryLookup(const (*var*) searchPointID: RegEntryID; {const} pathName: {variable-size-array} RegCStrPathNamePtr; var foundEntry: RegEntryID): OSStatus; external name '_RegistryCStrEntryLookup';
{---------------------------------------------
* Convert an entry to a rooted name string
*
* A utility routine to turn an Entry ID
* back into a name string.
}
{
* RegistryEntryToPathSize()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryToPathSize(const (*var*) entryID: RegEntryID; var pathSize: RegPathNameSize): OSStatus; external name '_RegistryEntryToPathSize';
{
* RegistryCStrEntryToPath()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryCStrEntryToPath(const (*var*) entryID: RegEntryID; var pathName: RegCStrPathName; pathSize: RegPathNameSize): OSStatus; external name '_RegistryCStrEntryToPath';
{
* Parse a path name.
*
* Retrieve the last component of the path, and
* return a spec for the parent.
}
{
* RegistryCStrEntryToName()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryCStrEntryToName(const (*var*) entryID: RegEntryID; var parentEntry: RegEntryID; var nameComponent: RegCStrEntryName; var done: boolean): OSStatus; external name '_RegistryCStrEntryToName';
{ //////////////////////////////////////////////////////
//
// Property Management
//
////////////////////////////////////////////////////// }
{-------------------------------
* Adding and removing properties
}
{
* RegistryPropertyCreate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyCreate(const (*var*) entryID: RegEntryID; {const} propertyName: {variable-size-array} RegPropertyNamePtr; propertyValue: UnivPtr; propertySize: RegPropertyValueSize): OSStatus; external name '_RegistryPropertyCreate';
{
* RegistryPropertyDelete()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyDelete(const (*var*) entryID: RegEntryID; {const} propertyName: {variable-size-array} RegPropertyNamePtr): OSStatus; external name '_RegistryPropertyDelete';
{
* RegistryPropertyRename()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyRename(const (*var*) entry: RegEntryID; {const} oldName: {variable-size-array} RegPropertyNamePtr; {const} newName: {variable-size-array} RegPropertyNamePtr): OSStatus; external name '_RegistryPropertyRename';
{---------------------------
* Traversing the Properties of a name
*
}
{$endc} {CALL_NOT_IN_CARBON}
type
RegPropertyIter = ^SInt32; { an opaque 32-bit type }
RegPropertyIterPtr = ^RegPropertyIter; { when a var xx:RegPropertyIter parameter can be nil, it is changed to xx: RegPropertyIterPtr }
{$ifc CALL_NOT_IN_CARBON}
{
* RegistryPropertyIterateCreate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyIterateCreate(const (*var*) entry: RegEntryID; var cookie: RegPropertyIter): OSStatus; external name '_RegistryPropertyIterateCreate';
{
* RegistryPropertyIterateDispose()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyIterateDispose(var cookie: RegPropertyIter): OSStatus; external name '_RegistryPropertyIterateDispose';
{
* RegistryPropertyIterate()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyIterate(var cookie: RegPropertyIter; var foundProperty: RegPropertyName; var done: boolean): OSStatus; external name '_RegistryPropertyIterate';
{
* Get the value of the specified property for the specified entry.
*
}
{
* RegistryPropertyGetSize()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyGetSize(const (*var*) entryID: RegEntryID; {const} propertyName: {variable-size-array} RegPropertyNamePtr; var propertySize: RegPropertyValueSize): OSStatus; external name '_RegistryPropertyGetSize';
{
* (*propertySize) is the maximum size of the value returned in the buffer
* pointed to by (propertyValue). Upon return, (*propertySize) is the size of the
* value returned.
}
{
* RegistryPropertyGet()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyGet(const (*var*) entryID: RegEntryID; {const} propertyName: {variable-size-array} RegPropertyNamePtr; propertyValue: UnivPtr; var propertySize: RegPropertyValueSize): OSStatus; external name '_RegistryPropertyGet';
{
* RegistryPropertySet()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertySet(const (*var*) entryID: RegEntryID; {const} propertyName: {variable-size-array} RegPropertyNamePtr; propertyValue: UnivPtr; propertySize: RegPropertyValueSize): OSStatus; external name '_RegistryPropertySet';
{ //////////////////////////////////////////////////////
//
// Modifier Management
//
////////////////////////////////////////////////////// }
{
* Modifiers describe special characteristics of names
* and properties. Modifiers might be supported for
* some names and not others.
*
* Device Drivers should not rely on functionality
* specified as a modifier. These interfaces
* are for use in writing Experts.
}
{
* Get and Set operators for entry modifiers
}
{
* RegistryEntryGetMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryGetMod(const (*var*) entry: RegEntryID; var modifiers: RegEntryModifiers): OSStatus; external name '_RegistryEntryGetMod';
{
* RegistryEntrySetMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntrySetMod(const (*var*) entry: RegEntryID; modifiers: RegEntryModifiers): OSStatus; external name '_RegistryEntrySetMod';
{
* Get and Set operators for property modifiers
}
{
* RegistryPropertyGetMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertyGetMod(const (*var*) entry: RegEntryID; {const} name: {variable-size-array} RegPropertyNamePtr; var modifiers: RegPropertyModifiers): OSStatus; external name '_RegistryPropertyGetMod';
{
* RegistryPropertySetMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryPropertySetMod(const (*var*) entry: RegEntryID; {const} name: {variable-size-array} RegPropertyNamePtr; modifiers: RegPropertyModifiers): OSStatus; external name '_RegistryPropertySetMod';
{
* Iterator operator for entry modifier search
}
{
* RegistryEntryMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryMod(var cookie: RegEntryIter; relationship: RegEntryIterationOp; var foundEntry: RegEntryID; var done: boolean; matchingModifiers: RegEntryModifiers): OSStatus; external name '_RegistryEntryMod';
{
* Iterator operator for entries with matching
* property modifiers
}
{
* RegistryEntryPropertyMod()
*
* Availability:
* Non-Carbon CFM: in NameRegistryLib 1.0 and later
* CarbonLib: not available
* Mac OS X: not available
}
function RegistryEntryPropertyMod(var cookie: RegEntryIter; relationship: RegEntryIterationOp; var foundEntry: RegEntryID; var done: boolean; matchingModifiers: RegPropertyModifiers): OSStatus; external name '_RegistryEntryPropertyMod';
{$endc} {CALL_NOT_IN_CARBON}
{$ALIGN MAC68K}
end.
|
Program Game;
uses Crt;
const
CAT : String = 'cat';
DOG : String = 'dog';
LIGHT_GRAY: Integer = 7;
GRAY: Integer = 8;
DARK_BLUE: Integer = 3;
WHITE: Integer = 15;
GREEN: Integer = 10;
LIGHT_BLUE: Integer = 11;
var
user, pet, name, answer: string;
steps, menuChoice, hungry, mood, toilet, hygiene, energy: integer;
procedure WriteGameOverHalt( message: String);
begin
textcolor(12);
writeln('');
writeln('______________________________________________________');
writeln('');
writeln('!!! GAME OVER !!!');
writeLn;
writeln('Your record = ' ,steps);
writeLn;
writeln( message );
writeln;
writeln('______________________________________________________');
readln;
halt;
end;
procedure haltIfGameOver;
begin
Textbackground(black);
if hungry < 1 then WriteGameOverHalt('Next time do not forget to feed your ' + pet + ' !');
if mood < 1 then WriteGameOverHalt(name + ' is too unhappy and need some time to forgive you!');
if toilet < 1 then WriteGameOverHalt(name + ' made a poo on your bed and went for a walk alone!');
if hygiene < 1 then WriteGameOverHalt(pet + ' smells like a shit!');
if energy < 1 then WriteGameOverHalt('Your ' + pet + ' wants to sleep so much. Give it some time.');
end;
procedure givePetName;
begin
textcolor(LIGHT_GRAY);
writeln('');
writeln('Give a name to your ',pet);
textcolor(DARK_BLUE);
readln(name);
end;
procedure changeState(funnyString: String; _toilet, _mood, _energy, _hungry, _hygiene: Integer);
begin
clrscr;
textcolor(yellow);
writeln(funnyString);
textcolor(GRAY);
Write('(');
if _toilet <> 0 then Write('toilet: ' , _toilet);
if _mood <> 0 then Write(' mood: ', _mood);
if _energy <> 0 then Write(' energy: ', _energy);
if _hungry <> 0 then Write(' hungry: ', _hungry);
if _hygiene <> 0 then Write(' hygiene: ' ,_hygiene);
WriteLn(')');
toilet := toilet + _toilet;
mood := mood + _mood;
energy := energy + _energy;
hungry := hungry + _hungry;
end;
procedure maxStats(message: String);
begin
clrscr;
textcolor(yellow);
writeLn(message);
end;
begin
clrscr;
Textbackground(0);
textcolor(LIGHT_GRAY);
writeln('Hi! What is your name?');
textcolor(DARK_BLUE);
readln(user);
textcolor(LIGHT_GRAY);
writeln('');
writeln('Great, ' ,user, '! Now choose a pet: cat or dog?');
textcolor(DARK_BLUE);
readln(pet);
if (pet <> CAT) and (pet <> DOG) then
begin
writeln('You want ',pet,'... Are you serious? You can choose only cat or dog');
readln;
exit
end;
givePetName;
hungry := 3;
mood := 3;
toilet := 3;
hygiene := 3;
energy := 5;
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [1] ');
textcolor(DARK_BLUE); writeln('to feed your ' ,pet );
textcolor(GRAY); write('* hungry'); textcolor(LIGHT_GRAY); write(' (+1) ');
textcolor(GRAY); write('toilet, energy'); textcolor(LIGHT_GRAY); writeln(' (-1)');
writeln('');
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [2] ');
textcolor(DARK_BLUE); writeln('to make ' ,name, ' more happy');
textcolor(GRAY); write('* mood'); textcolor(LIGHT_GRAY); write(' (+1) ');
textcolor(GRAY); write('energy'); textcolor(LIGHT_GRAY); writeln(' (-1)');
writeln('');
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [3] ');
textcolor(DARK_BLUE); writeln('to avoid some dirty things');
textcolor(GRAY); write('* toilet, mood'); textcolor(LIGHT_GRAY); write(' (+1) ');
textcolor(GRAY); write('hungry, energy'); textcolor(LIGHT_GRAY); writeln(' (-1)');
writeln('');
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [4] ');
textcolor(DARK_BLUE); writeln('to wash your ' ,pet );
textcolor(GRAY); write('* hygiene'); textcolor(LIGHT_GRAY); write(' (+1) ');
textcolor(GRAY); write('mood, energy'); textcolor(LIGHT_GRAY); writeln(' (-1)');
writeln('');
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [5] ');
textcolor(DARK_BLUE); writeln('to send your pet to sleep' );
textcolor(GRAY); write('* energy'); textcolor(LIGHT_GRAY); write(' (+2) ');
textcolor(GRAY); write('hungry, toilet, hygiene, mood'); textcolor(LIGHT_GRAY); writeln(' (-1)');
writeln('');
textcolor(DARK_BLUE); write('Press'); textcolor(WHITE); write(' [6] ');
textcolor(DARK_BLUE); writeln('to exit the game' );
textcolor(LIGHT_GRAY); write('P.S. you will get'); textcolor(WHITE); write(' (+2) ');
textcolor(LIGHT_GRAY); write('if hungry, mood, toilet or hygiene'); textcolor(WHITE); writeln(' = 1');
while menuChoice < 7 do
begin
haltIfGameOver;
steps := steps + 1;
if pet = CAT then
begin
writeln('');
textcolor(LIGHT_GRAY); write(' [1] hungry : ',hungry);
textcolor(GREEN); writeln(' ^ ^ ' ); textcolor(LIGHT_GRAY); write(' [2] mood : ',mood);
textcolor(GREEN); writeln(' =(^.^)= '); textcolor(LIGHT_GRAY); write(' [3] toilet : ',toilet);
textcolor(GREEN); writeln(' x '); textcolor(LIGHT_GRAY); write(' [4] hygiene : ',hygiene);
textcolor(GREEN); writeln(' /( )\ '); textcolor(LIGHT_GRAY); write(' [5] energy : ',energy);
textcolor(GREEN); writeln(' U U' );
end
else if pet = DOG then
begin
writeln('');
textcolor(LIGHT_GRAY); write(' [1] hungry : ',hungry);
textcolor(LIGHT_BLUE); writeln(' {} {} '); textcolor(LIGHT_GRAY); write(' [2] mood : ',mood);
textcolor(LIGHT_BLUE); writeln(' (^ ^) '); textcolor(LIGHT_GRAY); write(' [3] toilet : ',toilet);
textcolor(LIGHT_BLUE); writeln(' _V_ '); textcolor(LIGHT_GRAY); write(' [4] hygiene : ',hygiene);
textcolor(LIGHT_BLUE); writeln(' /|___|\ '); textcolor(LIGHT_GRAY); write(' [5] energy : ',energy);
textcolor(LIGHT_BLUE); writeln(' O O');
end;
textcolor(WHITE);
readln(menuChoice);
if menuChoice = 1 then
case hungry of
4: changeState ('You gave food to ' + name, -1, 0, -1, +1, 0);
3: changeState ('Omnomnom', -1, 0, -1, +1, 0);
2: changeState ('Mmmm tasty! Thank you', -1, 0, -1, +1, 0);
1: changeState ('Yokarniy babay! '+user+'! Can you remember about me before I am so hungry that I am gonna die?!', -1, 0, -1, +2, 0);
0: ;
else maxStats(user + ' I do not want to be fat!!! Stop it!');
end
else if menuChoice = 2 then
case mood of
4: changeState ('You are playing with ' + name, 0, +1, -1, 0, 0);
3: changeState ('It is so much fun for ' + name, 0, +1, -1, 0, 0);
2: changeState ('Wooooohooooooo yeah baby!!! I like to play with you!', 0, +1, -1, 0, 0);
1: changeState ('I am the most sad '+ pet +' in the world... Ok, lets play a bit', 0, +2, -1, 0, 0);
0: ;
else maxStats('Ow, you know, I am happy enough. Next time... ok? ^_^');
end
else if menuChoice = 3 then
case toilet of
4: changeState ('You are walking in the park with ' + name, 1, 1, -1, -1, 0);
3: changeState ('You are walking near the lake', 1, 1, -1, -1, 0);
2: changeState (user + ', you are just in time. I want to do some dirty things ;)', 1, 1, -1, -1, 0);
1: changeState ('Thanks. Next time I will do it on your bed. Nothing personal.', 2, 1, -1, -1, 0);
0: ;
else maxStats('Thank you ' + user + ' but I do not want to the toilet');
end
else if menuChoice = 4 then
case hygiene of
4: changeState ('Oooow I am not so dirty.... okay...', 0, -1, -1, 0, +1);
3: changeState ('I hate taking a bath ...', 0, -1, -1, 0, +1);
2: changeState ('Perhaps you are right... I am a bit dirty', 0, -1, -1, 0, +1);
1: changeState (user + 'I stinck... cooool XD', 0, -1, -1, 0, +1);
0: ;
else maxStats('I am super clean. Take your shampoo away from me');
end
else if menuChoice = 5 then
case energy of
4: changeState ('Zzz', -1, -1, +2, -1, 0);
3: changeState ('woah... Zzz', -1, -1, +2, -1, 0);
2: changeState ('Yeah, it is a good time to have a nap', -1, -1, +2, -1, 0);
1: changeState ('I wanna sleep sooooo much... May I hug you, '+user+'? ... Zzz', -1, -1, +2, -1, 0);
0: ;
else maxStats('Sleep??? No no no, I am full of energy!');
end
else if menuChoice = 6 then
begin
textcolor(yellow);
writeln('Are you sure you want to exit? Y/N');
readln(answer);
if upcase(answer) <> 'N' then exit;
end;
end;
end.
|
unit IconUtils;
interface
uses
Windows, SysUtils, Graphics, ShellApi, ShlObj;
function GetIconFromPathIndx( const PathIndx : string ) : HICON;
function GetIconFromFile( const filename : string ) : TIcon;
function GetIconFromResource( Resource : string ) : TIcon;
function GetDirectoryLargeIcon : TIcon;
function GetDirectorySmallIcon : TIcon;
function GetSystemLargeIcon( const filename : string ) : TIcon;
function GetSystemSmallIcon( const filename : string ) : TIcon;
function GetShellLargeIcon( const filename : string ) : TIcon;
function GetShellSmallIcon( const filename : string ) : TIcon;
function GetOpenIcon( const filename : string ) : TIcon;
function GetComputerLargeIcon : TIcon;
function GetComputerSmallIcon : TIcon;
function GetPidlLargeIcon( aPidl : PItemIDList ) : TIcon;
function GetPidlSmallIcon( aPidl : PItemIDList ) : TIcon;
implementation
uses
StrUtils;
function GetIconFromPathIndx( const PathIndx : string ) : HICON;
var
Pos : integer;
Indx : integer;
begin
if PathIndx <> '%1'
then
begin
Pos := BackPos( ',', PathIndx, 0 );
if Pos <> 0
then
begin
Indx := StrToInt( RightStr( PathIndx, Length(PathIndx) - Pos ));
Result := ExtractIcon( hInstance, pchar(copy( PathIndx, 1, Pos - 1 )), Indx );
end
else Result := ExtractIcon( hInstance, pchar(PathIndx), 0);
end
else Result := 0;
end;
function GetIconFromFile( const filename : string ) : TIcon;
begin
result := TIcon.Create;
//filename := 'e:\esc\wise\cathegories\work\icons\' + filename;
result.LoadFromFile( filename );
end;
function GetIconFromResource( Resource : string ) : TIcon;
begin
result := TIcon.Create;
result.Handle := LoadIcon( hInstance, pchar(Resource) );
end;
function GetDirectoryLargeIcon : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( '', 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_LARGEICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetDirectorySmallIcon : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( '', 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetSystemLargeIcon( const filename : string ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(filename), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_LARGEICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetSystemSmallIcon( const filename : string ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(filename), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetShellLargeIcon( const filename : string ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(filename), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SHELLICONSIZE );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetShellSmallIcon( const filename : string ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(filename), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SHELLICONSIZE
or SHGFI_SMALLICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetOpenIcon( const filename : string ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(filename), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_OPENICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetComputerLargeIcon : TIcon;
var
str : string;
L : DWORD;
SHInfo : TSHFileInfo;
begin
SetLength( str, 50 );
L := 50;
GetComputerName( pchar(str), L );
SHGetFileInfo( pchar('\\' + str), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_LARGEICON );
result := TIcon.Create;
result.handle := SHInfo.HIcon;
end;
function GetComputerSmallIcon : TIcon;
var
str : string;
L : DWORD;
SHInfo : TSHFileInfo;
begin
SetLength( str, 50 );
L := 50;
GetComputerName( pchar(str), L );
SHGetFileInfo( pchar('\\' + str), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_ICON or SHGFI_SMALLICON );
result := TIcon.Create;
result.handle := SHInfo.HIcon;
end;
function GetPidlLargeIcon( aPidl : PItemIDList ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(aPidl), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_PIDL or SHGFI_ICON or SHGFI_SHELLICONSIZE );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
function GetPidlSmallIcon( aPidl : PItemIDList ) : TIcon;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(aPidl), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_PIDL or SHGFI_ICON or SHGFI_SHELLICONSIZE
or SHGFI_SMALLICON );
if SHInfo.hIcon <> 0
then
begin
result := TIcon.Create;
result.Handle := SHInfo.hIcon;
end
else result := nil;
end;
end.
|
unit bsDocumentContextSearcher;
{* Объект предназначенный для контекстного поиска в документе }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\bsDocumentContextSearcher.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TbsDocumentContextSearcher" MUID: (495137C70135)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, l3ProtoObject
, BaseSearchInterfaces
, eeEditor
, DynamicTreeUnit
, l3Interfaces
, nevTools
;
type
TbsDocumentContextSearcher = class(Tl3ProtoObject, IbsBaseDocumentContextSearcher)
{* Объект предназначенный для контекстного поиска в документе }
private
f_Editor: TeeCustomEditor;
f_Found: IFindIterator;
f_Context: Il3CString;
f_WasFound: Boolean;
f_CaretPoint: InevBasePoint;
private
procedure DoContextFound(const aFoundBlock: InevRange;
var aResult: TbsBaseSearchResult);
procedure DoSearchFinished(const aPrevFoundBlock: InevRange;
SearchDown: Boolean;
var aResult: TbsBaseSearchResult);
protected
function Find(const aContext: Il3CString): TbsBaseSearchResult;
{* поиск }
procedure ContextChanged(const aNewContext: Il3CString);
function pm_GetCanContinue: Boolean;
function pm_GetContext: Il3CString;
function FindBack: TbsBaseSearchResult;
{* Вернутся к предыдущему вхождению }
function Get_CanFindBack: Boolean;
function pm_GetFragmentsCount: Integer;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aEditor: TeeCustomEditor); reintroduce;
class function Make(aEditor: TeeCustomEditor): IbsBaseDocumentContextSearcher; reintroduce;
end;//TbsDocumentContextSearcher
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
, l3String
, nsTagNodeTools
, SysUtils
, DataAdapter
, nsTypes
, k2Tags
, nsContextSearchParams
, Document_Const
, Block_Const
, BaseTypesUnit
, nsFindIteratorNew
, nsFindIteratorNewForAutoreferat
, nsFindIteratorNewForDiction
, DocumentUnit
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, evSearch
, nsContextListForSearchViaEverestOwnSearcher
, nsFoundRangeCollector
, evTypes
, l3Variant
//#UC START# *495137C70135impl_uses*
//#UC END# *495137C70135impl_uses*
;
procedure TbsDocumentContextSearcher.DoContextFound(const aFoundBlock: InevRange;
var aResult: TbsBaseSearchResult);
var l_Lock: Il3Lock;
var l_Start: InevBasePoint;
var l_Finish: InevBasePoint;
//#UC START# *4A1FEB0D01AF_495137C70135_var*
//#UC END# *4A1FEB0D01AF_495137C70135_var*
begin
//#UC START# *4A1FEB0D01AF_495137C70135_impl*
aResult := bsrContinueSearch;
f_WasFound := True;
Supports(f_Editor, Il3Lock, l_Lock);
with f_Editor do
begin
if Assigned(l_Lock) then
l_Lock.Lock(Self);
try
if Assigned(f_CaretPoint) then
InevSelection(Selection).SelectPoint(f_CaretPoint, False, False);
Selection.FoundBlock := aFoundBlock;
InevSelection(Selection).GetBlock.GetBorderPoints(l_Start, l_Finish);
View.MakePairVisible(l_Start, l_Finish);
finally
if Assigned(l_Lock) then
l_Lock.UnLock(Self);
end;
end;
//#UC END# *4A1FEB0D01AF_495137C70135_impl*
end;//TbsDocumentContextSearcher.DoContextFound
procedure TbsDocumentContextSearcher.DoSearchFinished(const aPrevFoundBlock: InevRange;
SearchDown: Boolean;
var aResult: TbsBaseSearchResult);
var l_HasEntries: Boolean;
//#UC START# *4A1FEB3F01DB_495137C70135_var*
//#UC END# *4A1FEB3F01DB_495137C70135_var*
begin
//#UC START# *4A1FEB3F01DB_495137C70135_impl*
l_HasEntries := Assigned(f_Found) and (f_Found.GetCount > 0);
f_Editor.Selection.FoundBlock := aPrevFoundBlock;
// Завершен поиск в выделенном:
if SearchDown then
begin
if f_wasFound then
aResult := bsrSearchFinished
// - поиск в тексте завершен;
else
if l_HasEntries then
aResult := bsrSearchFinishedAllInHidden
else
aResult := bsrSearchFinishedNotFound;
// - в тексте ничего не нашли;
end
else
aResult := bsrSearchFinishedAllInHidden;
if aResult <> bsrSearchFinished then
f_Found := nil;
f_WasFound := False;
//#UC END# *4A1FEB3F01DB_495137C70135_impl*
end;//TbsDocumentContextSearcher.DoSearchFinished
constructor TbsDocumentContextSearcher.Create(aEditor: TeeCustomEditor);
//#UC START# *4C9C8EA2016A_495137C70135_var*
//#UC END# *4C9C8EA2016A_495137C70135_var*
begin
//#UC START# *4C9C8EA2016A_495137C70135_impl*
inherited Create;
f_Editor := aEditor;
//#UC END# *4C9C8EA2016A_495137C70135_impl*
end;//TbsDocumentContextSearcher.Create
class function TbsDocumentContextSearcher.Make(aEditor: TeeCustomEditor): IbsBaseDocumentContextSearcher;
var
l_Inst : TbsDocumentContextSearcher;
begin
l_Inst := Create(aEditor);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TbsDocumentContextSearcher.Make
function TbsDocumentContextSearcher.Find(const aContext: Il3CString): TbsBaseSearchResult;
{* поиск }
//#UC START# *4952664C03BC_495137C70135_var*
function lp_MakeFound(const aDoc : InevObject;
const aPoint : InevBasePoint): IFindIterator;
function FindInProvider(aDoc : Tl3Variant;
aFromParaID : Integer;
out theIterator : IFindIterator) : Boolean;
var
l_Provider : IDocumentTextProvider;
l_Found : IFoundContext;
begin//FindInProvider
if aDoc.Box.QI(IDocumentTextProvider, l_Provider) then
try
Result := true;
try
l_Provider.FindContext(nsIStr(aContext),
aFromParaID,
l_Found);
except
on ECannotFindData do
begin
theIterator := nil;
Exit;
end;//ECannotFindData
end;//try..except
theIterator := TnsFindIteratorNew.Make(l_Found);
finally
l_Provider := nil;
end//try..finally
else
Result := false;
end;//FindInProvider
function FindViaEverestOwnSearcher(const aDoc: InevObject;
const aPoint : InevBasePoint;
out theIterator : IFindIterator): Boolean;
const
cOp = [ev_soGlobal, ev_soReplace, ev_soReplaceAll, ev_soNoException];
var
l_C : TnsFoundRangeCollector;
l_BM : TevBMTextSearcher;
l_P : InevPara;
l_Ctx : Il3CString;
begin//FindViaEverestOwnSearcher
Result := false;
l_C := TnsFoundRangeCollector.Create;
try
l_BM := TevBMTextSearcher.Create;
try
l_Ctx := aContext;
l3DeleteChars(l_Ctx, ['*','"','!']);
l_BM.Text := l3Str(l_Ctx);
if not aDoc.AsObject.QT(InevPara, l_P) then
Assert(false);
l_C.Options := cOp;
l_BM.Options := cOp;
if evReplaceInPara(l_P, l_BM, l_C, nil, aPoint) then
if not l_C.FoundRanges.Empty then
begin
Result := true;
theIterator := TnsFindIteratorNew.Make(
TnsContextListForSearchViaEverestOwnSearcher.Make(
aDoc,
l_C.FoundRanges));
end;//not l_C.FoundRanges.Empty
finally
FreeAndNil(l_BM);
end;//try..finally
finally
FreeAndNil(l_C);
end;//try..finally
end;//FindViaEverestOwnSearcher
procedure TryFindInProvidersList(const aDoc : InevObjectList; var thereWasDoc : Boolean);
var
l_ID : Integer;
l_L : TnsIFindIteratorList;
procedure DoDoc(const aDoc : InevObject; aNeedID : Boolean);
var
l_It : IFindIterator;
l_ThisDocID : Integer;
l_Pt : InevBasePoint;
begin//DoDoc
if aDoc.AsObject.IsKindOf(k2_typDocument) then
begin
// - это вложенный документ
thereWasDoc := true;
if aNeedID then
l_ThisDocID := l_ID
else
l_ThisDocID := 0;
if FindInProvider(aDoc.AsObject, l_ThisDocID, l_It) then
begin
// - вкладываем один итератор в другой
if (l_It <> nil) then
l_L.Add(TnsFindIteratorDef_C(aDoc, l_It));
end//FindInProvider(aDoc, l_ThisDocID, l_It)
else
begin
if aNeedID then
begin
l_Pt := aPoint.MostInner.PointToParent(aDoc);
// - учитываем что попросили искать не с самого начала документа
Assert(l_Pt <> nil);
end//aNeedID
else
l_Pt := aDoc.MakePoint;
FindViaEverestOwnSearcher(aDoc, l_Pt, l_It);
if (l_It <> nil) then
l_L.Add(TnsFindIteratorDef_C(aDoc, l_It));
end;//FindInProvider(aDoc, l_ThisDocID, l_It)
end;//aDoc.IsKindOf(k2_typDocument)
end;//DoDoc
var
l_Index : Integer;
l_C : InevObject;
l_Median : Integer;
begin//TryFindInProvidersList
l_L := TnsIFindIteratorList.Create;
try
l_Median := aPoint.Position;
Dec(l_Median);
// - учитываем кривизну мира курсоров от списков параграфов
Assert(l_Median >= 0);
l_ID := aPoint.MostInner.AsObject.IntA[k2_tiHandle];
for l_Index := l_Median to Pred(aDoc.Count) do
DoDoc(aDoc.Obj[l_Index], l_Index = l_Median);
for l_Index := 0 to Pred(l_Median) do
DoDoc(aDoc.Obj[l_Index], false);
if (l_L.Count > 0) then
begin
Result := TnsFindIteratorNewForAutoreferat.Make(l_L);
end//l_L.Count > 0
else
begin
//Assert(false);
// http://mdp.garant.ru/pages/viewpage.action?pageId=255981614
Result := nil;
end;//l_L.Count > 0
finally
FreeAndNil(l_L);
end;//try..finally
end;//TryFindInProvidersList
var
l_Child0 : Tl3Variant;
l_FromParaID : Integer;
l_WasDoc : Boolean;
begin//lp_MakeFound
l_FromParaID := aPoint.MostInner.AsObject.IntA[k2_tiHandle];
if FindInProvider(aDoc.AsObject, l_FromParaID, Result) then
// - нашли в "новом" документе
begin
Exit;
end//FindInProvider(aDoc, l_FromParaID, Result)
else
if (aDoc.AsObject.ChildrenCount = 1) then
begin
l_Child0 := aDoc.AsObject.Child[0];
if l_Child0.IsKindOf(k2_typBlock) AND
not l_Child0.IsKindOf(k2_typDocument) then
// - наверное это толковый словарь
begin
if FindInProvider(l_Child0, l_FromParaID, Result) then
begin
if (Result <> nil) then
Result := TnsFindIteratorNewForDiction.Make(Result, l_Child0);
Exit;
end;//FindInProvider(l_Child0, l_FromParaID, Result)
end;//l_Child0.IsKindOf(k2_typBlock)
end;//aDoc.ChildrenCount = 1
if (Result = nil) then
begin
l_WasDoc := false;
TryFindInProvidersList(aDoc.ToList, l_WasDoc);
if not l_WasDoc then
// - это не составной документ, попытаемся искать своими собственными средствами
begin
FindViaEverestOwnSearcher(aDoc, aPoint, Result);
end;//not l_WasDoc
end;//Result = nil
end;//lp_MakeFound
var
l_Doc : InevObject;
l_SearchResult : Boolean;
l_PrevFoundBlock : InevRange;
l_FoundBlock : InevRange;
//#UC END# *4952664C03BC_495137C70135_var*
begin
//#UC START# *4952664C03BC_495137C70135_impl*
Result := bsrNone;
if not l3IsNil(aContext) then
begin
with f_Editor, Selection do
if Assigned(FoundBlock) then
l_PrevFoundBlock := FoundBlock.CloneSel(View)
else
l_PrevFoundBlock := nil;
f_Editor.Selection.DeleteFoundBlockBeforeSearch;
l_Doc := f_Editor.Document;
// Поиск в тексте:
f_Context := aContext;
if Assigned(f_CaretPoint) and
(f_CaretPoint.Compare(f_Editor.Selection.Cursor) <> 0) then
f_Found := nil;
if not f_WasFound then
f_Found := nil;
if not Assigned(f_Found) then
f_Found := lp_MakeFound(l_Doc, f_Editor.Selection.Cursor);
l_SearchResult := nsIteratorToRange(l_Doc,
f_Found,
f_Editor.View,
nil,
True,
f_Editor,
l_FoundBlock,
f_CaretPoint);
if l_SearchResult then
DoContextFound(l_FoundBlock, Result)
// Ничего не нашли:
else
DoSearchFinished(l_PrevFoundBlock, true, Result);
end;//not l3IsNil(aContext)
//#UC END# *4952664C03BC_495137C70135_impl*
end;//TbsDocumentContextSearcher.Find
procedure TbsDocumentContextSearcher.ContextChanged(const aNewContext: Il3CString);
//#UC START# *4952665F0298_495137C70135_var*
//#UC END# *4952665F0298_495137C70135_var*
begin
//#UC START# *4952665F0298_495137C70135_impl*
if (aNewContext = nil) or not l3Same(f_Context, aNewContext) then
begin
f_Found := nil;
f_Context := nil;
f_WasFound := False;
end;//(aNewContext = nil) or not l3Same(f_Context, aNewContext)
//#UC END# *4952665F0298_495137C70135_impl*
end;//TbsDocumentContextSearcher.ContextChanged
function TbsDocumentContextSearcher.pm_GetCanContinue: Boolean;
//#UC START# *4952667C0385_495137C70135get_var*
//#UC END# *4952667C0385_495137C70135get_var*
begin
//#UC START# *4952667C0385_495137C70135get_impl*
Result := Assigned(f_Found);
//#UC END# *4952667C0385_495137C70135get_impl*
end;//TbsDocumentContextSearcher.pm_GetCanContinue
function TbsDocumentContextSearcher.pm_GetContext: Il3CString;
//#UC START# *495266A500B0_495137C70135get_var*
//#UC END# *495266A500B0_495137C70135get_var*
begin
//#UC START# *495266A500B0_495137C70135get_impl*
Result := f_Context;
//#UC END# *495266A500B0_495137C70135get_impl*
end;//TbsDocumentContextSearcher.pm_GetContext
function TbsDocumentContextSearcher.FindBack: TbsBaseSearchResult;
{* Вернутся к предыдущему вхождению }
//#UC START# *49FEAD670382_495137C70135_var*
var
l_Doc : InevObject;
l_SearchResult: Boolean;
l_FoundBlock: InevRange;
l_PrevFoundBlock: InevRange;
//#UC END# *49FEAD670382_495137C70135_var*
begin
//#UC START# *49FEAD670382_495137C70135_impl*
Result := bsrNone;
if Assigned(f_Found) then
begin
with f_Editor, Selection do
if Assigned(FoundBlock) then
l_PrevFoundBlock := FoundBlock.CloneSel(View)
else
l_PrevFoundBlock := nil;
f_Editor.Selection.DeleteFoundBlockBeforeSearch;
l_Doc := f_Editor.Document;
l_SearchResult := nsFindBackToRange(l_Doc,
f_Found,
f_Editor.View,
nil,
True,
f_Editor,
l_FoundBlock,
f_CaretPoint);
if l_SearchResult then
DoContextFound(l_FoundBlock, Result)
// Ничего не нашли:
else
DoSearchFinished(l_PrevFoundBlock, False, Result);
end;//Assigned(f_Found)
//#UC END# *49FEAD670382_495137C70135_impl*
end;//TbsDocumentContextSearcher.FindBack
function TbsDocumentContextSearcher.Get_CanFindBack: Boolean;
//#UC START# *49FEB49800A8_495137C70135get_var*
//#UC END# *49FEB49800A8_495137C70135get_var*
begin
//#UC START# *49FEB49800A8_495137C70135get_impl*
Result := Assigned(f_Found) and not f_Found.IsFirst;
//#UC END# *49FEB49800A8_495137C70135get_impl*
end;//TbsDocumentContextSearcher.Get_CanFindBack
function TbsDocumentContextSearcher.pm_GetFragmentsCount: Integer;
//#UC START# *49FFE06200FA_495137C70135get_var*
//#UC END# *49FFE06200FA_495137C70135get_var*
begin
//#UC START# *49FFE06200FA_495137C70135get_impl*
if Assigned(f_Found) then
Result := f_Found.GetCount
else
Result := 0;
//#UC END# *49FFE06200FA_495137C70135get_impl*
end;//TbsDocumentContextSearcher.pm_GetFragmentsCount
procedure TbsDocumentContextSearcher.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_495137C70135_var*
//#UC END# *479731C50290_495137C70135_var*
begin
//#UC START# *479731C50290_495137C70135_impl*
f_CaretPoint := nil;
f_Found := nil;
f_Context := nil;
f_Editor := nil;
inherited;
//#UC END# *479731C50290_495137C70135_impl*
end;//TbsDocumentContextSearcher.Cleanup
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
unit Languages;
interface
uses
Classes, CacheAgent, MapStringToObject;
type
TLanguageId = string;
type
TMultiString =
class( TStringList )
end;
TRegMultiString =
class( TMultiString )
public
constructor Create( anId, aDefValue : string );
destructor Destroy; override;
private
fId : string;
fDefaultValue : string;
public
property Id : string read fId;
property DefaultValue : string read fDefaultValue;
end;
TDictionary =
class
public
constructor Create( filename : string );
private
fLangId : TLanguageId;
fValues : TStringList;
fIndex : TStringList;
private
function GetValue( Id : string ) : string;
procedure SetValue( Id, value : string );
public
property LangId : TLanguageId read fLangId write fLangId;
property Values[Id : string] : string read GetValue write SetValue;
public
procedure Store( filename : string );
end;
const
langDefault = '0';
procedure InitMLS;
procedure DoneMLS;
const
LangList : TStringList = nil;
NullString : TRegMultiString = nil;
procedure RequestLanguage( Id : string );
function CreateDictionary : TDictionary;
procedure ApplyDictionary( Dict : TDictionary; LangId : TLanguageId );
function GetMultiString( Id : string ) : TRegMultiString;
function InstantiateMultiString( Source : TRegMultiString; Data : array of const ) : TMultiString;
function CloneMultiString( Source : TMultiString ) : TMultiString;
procedure StoreMultiStringToCache( Name : string; MS : TMultiString; Cache : TObjectCache );
procedure RegisterBackup;
procedure LoadMLSFrom(path : string);
implementation
uses
SysUtils, Collection, VCLBackup, Logs;
const
MLSRegistry : TStringList = nil;
// RegMultiString
constructor TRegMultiString.Create( anId, aDefValue : string );
begin
inherited Create;
fId := anId;
fDefaultValue := aDefValue;
Values[langDefault] := fDefaultValue;
MLSRegistry.AddObject( fId, self );
end;
destructor TRegMultiString.Destroy;
begin
try
Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName );
except
end;
inherited;
end;
// TDictionary
constructor TDictionary.Create( filename : string );
var
i : integer;
p : integer;
aux : string;
name : string;
begin
fValues := TStringList.Create;
if filename <> ''
then
begin
fValues.LoadFromFile( filename );
fLangId := fValues.Values['LangId'];
fIndex := TStringList.Create;
fIndex.Sorted := true;
fIndex.Duplicates := dupIgnore;
for i := 0 to pred(fValues.Count) do
begin
aux := fValues[i];
p := system.pos('=', aux);
if p > 0
then
begin
name := copy(aux, 1, p - 1);
fIndex.AddObject(name, TObject(i));
end;
end;
end
else fLangId := '0';
end;
function TDictionary.GetValue( Id : string ) : string;
var
idx : integer;
aux : string;
p : integer;
begin
if fIndex = nil
then result := fValues.Values[Id]
else
begin
idx := fIndex.IndexOf(Id);
if idx >= 0
then
begin
idx := integer(fIndex.Objects[idx]);
aux := fValues[idx];
end
else aux := '';
p := system.pos('=', aux);
if p > 0
then result := system.copy(aux, p + 1, length(aux) - p)
else result := '';
end;
end;
procedure TDictionary.SetValue( Id, value : string );
begin
fValues.Values[Id] := value;
end;
procedure TDictionary.Store( filename : string );
begin
fValues.SaveToFile( filename );
end;
procedure InitMLS;
begin
MLSRegistry := TStringList.Create;
LangList := TStringList.Create;
NullString := TRegMultiString.Create( 'NULL', '+++STRING NOT DEFINED+++' );
end;
procedure DoneMLS;
begin
MLSRegistry.Free;
end;
procedure RequestLanguage( Id : string );
begin
LangList.Add( Id );
end;
function CreateDictionary : TDictionary;
var
i : integer;
MS : TRegMultiString;
begin
result := TDictionary.Create( '' );
for i := 0 to pred(MLSRegistry.Count) do
begin
MS := TRegMultiString(MLSRegistry.Objects[i]);
if MS <> NullString
then result.Values[MS.fId] := MS.fDefaultValue;
end;
end;
procedure ApplyDictionary( Dict : TDictionary; LangId : TLanguageId );
var
i : integer;
MS : TRegMultiString;
begin
for i := 0 to pred(MLSRegistry.Count) do
begin
MS := TRegMultiString(MLSRegistry.Objects[i]);
if MS <> NullString
then MS.Values[LangId] := Dict.Values[MS.fId];
end;
end;
function GetMultiString( Id : string ) : TRegMultiString;
var
idx : integer;
begin
idx := MLSRegistry.IndexOf( id );
if idx <> -1
then result := TRegMultiString(MLSRegistry.Objects[idx])
else result := NullString;
end;
function InstantiateMultiString( Source : TRegMultiString; Data : array of const ) : TMultiString;
var
i : integer;
begin
result := TMultiString.Create;
for i := 0 to pred(Source.Count) do
try
result.Add( Format( Source[i], Data ) );
except
end;
end;
function CloneMultiString( Source : TMultiString ) : TMultiString;
var
i : integer;
begin
result := TMultiString.Create;
for i := 0 to pred(Source.Count) do
result.Add( Source[i] );
end;
procedure StoreMultiStringToCache( Name : string; MS : TMultiString; Cache : TObjectCache );
var
i : integer;
begin
for i := 0 to pred(LangList.Count) do
Cache.WriteString( Name + IntToStr(i), MS.Values[LangList[i]] );
end;
type
TMultiStringBackupAgent =
class( TStringListBackupAgent )
end;
procedure RegisterBackup;
begin
TMultiStringBackupAgent.Register( [TMultiString] );
end;
procedure LoadMLSFrom(path : string);
var
Srch : TSearchRec;
begin
if FindFirst(path + '\*.*', faDirectory, Srch) = 0
then
repeat
if (Srch.Attr and faDirectory <> 0) and (Srch.Attr and faArchive = 0) and (Srch.Name <> '..') and (Srch.Name <> '.')
then RequestLanguage(Srch.Name);
until FindNext(Srch) <> 0;
end;
initialization
InitMLS;
finalization
DoneMLS;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2022 Kike Pérez
Unit : Quick.Linq
Description : Arrays and Generic Lists Linq functions
Author : Kike Pérez
Version : 1.0
Created : 04/04/2019
Modified : 27/01/2022
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.Linq;
{$i QuickLib.inc}
interface
uses
SysUtils,
Generics.Collections,
Generics.Defaults,
RTTI,
Quick.RTTI.Utils,
Quick.Expression,
Quick.Commons,
Quick.Value,
{$IFDEF FPC}
Quick.Value.RTTI,
{$ELSE}
System.RegularExpressions,
{$ENDIF}
Quick.Arrays;
type
TOrderDirection = (odAscending, odDescending);
{$IFNDEF FPC}
TLinqExpression<T : class> = class(TExpression)
private
fPredicate : TPredicate<T>;
public
constructor Create(aPredicate : TPredicate<T>);
function Validate(const aValue : TValue) : Boolean; override;
function IsNull : Boolean; override;
end;
{$ENDIF}
ILinqArray<T> = interface
['{3133DCAB-06C5-434B-B169-B32DC8C6308B}']
function Any : Boolean; overload;
function Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean; overload;
function Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<T>; overload;
function OrderAscending : ILinqArray<T>;
function OrderDescending : ILinqArray<T>;
function SelectFirst : T;
function SelectLast : T;
function SelectTop(aLimit : Integer) : TArray<T>;
function Select : TArray<T>; overload;
function Count : Integer;
function Update(const aNewValue : T) : Integer;
function Delete : Integer;
end;
{$IFNDEF FPC}
TLinqArray<T> = class(TInterfacedObject,ILinqArray<T>)
type
TLinqComparer = class(TInterfacedObject,IComparer<T>)
private
fSortAscending : Boolean;
public
constructor Create(aSortAscending : Boolean);
property SortAscending : Boolean read fSortAscending;
function Compare(const L, R: T): Integer;
end;
private
fArray : TArray<T>;
fMatchString : string;
fUseRegEx : Boolean;
function Validate(aValue : T) : Boolean;
public
constructor Create(aArray : TArray<T>);
function Any : Boolean; overload;
function Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean; overload;
function Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<T>; overload;
function OrderAscending : ILinqArray<T>;
function OrderDescending : ILinqArray<T>;
function SelectFirst : T;
function SelectLast : T;
function SelectTop(aLimit : Integer) : TArray<T>;
function Select : TArray<T>; overload;
function Count : Integer;
function Update(const aNewValue : T) : Integer;
function Delete : Integer;
end;
TLinqArrayHelper = record helper for TArray<string>
function Add(const aValue : string) : Integer;
function AddIfNotExists(const aValue : string) : Integer;
function Remove(const aValue : string) : Boolean;
function Any : Boolean; overload;
function Any(const aValue : string) : Boolean; overload;
function Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean; overload;
function Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<string>; overload;
end;
{$ENDIF}
ILinqQuery<T> = interface
['{16B68C0B-EA38-488A-99D9-BAD1E8560E8E}']
function Where(const aWhereClause : string; aWhereValues : array of const) : ILinqQuery<T>; overload;
function Where(const aWhereClause: string): ILinqQuery<T>; overload;
{$IFNDEF FPC}
function Where(aPredicate : TPredicate<T>) : ILinqQuery<T>; overload;
{$ENDIF}
function OrderBy(const aFieldNames : string) : ILinqQuery<T>;
function OrderByDescending(const aFieldNames : string) : ILinqQuery<T>;
function SelectFirst : T;
function SelectLast : T;
function SelectTop(aLimit : Integer) : TxArray<T>;
function Select : TxArray<T>; overload;
function Select(const aPropertyName : string) : TFlexArray; overload;
function Count : Integer;
function Update(const aFields : array of string; aValues : array of const) : Integer;
function Delete : Integer;
end;
TLinqQuery<T : class> = class(TInterfacedObject,ILinqQuery<T>)
private type
arrayOfT = array of T;
TArrType = (atArray, atXArray, atList, atObjectList);
private
fWhereClause : TExpression;
fOrderBy : TArray<string>;
fOrderDirection : TOrderDirection;
fPList : Pointer;
fList : arrayOfT;
fArrType : TArrType;
function FormatParams(const aWhereClause : string; aWhereParams : array of const) : string;
procedure DoOrderBy(vArray : ArrayOfT);
function Compare(const aPropertyName : string; L, R : T) : Integer;
procedure Clear;
public
{$IFNDEF FPC}
constructor Create(aObjectList : TObjectList<T>); overload;
{$ENDIF}
constructor Create(aList : TList<T>); overload;
constructor Create(aXArray : TxArray<T>); overload;
constructor Create(aArray : TArray<T>); overload;
destructor Destroy; override;
function Where(const aWhereClause : string; aWhereParams : array of const) : ILinqQuery<T>; overload;
function Where(const aWhereClause: string): ILinqQuery<T>; overload;
{$IFNDEF FPC}
function Where(aPredicate : TPredicate<T>) : ILinqQuery<T>; overload;
{$ENDIF}
function OrderBy(const aFieldNames : string) : ILinqQuery<T>;
function OrderByDescending(const aFieldNames : string) : ILinqQuery<T>;
function SelectFirst : T;
function SelectLast : T;
function SelectTop(aLimit : Integer) : TxArray<T>;
function Select : TxArray<T>; overload;
function Select(const aPropertyName : string) : TFlexArray; overload;
function Count : Integer;
function Update(const aFields : array of string; aValues : array of const) : Integer;
function Delete : Integer;
end;
TLinq<T : class> = class
public
{$IFNDEF FPC}
class function From(aObjectList : TObjectList<T>) : ILinqQuery<T>; overload;
{$ENDIF}
class function From(aArray : TArray<T>) : ILinqQuery<T>; overload;
class function From(aXArray : TXArray<T>) : ILinqQuery<T>; overload;
end;
ELinqNotValidExpression = class(Exception);
ELinqError = class(Exception);
implementation
{ TLinqQuery<T> }
procedure TLinqQuery<T>.Clear;
begin
SetLength(fOrderBy,0);
end;
constructor TLinqQuery<T>.Create(aArray: TArray<T>);
begin
Clear;
fPList := Pointer(aArray);
fList := aArray;
fArrType := TArrType.atArray;
end;
{$IFNDEF FPC}
constructor TLinqQuery<T>.Create(aObjectList: TObjectList<T>);
begin
Clear;
fPList := Pointer(aObjectList);
{$IFDEF DELPHIRX104_UP}
fList := aObjectList.PList^;
{$ELSE}
fList := aObjectList.List;
{$ENDIF}
fArrType := TArrType.atObjectList;
end;
{$ENDIF}
constructor TLinqQuery<T>.Create(aXArray: TxArray<T>);
begin
Clear;
fPList := Pointer(aXArray);
fList := aXArray.PArray^;
fArrType := TArrType.atXArray;
end;
constructor TLinqQuery<T>.Create(aList: TList<T>);
begin
Clear;
fPList := Pointer(aList);
{$IFDEF DELPHIRX104_UP}
fList := aList.PList^;
{$ELSE}
fList := aList.ToArray;
{$ENDIF}
fArrType := TArrType.atList;
end;
function TLinqQuery<T>.Compare(const aPropertyName: string; L, R: T): Integer;
var
valueL : TValue;
valueR : TValue;
begin
Result := 0;
valueL := TRTTI.GetPathValue(L,aPropertyName);
valueR := TRTTI.GetPathValue(R,aPropertyName);
if (valueL.IsEmpty) and (not valueR.IsEmpty) then Exit(1)
else if (not valueL.IsEmpty) and (valueR.IsEmpty) then Exit(-1);
case valueL.Kind of
{$IFNDEF FPC}
tkString,
{$ENDIF}
tkChar, tkWString, tkUString : Result := CompareText(valueL.AsString, valueR.AsString);
tkInteger, tkInt64 :
begin
if valueL.AsInteger > valueR.AsInteger then Result := 1
else if valueL.AsInteger < valueR.AsInteger then Result := -1;
end;
tkFloat :
begin
if valueL.AsExtended > valueR.AsExtended then Result := 1
else if valueL.AsExtended < valueR.AsExtended then Result := -1;
end;
end;
end;
function TLinqQuery<T>.Count: Integer;
var
i : Integer;
begin
Result := 0;
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for i := High(fList) downto Low(fList) do
begin
if fWhereClause.Validate(fList[i]) then
begin
Inc(Result);
end;
end;
end;
function TLinqQuery<T>.Delete: Integer;
var
i : Integer;
begin
Result := 0;
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for i := High(fList) downto Low(fList) do
begin
if fWhereClause.Validate(fList[i]) then
begin
case fArrType of
TArrType.atArray, TArrType.atXArray :
begin
TObject(fList[i]).Free;
System.Delete(fList,i,1);
//fPList := Pointer(fList);
end;
TArrType.atList :
begin
TList<T>(fPList).Delete(i);
end;
TArrType.atObjectList :
begin
TObjectList<T>(fPList).Delete(i);
end;
end;
Inc(Result);
end;
end;
end;
destructor TLinqQuery<T>.Destroy;
begin
if Assigned(fWhereClause) then fWhereClause.Free;
inherited;
end;
procedure TLinqQuery<T>.DoOrderBy(vArray : ArrayOfT);
begin
if High(fOrderBy) < 0 then Exit;
{$IFNDEF FPC}
TArray.Sort<T>(vArray, TComparer<T>.Construct(
function (const A, B: T): Integer
var
field : string;
begin
for field in fOrderBy do
begin
Result := Compare(field,A,B);
if Result <> 0 then Break;
end;
if fOrderDirection = TOrderDirection.odDescending then Result := Result * -1;
end)
);
{$ENDIF}
end;
function TLinqQuery<T>.OrderBy(const aFieldNames: string): ILinqQuery<T>;
begin
Result := Self;
if aFieldNames = '' then raise ELinqError.Create('No order fields specified!');
fOrderBy := aFieldNames.Split([',']);
fOrderDirection := TOrderDirection.odAscending;
end;
function TLinqQuery<T>.OrderByDescending(const aFieldNames: string): ILinqQuery<T>;
begin
Result := Self;
if aFieldNames = '' then raise ELinqError.Create('No order fields specified!');
fOrderBy := aFieldNames.Split([',']);
fOrderDirection := TOrderDirection.odDescending;
end;
function TLinqQuery<T>.Select(const aPropertyName: string): TFlexArray;
var
obj : T;
value : TFlexValue;
begin
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then
begin
//value := TRTTI.GetProperty(obj,aPropertyName);
{$IFNDEF FPC}
value := TRTTI.GetPathValue(obj,aPropertyName).AsVariant;
{$ELSE}
value.AsTValue := TRTTI.GetPathValue(obj,aPropertyName);
{$ENDIF}
Result.Add(value);
end;
end;
end;
function TLinqQuery<T>.Select: TxArray<T>;
var
obj : T;
begin
{$If Defined(FPC) OR Defined(DELPHIRX102_UP)}
Result := [];
{$ELSE}
Result := nil;
{$ENDIF}
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then Result.Add(obj);
end;
DoOrderBy(Result);
end;
function TLinqQuery<T>.SelectFirst: T;
var
obj : T;
begin
{$IFNDEF FPC}
Result := nil;
{$ENDIF}
DoOrderBy(fList);
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then Exit(obj);
end;
end;
function TLinqQuery<T>.SelectLast: T;
var
obj : T;
begin
{$IFNDEF FPC}
Result := nil;
{$ENDIF}
DoOrderBy(fList);
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then Result := obj;
end;
end;
function TLinqQuery<T>.SelectTop(aLimit: Integer): TxArray<T>;
var
obj : T;
i : Integer;
begin
{$If Defined(FPC) OR Defined(DELPHIRX102_UP)}
Result := [];
{$ELSE}
Result := nil;
{$ENDIF}
DoOrderBy(fList);
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
i := 0;
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then
begin
Result.Add(obj);
Inc(i);
if i > aLimit then Exit;
end;
end;
end;
function TLinqQuery<T>.Update(const aFields: array of string; aValues: array of const): Integer;
var
obj : T;
i : Integer;
{$IFDEF FPC}
value : TValue;
{$ENDIF}
begin
Result := 0;
if fWhereClause = nil then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for obj in fList do
begin
{$IFNDEF FPC}
if obj = nil then continue;
{$ELSE}
if Pointer(obj) = nil then continue;
{$ENDIF}
if fWhereClause.Validate(obj) then
begin
for i := Low(aFields) to High(aFields) do
begin
if not TRTTI.PropertyExists(TypeInfo(T),aFields[i]) then raise ELinqError.CreateFmt('Linq update field "%s" not found in obj',[aFields[i]]);
try
{$IFNDEF FPC}
TRTTI.SetPropertyValue(obj,aFields[i],aValues[i]);
{$ELSE}
case aValues[i].VType of
vtString : value := string(aValues[i].VString^);
vtChar : value := string(aValues[i].VChar);
{$IFDEF MSWINDOWS}
vtAnsiString : value := AnsiString(aValues[i].VAnsiString);
vtWideString : value := WideString(aValues[i].VWideString);
{$ENDIF}
{$IFDEF UNICODE}
vtUnicodeString: AsString := string(aValues[i].VUnicodeString);
{$ENDIF UNICODE}
vtInteger : value := aValues[i].VInteger;
vtInt64 : value := aValues[i].VInt64^;
vtExtended : value := aValues[i].VExtended^;
vtBoolean : value := aValues[i].VBoolean;
else raise Exception.Create('DataType not supported by Linq update');
end;
TRTTI.SetPropertyValue(obj,aFields[i],value);
{$ENDIF}
except
on E : Exception do raise ELinqError.CreateFmt('Linq update error: %s',[e.Message]);
end;
end;
Inc(Result);
end;
end;
end;
function TLinqQuery<T>.FormatParams(const aWhereClause : string; aWhereParams : array of const) : string;
var
i : Integer;
begin
Result := aWhereClause;
if aWhereClause = '' then
begin
Result := '1 = 1';
Exit;
end;
for i := 0 to aWhereClause.CountChar('?') - 1 do
begin
case aWhereParams[i].VType of
vtInteger : Result := StringReplace(Result,'?',IntToStr(aWhereParams[i].VInteger),[]);
vtInt64 : Result := StringReplace(Result,'?',IntToStr(aWhereParams[i].VInt64^),[]);
vtExtended : Result := StringReplace(Result,'?',FloatToStr(aWhereParams[i].VExtended^),[]);
vtBoolean : Result := StringReplace(Result,'?',BoolToStr(aWhereParams[i].VBoolean),[]);
vtAnsiString : Result := StringReplace(Result,'?',string(aWhereParams[i].VAnsiString),[]);
vtWideString : Result := StringReplace(Result,'?',string(aWhereParams[i].VWideString^),[]);
{$IFNDEF NEXTGEN}
vtString : Result := StringReplace(Result,'?',string(aWhereParams[i].VString^),[]);
{$ENDIF}
vtChar : Result := StringReplace(Result,'?',string(aWhereParams[i].VChar),[]);
vtPChar : Result := StringReplace(Result,'?',string(aWhereParams[i].VPChar),[]);
else Result := StringReplace(Result,'?', DbQuotedStr(string(aWhereParams[i].VUnicodeString)),[]);
end;
end;
end;
function TLinqQuery<T>.Where(const aWhereClause: string; aWhereParams: array of const): ILinqQuery<T>;
begin
Result := Where(FormatParams(aWhereClause,aWhereParams));
end;
function TLinqQuery<T>.Where(const aWhereClause: string): ILinqQuery<T>;
begin
Result := Self;
try
fWhereClause := TExpressionParser.Parse(aWhereClause);
except
on E : Exception do raise ELinqNotValidExpression.Create(e.Message);
end;
end;
{$IFNDEF FPC}
function TLinqQuery<T>.Where(aPredicate: TPredicate<T>): ILinqQuery<T>;
begin
Result := Self;
fWhereClause := TLinqExpression<T>.Create(aPredicate);
end;
{$ENDIF}
{ TLinq }
{$IFNDEF FPC}
class function TLinq<T>.From(aObjectList: TObjectList<T>): ILinqQuery<T>;
begin
Result := TLinqQuery<T>.Create(aObjectList);
end;
{$ENDIF}
class function TLinq<T>.From(aArray: TArray<T>): ILinqQuery<T>;
begin
Result := TLinqQuery<T>.Create(aArray);
end;
class function TLinq<T>.From(aXArray : TXArray<T>) : ILinqQuery<T>;
begin
Result := TLinqQuery<T>.Create(aXArray);
end;
{ TLinqExpression<T> }
{$IFNDEF FPC}
constructor TLinqExpression<T>.Create(aPredicate: TPredicate<T>);
begin
fPredicate := aPredicate;
end;
function TLinqExpression<T>.Validate(const aValue : TValue) : Boolean;
begin
Result := fPredicate(aValue.AsType<T>);
end;
function TLinqExpression<T>.IsNull : Boolean;
begin
Result := not Assigned(fPredicate);
end;
{ TLinqArray<T> }
function TLinqArray<T>.Any : Boolean;
begin
Result := High(fArray) >= 0;
end;
function TLinqArray<T>.Any(const aMatchString: string; aUseRegEx: Boolean): Boolean;
begin
fMatchString := aMatchString;
fUseRegEx := aUseRegEx;
end;
function TLinqArray<T>.Count: Integer;
begin
Result := High(fArray) + 1;
end;
constructor TLinqArray<T>.Create(aArray: TArray<T>);
begin
{$IFDEF DELPHIRX104_UP}
Pointer(fArray) := aArray;
{$ELSE}
fArray := aArray;
{$ENDIF}
end;
function TLinqArray<T>.Delete: Integer;
var
i : Integer;
{$IFNDEF DELPHIXE7_UP}
n : Integer;
len : Integer;
{$ENDIF}
begin
Result := 0;
if fMatchString.IsEmpty then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for i := High(fArray) downto Low(fArray) do
begin
if Validate(fArray[i]) then
begin
//TObject(fArray[i]).Free;
{$IFDEF DELPHIXE7_UP}
System.Delete(fArray,i,1);
{$ELSE}
len := Length(fArray);
if (len > 0) and (i < len) then
begin
for n := i + 1 to len - 1 do fArray[n - 1] := fArray[n];
SetLength(fArray, len - 1);
end;
{$ENDIF}
Inc(Result);
end;
end;
end;
function TLinqArray<T>.OrderAscending: ILinqArray<T>;
var
comparer : IComparer<T>;
begin
comparer := TLinqComparer.Create(True);
TArray.Sort<T>(fArray,comparer);
end;
function TLinqArray<T>.OrderDescending: ILinqArray<T>;
var
comparer : IComparer<T>;
begin
comparer := TLinqComparer.Create(False);
TArray.Sort<T>(fArray,comparer);
end;
function TLinqArray<T>.Select: TArray<T>;
var
value : T;
begin
Result := [];
//DoOrderBy(fList);
if fMatchString.IsEmpty then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for value in fArray do
begin
if Validate(value) then Result := Result + [value];
end;
end;
function TLinqArray<T>.SelectFirst: T;
var
value : T;
begin
//DoOrderBy(fList);
if fMatchString.IsEmpty then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for value in fArray do
begin
if Validate(value) then Exit(value);
end;
end;
function TLinqArray<T>.SelectLast: T;
var
value : T;
found : T;
begin
//DoOrderBy(fList);
if fMatchString.IsEmpty then raise ELinqNotValidExpression.Create('Not valid expression defined!');
for value in fArray do
begin
if Validate(value) then found := value;
end;
Result := found;
end;
function TLinqArray<T>.SelectTop(aLimit: Integer): TArray<T>;
var
i : Integer;
limit : Integer;
begin
Result := [];
if aLimit > High(fArray) then limit := High(fArray)
else limit := aLimit;
SetLength(Result,limit);
for i := Low(fArray) to limit do
begin
Result[i] := fArray[i];
end;
end;
function TLinqArray<T>.Update(const aNewValue: T): Integer;
var
i : Integer;
begin
for i := Low(fArray) to High(fArray) do
begin
if Validate(fArray[i]) then fArray[i] := aNewValue;
end;
end;
function TLinqArray<T>.Validate(aValue: T): Boolean;
var
regEx : TRegEx;
value : TValue;
begin
value := TValue.From<T>(aValue);
if fUseRegEx then
begin
regEx := TRegEx.Create(fMatchString,[roIgnoreCase,roMultiline]);
try
Result := regEx.IsMatch(value.AsString);
except
raise Exception.Create('TLinqArray not valid RegEx!');
end;
end
else
begin
Result := CompareText(fMatchString,value.AsString) = 0;
end;
end;
function TLinqArray<T>.Where(const aMatchString: string; aUseRegEx: Boolean): ILinqArray<T>;
begin
Result := Self;
fMatchString := aMatchString;
fUseRegEx := aUseRegEx;
end;
{ TLinqArray<T>.TLinqComparer }
constructor TLinqArray<T>.TLinqComparer.Create(aSortAscending : Boolean);
begin
fSortAscending := aSortAscending;
end;
function TLinqArray<T>.TLinqComparer.Compare(const L, R: T): Integer;
var
valueL : TValue;
valueR : TValue;
hr : Integer;
lr : Integer;
begin
Result := 0;
if fSortAscending then
begin
hr := 1;
lr := -1;
end
else
begin
hr := -1;
lr := 1;
end;
valueL := TValue.From<T>(L);
valueR := TValue.From<T>(R);
if (valueL.IsEmpty) and (not valueR.IsEmpty) then Exit(hr)
else if (not valueL.IsEmpty) and (valueR.IsEmpty) then Exit(lr);
case valueL.Kind of
{$IFNDEF FPC}
tkString,
{$ENDIF}
tkChar, tkWString, tkUString : Result := CompareText(valueL.AsString, valueR.AsString);
tkInteger, tkInt64 :
begin
if valueL.AsInteger > valueR.AsInteger then Result := hr
else if valueL.AsInteger < valueR.AsInteger then Result := lr;
end;
tkFloat :
begin
if valueL.AsExtended > valueR.AsExtended then Result := hr
else if valueL.AsExtended < valueR.AsExtended then Result := lr;
end;
end;
end;
{ TLinqArrayHelper }
function TLinqArrayHelper.Add(const aValue : string) : Integer;
begin
SetLength(Self,Length(Self)+1);
Self[High(Self)] := aValue;
Result := High(Self);
end;
function TLinqArrayHelper.AddIfNotExists(const aValue : string) : Integer;
var
i : Integer;
begin
for i := Low(Self) to High(Self) do
begin
if CompareText(Self[i],aValue) = 0 then Exit(i);
end;
//if not exists add it
Result := Self.Add(aValue);
end;
function TLinqArrayHelper.Remove(const aValue : string) : Boolean;
var
i : Integer;
begin
for i := Low(Self) to High(Self) do
begin
if CompareText(Self[i],aValue) = 0 then
begin
System.Delete(Self,i,1);
Exit(True);
end;
end;
Result := False;
end;
function TLinqArrayHelper.Any : Boolean;
begin
Result := High(Self) >= 0;
end;
function TLinqArrayHelper.Any(const aValue : string) : Boolean;
var
value : string;
begin
Result := False;
for value in Self do
begin
if CompareText(value,aValue) = 0 then Exit(True)
end;
end;
function TLinqArrayHelper.Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean;
begin
Result := TLinqArray<string>.Create(Self).Any(aMatchString,aUseRegEx);
end;
function TLinqArrayHelper.Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<string>;
begin
Result := TLinqArray<string>.Create(Self).Where(aMatchString,aUseRegEx);
end;
{$ENDIF}
end.
|
unit Accel;
{$BoolEval OFF}
interface
uses
Windows, Messages, Classes, Controls, Forms, TimerUtils, ExtCtrls;
type
EAccelError = class(EOutOfResources);
const
MaxEntryCount = 103*2*2;
const
DefEntryCount = 20;
IncSize = 16;
type
TNotifyCommandProc = procedure(Command : word) of object;
type
PAccelArray = ^TAccelArray;
TAccelArray = array[0..Pred(MaxEntryCount)] of TAccel;
type
TKeyMapper =
class
protected
fActive : boolean;
fAccelArray : PAccelArray;
fEntryCount : integer;
fOnCommand : TNotifyCommandProc;
Count : integer;
public
constructor Create;
destructor Destroy; override;
public
procedure AddAccelerator(aKey : word; aFlags : byte; aCommand : word; aRepeat : boolean); virtual;
procedure DelAccelerator(aKey : word; aFlags : byte); virtual;
procedure Reset; virtual;
public
procedure InitMapping; virtual;
procedure PauseMapping; virtual;
procedure ResumeMapping; virtual;
procedure DoneMapping; virtual;
protected
procedure AllocTable; virtual;
procedure ReallocTable; virtual;
procedure NotifyCommand(aCommand : word); virtual;
protected
procedure SetActive(aActive : boolean); virtual;
function GetAccel(index : integer) : TAccel; virtual;
public
property Active : boolean read fActive write SetActive;
property Accels[index : integer] : TAccel read GetAccel; default;
property EntryCount : integer read fEntryCount;
property OnCommand : TNotifyCommandProc read fOnCommand write fOnCommand;
end;
type
TAccelTable =
class(TKeyMapper)
private
fHandle : HAccel;
fLoaded : boolean;
public
destructor Destroy; override;
protected
procedure AppHookProc(var Msg : TMsg; var Handled : boolean);
function HookProc(var aMsg : TMessage) : boolean;
public
procedure InitMapping; override;
procedure DoneMapping; override;
procedure Reset; override;
public
property Handle : HAccel read fHandle write fHandle;
property Loaded : boolean read fLoaded;
end;
type
TKeyInfo =
record
RepeatIt : boolean;
Pressed : boolean;
Retrace : integer;
end;
type
PKeyInfoArray = ^TKeyInfoArray;
TKeyInfoArray = array[0..Pred(MaxEntryCount)] of TKeyInfo;
type
TTimerKeyMapper =
class(TKeyMapper)
private
fKeysInfo : PKeyInfoArray;
SimTimer : TTimer;
public
constructor Create;
destructor Destroy; override;
public
procedure AddAccelerator(aKey : word; aFlags : byte; aCommand : word; aRepeat : boolean); override;
public
procedure InitMapping; override;
procedure DoneMapping; override;
procedure Reset; override;
procedure AllKeysUp;
protected
procedure AppHookProc(var Msg : TMsg; var Handled : boolean);
function HookProc(var aMsg : TMessage) : boolean;
protected
procedure Timer( Sender : TObject );
function HookKeyDown(Msg : TWMKeyDown) : boolean;
function HookKeyUp(Msg : TWMKeyDown) : boolean;
function VerifyFlags(flags : word) : boolean;
protected
procedure AllocTable; override;
procedure ReallocTable; override;
public
function FirstIndexOf(aKey : word) : integer;
function NextIndexOf(aKey : word; CurrentIndex : integer) : integer;
end;
const
KeyboardRate = 50;
KeyboardRetrace = 3;
implementation
uses
SysUtils;
// TKeyMapper
constructor TKeyMapper.Create;
begin
inherited;
Count := DefEntryCount;
Alloctable;
end;
destructor TKeyMapper.Destroy;
begin
FreeMem(fAccelArray);
inherited;
end;
procedure TKeyMapper.AddAccelerator(aKey : word; aFlags : byte; aCommand : word; aRepeat : boolean);
begin
if EntryCount = Count
then ReallocTable;
with fAccelArray[EntryCount] do
begin
FVirt := aFlags;
Key := aKey;
Cmd := aCommand;
end;
Inc(fEntryCount);
end;
procedure TKeyMapper.DelAccelerator(aKey : word; aFlags : byte);
var
i : integer;
begin
i := 0;
while (i < EntryCount) and ( (aKey <> fAccelArray[i].Key) or (aFlags <> fAccelArray[i].FVirt)) do
inc(i);
if i < EntryCount
then
begin
Dec(fEntryCount);
Move(fAccelArray[Succ(i)], fAccelArray[i], EntryCount - i);
end;
end;
procedure TKeyMapper.Reset;
begin
fEntryCount := 0;
FreeMem(fAccelArray);
Count := DefEntryCount;
AllocTable;
end;
procedure TKeyMapper.InitMapping;
begin
Active := true;
end;
procedure TKeyMapper.PauseMapping;
begin
if Active
then Active := false;
end;
procedure TKeyMapper.ResumeMapping;
begin
if not Active
then Active := true;
end;
procedure TKeyMapper.DoneMapping;
begin
Active := false;
end;
procedure TKeyMapper.AllocTable;
begin
GetMem(fAccelArray, SizeOf(TAccel)*Count);
end;
procedure TKeyMapper.ReallocTable;
begin
Inc(Count, IncSize);
ReallocMem(fAccelArray, Count);
end;
procedure TKeyMapper.NotifyCommand(aCommand : word);
begin
if Active and Assigned(fOncommand)
then fOnCommand(aCommand);
end;
procedure TKeyMapper.SetActive(aActive : boolean);
begin
fActive := aActive;
end;
function TKeyMapper.GetAccel(index : integer) : TAccel;
begin
Assert(((index >=0) and (index < EntryCount)), 'TAccelTable.GetAccel : Index Out of bounds');
Result := fAccelArray[index];
end;
// TAccelTable
destructor TAccelTable.Destroy;
begin
DoneMapping;
inherited;
end;
procedure TAccelTable.InitMapping;
begin
inherited;
Application.OnMessage := AppHookProc;
if (EntryCount > 0) and (not Loaded) and Assigned(fOnCommand)
then
begin
fHandle := CreateAcceleratorTable(fAccelArray^, EntryCount);
if Handle <> 0
then
begin
fLoaded := true;
Application.OnMessage := AppHookProc;
Application.HookMainWindow(HookProc);
end
else raise EAccelError.Create('Could not create accelerator table');
end;
end;
procedure TAccelTable.DoneMapping;
begin
inherited;
if Loaded and not LongBool(DestroyAcceleratorTable(Handle))
then raise EAccelError.Create('Could not destroy accelerator table, Windows error : ' + IntToStr(GetLastError))
else
begin
fLoaded := false;
Application.OnMessage := nil;
Application.UnhookMainWindow(HookProc);
end;
end;
procedure TAccelTable.Reset;
begin
DoneMapping;
fLoaded := false;
inherited;
end;
procedure TAccelTable.AppHookProc(var Msg : TMsg; var Handled : boolean);
begin
if Active
then Handled := longbool (TranslateAccelerator(Application.Handle, Handle, Msg))
else Handled := false;
end;
function TAccelTable.HookProc(var aMsg : TMessage) : boolean;
begin
if aMsg.Msg = WM_COMMAND
then
begin
NotifyCommand(aMsg.wParam);
Result := true;
end
else Result := false;
end;
// TTimerKeyMapper
constructor TTimerKeyMapper.Create;
begin
inherited;
SimTimer := TTimer.Create( nil );
SimTimer.Interval := 50;
SimTimer.OnTimer := Timer;
end;
destructor TTimerKeyMapper.Destroy;
begin
DoneMapping;
SimTimer.Free;
FreeMem(fKeysInfo);
inherited;
end;
procedure TTimerKeyMapper.AddAccelerator(aKey : word; aFlags : byte; aCommand : word; aRepeat : boolean);
begin
inherited;
with fKeysInfo[Pred(EntryCount)] do
begin
RepeatIt := aRepeat;
Pressed := false;
Retrace := 0;
end;
end;
procedure TTimerKeyMapper.InitMapping;
begin
inherited;
Application.OnMessage := AppHookProc;
SimTimer.Enabled := true;
end;
procedure TTimerKeyMapper.DoneMapping;
begin
SimTimer.Enabled := false;
Application.OnMessage := nil;
inherited;
end;
procedure TTimerKeyMapper.Reset;
begin
inherited;
SimTimer.Enabled := false;
FreeMem(fKeysInfo);
GetMem(fKeysInfo, SizeOf(TKeyInfo)*Count);
end;
procedure TTimerKeyMapper.AllKeysUp;
var
i : integer;
begin
for i := 0 to Pred(EntryCount) do
if fKeysInfo[i].Pressed
then fKeysInfo[i].Pressed := false;
end;
procedure TTimerKeyMapper.AppHookProc(var Msg : TMsg; var Handled : boolean);
var
TmpMsg : TMessage;
begin
TmpMsg.Msg := Msg.Message;
TmpMsg.WParam := Msg.WParam;
Handled := HookProc(TmpMsg);
end;
function TTimerKeyMapper.HookProc(var aMsg : TMessage) : boolean;
begin
with aMsg do
case Msg of
WM_KeyDown :
HookProc := HookKeyDown(TWMKeyDown(aMsg));
WM_KeyUp :
HookProc := HookKeyUp(TWMKeyDown(aMsg));
else
HookProc := false;
end;
end;
procedure TTimerKeyMapper.Timer( Sender : TObject );
var
i : integer;
begin
if Active
then
for i := 0 to Pred(EntryCount) do
if fKeysInfo[i].Pressed and fKeysInfo[i].RepeatIt
then
begin
if fKeysInfo[i].Retrace < KeyboardRetrace
then Inc(fKeysInfo[i].Retrace)
else
if VerifyFlags(fAccelArray[i].fVirt)
then NotifyCommand(fAccelArray[i].Cmd);
end;
end;
function TTimerKeyMapper.HookKeyDown(Msg : TWMKeyDown) : boolean;
var
index : integer;
begin
if Active
then
begin
index := FirstIndexOf(Msg.CharCode);
if (index <> -1) and not fKeysInfo[index].Pressed
then
begin
Result := true;
repeat
fKeysInfo[index].Pressed := true;
fKeysInfo[index].Retrace := 0;
if Active and VerifyFlags(fAccelArray[index].fVirt)
then NotifyCommand(fAccelArray[index].Cmd);
index := NextIndexOf(Msg.CharCode, index);
until index = -1;
end
else Result := false;
end
else Result := false;
end;
function TTimerKeyMapper.HookKeyUp(Msg : TWMKeyDown) : boolean;
var
index : integer;
begin
Result := false;
index := FirstIndexOf(Msg.CharCode);
if index <> -1
then
begin
repeat
if fKeysInfo[index].Pressed
then
begin
Result := true;
fKeysInfo[index].Pressed := false;
end;
index := NextIndexOf(Msg.CharCode, index);
until index = -1;
end
end;
function TTimerKeyMapper.VerifyFlags(flags : word) : boolean;
begin
Result := not(wordbool(flags and FCONTROL) xor bytebool(GetKeyState(VK_CONTROL) and 128)) and
not(wordbool(flags and FALT) xor bytebool(GetKeyState(VK_MENU) and 128)) and
not(wordbool(flags and FSHIFT) xor bytebool(GetKeyState(VK_SHIFT) and 128));
end;
procedure TTimerKeyMapper.AllocTable;
begin
inherited;
GetMem(fKeysInfo, SizeOf(TKeyInfo)*Count);
end;
procedure TTimerKeyMapper.ReallocTable;
begin
inherited;
ReallocMem(fKeysInfo, SizeOf(TKeyInfo)*Count);
end;
function TTimerKeyMapper.FirstIndexOf(aKey : word) : integer;
begin
Result := NextIndexOf(aKey, -1);
end;
function TTimerKeyMapper.NextIndexOf(aKey : word; CurrentIndex : integer) : integer;
var
i : integer;
begin
i := Succ(CurrentIndex);
while (i < EntryCount) and (fAccelArray[i].key <> aKey) do
inc(i);
if i < EntryCount
then Result := i
else Result := -1;
end;
end.
|
unit UCliente;
interface
uses UEndereco, System.Generics.Collections, System.sysutils;
type
TCliente = class
private
FNome: String;
FEmail: String;
FCPF: String;
FIdentidade: String;
FEndereco: TList<TEndereco>;
FTelefone: String;
FID: integer;
procedure SetNome(const Value: String);
procedure SetCPF(const Value: String);
procedure SetEmail(const Value: String);
procedure SetEndereco(const Value: TList<TEndereco>);
procedure SetIdentidade(const Value: String);
procedure SetTelefone(const Value: String);
procedure SetID(const Value: integer);
public
constructor Create;
destructor Destroy; override;
property ID:integer read FID write SetID;
property Nome: String read FNome write SetNome;
property Identidade: String read FIdentidade write SetIdentidade;
property CPF: String read FCPF write SetCPF;
property Telefone: String read FTelefone write SetTelefone;
property Email: String read FEmail write SetEmail;
property Endereco: TList<TEndereco> read FEndereco write SetEndereco;
end;
implementation
{ TCliente }
constructor TCliente.Create;
begin
FEmail := '';
FCPF := '';
FId := 0;
FIdentidade := '';
FNome := '';
FTelefone := '';
FEndereco := TList<TEndereco>.Create;
end;
destructor TCliente.Destroy;
begin
FEndereco.Free;
inherited;
end;
procedure TCliente.SetCPF(const Value: String);
begin
FCPF := Value;
end;
procedure TCliente.SetEmail(const Value: String);
begin
FEmail := Value;
end;
procedure TCliente.SetEndereco(const Value: TList<TEndereco>);
begin
FEndereco := Value;
end;
procedure TCliente.SetID(const Value: integer);
begin
FID := Value;
end;
procedure TCliente.SetIdentidade(const Value: String);
begin
FIdentidade := Value;
end;
procedure TCliente.SetNome(const Value: String);
begin
FNome := Value;
if Value.Equals(EmptyStr) then
raise Exception.Create('Nome do Cliente não pode ser branco.');
end;
procedure TCliente.SetTelefone(const Value: String);
begin
FTelefone := Value;
end;
end.
|
unit uVersaoSistema;
interface
uses System.SysUtils, Vcl.Forms, uDM, FireDAC.Stan.Param, Data.DB,
FireDAC.Comp.Client, uFormVersao;
type
TVersaoSistema = class
private
procedure ExecutarSQL(LinhaComando: string);
function RetornaVersao: Integer;
function SoNumeros(Valor: string): string;
function RetornaVersaoAquivo(LinhaComando: string): Integer;
procedure AtualizaVersao(versao: Integer);
public
procedure LerVersao;
end;
implementation
{ TVersaoSistema }
procedure TVersaoSistema.AtualizaVersao(versao: Integer);
var
sql: TFDQuery;
sVersao: string;
numero1: string;
numero2: string;
numero3: string;
begin
versao := versao + 1;
sVersao := IntToStr(versao);
numero1 := Copy(sVersao, 1,1);
numero2 := Copy(sVersao, 2,3);
numero3 := Copy(sVersao, 5,2);
sVersao := numero1 + '.' + numero2 + '.' + numero3;
sql := TFDQuery.Create(nil);
try
sql.Connection := dm.Conexao;
sql.SQL.Text := 'UPDATE Parametros SET Par_Valor = :Valor WHERE Par_Codigo = :Codigo';
sql.Params[0].AsString := sVersao;
sql.Params[1].AsInteger := 11;
sql.ExecSQL();
finally
FreeAndNil(sql);
end;
end;
procedure TVersaoSistema.ExecutarSQL(LinhaComando: string);
var
sql: TFDQuery;
begin
sql := TFDQuery.Create(nil);
try
sql.Connection := dm.Conexao;
sql.SQL.Text := LinhaComando;
sql.ExecSQL();
finally
FreeAndNil(sql);
end;
end;
procedure TVersaoSistema.LerVersao;
var
Arquivo: string;
Arq: TextFile;
Registro: string;
VersaoAtual: Integer;
VersaoArquivo: Integer;
flag: Boolean;
InstrucaoSQL: TStringBuilder;
begin
Arquivo := ExtractFilePath(Application.ExeName) + '\DomperVersao.sql';
AssignFile(Arq, Arquivo);
Reset(Arq);
flag := True;
VersaoAtual := RetornaVersao();
InstrucaoSQL := TStringBuilder.Create;
try
if VersaoAtual = 100000 then
Exit;
while not Eof(Arq) do
begin
Readln(Arq, Registro);
if Trim(Registro) = '' then
Continue;
if flag then
VersaoArquivo := RetornaVersaoAquivo(Registro);
if VersaoArquivo <= VersaoAtual then
Continue;
if flag then
flag := False;
if Trim(Registro.ToUpper) <> 'GO' then
begin
InstrucaoSQL.AppendLine(Registro);
frmVersao.mmScript.Lines.Add(Registro);
end;
if Trim(Registro.ToUpper) = 'GO' then
begin
ExecutarSQL(InstrucaoSQL.ToString);
InstrucaoSQL.Clear;
frmVersao.mmScript.Clear;
end;
end;
if flag = False then
begin
AtualizaVersao(VersaoAtual);
end;
finally
CloseFile(Arq);
FreeAndNil(InstrucaoSQL);
end;
end;
function TVersaoSistema.RetornaVersao: Integer;
var
sql: TFDQuery;
iValor: Integer;
begin
sql := TFDQuery.Create(nil);
try
sql.Connection := dm.Conexao;
sql.SQL.Text := 'SELECT Par_Valor FROM Parametros WHERE Par_Codigo = 11';
sql.Open();
iValor := StrToIntDef(SoNumeros(sql.Fields[0].AsString),0);
if iValor = 0 then
Result := 100000
else
Result := iValor;
finally
FreeAndNil(sql);
end;
end;
function TVersaoSistema.RetornaVersaoAquivo(LinhaComando: string): Integer;
var
sLinha: string;
sVersao: string;
begin
sLinha := Copy(LinhaComando, 1, 8);
if sLinha = '--VERSAO' then
begin
sVersao := Trim(Copy(LinhaComando, 10, 20));
Result := StrToInt(SoNumeros(sVersao));
end
else
Result := 0;
end;
function TVersaoSistema.SoNumeros(Valor: string): string;
var
sql: TFDQuery;
begin
sql := TFDQuery.Create(nil);
try
sql.Connection := dm.Conexao;
sql.SQL.Text := 'SELECT dbo.SoNumeros(:Valor)';
sql.Params[0].AsString := Valor;
sql.Open();
Result := sql.Fields[0].AsString;
finally
FreeAndNil(sql);
end;
end;
end.
|
unit ActiveHandleException;
interface
uses
Vcl.Forms, System.SysUtils, System.Classes, Vcl.dialogs;
type
TActiveHandleException = class
private
FLogFile: String;
procedure AppException(Sender: System.TObject; E: Exception);
public
constructor Create;
end;
implementation
procedure TActiveHandleException.AppException(Sender: System.TObject;
E: Exception);
var
Log: TextFile;
begin
{$I-}
AssignFile(Log, FLogFile);
if FileExists(FLogFile) then
begin
Append(Log);
end
else
begin
Rewrite(Log);
end;
try
Writeln(Log, 'Exception ocorrida em ' + FormatDateTime('dd" de "mmm" de "yyyy" ās "hh:mm:ss',Now));
Writeln(Log, '----------------------------------------');
if TComponent(Sender) is TForm then
begin
Writeln(Log, 'Form.................: ' + TForm(Sender).Name);
Writeln(Log, 'Caption do Form......: ' + TForm(Sender).Caption);
end
else
begin
Writeln(Log, 'Form.................: ' + TForm(TComponent(Sender).Owner).Name);
Writeln(Log, 'Caption do Form......: ' + TForm(TComponent(Sender).Owner).Caption);
end;
Writeln(Log, '----------------------------------------');
Writeln(Log, 'Classe da Exception..: ' + E.ClassName);
Writeln(Log, 'Mensagem de Exception: ' + E.Message);
Writeln(Log, '');
MessageDlg(E.Message, mtError, [mbOK], 0);
finally
CloseFile(Log);
end;
{$I+}
end;
constructor TActiveHandleException.Create;
begin
inherited Create;
Application.OnException := AppException;
FLogFile := ChangeFileExt(Paramstr(0), '.log');
end;
var
ActiveException: TActiveHandleException;
Initialization
ActiveException := TActiveHandleException.Create;
Finalization
ActiveException.Free;
end.
|
unit Pedidos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait,
FireDAC.Comp.Client, Data.DB, Data.DBXMySQL, Data.SqlExpr, Data.FMTBcd,
Vcl.Grids, Vcl.DBGrids, Vcl.Buttons, oPedido, System.UITypes;
type
TfrmPedidos = class(TForm)
Label1: TLabel;
edtCodigoCliente: TLabeledEdit;
edtCodigoProduto: TLabeledEdit;
edtQuantidade: TLabeledEdit;
edtValorUnitario: TLabeledEdit;
dsItensPedido: TDataSource;
DBGrid1: TDBGrid;
Label2: TLabel;
btnInsereProduto: TBitBtn;
btnGravar: TBitBtn;
btnCarregaPedido: TBitBtn;
btnCancelarPedido: TBitBtn;
lblNomeCliente: TLabel;
lblTotal: TLabel;
Label3: TLabel;
lblNumPedido: TLabel;
procedure edtValorUnitarioKeyPress(Sender: TObject; var Key: Char);
procedure btnInsereProdutoClick(Sender: TObject);
procedure edtCodigoClienteExit(Sender: TObject);
procedure edtCodigoClienteChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarPedidoClick(Sender: TObject);
procedure btnCarregaPedidoClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure DBGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
procedure Reset;
procedure ExcluirItemProduto;
public
{ Public declarations }
objPedido: TPedido;
end;
var
frmPedidos: TfrmPedidos;
implementation
uses
DataModule, AlteraProduto;
{$R *.dfm}
procedure TfrmPedidos.btnCancelarPedidoClick(Sender: TObject);
var
numPedido: String;
begin
if not InputQuery('Cancelamento de Pedido', 'Número do Pedido', numPedido) then
Exit;
with dmWKTeste.qryAux.SQL do
begin
Clear;
Add('SELECT numeroPedido FROM pedidosdadosgerais');
Add('WHERE numeroPedido = ' + numPedido);
end;
try
dmWKTeste.qryAux.Open();
if dmWKTeste.qryAux.IsEmpty then
begin
ShowMessage('Pedido numero ' + numPedido + ' não foi localizado.');
Exit;
end;
finally
dmWKTeste.qryAux.Close;
end;
if MessageDlg('Deseja cancelar o Pedido ' + numPedido + '?', mtConfirmation, [mbYES, mbNO], 0) <> mrYes then
Exit;
dmWKTeste.FDConnection1.StartTransaction;
try
dmWKTeste.FDConnection1.ExecSQL('DELETE FROM pedidosprodutos WHERE numeroPedido = ' + numPedido);
dmWKTeste.FDConnection1.ExecSQL('DELETE FROM pedidosdadosgerais WHERE numeroPedido = ' + numPedido);
dmWKTeste.FDConnection1.Commit;
ShowMessage('Pedido número ' + numPedido + ' foi cancelado.');
except
on E: Exception do
begin
dmWKTeste.FDConnection1.Rollback;
ShowMessage('Erro ao gravar os dados: ' + E.Message);
end;
end;
end;
procedure TfrmPedidos.btnCarregaPedidoClick(Sender: TObject);
var
numPedido: String;
begin
if not InputQuery('Carregar Pedido', 'Número do Pedido', numPedido) then
Exit;
with dmWKTeste.qryAux.SQL do
begin
Clear;
Add('SELECT numeroPedido, codigoCliente, valorTotal');
Add(', clientes.nome');
Add('FROM pedidosdadosgerais');
Add('INNER JOIN clientes ON clientes.codigo = pedidosdadosgerais.codigoCliente');
Add('WHERE numeroPedido = ' + numPedido);
end;
try
dmWKTeste.qryAux.Open();
if dmWKTeste.qryAux.IsEmpty then
begin
ShowMessage('Pedido numero ' + numPedido + ' não foi localizado.');
Exit;
end;
lblNumPedido.Caption := dmWKTeste.qryAux.FieldByName('numeroPedido').AsString;
objPedido.Cliente := dmWKTeste.qryAux.FieldByName('codigoCliente').AsInteger;
objPedido.Total := dmWKTeste.qryAux.FieldByName('valorTotal').AsFloat;
edtCodigoCliente.Text := dmWKTeste.qryAux.FieldByName('codigoCliente').AsString;
lblTotal.Caption := FormatFloat('#,##0.00', dmWKTeste.qryAux.FieldByName('valorTotal').AsFloat);
lblNomeCliente.Caption := dmWKTeste.qryAux.FieldByName('nome').AsString;
dmWKTeste.tblItensPedido.EmptyDataSet;
dmWKTeste.qryAux.Close;
with dmWKTeste.qryAux.SQL do
begin
Clear;
Add('SELECT quantidade, valorUnitario, valorTotal, codigoProduto');
Add(', produtos.descricao');
Add('FROM pedidosprodutos');
Add('INNER JOIN produtos ON produtos.codigo = pedidosprodutos.codigoProduto');
Add('WHERE numeroPedido = ' + numPedido);
end;
dmWKTeste.qryAux.Open();
while not dmWKTeste.qryAux.Eof do
begin
dmWKTeste.tblItensPedido.Append;
dmWKTeste.tblItensPedido.FieldByName('codigoProduto').AsInteger := dmWKTeste.qryAux.FieldByName('codigoProduto').AsInteger;
dmWKTeste.tblItensPedido.FieldByName('descricaoProduto').AsString := dmWKTeste.qryAux.FieldByName('descricao').AsString;
dmWKTeste.tblItensPedido.FieldByName('vlrUnitario').AsCurrency := dmWKTeste.qryAux.FieldByName('valorUnitario').AsCurrency;
dmWKTeste.tblItensPedido.FieldByName('quantidade').AsFloat := dmWKTeste.qryAux.FieldByName('quantidade').AsFloat;
dmWKTeste.tblItensPedido.Post;
dmWKTeste.qryAux.Next;
end;
finally
dmWKTeste.qryAux.Close;
edtCodigoCliente.SetFocus;
end;
end;
procedure TfrmPedidos.btnGravarClick(Sender: TObject);
var
numPedido: Integer;
sSQL: String;
format: TFormatSettings;
begin
if not dmWKTeste.FDConnection1.Connected then
Exit;
if dmWKTeste.tblItensPedido.RecordCount = 0 then
begin
edtCodigoProduto.SetFocus;
ShowMessage('Nenhum produto incluido');
Exit;
end;
// Cliente não selecionado ...
if objPedido.Cliente < 1 then
begin
edtCodigoCliente.SetFocus;
ShowMessage('Cliente não selecionado');
Exit;
end;
format.DecimalSeparator := '.';
format.ThousandSeparator := #0;
with dmWKTeste do
begin
with qryAux.SQL do
begin
Clear;
Add('SELECT ifnull(max(numeroPedido) + 1, 1) AS id FROM pedidosdadosgerais');
end;
qryAux.Open();
numPedido := qryAux.FieldByName('id').AsInteger;
qryAux.Close;
lblNumPedido.Caption := IntToStr(numPedido);
FDConnection1.StartTransaction;
try
sSQL :=
'INSERT INTO pedidosdadosgerais (dataEmissao, numeroPedido, valorTotal, codigoCliente) ' +
'VALUES (NOW(), ' +
IntToStr(numPedido) + ', ' +
FloatToStr(objPedido.Total, format) + ', ' +
IntToStr(objPedido.Cliente) + ')';
FDConnection1.ExecSQL(sSQL);
tblItensPedido.First;
while not tblItensPedido.Eof do
begin
FDConnection1.ExecSQL('INSERT INTO pedidosprodutos ' +
'(numeroPedido, quantidade, valorUnitario, valorTotal, codigoProduto) VALUES (' +
IntToStr(numPedido) + ', ' +
tblItensPedido.FieldByName('quantidade').AsString + ', ' +
FloatToStr(tblItensPedido.FieldByName('vlrUnitario').AsFloat, format) + ', ' +
FloatToStr(tblItensPedido.FieldByName('vlrTotal').AsFloat, format) + ', ' +
tblItensPedido.FieldByName('codigoProduto').AsString + ')');
tblItensPedido.Next;
end;
FDConnection1.Commit;
ShowMessage('Pedido gravado com sucesso!');
edtCodigoCliente.SetFocus;
except
on E: Exception do
begin
FDConnection1.Rollback;
ShowMessage('Erro ao gravar os dados: ' + E.Message);
end;
end;
end;
end;
procedure TfrmPedidos.btnInsereProdutoClick(Sender: TObject);
var
fQtd,
fVlrUnit: Double;
begin
if not dmWKTeste.FDConnection1.Connected then
Exit;
if edtCodigoProduto.Text = '' then
Exit;
// Cliente não selecionado ...
if objPedido.Cliente < 1 then
begin
edtCodigoCliente.SetFocus;
ShowMessage('Cliente não selecionado');
Exit;
end;
with dmWKTeste.qryAux.SQL do
begin
Clear;
Add('SELECT codigo, descricao, precoVenda FROM produtos');
Add('WHERE codigo = ' + edtCodigoProduto.Text);
end;
try
with dmWKTeste do
begin
qryAux.Open();
if edtQuantidade.Text = '' then
fQtd := 1
else
fQtd := StrToFloat(edtQuantidade.Text);
if edtValorUnitario.Text = '' then
fVlrUnit := qryAux.FieldByName('precoVenda').AsCurrency
else
fVlrUnit := StrToFloat(edtValorUnitario.Text);
if qryAux.IsEmpty then
begin
ShowMessage('Produto código ' + edtCodigoProduto.Text + ' não foi localizado.');
Exit;
end;
tblItensPedido.Append;
tblItensPedido.FieldByName('codigoProduto').AsInteger := qryAux.FieldByName('codigo').AsInteger;
// A descrição do produto é carregada no evento onChange do campo 'codigoProduto'
tblItensPedido.FieldByName('vlrUnitario').AsCurrency := fVlrUnit;
tblItensPedido.FieldByName('quantidade').AsFloat := fQtd;
tblItensPedido.Post;
objPedido.Soma(tblItensPedido.FieldByName('vlrTotal').AsFloat);
end;
edtCodigoProduto.Clear;
edtQuantidade.Clear;
edtValorUnitario.Clear;
edtCodigoProduto.SetFocus;
finally
dmWKTeste.qryAux.Close;
end;
end;
procedure TfrmPedidos.DBGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_DELETE) then
ExcluirItemProduto
else if (Key = VK_RETURN) then
begin
try
objPedido.Subtrai(dmWKTeste.tblItensPedido.FieldByName('vlrTotal').AsFloat);
Application.CreateForm(TfrmAlteraProduto, frmAlteraProduto);
frmAlteraProduto.ShowModal;
objPedido.Soma(dmWKTeste.tblItensPedido.FieldByName('vlrTotal').AsFloat);
finally
FreeAndNil(frmAlteraProduto);
end;
end;
end;
procedure TfrmPedidos.edtCodigoClienteChange(Sender: TObject);
begin
btnCarregaPedido.Visible := (edtCodigoCliente.Text = '');
btnCancelarPedido.Visible := (edtCodigoCliente.Text = '');
end;
procedure TfrmPedidos.edtCodigoClienteExit(Sender: TObject);
begin
Reset;
if not dmWKTeste.FDConnection1.Connected then
Exit;
if edtCodigoCliente.Text = '' then
Exit;
with dmWKTeste.qryAux.SQL do
begin
Clear;
Add('SELECT codigo, nome FROM clientes');
Add('WHERE codigo = ' + edtCodigoCliente.Text);
end;
try
with dmWKTeste do
begin
qryAux.Open();
if qryAux.IsEmpty then
begin
ShowMessage('Cliente código ' + edtCodigoCliente.Text + ' não foi localizado.');
Exit;
end;
// Inicia um novo Pedido ...
objPedido.Cliente := qryAux.FieldByName('codigo').AsInteger;
lblNomeCliente.Caption := qryAux.FieldByName('nome').AsString;
end;
finally
dmWKTeste.qryAux.Close;
end;
end;
procedure TfrmPedidos.edtValorUnitarioKeyPress(Sender: TObject; var Key: Char);
var
sText: String;
begin
sText := (Sender as TLabeledEdit).Text;
if not (Key in ['0'..'9', #8]) then
begin
if (Key = '.') and (Pos(',', sText) = 0) then
Key := ','
else if (Key = ',') and (Pos(',', sText) = 0) then
Key := ','
else
key := #0;
end;
end;
procedure TfrmPedidos.FormCreate(Sender: TObject);
begin
objPedido := TPedido.Create(lblTotal);
end;
procedure TfrmPedidos.FormShow(Sender: TObject);
begin
Reset;
edtCodigoCliente.SetFocus;
end;
procedure TfrmPedidos.Reset;
begin
lblNomeCliente.Caption := '';
objPedido.Cliente := 0;
objPedido.Total := 0;
dmWKTeste.tblItensPedido.EmptyDataSet;
lblTotal.Caption := '0';
lblNumPedido.Caption := '---';
edtCodigoProduto.Clear;
edtQuantidade.Clear;
edtValorUnitario.Clear;
end;
procedure TfrmPedidos.ExcluirItemProduto;
begin
if MessageDlg('Deseja excluir este produto?', mtConfirmation, [mbYES, mbNO], 0) <> mrYes then
Exit;
objPedido.Subtrai(dmWKTeste.tblItensPedido.FieldByName('vlrTotal').AsFloat);
dmWKTeste.tblItensPedido.Delete;
end;
end.
|
/// Miscellaneous utilities
unit tmsUFlxUtils;
{$INCLUDE ..\FLXCOMPILER.INC}
interface
uses tmsUExcelAdapter, tmsUFlxMessages, SysUtils, tmsXlsMessages, Graphics;
//------------------------------------------------------------------------//
/// <summary>
/// \Returns the most similar entry on the excel palette for a given color.
/// </summary>
/// <remarks>
/// <b>You will normally want to use <see cref="TFlexCelImport.NearestColorIndex@TColor@BooleanArray" text="TFlexCelImport.NearestColorIndex" />
/// instead of this method.</b><para></para>
/// <para></para>
/// If UsedColors is not nil, it will try to modify the Excel color palette to get a better match on the
/// color, modifying among the not used colors. Note that modifying the standard palette might result on
/// a file that is not easy to edit on Excel later, since it does not have the standard Excel colors.
/// </remarks>
/// <param name="Workbook">Excel file where you want to get the color.</param>
/// <param name="aColor">Color for which you want to find the nearest one.</param>
/// <param name="UsedColors">A list of used colors.</param>
/// <returns>
/// The color that is nearest to the one specified in aColor.
/// </returns>
function MatchNearestColor(const Workbook: TExcelFile; const aColor: TColor;
const UsedColors: BooleanArray): integer;
/// <summary>
/// Calculates the needed parameters to place an image in Excel given its dimensions in pixels.
/// </summary>
/// <remarks>
/// Normally you don't need to call this method directly, since TFlexCelImport has overload for the
/// methods that accept image dimensions in pixels and internally use this method to enter the image in
/// Excel.<para></para>
/// Use CalcImgDimensions to make the inverse convert, from Excel units to pixels.
/// </remarks>
/// <param name="Workbook">Workbook where you are going to place the image. FlexCel needs this
/// value so it can know the height of rows and width of columns, so it
/// can calculate how many rows and columns the image needs.</param>
/// <param name="Row">Row where you are going to place the image.</param>
/// <param name="Col">Column where you are going to place the image.</param>
/// <param name="dh">Offset from the top of the row for the image. (1/255 of a cell. 0
/// means totally at the top, 128 on half of the cell, 255 means at the
/// top of next cell.)</param>
/// <param name="dw">Offset from the left of the cell for the image. (1/255 of a cell. 0
/// means totally at the top, 128 on half of the cell, 255 means at the
/// top of next cell.)</param>
/// <param name="ImgHeightInPixels">Height you want for the image to have in pixels.</param>
/// <param name="ImgWidthInPixels">Width you want for the image to have in pixels.</param>
/// <param name="Props">\Returns the column and rows where the image will be placed.</param>
procedure CalcImgCells(const Workbook: TExcelFile; const Row, Col, dh, dw:integer; const ImgHeightInPixels, ImgWidthInPixels: extended; out Props: TImageProperties);
/// <summary>
/// Calculates the image dimensions in pixels given an Excel anchor.
/// </summary>
/// <remarks>
/// This method is the reverse of CalcImgCells, and it gives you a way to calculate the width and height
/// of an image in pixels.<para></para>
/// <para></para>
/// There are two very similar overloads for this method, one returns the pixels as integers, the other
/// as floating numbers. Even when pixels are integer numbers, the floating point version might be good
/// if you are manipulating the magnitudes (for example adding them), to avoid rounding errors. You can
/// round to pixels at the end of the operations, not on each step.
/// </remarks>
/// <param name="Workbook">\File where the image is located.</param>
/// <param name="Anchor">Excel anchor indicating the columns and rows where the image is located.</param>
/// <param name="w">\Returns the width in pixels for the image</param>
/// <param name="h">\Returns the height in pixels from the image.</param>
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out w, h: integer);overload;
/// <summary>
/// Calculates the image dimensions in pixels given an Excel anchor.
/// </summary>
/// <remarks>
/// This method is the reverse of CalcImgCells, and it gives you a way to calculate the width and height
/// of an image in pixels.<para></para>
/// <para></para>
/// There are two very similar overloads for this method, one returns the pixels as integers, the other
/// as floating numbers. Even when pixels are integer numbers, the floating point version might be good
/// if you are manipulating the magnitudes (for example adding them), to avoid rounding errors. You can
/// round to pixels at the end of the operations, not on each step.
/// </remarks>
/// <param name="Workbook">\File where the image is located.</param>
/// <param name="Anchor">Excel anchor indicating the columns and rows where the image is located.</param>
/// <param name="w">\Returns the width in pixels for the image</param>
/// <param name="h">\Returns the height in pixels from the image.</param>
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out w, h: extended); overload;
/// <summary>
/// Calculates the image dimensions in pixels given an Excel anchor.
/// </summary>
/// <remarks>
/// This method is the reverse of CalcImgCells, and it gives you a way to calculate the width and height
/// of an image in pixels.
/// </remarks>
/// <param name="Workbook">\File where the image is located.</param>
/// <param name="Anchor">Excel anchor indicating the columns and rows where the image is located.</param>
/// <param name="XOfsPixel">\Returns how many pixels the image is offset from the left of the cell.</param>
/// <param name="YOfsPixel">\Returns how many pixels the image is offset from the top of the cell.</param>
/// <param name="w">\Returns the width in pixels for the image</param>
/// <param name="h">\Returns the height in pixels from the image.</param>
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out XOfsPixel, YOfsPixel, w, h: extended); overload;
//-------------------------------------------------------------------------//
implementation
function MatchNearestColor(const Workbook: TExcelFile; const aColor: TColor;
const UsedColors: BooleanArray): integer;
type
TCb= array[0..3] of byte;
var
i: integer;
sq, MinSq: extended;
ac1, ac2: TCb;
Result2: integer;
begin
Result:=1;
MinSq:=-1;
ac1:=TCb(ColorToRgb(aColor));
for i:=1 to 55 do
begin
ac2:=TCb(Workbook.ColorPalette[i]);
sq := Sqr(ac2[0] - ac1[0]) +
Sqr(ac2[1] - ac1[1]) +
Sqr(ac2[2] - ac1[2]);
if (MinSq<0) or (sq< MinSq) then
begin
MinSq:=sq;
Result:=i;
if sq=0 then
begin
if (UsedColors <> nil) then UsedColors[Result] := true;
exit; //exact match...
end
end;
end;
if (UsedColors = nil) then exit;
//Find the nearest color between the ones that are not in use.
UsedColors[0] := true; //not really used
UsedColors[1] := true; //pure black
UsedColors[2] := true; //pure white
Result2:=-1;
MinSq:=-1;
for i:=1 to 55 do
begin
if (Length(UsedColors) <= i) or UsedColors[i] then continue;
ac2:=TCb(Workbook.ColorPalette[i]);
sq := Sqr(ac2[0] - ac1[0]) +
Sqr(ac2[1] - ac1[1]) +
Sqr(ac2[2] - ac1[2]);
if (MinSq<0) or (sq< MinSq) then
begin
MinSq:=sq;
Result2:=i;
if sq=0 then
begin
Result := Result2;
if (UsedColors <> nil) then UsedColors[Result] := true;
exit; //exact match...
end;
end;
end;
if (Result2 < 0) or (Result2 >= Length(UsedColors)) then
begin
if (UsedColors <> nil) then UsedColors[Result] := true;
exit; //Not available colors to modify
end;
Workbook.ColorPalette[Result2] := ColorToRGB(aColor);
UsedColors[Result2] := true;
Result:= Result2;
end;
//----------------------------------------------------------------------
procedure CalcImgCells(const Workbook: TExcelFile; const Row, Col, dh, dw:integer; const ImgHeightInPixels, ImgWidthInPixels: extended; out Props: TImageProperties);
function Rh(const Row: integer): extended;
begin
if not Workbook.IsEmptyRow(Row) then Result:=Workbook.RowHeightHiddenIsZero[Row]/RowMult else
Result:=Workbook.DefaultRowHeight/RowMult;
end;
function Cw(const Col: integer): extended;
begin
Result:=Workbook.ColumnWidthHiddenIsZero[Col]/ColMult;
end;
var
r, c : integer;
h, w: extended;
Row1, Col1: integer;
dx1, dy1: extended;
EmptyProps: TImageProperties;
begin
if Workbook=nil then raise Exception.Create(ErrNoOpenFile);
FillChar(EmptyProps, SizeOf(EmptyProps), 0); //Just to make sure all record is empty. We can fillchar because strings are initialized to nil in local variables.
Props := EmptyProps;
Row1:=Row; Col1:=Col; dx1:=dw; dy1:=dh;
//If delta spawns more than one cell, advance the cells.
while dx1>Cw(Col1) do
begin
dx1:=dx1- Cw(Col1);
inc(Col1);
end;
while dy1>Rh(Row1) do
begin
dy1:=dy1- Rh(Row1);
inc(Row1);
end;
if Row1<1 then begin Row1:=1;dy1:=0;end;
if Col1<1 then begin Col1:=1;dx1:=0;end;
Props.Row1:=Row1;
Props.Col1:=Col1;
Props.dx1:=Round(1024*dx1/Cw(Col1));
Props.dy1:=Round(255*dy1/Rh(Row1));
r:=Row1; h:=Rh(Row1)-dy1;
while Round(h)<ImgHeightInPixels do
begin
inc(r);
h:=h+ Rh(r);
end;
Props.Row2:=r;
Props.dy2:=Round((Rh(r)-(h-ImgHeightInPixels))/Rh(r)*255);
c:=Col1; w:=Cw(Col1)-dx1;
while Round(w)<ImgWidthInPixels do
begin
inc(c);
w:=w+Cw(c);
end;
Props.Col2:=c;
Props.dx2:=Round((Cw(c)-(w-ImgWidthInPixels))/Cw(c)*1024);
if Props.Row2>Max_Rows+1 then
begin
Props.Row1:=Max_Rows+1-(Props.Row2-Props.Row1);
Props.Row2:=Max_Rows+1;
end;
if Props.Col2>Max_Columns+1 then
begin
Props.Col1:=Max_Columns+1-(Props.Col2-Props.Col1);
Props.Col2:=Max_Columns+1;
end;
//Just in case of an image bigger than the spreadsheet...
if Props.Col1<1 then Props.Col1:=1;
if Props.Row1<1 then Props.Row1:=1;
end;
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out XOfsPixel, YOfsPixel, w, h: extended);overload;
function Rh(const Row: integer): extended;
begin
if not Workbook.IsEmptyRow(Row) then Result:=Workbook.RowHeightHiddenIsZero[Row]/RowMult else
Result:=Workbook.DefaultRowHeight/RowMult;
end;
function Cw(const Col: integer): extended;
begin
Result:=Workbook.ColumnWidthHiddenIsZero[Col]/ColMult;
end;
var
i: integer;
begin
w:=0;
for i:=Anchor.Col1 to Anchor.Col2-1 do w:=w+ Cw(i);
XOfsPixel := (Cw(Anchor.Col1)*(Anchor.Dx1)/1024);
w:=w - XOfsPixel;
w:=w +(Cw(Anchor.Col2)*(Anchor.Dx2)/1024);
h:=0;
for i:=Anchor.Row1 to Anchor.Row2-1 do h:=h+ Rh(i);
YOfsPixel := (Rh(Anchor.Row1)*(Anchor.Dy1)/255);
h:=h - YOfsPixel;
h:=h + (Rh(Anchor.Row2)*(Anchor.Dy2)/255);
end;
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out w, h: integer);overload;
var
w1, h1: extended;
begin
CalcImgDimentions(Workbook,Anchor,w1, h1);
w:=Round(w1);
h:=Round(h1);
end;
procedure CalcImgDimentions(const Workbook: TExcelFile; const Anchor: TClientAnchor; out w, h: extended);overload;
var
w1, h1: extended;
XOfsPixel, YOfsPixel: extended;
begin
CalcImgDimentions(Workbook,Anchor, XOfsPixel, YOfsPixel, w1, h1);
w:=Round(w1);
h:=Round(h1);
end;
end.
|
// generates formatted Pascal code from a token collection
// Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html)
// Contributors: Thomas Mueller (http://www.dummzeuch.de)
// Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features
unit GX_CodeFormatterFormatter;
{$I GX_CondDefine.inc}
interface
uses
SysUtils,
Classes,
GX_GenericUtils,
GX_CodeFormatterTypes,
GX_CodeFormatterStack,
GX_CodeFormatterTokens,
GX_CodeFormatterTokenList,
GX_CodeFormatterSettings;
type
TCodeFormatterFormatter = class
private
FSettings: TCodeFormatterSettings;
FTokens: TPascalTokenList;
FTokenIdx: Integer;
FPrevToken: TPascalToken;
FCurrentToken: TPascalToken;
FCurrentRType: TReservedType;
FPrevLine: TLineFeed;
FPrevPrevLine: TLineFeed;
FHasAligned: Boolean;
// the StackStack is used to preserve indenting over IFDEF/ELSE/ENDIF statments
FStackStack: TCodeFormatterStack;
FStack: TCodeFormatterSegment;
FLastPopResType: TReservedType;
// True between 'interface' and 'implementation'
FIsInInterfacePart: Boolean;
FWrapIndent: Boolean;
// stores WrapIndent from before an opening bracket until the closing one
FOldWrapIndent: Boolean;
procedure UppercaseCompilerDirective(_Token: TPascalToken);
function NoBeginTryIndent(_rType: TReservedType): Boolean;
procedure SetPrevLineIndent(_Additional: Integer);
procedure DecPrevLineIndent;
{: replaces a TExpression with a TAlignExpression }
function AlignExpression(_Idx: Integer; _Pos: Integer): TPascalToken;
procedure CheckWrapping;
function PrevTokenIsRType(_rType: TReservedType): Boolean;
procedure CheckBlankLinesAroundProc;
procedure PutCommentBefore(const _Comment: TGXUnicodeString);
procedure FormatAsm(_NTmp: Integer);
procedure AdjustSpacing(_CurrentToken, _PrevToken: TPascalToken; _TokenIdx: Integer);
{: return token with index Idx or nil if out of bounds }
function GetToken(_Idx: Integer): TPascalToken; overload;
{: get token with index Idx, returns False if index is out of bounds }
function GetToken(_Idx: Integer; out _Token: TPascalToken): Boolean; overload;
{: Check whether the token at index Idx has the reserved type RType
@param Idx is the index of the token to check
@param RType is the queried reserverd type
@returns true, if the token has the queried type, false otherwise }
function TokenAtIs(_Idx: Integer; _rType: TReservedType): Boolean;
function GetNextNoComment(_StartPos: Integer; out _Offset: Integer): TPascalToken; overload;
function GetNextNoComment(_StartPos: Integer; out _Token: TPascalToken; out _Offset: Integer): Boolean; overload;
function GetNextNoComment(_StartPos: Integer; out _Token: TPascalToken): Boolean; overload;
function InsertBlankLines(_AtIndex, _NLines: Integer): TLineFeed;
function AssertLineFeedAfter(_StartPos: Integer): TLineFeed;
procedure CheckSlashComment;
procedure ComplexIfElse(_NTmp: Integer);
procedure CheckShortLine;
{: This function does the actual formatting }
procedure doExecute(_Tokens: TPascalTokenList);
procedure HandleIf;
procedure HandleThen;
procedure HandleColon(_RemoveMe: Integer);
procedure HandleElse(_NTmp: Integer);
property Settings: TCodeFormatterSettings read FSettings write FSettings;
public
class procedure Execute(_Tokens: TPascalTokenList; _Settings: TCodeFormatterSettings);
constructor Create(_Settings: TCodeFormatterSettings);
destructor Destroy; override;
end;
implementation
uses
{$IFDEF GX_VER250_up}
AnsiStrings,
{$ENDIF}
GX_CodeFormatterUnicode;
class procedure TCodeFormatterFormatter.Execute(_Tokens: TPascalTokenList; _Settings: TCodeFormatterSettings);
var
Formatter: TCodeFormatterFormatter;
begin
Formatter := TCodeFormatterFormatter.Create(_Settings);
try
Formatter.doExecute(_Tokens);
finally
Formatter.Free;
end;
end;
constructor TCodeFormatterFormatter.Create(_Settings: TCodeFormatterSettings);
begin
inherited Create;
FSettings := _Settings;
FHasAligned := False;
FPrevLine := nil;
FStack := TCodeFormatterSegment.Create;
end;
destructor TCodeFormatterFormatter.Destroy;
begin
FStack.Free;
inherited;
end;
function TCodeFormatterFormatter.AlignExpression(_Idx: Integer; _Pos: Integer): TPascalToken;
var
OldExpr: TExpression;
begin
FHasAligned := True;
OldExpr := TExpression(FTokens.Extract(_Idx));
Result := TAlignExpression.Create(OldExpr, _Pos);
FTokens.AtInsert(_Idx, Result);
OldExpr.Free;
end;
procedure TCodeFormatterFormatter.AdjustSpacing(_CurrentToken, _PrevToken: TPascalToken; _TokenIdx: Integer);
var
Prev2: TPascalToken;
rType: TReservedType;
wType: TWordType;
Idx: Integer;
function DetectGeneric: Boolean;
var
Next: TPascalToken;
NextNext: TPascalToken;
Idx, Offset: Integer;
exp: TGXUnicodeString;
begin
Result := False;
try
if FCurrentRType <> rtLogOper then
Exit; //=>
if not FCurrentToken.GetExpression(exp) or (exp = '<=') or (exp = '>=') then
Exit; //=>
if FStack.GetTopType in [rtType, rtProcedure] then begin
Result := True;
Exit; //=>
end;
if not GetNextNoComment(_TokenIdx, Next, Offset) then
Exit;
if (exp = '>') then begin
if Next.ReservedType = rtDot then begin
// detect "x>.5" in contrast to "TSomeGeneric<SomeType>.Create"
if not GetNextNoComment(_TokenIdx + 1, NextNext, Offset) or (NextNext.WordType = wtNumber) then
Result := False
else
Result := True;
Exit;
end;
if (Next.ReservedType = rtSemiColon) or (Next.ReservedType = rtRightBr) then begin
Result := True;
Exit;
end;
end;
if Next.ReservedType in [rtLogOper, rtComma, rtSemiColon, rtLeftBr, rtRightBr] then begin
Result := False;
Exit; //=>
end;
Idx := _TokenIdx + Offset;
while GetNextNoComment(Idx, Next, Offset) do begin
case Next.ReservedType of
rtLogOper:
if GetNextNoComment(Idx + Offset, Next) then begin
if Next.ReservedType in [rtLogOper, rtDot, rtComma, rtSemiColon, rtLeftBr, rtRightBr] then begin
Result := True;
Exit; //=>
end else
Inc(Idx, Offset + 1);
end else
Exit; //=>
rtComma:
Inc(Idx, Offset + 1);
else
Exit; //=>
end;
end;
finally
FStack.GenericsElement := Result;
end;
end;
begin
if _CurrentToken = nil then
Exit;
rType := _CurrentToken.ReservedType;
wType := _CurrentToken.WordType;
{ TODO -otwm : This doesn't really belong here, it has nothing to do with spacing }
if not (rType in NoReservedTypes) then
_CurrentToken.ExpressionCase := Settings.ReservedCase
else if rType in StandardDirectives then
_CurrentToken.ExpressionCase := Settings.StandDirectivesCase
else begin
_CurrentToken.ExpressionCase := rfUnchanged;
if wType = wtWord then
Settings.HandleCapitalization(_CurrentToken);
end;
case rType of
rtThen, rtOf, rtElse, rtDo, rtAsm:
_CurrentToken.SetSpace([spBefore, spAfter], True);
rtEnd, rtFuncDirective:
_CurrentToken.SetSpace([spBefore], True);
rtIf, rtUntil, rtWhile, rtCase, rtRecord:
_CurrentToken.SetSpace([spAfter], True);
rtLogOper:
if DetectGeneric then
_CurrentToken.SetSpace([], True)
else
_CurrentToken.SetSpace(Settings.SpaceOperators, True);
rtOper, rtMathOper, rtPlus, rtMinus, rtEquals:
_CurrentToken.SetSpace(Settings.SpaceOperators, True);
rtAssignOper:
_CurrentToken.SetSpace(Settings.SpaceEqualOper, True);
rtColon:
_CurrentToken.SetSpace(Settings.SpaceColon, True);
rtSemiColon:
_CurrentToken.SetSpace(Settings.SpaceSemiColon, True);
rtComma:
if DetectGeneric then
_CurrentToken.SetSpace([], True)
else
_CurrentToken.SetSpace(Settings.SpaceComma, True);
rtLeftBr: begin
_CurrentToken.SetSpace(Settings.SpaceLeftBr, True);
if _PrevToken.ReservedType = rtLeftBr then
_CurrentToken.SetSpace([spBefore], False);
end;
rtLeftHook: begin
_CurrentToken.SetSpace(Settings.SpaceLeftHook, True);
if _PrevToken.ReservedType = rtLeftHook then
_CurrentToken.SetSpace([spBefore], False);
end;
rtRightBr:
_CurrentToken.SetSpace(Settings.SpaceRightBr, True);
rtRightHook:
_CurrentToken.SetSpace(Settings.SpaceRightHook, True);
end;
{ append space after : , ; }
if (wType = wtHexNumber) and Settings.UpperNumbers then
_CurrentToken.SetExpressionCase(rfUpperCase);
{ delimiter between 2 words (necessary) }
if _PrevToken = nil then
Exit;
if Settings.SpaceOperators <> [] then
if wType in [wtString, wtFullComment, wtHalfComment, wtHalfStarComment] then
if not (_PrevToken.ReservedType in [rtDotDot, rtLineFeed]) then
_CurrentToken.SetSpace([spBefore], True);
if rType in [rtMinus, rtPlus] then begin
Prev2 := _PrevToken;
Idx := 0;
while (Prev2 <> nil) and (Prev2.ReservedType in [rtComment, rtLineFeed]) do begin
Inc(Idx);
if Idx > _TokenIdx then
Prev2 := nil
else
Prev2 := FTokens[_TokenIdx - Idx];
end;
if (Prev2 <> nil) and (Prev2.ReservedType in [rtOper,
rtMathOper, rtPlus, rtMinus, rtSemiColon, rtOf,
rtMinus, rtLogOper, rtEquals, rtAssignOper, rtLeftBr,
rtLeftHook, rtComma, rtDefault]) then
_CurrentToken.SetSpace([spAfter], False); { sign operator }
end;
if rType = rtLeftHook then begin
if not (_PrevToken.ReservedType in [rtReserved, rtNothing, rtRightBr, rtRightHook]) then
_CurrentToken.SetSpace([spBefore], True);
end;
if _CurrentToken.Space(spBefore)
and (_PrevToken.ReservedType in [rtLeftBr, rtLeftHook, rtLineFeed]) then
_CurrentToken.SetSpace([spBefore], False);
if (_PrevToken.WordType in [wtWord, wtNumber, wtHexNumber, wtString])
and (wType in [wtWord, wtNumber, wtHexNumber]) then
_CurrentToken.SetSpace([spBefore], True);
if (_PrevToken.ReservedType = rtComment)
and (wType in [wtWord, wtNumber, wtHexNumber]) then
_CurrentToken.SetSpace([spBefore], True);
if _CurrentToken.Space(spBefore) and _PrevToken.Space(spAfter) then
_PrevToken.SetSpace([spAfter], False); { avoid double spaces }
end;
function TCodeFormatterFormatter.TokenAtIs(_Idx: Integer; _rType: TReservedType): Boolean;
var
Token: TPascalToken;
begin
Result := GetToken(_Idx, Token);
if Result then
Result := (Token.ReservedType = _rType);
end;
function TCodeFormatterFormatter.GetToken(_Idx: Integer): TPascalToken;
begin
GetToken(_Idx, Result);
end;
function TCodeFormatterFormatter.GetToken(_Idx: Integer; out _Token: TPascalToken): Boolean;
begin
Result := (_Idx >= 0) and (_Idx < FTokens.Count);
if Result then
_Token := FTokens[_Idx]
else
_Token := nil;
end;
function TCodeFormatterFormatter.GetNextNoComment(_StartPos: Integer; out _Offset: Integer): TPascalToken;
begin
if not GetNextNoComment(_StartPos, Result, _Offset) then
Result := nil;
end;
function TCodeFormatterFormatter.GetNextNoComment(_StartPos: Integer; out _Token: TPascalToken; out _Offset: Integer): Boolean;
begin
_Offset := 0;
repeat
Inc(_Offset);
Result := GetToken(_StartPos + _Offset, _Token);
until not Result or (_Token.ReservedType <> rtComment);
end;
function TCodeFormatterFormatter.GetNextNoComment(_StartPos: Integer; out _Token: TPascalToken): Boolean;
var
Offset: Integer;
begin
Result := GetNextNoComment(_StartPos, _Token, Offset);
end;
function TCodeFormatterFormatter.InsertBlankLines(_AtIndex, _NLines: Integer): TLineFeed;
var
LineIdx: Integer;
NextToken: TPascalToken;
begin
Result := FPrevLine;
for LineIdx := 0 to _NLines - 1 do begin //FI:W528
Result := TLineFeed.Create(0, Settings.SpacePerIndent);
Result.SetIndent(FStack.nIndent);
NextToken := GetToken(_AtIndex);
{ TODO -otwm -ccheck : is the if statement necessary? }
if NextToken.Space(spBefore) then
NextToken.SetSpace([spBefore], False);
FTokens.AtInsert(_AtIndex, Result);
AdjustSpacing(NextToken, Result, _AtIndex);
end;
if _AtIndex <= FTokenIdx then
Inc(FTokenIdx, _NLines);
end;
function TCodeFormatterFormatter.AssertLineFeedAfter(_StartPos: Integer): TLineFeed;
var
Next: TPascalToken;
Offset: Integer;
begin
if GetNextNoComment(_StartPos, Next, Offset) and (Next.ReservedType <> rtLineFeed) then
Result := InsertBlankLines(_StartPos + Offset, 1)
else
Result := FPrevLine;
end;
procedure TCodeFormatterFormatter.DecPrevLineIndent;
begin
if FPrevLine <> nil then
FPrevLine.IncIndent(-1);
end;
procedure TCodeFormatterFormatter.SetPrevLineIndent(_Additional: Integer);
begin
if FPrevLine <> nil then
FPrevLine.SetIndent(FStack.nIndent + _Additional + FStack.ProcLevel);
end;
function TCodeFormatterFormatter.NoBeginTryIndent(_rType: TReservedType): Boolean;
begin
Result := not (
(Settings.IndentBegin and (_rType = rtBegin))
or (Settings.IndentTry and (_rType = rtTry))
)
and (FStack.GetTopType in [rtDo, rtThen, rtIfElse]);
end;
procedure TCodeFormatterFormatter.UppercaseCompilerDirective(_Token: TPascalToken);
var
Idx: Integer;
s: TGXUnicodeString;
begin
_Token.GetExpression(s);
Idx := 2;
while (Idx < Length(s)) and (s[Idx] <> Space) and (s[Idx] <> Tab) do begin
s[Idx] := UpCase(s[Idx]);
Inc(Idx);
end;
_Token.SetExpression(s);
end;
function TCodeFormatterFormatter.PrevTokenIsRType(_rType: TReservedType): Boolean;
begin
Result := Assigned(FPrevToken) and (FPrevToken.ReservedType = _rType);
end;
{: checks and corrects the number of blank lines before a procedure / function declaration }
procedure TCodeFormatterFormatter.CheckBlankLinesAroundProc;
var
k: Integer;
Prev2: TPascalToken;
begin
if (FPrevToken <> nil) then begin
k := 1;
if FPrevToken.ReservedType = rtClass then begin
// class procedure / function
k := 2;
Prev2 := GetToken(FTokenIdx - 2);
end else // just procedure / function
Prev2 := FPrevToken;
if (Prev2 <> nil) and (Prev2.ReservedType <> rtLineFeed) then begin
// no line feed at all -> add two for an empty line
FPrevLine := InsertBlankLines(FTokenIdx - k, 2);
FPrevToken := FPrevLine;
end else begin
// we got one linefeed already, check if there is another one -> empty line
Inc(k);
if GetToken(FTokenIdx - k, Prev2) and (Prev2.ReservedType <> rtLineFeed) then begin
// no, only one -> add one for an empty line
FPrevLine := InsertBlankLines(FTokenIdx - k + 1, 1);
FPrevToken := FPrevLine;
end;
end;
end;
end;
procedure TCodeFormatterFormatter.PutCommentBefore(const _Comment: TGXUnicodeString);
var
J: Integer;
P: TPascalToken;
s: TGXUnicodeString;
begin
J := FTokenIdx - 2;
P := GetToken(J);
s := _Comment;
if P.ReservedType = rtComment then
P.SetExpression(s)
else begin
P := TExpression.Create(wtWord, s);
P.SetReservedType(rtComment);
FTokens.AtInsert(FTokenIdx, P);
Inc(FTokenIdx);
P := TLineFeed.Create(0, Settings.SpacePerIndent);
TLineFeed(P).SetIndent(FStack.nIndent);
FTokens.AtInsert(FTokenIdx, P);
Inc(FTokenIdx);
end;
end;
// When we enter this method FCurrentToken is 'asm' and FCurrentRType os rtAsm
procedure TCodeFormatterFormatter.FormatAsm(_NTmp: Integer);
begin
// remove var / type stuff
while FStack.GetTopType in [rtVar, rtType] do
FStack.Pop;
// no additional indentation for
// procedure xxx;
// asm
if FStack.GetTopType = rtProcedure then begin
FStack.Pop;
DecPrevLineIndent;
end;
FStack.Push(FCurrentRType, 0);
// twm: now we handle all asm statements until we hit an 'end'
// rather ugly
FCurrentToken := GetToken(FTokenIdx);
while (FTokenIdx < FTokens.Count - 1) and (FCurrentToken.ReservedType <> rtEnd) do begin
if FCurrentToken.ReservedType = rtLineFeed then begin
FPrevLine := TLineFeed(FCurrentToken);
FPrevLine.NoOfSpaces := FPrevLine.OldNoOfSpaces;
end;
AdjustSpacing(FCurrentToken, FPrevToken, FTokenIdx);
Inc(FTokenIdx);
FPrevToken := FCurrentToken;
FCurrentToken := GetToken(FTokenIdx);
end;
if FTokenIdx < FTokens.Count then
SetPrevLineIndent(_NTmp);
Dec(FTokenIdx);
end;
procedure TCodeFormatterFormatter.CheckSlashComment;
var
Token: TPascalToken;
PrevPasWord: TPascalToken;
Expression: TGXUnicodeString;
PrevExpression: TGXUnicodeString;
i: Integer;
begin
if GetToken(FTokenIdx - 1, FPrevToken) and (FPrevToken.ReservedType = rtComment)
and FPrevToken.GetExpression(PrevExpression) and (PrevExpression[1] = '/') then begin
// fix for situation with a // comment on prev line: begin becomes part of the comment
if not FPrevToken.ChangeComment('{') then begin
i := 0;
Token := nil;
repeat
PrevPasWord := Token;
Token := GetToken(FTokenIdx + i);
Inc(i);
until (Token = nil) or (Token.ReservedType = rtLineFeed);
Dec(i);
if (PrevPasWord.ReservedType = rtComment)
and PrevPasWord.GetExpression(Expression)
and (Expression[1] = '/') then begin
FPrevToken.SetExpression('{' + Copy(PrevExpression, 2, 999999) + '}');
Exit;
end else
FTokens.Extract(FTokenIdx - 1);
FTokens.AtInsert(FTokenIdx + i, FPrevToken);
FPrevToken := GetToken(FTokenIdx - 1);
AdjustSpacing(FPrevToken, GetToken(FTokenIdx - 2), FTokenIdx - 1);
FCurrentToken := GetToken(FTokenIdx);
end;
end;
FPrevLine := FPrevPrevLine;
end;
procedure TCodeFormatterFormatter.ComplexIfElse(_NTmp: Integer);
begin
while not FStack.IsEmpty and (FLastPopResType <> rtThen) do begin
FLastPopResType := FStack.Pop;
if FLastPopResType = rtIfElse then
ComplexIfElse(_NTmp);
end;
SetPrevLineIndent(_NTmp);
end;
procedure TCodeFormatterFormatter.CheckShortLine;
var
Token: TPascalToken;
function TokenRType: TReservedType;
begin
if Token = nil then
Result := rtNothing
else
Result := Token.ReservedType;
end;
var
Offset: Integer;
begin { CheckShortLine }
Offset := 1;
Token := GetToken(FTokenIdx + Offset);
if TokenRType <> rtLineFeed then
Exit;
while not ((TokenRType in [rtSemiColon, rtBegin, rtElse, rtDo, rtWhile, rtOn, rtThen, rtCase])
or ((Offset > 1) and (Token.ReservedType = rtLineFeed))) do begin
Inc(Offset);
Token := GetToken(FTokenIdx + Offset);
end;
if TokenRType = rtSemiColon then
FTokens.Extract(FTokenIdx + 1).Free;
end;
procedure TCodeFormatterFormatter.HandleIf;
begin
if Settings.FeedAfterThen and not Settings.FeedElseIf
and (FStack.GetTopType = rtIfElse) and (FPrevToken = FPrevLine) then begin
FTokens.Extract(FTokenIdx - 1).Free;
Dec(FTokenIdx);
CheckSlashComment;
end else begin
if Settings.FeedElseIf and (FPrevToken <> FPrevLine) then begin
FPrevLine := AssertLineFeedAfter(FTokenIdx - 1);
FPrevToken := FPrevLine;
end;
end;
if PrevTokenIsRType(rtElse)
or (Settings.NoIndentElseIf and (FStack.GetTopType = rtIfElse)) then begin
FStack.Pop;
if FStack.GetTopType = rtThen then
FStack.Pop;
FWrapIndent := True;
FStack.Push(rtIfElse, 0);
end else
FStack.Push(rtIf, 0);
end;
procedure TCodeFormatterFormatter.HandleThen;
begin
if FStack.GetTopType in [rtIf, rtIfElse] then begin
FWrapIndent := False;
FLastPopResType := FStack.Pop;
if Settings.NoFeedBeforeThen and (FPrevToken = FPrevLine)
and (GetToken(FTokenIdx - 1).ReservedType <> rtComment) then begin
FTokens.Extract(FTokenIdx - 1).Free;
Dec(FTokenIdx);
CheckSlashComment;
end;
if Settings.FeedAfterThen then begin
if AssertLineFeedAfter(FTokenIdx) <> FPrevLine then begin
if (FLastPopResType = rtIf) and Settings.ExceptSingle then
CheckShortLine;
end;
end;
FStack.Push(rtThen, 1);
end;
end;
procedure TCodeFormatterFormatter.HandleColon(_RemoveMe: Integer);
begin
case FStack.GetTopType of
rtOf: begin
FStack.Push(FCurrentRType, 1);
if Settings.FeedAfterThen then begin
if (GetNextNoComment(FTokenIdx, _RemoveMe).ReservedType = rtBegin)
and (AssertLineFeedAfter(FTokenIdx) <> FPrevLine) then
CheckShortLine;
end;
FWrapIndent := False;
end;
rtClassDecl: begin
FStack.Pop;
FStack.Push(rtClass, 1);
end;
rtVar:
if Settings.AlignVar then
FCurrentToken := AlignExpression(FTokenIdx, Settings.AlignVarPos);
rtProcedure, rtProcDeclare:
; // do nothing
else
// label????
FWrapIndent := False;
end;
end;
procedure TCodeFormatterFormatter.HandleElse(_NTmp: Integer);
var
Next: TPascalToken;
begin
FLastPopResType := rtNothing;
while not FStack.IsEmpty and not (FStack.GetTopType in [rtThen, rtOf, rtTry]) do
FLastPopResType := FStack.Pop;
if FLastPopResType = rtIfElse then
ComplexIfElse(_NTmp);
if (Settings.FeedRoundBegin = Hanging)
and (FPrevToken <> nil)
and TokenAtIs(FTokenIdx - 1, rtLineFeed)
and TokenAtIs(FTokenIdx - 2, rtEnd) then begin
FTokens.Extract(FTokenIdx - 1).Free;
Dec(FTokenIdx);
FPrevLine := nil;
FPrevToken := FPrevLine;
end;
if Settings.FeedAfterThen then begin
if (FPrevToken <> nil)
and ((Settings.FeedRoundBegin <> Hanging) or not TokenAtIs(FTokenIdx - 1, rtEnd))
and not TokenAtIs(FTokenIdx - 1, rtLineFeed) then begin
FPrevLine := AssertLineFeedAfter(FTokenIdx - 1);
FPrevToken := FPrevLine;
end;
if GetNextNoComment(FTokenIdx, Next)
and (Next.ReservedType <> rtIf) then
AssertLineFeedAfter(FTokenIdx);
end;
FStack.GetTopIndent;
if FPrevToken = FPrevLine then
SetPrevLineIndent(_NTmp);
if Settings.IndentTryElse and (FStack.GetTopType = rtTry) then begin
FStack.nIndent := FStack.nIndent + 1;
SetPrevLineIndent(_NTmp);
end else if Settings.IndentCaseElse and (FStack.GetTopType = rtOf) then begin
FStack.nIndent := FStack.nIndent + 1;
SetPrevLineIndent(_NTmp);
end;
if FStack.GetTopType = rtThen then
FStack.Push(rtIfElse, 1)
else
FStack.Push(rtElse, 1);
FWrapIndent := False;
end;
procedure TCodeFormatterFormatter.doExecute(_Tokens: TPascalTokenList);
var
NTmp: Integer;
PrevOldNspaces: Integer;
procedure CheckIndent;
var
RemoveMe: Integer;
Next: TPascalToken;
TempWordIdx: Integer;
Prev1: TPascalToken;
FunctDeclare, IsDelegate, NoBlankLine: Boolean;
FeedRound: TFeedBegin;
wType: TWordType;
begin
if FCurrentToken = nil then
Exit;
FCurrentRType := FCurrentToken.ReservedType;
wType := FCurrentToken.WordType;
{ This handles the case where a reserved word was used as the name of
a class member. Is that even allowed? }
if (FCurrentRType in [rtWhile, rtEnd, rtRepeat, rtBegin, rtUses, rtTry,
rtProgram, rtType, rtVar, rtIf, rtThen, rtElse] + StandardDirectives)
and PrevTokenIsRType(rtDot) then begin
FCurrentToken.SetReservedType(rtNothing);
FCurrentRType := rtNothing;
end;
{ SetSpacing; }
case FCurrentRType of
rtIf:
HandleIf;
rtThen:
HandleThen;
rtColon:
HandleColon(RemoveMe);
rtElse:
HandleElse(NTmp);
rtRepeat, rtRecord: begin
FStack.Push(FCurrentRType, 1);
FWrapIndent := False;
end;
rtClass: begin
if not (GetNextNoComment(FTokenIdx, Next)
and (Next.ReservedType in [rtProcedure, rtProcDeclare, rtOf, rtVar])) then begin
{ not a "class function" or "class of" declaration }
FWrapIndent := False;
FStack.Push(rtClassDecl, 1);
end else
{ first assume that it is a class declaration
the first procedure replaces it with rtClass }
FCurrentToken.SetSpace([spAfter], True);
end;
rtUntil: begin
repeat
FLastPopResType := FStack.Pop;
until (FLastPopResType = rtRepeat) or FStack.IsEmpty;
SetPrevLineIndent(NTmp);
end;
rtLeftBr:
if (FStack.GetTopType = rtLeftBr) then
FStack.Push(FCurrentRType, 0)
else begin
FOldWrapIndent := FWrapIndent;
if (FStack.ProcLevel <= 0) or (FStack.GetTopType <> rtProcedure) then
{ niet erg netjes }
FStack.Push(FCurrentRType, 1)
else begin
RemoveMe := 1;
while (FTokenIdx > RemoveMe) and (GetToken(FTokenIdx - RemoveMe, Next)
and (Next.ReservedType in [rtDot, rtNothing])) do begin
Inc(RemoveMe);
end;
if (Next <> nil) and (Next.ReservedType = rtProcedure) then
FStack.Push(FCurrentRType, 0)
else
FStack.Push(FCurrentRType, 1);
end;
FWrapIndent := False;
end;
rtWhile: // Helper For
if not PrevTokenIsRType(rtReserved) then
FStack.Push(FCurrentRType, 0);
rtLeftHook, rtOn: // left hook = '['
FStack.Push(FCurrentRType, 0);
rtRightBr: begin
repeat
FLastPopResType := FStack.Pop;
until (FLastPopResType = rtLeftBr) or FStack.IsEmpty;
if FStack.GetTopType <> rtLeftBr then
FWrapIndent := FOldWrapIndent;
end;
rtRightHook: begin // right hook = ']'
repeat
FLastPopResType := FStack.Pop;
until (FLastPopResType = rtLeftHook) or FStack.IsEmpty;
if FStack.GetTopType = rtClassDecl { Interface } then
FWrapIndent := False;
end;
rtExcept: begin
while not FStack.IsEmpty and (FStack.GetTopType <> rtTry) do
FStack.Pop;
FStack.GetTopIndent;
SetPrevLineIndent(NTmp);
FStack.nIndent := FStack.nIndent + 1;
FWrapIndent := False;
end;
rtVisibility:
if FStack.GetTopType in [rtClass, rtClassDecl, rtRecord] then begin
if PrevTokenIsRType(rtLineFeed) then begin
DecPrevLineIndent;
FWrapIndent := False;
end;
end else if (FStack.GetTopType in [rtVar, rtType]) and (FStack.GetType(1) in [rtClass, rtClassDecl, rtRecord]) then begin
FStack.Pop;
DecPrevLineIndent;
DecPrevLineIndent;
FWrapIndent := False;
end else
FCurrentToken.SetReservedType(rtNothing);
rtOf: begin
case FStack.GetTopType of
rtCase: begin
FStack.Push(FCurrentRType, 1);
if Settings.FeedAfterThen then
AssertLineFeedAfter(FTokenIdx);
FWrapIndent := False;
end;
rtRecord:
FWrapIndent := False;
end;
end;
rtLineFeed: begin
if FStack.IsEmpty then
FWrapIndent := False;
if Settings.RemoveDoubleBlank and (FTokenIdx >= 2) and (FPrevToken <> nil)
and (FPrevToken = FPrevLine) and (FTokens[FTokenIdx - 2] = FPrevPrevLine) then begin
FTokens.Extract(FTokenIdx - 2).Free;
Dec(FTokenIdx);
end;
if GetNextNoComment(FTokenIdx, Next) then begin
if Next.ReservedType in [rtElse, rtIfElse, rtBegin, rtEnd, rtUntil, rtExcept] then
FWrapIndent := False;
if FWrapIndent then
NTmp := 1
else
NTmp := 0;
FWrapIndent := True;
if (Next.ReservedType in [rtLineFeed])
or (FStack.GetTopType in [rtUses, rtLeftBr]) then
FWrapIndent := False;
end;
FPrevPrevLine := FPrevLine;
FPrevLine := TLineFeed(FCurrentToken);
SetPrevLineIndent(NTmp);
end;
rtAsm: begin
FormatAsm(NTmp);
Exit;
end;
rtComma:
if Settings.FeedEachUnit and (FStack.GetTopType = rtUses) then begin
Next := GetNextNoComment(FTokenIdx, RemoveMe);
if Next.ReservedType <> rtLineFeed then
AssertLineFeedAfter(FTokenIdx);
end;
rtProgram, rtUses, rtInitialization:
if FStack.GetTopType <> rtLeftBr then begin
Next := GetNextNoComment(FTokenIdx, RemoveMe);
if (FCurrentRType = rtUses) and (FStack.GetTopType in [rtProcedure, rtProcDeclare, rtClass]) then
FCurrentToken.SetReservedType(rtNothing)
else begin
DecPrevLineIndent;
FStack.Clear;
FStack.Push(FCurrentRType, 1);
FWrapIndent := False;
end;
end;
rtAbsolute:
if not (FStack.GetTopType in [rtVar, rtType]) then
FCurrentToken.SetReservedType(rtNothing)
else begin
Next := GetNextNoComment(FTokenIdx, RemoveMe);
if Next.ReservedType = rtColon then begin
DecPrevLineIndent;
FCurrentToken.SetReservedType(rtNothing);
end;
end;
rtFuncDirective, rtDefault: begin
Next := GetNextNoComment(FTokenIdx, RemoveMe);
if (Next.ReservedType = rtColon)
or not (FStack.GetTopType in [rtProcedure, rtProcDeclare, rtClass])
or (FPrevToken.ReservedType in [rtProcedure, rtProcDeclare, rtDot]) then
FCurrentToken.SetReservedType(rtNothing);
end;
rtForward: begin
if FStack.GetTopType in [rtProcedure, rtProcDeclare] then
FStack.Pop
else
FCurrentToken.SetReservedType(rtNothing);
end;
rtProcedure: begin
if FStack.GetTopType in [rtClassDecl, rtRecord] then begin
FStack.Pop;
FStack.Push(rtClass, 1);
end else if (FStack.GetTopType in [rtVar, rtType])
and (FStack.GetType(1) in [rtClass, rtClassDecl, rtRecord])
and (FPrevToken.ReservedType <> rtEquals) then begin
// There was a nested class/record declaration that ended
FStack.Pop;
FStack.Pop;
FStack.Push(rtClass, 1);
DecPrevLineIndent;
end;
Prev1 := FPrevToken;
TempWordIdx := FTokenIdx;
if Prev1 <> nil then begin
while (TempWordIdx > 0) and (Prev1.ReservedType in [rtComment, rtLineFeed]) do begin
Dec(TempWordIdx);
Prev1 := FTokens[TempWordIdx];
end;
FunctDeclare := (Prev1 <> nil) and (Prev1.ReservedType in [rtEquals, rtColon, rtComma]);
end else
FunctDeclare := False;
NoBlankLine := False;
IsDelegate := False;
if not FunctDeclare then begin
RemoveMe := 0;
repeat
Inc(RemoveMe);
if GetToken(FTokenIdx + RemoveMe, Next) then
if Next.ReservedType = rtLeftBr then
repeat
Inc(RemoveMe);
until not GetToken(FTokenIdx + RemoveMe, Next) or (Next.ReservedType = rtRightBr);
until (Next = nil) or (Next.ReservedType in [rtSemiColon, rtBegin]);
// Begin before a SemiColon, presume that is a anonymous delegate...
if Next.ReservedType = rtBegin then begin
IsDelegate := True;
Next.AddOption(toFeedNewLine); // Force NewLine Feed!
end;
if Next <> nil then begin
repeat
Inc(RemoveMe);
until not GetToken(FTokenIdx + RemoveMe, Next) or not (Next.ReservedType in [rtLineFeed, rtComment]);
if (Next <> nil) and (Next.ReservedType = rtForward) then
NoBlankLine := True;
end;
end;
if not (FunctDeclare or FIsInInterfacePart or (FStack.GetTopType = rtClass)) then begin
if not FStack.HasType(rtProcedure) then begin
if not IsDelegate then begin
if (FStack.nIndent > 0) then begin
FStack.nIndent := 0;
SetPrevLineIndent(NTmp);
end;
FStack.ProcLevel := 0;
if Settings.BlankProc and not NoBlankLine then
CheckBlankLinesAroundProc;
if Settings.CommentFunction then
PutCommentBefore('{ procedure }');
end;
end else begin
if Settings.BlankSubProc and not NoBlankLine then
CheckBlankLinesAroundProc;
FStack.ProcLevel := FStack.ProcLevel + 1;
if FStack.nIndent = 0 then begin
SetPrevLineIndent(NTmp);
FStack.nIndent := FStack.nIndent + 1;
end;
end;
FStack.Push(rtProcedure, 0);
end else begin
// Array of Procedure, Reference To Function...
if (FStack.GetTopType = rtType) and Assigned(Prev1) and (Prev1.ReservedType in [rtOf, rtOper, rtComma]) then begin
// SetPrevLineIndent(NTmp);
//
// FStack.ProcLevel := FStack.ProcLevel + 1;
/// / FStack.Push(FCurrentRType , 1);
//
end else begin
if (not FunctDeclare) and (not (FStack.GetTopType = rtClass)) then begin
FStack.nIndent := 0;
SetPrevLineIndent(NTmp);
end;
FStack.Push(rtProcDeclare, 0);
end;
end;
end;
rtInterface: begin
if PrevTokenIsRType(rtEquals) then begin
{ declaration of a OLE object: IClass = interface [' dfgsgdf'] }
FStack.Push(rtClassDecl, 1);
end else begin
FIsInInterfacePart := True;
DecPrevLineIndent;
end;
FWrapIndent := False;
end;
rtImplementation: begin
FStack.Clear;
FIsInInterfacePart := False;
FWrapIndent := False;
{ DecPrevIndent; }
{ nIndent := 0; }
SetPrevLineIndent(NTmp);
end;
rtBegin, rtTry: begin
while FStack.GetTopType in [rtVar, rtType] do
FStack.Pop;
if FStack.GetTopType in [rtProcedure, rtProgram] then
FStack.Pop;
if FStack.IsEmpty then
FStack.nIndent := 0;
if NoBeginTryIndent(FCurrentRType) then
FStack.nIndent := FStack.nIndent - 1;
case FCurrentRType of
rtBegin:
if FCurrentToken.HasOption(toFeedNewLine) then
FeedRound := NewLine
else
FeedRound := Settings.FeedRoundBegin;
rtTry:
FeedRound := Settings.FeedRoundTry;
else
FeedRound := Unchanged;
end;
case FeedRound of
Hanging: begin
if (FStack.GetTopType in [rtDo, rtThen, rtIfElse, rtElse, rtColon])
and (FPrevToken <> nil) and (GetToken(FTokenIdx - 1) = FPrevLine) then begin
FTokens.Extract(FTokenIdx - 1).Free;
Dec(FTokenIdx);
CheckSlashComment;
end;
AssertLineFeedAfter(FTokenIdx);
end;
NewLine: begin
if (FPrevToken <> nil) and (GetToken(FTokenIdx - 1).ReservedType <> rtLineFeed) then begin
FPrevLine := AssertLineFeedAfter(FTokenIdx - 1);
FPrevToken := FPrevLine;
end;
AssertLineFeedAfter(FTokenIdx);
end;
end;
FStack.Push(FCurrentRType, 1);
if FPrevToken = FPrevLine then begin
SetPrevLineIndent(NTmp);
DecPrevLineIndent;
end;
FWrapIndent := False;
end;
rtEquals:
if Settings.AlignVar and (FStack.GetTopType = rtVar) then
FCurrentToken := AlignExpression(FTokenIdx, Settings.AlignVarPos);
rtVar, rtType:
if not (FStack.GetTopType in [rtLeftBr, rtLeftHook]) then begin
FWrapIndent := False;
if FStack.nIndent < 1 then
FStack.nIndent := 1;
if (FStack.GetTopType in [rtVar, rtType]) then begin
if (FCurrentRType = rtType) and PrevTokenIsRType(rtEquals) then begin
// in classes.pas I found
// t = type AnsiString
FStack.Pop
end else if FStack.GetType(1) in [rtClass, rtClassDecl, rtRecord] then begin
FStack.Pop;
DecPrevLineIndent;
end else
FStack.Pop;
end;
if (FStack.GetTopType in [rtClass, rtClassDecl, rtRecord]) then begin
FStack.Push(FCurrentRType, 1);
end else begin
FStack.Push(FCurrentRType, 0);
if not PrevTokenIsRType(rtEquals) then begin
DecPrevLineIndent;
if Settings.FeedAfterVar then
AssertLineFeedAfter(FTokenIdx);
end;
end;
end;
rtCase:
if not (FStack.GetTopType in [rtRecord, rtLeftBr]) then
FStack.Push(FCurrentRType, 0)
else begin
FWrapIndent := False;
FStack.Push(rtRecCase, 1);
end;
rtDo:
if FStack.GetTopType in [rtWhile, rtOn] then begin
FLastPopResType := FStack.GetTopType;
FStack.Push(FCurrentRType, 1);
FWrapIndent := False;
if Settings.NoFeedBeforeThen and (FPrevToken = FPrevLine) then begin
FTokens.Extract(FTokenIdx - 1).Free;
Dec(FTokenIdx);
CheckSlashComment;
end;
if Settings.FeedAfterThen then begin
if AssertLineFeedAfter(FTokenIdx) <> FPrevLine then begin
if (FLastPopResType in [rtOn, rtWhile]) and Settings.ExceptSingle then
CheckShortLine;
end;
end;
end;
rtEnd: begin
FWrapIndent := False;
repeat
FLastPopResType := FStack.Pop;
until FStack.IsEmpty or (FLastPopResType in [rtClass, rtClassDecl, rtRecord, rtTry, rtCase, rtBegin, rtAsm (* , rtVisibility *)]);
if FStack.IsEmpty then
FStack.nIndent := 0;
if Settings.FeedBeforeEnd and (FPrevToken <> nil)
and (GetToken(FTokenIdx - 1).ReservedType <> rtLineFeed) then begin
FPrevLine := AssertLineFeedAfter(FTokenIdx - 1);
FPrevToken := FPrevLine;
end;
if (FPrevToken = FPrevLine) then
SetPrevLineIndent(NTmp);
if NoBeginTryIndent(FCurrentRType) then
FStack.nIndent := FStack.nIndent + 1;
end;
rtComment: begin
if Settings.IndentComments and (FStack.GetTopType <> rtLeftHook) then
FWrapIndent := False;
if FStack.IsEmpty and (FStack.nIndent > 0) then begin
FStack.nIndent := 0;
SetPrevLineIndent(NTmp);
end;
AdjustSpacing(GetToken(FTokenIdx + 1), FCurrentToken, FTokenIdx + 1);
if (FPrevLine <> nil) and (FPrevLine = FPrevToken) then begin
if not Settings.IndentComments
or (FCurrentToken.WordType in [wtFullOutComment, wtHalfOutComment]) then
FPrevLine.NoOfSpaces := FPrevLine.OldNoOfSpaces
else begin
if PrevOldNspaces >= 0 then
FPrevLine.NoOfSpaces := FPrevLine.NoOfSpaces +
(FPrevLine.OldNoOfSpaces - PrevOldNspaces)
else
PrevOldNspaces := FPrevLine.OldNoOfSpaces;
end;
end else if Settings.AlignComments and (FCurrentToken.WordType = wtFullComment) then begin
if GetToken(FTokenIdx + 1, Next) and (Next.ReservedType = rtLineFeed) then
FCurrentToken := AlignExpression(FTokenIdx, Settings.AlignCommentPos);
end;
end;
rtSemiColon:
if not (FStack.GetTopType in [rtLeftBr, rtLeftHook]) then begin
while not FStack.IsEmpty and (FStack.GetTopType in [rtDo, rtWhile,
rtProcDeclare, rtThen, rtProgram, rtUses, rtColon, rtClassDecl])
or (FStack.GetTopType = rtIfElse) do
FStack.Pop;
FWrapIndent := False;
RemoveMe := 0;
repeat
Inc(RemoveMe);
until not GetToken(FTokenIdx + RemoveMe, Next) or (not (Next.ReservedType in [{ rtComment, }rtLineFeed]));
if Next <> nil then begin
if (Next.ReservedType = rtAbsolute)
or ((FStack.GetTopType in [rtProcedure, rtProcDeclare, rtClass])
and (Next.ReservedType in [rtFuncDirective, rtForward])
and (FStack.ProcLevel = 0)) then
FWrapIndent := True
else if Settings.FeedAfterSemiColon
and not (Next.ReservedType in [rtForward, rtFuncDirective, rtDefault]) then
AssertLineFeedAfter(FTokenIdx);
end;
end;
rtCompIf: begin
// push current stack to preserve indenting from before the ifdef
FStackStack.Push(FStack.Clone);
end;
rtCompElse: begin
if not FStackStack.IsEmpty then begin
// Free current stack and take a copy of the one from before the corresponding ifdef.
FStack.Free;
FStack := FStackStack.Top.Clone;
end;
end;
rtCompEndif: begin
// pop and free the saved stack
if not FStackStack.IsEmpty then
FStackStack.Pop.Free;
end;
end; // case FCurrentRType
AdjustSpacing(FCurrentToken, FPrevToken, FTokenIdx);
if not (FCurrentRType in [rtLineFeed, rtComment]) then
PrevOldNspaces := -1;
if wType = wtCompDirective then begin
FWrapIndent := False;
if not Settings.IndentCompDirectives and PrevTokenIsRType(rtLineFeed) then begin
NTmp := -FStack.nIndent;
SetPrevLineIndent(NTmp);
end;
if Settings.UpperCompDirectives then
UppercaseCompilerDirective(FCurrentToken);
end;
if not (FCurrentToken.ReservedType = rtComment) then
FPrevToken := FCurrentToken;
end;
begin { procedure TCodeFormatterFormatter.doExecute; }
FTokens := _Tokens;
if Settings.ChangeIndent then begin
FPrevLine := nil;
FPrevPrevLine := nil;
FPrevToken := nil;
FWrapIndent := True;
FIsInInterfacePart := False;
NTmp := 0;
PrevOldNspaces := -1;
// the StackStack is used to preserve indenting over IFDEF/ELSE/ENDIF statements
FStackStack := TCodeFormatterStack.Create;
try
FTokenIdx := 0;
while GetToken(FTokenIdx, FCurrentToken) do begin
CheckIndent;
Inc(FTokenIdx);
end;
finally
FreeAndNil(FStackStack);
end;
end;
// remove empty lines from the end
FTokenIdx := FTokens.Count - 1;
while (FTokenIdx > 0) and TokenAtIs(FTokenIdx, rtLineFeed) do begin
FTokens.Extract(FTokenIdx).Free;
Dec(FTokenIdx);
end;
if Settings.WrapLines or FHasAligned then
CheckWrapping;
end;
procedure TCodeFormatterFormatter.CheckWrapping;
var
HasInserted: Boolean;
procedure InsertLinefeed(ATokenIdx: Integer);
var
PrevPrevLine: TLineFeed;
begin
PrevPrevLine := FPrevLine;
FPrevLine := TLineFeed.Create(PrevPrevLine.OldNoOfSpaces, Settings.SpacePerIndent);
FPrevLine.NoOfSpaces := PrevPrevLine.NoOfSpaces;
FPrevLine.Wrapped := True;
GetToken(ATokenIdx).SetSpace([spBefore], False);
FTokens.AtInsert(ATokenIdx, FPrevLine);
HasInserted := True;
end;
var
TokenIdx, J, k: Integer;
K2, LineLen: Integer;
Token: TPascalToken;
Expression: TAlignExpression;
begin
LineLen := 0;
FPrevLine := nil;
J := 0;
TokenIdx := 0;
while TokenIdx < FTokens.Count do begin
Token := GetToken(TokenIdx);
// GetLength as a side effect, adjusts the alignment
Token.GetLength(LineLen);
if Settings.WrapLines and (Token is TAlignExpression)
and (LineLen > Settings.WrapPosition) then begin
Expression := Token as TAlignExpression;
k := Expression.NoOfSpaces - LineLen - Settings.WrapPosition;
if k < 1 then
Expression.NoOfSpaces := 1
else
Expression.NoOfSpaces := k;
LineLen := Settings.WrapPosition;
end;
if Token.ReservedType = rtLineFeed then begin
FPrevLine := TLineFeed(Token);
if (LineLen > Settings.WrapPosition) then
LineLen := 0;
J := TokenIdx;
end;
if Settings.WrapLines and (LineLen > Settings.WrapPosition) and (TokenIdx > J + 3) then begin
k := TokenIdx - 1;
K2 := 0;
HasInserted := False;
while (k >= J) and not HasInserted do begin
if (GetToken(k).ReservedType in [rtThen, rtDo])
or (GetToken(k).ReservedType = rtElse)
and (GetToken(k + 1).ReservedType <> rtIf) then begin
InsertLinefeed(k + 1);
TokenIdx := J;
end;
if (K2 = 0) and (GetToken(k).Space(spAfter)
or GetToken(k + 1).Space(spBefore)) then
K2 := k + 1;
Dec(k);
end;
if not HasInserted and (K2 <> 0) and (K2 > J) then begin
InsertLinefeed(K2);
TokenIdx := J;
end;
LineLen := 0;
end;
Inc(TokenIdx);
end;
end;
end.
|
unit uUtil;
interface
uses
SysUtils, Classes,Windows,Forms,
ComCtrls,
uCheckValiable,
uCommon,
dllFunction,
WinSock;
procedure Delay(MSecs: Longint);
procedure MyDelay(Milliseconds: DWORD);
function ResponseCheck(aIndex,aDelay:integer):Boolean;
Function ByteCopy(p:pAnsiChar;n:cardinal):String;
function CardReaderResponseCheck(aIndex,aDelay:integer):Boolean;
function CardReaderVersionResponseCheck(aIndex,aDelay:integer):Boolean;
function ZoneExtentionVersionResponseCheck(aIndex,aDelay:integer):Boolean;
function PortResponseCheck(aIndex,aDelay:integer):Boolean;
function GetNodeByText(ATree : TTreeView; AValue:String; AVisible: Boolean): TTreeNode;
function CheckIPType(aIP:string;aZeroType:Boolean):Boolean;
function SetSpacelength(st : String; aLength : Integer) : String;
function Get_Local_IPAddr : string;
Function GetIpFromDomain(aDomain:string):string;
function Ascii2Hex(aData:string;bReverse:Boolean = False):string;
function MakeHexSum(aHex:string;nCSType:integer=0):Char;
Function MakeHexCSData(aHexData: string;nCSType:integer=0):String;
procedure LogSave(aFileName,ast:string);
function IsIPTypeCheck(ip: string): Boolean;
function FillCharStr(aCardNo:string;aChar:char;aLen:integer):string;
implementation
function Ascii2Hex(aData:string;bReverse:Boolean = False):string;
var
i : integer;
stHex : string;
nLen : integer;
begin
stHex := '';
nLen := Length(aData);
for i:= 1 to nLen do
begin
if Not bReverse then stHex := stHex + Dec2Hex(Ord(aData[i]),2)
else stHex := Dec2Hex(Ord(aData[i]),2) + stHex;
end;
result := stHex;
end;
Function ByteCopy(p:pAnsiChar;n:cardinal):String;
var
rP:pAnsiChar;
begin
setLength(result,n);
rP:=pAnsiChar(result);
while n <> 0 do
begin
rP^:=p^;
inc(rP);
inc(p);
dec(n);
end;
end;
procedure Delay(MSecs: Longint);
var
FirstTickCount, Now: Longint;
begin
FirstTickCount := GetTickCount;
repeat
Application.ProcessMessages;
{ allowing access to other controls, etc. }
Now := GetTickCount;
until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;
procedure MyDelay(Milliseconds: DWORD);
{by Hagen Reddmann}
var
Tick: DWORD;
NowTick: DWORD;
Event: THandle;
begin
Event := CreateEvent(nil, False, False, nil);
try
//WaitForSingleObject(Event,Milliseconds);
Tick := GetTickCount + DWORD(Milliseconds);
while (Milliseconds > 0) and
(MsgWaitForMultipleObjects(1, Event, False, Milliseconds,
QS_ALLINPUT) <> WAIT_TIMEOUT) do
begin
sleep(1);
//MyProcessMessage;
Application.ProcessMessages;
Try
NowTick := GetTickCount;
if Tick > NowTick then
Milliseconds := Tick - NowTick
else Milliseconds := 0 ;
Except
Exit;
End;
end;
finally
CloseHandle(Event);
end;
end;
function MakeHexSum(aHex:string;nCSType:integer=0):Char;
var
i: Integer;
aBcc: Byte;
BCC: string;
begin
aBcc := 0;
for i := 1 to (Length(aHex) div 2) do
begin
//aBcc := aBcc + Ord(Hex2Ascii(copy(aHex,(i * 2) - 1,2)));
aBcc := aBcc + Hex2Dec(copy(aHex,(i * 2) - 1,2));
end;
if nCSType = 1 then
begin
aBcc := aBcc + Ord(#$A7);
end else if nCSType = 2 then
begin
aBcc := aBcc + Ord(#$9E);
end;
BCC := Chr(aBcc);
Result := BCC[1];
end;
Function MakeHexCSData(aHexData: string;nCSType:integer=0):String;
var
aSum: Integer;
I: Integer;
st: string;
begin
aSum:= Ord(MakeHexSum(aHexData,nCSType));
aSum:= aSum*(-1);
st:= Dec2Hex(aSum,2);
st := copy(st,Length(st)-1,2);
Result := Ascii2Hex(st);
end;
function ResponseCheck(aIndex,aDelay:integer):Boolean;
var
FirstTickCount : double;
begin
Try
G_bResponseChecking := True;
FirstTickCount := GetTickCount + aDelay;
While Not G_bDeviceResponse[aIndex] do
begin
Application.ProcessMessages;
if GetTickCount > FirstTickCount then Break;
end;
result := G_bDeviceResponse[aIndex];
Finally
G_bResponseChecking := False;
End;
end;
function CardReaderResponseCheck(aIndex,aDelay:integer):Boolean;
var
FirstTickCount : double;
begin
Try
G_bResponseChecking := True;
FirstTickCount := GetTickCount + aDelay;
While Not G_bCardReaderResponse[aIndex] do
begin
Application.ProcessMessages;
if GetTickCount > FirstTickCount then Break;
end;
result := G_bCardReaderResponse[aIndex];
Finally
G_bResponseChecking := False;
End;
end;
function CardReaderVersionResponseCheck(aIndex,aDelay:integer):Boolean;
var
FirstTickCount : double;
begin
Try
G_bResponseChecking := True;
FirstTickCount := GetTickCount + aDelay;
While Not G_bCardReaderVersionResponse[aIndex] do
begin
Application.ProcessMessages;
if GetTickCount > FirstTickCount then Break;
end;
result := G_bCardReaderVersionResponse[aIndex];
Finally
G_bResponseChecking := False;
End;
end;
function ZoneExtentionVersionResponseCheck(aIndex,aDelay:integer):Boolean;
var
FirstTickCount : double;
begin
Try
G_bResponseChecking := True;
FirstTickCount := GetTickCount + aDelay;
While Not G_bExtentionVersionResponse[aIndex] do
begin
Application.ProcessMessages;
if GetTickCount > FirstTickCount then Break;
end;
result := G_bExtentionVersionResponse[aIndex];
Finally
G_bResponseChecking := False;
End;
end;
function PortResponseCheck(aIndex,aDelay:integer):Boolean;
var
FirstTickCount : double;
begin
Try
G_bResponseChecking := True;
FirstTickCount := GetTickCount + aDelay;
While Not G_bPortResponse[aIndex] do
begin
if G_bApplicationTerminate then Exit;
Application.ProcessMessages;
if GetTickCount > FirstTickCount then Break;
end;
result := G_bPortResponse[aIndex];
Finally
G_bResponseChecking := False;
End;
end;
function GetNodeByText(ATree : TTreeView; AValue:String; AVisible: Boolean): TTreeNode;
var
Node: TTreeNode;
begin
Result := nil;
if ATree.Items.Count = 0 then Exit;
Node := ATree.Items[0];
while Node <> nil do
begin
if UpperCase(Node.Text) = UpperCase(AValue) then
begin
Result := Node;
if AVisible then
Result.MakeVisible;
Break;
end;
Node := Node.GetNext;
end;
end;
function CheckIPType(aIP:string;aZeroType:Boolean):Boolean;
var
stTemp : string;
i : integer;
nSum : integer;
nTemp : integer;
begin
Result := False;
nSum := 0;
Try
for i := 0 to 3 do
begin
stTemp := FindCharCopy(aIP, i, '.');
nTemp := StrToInt(stTemp);
if nTemp > 255 then Exit;
nSum := nSum + nTemp;
end;
Except
Exit;
End;
if Not aZeroType then //0.0.0.0 을 잘못된 타입으로 인식하는 경우
begin
if nSum = 0 then Exit;
end;
result := True;
end;
function SetSpacelength(st : String; aLength : Integer) : String;
begin
result := st;
while Length(Result) < aLength do
Result := Result + ' ';
Result := Copy(Result,1,aLength);
end;
function Get_Local_IPAddr : string;
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : array [0..63] of char;
I : Integer;
GInitData : TWSADATA;
begin
try
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
i := 0;
result := '';
while pptr^[I] <> nil do
begin
result:= result + StrPas(inet_ntoa(pptr^[I]^)) + ' ';
Inc(I);
end;
finally WSACleanup; end;
end;
Function GetIpFromDomain(aDomain:string):string;
var
WSAData1: WSADATA;
HostEnt: PHostEnt;
pAddr: PChar;
addr: in_addr;
begin
Result:='';
// GetHostByName 을 쓰기 위해 WSAStartup 을 한번 해줘야 함
if WSAStartup(MAKEWORD(2, 2), WSAData1)<>0 then Exit;
// WSAStartup 호출이 제대로 되지 않음을 체크(?)
if (LOBYTE(WSAData1.wVersion)<>2) or (HIBYTE(WSAData1.wVersion)<>2) then begin
WSACleanup;
Exit;
end;
// HostEnt 로 매개변수로 받아온 도메인이름의 정보를 받아옴
HostEnt := GetHostByName(pAnsiChar(aDomain));
if HostEnt=nil then Exit;
// PChar 형 변수로 ip 주소를 옮김
pAddr := HostEnt^.h_addr_list^;
if pAddr=nil then Exit;
// 옮긴 ip 주소를 in_addr 로 적절히 변환
addr.S_un_b.s_b1 := pAddr[0];
addr.S_un_b.s_b2 := pAddr[1];
addr.S_un_b.s_b3 := pAddr[2];
addr.S_un_b.s_b4 := pAddr[3];
// 변환된 ip 주소를 반환
Result := inet_ntoa(addr);
end;
procedure LogSave(aFileName,ast:string);
Var
f: TextFile;
st: string;
stDir : string;
begin
{$I-}
stDir := ExtractFilePath(aFileName);
if not DirectoryExists(stDir) then CreateDir(stDir);
AssignFile(f, aFileName);
Append(f);
if IOResult <> 0 then Rewrite(f);
st := FormatDateTIme('yyyy-mm-dd hh:nn:ss:zzz">"',Now) + ' ' + ast;
WriteLn(f,st);
System.Close(f);
{$I+}
end;
function IsIPTypeCheck(ip: string): Boolean;
var
z, i: byte;
st: array[1..3] of byte;
const
ziff = ['0'..'9'];
begin
st[1] := 0;
st[2] := 0;
st[3] := 0;
z := 0;
Result := False;
for i := 1 to Length(ip) do
if ip[i] in ziff then
else
begin
if ip[i] = '.' then
begin
Inc(z);
if z < 4 then st[z] := i
else
begin
Exit;
end;
end
else
begin
Exit;
end;
end;
if (z <> 3) or (st[1] < 2) or (st[3] = Length(ip)) or (st[1] + 2 > st[2]) or
(st[2] + 2 > st[3]) or (st[1] > 4) or (st[2] > st[1] + 4) or (st[3] > st[2] + 4) then
begin
Exit;
end;
z := StrToInt(Copy(ip, 1, st[1] - 1));
if (z > 255) or (ip[1] = '0') then
begin
Exit;
end;
z := StrToInt(Copy(ip, st[1] + 1, st[2] - st[1] - 1));
if (z > 255) or ((z <> 0) and (ip[st[1] + 1] = '0')) then
begin
Exit;
end;
z := StrToInt(Copy(ip, st[2] + 1, st[3] - st[2] - 1));
if (z > 255) or ((z <> 0) and (ip[st[2] + 1] = '0')) then
begin
Exit;
end;
z := StrToInt(Copy(ip, st[3] + 1, Length(ip) - st[3]));
if (z > 255) or ((z <> 0) and (ip[st[3] + 1] = '0')) then
begin
Exit;
end;
result := True;
end;
function FillCharStr(aCardNo:string;aChar:char;aLen:integer):string;
var
nLen : integer;
i : integer;
begin
nLen := length(aCardNo);
for i:=nLen + 1 to aLen do
begin
aCardNo := aCardNo + aChar;
end;
result := aCardNo;
end;
end.
|
unit debugHelper;
{$mode objfpc}{$H+}
{
DebugForm.Append('Start');
DebugForm.Append('%s', 'test=');
DebugForm.Append('%s=%d', 'test=', 69);
DebugForm.Append('%s=%s', 'true', true);
DebugForm.Append('%s=%s', 'false', false);
DebugForm.Append('%s=%d', 'true', Integer(true));
DebugForm.Append('%s=%d', 'false', Integer(false));
}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TDebugForm }
TDebugForm = class(TForm)
Memo: TMemo;
ButtonClear: TButton;
procedure ButtonClearClick(Sender: TObject);
procedure Append(sText: string);
procedure Append(sFormat:string; sText: string);
procedure Append(sFormat:string; sText: string; iNumber: integer);
procedure Append(sFormat:string; sText: string; bFlag: boolean);
procedure Append(sFormat:string; iNumber: integer);
private
public
end;
var
DEBUG: TDebugForm;
implementation
{$R *.lfm}
{ TDebugForm }
procedure TDebugForm.Append(sText: string);
begin
Memo.Append(sText);
end;
procedure TDebugForm.Append(sFormat:string; sText: string);
begin
sText:=Format(sFormat, [sText]);
Memo.Append(sText);
end;
procedure TDebugForm.Append(sFormat:string; sText: string; iNumber: integer);
begin
sText:=Format(sFormat, [sText,iNumber] );
Memo.Append(sText);
end;
procedure TDebugForm.Append(sFormat:string; sText: string; bFlag: boolean);
var
BOOL_TEXT: array[boolean] of string = ('False', 'True');
begin
sText:=Format(sFormat, [sText,BOOL_TEXT[bFlag]] );
Memo.Append(sText);
end;
procedure TDebugForm.Append(sFormat:string; iNumber: integer);
begin
Memo.Append(Format(sFormat, [iNumber] ));
end;
procedure TDebugForm.ButtonClearClick(Sender: TObject);
begin
Memo.Clear;
end;
end.
|
unit ResourceUtils;
(*************************************************************
Copyright © 2012 Toby Allen (https://github.com/tobya)
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, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice, and every other copyright notice found in this software, and all the attributions in every file, and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
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.
****************************************************************)
interface
uses Classes, strutils, sysutils;
type
TResourceStrings = class(TStringList)
private
FValuesAreHex: Boolean;
FValuesAreInt: Boolean;
procedure SetValuesAreHex(const Value: Boolean);
procedure SetValuesAreInt(const Value: Boolean);
function GetValueasInt(Name: String): Integer;
procedure SetValueasInt(Name: String; const Value: Integer);
function GetValuebyIndexasInt(idx: integer): Integer;
procedure SetValuebyIndexasInt(idx: integer; const Value: Integer);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
Constructor Create(ResourceName : String);
Procedure Load(ResourceName: String);
Procedure Append(ResourceName : String);
Function Exists(Key : String) : Boolean;
Property ValuesAreHex : Boolean read FValuesAreHex write SetValuesAreHex;
property ValuesAreInt : Boolean read FValuesAreInt write SetValuesAreInt;
Property ValueasInt[Name: String]: Integer read GetValueasInt write SetValueasInt;
Property ValuebyIndexasInt[idx: integer] : Integer read GetValuebyIndexasInt write SetValuebyIndexasInt;
published
{ published declarations }
end;
procedure LoadStringListFromResource(const ResName: string;SL : TStringList; Append: Boolean = false);
implementation
procedure LoadStringListFromResource(const ResName: string;SL : TStringList; Append: Boolean = false);
var
RS: TResourceStream;
tempSL : TStringList;
begin
tempSL := TStringList.Create();
RS := TResourceStream.Create(HInstance, ResName, 'Text');
try
tempSL.LoadFromStream(RS);
finally
RS.Free;
end;
if Append then
begin
SL.AddStrings(tempSL);
end else
begin
SL.Text := tempSL.Text;
end;
end;
{ TResourceStrings }
procedure TResourceStrings.Append(ResourceName: String);
begin
LoadStringListFromResource(ResourceName,Self,true);
end;
constructor TResourceStrings.Create(ResourceName: String);
begin
inherited Create;
FValuesAreHex := false;
FValuesAreInt := false;
Load(ResourceName);
end;
function TResourceStrings.Exists(Key: String): Boolean;
var idx : integer;
begin
Result := false;
idx := Self.IndexOfName(Key);
if idx > -1 then
begin
Result := True;
end;
end;
function TResourceStrings.GetValueasInt(Name: String): Integer;
var
val : String;
begin
val := Self.Values[Name];
Result := Strtoint(val);
end;
function TResourceStrings.GetValuebyIndexasInt(idx: integer): Integer;
var
val : String;
begin
val := Self.ValueFromIndex[idx];
Result := Strtoint(val);
end;
procedure TResourceStrings.Load(ResourceName: String);
begin
LoadStringListFromResource(ResourceName,Self);
end;
procedure TResourceStrings.SetValueasInt(Name: String; const Value: Integer);
begin
end;
procedure TResourceStrings.SetValuebyIndexasInt(idx: integer;
const Value: Integer);
begin
end;
procedure TResourceStrings.SetValuesAreHex(const Value: Boolean);
begin
FValuesAreHex := Value;
end;
procedure TResourceStrings.SetValuesAreInt(const Value: Boolean);
begin
FValuesAreInt := Value;
end;
end.
|
(*
Tg framework, FCL HTTP Daemon Broker
Copyright (C) 2014 Silvio Clecio
See the file LICENSE.txt, included in this distribution,
for details about the copyright.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*)
unit tgshelldmn;
{$mode objfpc}{$H+}
interface
uses
{$IFDEF MSWINDOWS}
ServiceManager,
{$ENDIF}
DaemonApp, Classes, SysUtils,
tgsendertypes, shellthread
;
type
{ TTgShellDaemon }
TTgShellDaemon = class(TCustomDaemon)
private
FThread: TThread;
public
function Install: Boolean; override;
function Uninstall: Boolean; override;
function Start: Boolean; override;
function Stop: Boolean; override;
end;
{ TTgShellDaemonMapper }
TTgShellDaemonMapper = class(TCustomDaemonMapper)
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{ TTgShellDaemon }
function TTgShellDaemon.Start: Boolean;
begin
Result := inherited Start;
FThread := TShellThread.Create;
FThread.Start;
end;
function TTgShellDaemon.Stop: Boolean;
begin
Result := inherited Stop;
FThread.Terminate;
//FThread.Free;
end;
function TTgShellDaemon.Install: Boolean;
{$IFDEF MSWINDOWS}
var
VSM: TServiceManager;
{$ENDIF}
begin
Result := inherited Install;
{$IFDEF MSWINDOWS}
VSM := TServiceManager.Create(nil);
try
VSM.Connect;
if VSM.Connected then
VSM.StartService('TgShBotD', nil);
VSM.Disconnect;
finally
VSM.Free;
end;
{$ENDIF}
WriteLn('Service installed.');
WriteLn('Show text in terminal');
end;
function TTgShellDaemon.Uninstall: Boolean;
{$IFDEF MSWINDOWS}
var
VSM: TServiceManager;
{$ENDIF}
begin
Result := inherited Uninstall;
{$IFDEF MSWINDOWS}
VSM := TServiceManager.Create(nil);
try
VSM.Connect;
if VSM.Connected then
VSM.StopService('TgShBotD', True);
VSM.Disconnect;
finally
VSM.Free;
end;
{$ENDIF}
WriteLn('Service uninstalled.');
end;
{ TTgShellDaemonMapper }
constructor TTgShellDaemonMapper.Create(AOwner: TComponent);
var
VDaemonDef: TDaemonDef;
begin
inherited Create(AOwner);
VDaemonDef := DaemonDefs.Add as TDaemonDef;
VDaemonDef.Description := 'Telegram bot of shell emulator';
VDaemonDef.DisplayName := 'Telegram Bot Shell emulator';
VDaemonDef.Name := 'TgShBot';
VDaemonDef.DaemonClassName := 'TTgShellDaemon';
VDaemonDef.WinBindings.ServiceType := stWin32;
end;
initialization
RegisterDaemonClass(TTgShellDaemon);
RegisterDaemonMapper(TTgShellDaemonMapper);
end.
|
unit l3AutolinkService;
// Модуль: "w:\common\components\rtl\Garant\L3\l3AutolinkService.pas"
// Стереотип: "Service"
// Элемент модели: "Tl3AutolinkService" MUID: (552BF69B039B)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, l3Variant
;
(*
Ml3AutolinkService = interface
{* Контракт сервиса Tl3AutolinkService }
function GetAutolinkFilter: Ik2TagGenerator;
procedure CleanAutolinkFilter;
end;//Ml3AutolinkService
*)
type
Il3AutolinkService = interface
{* Интерфейс сервиса Tl3AutolinkService }
function GetAutolinkFilter: Ik2TagGenerator;
procedure CleanAutolinkFilter;
end;//Il3AutolinkService
Tl3AutolinkService = {final} class(Tl3ProtoObject)
private
f_Alien: Il3AutolinkService;
{* Внешняя реализация сервиса Il3AutolinkService }
protected
procedure pm_SetAlien(const aValue: Il3AutolinkService);
procedure ClearFields; override;
public
function GetAutolinkFilter: Ik2TagGenerator;
procedure CleanAutolinkFilter;
class function Instance: Tl3AutolinkService;
{* Метод получения экземпляра синглетона Tl3AutolinkService }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property Alien: Il3AutolinkService
write pm_SetAlien;
{* Внешняя реализация сервиса Il3AutolinkService }
end;//Tl3AutolinkService
implementation
uses
l3ImplUses
{$If Defined(Archi) AND NOT Defined(NoScripts)}
, AutolinkFilterWordsPack
{$IfEnd} // Defined(Archi) AND NOT Defined(NoScripts)
, SysUtils
, l3Base
//#UC START# *552BF69B039Bimpl_uses*
//#UC END# *552BF69B039Bimpl_uses*
;
var g_Tl3AutolinkService: Tl3AutolinkService = nil;
{* Экземпляр синглетона Tl3AutolinkService }
procedure Tl3AutolinkServiceFree;
{* Метод освобождения экземпляра синглетона Tl3AutolinkService }
begin
l3Free(g_Tl3AutolinkService);
end;//Tl3AutolinkServiceFree
procedure Tl3AutolinkService.pm_SetAlien(const aValue: Il3AutolinkService);
begin
Assert((f_Alien = nil) OR (aValue = nil));
f_Alien := aValue;
end;//Tl3AutolinkService.pm_SetAlien
function Tl3AutolinkService.GetAutolinkFilter: Ik2TagGenerator;
//#UC START# *552BF6BD0156_552BF69B039B_var*
//#UC END# *552BF6BD0156_552BF69B039B_var*
begin
//#UC START# *552BF6BD0156_552BF69B039B_impl*
if (f_Alien <> nil) then
Result := f_Alien.GetAutolinkFilter
else
Result := nil;
//#UC END# *552BF6BD0156_552BF69B039B_impl*
end;//Tl3AutolinkService.GetAutolinkFilter
procedure Tl3AutolinkService.CleanAutolinkFilter;
//#UC START# *552BF6FF02A9_552BF69B039B_var*
//#UC END# *552BF6FF02A9_552BF69B039B_var*
begin
//#UC START# *552BF6FF02A9_552BF69B039B_impl*
if (f_Alien <> nil) then
f_Alien.CleanAutolinkFilter;
//#UC END# *552BF6FF02A9_552BF69B039B_impl*
end;//Tl3AutolinkService.CleanAutolinkFilter
class function Tl3AutolinkService.Instance: Tl3AutolinkService;
{* Метод получения экземпляра синглетона Tl3AutolinkService }
begin
if (g_Tl3AutolinkService = nil) then
begin
l3System.AddExitProc(Tl3AutolinkServiceFree);
g_Tl3AutolinkService := Create;
end;
Result := g_Tl3AutolinkService;
end;//Tl3AutolinkService.Instance
class function Tl3AutolinkService.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_Tl3AutolinkService <> nil;
end;//Tl3AutolinkService.Exists
procedure Tl3AutolinkService.ClearFields;
begin
Alien := nil;
inherited;
end;//Tl3AutolinkService.ClearFields
end.
|
{ 解析网页的公共方法,类 }
unit HtmlParseUtils;
interface
uses
mshtml, Windows, Classes, SysUtils, StrUtils, ActiveX, Contnrs, ExtCtrls,
SHDocVW, Graphics, Messages;
const
WM_PROCESS_YESNODLG = WM_USER + $9801;
WM_REMOVE_OBJ = WM_USER + $9802;
type
EHtmlParseException = class(Exception)
end;
{ 表格数据支持.提供者可以是网页,excel文件或文本文件 }
IGridDataProvider = interface
{ todo: a column name x-reference table required }
function GetCell(AColName: string): string;
function GetCellDef(AColName: string; const ADef: string = ''): string;
function GetCellHtmlDef(AColName: string; const ADef: string = ''): string;
property Cells[AColName: string]: string read GetCell; default;
end;
{ 处理横表,整个表表示一条记录.它的奇数列指出名字,偶数列为值. }
THorizTableParser = class(TObject, IGridDataProvider)
private
FCells: TStringList; // colnames & colvalues mixed
public
constructor Create(ATable: IHTMLTable); reintroduce;
destructor Destroy; override;
{ 特殊表格调用.设置第一个可识别的列名.在此列之前的单元格均被裁剪掉. }
procedure SetFirstColumn(const ACol: string);
function GetCell(AColName: string): string;
property Cells[AColName: string]: string read GetCell; default;
function GetCellDef(AColName: string; const ADef: string = ''): string;
function GetCellHtmlDef(AColName: string; const ADef: string = ''): string;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{ 处理交叉表,第一列为列头,第一行为表头,一对表头和列头定位一个单元格 }
TCrossTableParser = class(TObject)
private
FColHeader, FRowHeader: TStringList;
FTable: IHTMLTable;
public
constructor Create(ATable: IHTMLTable); reintroduce;
destructor Destroy; override;
function ParseHeader(ColHeader: array of string): Boolean;
function GetCellDef(AColName, ARowName: string; const ADef: string = ''): string;
end;
{ 处理第一列为表头(或用ParseHeaderWithCols指出表头包含的列),以下列为表内容的表格 }
TSimpleTableParser = class(TObject, IGridDataProvider)
private
FCols: TStringList; // colname, object=integer of col index
FRowIndex: Integer;
FTable: IHTMLTable;
function GetCell(AColName: string): string;
function GetRowCount: Integer;
procedure ParseHeader;
public
constructor Create(ATable: IHTMLTable); reintroduce;
destructor Destroy; override;
{ 特殊表格调用。处理一个包含给定表头的行 }
procedure ParseHeaderWithCols(Cols: array of string);
property Cells[AColName: string]: string read GetCell; default;
function GetCellDef(AColName: string; const ADef: string = ''): string; overload;
function GetCellDef(AColIndex: Integer; const ADef: string = ''): string; overload;
function GetCellHtmlDef(AColName: string; const ADef: string = ''): string;
function GetTableCell(AColName: string): IHTMLElement;
function GetRow: IHTMLTableRow;
function BackRow: Boolean;
function NextRow: Boolean;
procedure Reset;
property RowCount: Integer read GetRowCount;
function EOT: Boolean;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{ 处理导出文件的基类.纯虚类.接口尽量简单. }
TCommonExchangeFileParserBase = class(TObject, IGridDataProvider)
public
constructor Create(AFileName: string); virtual; abstract;
destructor Destroy; override; abstract;
function TextExists(AText: string): Boolean; virtual; abstract;
function ParseHeader(ARequiredCols: array of string): Boolean; virtual; abstract;
function NextRow: Boolean; virtual; abstract;
function EOT: Boolean; virtual; abstract;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function GetCell(AColName: string): string; virtual; abstract;
function GetCellDef(AColName: string; const ADef: string = ''): string; virtual; abstract;
function GetCellHtmlDef(AColName: string; const ADef: string = ''): string; virtual; abstract;
property Cells[AColName: string]: string read GetCell; default;
end;
{ 处理逗号分隔的CSV文件 }
TCSVGridParser = class(TCommonExchangeFileParserBase)
private
FCols: TStringList;
FLines: TStringList;
FLineSplitted: TStringList;
FCurLine: Integer;
FLastLine: Integer;
protected
procedure LineSplittedRequired;
function RefineCell(S: string): string;
public
constructor Create(AFileName: string); reintroduce;
destructor Destroy; override;
function TextExists(AText: string): Boolean; override;
function ParseHeader(ARequiredCols: array of string): Boolean; override;
function NextRow: Boolean; override;
function EOT: Boolean; override;
function GetCell(AColName: string): string; override;
function GetCellDef(AColName: string; const ADef: string = ''): string; override;
property Cells; default;
end;
TMultiPageParseHelper = class;
TOnGetPageOKProc = procedure (ASender: TMultiPageParseHelper; var PageOK: Boolean) of object;
TOnAnalysePageProc = procedure (ASender: TMultiPageParseHelper) of object;
TOnGetIsLastPageProc = procedure (ASender: TMultiPageParseHelper; var IsLastPage: Boolean) of object;
TOnNextPageProc = procedure (ASender: TMultiPageParseHelper) of object;
TOnAllPageOK = procedure (ASender: TMultiPageParseHelper) of object;
TOnGetHtmlProc = procedure (ASender: TMultiPageParseHelper; var aNewHtml: string) of object;
{ 处理分多页的表格/页面 }
TMultiPageParseHelper = class
private
FTimer: TTimer;
FLastHtml: string;
FDocument: IHTMLDocument2;
FPageIndex: Integer;
FOnAllPageOK: TOnAllPageOK;
FOnAnalysePage: TOnAnalysePageProc;
FOnGetIsLastPage: TOnGetIsLastPageProc;
FOnGetPageOK: TOnGetPageOKProc;
FOnNextPage: TOnNextPageProc;
FIfCompareHtml: Boolean;
FOnGetHtml: TOnGetHtmlProc;
protected
function IsPageOK: Boolean; virtual;
procedure AnalysePage; virtual;
function IsLastPage: Boolean; virtual;
procedure NextPage; virtual;
procedure AllPageOK; virtual;
function GetHtml: string; virtual;
procedure OnTimer(Sender: TObject);
public
constructor Create; reintroduce;
destructor Destroy; override;
{ 当前分析的页 }
property PageIndex: Integer read FPageIndex;
{ 开始分析 }
procedure Start(ADoc: IHTMLDocument2);
{ 停止分析 }
procedure Stop;
{ 当前页是否加载完成 }
property OnGetPageOK: TOnGetPageOKProc read FOnGetPageOK write FOnGetPageOK;
{ 分析当前页 }
property OnAnalysePage: TOnAnalysePageProc read FOnAnalysePage write FOnAnalysePage;
{ 是否是最后一页 }
property OnGetIsLastPage: TOnGetIsLastPageProc read FOnGetIsLastPage write FOnGetIsLastPage;
{ 前往下一页 }
property OnNextPage: TOnNextPageProc read FOnNextPage write FOnNextPage;
{ 所有页分析完成 }
property OnAllPageOK: TOnAllPageOK read FOnAllPageOK write FOnAllPageOK;
{ 是否比较两次页面 (相同则不进行页面分析) }
property IfCompareHtml: Boolean read FIfCompareHtml write FIfCompareHtml;
{ 比较网页时,可由外部确定比较网页的内容(当网页的变化是在Frame中时,就得用这个) }
property OnGetHtml: TOnGetHtmlProc read FOnGetHtml write FOnGetHtml;
end;
{ 全局类,内部使用.自动捕捉IE弹出的脚本错误对话框,并且对"是否继续运行脚本"点它的"是"按钮
(只对主线程有效) }
TIEPopupDialogWatcher = class
private
FHandle: HWND;
protected
procedure WndProc(var Msg: TMessage);
procedure OnProcessYesNoDlg(var Msg: TMessage); message WM_PROCESS_YESNODLG;
public
constructor Create;
destructor Destroy; override;
property Handle: HWND read FHandle;
end;
TNavigateAndCallFunc = procedure(AWB: TWebBrowser; var Done: Boolean) of object;
// 得到某一帧的document
function GetFrameEleColl(FrameNum: OleVariant; HtmlDoc: IHTMLDocument2):
IHTMLdocument2;
// 比较两个字符串是否互相包含
function CompareInnerText(s1,s2:string;ACase:boolean):boolean;
// 触发innertext=xxx的链接
function HrefClick(SoucEleColl:OleVariant;Const AText:string;ACase:Boolean=false):boolean;
// 触发href=xxx的链接
function HrefClickByHrefStr(SoucEleColl:OleVariant;Const AText:string;ACase:Boolean=false):boolean;
// 根据某一属性查找对象
function LocateObject(SoucEleColl:OleVariant;Const TgName,AText,AttrStr:string):OleVariant;
// 从一个窗口中查找它容纳的IHTMLDocument2对象(会自动查找子窗口) IE5.5
function GetIHTMLDocumentFromHWND(const H: HWND): IHTMLDocument2;
{ 查找给出id的frame(递归) }
function FindFrameByID(Doc: IHTMLDocument2; const FrameID: string): IHTMLWindow2;
{ 获取给出id的select项的选中文字 }
function GetSelectOptionText(ADoc: IHTMLDocument2; const SelectID: string): string;
{ 查找包含所有给出列名的table(注:既查找纵表,也查找横表) }
function FindTableWithColumns(ADoc: IHTMLDocument2; Cols: array of string; const aHeadTag: string = 'td'; const aTabIndex: Integer = 0): IHTMLTable;
{ 处理带','号的字符串币种 }
function MWStrToCurrDef(S: string; ADef: Currency): Currency;
{ 获得某select框的所有选项和值列表.ATexts,AValues由调用方创建 }
function GetSelectOptions(ADoc: IHTMLDocument2; ASelectId: string; ATexts, AValues: TStrings): Boolean;
{ 从IHTMLIMGElement中抓取图像.Bmp由调用方创建和释放. }
function CaptureHtmlImg(const AImg: IHTMLIMGElement; var Bmp: TBitmap): Boolean;
{ 设置select框的选项 }
function SetSelectOption(ADoc: IHTMLDocument2; ASelectId: string; AOption: string): Boolean;
function SetSelectOptionByValue(ADoc: IHTMLDocument2; ASelectId: string; AValue: string): Boolean;
{ 设置input框的文本 }
function SetInputTagText(ADoc: IHTMLDocument2; AInputId: string; AText: string): Boolean;
{ 浏览器访问网页,在其完成后调用给出方法.若方法返回未完成,则持续调用直到完成;若超时无结果,则调用超时方法.
* !!! * 在ACallback或ATimeoutFunc对象析构时必须调用UnregisterCallerObject方法移除所有相关回调对象。 }
{ NOTE: This function has been prooved very *BUGGY*, use CallUntilDone instead. }
procedure NavigateAndCall(AWB: TWebBrowser; AUrl: string; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent = nil); deprecated;
{ 在定时器中不断尝试调用ACallback,直到ACallback返回Done=TRUE或者超时。超时则调用ATimeoutFunc,
* !!! * 在ACallback或ATimeoutFunc对象析构时必须调用UnregisterCallerObject方法移除所有相关回调对象。 }
procedure CallUntilDone(AWB: TWebBrowser; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent = nil);
{ 移除对象所有相关回调对象 }
procedure UnregisterCallerObject(AObject: TObject);
{ 检查表格是否包含给出的所有单元格 }
function IsTableContainCells(const ATable: IHTMLTable; const ACells: array of string): Boolean;
{ 查找给出的tag和class的元素.找不到返回nil }
function FindElemByTagAndClass(ADoc: IHTMLDocument2; const ATagName, AClassName: string): IHTMLElement;
function FindElemByTagAndID(ADoc: IHTMLDocument2; const ATagName, AID: string): IHTMLElement;
function FindElemByTagAndText(ADoc: IHTMLDocument2; const ATagName, AText: string): IHTMLElement;
function FindElemByTagAndTitle(ADoc: IHTMLDocument2; const ATagName, ATitle: string): IHTMLElement;
{ 根据value查找Input }
function FindButtonByValue(ADoc: IHTMLDocument2; const aValue: string): IHTMLButtonElement;
function FindInputByValue(ADoc: IHTMLDocument2; const aValue: string): IHTMLInputElement;
function FindInputByName(ADoc: IHTMLDocument2; const aName: string): IHTMLInputElement;
{ 根据src属性查找img对象 }
function FindIMGBySRC(ADoc: IHTMLDocument2; const aSRC: string): IHTMLImgElement;
{ 计算HTML元素的区域。相对于Document的区域 }
function CalcElementClientRect(AElem: IHTMLElement): TRect;
{ 计算HTML元素的区域,方法2 }
function CalcElementClientRect2(AElem, ABody: IHTMLElement): TRect;
{ 调用一个IDispatch对象的方法 }
function SafeFireEvent(ADisp: IDispatch; AEventName: string; Params: array of const): Boolean;
{ 使用post方法提交数据给iframe }
procedure FramePostData(AWB: TWebBrowser; AUrl: string; APostData: string; AFrameId: string);
{ 设置自定义控件文本。它必须实现IOleWindow接口,并且是通过GetFocus来判断是否被激活的。 }
procedure SetCustomActiveXControlText(AElem: IHTMLElement; AText: string; ADllName: string);
{ 调用ImmDisableIME API禁止本线程使用IME。插件创建Browser窗口前调用。 }
procedure DisableCurrentThreadIME;
implementation
uses
CommCtrl, Forms, Variants, IMM, SyncObjs;
type
TNavigateAndCallObj = class
private
FWB: TWebBrowser;
FUrl: string;
FTimer: TTimer;
FTimerTimeout: TTimer;
FOldDocumentComplete: TWebBrowserDocumentComplete;
FCallback: TNavigateAndCallFunc;
FOnTimeout: TNotifyEvent;
private
procedure OnTimer(Sender: TObject);
procedure OnTimeout(Sender: TObject);
public
constructor Create(AWB: TWebBrowser; AUrl: string; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent = nil); reintroduce;
destructor Destroy; override;
procedure OnDocumentComplete(Sender: TObject; const pDisp: IDispatch; var URL: OleVariant);
end;
TCallUntilDoneObj = class
private
FWB: TWebBrowser;
FTimer: TTimer;
FCallback: TNavigateAndCallFunc;
FTimeCount: Integer;
FTimeoutFunc: TNotifyEvent;
private
procedure OnTimer(Sender: TObject);
public
constructor Create(AWB: TWebBrowser; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent);
destructor Destroy; override;
end;
TTempObjList = class(TList)
private
FHandle: HWND;
procedure WndProc(var Msg: TMessage);
public
constructor Create;
{ **Note** AObj is type of TCallUntilDoneObj or TNavigateAndCallObj }
procedure Remove(AObj: TObject); reintroduce;
{ * Remove all TCallUntilDoneObj/TNavigateAndCallObj which contain object pointers to the caller object * }
procedure OnCallerDestroyed(ACaller: TObject);
destructor Destroy; override;
procedure Add(AObj: TObject); reintroduce;
property Handle: HWND read FHandle;
end;
var
l_IEPopupDialogWatcher: TIEPopupDialogWatcher;
l_OldCallWndProcHook: HHOOK = 0;
l_TempObjList: TTempObjList;
//得到某一帧的document
function GetFrameEleColl(FrameNum: OleVariant; HtmlDoc: IHTMLDocument2):
IHTMLdocument2;
var
Nw:IHTMLWindow2;
HF:IHTMLFramesCollection2;
spDisp : IDispatch;
begin
HF:=HtmlDoc.frames;
spDisp:=HF.item(FrameNum);
if SUCCEEDED(spDisp.QueryInterface(IHTMLWindow2 ,Nw))then
begin
result:=(Nw.document as IHTMLdocument2);
end;
end;
function CompareInnerText(s1,s2:string;ACase:boolean):boolean;
begin
result:=false;
if ACase then
begin
if pos(s2,s1)>0 then
result:=true;
end
else
if (Trim(s1)=Trim(s2)) then
result:=true;
end;
//触发innertext=xxx的链接
function HrefClick(SoucEleColl:OleVariant;Const AText:string;ACase:Boolean=false):boolean;
var
Item,FAll:OleVariant;
i:integer;
begin
result:=false;
FAll:=SoucEleColl.Tags('A');
for i:=0 to FAll.length-1 do
begin
item:=FAll.item(i);
if CompareInnerText(item.innerText,AText,ACase) then
begin
item.click;
result:=true;
break;
end;
end
end;
//触发href=xxx的链接
function HrefClickByHrefStr(SoucEleColl:OleVariant;Const AText:string;ACase:Boolean=false):boolean;
var
Item,FAll:OleVariant;
i:integer;
begin
result:=false;
FAll:=SoucEleColl.Tags('A');
for i:=0 to FAll.length-1 do
begin
item:=FAll.item(i);
if CompareInnerText(item.href,AText,ACase) then
begin
item.click;
result:=true;
break;
end;
end
end;
//根据某一属性查找对象
function LocateObject(SoucEleColl:OleVariant;Const TgName,AText,AttrStr:string):OleVariant;
var
Item,FAll:OleVariant;
i:integer;
begin
FAll:=SoucEleColl.Tags(TgName);
for i:=0 to FAll.length-1 do
begin
item:=FAll.item(i);
if Trim(item.getAttribute(AttrStr))=Trim(AText) then
begin
result:=item;
break;
end;
end;
end;
type
PHWND = ^HWND;
function __EnumChildWindowsProc(H: HWND; lp: LPARAM): LongBool; stdcall;
var
ClsName: string;
begin
SetLength(ClsName, 32);
SetLength(ClsName, GetClassName(H, PChar(ClsName), 32));
OutputDebugString(PChar(ClsName));
if ClsName = 'Internet Explorer_Server' then
begin
PHWND(lp)^ := H;
Result := False;
Exit;
end;
Result := True;
end;
function GetIHTMLDocumentFromHWND(const H: HWND): IHTMLDocument2;
type
TObjectFromLresultFunc = function (lr: LRESULT; const riid: TIID; wp: WPARAM; var pObj: IUnknown): HRESULT; stdcall;
var
LibHandle: HMODULE;
ObjectFromLresult: TObjectFromLresultFunc;
lr: Cardinal;
Msg: UINT;
Obj: IUnknown;
TargetWnd: HWND;
ClsName: string;
begin
Result := nil;
TargetWnd := 0;
SetLength(ClsName, 32);
SetLength(ClsName, GetClassName(H, PChar(ClsName), 32));
if ClsName = 'Internet Explorer_Server' then TargetWnd := H
else EnumChildWindows(H, @__EnumChildWindowsProc, Integer(@TargetWnd));
if TargetWnd = 0 then Exit;
CoInitialize(nil);
try
LibHandle := LoadLibrary('oleacc.dll');
if LibHandle = 0 then Exit;
try
Msg := RegisterWindowMessage('WM_HTML_GETOBJECT');
SendMessageTimeout(TargetWnd, Msg, 0, 0, SMTO_ABORTIFHUNG, 1000, lr);
@ObjectFromLresult := GetProcAddress(LibHandle, 'ObjectFromLresult');
if @ObjectFromLresult = nil then Exit;
ObjectFromLresult(lr, IID_IHTMLDocument2, 0, Obj);
if (Obj <> nil) and Supports(Obj, IID_IHTMLDocument2) then Result := Obj as IHTMLDocument2;
finally
FreeLibrary(LibHandle);
end;
finally
CoUninitialize;
end;
end;
{ 查找给出id的frame(递归) }
function FindFrameByID(Doc: IHTMLDocument2; const FrameID: string): IHTMLWindow2;
var
I: Integer;
ItemID: OleVariant;
Elem: IHTMLWindow2;
begin
Result := nil;
for I := 0 to Doc.frames.length - 1 do
begin
ItemID := I;
Elem := IDispatch(Doc.frames.item(ItemID)) as IHTMLWindow2;
if SameText(Elem.name, FrameID) then
begin
Result := Elem;
Exit;
end;
Result := FindFrameByID(Elem.document, FrameID);
if Result <> nil then Exit;
end;
end;
{ 获取给出id的select项的选中文字 }
function GetSelectOptionText(ADoc: IHTMLDocument2; const SelectID: string): string;
var
Elem: IHTMLElement;
Select: IHTMLSelectElement;
begin
Elem := (ADoc.all as IHTMLElementCollection).item(SelectID, 0) as IHTMLElement;
if not Supports(Elem, IHTMLSelectElement) then Exit;
Select := Elem as IHTMLSelectElement;
if Select.selectedIndex < 0 then Exit;
try
Elem := Select.item(Select.selectedIndex, 0) as IHTMLElement;
except
Exit;
end;
if not Supports(Elem, IHTMLOptionElement) then Exit;
Result := (Elem as IHTMLOptionElement).text;
end;
function FindTableWithColumns(ADoc: IHTMLDocument2; Cols: array of string; const aHeadTag: string; const aTabIndex: Integer): IHTMLTable;
function FindSubTables(AAll: IHTMLElementCollection; Cols: array of string; const aTabIndex: Integer): IHTMLTable;
var
Tags, Cells: IHTMLElementCollection;
Table: IHTMLTable;
Elem: IHTMLElement;
I, J, Index, N: Integer;
SL: TStringList;
vTabIndex: Integer;
begin
Result := nil;
vTabIndex := aTabIndex;
Tags := AAll.tags('table') as IHTMLElementCollection;
SL := TStringList.Create;
try
SL.Sorted := True;
for I := Low(Cols) to High(Cols) do SL.Add(Cols[I]);
for I := 0 to Tags.length - 1 do
begin
Table := Tags.item(I, 0) as IHTMLTable;
for J := 0 to SL.Count - 1 do SL.Objects[J] := TObject(0);
N := SL.Count;
Cells := ((Table as IHTMLElement).all as IHTMLElementCollection).tags(aHeadTag) as IHTMLElementCollection;
for J := 0 to Cells.length - 1 do
begin
Elem := Cells.item(J, 0) as IHTMLElement;
Index := SL.IndexOf(Trim(Elem.innerText));
if Index < 0 then Continue;
if Integer(SL.Objects[Index]) <> 0 then Continue;
SL.Objects[Index] := TObject(1);
Dec(N);
if N = 0 then
begin
if vTabIndex > 0 then
begin
Dec(vTabIndex);
Break;
end;
Result := Table;
// 找尽可能小的table
Table := FindSubTables((Table as IHTMLElement).all as IHTMLElementCollection, Cols, aTabIndex);
if Table <> nil then Result := Table;
Exit;
end;
end;
end;
finally
FreeAndNil(SL);
end;
end;
begin
Result := FindSubTables(ADoc.all, Cols, aTabIndex);
end;
{ TSimpleTableParser }
function TSimpleTableParser.BackRow: Boolean;
var
Row: IHTMLTableRow;
begin
Result := False;
if FRowIndex <= 0 then Exit;
Dec(FRowIndex);
if FRowIndex <= 0 then Exit;
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
if Row.cells.length <> FCols.Count then Result := BackRow // not a valid row
else Result := True;
end;
constructor TSimpleTableParser.Create(ATable: IHTMLTable);
begin
FRowIndex := 0;
FCols := TStringList.Create;
FTable := ATable;
ParseHeader;
end;
destructor TSimpleTableParser.Destroy;
begin
FreeAndNil(FCols);
inherited;
end;
function TSimpleTableParser.EOT: Boolean;
begin
Result := FRowIndex >= FTable.rows.length;
end;
function TSimpleTableParser.GetCell(AColName: string): string;
var
Row: IHTMLTableRow;
Index: Integer;
Elem: IHTMLElement;
begin
if FRowIndex >= FTable.rows.length then raise EHtmlParseException.Create('index out of range');
Index := FCols.IndexOf(AColName);
if Index < 0 then raise EHtmlParseException.CreateFmt('column %s not found', [AColName]);
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
Elem := Row.cells.item(Index, 0) as IHTMLElement;
Result := Trim(Elem.innerText);
end;
function TSimpleTableParser.GetCellDef(AColName: string;
const ADef: string): string;
var
Row: IHTMLTableRow;
Index: Integer;
Elem: IHTMLElement;
begin
if FRowIndex >= FTable.rows.length then Result := ADef
else
begin
Index := FCols.IndexOf(AColName);
if Index < 0 then Result := ADef
else
begin
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
Elem := Row.cells.item(Index, 0) as IHTMLElement;
Result := Trim(Elem.innerText);
end;
end;
end;
function TSimpleTableParser.GetCellDef(AColIndex: Integer;
const ADef: string): string;
var
Row: IHTMLTableRow;
Index: Integer;
Elem: IHTMLElement;
begin
if FRowIndex >= FTable.rows.length then Result := ADef
else
begin
Index := AColIndex;
if Index < 0 then Result := ADef
else
begin
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
Elem := Row.cells.item(Index, 0) as IHTMLElement;
Result := Trim(Elem.innerText);
end;
end;
end;
function TSimpleTableParser.GetCellHtmlDef(AColName: string;
const ADef: string): string;
var
Row: IHTMLTableRow;
Index: Integer;
Elem: IHTMLElement;
begin
if FRowIndex >= FTable.rows.length then Result := ADef
else
begin
Index := FCols.IndexOf(AColName);
if Index < 0 then Result := ADef
else
begin
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
Elem := Row.cells.item(Index, 0) as IHTMLElement;
Result := Trim(Elem.innerHTML);
end;
end;
end;
function TSimpleTableParser.GetRow: IHTMLTableRow;
begin
if FRowIndex >= FTable.rows.length then
Result := nil
else
Result := FTable.rows.item(FRowIndex, FRowIndex) as IHTMLTableRow;
end;
function TSimpleTableParser.GetRowCount: Integer;
begin
Result := FTable.rows.length - 1;
end;
function TSimpleTableParser.GetTableCell(AColName: string): IHTMLElement;
var
Index: Integer;
Row: IHTMLTableRow;
begin
if FRowIndex >= FTable.rows.length then Result := nil
else
begin
Index := FCols.IndexOf(AColName);
if Index < 0 then Result := nil
else
begin
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
Result := Row.cells.item(Index, 0) as IHTMLElement;
end;
end;
end;
function TSimpleTableParser.NextRow: Boolean;
var
Row: IHTMLTableRow;
begin
Result := False;
if FRowIndex >= FTable.rows.length then Exit;
Inc(FRowIndex);
if FRowIndex >= FTable.rows.length then Exit;
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
if Row.cells.length <> FCols.Count then Result := NextRow // not a valid row
else Result := True;
end;
procedure TSimpleTableParser.ParseHeader;
var
I: Integer;
Row: IHTMLTableRow;
Elem: IHTMLElement;
begin
Row := FTable.rows.item(0, 0) as IHTMLTableRow;
FCols.Clear;
for I := 0 to Row.cells.length - 1 do
begin
Elem := Row.cells.item(I, 0) as IHTMLElement;
FCols.Add(Trim(Elem.innerText));
end;
Reset;
end;
procedure TSimpleTableParser.ParseHeaderWithCols(Cols: array of string);
var
I, J, K, L: Integer;
Row: IHTMLTableRow;
S: string;
Elem: IHTMLElement;
Found: Boolean;
begin
FCols.Clear;
for I := 0 to FTable.rows.length - 1 do
begin
Row := FTable.rows.item(I, 0) as IHTMLTableRow;
for J := Low(Cols) to High(Cols) do
begin
S := Cols[J];
Found := False;
for K := 0 to Row.cells.length - 1 do
begin
Elem := Row.cells.item(K, 0) as IHTMLElement;
if SameText(Trim(Elem.innerText), S) then
begin
Found := True;
Break;
end;
end;
if not Found then Break
else if J = High(Cols) then
begin
// the last one found, parse then row
for L := 0 to Row.cells.length - 1 do
begin
Elem := Row.cells.item(L, 0) as IHTMLElement;
FCols.Add(Trim(Elem.innerText));
end;
Reset;
Exit;
end;
end;
end;
end;
function TSimpleTableParser.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
Result := E_NOTIMPL;
end;
procedure TSimpleTableParser.Reset;
var
Row: IHTMLTableRow;
begin
FRowIndex := 0;
// 第一个满足条件的行:表头
repeat
if FRowIndex >= FTable.rows.length then Exit;
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
if Row.cells.length = FCols.Count then Break;
Inc(FRowIndex);
until False;
Inc(FRowIndex);
// 第二个满足条件的行:第一条数据
repeat
if FRowIndex >= FTable.rows.length then Exit;
Row := FTable.rows.item(FRowIndex, 0) as IHTMLTableRow;
if Row.cells.length = FCols.Count then Break;
Inc(FRowIndex);
until False;
end;
function MWStrToCurrDef(S: string; ADef: Currency): Currency;
begin
S := AnsiReplaceText(S, '$', '');
S := AnsiReplaceText(S, '$', '');
S := AnsiReplaceText(S, '¥', '');
S := AnsiReplaceText(S, '元', '');
S := AnsiReplaceText(S, ' ', '');
Result := StrToCurrDef(AnsiReplaceText(S, ',', ''), ADef);
end;
function TSimpleTableParser._AddRef: Integer;
begin
Result := 0;
end;
function TSimpleTableParser._Release: Integer;
begin
Result := 0;
end;
{ TMultiPageParseHelper }
procedure TMultiPageParseHelper.AllPageOK;
begin
if Assigned(FOnAllPageOK) then FOnAllPageOK(Self);
end;
procedure TMultiPageParseHelper.AnalysePage;
begin
if Assigned(FOnAnalysePage) then FOnAnalysePage(Self);
end;
constructor TMultiPageParseHelper.Create;
begin
FDocument := nil;
FTimer := TTimer.Create(nil);
FTimer.Interval := 1000;
FTimer.Enabled := False;
FTimer.OnTimer := OnTimer;
FIfCompareHtml := True;
FLastHtml := '';
end;
destructor TMultiPageParseHelper.Destroy;
begin
FreeAndNil(FTimer);
FDocument := nil;
inherited;
end;
function TMultiPageParseHelper.GetHtml: string;
begin
Result := '';
if Assigned(FOnGetHtml) then
FOnGetHtml(Self, Result)
else if FDocument.body <> nil then
Result := FDocument.body.innerHTML;
end;
function TMultiPageParseHelper.IsLastPage: Boolean;
begin
if Assigned(FOnGetIsLastPage) then FOnGetIsLastPage(Self, Result)
else raise EHtmlParseException.Create('not assigned OnGetIsLastPage!');
end;
function TMultiPageParseHelper.IsPageOK: Boolean;
begin
if Assigned(FOnGetPageOK) then FOnGetPageOK(Self, Result)
else raise EHtmlParseException.Create('not assigned OnGetPageOK!');
end;
procedure TMultiPageParseHelper.NextPage;
begin
if Assigned(FOnNextPage) then FOnNextPage(Self)
else raise EHtmlParseException.Create('not assigned OnNextPage!');
end;
procedure TMultiPageParseHelper.OnTimer(Sender: TObject);
var
Done: Boolean;
NewHtml: string;
Succ: Boolean;
begin
Done := False;
FTimer.Enabled := False;
try
if IsPageOK then
begin
NewHtml := GetHtml;
if FIfCompareHtml and (FLastHtml <> '') and (FLastHtml = NewHtml) then Exit;
AnalysePage;
FLastHtml := NewHtml;
if IsLastPage then
begin
AllPageOK;
Done := True;
end
else
begin
Inc(FPageIndex);
Succ := False;
repeat
try
// user can raise an EAbort exception to indicate that operation failed
NextPage;
Succ := True;
except
on E: EHtmlParseException do raise
else Succ := False;
end;
if not Succ then Application.ProcessMessages;
until Succ;
end;
end;
finally
if not Done then FTimer.Enabled := True;
end;
end;
procedure TMultiPageParseHelper.Start(ADoc: IHTMLDocument2);
begin
FDocument := ADoc;
FTimer.Enabled := True;
FPageIndex := 0;
FLastHtml := '';
end;
procedure TMultiPageParseHelper.Stop;
begin
FTimer.Enabled := False;
end;
{ TNavigateAndCallObj }
constructor TNavigateAndCallObj.Create(AWB: TWebBrowser; AUrl: string;
ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent);
begin
FWB := AWB;
FCallback := ACallback;
FUrl := AUrl;
FOldDocumentComplete := FWB.OnDocumentComplete;
FWB.OnDocumentComplete := OnDocumentComplete;
FWB.Navigate(FUrl);
FTimer := TTimer.Create(nil);
FTimer.Enabled := False;
FTimer.Interval := 2000;
FTimer.OnTimer := OnTimer;
FTimerTimeout := TTimer.Create(nil);
FTimerTimeout.Enabled := True;
FTimerTimeout.Interval := 80000;
FTimerTimeout.OnTimer := OnTimeout;
FOnTimeout := ATimeoutFunc;
end;
destructor TNavigateAndCallObj.Destroy;
begin
FWB.OnDocumentComplete := FOldDocumentComplete;
FreeAndNil(FTimer);
FreeAndNil(FTimerTimeout);
l_TempObjList.Remove(Self);
inherited;
end;
procedure TNavigateAndCallObj.OnDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
Done: Boolean;
begin
if Assigned(FOldDocumentComplete) then FOldDocumentComplete(Sender, pDisp, URL);
Done := False;
FTimer.Enabled := False;
FTimerTimeout.Enabled := False;
FCallback(FWB, Done);
if Done then PostMessage(l_TempObjList.Handle, WM_REMOVE_OBJ, 0, Integer(Self)) //Self.Free
else
begin
FTimer.Enabled := True;
FTimerTimeout.Enabled := True;
end;
end;
procedure TNavigateAndCallObj.OnTimeout(Sender: TObject);
begin
FTimer.Enabled := False;
FTimerTimeout.Enabled := False;
FWB.OnDocumentComplete := FOldDocumentComplete;
if Assigned(FOnTimeout) then FOnTimeout(Self);
Self.Free;
end;
procedure TNavigateAndCallObj.OnTimer(Sender: TObject);
var
Done: Boolean;
begin
FTimer.Enabled := False;
FTimerTimeout.Enabled := False;
FCallback(FWB, Done);
if Done then Self.Free
else
begin
FTimer.Enabled := True;
FTimerTimeout.Enabled := True;
end;
end;
procedure NavigateAndCall(AWB: TWebBrowser; AUrl: string; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent);
begin
l_TempObjList.Add(TNavigateAndCallObj.Create(AWB, AUrl, ACallback, ATimeoutFunc));
end;
procedure CallUntilDone(AWB: TWebBrowser; ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent);
begin
l_TempObjList.Add(TCallUntilDoneObj.Create(AWB, ACallback, ATimeoutFunc));
end;
function FindElemByTagAndClass(ADoc: IHTMLDocument2; const ATagName, AClassName: string): IHTMLElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLElement;
begin
Result := nil;
Tags := ADoc.all.tags(ATagName) as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLElement;
if SameText(Elem.className, AClassName) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindElemByTagAndID(ADoc: IHTMLDocument2; const ATagName, AID: string): IHTMLElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLElement;
begin
Result := nil;
Tags := ADoc.all.tags(ATagName) as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLElement;
if SameText(Elem.id, AID) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindElemByTagAndText(ADoc: IHTMLDocument2; const ATagName, AText: string): IHTMLElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLElement;
begin
Result := nil;
Tags := ADoc.all.tags(ATagName) as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLElement;
if SameText(Elem.innerText, aText) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindElemByTagAndTitle(ADoc: IHTMLDocument2; const ATagName, ATitle: string): IHTMLElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLElement;
begin
Result := nil;
Tags := ADoc.all.tags(ATagName) as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLElement;
if SameText(Elem.title, ATitle) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindButtonByValue(ADoc: IHTMLDocument2; const aValue: string): IHTMLButtonElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLButtonElement;
begin
Result := nil;
Tags := ADoc.all.tags('button') as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLButtonElement;
if SameText(Elem.value, aValue) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindInputByValue(ADoc: IHTMLDocument2; const aValue: string): IHTMLInputElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLInputElement;
begin
Result := nil;
Tags := ADoc.all.tags('input') as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLInputElement;
if SameText(Elem.value, aValue) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindInputByName(ADoc: IHTMLDocument2; const aName: string): IHTMLInputElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLInputElement;
begin
Result := nil;
Tags := ADoc.all.tags('input') as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLInputElement;
if SameText(Elem.name, aName) then
begin
Result := Elem;
Exit;
end;
end;
end;
function FindIMGBySRC(ADoc: IHTMLDocument2; const aSRC: string): IHTMLImgElement;
var
Tags: IHTMLElementCollection;
I: Integer;
Elem: IHTMLImgElement;
begin
Result := nil;
Tags := ADoc.all.tags('img') as IHTMLElementCollection;
if (Tags = nil) or (Tags.length = 0) then Exit;
for I := 0 to Tags.length - 1 do
begin
Elem := Tags.item(I, 0) as IHTMLImgElement;
if SameText(Elem.src, aSRC) then
begin
Result := Elem;
Exit;
end;
end;
end;
function GetSelectOptions(ADoc: IHTMLDocument2; ASelectId: string; ATexts, AValues: TStrings): Boolean;
var
Elem: IHTMLElement;
Select: IHTMLSelectElement;
I: Integer;
begin
ATexts.Clear;
AValues.Clear;
Result := False;
Elem := ADoc.all.item(ASelectId, 0) as IHTMLElement;
if not Supports(Elem, IHTMLSelectElement) then Exit;
Select := Elem as IHTMLSelectElement;
for I := 0 to Select.length - 1 do
begin
Elem := Select.item(I, 0) as IHTMLElement;
ATexts.Add(Trim(Elem.innerText));
AValues.Add(Trim((Elem as IHTMLOptionElement).value));
end;
Result := True;
end;
function IsTableContainCells(const ATable: IHTMLTable; const ACells: array of string): Boolean;
var
TDs: IHTMLElementCollection;
Elem: IHTMLElement;
I, J, N: Integer;
FoundArray: array of Boolean;
begin
Result := False;
TDs := ((ATable as IHTMLElement).all as IHTMLElementCollection).tags('td') as IHTMLElementCollection;
if TDs = nil then Exit;
if Length(ACells) = 0 then Exit;
SetLength(FoundArray, Length(ACells));
for I := 0 to High(FoundArray) do FoundArray[I] := False;
N := Length(ACells);
for J := 0 to TDs.length - 1 do
begin
Elem := TDs.item(J, 0) as IHTMLElement;
if Elem = nil then Continue;
for I := 0 to High(ACells) do
begin
if FoundArray[I] then Continue; // already found
if not SameText(Trim(Elem.innerText), ACells[I]) then Continue;
FoundArray[I] := True;
Dec(N);
if N = 0 then // all found
begin
Result := True;
Exit;
end;
end;
end;
end;
type
// *********************************************************************//
// Interface: IHTMLElementRender
// Flags: (0)
// GUID: {3050F669-98B5-11CF-BB82-00AA00BDCE0B}
// *********************************************************************//
IHTMLElementRender = interface(IUnknown)
['{3050F669-98B5-11CF-BB82-00AA00BDCE0B}']
function DrawToDC(hdc: HDC): HResult; stdcall;
function SetDocumentPrinter(const bstrPrinterName: WideString; var hdc: _RemotableHandle): HResult; stdcall;
end;
{ capture an IHTMLImgElement from a page. bmp must be created&freed by the caller.(content maybe modified) }
function CaptureHtmlImg(const AImg: IHTMLIMGElement; var Bmp: TBitmap): Boolean;
begin
Result := False;
if not Supports(AImg, IHTMLElementRender) then Exit;
// LogFmt('width=%d height=%d', [AImg.width, AImg.height]);
if (AImg.width = 0) or (AImg.height = 0) then Exit;
Bmp.Width := AImg.width;
Bmp.Height := AImg.height;
Result := Succeeded((AImg as IHTMLElementRender).DrawToDC(Bmp.Canvas.Handle));
end;
function SetSelectOption(ADoc: IHTMLDocument2; ASelectId: string; AOption: string): Boolean;
var
Elem: IHTMLElement;
Select: IHTMLSelectElement;
I: Integer;
Option: IHTMLOptionElement;
begin
Result := False;
Elem := ADoc.all.item(AselectId, 0) as IHTMLElement;
if Elem = nil then Exit;
if not Supports(Elem, IHTMLSelectElement) then Exit;
Select := Elem as IHTMLSelectElement;
for I := 0 to Select.length - 1 do
begin
Elem := Select.item(I, 0) as IHTMLElement;
if not Supports(Elem, IHTMLOptionElement) then Continue;
Option := Elem as IHTMLOptionElement;
if not SameText(Trim(Option.text), AOption) then Continue;
Select.selectedIndex := I;
SafeFireEvent(Select, 'onchange', []);
Result := True;
Break;
end;
end;
function SetSelectOptionByValue(ADoc: IHTMLDocument2; ASelectId: string; AValue: string): Boolean;
var
Elem: IHTMLElement;
Select: IHTMLSelectElement;
I: Integer;
Option: IHTMLOptionElement;
begin
Result := False;
Elem := ADoc.all.item(AselectId, 0) as IHTMLElement;
if Elem = nil then Exit;
if not Supports(Elem, IHTMLSelectElement) then Exit;
Select := Elem as IHTMLSelectElement;
for I := 0 to Select.length - 1 do
begin
Elem := Select.item(I, 0) as IHTMLElement;
if not Supports(Elem, IHTMLOptionElement) then Continue;
Option := Elem as IHTMLOptionElement;
if not SameText(Trim(Option.value), AValue) then Continue;
Select.selectedIndex := I;
SafeFireEvent(Select, 'onchange', []);
Result := True;
Break;
end;
end;
function SetInputTagText(ADoc: IHTMLDocument2; AInputId: string; AText: string): Boolean;
var
Elem: IHTMLElement;
I: Integer;
begin
Result := False;
I := 0;
while True do
begin
Elem := ADoc.all.item(AInputId, I) as IHTMLElement;
if Elem = nil then Exit;
if Supports(Elem, IHTMLInputElement) then
begin
if SameText((Elem as IHTMLInputElement).type_, 'text')
or SameText((Elem as IHTMLInputElement).type_, 'password')
or SameText((Elem as IHTMLInputElement).type_, 'hidden') then
begin
(Elem as IHTMLInputElement).value := AText;
Result := True;
Exit;
end;
end;
Inc(I);
end;
end;
function CalcElementClientRect(AElem: IHTMLElement): TRect;
var
CR: IHTMLRectCollection;
I: Integer;
R: IHTMLRect;
V: OleVariant;
begin
Result := Rect(0, 0, 0, 0);
CR := (AElem as IHTMLElement2).getClientRects;
if CR.length = 0 then Exit;
V := 0;
R := IUnknown(CR.item(V)) as IHTMLRect;
Result := Rect(R.left, R.top, R.right, R.bottom);
for I := 1 to CR.length - 1 do
begin
V := I;
R := IUnknown(CR.item(V)) as IHTMLRect;
if R.left < Result.Left then Result.Left := R.left;
if R.top < Result.Top then Result.Top := R.top;
if R.right > Result.Right then Result.Right := R.right;
if R.bottom > Result.Bottom then Result.Bottom := R.bottom;
end;
end;
function CalcElementClientRect2(AElem, ABody: IHTMLElement): TRect;
var
W, H: Integer;
begin
W := AElem.offsetWidth;
H := AElem.offsetHeight;
SetRect(Result, (ABody as IHTMLElement2).clientLeft, (ABody as IHTMLElement2).clientTop, 0, 0);
while AElem <> nil do
begin
Inc(Result.Left, AElem.offsetLeft);
Inc(Result.Top, AElem.offsetTop);
AElem := AElem.offsetParent;
if AElem = ABody then Break;
end;
Result.Right := Result.Left + W;
Result.Bottom := Result.Top + H;
end;
{ TCallUntilDoneObj }
constructor TCallUntilDoneObj.Create(AWB: TWebBrowser;
ACallback: TNavigateAndCallFunc; ATimeoutFunc: TNotifyEvent);
begin
FWB := AWB;
FCallback := ACallback;
FTimer := TTimer.Create(nil);
FTimer.Interval := 2000;
FTimer.Enabled := True;
FTimer.OnTimer := OnTimer;
FTimeCount := 40;
end;
destructor TCallUntilDoneObj.Destroy;
begin
FreeAndNil(FTimer);
l_TempObjList.Remove(Self);
inherited;
end;
procedure TCallUntilDoneObj.OnTimer(Sender: TObject);
var
Done: Boolean;
begin
FTimer.Enabled := False;
if Assigned(FCallback) then
begin
try
FCallback(FWB, Done);
except
Done := True;
end;
if Done then
begin
Self.Free;
Exit;
end;
end;
Dec(FTimeCount);
if FTimeCount <= 0 then
begin
if Assigned(FTimeoutFunc) then
begin
try
FTimeoutFunc(Self);
except
;
end;
end;
Self.Free;
Exit;
end;
FTimer.Enabled := True;
end;
{ TCSVGridParser }
constructor TCSVGridParser.Create(AFileName: string);
begin
if not FileExists(AFileName) then
raise EHtmlParseException.CreateFmt('文件%s不存在!', [AFileName]);
FCols := TStringList.Create;
FLines := TStringList.Create;
FLines.LoadFromFile(AFileName);
FLineSplitted := nil;
FCurLine := 0;
FLastLine := -1;
end;
destructor TCSVGridParser.Destroy;
begin
if Assigned(FLineSplitted) then FreeAndNil(FLineSplitted);
FreeAndNil(FLines);
FreeAndNil(FCols);
inherited;
end;
function TCSVGridParser.EOT: Boolean;
begin
Result := FCurLine > FLastLine;
end;
function TCSVGridParser.GetCell(AColName: string): string;
var
I: Integer;
begin
I := FCols.IndexOf(AColName);
if I < 0 then raise EHtmlParseException.CreateFmt('column %s not found', [AColName]);
LineSplittedRequired;
if I >= FLineSplitted.Count then raise EHtmlParseException.Create('index out of range');
Result := RefineCell(Trim(FLineSplitted[I]));
end;
function TCSVGridParser.GetCellDef(AColName: string;
const ADef: string): string;
var
I: Integer;
begin
Result := ADef;
I := FCols.IndexOf(AColName);
if I < 0 then Exit;
LineSplittedRequired;
if I >= FLineSplitted.Count then Exit;
Result := RefineCell(Trim(FLineSplitted[I]));
end;
function TCSVGridParser.NextRow: Boolean;
begin
Result := False;
repeat
if Assigned(FLineSplitted) then FreeAndNil(FLineSplitted);
Inc(FCurLine);
if FCurLine > FLastLine then Exit;
LineSplittedRequired;
if FLineSplitted.Count = FCols.Count then
begin
Result := True;
Exit;
end;
until False;
end;
function TCSVGridParser.ParseHeader(
ARequiredCols: array of string): Boolean;
var
I, J: Integer;
SL: TStringList;
S: string;
begin
if Assigned(FLineSplitted) then FreeAndNil(FLineSplitted);
FCurLine := 0;
Result := False;
// refine texts
for I := 0 to FLines.Count - 1 do
begin
S := Trim(FLines[I]);
while (S <> '') and (S[Length(S)] = ',') do S := Copy(S, 1, Length(S) - 1);
FLines[I] := S;
end;
for I := 0 to FLines.Count - 1 do
begin
FCols.CommaText := FLines[I];
if FCols.Count < Length(ARequiredCols) then Continue;
Result := True;
for J := Low(ARequiredCols) to High(ARequiredCols) do
begin
if FCols.IndexOf(ARequiredCols[J]) < 0 then
begin
Result := False;
Break;
end;
end;
if not Result then Continue;
FCurLine := I + 1;
Break;
end;
if not Result then Exit;
SL := TStringList.Create;
try
FLastLine := -1;
for I := FLines.Count - 1 downto 0 do
begin
SL.CommaText := FLines[I];
if SL.Count = FCols.Count then
begin
FLastLine := I;
Break;
end;
end;
for I := FCurLine to FLastLine do
begin
SL.CommaText := FLines[I];
if SL.Count = FCols.Count then
begin
FCurLine := I;
Break;
end;
end;
finally
FreeAndNil(SL);
end;
end;
procedure TCSVGridParser.LineSplittedRequired;
begin
if not Assigned(FLineSplitted) then
begin
FLineSplitted := TStringList.Create;
FLineSplitted.CommaText := FLines[FCurLine];
end;
end;
function TCSVGridParser.RefineCell(S: string): string;
var
P: PChar;
begin
if S <> '' then
begin
if (S[1] = '''') and (S[Length(S)] = '''') then
begin
P := PChar(S);
Result := Trim(AnsiExtractQuotedStr(P, ''''));
Exit;
end
else if (S[1] = '"') and (S[Length(S)] = '"') then
begin
P := PChar(S);
Result := Trim(AnsiExtractQuotedStr(P, '"'));
Exit;
end;
end;
Result := S;
end;
function TCSVGridParser.TextExists(AText: string): Boolean;
begin
Result := Pos(AText, FLines.Text) > 0;
end;
{ TCommonExchangeFileParserBase }
function TCommonExchangeFileParserBase._AddRef: Integer;
begin
Result := 0;
end;
function TCommonExchangeFileParserBase._Release: Integer;
begin
Result := 0;
end;
function TCommonExchangeFileParserBase.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
Result := E_NOTIMPL;
end;
{ THorizTableParser }
function THorizTableParser._AddRef: Integer;
begin
Result := 0;
end;
function THorizTableParser._Release: Integer;
begin
Result := 0;
end;
function THorizTableParser.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
Result := E_NOTIMPL;
end;
constructor THorizTableParser.Create(ATable: IHTMLTable);
var
TDs: IHTMLElementCollection;
I: Integer;
Cell: IHTMLElement;
begin
FCells := TStringList.Create;
FCells.Sorted := False;
TDs := ((ATable as IHTMLElement).all as IHTMLElementCollection).tags('td') as IHTMLElementCollection;
for I := 0 to TDs.length - 1 do
begin
Cell := TDs.item(I, 0) as IHTMLElement;
FCells.Add(Trim(Cell.innerText));
end;
end;
destructor THorizTableParser.Destroy;
begin
FreeAndNil(FCells);
inherited;
end;
function THorizTableParser.GetCell(AColName: string): string;
var
I: Integer;
begin
I := FCells.IndexOf(AColName);
if I < 0 then raise EHtmlParseException.CreateFmt('col %s does not exists!', [AColName]);
if I + 1 >= FCells.Count then raise EHtmlParseException.CreateFmt('col %s has no value!', [AColName]);
Result := FCells[I + 1];
end;
function THorizTableParser.GetCellDef(AColName: string;
const ADef: string): string;
var
I: Integer;
begin
I := FCells.IndexOf(AColName);
if I < 0 then Result := ADef
else if I + 1 >= FCells.Count then Result := ADef
else Result := FCells[I + 1];
end;
procedure THorizTableParser.SetFirstColumn(const ACol: string);
var
I: Integer;
begin
I := FCells.IndexOf(ACol);
if I < 0 then Exit;
while I > 0 do
begin
FCells.Delete(0);
Dec(I);
end;
end;
function THorizTableParser.GetCellHtmlDef(AColName: string;
const ADef: string): string;
begin
Result := '';
end;
{ TCrossTableParser }
constructor TCrossTableParser.Create(ATable: IHTMLTable);
begin
FTable := ATable;
FColHeader := TStringList.Create;
FRowHeader := TStringList.Create;
end;
destructor TCrossTableParser.Destroy;
begin
FTable := nil;
FreeAndNil(FColHeader);
FreeAndNil(FRowHeader);
inherited;
end;
function TCrossTableParser.GetCellDef(AColName, ARowName: string;
const ADef: string): string;
var
RowIndex, ColIndex: Integer;
Row: IHTMLTableRow;
Cell: IHTMLTableCell;
begin
RowIndex := FRowHeader.IndexOf(ARowName);
ColIndex := FColHeader.IndexOf(AColName);
if (RowIndex < 0) or (ColIndex < 0) then Result := ADef
else
begin
Row := FTable.rows.item(RowIndex, 0) as IHTMLTableRow;
if ColIndex >= Row.cells.length then Result := ADef
else
begin
Cell := Row.cells.item(ColIndex, 0) as IHTMLTableCell;
Result := Trim((Cell as IHTMLElement).innerText);
end;
end;
end;
function TCrossTableParser.ParseHeader(ColHeader: array of string): Boolean;
var
I, J, K, L, M: Integer;
Row: IHTMLTableRow;
Flags: array of Boolean;
S: string;
begin
FColHeader.Clear;
FRowHeader.Clear;
Result := False;
// parse col header(a row)
SetLength(Flags, Length(ColHeader));
try
for I := 0 to FTable.rows.length - 1 do
begin
Row := FTable.rows.item(I, 0) as IHTMLTableRow;
if Row.cells.length < Length(ColHeader) then Continue;
for J := High(Flags) downto 0 do Flags[J] := False;
K := Length(ColHeader);
for J := 0 to Row.cells.length - 1 do
begin
S := Trim((Row.cells.item(J, 0) as IHTMLElement).innerText);
for L := 0 to High(ColHeader) do
begin
if Flags[L] then Continue;
if SameText(S, ColHeader[L]) then
begin
Flags[L] := True;
Dec(K);
if K = 0 then
begin
for M := 0 to Row.cells.length - 1 do FColHeader.Add(Trim((Row.cells.item(M, 0) as IHTMLElement).innerText));
Abort;
end;
end;
end;
end;
end;
except
Result := True; // to catch the abort
end;
// parse row header(a column)
for I := 0 to FTable.rows.length - 1 do
begin
Row := FTable.rows.item(I, 0) as IHTMLTableRow;
if Row.cells.length = 0 then S := ''
else S := Trim((Row.cells.item(0, 0) as IHTMLElement).innerText);
FRowHeader.Add(S);
end;
end;
function _IEPopupDialogHookProp(nCode: Integer; wp: WPARAM; lp: LPARAM): LRESULT; stdcall;
var
pcwp: PCWPStruct;
ClsName, WndName: string;
begin
Result := CallNextHookEx(l_OldCallWndProcHook, nCode, wp, lp);
pcwp := PCWPStruct(lp);
if (pcwp.message = WM_SHOWWINDOW) and (pcwp.wParam = 1) and IsWindow(pcwp.hwnd) then
begin
SetLength(ClsName, 64);
SetLength(ClsName, GetClassName(pcwp.hwnd, PChar(ClsName), 64));
if SameText(ClsName, 'Internet Explorer_TridentDlgFrame') then
begin
{ 出现"脚本错误"对话框.它是一个网页对话框,在显示时页面并没有加载完成,因此
此时找不到"是"按钮. 这里首先把它的大小设为0x0,然后等待它加载完成. }
if Assigned(l_IEPopupDialogWatcher) then
begin
MoveWindow(pcwp.hwnd, 0, 0, 0, 0, False);
PostMessage(l_IEPopupDialogWatcher.Handle, WM_PROCESS_YESNODLG, pcwp.hwnd, 0);
end;
end
else if SameText(ClsName, '#32770') then
begin
SetLength(WndName, 32);
SetLength(WndName, GetWindowText(pcwp.hwnd, PChar(WndName), 32));
if SameText(WndName, '错误') then
begin
if (GetDlgItem(pcwp.hwnd, IDYES) <> 0) and (GetDlgItem(pcwp.hwnd, IDNO) <> 0) then
begin
{ 出现脚本错误调试对话框。是否调试->选否 }
MoveWindow(pcwp.hwnd, 0, 0, 0, 0, False);
PostMessage(pcwp.hwnd, WM_COMMAND, IDNO, 0);
end;
end
else if SameText(WndName, 'Microsoft Internet Explorer') then
begin
if FindWindowEx(pcwp.hwnd, 0, nil, '当前安全设置禁止运行该页中的 ActiveX 控件。因此,该页可能无法正常显示。') <> 0 then
begin
{ 出现安全设置对话框。关闭 }
MoveWindow(pcwp.hwnd, 0, 0, 0, 0, False);
PostMessage(pcwp.hwnd, WM_COMMAND, IDCANCEL, 0);
end;
end;
end;
end;
end;
{ TIEPopupDialogWatcher }
constructor TIEPopupDialogWatcher.Create;
begin
FHandle := Classes.AllocateHWnd(WndProc);
if l_OldCallWndProcHook = 0 then
l_OldCallWndProcHook := SetWindowsHookEx(WH_CALLWNDPROC, _IEPopupDialogHookProp, 0, GetCurrentThreadId);
end;
destructor TIEPopupDialogWatcher.Destroy;
begin
if l_OldCallWndProcHook <> 0 then UnhookWindowsHookEx(l_OldCallWndProcHook);
Classes.DeallocateHWnd(FHandle);
inherited;
end;
procedure TIEPopupDialogWatcher.OnProcessYesNoDlg(var Msg: TMessage);
var
Doc: IHTMLDocument2;
Elem: IHTMLElement;
begin
if not IsWindow(Msg.WParam) then Exit;
Doc := GetIHTMLDocumentFromHWND(Msg.WParam);
if Doc <> nil then
begin
Elem := Doc.all.item('btnYes', 0) as IHTMLElement;
if Elem <> nil then
begin
Elem.click;
end;
end;
PostMessage(Handle, WM_PROCESS_YESNODLG, Msg.WParam, 0);
end;
procedure TIEPopupDialogWatcher.WndProc(var Msg: TMessage);
begin
if Msg.Msg < WM_USER then Msg.Result := DefWindowProc(Handle, Msg.Msg, Msg.WParam, Msg.LParam)
else Dispatch(Msg);
end;
{ TTempObjList }
procedure TTempObjList.Add(AObj: TObject);
begin
inherited Add(AObj);
end;
constructor TTempObjList.Create;
begin
FHandle := Classes.AllocateHWnd(WndProc);
end;
destructor TTempObjList.Destroy;
begin
Classes.DeallocateHWnd(FHandle);
while Self.Count > 0 do
begin
TObject(Items[0]).Free;
end;
inherited;
end;
procedure TTempObjList.OnCallerDestroyed(ACaller: TObject);
type
TNotifyEventRec = packed record
PFunc: Pointer;
PObj: Pointer;
end;
var
I: Integer;
Obj: TObject;
Rec: TNotifyEventRec;
NeedRemove: Boolean;
begin
for I := Self.Count - 1 downto 0 do
begin
Obj := TObject(Items[I]);
NeedRemove := False;
if Obj is TCallUntilDoneObj then
begin
CopyMemory(@Rec, @@TCallUntilDoneObj(Obj).FCallback, 8);
if Rec.PObj = ACaller then NeedRemove := True;
CopyMemory(@Rec, @@TCallUntilDoneObj(Obj).FTimeoutFunc, 8);
if Rec.PObj = ACaller then NeedRemove := True;
end
else if Obj is TNavigateAndCallObj then
begin
CopyMemory(@Rec, @@TNavigateAndCallObj(Obj).FCallback, 8);
if Rec.PObj = ACaller then NeedRemove := True;
CopyMemory(@Rec, @@TNavigateAndCallObj(Obj).FOnTimeout, 8);
if Rec.PObj = ACaller then NeedRemove := True;
end;
if NeedRemove then TObject(Items[I]).Free;
end;
end;
procedure TTempObjList.Remove(AObj: TObject);
begin
inherited Remove(AObj);
end;
procedure UnregisterCallerObject(AObject: TObject);
begin
l_TempObjList.OnCallerDestroyed(AObject);
end;
function SafeFireEvent(ADisp: IDispatch; AEventName: string; Params: array of const): Boolean;
type
PVarArg = ^TVarArg;
TVarArg = array[0..3] of DWORD;
var
Name: WideString;
DispID: Integer;
DispParams: TDispParams;
I: Integer;
Args: array[0..31] of OleVariant;
InvokeResult: OleVariant;
Rec: TVarRec;
V: OleVariant;
TmpDisp: IUnknown;
ExcepInfo: TExcepInfo;
begin
Result := False;
Name := AEventName;
if Succeeded(ADisp.GetIDsOfNames(GUID_NULL, @Name, 1, 0, @DispID)) then
begin
DispParams.cArgs := Length(Params);
DispParams.cNamedArgs := 0;
for I := 0 to High(Params) do
begin
Rec := Params[I];
case Rec.VType of
vtInteger: V := Rec.VInteger;
vtBoolean: V := Rec.VBoolean;
vtChar: V := Rec.VChar;
vtExtended: V := Rec.VExtended^;
vtString: V := Rec.VString^;
vtPointer: raise Exception.Create('pointer type not supported');
vtPChar: V := string(Rec.VPChar);
vtObject: begin
if Rec.VObject.GetInterface(IUnknown, TmpDisp) then V := TmpDisp
else raise Exception.Create('object type not supported');
end;
vtWideChar: V := Rec.VWideChar;
vtPWideChar: V := WideString(Rec.VPWideChar);
vtAnsiString: V := string(Rec.VAnsiString^);
vtCurrency: V := Rec.VCurrency^;
vtVariant: V := Rec.VVariant^;
vtInterface: V := IUnknown(Rec.VInterface^);
vtWideString: V := WideString(Rec.VWideString^);
vtInt64: V := Rec.VInt64^
else raise Exception.Create('type not supported!');
end;
Args[I] := V;
end;
DispParams.rgvarg := @Args;
Result := Succeeded(ADisp.Invoke(DispID, GUID_NULL, 0, DISPATCH_METHOD, DispParams, @InvokeResult, @ExcepInfo, nil));
end;
end;
procedure TTempObjList.WndProc(var Msg: TMessage);
var
Obj: Pointer;
Index: Integer;
begin
if Msg.Msg = WM_REMOVE_OBJ then
begin
Obj := Pointer(Msg.LParam);
Index := IndexOf(Obj);
if Index >= 0 then
begin
Self.Delete(Index);
TObject(Obj).Free;
end;
end else Msg.Result := DefWindowProc(FHandle, Msg.Msg, Msg.WParam, Msg.LParam);
end;
procedure FramePostData(AWB: TWebBrowser; AUrl: string; APostData: string; AFrameId: string);
var
PostData, Header: OleVariant;
Flags: OleVariant;
FrameName: OleVariant;
P: Pointer;
begin
Flags := 0;
PostData := VarArrayCreate([0, Length(APostData) - 1], varByte);
P := VarArrayLock(PostData);
try
Move( PChar(APostData)^, P^, Length(APostData) );
finally
VarArrayUnlock(PostData);
end;
Header := 'Content-Type: application/x-www-form-urlencodedrn';
FrameName := AFrameId;
AWB.Navigate(AUrl, Flags, FrameName, PostData, Header);
end;
{ ******************** SetCustomActiveXControlText ******************** }
type
PImageImportDescriptor = ^TImageImportDescriptor;
TImageImportDescriptor = packed record
OriginalFirstThunk: DWORD; // or Characteristics: DWORD
TimeDateStamp: DWORD;
ForwarderChain: DWORD;
Name: DWORD;
FirstThunk: DWORD;
end;
PImageChunkData = ^TImageChunkData;
TImageChunkData = packed record
case Integer of
0: ( ForwarderString: DWORD );
1: ( Func: DWORD );
2: ( Ordinal: DWORD );
3: ( AddressOfData: DWORD );
end;
PImageImportByName = ^TImageImportByName;
TImageImportByName = packed record
Hint: Word;
Name: array[0..0] of Byte;
end;
type
PHookRec = ^THookRec;
THookRec = packed record
OldFunc: Pointer;
NewFunc: Pointer;
end;
procedure HookApiInMod(ImageBase: Cardinal; DllName: PChar; ApiName: PChar; PHook: PHookRec);
var
pidh: PImageDosHeader;
pinh: PImageNtHeaders;
pSymbolTable: PIMAGEDATADIRECTORY;
piid: PIMAGEIMPORTDESCRIPTOR;
written, oldAccess: DWORD;
pProtoFill: Pointer;
Loaded: HMODULE;
pCode: ^Pointer;
begin
if ImageBase = 0 then Exit;
Loaded := LoadLibrary(DllName);
pProtoFill := GetProcAddress(Loaded, ApiName);
pidh := PImageDosHeader(ImageBase);
pinh := PImageNtHeaders(DWORD(ImageBase) + Cardinal(pidh^._lfanew));
pSymbolTable := @pinh^.OptionalHeader.DataDirectory[1];
piid := PImageImportDescriptor(DWORD(ImageBase) + pSymbolTable^.VirtualAddress);
while piid^.Name <> 0 do
begin
pCode := Pointer(dword(ImageBase) + piid^.FirstThunk);
while pCode^ <> nil do
begin
if (pCode^ = pProtoFill) then
begin
PHook^.OldFunc := pCode^;
VirtualProtect(pCode, SizeOf(DWORD), PAGE_WRITECOPY, oldAccess);
WriteProcessMemory(GetCurrentProcess(), pCode, @PHook^.NewFunc, SizeOf(DWORD), written);
VirtualProtect(pCode, SizeOf(DWORD), oldAccess, oldAccess);
end;
pCode := Pointer(dword(pCode) + 4);
end;
piid := Pointer(dword(piid) + 20);
end;
end;
procedure UnHookApiInMod(ImageBase: Cardinal; DllName: PChar; ApiName: PChar; const PHook: PHookRec);
var
pidh: PImageDosHeader;
pinh: PImageNtHeaders;
pSymbolTable: PIMAGEDATADIRECTORY;
piid: PIMAGEIMPORTDESCRIPTOR;
written, oldAccess: DWORD;
pCode: ^Pointer;
begin
if ImageBase = 0 then Exit;
pidh := PImageDosHeader(ImageBase);
pinh := PImageNtHeaders(DWORD(ImageBase) + Cardinal(pidh^._lfanew));
pSymbolTable := @pinh^.OptionalHeader.DataDirectory[1];
piid := PImageImportDescriptor(DWORD(ImageBase) + pSymbolTable^.VirtualAddress);
while piid^.Name <> 0 do
begin
pCode := Pointer(dword(ImageBase) + piid^.FirstThunk);
while pCode^ <> nil do
begin
if (pCode^ = pHook^.NewFunc) then
begin
VirtualProtect(pCode, SizeOf(DWORD), PAGE_WRITECOPY, oldAccess);
WriteProcessMemory(GetCurrentProcess(), pCode, @PHook^.OldFunc, SizeOf(DWORD), written);
VirtualProtect(pCode, SizeOf(DWORD), oldAccess, oldAccess);
end;
pCode := Pointer(dword(pCode) + 4);
end;
piid := Pointer(dword(piid) + 20);
end;
end;
type
PHookProcInstanceRec = ^THookProcInstanceRec;
THookProcInstanceRec = packed record
Code: Byte; { $E8 CALL NEAR PTR }
Offset: Integer; { offset }
Obj: Pointer; { pointer of this }
Code1: Byte; { $59 pop ecx }
Code2: Byte; { $E9 JMP NEAR PTR }
StdProc: Integer; { offset stdproc }
end;
TGetFocusContext = class
private
FCode: PHookProcInstanceRec;
public
ForceFocus: HWND;
HookRec: THookRec;
function GetFocus: HWND; stdcall;
function NewProcPtr: Pointer;
constructor Create;
destructor Destroy; override;
end;
type
TGetFocusFunc = function: HWND; stdcall;
function _StdGetFocusFunc: HWND; stdcall; assembler;
asm
MOV ECX, [ECX]
PUSH ECX
CALL TGetFocusContext.GetFocus
end;
function _SimpleSimulateKeyStrikes(const S: string): Boolean;
var
Code: Short;
I: Integer;
Ch: Char;
CapslockDown: Boolean;
NeedShift: Boolean;
procedure EnsureKeyEvent(ACode: Byte; ADown: Boolean);
begin
if ADown then keybd_event(ACode, 1, 0, 0)
else keybd_event(ACode, 1, KEYEVENTF_KEYUP, 0);
Sleep(20);
end;
begin
CapslockDown := (GetKeyState(VK_CAPITAL) and 1) <> 0;
for I := 1 to Length(S) do
begin
Code := VkKeyScan(S[I]);
Ch := Char(Code and $FF);
NeedShift := (Code and $100) <> 0;
if Ch in ['A'..'Z'] then
begin
if CapslockDown then NeedShift := not NeedShift;
end;
if NeedShift then // shift is down
begin
EnsureKeyEvent(VK_SHIFT, True);
EnsureKeyEvent(Code, True);
EnsureKeyEvent(Code, False);
EnsureKeyEvent(VK_SHIFT, False);
end
else
begin
EnsureKeyEvent(Code, True);
EnsureKeyEvent(Code, False);
end;
end;
Result := True;
end;
const
PROP_OLDWNDPROC = 'BM_OLD_WNDPROC';
var
l_SCACTEvent: TEvent;
type
TStdWndProc = function (hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
function StdDisableFocusChangeWndProc(H: HWND; uMsg: UINT; wp: WPARAM; lp: LPARAM): LRESULT; stdcall;
var
OldWndProc: TStdWndProc;
begin
OldWndProc := TStdWndProc(GetProp(H, PROP_OLDWNDPROC));
if ((uMsg = WM_SETFOCUS) or (uMsg = WM_KILLFOCUS)) and (HWND(lp) <> H) then
begin
Result := 0;
// Log('WM_SETFOCUS/WM_KILLFOCUS eat');
end
else
begin
if (uMsg = WM_SETFOCUS) or (uMsg = WM_KILLFOCUS) then
begin
// Log('WM_SETFOCUS/WM_KILLFOCUS pass');
end;
Result := OldWndProc(H, uMsg, wp, lp);
end;
end;
procedure SetCustomActiveXControlText(AElem: IHTMLElement; AText: string; ADllName: string);
var
H: HWND;
Ctx: TGetFocusContext;
OldWndProc: LongInt;
Msg: tagMsg;
begin
while True do
begin
if l_SCACTEvent.WaitFor(100) = wrSignaled then Break;
Application.ProcessMessages;
end;
try
(AElem as IOleWindow).GetWindow(H);
Ctx := TGetFocusContext.Create;
try
Ctx.HookRec.OldFunc := nil;
Ctx.HookRec.NewFunc := Ctx.NewProcPtr;
if GetModuleHandle(PChar(ADllName)) = 0 then raise Exception.CreateFmt('%s not loaded', [ADllName]);
// hook the getfocus function called by the control
HookApiInMod( GetModuleHandle(PChar(ADllName)), 'user32.dll', 'GetFocus', @Ctx.HookRec );
Ctx.ForceFocus := H;
// send this message so the control will set the LL_Keyboard hook
OldWndProc := GetWindowLong(H, GWL_WNDPROC);
SetProp(H, PROP_OLDWNDPROC, OldWndProc);
SetWindowLong(H, GWL_WNDPROC, Integer(@StdDisableFocusChangeWndProc));
SendMessage(H, WM_SETFOCUS, 0, H);
// now simulate keystrikes, all keys will go to the control & because getfocus returns itself, it will accept all keys
_SimpleSimulateKeyStrikes(AText);
// process all keyboard & other messages generated during the keybd_event
while PeekMessage(Msg, H, WM_KEYFIRST, WM_USER, PM_REMOVE) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
Ctx.ForceFocus := 0;
SetWindowLong(H, GWL_WNDPROC, OldWndProc);
RemoveProp(H, PROP_OLDWNDPROC);
// send this message so the control will unhook the LL_Keyboard hook
SendMessage(H, WM_KILLFOCUS, 0, H);
// Log('simulate done');
// unhook the function
UnHookApiInMod( GetModuleHandle(PChar(ADllName)), 'user32.dll', 'GetFocus', @Ctx.HookRec );
finally
FreeAndNil(Ctx);
end;
finally
l_SCACTEvent.SetEvent;
end;
end;
{ TGetFocusContext }
function CalcJmpOffset(Src, Dest: Pointer): Longint;
begin
Result := Longint(Dest) - (Longint(Src) + 5);
end;
constructor TGetFocusContext.Create;
begin
FCode := VirtualAlloc(nil, SizeOf(THookProcInstanceRec), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
FCode.Code := $E8;
FCode.Offset := CalcJmpOffset(@FCode.Code, @FCode.Code1);
FCode.Obj := Self;
FCode.Code1 := $59;
FCode.Code2 := $E9;
FCode.StdProc := CalcJmpOffset(@FCode.Code2, @_StdGetFocusFunc);
end;
destructor TGetFocusContext.Destroy;
begin
VirtualFree(FCode, 0, MEM_RELEASE);
inherited;
end;
function TGetFocusContext.GetFocus: HWND;
begin
if ForceFocus = 0 then Result := TGetFocusFunc(HookRec.OldFunc)()
else Result := ForceFocus;
// LogFmt('GetFocus returns:%X', [Result]);
end;
function TGetFocusContext.NewProcPtr: Pointer;
begin
Result := FCode;
end;
procedure DisableCurrentThreadIME;
type
TImmDisableIMEFunc = function (AThreadId: Cardinal): LongBool; stdcall;
var
_ImmDisableIME: TImmDisableIMEFunc;
begin
_ImmDisableIME := GetProcAddress( GetModuleHandle('imm32.dll'), 'ImmDisableIME' );
if @_ImmDisableIME <> nil then _ImmDisableIME(GetCurrentThreadId);
end;
initialization
l_TempObjList := TTempObjList.Create;
l_IEPopupDialogWatcher := TIEPopupDialogWatcher.Create;
l_SCACTEvent := TEvent.Create(nil, False, True, '');
finalization
FreeAndNil(l_SCACTEvent);
l_TempObjList.Free;
l_TempObjList := nil;
FreeAndNil(l_IEPopupDialogWatcher);
end.
|
unit evContentsNodeFilter;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Автор: Инишев Д.А.
// Модуль: "w:/common/components/gui/Garant/Everest/evContentsNodeFilter.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::ContentsTree::TevContentsNodeFilter
//
// фильтр оглваления документа
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
k2Interfaces,
l3Base,
k2TagList,
nevTools,
evInternalInterfaces,
nevBase
;
type
TevContentsNodeFilter = class(Tl3Base, InevContentsNodeFilter)
{* фильтр оглваления документа }
private
// private fields
f_FilteredNodeFlag : Integer;
f_Document : Ik2Tag;
f_FilterTagList : Tk2TagList;
{* Список удаленных тегов.}
private
// private methods
function NeedColor(const aNode: InevNode): Boolean;
protected
// realized methods
procedure ColorNode(const aNode: InevNode);
function pm_GetFilteredNodeFlag: Integer;
procedure pm_SetFilteredNodeFlag(aValue: Integer);
procedure CheckTagList;
procedure AddFilterTag(const aTag: InevTag);
procedure ChangeDocument(const aDocument: InevTag);
function NeedCreate(const aTag: InevTag): Boolean;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
// public methods
constructor Create(const aDocument: Ik2Tag); reintroduce; virtual;
class function Make(const aDocument: Ik2Tag): InevContentsNodeFilter;
end;//TevContentsNodeFilter
implementation
uses
evdTypes,
l3TreeInterfaces,
SysUtils,
k2Tags,
l3Bits,
l3Types,
l3MinMax
;
// start class TevContentsNodeFilter
function TevContentsNodeFilter.NeedColor(const aNode: InevNode): Boolean;
//#UC START# *4ECA574B02DB_4DFEF1DF009F_var*
var
l_Level : Integer;
l_ParentNode : InevNode;
l_CurLevel : Integer;
l_ContentsLevel : Integer;
l_Part : IevDocumentPart;
//#UC END# *4ECA574B02DB_4DFEF1DF009F_var*
begin
//#UC START# *4ECA574B02DB_4DFEF1DF009F_impl*
Result := False;
with f_Document.Attr[k2_tiContentsLevel6] do
if IsValid then
l_ContentsLevel := AsLong
else
l_ContentsLevel := 0;
if (l_ContentsLevel > 0) then
begin
Inc(l_ContentsLevel);
l_CurLevel := aNode.GetLevel;
l_ParentNode := aNode;
l_Level := 0;
while l_ParentNode.GetLevel > 1 do
begin
if (l_ParentNode <> nil) and Supports(l_ParentNode, IevDocumentPart, l_Part) then
try
if (l_Part.ContentsRec.rLevel6 < Pred(High(Long))) then
begin
l_Level := l_ParentNode.GetLevel;
l_Level := l_Level + l_Part.ContentsRec.rLevel6;
end; // if (l_Part.ContentsRec.rLevel6 < Pred(High(Long))) then
finally
l_Part := nil;
end;//try..finally
l_ContentsLevel := Max(l_Level, l_ContentsLevel);
l_ParentNode := l_ParentNode.ParentNode;
end; // while l_ParentNode.GetLevel > 1 do
if (l_CurLevel > l_ContentsLevel) then
Result := True;
end // if l_ContentsLevel then
else
Result := True;
//#UC END# *4ECA574B02DB_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.NeedColor
constructor TevContentsNodeFilter.Create(const aDocument: Ik2Tag);
//#UC START# *4DFEF2F303DD_4DFEF1DF009F_var*
//#UC END# *4DFEF2F303DD_4DFEF1DF009F_var*
begin
//#UC START# *4DFEF2F303DD_4DFEF1DF009F_impl*
f_FilteredNodeFlag := nfHidden;
f_Document := aDocument;
f_FilterTagList := Tk2TagList.Make;
//#UC END# *4DFEF2F303DD_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Create
class function TevContentsNodeFilter.Make(const aDocument: Ik2Tag): InevContentsNodeFilter;
//#UC START# *4DFEF31A0273_4DFEF1DF009F_var*
var
l_Filter: TevContentsNodeFilter;
//#UC END# *4DFEF31A0273_4DFEF1DF009F_var*
begin
//#UC START# *4DFEF31A0273_4DFEF1DF009F_impl*
l_Filter := TevContentsNodeFilter.Create(aDocument);
try
Result := l_Filter;
finally
l3Free(l_Filter);
end;
//#UC END# *4DFEF31A0273_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Make
procedure TevContentsNodeFilter.ColorNode(const aNode: InevNode);
//#UC START# *4A2628130085_4DFEF1DF009F_var*
var
l_Flags : Integer;
//#UC END# *4A2628130085_4DFEF1DF009F_var*
begin
//#UC START# *4A2628130085_4DFEF1DF009F_impl*
if (aNode = nil) then
Exit;
l_Flags := aNode.Flags;
if NeedColor(aNode) then
l3SetMask(l_Flags, f_FilteredNodeFlag)
else
l3ClearMask(l_Flags, f_FilteredNodeFlag);
aNode.Flags := l_Flags;
//#UC END# *4A2628130085_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.ColorNode
function TevContentsNodeFilter.pm_GetFilteredNodeFlag: Integer;
//#UC START# *4A26284D0339_4DFEF1DF009Fget_var*
//#UC END# *4A26284D0339_4DFEF1DF009Fget_var*
begin
//#UC START# *4A26284D0339_4DFEF1DF009Fget_impl*
Result := f_FilteredNodeFlag;
//#UC END# *4A26284D0339_4DFEF1DF009Fget_impl*
end;//TevContentsNodeFilter.pm_GetFilteredNodeFlag
procedure TevContentsNodeFilter.pm_SetFilteredNodeFlag(aValue: Integer);
//#UC START# *4A26284D0339_4DFEF1DF009Fset_var*
//#UC END# *4A26284D0339_4DFEF1DF009Fset_var*
begin
//#UC START# *4A26284D0339_4DFEF1DF009Fset_impl*
f_FilteredNodeFlag := aValue;
//#UC END# *4A26284D0339_4DFEF1DF009Fset_impl*
end;//TevContentsNodeFilter.pm_SetFilteredNodeFlag
procedure TevContentsNodeFilter.CheckTagList;
//#UC START# *4E09B99A0384_4DFEF1DF009F_var*
//#UC END# *4E09B99A0384_4DFEF1DF009F_var*
begin
//#UC START# *4E09B99A0384_4DFEF1DF009F_impl*
if f_FilterTagList <> nil then
f_FilterTagList.Clear;
//#UC END# *4E09B99A0384_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.CheckTagList
procedure TevContentsNodeFilter.AddFilterTag(const aTag: InevTag);
//#UC START# *4E09BCEA0004_4DFEF1DF009F_var*
//#UC END# *4E09BCEA0004_4DFEF1DF009F_var*
begin
//#UC START# *4E09BCEA0004_4DFEF1DF009F_impl*
f_FilterTagList.Add(aTag);
//#UC END# *4E09BCEA0004_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.AddFilterTag
procedure TevContentsNodeFilter.ChangeDocument(const aDocument: InevTag);
//#UC START# *4EAE94530363_4DFEF1DF009F_var*
//#UC END# *4EAE94530363_4DFEF1DF009F_var*
begin
//#UC START# *4EAE94530363_4DFEF1DF009F_impl*
f_Document := aDocument;
//#UC END# *4EAE94530363_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.ChangeDocument
function TevContentsNodeFilter.NeedCreate(const aTag: InevTag): Boolean;
//#UC START# *4ECA564903B7_4DFEF1DF009F_var*
//#UC END# *4ECA564903B7_4DFEF1DF009F_var*
begin
//#UC START# *4ECA564903B7_4DFEF1DF009F_impl*
if aTag = nil then
Result := True
else
Result := f_FilterTagList.IndexOf(aTag) < 0;
//#UC END# *4ECA564903B7_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.NeedCreate
procedure TevContentsNodeFilter.Cleanup;
//#UC START# *479731C50290_4DFEF1DF009F_var*
//#UC END# *479731C50290_4DFEF1DF009F_var*
begin
//#UC START# *479731C50290_4DFEF1DF009F_impl*
f_Document := nil;
CheckTagList;
l3Free(f_FilterTagList);
inherited;
//#UC END# *479731C50290_4DFEF1DF009F_impl*
end;//TevContentsNodeFilter.Cleanup
end. |
unit StepParams;
interface
uses
StepParamsIntf, StepParamIntf, Classes, SysUtils;
type
EInvalidParamType = class(EVariantError);
TStepParams = class(TInterfacedObject, IStepParams)
private
FParams: IInterfaceList;
function GetParam(AParam: Variant): IStepParam;
procedure SetParam(AParam: Variant; const Value: IStepParam);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Add(const AParam: string): IStepParam;
function ByName(const AParamName: string): IStepParam;
property Param[AParam: Variant]: IStepParam read GetParam write SetParam; default;
end;
implementation
uses
StepParam, TypeUtils, Constants, Variants;
procedure TStepParams.Clear;
begin
FParams.Clear;
end;
constructor TStepParams.Create;
begin
inherited Create;
FParams := TInterfaceList.Create;
end;
destructor TStepParams.Destroy;
begin
Clear;
FParams := nil;
inherited Destroy;
end;
function TStepParams.Add(const AParam: string): IStepParam;
begin
Result := TStepParam.Create;
Result.Name := AParam;
Result.Value := AParam;
FParams.Add(Result);
end;
function TStepParams.ByName(const AParamName: string): IStepParam;
var
I: Integer;
begin
Result := nil;
for I := 0 to FParams.Count - 1 do
if S((FParams[i] as IStepParam).Name).Equals(AParamName) then
begin
Result := (FParams[i] as IStepParam);
Break;
end;
end;
function TStepParams.GetParam(AParam: Variant): IStepParam;
begin
if not (VarIsStr(AParam) or VarIsOrdinal(AParam)) then
raise EInvalidParamType.CreateFmt(InvalidParamTypeError, [VarTypeAsText(TVarData(AParam).VType)]);
case TVarData(AParam).VType of
varString, varOleStr, varUString: Result := ByName(AParam)
else
Result := (FParams[AParam] as IStepParam);
end
end;
procedure TStepParams.SetParam(AParam: Variant; const Value: IStepParam);
var
LParam: IStepParam;
begin
case TVarData(AParam).VType of
varString, varOleStr, varUString: LParam := ByName(AParam)
else
if FParams.Count -1 >= AParam then
LParam := (FParams[AParam] as IStepParam)
end;
if (LParam = nil) then
if (Value <> nil) then
LParam := Value
else
begin
LParam := TStepParam.Create;
LParam.Name := AParam;
LParam.Value := AParam;
end;
if FParams.IndexOf(LParam) = NotFound then
FParams.Add(LParam);
end;
end.
|
unit frmLogOn;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, XPMan, StdCtrls, ExtCtrls, WinUtils, GenUtils, Globals, SQLAccess;
type
TformLogOn = class(TForm)
lbUser: TLabel;
lbPassword: TLabel;
lbHost: TLabel;
lbPort: TLabel;
lbDB: TLabel;
edtUser: TEdit;
edtPass: TEdit;
edtHost: TEdit;
edtDB: TEdit;
edtPort: TEdit;
pnlSep1: TPanel;
pnlSep2: TPanel;
btAccept: TButton;
btCancel: TButton;
xpManifest: TXPManifest;
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btAcceptClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
formLogOn: TformLogOn;
implementation
uses frmMain;
{$R *.dfm}
procedure TformLogOn.btCancelClick(Sender: TObject);
begin
Close();
end;
procedure TformLogOn.FormCreate(Sender: TObject);
begin
{
Load default settings from Registry and fill in the Edit Boxes.
}
edtHost.Text := LoadOption( 'Host', 'Software\SchoolMgr', 'localhost', HKEY_CURRENT_USER );
edtPort.Text := IntToStr( atoi( LoadOption( 'Port', 'Software\SchoolMgr', '0', HKEY_CURRENT_USER ) ) );
edtDB.Text := LoadOption( 'DB', 'Software\SchoolMgr', 'school', HKEY_CURRENT_USER );
edtUser.Text := LoadOption( 'User', 'Software\SchoolMgr', '', HKEY_CURRENT_USER );
edtPass.Text := LoadOption( 'Password', 'Software\SchoolMgr', '', HKEY_CURRENT_USER );
end;
procedure TformLogOn.FormDestroy(Sender: TObject);
begin
{
Save default settings to Registry.
}
SaveOption( 'Host', 'Software\SchoolMgr', edtHost.Text, HKEY_CURRENT_USER );
SaveOption( 'DB', 'Software\SchoolMgr', edtDB.Text, HKEY_CURRENT_USER );
SaveOption( 'User', 'Software\SchoolMgr', edtUser.Text, HKEY_CURRENT_USER );
SaveOption( 'Password', 'Software\SchoolMgr', edtPass.Text, HKEY_CURRENT_USER );
SaveOption( 'Port', 'Software\SchoolMgr', IntToStr( atoi( edtPort.Text ) ), HKEY_CURRENT_USER );
end;
procedure TformLogOn.btAcceptClick(Sender: TObject);
var
cs : TConnectSpec;
bCould : Boolean;
begin
Globals.SQL := TSchSQLAccess.Create();
cs.sHost := edtHost.Text;
cs.wPort := atoi( edtPort.Text );
cs.sUser := edtUser.Text;
cs.sPassword := edtPass.Text;
cs.sDBName := edtDB.Text;
{ Disable Controls }
edtHost .Enabled := False;
edtPort .Enabled := False;
edtUser .Enabled := False;
edtPass .Enabled := False;
edtDB .Enabled := False;
btCancel .Enabled := False;
btAccept .Enabled := False;
bCould := Globals.Perform_Connect( cs );
if ( not bCould ) then
begin
Application.MessageBox( 'Connection to the selected DataBase could not been established!', 'Error', MB_OK or MB_ICONERROR );
{ Enable Controls }
edtHost .Enabled := True;
edtPort .Enabled := True;
edtUser .Enabled := True;
edtPass .Enabled := True;
edtDB .Enabled := True;
btCancel .Enabled := True;
btAccept .Enabled := True;
end else
begin
Globals.LoadLastIndexes();
Hide();
formMain.ShowModal();
Close();
end;
end;
procedure TformLogOn.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := not Globals.DB_Busy();
end;
end.
|
{Creeated by Simon King 2017
Batch generates all containers in the current open Outjob
Must turn off Camtastic Autoload and open as Camtastic loading will terminate script before completion.
Might be ok i made the last container?
last edit 2017-09-13 by Dennis Saputelli added confirmation dialog as this could run a while
added button icon
}
procedure OutputJobBatch();
uses
SysUtils;
IniFiles;
var
Workspace : IWorkspace;
projDocument : IDocument;
projOutput : IWSM_OutputJobDocument;
i : Integer;
buttonSelected : Integer;
begin
// Show a confirmation dialog
buttonSelected := messagedlg(
'Proceed with Batch Output Generation?'+ #10#13+'Might take a while...'+#10#13+#10#13+
'This script is going to batch generate all of the outputs in the currently open Outjob.'+#10#13+#10#13+
'Must turn off "Camtastic Autoload" before running.'+#10#13+#10#13+
'Suggest to turn off "Open Generated Outputs" and "Open PDF after export" so you can watch progress.'+#10#13,
mtWarning, mbOKCancel, 0);
if buttonSelected = mrCancel then Exit;
if buttonSelected = mbOK then;
begin
Workspace := GetWorkspace;
if (Workspace = nil) then
begin
ShowError('Unable to find current workspace.');
Exit;
end;
projDocument := Workspace.DM_FocusedDocument;
if (projDocument.DM_DocumentKind <> 'OUTPUTJOB') then
begin
ShowError('Document is not an Output Job File.');
Exit;
end;
projOutput := Workspace.DM_GetOutputJobDocumentByPath(projDocument.DM_FullPath);
for i := 0 to (projOutput.OutputMediumCount - 1) do
begin
if (projOutput.OutputMedium(i).TypeString = 'PDF') then
begin
ResetParameters;
AddStringParameter ('Action' , 'PublishToPDF');
AddStringParameter ('OutputMedium' , projOutput.OutputMedium(i).Name);
AddStringParameter ('ObjectKind' , 'OutputBatch');
AddStringParameter ('DisableDialog' , 'True');
AddStringParameter ('OpenOutput' , 'False');
RunProcess('WorkspaceManager:Print');
Sleep(1000);
end;
if (projOutput.OutputMedium(i).TypeString = 'Generate Files') then
begin
ResetParameters;
AddStringParameter ('Action' , 'Run');
AddStringParameter ('OutputMedium' , projOutput.OutputMedium(i).Name);
AddStringParameter ('ObjectKind' , 'OutputBatch');
AddStringParameter ('DisableDialog' , 'True');
RunProcess('WorkspaceManager:GenerateReport');
Sleep(1000);
end;
end;
end;
end;
end;
|
unit TestAddressesSamplesUnit;
interface
uses
TestFramework, Classes, SysUtils,
BaseTestOnlineExamplesUnit;
type
TTestAddressesSamples = class(TTestOnlineExamples)
published
procedure MarkAsVisited;
procedure MarkAsDeparted;
procedure MarkAsDetectedAsVisited;
procedure MarkAsDetectedAsDeparted;
end;
implementation
uses AddressParametersUnit, AddressUnit, NullableBasicTypesUnit, AddressBookContactUnit, DataObjectUnit;
{ TTestAddressesSamples }
procedure TTestAddressesSamples.MarkAsDeparted;
var
ErrorString: String;
IsDeparted: boolean;
RouteId: String;
AddressId: integer;
MemberId: integer;
begin
RouteId := 'DD376C7148E7FEE36CFABE2BD9978BDD';
MemberId := 1;
AddressId := 183045808;
IsDeparted := True;
FRoute4MeManager.Address.MarkAsDeparted(
RouteId, AddressId, MemberId, IsDeparted, ErrorString);
CheckEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDeparted(
'qwe', AddressId, MemberId, IsDeparted, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDeparted(
RouteId, -123, MemberId, IsDeparted, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDeparted(
RouteId, AddressId, -123741, IsDeparted, ErrorString);
// I don't know why this case is not considered an error
CheckEquals(EmptyStr, ErrorString);
IsDeparted := False;
FRoute4MeManager.Address.MarkAsDeparted(
RouteId, AddressId, MemberId, IsDeparted, ErrorString);
CheckEquals(EmptyStr, ErrorString);
end;
procedure TTestAddressesSamples.MarkAsDetectedAsDeparted;
var
ErrorString: String;
IsDeparted: boolean;
RouteId: String;
RouteDestinationId: integer;
begin
RouteId := '241466F15515D67D3F951E2DA38DE76D';
RouteDestinationId := 167899269;
IsDeparted := True;
FRoute4MeManager.Address.MarkAsDetectedAsDeparted(
RouteId, RouteDestinationId, IsDeparted, ErrorString);
CheckEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
'qwe', RouteDestinationId, IsDeparted, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, -123, IsDeparted, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
IsDeparted := False;
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, RouteDestinationId, IsDeparted, ErrorString);
CheckEquals(EmptyStr, ErrorString);
end;
procedure TTestAddressesSamples.MarkAsDetectedAsVisited;
var
ErrorString: String;
IsVisited: boolean;
RouteId: String;
RouteDestinationId: integer;
begin
RouteId := '241466F15515D67D3F951E2DA38DE76D';
RouteDestinationId := 167899269;
IsVisited := True;
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, RouteDestinationId, IsVisited, ErrorString);
CheckEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
'qwe', RouteDestinationId, IsVisited, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, -123, IsVisited, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
IsVisited := False;
FRoute4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, RouteDestinationId, IsVisited, ErrorString);
CheckEquals(EmptyStr, ErrorString);
end;
procedure TTestAddressesSamples.MarkAsVisited;
var
ErrorString: String;
IsVisited: boolean;
RouteId: String;
AddressId: integer;
MemberId: integer;
IsException: boolean;
begin
RouteId := 'DD376C7148E7FEE36CFABE2BD9978BDD';
MemberId := 1;
AddressId := 183045808;
IsVisited := True;
FRoute4MeManager.Address.MarkAsVisited(
RouteId, AddressId, MemberId, IsVisited, ErrorString);
CheckEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsVisited(
'qwe', AddressId, MemberId, IsVisited, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
FRoute4MeManager.Address.MarkAsVisited(
RouteId, -123, MemberId, IsVisited, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
// I don't know why it happens exception
IsException := False;
try
FRoute4MeManager.Address.MarkAsVisited(
RouteId, AddressId, -123, IsVisited, ErrorString);
CheckNotEquals(EmptyStr, ErrorString);
except
IsException := True;
end;
CheckTrue(IsException);
IsVisited := False;
FRoute4MeManager.Address.MarkAsVisited(
RouteId, AddressId, MemberId, IsVisited, ErrorString);
CheckEquals(EmptyStr, ErrorString);
end;
initialization
RegisterTest('Examples\Online\Addresses\', TTestAddressesSamples.Suite);
end.
|
program proc_func;
uses Crt;
var a, b, x : real;
o, mes, error : integer;
procedure vypis_operace(var mes: integer);
begin
error:=0;
clrscr;
if (mes=1) then begin
WriteLn('Nezanama operace! Zadejte kod operace znovu.');
WriteLn('********************************************');
end;
WriteLn('Zadej cislo operace kterou chces provest');
WriteLn('1 - scitani');
WriteLn('2 - odcitani');
WriteLn('3 - nasobeni');
WriteLn('4 - deleni');
end;
function scitani(a,b:real) :real;
begin
x := a+b;
scitani:=x;
end;
function odcitani(a,b:real) :real;
begin
x := a-b;
odcitani:=x;
end;
function nasobeni(a,b:real) :real;
begin
x := a*b;
nasobeni:=x;
end;
function deleni(a,b:real) :real;
begin
if (b=0) then begin WriteLn('Nulou delit nelze!'); error:=1; end
else begin x := a / b;
deleni:=x;
end;
end;
begin
mes:=0;
repeat
vypis_operace(mes);
ReadLn(o);
mes:=1;
until (o > 0) and (o < 5);
WriteLn('Zadej prvni cislo:');
ReadLn(a);
WriteLn('Zadej druhe cislo:');
ReadLn(b);
if (o=1) then scitani(a,b);
if (o=2) then odcitani(a,b);
if (o=3) then nasobeni(a,b);
if (o=4) then deleni(a,b);
if (error<>1)then WriteLn('Vysledek pozadovane operace je: ', x:0:2);
readln;
end.
|
Unit TERRA_NullRenderer;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_Stream, TERRA_Renderer, TERRA_VertexFormat,
TERRA_Color, TERRA_Image, TERRA_Vector2D, TERRA_Vector3D, TERRA_Vector4D,
TERRA_Matrix3x3, TERRA_Matrix4x4;
Type
NullFeatures = Class(RendererFeatures)
Public
Constructor Create(Owner:GraphicsRenderer);
End;
NullVBO = Class(VertexBufferInterface)
Protected
Procedure Submit(Wireframe:Boolean); Override;
Public
Function Generate(Vertices:VertexData; IndexData, EdgeData:Pointer; TriangleCount:Integer; DynamicUsage:Boolean):Boolean; Override;
Procedure Invalidate(); Override;
End;
NullTexture = Class(TextureInterface)
Protected
_Handle:Cardinal;
Public
Function Generate(Pixels:Pointer; Width, Height:Integer; SourceFormat, TargetFormat:TextureColorFormat; ByteFormat:PixelSizeType):Boolean; Override;
Function Bind(Slot:Integer):Boolean; Override;
Function GetImage():Image; Override;
Procedure Invalidate(); Override;
End;
NullCubeMap = Class(CubeMapInterface)
Protected
_Handle:Cardinal;
Public
Function Bind(Slot:Integer):Boolean; Override;
Function Generate(Width, Height:Integer; SourceFormat, TargetFormat:TextureColorFormat; ByteFormat:PixelSizeType):Boolean; Override;
Procedure Invalidate(); Override;
End;
NullFBO = Class(RenderTargetInterface)
Public
Function Generate(Width, Height:Integer; MultiSample:Boolean; PixelSize:PixelSizeType; TargetCount:Integer; DepthBuffer, StencilBuffer:Boolean):Boolean; Override;
Function Bind(Slot:Integer):Boolean; Override;
Procedure BeginCapture(Flags:Cardinal = clearAll); Override;
Procedure EndCapture; Override;
Procedure Resize(NewWidth, NewHeight:Integer); Override;
Function GetImage():Image; Override;
Function GetPixel(X,Y:Integer):Color; Override;
Procedure Invalidate(); Override;
End;
NullShaderAttribute = Record
Name:TERRAString;
Handle:Integer;
End;
NullShader = Class(ShaderInterface)
Protected
_VertexCode:TERRAString;
_FragmentCode:TERRAString;
_VertexShaderHandle:Cardinal;
_FragmentShaderHandle:Cardinal;
_Program:Cardinal;
_Linked:Boolean;
_MRT:Boolean;
_Attributes:Array Of NullShaderAttribute;
_AttributeCount:Integer;
Public
Function Generate(Const Name:TERRAString; ShaderCode:TERRAString):Boolean; Override;
Function IsReady():Boolean; Override;
Function Bind():Boolean; Override;
Function Unbind():Boolean; Override;
Procedure SetIntegerUniform(Const Name:TERRAString; Const Value:Integer); Override;
Procedure SetFloatUniform(Const Name:TERRAString; Const Value:Single); Override;
Procedure SetVec2Uniform(Const Name:TERRAString; Const Value:Vector2D); Override;
Procedure SetVec3Uniform(Const Name:TERRAString; const Value:Vector3D); Override;
Procedure SetVec4Uniform(Const Name:TERRAString; const Value:Vector4D); Override;
Procedure SetMat3Uniform(Const Name:TERRAString; Value:Matrix3x3); Override;
Procedure SetMat4Uniform(Const Name:TERRAString; Value:Matrix4x4); Override;
Procedure SetVec4ArrayUniform(Const Name:TERRAString; Count:Integer; Values:PVector4D); Override;
Function GetUniform(Name:TERRAString):Integer; Override;
Function GetAttributeHandle(Const Name:TERRAString):Integer; Override;
Procedure Invalidate(); Override;
End;
NullRenderer = Class(GraphicsRenderer)
Protected
Function Initialize():Boolean; Override;
Public
Procedure ResetState(); Override;
Function CreateTexture():TextureInterface; Override;
Function CreateCubeMap():CubeMapInterface; Override;
Function CreateVertexBuffer():VertexBufferInterface; Override;
Function CreateShader():ShaderInterface; Override;
Function CreateRenderTarget():RenderTargetInterface; Override;
Procedure ClearBuffer(Color, Depth, Stencil:Boolean); Override;
Procedure SetClearColor(Const ClearColor:Color); Override;
Procedure SetStencilTest(Enable:Boolean); Override;
Procedure SetStencilOp(fail, zfail, zpass:StencilOperation); Override;
Procedure SetStencilFunction(Mode:CompareMode; StencilID:Cardinal; Mask:Cardinal = $FFFFFFFF); Override;
Procedure SetColorMask(Red, Green, Blue, Alpha:Boolean); Override;
Procedure SetDepthMask(WriteZ:Boolean); Override;
Procedure SetDepthTest(Enable:Boolean); Override;
Procedure SetDepthFunction(Mode:CompareMode); Override;
Procedure SetCullMode(Mode:CullMode); Override;
Procedure SetBlendMode(BlendMode:Integer); Override;
Procedure SetProjectionMatrix(Const Mat:Matrix4x4); Override;
Procedure SetModelMatrix(Const Mat:Matrix4x4); Override;
Procedure SetTextureMatrix(Const Mat:Matrix4x4); Override;
Procedure SetScissorState(Enabled:Boolean); Override;
Procedure SetScissorArea(X,Y, Width, Height:Integer); Override;
Procedure SetViewport(X,Y, Width, Height:Integer); Override;
Procedure SetAttributeSource(Const Name:AnsiString; AttributeKind:Cardinal; ElementType:DataFormat; AttributeSource:Pointer); Override;
Procedure SetDiffuseColor(Const C:Color); Override;
Procedure DrawSource(Primitive:RenderPrimitive; Count:Integer); Override;
Procedure DrawIndexedSource(Primitive:RenderPrimitive; Count:Integer; Indices:System.PWord); Override;
Public
End;
Implementation
Uses TERRA_Log, TERRA_Application, TERRA_GraphicsManager, TERRA_FileManager, TERRA_FileUtils, TERRA_FileStream, TERRA_Error;
{ NullFeatures }
Constructor NullFeatures.Create(Owner:GraphicsRenderer);
Begin
Inherited Create(Owner);
_MaxTextureUnits := 8;
_MaxTextureSize := 4096;
_maxRenderTargets := 4;
_maxAnisotrophy := 0;
_multiSampleCount := 0;
_VertexCacheSize := 32;
TextureCompression.Avaliable := False;
Shaders.Avaliable := True;
VertexBufferObject.Avaliable := True;
FrameBufferObject.Avaliable := True;
PostProcessing.Avaliable := True;
CubeMapTexture.Avaliable := True;
SeparateBlends.Avaliable := True;
SeamlessCubeMap.Avaliable := True;
NPOT.Avaliable := True;
PackedStencil.Avaliable := True;
_MaxUniformVectors := 1024;
TextureArray.Avaliable := False;
FloatTexture.Avaliable := True;
DeferredLighting.Avaliable := True;
StencilBuffer.Avaliable := True;
End;
{ NullRenderer }
Procedure NullRenderer.ClearBuffer(Color, Depth, Stencil:Boolean);
Begin
End;
Procedure NullRenderer.SetClearColor(const ClearColor: Color);
Begin
End;
Function NullRenderer.Initialize():Boolean;
Begin
_Features := NullFeatures.Create(Self);
_DeviceName := 'Null Renderer';
_DeviceVendor := 'TERRA';
_DeviceVersion := StringToVersion('2.0.0');
Result := True;
End;
Procedure NullRenderer.SetColorMask(Red, Green, Blue, Alpha: Boolean);
Begin
End;
Procedure NullRenderer.SetDepthMask(WriteZ: Boolean);
Begin
End;
Procedure NullRenderer.SetDepthFunction(Mode: CompareMode);
Begin
End;
Procedure NullRenderer.SetStencilTest(Enable: Boolean);
Begin
End;
Procedure NullRenderer.SetStencilFunction(Mode: CompareMode; StencilID, Mask: Cardinal);
Begin
End;
Procedure NullRenderer.SetStencilOp(fail, zfail, zpass: StencilOperation);
Begin
End;
Procedure NullRenderer.SetCullMode(Mode: CullMode);
Begin
End;
Procedure NullRenderer.SetDepthTest(Enable: Boolean);
Begin
End;
Procedure NullRenderer.SetBlendMode(BlendMode: Integer);
Begin
End;
Procedure NullRenderer.SetModelMatrix(Const Mat: Matrix4x4);
Begin
End;
Procedure NullRenderer.SetProjectionMatrix(Const Mat:Matrix4x4);
Begin
End;
Procedure NullRenderer.SetTextureMatrix(Const Mat: Matrix4x4);
Begin
End;
Procedure NullRenderer.SetDiffuseColor(Const C: Color);
Begin
End;
Procedure NullRenderer.SetAttributeSource(Const Name:AnsiString; AttributeKind:Cardinal; ElementType:DataFormat; AttributeSource:Pointer);
Begin
End;
Procedure NullRenderer.DrawSource(Primitive: RenderPrimitive; Count: Integer);
Begin
End;
Procedure NullRenderer.DrawIndexedSource(Primitive:RenderPrimitive; Count:Integer; Indices:System.PWord);
Begin
End;
Procedure NullRenderer.SetViewport(X, Y, Width, Height:Integer);
Begin
End;
Procedure NullRenderer.ResetState();
Begin
End;
Procedure NullRenderer.SetScissorArea(X,Y, Width, Height:Integer);
Begin
End;
Procedure NullRenderer.SetScissorState(Enabled: Boolean);
Begin
End;
Function NullRenderer.CreateCubeMap: CubeMapInterface;
Begin
Result := NullCubeMap.Create(Self);
End;
Function NullRenderer.CreateRenderTarget: RenderTargetInterface;
Begin
Result := NullFBO.Create(Self);
End;
Function NullRenderer.CreateTexture: TextureInterface;
Begin
Result := NullTexture.Create(Self);
End;
Function NullRenderer.CreateVertexBuffer: VertexBufferInterface;
Begin
Result := NullVBO.Create(Self);
End;
Function NullRenderer.CreateShader: ShaderInterface;
Begin
Result := NullShader.Create(Self);
End;
{ NullVBO }
Function NullVBO.Generate(Vertices:VertexData; IndexData, EdgeData:Pointer; TriangleCount:Integer; DynamicUsage:Boolean):Boolean;
Var
Index:Single;
I, N:Integer;
Flags:Integer;
P:Pointer;
Begin
Self._Vertices := Vertices;
Self._IndexList := IndexData;
Self._EdgeList := EdgeData;
Self._Dynamic := DynamicUsage;
Self._TriangleCount := TriangleCount;
Self._EdgeCount := 0;
Self._WireframeIndices := Nil;
Result := True;
End;
Procedure NullVBO.Invalidate;
Begin
End;
Procedure NullVBO.Submit(Wireframe: Boolean);
Begin
End;
{ NullCubeMap }
Function NullCubeMap.Bind(Slot: Integer):Boolean;
Begin
Result := True;
End;
Function NullCubeMap.Generate(Width, Height:Integer; SourceFormat, TargetFormat:TextureColorFormat; ByteFormat:PixelSizeType): Boolean;
Begin
_Width := Width;
_Height := Height;
Self.SetWrapMode(wrapNothing);
Self.MipMapped := True;
Self.SetFilter(filterBilinear);
Result := True;
End;
Procedure NullCubeMap.Invalidate;
Begin
End;
{ NullFBO }
Function NullFBO.Generate(Width, Height:Integer; MultiSample:Boolean; PixelSize:PixelSizeType; TargetCount:Integer; DepthBuffer,StencilBuffer:Boolean):Boolean;
Begin
Self._Size := Width * Height * 4 * 2;
_BackgroundColor := ColorCreate(Byte(0), Byte(0), Byte(0), Byte(0));
_PixelSize := PixelSize;
_Width := Width;
_Height := Height;
Result := True;
End;
Procedure NullFBO.BeginCapture(Flags: Cardinal);
Begin
GraphicsManager.Instance.ActiveViewport.SetViewArea(0, 0, _Width, _Height);
End;
Procedure NullFBO.EndCapture;
Begin
End;
Procedure NullFBO.Resize(NewWidth, NewHeight:Integer);
Begin
_Width := NewWidth;
_Height := NewHeight;
End;
Function NullFBO.Bind(Slot: Integer):Boolean;
Begin
Result := True;
End;
Function NullFBO.GetImage():Image;
Begin
Result := Image.Create(_Width, _Height);
End;
Function NullFBO.GetPixel(X,Y:Integer):Color;
Begin
Result := ColorNull;
End;
Procedure NullFBO.Invalidate;
Begin
End;
{ NullTexture }
Function NullTexture.Bind(Slot: Integer): Boolean;
Begin
Result := True;
End;
Function NullTexture.Generate(Pixels: Pointer; Width, Height:Integer; SourceFormat, TargetFormat:TextureColorFormat; ByteFormat:PixelSizeType): Boolean;
Begin
_Width := Width;
_Height := Height;
_Size := Trunc(4 * _Width * _Height);
Result := True;
End;
Function NullTexture.GetImage:Image;
Begin
Result := Image.Create(_Width, _Height);
End;
Procedure NullTexture.Invalidate;
Begin
End;
{ NullShader }
Function NullShader.Bind:Boolean;
Begin
Result := True;
End;
Function NullShader.GetAttributeHandle(const Name: TERRAString): Integer;
Begin
Result := 1;
End;
Function NullShader.GetUniform(Name: TERRAString): Integer;
Begin
Result := 2;
End;
Procedure NullShader.Invalidate;
Begin
_VertexShaderHandle := 0;
_FragmentShaderHandle := 0;
_Program := 0;
_AttributeCount := 0;
// _Status := rsUnloaded;
_Linked := False;
End;
Function NullShader.IsReady: Boolean;
Begin
Result := _Linked;
End;
Procedure NullShader.SetFloatUniform(const Name: TERRAString; const Value: Single);
Begin
End;
Procedure NullShader.SetIntegerUniform(const Name: TERRAString; const Value: Integer);
Begin
End;
Procedure NullShader.SetMat3Uniform(const Name: TERRAString; Value: Matrix3x3);
Begin
End;
Procedure NullShader.SetMat4Uniform(const Name: TERRAString; Value: Matrix4x4);
Begin
End;
Procedure NullShader.SetVec2Uniform(const Name: TERRAString; const Value: Vector2D);
Begin
End;
Procedure NullShader.SetVec3Uniform(const Name: TERRAString; const Value: Vector3D);
Begin
End;
Procedure NullShader.SetVec4Uniform(const Name: TERRAString; const Value:Vector4D);
Begin
End;
Procedure NullShader.SetVec4ArrayUniform(const Name: TERRAString; Count:Integer; Values: PVector4D);
Begin
End;
Function NullShader.Generate(const Name: TERRAString; ShaderCode: TERRAString): Boolean;
Begin
Result := True;
End;
Function NullShader.Unbind: Boolean;
Begin
Result := True;
End;
End.
|
unit tgshbot;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, tgsendertypes
;
type
{ TTgShBot }
TTgShBot = class (TTelegramSender)
private
FServiceUser: Int64;
protected
function IsAdminUser(ChatID: Int64): Boolean; override;
function IsBanned(ChatID: Int64): Boolean; override;
public
{ Independently split too large messages and waits in case of error 429 }
function sendMessageCode(const AMessage: String; ReplyMarkup: TReplyMarkup = nil): Boolean; overload;
function sendMessageSafe(const AMessage: String; ParseMode: TParseMode = pmDefault;
DisableWebPagePreview: Boolean=False; ReplyMarkup: TReplyMarkup = nil;
ReplyToMessageID: Integer = 0): Boolean; overload;
property ServiceUser: Int64 read FServiceUser write FServiceUser;
end;
function IsolateShellOutput(const S: String): String;
implementation
uses
configuration, fpjson
;
function IsolateShellOutput(const S: String): String;
begin
Result:='```sh'+LineEnding+S+LineEnding+'```';
end;
{ TTgShBot }
function TTgShBot.IsAdminUser(ChatID: Int64): Boolean;
begin
Result:=Cnfg.Users[ChatID]=usAdmin;
end;
function TTgShBot.IsBanned(ChatID: Int64): Boolean;
begin
Result:=Cnfg.Users[ChatID]=usBanned;
end;
function TTgShBot.sendMessageCode(const AMessage: String;
ReplyMarkup: TReplyMarkup): Boolean;
var
Msg, MsgRest: String;
const
MaxMsgLength = 4096; // Maximum message length to send
MsgPartLength = 3500; // Length of one message part for the splitting
begin
Result:=False;
if AMessage<>EmptyStr then
begin
Msg:=IsolateShellOutput(AMessage);
if Length(Msg)<MaxMsgLength then
Result:=sendMessageSafe(Msg, pmMarkdown, False, ReplyMarkup)
else begin
MsgRest:=AMessage;
while MsgRest<>EmptyStr do
begin
Msg:=LeftStr(MsgRest, MsgPartLength);
MsgRest:=RightStr(AMessage, Length(MsgRest)-Length(Msg));
Result:=sendMessageSafe(IsolateShellOutput(Msg), pmMarkdown, False, ReplyMarkup);
Sleep(300);
end;
end;
end
else
Result:=True;
end;
function TTgShBot.sendMessageSafe(const AMessage: String;
ParseMode: TParseMode; DisableWebPagePreview: Boolean;
ReplyMarkup: TReplyMarkup; ReplyToMessageID: Integer): Boolean;
var
SleepTime: Integer;
aChatID: Int64;
begin
aChatID:=CurrentChatId;
if CurrentChatId=0 then
aChatID:=FServiceUser;
Result:=sendMessage(aChatID, AMessage, ParseMode, DisableWebPagePreview, ReplyMarkup, ReplyToMessageID);
if not Result then
if LastErrorCode=429 then // Too many requests
begin
try
SleepTime:=(JSONResponse as TJSONObject).Integers['retry_after']*MSecsPerSec;
except
SleepTime:=20*MSecsPerSec;
end;
sleep(SleepTime); { TODO : Provide protection from unlikely loops }
Result:=sendMessageSafe(AMessage, ParseMode, DisableWebPagePreview, ReplyMarkup, ReplyToMessageID);
end;
end;
end.
|
unit jc.Libs.Interfaces;
interface
uses
Classes, System.SysUtils;
type
IJcIniFile = interface
['{D9DBD781-CA6C-401A-B58B-6620CBBBF5EC}']
function FileName(const Value: string): IJcIniFile;
function AddSection(const Section, Values: string): IJcIniFile;
function AddString(const Section, Ident, Value: string): IJcIniFile;
function AddInteger(const Section, Ident: string; Value: integer): IJcIniFile;
function AddBoolean(const Section, Ident: string; Value: Boolean): IJcIniFile;
function DeleteKey(const Section, Ident: String): IJcIniFile;
function DeleteSection(const Section: String): IJcIniFile;
function GetSections(var Sections: TStrings): IJcIniFile;
function GetSectionValues(const Section: String; Strings: TStrings): IJcIniFile;
function GetString(const Section, Ident, Default: string): string;
function GetInteger(const Section, Ident: string; Default: integer): integer;
function GetBoolean(const Section, Ident: string; Default: Boolean): Boolean;
end;
IJcLog = interface
['{32FB4942-419A-4E91-8405-FF6E3DE45393}']
function CatchException(Sender: TObject; E: Exception): IJcLog;
function CustomMsg(Msg: String): IJcLog;
function SaveLog(Alog: String = ''): IJcLog;
function SaveError: IJcLog;
function ShowLog(Alog: String = ''): IJcLog;
function showError: IJcLog;
end;
implementation
end.
|
unit GX_UnitPositions;
interface
uses
Classes, ToolsAPI, mPasLex;
type
TUnitPosition = record
Name: string;
Position: Integer;
end;
TUnitPositions = class(TObject)
private
FParser: TmwPasLex;
FFileContent: string;
FPosList: TStringList;
procedure GetPositions;
function GetCount: Integer;
function GetPosition(Index: Integer): TUnitPosition;
public
constructor Create(const SourceEditor: IOTASourceEditor);
destructor Destroy; override;
property Count: Integer read GetCount;
property Positions[Index: Integer]: TUnitPosition read GetPosition;
end;
implementation
uses
SysUtils, GX_OtaUtils;
resourcestring
SUnitName = 'unit';
SProgramName = 'program';
SLibraryName = 'library';
SInterfaceName = 'interface';
SInterfaceUsesName = 'interface uses';
SImplementationName = 'implementation';
SImplementationUsesName = 'implementation uses';
SInitializationName = 'initialization';
SFinalizationName = 'finalization';
SBeginName = 'begin';
SEndName = 'end.';
{ TUnitPositions }
constructor TUnitPositions.Create(const SourceEditor: IOTASourceEditor);
begin
inherited Create;
Assert(Assigned(SourceEditor));
FParser := nil;
FPosList := TStringList.Create;
FFileContent := GxOtaReadEditorTextToString(SourceEditor.CreateReader);
FParser := TmwPasLex.Create;
FParser.Origin := @FFileContent[1];
GetPositions;
end;
destructor TUnitPositions.Destroy;
begin
FreeAndNil(FPosList);
FreeAndNil(FParser);
inherited Destroy;
end;
function TUnitPositions.GetCount: Integer;
begin
Result := FPosList.Count;
end;
function TUnitPositions.GetPosition(Index: Integer): TUnitPosition;
begin
Result.Name := FPosList[Index];
Result.Position := Integer(FPosList.Objects[Index]);
end;
procedure TUnitPositions.GetPositions;
var
Section: (sUnknown, sInterface, sImplementation);
EndPos: Integer;
IsProgramOrLibrary: Boolean;
FoundBeginAlready: Boolean;
begin
Section := sUnknown;
FParser.RunPos := 0;
IsProgramOrLibrary := False;
FoundBeginAlready := False;
EndPos := -1;
while FParser.TokenID <> tkNull do
begin
case FParser.TokenID of
tkEnd: // Only the last 'end' will be recorded (see below)
EndPos := FParser.TokenPos;
tkBegin:
begin
if IsProgramOrLibrary and not FoundBeginAlready then
begin
FPosList.AddObject(SBeginName, TObject(FParser.TokenPos));
FoundBeginAlready := True;
end;
end;
tkProgram:
begin
FPosList.AddObject(SProgramName, TObject(FParser.TokenPos));
IsProgramOrLibrary := True;
end;
tkLibrary:
begin
FPosList.AddObject(SLibraryName, TObject(FParser.TokenPos));
IsProgramOrLibrary := True;
end;
tkUnit:
FPosList.AddObject(SUnitName, TObject(FParser.TokenPos));
tkFinalization:
FPosList.AddObject(SFinalizationName, TObject(FParser.TokenPos));
tkInitialization:
FPosList.AddObject(SInitializationName, TObject(FParser.TokenPos));
tkInterface:
begin
if Section = sUnknown then
begin
FPosList.AddObject(SInterfaceName, TObject(FParser.TokenPos));
Section := sInterface;
end;
end;
tkImplementation:
begin
Section := sImplementation;
FPosList.AddObject(SImplementationName, TObject(FParser.TokenPos));
end;
tkUses:
begin
if Section = sImplementation then
FPosList.AddObject(SImplementationUsesName, TObject(FParser.TokenPos))
else
FPosList.AddObject(SInterfaceUsesName, TObject(FParser.TokenPos));
end;
else // FI:W506
// Ignore the token
end;
FParser.NextNoJunk;
end;
if EndPos <> -1 then
FPosList.AddObject(SEndName, TObject(EndPos));
end;
end.
|
{ ******************************************************* }
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright (c) 1995-2007 CodeGear }
{ }
{ ******************************************************* }
unit System.IniFilesEx;
{$R-,T-,H+,X+}
interface
{$I delphi.inc}
{$I PDVCustomDefine.pas}
{$IFNDEF MSWINDOWS}
{$UNDEF CRIA_LOGS}
{$ENDIF}
uses SysUtils, Classes,
{$IFDEF BPL} VCL.Dialogs, {$ENDIF}
IniFiles;
type
TCustomIniFileHelper = class Helper for {$IFDEF MSWINDOWS} TCustomIniFile
{$ELSE} TMemIniFile {$ENDIF}
private class
var
FFileNameFull: string;
FChanged: boolean;
private
procedure SetFileNameFull(const Value: string);
function GetFileNameFull: string;
procedure SetChanged(const Value: boolean);
function GetChanged: boolean;
public
constructor Create(const AFileName: string);
property FileNameFull: string read GetFileNameFull write SetFileNameFull;
function ReadStringDefault(const Section, Ident, Default: string): string;
function ReadIntegerDefault(const Section, Ident: string;
Default: integer): integer;
function GetValuesCount(Section: string): integer;
property Changed: boolean read GetChanged write SetChanged;
function ToJson: string;
procedure FromJson(AJson: string);
procedure WriteObject(const ASection: string; AObj: TObject);
procedure ReadObject(const ASection: string; AObj: TObject);
end;
TMobiIniFile = class(TIniFile)public constructor Create(sFile: string);
end;
function GetIniFilesDir(): string;
function GetConfigFilesDir(sFile: string; usuario: string = ''): string;
procedure SetIniFilesDir(sDir: string);
procedure add_LogFileConfig(sFile: string);
function GetAppIniFileName(): string;
var
PlacementUserCod: string;
implementation
uses
System.Threading, System.SyncObjs,
System.Json, DllFunctions, System.DateUtils,
System.Rtti, System.Classes.helper, System.TypInfo, System.Rtti.helper,
{$IFDEF MSWINDOWS}
Windows, uRegistry_Functions,
{$ENDIF}
{$IFDEF VCL}
uDebug, RTLConsts, Registry;
{$ELSE}
System.IOUtils;
{$ENDIF}
var
FIniDirectory: String;
const
{$IFDEF MSWINDOWS}
barraPath = '\';
{$ELSE}
barraPath = PathDelim;
{$ENDIF}
{ TCustomIniFile } // uJson db.helper
function ISODateTimeToString(ADateTime: TDatetime): string;
var
fs: TFormatSettings;
begin
fs.TimeSeparator := ':';
result := FormatDateTime('yyyy-mm-dd hh:nn:ss', ADateTime, fs);
end;
function ISOStrToDateTime(DateTimeAsString: string): TDatetime;
begin
result := EncodeDateTime(StrToInt(Copy(DateTimeAsString, 1, 4)),
StrToInt(Copy(DateTimeAsString, 6, 2)),
StrToInt(Copy(DateTimeAsString, 9, 2)),
StrToInt(Copy(DateTimeAsString, 12, 2)),
StrToInt(Copy(DateTimeAsString, 15, 2)),
StrToInt(Copy(DateTimeAsString, 18, 2)), 0);
end;
procedure TCustomIniFileHelper.FromJson(AJson: string);
var
LJson: TJsonObject;
LSecao: TJsonArray;
Chave: string;
item: string;
Value: string;
it: TJSONPair;
itValue: TJsonValue;
pair: TJSONPair;
LItem: TJsonObject;
i: integer;
begin
LJson := TJsonObject.ParseJSONValue(AJson) as TJsonObject;
for it in LJson do
begin
Chave := it.JsonString.Value;
LJson.TryGetValue<TJsonArray>(Chave, LSecao);
for itValue in LSecao do
begin
LItem := itValue as TJsonObject;
for pair in LItem do
writeString(Chave, pair.JsonString.Value, pair.JsonValue.Value);
end;
end;
end;
function TCustomIniFileHelper.GetChanged: boolean;
begin
result := FChanged;
end;
function TCustomIniFileHelper.GetFileNameFull: string;
begin
result := FFileNameFull;
end;
function TCustomIniFileHelper.GetValuesCount(Section: string): integer;
var
str: TStringList;
begin
str := TStringList.Create;
try
ReadSectionValues(Section, str);
result := str.count;
finally
str.free;
end;
end;
function TCustomIniFileHelper.ToJson: string;
var
i, n: integer;
sec: TStringList;
it: TStringList;
s: string;
begin
sec := TStringList.Create;
it := TStringList.Create;
try
ReadSections(sec);
result := '';
for i := 0 to sec.count - 1 do
begin
ReadSection(sec[i], it);
s := '"' + sec[i] + '": [{';
for n := 0 to it.count - 1 do
begin
if n > 0 then
s := s + ', ';
s := s + '"' + it[n] + '": "' + ReadString(sec[i], it[n], '') + '"';
end;
s := s + '}]';
if result <> '' then
result := result + ', ';
result := result + s;
end;
result := '{' + result + '}';
finally
it.free;
sec.free;
end;
end;
procedure TCustomIniFileHelper.WriteObject(const ASection: string;
AObj: TObject);
var
aCtx: TRttiContext;
AFld: TRttiProperty;
AValue: TValue;
begin
aCtx := TRttiContext.Create;
try
for AFld in aCtx.GetType(AObj.ClassType).GetProperties do
begin
if AFld.Visibility in [mvPublic] then
begin
AValue := AFld.GetValue(AObj);
if AValue.IsDate or AValue.IsDateTime then
WriteString(ASection, AFld.Name, ISODateTimeToString(AValue.AsDouble))
else if AValue.IsBoolean then
WriteBool(ASection, AFld.Name, AValue.AsBoolean)
else if AValue.IsInteger then
WriteInteger(ASection, AFld.Name, AValue.AsInteger)
else if AValue.IsFloat or AValue.IsNumeric then
WriteFloat(ASection, AFld.Name, AValue.AsFloat)
else
WriteString(ASection, AFld.Name, AValue.ToString);
end;
end;
finally
aCtx.free;
end;
end;
procedure TCustomIniFileHelper.ReadObject(const ASection: string;
AObj: TObject);
var
aCtx: TRttiContext;
AFld: TRttiProperty;
AValue, ABase: TValue;
begin
aCtx := TRttiContext.Create;
try
for AFld in aCtx.GetType(AObj.ClassType).GetProperties do
begin
if AFld.Visibility in [mvPublic] then
begin
ABase := AFld.GetValue(AObj);
AValue := AFld.GetValue(AObj);
if ABase.IsDate or ABase.IsDateTime then
AValue := ISOStrToDateTime(ReadString(ASection, AFld.Name,
ISODateTimeToString(ABase.AsDouble)))
else if ABase.IsBoolean then
AValue := ReadBool(ASection, AFld.Name, ABase.AsBoolean)
else if ABase.IsInteger then
AValue := ReadInteger(ASection, AFld.Name, ABase.AsInteger)
else if ABase.IsFloat or ABase.IsNumeric then
AValue := ReadFloat(ASection, AFld.Name, ABase.AsFloat)
else
AValue := ReadString(ASection, AFld.Name, ABase.asString);
AFld.SetValue(AObj, AValue);
end;
end;
finally
aCtx.free;
end;
end;
function TCustomIniFileHelper.ReadIntegerDefault(const Section, Ident: string;
Default: integer): integer;
begin
result := strToIntDef(ReadStringDefault(Section, Ident,
intToStr(Default)), 0);
end;
function TCustomIniFileHelper.ReadStringDefault(const Section, Ident,
Default: string): string;
begin
result := ReadString(Section, Ident, '');
if result = '' then
begin
try
writeString(Section, Ident, Default);
except
end;
FChanged := true;
result := Default;
end;
end;
function GetAppIniFileName(): string;
begin
result := ExtractFileName(ParamStr(0));
result := copy(result, 1, pos('.', result) - 1) + '.ini';
end;
function AppDir(): string;
begin
result := ExtractFilePath(ParamStr(0));
end;
function GetWinDir: string;
var
LDir: array [0 .. 255] of Char;
begin
{$IFDEF VCL}
GetWindowsDirectory(LDir, 255);
result := StrPas(LDir);
{$ELSE}
result := TPath.GetSharedDocumentsPath;
{$ENDIF}
end;
{$WARN SYMBOL_DEPRECATED OFF}
procedure SlashDir(var ADiretorio: string);
// var
// LD: String;
begin
if ADiretorio = '' then
ADiretorio := barraPath
else if ADiretorio[Length(ADiretorio)] <> barraPath then
begin
ADiretorio := ADiretorio + barraPath;
end;
end;
{$WARN SYMBOL_DEPRECATED OFF}
procedure SetIniFilesDir(sDir: string);
begin
SlashDir(sDir);
FIniDirectory := sDir;
try
if not DirectoryExists(FIniDirectory) then
mkDir(FIniDirectory);
except
end;
end;
function GetConfigFilesDir(sFile: string; usuario: string = ''): string;
var
i: integer;
wf: string;
begin
if usuario = '' then
usuario := PlacementUserCod;
result := ExtractFileName(sFile);
i := pos('.', result);
if i > 1 then
result := copy(result, 1, i - 1);
wf := System.IniFilesEx.GetIniFilesDir + 'usuario' + usuario + barraPath;
if not DirectoryExists(wf) then
ForceDirectories(wf);
result := wf + result + '.config';
if (not fileExists(result)) then
if fileExists(GetWinDir + barraPath + ExtractFileName(sFile)) then
begin
wf := GetWinDir + barraPath + ExtractFileName(sFile);
{ if FileExists(wf) then // nao precisa gravar a posicao antiga.
CopyFile(pchar(wf),pchar(result),false); } // nao precisa...
end;
add_LogFileConfig(result);
end;
{$IFNDEF MSWINDOWS}
function GetProgramFilesDir: string;
begin
result := TPath.GetDocumentsPath;
end;
{$ENDIF}
function GetIniFilesDir(): string;
begin
if FIniDirectory = '' then
begin
{$IFDEF BPL}
// FIniDirectory := GetTempDir;
{$ELSE}
FIniDirectory := GetProgramFilesDir + barraPath + 'Store' + barraPath +
'Config' + barraPath;
{$ENDIF}
try
if not DirectoryExists(FIniDirectory) then
ForceDirectories(FIniDirectory);
except
end;
end;
result := FIniDirectory;
end;
constructor TCustomIniFileHelper.Create(const AFileName: string);
var
s: string;
winFileName, tmp: String;
i: integer;
begin
{$IFDEF BPL}
FFileNameFull := AFileName;
{$ELSE}
FChanged := true; // reavaliar - usado no IniFileList;
tmp := AFileName;
{$IFDEF MSWINDOWS}
i := pos(barraPath + 'store' + barraPath + 'config' + barraPath,
lowerCase(tmp));
if i > 0 then
begin
if not fileExists(tmp) then
begin
i := pos(barraPath + 'usuario', AFileName);
if i > 0 then
tmp := FIniDirectory + copy(tmp, i + 1, 255)
else
tmp := FIniDirectory + ExtractFileName(AFileName); // limpa
end;
end;
// FFileName := tmp;
s := ExtractFileName(tmp);
if tmp <> s then // checa se ja foi definido o diretorio padrao do arquivo
FFileNameFull := tmp // ja foi definido o diretorio
else
begin
if sametext(ExtractFileExt(AFileName), '.config') then
begin
FFileNameFull := GetConfigFilesDir(AFileName);
end
else
begin
if FIniDirectory = '' then
GetIniFilesDir();
if fileExists(FIniDirectory + AFileName) then
FFileNameFull := FIniDirectory + AFileName
// checa se tem o arquivo no diretorio de inicio exec
else if fileExists(AppDir + AFileName) then
// procurar primeiro no diretorio local.
FFileNameFull := AppDir + AFileName
// checa se existe o arquivo no diretorio do EXE
else
begin
winFileName := GetWinDir + barraPath + s;
if fileExists(winFileName) then
begin
try // migra as configuraoces para a pasta config.
tmp := FIniDirectory + ExtractFileName(winFileName);
CopyFile(pchar(winFileName), pchar(tmp), false);
FFileNameFull := tmp;
winFileName := '';
// Estava saindo e nao carregava o inherited do inifile
// ocorria erro para ler ou gravar - Calixto
// exit;
except
end;
end;
if (AFileName = s) and (not fileExists(winFileName)) then
FFileNameFull := FIniDirectory + AFileName
// se nao existe o arquivo... criar o arquivo localmente
else
FFileNameFull := AFileName;
end;
end;
end;
add_LogFileConfig(FFileNameFull);
{$ELSE}
FFileNameFull := tmp;
s := ExtractFileName(tmp);
if sametext(tmp, s) then
FFileNameFull := TPath.Combine(TPath.GetDocumentsPath, tmp);
{$ENDIF}
{$ENDIF}
{$IFDEF BPL}
FFileNameFull := 'c:\fontes\' + ExtractFileName(FFileNameFull);
try
inherited Create(FFileNameFull);
except
// SetDebugOn(true);
// DebugLog(FFileNameFull);
showMessage(FFileNameFull);
end;
{$ELSE}
inherited Create(FFileNameFull);
{$ENDIF}
end;
procedure TCustomIniFileHelper.SetChanged(const Value: boolean);
begin
FChanged := Value;
end;
procedure TCustomIniFileHelper.SetFileNameFull(const Value: string);
begin
FFileNameFull := Value;
end;
var
LLogFileConfig: TStringList;
LEncerrou: boolean = false;
LLock: tCriticalSection;
procedure add_LogFileConfig(sFile: string);
begin
if LEncerrou then
exit;
if not assigned(LLogFileConfig) then
LLogFileConfig := TStringList.Create;
try
System.TMonitor.Enter(LLogFileConfig);
if LLogFileConfig.IndexOf(sFile) < 0 then
LLogFileConfig.add(sFile);
finally
System.TMonitor.exit(LLogFileConfig);
end;
end;
{$IFDEF XE}
function lowS(s: string): integer;
begin
result := low(s);
end;
function highS(s: string): integer;
begin
result := high(s);
end;
{$ENDIF}
// Procura a posição de pelo menos um item da lista se esta presente no texto (como POS() - para um lista separado por virgula/ponto-virgula)
// Retorno: 0 - não encontrou; maior 0 -> indica a posição onde se inicia;
// exemplo: n := PosA( 'windows,system', 'c:\windows\system32'); -> retorna a posição encontrada para a palavra "windows"
function PosA(lista: String; texto: String): integer;
var
i: integer;
s: string;
begin
result := -1;
lista := lowerCase(lista);
texto := lowerCase(texto);
s := '';
for i := lowS(lista) to highS(lista) do
begin
case lista[i] of
',', ';':
begin
result := pos(s, texto);
if result > 0 then
exit;
s := '';
end;
else
s := s + lista[i];
end;
end;
if s <> '' then
result := pos(s, texto);
end;
var
LDir: string;
{ TMobiIniFile }
constructor TMobiIniFile.Create(sFile: string);
begin
{$IFDEF MSWINDOWS}
inherited Create(sFile);
{$ELSE}
inherited Create(TPath.Combine(TPath.GetDocumentsPath,
ExtractFileName(sFile)));
{$ENDIF}
end;
initialization
// LLogFileConfig := TStringList.Create;
LLock := tCriticalSection.Create; // compatiblidade com XE6
FIniDirectory := '';
PlacementUserCod := '0';
finalization
{$IFDEF CRIA_LOGS}
try
LDir := lowerCase(GetCurrentDir + barraPath + 'Logs');
if PosA('system,windows', LDir) > 0 then
LDir := ExtractFilePath(ParamStr(0)) + barraPath + 'Logs';
if not DirectoryExists(LDir) then
ForceDirectories(LDir);
if assigned(LLogFileConfig) then
begin
LLogFileConfig.SaveToFile(LDir + barraPath + 'ArquivosCarregados.txt');
end;
except
end;
{$ENDIF}
freeAndNil(LLogFileConfig);
LEncerrou := true;
{$IFDEF VCL}
// DebugLog('Encerrou: IniFilesEx');
{$ENDIF}
freeAndNil(LLock);
end.
|
unit HashedOptionPart;
interface
uses
Classes, DCL_intf, SearchOption_Intf;
type
THashedOptionPart = class(TAbsSearchOptionPart)
protected
FHashMap: IStrStrMap;
procedure Init;
public
constructor Create; virtual;
destructor Destroy;
function GetValues(key: String): String; override;
procedure SetValues(key, val: String); override;
property Items[key: String]: String read GetValues write SetValues;
end;
implementation
uses
HashMap, System.SysUtils, QueryReader, StrUtils;
{ THashedOptionPart }
constructor THashedOptionPart.Create;
begin
Init;
end;
destructor THashedOptionPart.Destroy;
begin
FHashMap.Clear;
FHashMap._Release;
inherited;
end;
function THashedOptionPart.GetValues(key: String): String;
begin
if key = 'use' then
result := BoolToStr( FUse )
else
result := FHashMap.GetValue( key );
end;
procedure THashedOptionPart.Init;
begin
FHashMap := TStrStrHashMap.Create;
FUse := false;
end;
procedure THashedOptionPart.SetValues(key: String; val: String);
begin
FHashMap.PutValue( key, val );
if RightStr( key, 4 ) = '.use' then FUse := ( val = 'true' );
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmUserProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, dxBar, cxMemo, cxRichEdit,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxControls, cxGridCustomView, cxGrid, cxLabel, cxContainer,
cxTextEdit, cxPC, StdCtrls, ExtCtrls, GenelDM, frmBaseForm, OraBarConn, OraUser,
cxCheckBox, cxCalc, cxImageComboBox, MemDS, VirtualTable;
type
TUserPropertiesFrm = class(TBaseform)
Panel1: TPanel;
imgToolBar: TImage;
lblDescription: TLabel;
pcUserProperties: TcxPageControl;
tsUserDetails: TcxTabSheet;
dxBarDockControl1: TdxBarDockControl;
edtUserName: TcxTextEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
edtDefaultTablespace: TcxTextEdit;
cxLabel3: TcxLabel;
edtTemporaryTablespace: TcxTextEdit;
cxLabel4: TcxLabel;
edtProfile: TcxTextEdit;
cxLabel5: TcxLabel;
edtDateCreated: TcxTextEdit;
cxLabel6: TcxLabel;
cxLabel7: TcxLabel;
edtAccountIsLocked: TcxTextEdit;
edtPasswordExpireDate: TcxTextEdit;
cxLabel8: TcxLabel;
edtUserId: TcxTextEdit;
tsUserRoles: TcxTabSheet;
tsSystemPrivileges: TcxTabSheet;
tsUserQuotas: TcxTabSheet;
tsSequenceScripts: TcxTabSheet;
redtDDL: TcxRichEdit;
dxBarManager1: TdxBarManager;
bbtnCreateUser: TdxBarButton;
bbtnDropUser: TdxBarButton;
bbtnAlterUser: TdxBarButton;
bbtnRefreshUser: TdxBarButton;
cxLabel9: TcxLabel;
edtLockDate: TcxTextEdit;
cxLabel10: TcxLabel;
cxLabel11: TcxLabel;
edtExternalName: TcxTextEdit;
edtInitialResourceGroup: TcxTextEdit;
vtRoles: TVirtualTable;
vtQuotas: TVirtualTable;
vtPrivs: TVirtualTable;
dsRoles: TDataSource;
dsSystemPrivileges: TDataSource;
dsQuotas: TDataSource;
GridGrants: TcxGrid;
GridGrantsDBTableView1: TcxGridDBTableView;
GridGrantsDBTableView1Column1: TcxGridDBColumn;
GridGrantsDBTableView1Column2: TcxGridDBColumn;
GridGrantsDBTableView1Column3: TcxGridDBColumn;
GridGrantsDBTableView1Column4: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
cxGrid1: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
cxGrid2: TcxGrid;
cxGridDBTableView2: TcxGridDBTableView;
cxGridDBColumn4: TcxGridDBColumn;
cxGridDBColumn5: TcxGridDBColumn;
cxGridDBColumn6: TcxGridDBColumn;
cxGridDBColumn7: TcxGridDBColumn;
cxGridLevel2: TcxGridLevel;
procedure pcUserPropertiesPageChanging(Sender: TObject;
NewPage: TcxTabSheet; var AllowChange: Boolean);
procedure bbtnCreateUserClick(Sender: TObject);
procedure bbtnAlterUserClick(Sender: TObject);
procedure bbtnDropUserClick(Sender: TObject);
procedure bbtnRefreshUserClick(Sender: TObject);
private
{ Private declarations }
FUserName: string;
User: TUser;
procedure GetUser;
procedure GetUserDetail;
procedure GetRoles;
procedure GetPrivs;
procedure GetQuotas;
public
{ Public declarations }
procedure Init(ObjName, OwnerName: string); override;
end;
var
UserPropertiesFrm: TUserPropertiesFrm;
implementation
{$R *.dfm}
uses frmSchemaBrowser, Util, frmUserDetail, OraStorage, OraGrants, VisualOptions,
frmSchemaPublicEvent;
procedure TUserPropertiesFrm.Init(ObjName, OwnerName: string);
var
a: boolean;
begin
inherited Show;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
top := 0;
left := 0;
FUserName := ObjName;
GetUser;
pcUserPropertiesPageChanging(self, pcUserProperties.ActivePage ,a);
end;
procedure TUserPropertiesFrm.GetUser;
begin
if User <> nil then
FreeAndNil(User);
User := TUser.Create;
User.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession;
User.USERNAME := FUserName;
User.SetDDL;
lblDescription.Caption := User.Status;
redtDDL.Text := User.GetDDL;
CodeColors(self, 'Default', redtDDL, false);
GetUserDetail;
end;
procedure TUserPropertiesFrm.GetUserDetail;
begin
edtUserId.Text := User.USER_ID;
edtUserName.Text := User.USERNAME;
edtDefaultTablespace.Text := User.DEFAULT_TABLESPACE;
edtTemporaryTablespace.Text := User.TEMPORARY_TABLESPACE;
edtProfile.Text := User.PROFILE;
edtDateCreated.Text := User.CREATED;
edtAccountIsLocked.Text := User.ACCOUNT_STATUS;
edtPasswordExpireDate.Text := User.EXPIRY_DATE;
edtLockDate.Text := User.LOCK_DATE;
edtExternalName.Text := User.EXTERNAL_NAME;
edtInitialResourceGroup.Text := User.INITIAL_RSRC_CONSUMER_GROUP;
GetRoles;
GetPrivs;
GetQuotas;
end;
procedure TUserPropertiesFrm.GetRoles;
begin
vtRoles.close;
vtRoles.Assign(User.RoleList.DSRoleList);
vtRoles.Open;
end;
procedure TUserPropertiesFrm.GetPrivs;
begin
vtPrivs.Close;
vtPrivs.Assign(User.PrivList.DSPrivList);
vtPrivs.Open;
end;
procedure TUserPropertiesFrm.GetQuotas;
begin
vtQuotas.Close;
vtQuotas.Assign(User.QuotaList.DSQuotaList);
vtQuotas.Open;
end;
procedure TUserPropertiesFrm.pcUserPropertiesPageChanging(Sender: TObject;
NewPage: TcxTabSheet; var AllowChange: Boolean);
begin
//
end;
procedure TUserPropertiesFrm.bbtnCreateUserClick(Sender: TObject);
var
u: TUser;
begin
inherited;
u := TUser.Create;
u.USERNAME := '';
u.OraSession := User.OraSession;
if UserDetailFrm.Init(u) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbUsers);
end;
procedure TUserPropertiesFrm.bbtnAlterUserClick(Sender: TObject);
begin
inherited;
if User = nil then exit;
if UserDetailFrm.Init(User) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbUsers);
end;
procedure TUserPropertiesFrm.bbtnDropUserClick(Sender: TObject);
begin
inherited;
if User = nil then exit;
if User.USERNAME = '' then exit;
if SchemaPublicEventFrm.Init(User, oeDrop) then
TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbUsers);
end;
procedure TUserPropertiesFrm.bbtnRefreshUserClick(Sender: TObject);
begin
inherited;
GetUserDetail;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraTablespace;
interface
uses Classes, SysUtils, Ora, OraStorage, DB, DBQuery, Forms, Dialogs, VirtualTable;
type
DataFile = record
NAME,
TABLESPACE_NAME: string;
SIZE: Extended;
UNITS: string;
REUSE,
AUTOEXTEND: boolean;
NEXT: Extended;
NEXT_UNITS: string;
MAX_UNLIMITED: boolean;
MAX_SIZE: Extended;
MAX_UNITS: string;
end;
TDataFile = ^DataFile;
TTablespace = class(TObject)
private
FTABLESPACE_NAME: string;
FBLOCK_SIZE,
FINITIAL_EXTENT,
FNEXT_EXTENT,
FMIN_EXTENTS,
FMAX_EXTENTS,
FPCT_INCREASE,
FMIN_EXTLEN: extended;
FSTATUS: TTablespaceStatus;
FCONTENTS: TTablespaceContents;
FLOGGING: TLoggingType;
FFORCE_LOGGING: boolean;
FEXTENT_MANAGEMENT: TTablespaceExtentManagement;
FALLOCATION_TYPE: TTablespaceAllocation;
FSEGMENT_SPACE_MANAGEMENT: TSegmentSpaceManagement;
FDEF_TAB_COMPRESSION: boolean;
FRETENTION: TTablespaceRetention;
FBIGFILE: boolean;
FDataFileList: TList;
FMode: TMode;
FOraSession: TOraSession;
function GetTablespaceDetail: String;
function GetDataFileDetail: String;
function GetDataFile(Index: Integer): TDataFile;
procedure SetDataFile(Index: Integer; DataFile: TDataFile);
function GetDataFileCount: Integer;
function GetDataFileDDL: string;
function GetAlterDataFileDDL: string;
procedure SetDataFileDDL;
public
property TABLESPACE_NAME : String read FTABLESPACE_NAME write FTABLESPACE_NAME;
property BLOCK_SIZE : extended read FBLOCK_SIZE write FBLOCK_SIZE;
property INITIAL_EXTENT : extended read FINITIAL_EXTENT write FINITIAL_EXTENT;
property NEXT_EXTENT : extended read FNEXT_EXTENT write FNEXT_EXTENT;
property MIN_EXTENTS : extended read FMIN_EXTENTS write FMIN_EXTENTS;
property MAX_EXTENTS : extended read FMAX_EXTENTS write FMAX_EXTENTS;
property PCT_INCREASE : extended read FPCT_INCREASE write FPCT_INCREASE;
property MIN_EXTLEN : extended read FMIN_EXTLEN write FMIN_EXTLEN;
property STATUS: TTablespaceStatus read FSTATUS write FSTATUS;
property CONTENTS: TTablespaceContents read FCONTENTS write FCONTENTS;
property LOGGING: TLoggingType read FLOGGING write FLOGGING;
property FORCE_LOGGING: boolean read FFORCE_LOGGING write FFORCE_LOGGING;
property EXTENT_MANAGEMENT: TTablespaceExtentManagement read FEXTENT_MANAGEMENT write FEXTENT_MANAGEMENT;
property ALLOCATION_TYPE: TTablespaceAllocation read FALLOCATION_TYPE write FALLOCATION_TYPE;
property SEGMENT_SPACE_MANAGEMENT: TSegmentSpaceManagement read FSEGMENT_SPACE_MANAGEMENT write FSEGMENT_SPACE_MANAGEMENT;
property DEF_TAB_COMPRESSION: boolean read FDEF_TAB_COMPRESSION write FDEF_TAB_COMPRESSION;
property RETENTION: TTablespaceRetention read FRETENTION write FRETENTION;
property BIGFILE: boolean read FBIGFILE write FBIGFILE;
property DataFileCount: Integer read GetDataFileCount;
property DatafileItems[Index: Integer]: TDataFile read GetDataFile write SetDataFile;
property Mode: TMode read FMode write FMode;
property OraSession: TOraSession read FOraSession write FOraSession;
procedure DataFileAdd(DataFile: TDataFile);
procedure DataFileDelete(Index: Integer);
function FindByDataFileId(FileName: string): integer;
procedure SetDDL;
function GetDDL: string;
function GetAlterDDL(OldTablespace: TTablespace): string;
function TablespaceToOnline: boolean;
function TablespaceToOffline: boolean;
function CreateTablespace(Script: string) : boolean;
function AlterTablespace(Script: string) : boolean;
function DropTablespace: boolean;
constructor Create;
destructor Destroy; override;
end;
function GetTablespaces(): string;
implementation
uses Util, frmSchemaBrowser, OraScripts, Languages;
resourcestring
strTablespaceDropped = 'Tablespace %s has been dropped.';
strTablespaceAltered = 'Tablespace %s has been altered.';
strTablespaceCreated = 'Tablespace %s has been created.';
strTablespaceOnline = 'Tablespace %s has been Online.';
strTablespaceOffline = 'Tablespace %s has been Offline.';
function GetTablespaces(): string;
begin
result := 'select * from sys.user_tablespaces order by tablespace_name ';
end;
constructor TTablespace.Create;
begin
FDataFileList := TList.Create;
inherited;
end;
destructor TTablespace.destroy;
var
i : Integer;
FDataFile: TDataFile;
begin
try
if FDataFileList.Count > 0 then
begin
for i := FDataFileList.Count - 1 downto 0 do
begin
FDataFile := FDataFileList.Items[i];
Dispose(FDataFile);
end;
end;
finally
FDataFileList.Free;
end;
inherited;
end;
function TTablespace.GetDataFile(Index: Integer): TDataFile;
begin
Result := FDataFileList.Items[Index];
end;
procedure TTablespace.SetDataFile(Index: Integer; DataFile: TDataFile);
begin
if Assigned(DataFile) then
FDataFileList.Items[Index] := DataFile;
end;
function TTablespace.GetDataFileCount: Integer;
begin
Result := FDataFileList.Count;
end;
procedure TTablespace.DataFileAdd(DataFile: TDataFile);
begin
FDataFileList.Add(DataFile);
end;
procedure TTablespace.DataFileDelete(Index: Integer);
var
FDataFile: TDataFile;
begin
FDataFile := FDataFileList.Items[Index];
Dispose(FDataFile);
FDataFileList.Delete(Index);
end;
function TTablespace.FindByDataFileId(FileName: string): integer;
var
i: integer;
begin
result := -1;
for i := 0 to FDataFileList.Count -1 do
begin
if TDataFile(FDataFileList.Items[i])^.NAME = FileName then
begin
result := i;
exit;
end;
end;
end;
function TTablespace.GetTablespaceDetail: String;
begin
Result :=
'Select * '
+' from sys.user_tablespaces '
+'WHERE tablespace_name = :pName ';
end;
function TTablespace.GetDataFileDetail: String;
begin
Result :=
'Select * '
+' from DBA_DATA_FILES '
+'WHERE tablespace_name = :pName ';
end;
procedure TTablespace.SetDDL;
var
q1: TOraQuery;
begin
if FTABLESPACE_NAME = '' then exit;
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetTablespaceDetail;
q1.ParamByName('pName').AsString := FTABLESPACE_NAME;
q1.Open;
FTABLESPACE_NAME := q1.FieldByName('TABLESPACE_NAME').AsString;
FBLOCK_SIZE := StrToFloat(isNull(q1.FieldByName('BLOCK_SIZE').AsString));
FINITIAL_EXTENT := StrToFloat(isNull(q1.FieldByName('INITIAL_EXTENT').AsString));
FNEXT_EXTENT := StrToFloat(isNull(q1.FieldByName('NEXT_EXTENT').AsString));
FMIN_EXTENTS := StrToFloat(isNull(q1.FieldByName('MIN_EXTENTS').AsString));
FMAX_EXTENTS := StrToFloat(isNull(q1.FieldByName('MAX_EXTENTS').AsString));
FPCT_INCREASE := StrToFloat(isNull(q1.FieldByName('PCT_INCREASE').AsString));
FMIN_EXTLEN := StrToFloat(isNull(q1.FieldByName('MIN_EXTLEN').AsString));
FSTATUS := tsOnline;
if q1.FieldByName('STATUS').AsString = 'READ ONLY' then FSTATUS := tsReadOnly;
if q1.FieldByName('STATUS').AsString = 'OFFLINE' then FSTATUS := tsOffline;
FCONTENTS := tcPermanent;
if q1.FieldByName('CONTENTS').AsString = 'TEMPORARY' then FCONTENTS := tcTemporary;
if q1.FieldByName('CONTENTS').AsString = 'UNDO' then FCONTENTS := tcUndo;
FLOGGING := ltDefault;
if q1.FieldByName('LOGGING').AsString = 'LOGGING' then FLOGGING := ltLogging;
if q1.FieldByName('LOGGING').AsString = 'NOLOGGING' then FLOGGING := ltNoLogging;
FFORCE_LOGGING := q1.FieldByName('FORCE_LOGGING').AsString = 'YES';
FEXTENT_MANAGEMENT := temDictionary;
if q1.FieldByName('EXTENT_MANAGEMENT').AsString = 'LOCAL' then FEXTENT_MANAGEMENT := temLocal;
FALLOCATION_TYPE := taDefault;
if q1.FieldByName('ALLOCATION_TYPE').AsString = 'UNIFORM' then
FALLOCATION_TYPE := taUniform;
if q1.FieldByName('ALLOCATION_TYPE').AsString = 'SYSTEM' then
FALLOCATION_TYPE := taAuto;
FSEGMENT_SPACE_MANAGEMENT := ssmManual;
if q1.FieldByName('SEGMENT_SPACE_MANAGEMENT').AsString = 'AUTO' then
FSEGMENT_SPACE_MANAGEMENT := ssmAuto;
FDEF_TAB_COMPRESSION := q1.FieldByName('DEF_TAB_COMPRESSION').AsString = 'ENABLED';
FRETENTION := trGuarantee;
if q1.FieldByName('RETENTION').AsString = 'NOT APPLY' then FRETENTION := trNotApply;
if q1.FieldByName('RETENTION').AsString = 'NOGUARANTEE' then FRETENTION := trNoGuarantee;
FBIGFILE := q1.FieldByName('BIGFILE').AsString = 'YES';
Q1.close;
SetDataFileDDL;
end;
procedure TTablespace.SetDataFileDDL;
var
q1: TOraQuery;
DataFile: TDataFile;
begin
if FTABLESPACE_NAME = '' then exit;
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetDataFileDetail;
q1.ParamByName('pName').AsString := FTABLESPACE_NAME;
q1.Open;
while not q1.Eof do
begin
new(DataFile);
DataFile^.TABLESPACE_NAME := FTABLESPACE_NAME;
DataFile^.NAME := q1.FieldByName('FILE_NAME').AsString;
DataFile^.SIZE := q1.FieldByName('BYTES').AsFloat;
DataFile^.UNITS := 'KB';
DataFile^.REUSE := FALSE;
DataFile^.AUTOEXTEND := q1.FieldByName('AUTOEXTENSIBLE').AsString = 'YES';
DataFile^.NEXT := 0;
DataFile^.NEXT_UNITS := '';
DataFile^.MAX_UNLIMITED := FALSE;
DataFile^.MAX_SIZE := q1.FieldByName('MAXBYTES').AsFloat;
DataFile^.MAX_UNITS := 'KB';
DataFileAdd(DataFile);
q1.Next;
end;
end;
function TTablespace.GetDataFileDDL: string;
var
i: integer;
begin
result := '';
for i := 0 to FDataFileList.Count -1 do
begin
result := result + ln
+ ' '+Str(TDataFile(FDataFileList.Items[i])^.NAME)
+' SIZE '+FloatToStr(TDataFile(FDataFileList.Items[i])^.SIZE);
//+' '+TDataFile(FDataFileList.Items[i])^.UNITS;
if TDataFile(FDataFileList.Items[i])^.REUSE then
result := result +' REUSE';
if TDataFile(FDataFileList.Items[i])^.AUTOEXTEND then
begin
result := result +ln+' AUTOEXTEND ON NEXT '
+FloatToStr(TDataFile(FDataFileList.Items[i])^.NEXT)
+' '+TDataFile(FDataFileList.Items[i])^.NEXT_UNITS
+' MAXSIZE ';
if TDataFile(FDataFileList.Items[i])^.MAX_SIZE > 0 then
result := result + FloatToStr(TDataFile(FDataFileList.Items[i])^.MAX_SIZE)
+' '+TDataFile(FDataFileList.Items[i])^.MAX_UNITS
else
result := result + ' UNLIMITED';
end;
if i <> FDataFileList.Count -1 then
result := result +',';
end;
if result <> '' then result := ln+'DATAFILE'
+result;
end;
function TTablespace.GetAlterDataFileDDL: string;
var
i: integer;
begin
result := '';
for i := 0 to FDataFileList.Count -1 do
begin
result := result + ln +'ALTER TABLESPACE '+FTABLESPACE_NAME +' ADD DATAFILE '
+ ' '+Str(TDataFile(FDataFileList.Items[i])^.NAME)
+' SIZE '+FloatToStr(TDataFile(FDataFileList.Items[i])^.SIZE);
//+' '+TDataFile(FDataFileList.Items[i])^.UNITS;
if TDataFile(FDataFileList.Items[i])^.REUSE then
result := result +' REUSE';
if TDataFile(FDataFileList.Items[i])^.AUTOEXTEND then
begin
result := result +ln+' AUTOEXTEND ON NEXT '
+FloatToStr(TDataFile(FDataFileList.Items[i])^.NEXT)
+' '+TDataFile(FDataFileList.Items[i])^.NEXT_UNITS
+' MAXSIZE ';
if TDataFile(FDataFileList.Items[i])^.MAX_SIZE > 0 then
result := result + FloatToStr(TDataFile(FDataFileList.Items[i])^.MAX_SIZE)
+' '+TDataFile(FDataFileList.Items[i])^.MAX_UNITS
else
result := result + ' UNLIMITED';
end;
if i <> FDataFileList.Count -1 then
result := result +';';
end;
end;
function TTablespace.GetDDL: string;
var
s: string;
begin
s := '';
if FCONTENTS = tcTemporary then
begin
if FBIGFILE then
result := 'CREATE BIGFILE TEMPORARY TABLESPACE '+FTABLESPACE_NAME
else
result := 'CREATE TEMPORARY TABLESPACE '+FTABLESPACE_NAME;
result := result + ln +'EXTENT MANAGEMENT LOCAL UNIFORM';
end;
if FCONTENTS = tcUndo then
begin
if FBIGFILE then
result := 'CREATE BIGFILE UNDO TABLESPACE '+FTABLESPACE_NAME
else
result := 'CREATE UNDO TABLESPACE '+FTABLESPACE_NAME;
if FBLOCK_SIZE > 0 then
result := result + ln + 'BLOCKSIZE '+FloatToStr(FBLOCK_SIZE);
if FSTATUS = tsOnline then
result := result + ln + 'ONLINE';
if FSTATUS = tsOffline then
result := result + ln + 'OFFLINE';
result := result + ln +'EXTENT MANAGEMENT LOCAL AUTOALLOCATE';
if FRETENTION = trGuarantee then
result := result + ln + 'RETENTION GUARANTEE';
if FRETENTION = trNoGuarantee then
result := result + ln + 'RETENTION NOGUARANTEE';
end;
if FCONTENTS = tcPermanent then
begin
if FBIGFILE then
result := 'CREATE BIGFILE TABLESPACE '+FTABLESPACE_NAME
else
result := 'CREATE TABLESPACE '+FTABLESPACE_NAME;
result := result + GetDataFileDDL;
if FBLOCK_SIZE > 0 then
result := result + ln + 'BLOCKSIZE '+FloatToStr(FBLOCK_SIZE);
if FLOGGING = ltLogging then
result := result + ln + 'LOGGING';
if FLOGGING = ltNoLogging then
result := result + ln + 'NOLOGGING';
if FFORCE_LOGGING then
result := result + ln + 'FORCE LOGGING';
if FDEF_TAB_COMPRESSION then
result := result + ln + 'DEFAULT COMPRESS '
else
result := result + ln + 'DEFAULT NOCOMPRESS ';
if FSTATUS = tsOnline then
result := result + ln + 'ONLINE';
if FSTATUS = tsOffline then
result := result + ln + 'OFFLINE';
if FCONTENTS = tcPermanent then
result := result + ln + 'PERMANENT';
if FALLOCATION_TYPE = taUniform then
result := result + ln + 'EXTENT MANAGEMENT LOCAL UNIFORM';
if FALLOCATION_TYPE = taAuto then
result := result + ln + 'EXTENT MANAGEMENT LOCAL AUTOALLOCATE';
if FALLOCATION_TYPE = taDefault then
result := result + ln + 'EXTENT MANAGEMENT LOCAL';
if FSEGMENT_SPACE_MANAGEMENT = ssmManual then
result := result + ln + 'SEGMENT SPACE MANAGEMENT MANUAL'
else
result := result + ln + 'SEGMENT SPACE MANAGEMENT AUTO';
end; //tcPermanent
result := result +';';
end;
function TTablespace.GetAlterDDL(OldTablespace: TTablespace): string;
var
s: string;
begin
s := '';
if FLOGGING <> OldTablespace.LOGGING then
begin
if FLOGGING = ltLogging then
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME + ' LOGGING';
if FLOGGING = ltNoLogging then
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME + ' NOLOGGING';
result := result +';';
end;
if FFORCE_LOGGING <> OldTablespace.FORCE_LOGGING then
if FFORCE_LOGGING then
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME +' FORCE LOGGING;'
else
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME +' NO FORCE LOGGING;';
if FDEF_TAB_COMPRESSION <> OldTablespace.DEF_TAB_COMPRESSION then
begin
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME +' ';
if FDEF_TAB_COMPRESSION then
result := result + 'DEFAULT COMPRESS '
else
result := result + 'DEFAULT NOCOMPRESS ';
result := result +';';
end;
if FSTATUS <> OldTablespace.STATUS then
begin
result := result + ln +'ALTER TABLESPACE '+ FTABLESPACE_NAME +' ';
if FSTATUS = tsOnline then
result := result + 'ONLINE';
if FSTATUS = tsOffline then
result := result + 'OFFLINE';
if FSTATUS = tsReadOnly then
result := result + 'READ ONLY';
result := result +';';
end;
result := result + GetAlterDataFileDDL;
end;
function TTablespace.TablespaceToOnline: boolean;
var
script: string;
begin
result := false;
if FTABLESPACE_NAME = '' then exit;
script := 'ALTER TABLESPACE '+FTABLESPACE_NAME+' ONLINE';
result := ExecSQL(Script, Format(ChangeSentence('strTablespaceOnline',strTablespaceOnline),[FTABLESPACE_NAME]), FOraSession);
end;
function TTablespace.TablespaceToOffline: boolean;
var
script: string;
begin
result := false;
if FTABLESPACE_NAME = '' then exit;
script := 'ALTER TABLESPACE '+FTABLESPACE_NAME+' OFFLINE';
result := ExecSQL(Script, Format(ChangeSentence('strTablespaceOffline',strTablespaceOffline),[FTABLESPACE_NAME]), FOraSession);
end;
function TTablespace.CreateTablespace(Script: string) : boolean;
begin
result := false;
if FTABLESPACE_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strTablespaceCreated',strTablespaceCreated),[FTABLESPACE_NAME]), FOraSession);
end;
function TTablespace.AlterTablespace(Script: string) : boolean;
begin
result := false;
if FTABLESPACE_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strTablespaceAltered',strTablespaceAltered),[FTABLESPACE_NAME]), FOraSession);
end;
function TTablespace.DropTablespace: boolean;
var
FSQL: string;
begin
result := false;
if FTABLESPACE_NAME = '' then exit;
FSQL := 'DROP TABLESPACE '+FTABLESPACE_NAME;
result := ExecSQL(FSQL, Format(ChangeSentence('strTablespaceDropped',strTablespaceDropped),[FTABLESPACE_NAME]), FOraSession);
end;
end.
|
unit D_GetAbo;
{ $Id: D_GetAbo.pas,v 1.37 2014/11/27 14:11:11 voba Exp $ }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
BottomBtnDlg, HelpCnst,
OvcBase, l3Base, k2TagGen, k2Reader, evEditorWindow, evEditor, evMemo,
StdCtrls, ExtCtrls, Buttons, vtlister, vtSpin, Mask, vtCombo, vtDateEdit,
evMultiSelectEditorWindow, evCustomEditor, evEditorWithOperations, vtStringLister,
afwControl, afwInputControl, evCustomMemo, evCommonTypes, afwControlPrim,
afwBaseControl, nevControl, evCustomEditorWindowPrim,
evCustomEditorWindow, evCustomEditorWindowModelPart,
evCustomEditorModelPart;
type
TGetAbolishDataDlg = class(TBottomBtnDlg)
lstNameStr: TvtStringlister;
Label1: TLabel;
Label2: TLabel;
memoTextStr: TevMemo;
Label3: TLabel;
edtExpDate: TvtDateEdit;
procedure edtExpDateInvalidDate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lstNameStrCurrentChanged(Sender: TObject; aNewCurrent: Integer;
aOldCurrent: Integer);
procedure memoTextStrmemoTextStr_TextSourceGetReader(Sender: TObject;
aFormat: Cardinal; var Reader: TevCustomFileReader);
procedure memoTextStrmemoTextStr_TextSourceGetWriter(Sender: TObject;
Format: Cardinal; var Writer: Tk2TagGenerator);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses
l3Chars,
l3String,
k2Tags,
evTxtRd,
evTypes,
evFacadeSelection,
evFacadeUtils,
evTagsListFilter,
evTextFormatter,
Readers,
Writers,
Block_Const,
Hyperlink_Const,
Sub_Const,
TextPara_Const,
Segment_Const,
vtDialogs
;
{$R *.DFM}
procedure TGetAbolishDataDlg.edtExpDateInvalidDate(Sender: TObject);
begin
vtMessageDlg(l3CStr('Введена неверная дата'), mtError);
ActiveControl := edtExpDate;
end;
procedure TGetAbolishDataDlg.FormCreate(Sender: TObject);
begin
inherited;
lstNameStrCurrentChanged(Self, 0, 0);
HelpContext := hcSetAbolished;
memoTextStr.TextSource.OnGetReader := memoTextStrmemoTextStr_TextSourceGetReader;
memoTextStr.KeepAllFormatting := True;
evSetPlainTextFlag(memoTextStr, False);
edtExpDate.CheckOnExit := False;
end;
procedure TGetAbolishDataDlg.lstNameStrCurrentChanged(Sender: TObject; aNewCurrent: Integer; aOldCurrent: Integer);
begin
case aNewCurrent of
0 : memoTextStr.Text := 'настоящий признан утратившим силу';
1 : memoTextStr.Text := 'настоящая признана утратившей силу';
2 : memoTextStr.Text := 'настоящее признано утратившим силу';
3 : memoTextStr.Text := 'настоящие признаны утратившими силу';
4 : memoTextStr.Text := 'прекратил действие';
5 : memoTextStr.Text := 'прекратила действие';
6 : memoTextStr.Text := 'прекратило действие';
7 : memoTextStr.Text := 'прекратило действие';
8 : memoTextStr.Text := 'снят с контроля';
9 : memoTextStr.Text := ''; //'Настоящий законопроект вступил в силу';
10 : memoTextStr.Text := ''; //'Настоящий законопроект снят с рассмотрения';
11 : memoTextStr.Text := ''; //не действует
12 : memoTextStr.Text := 'настоящий отменен';
13 : memoTextStr.Text := 'настоящее отменено';
14 : memoTextStr.Text := 'настоящая отменена';
15 : memoTextStr.Text := 'настоящие отменены';
16 : memoTextStr.Text := 'действие приостановлено';
17 : memoTextStr.Text := ''; //не применяется
18..21 : memoTextStr.Text := ''; //не вступил в силу';
end;
end;
procedure TGetAbolishDataDlg.memoTextStrmemoTextStr_TextSourceGetWriter(
Sender: TObject; Format: Cardinal; var Writer: Tk2TagGenerator);
var
l_TagFilter: TevTagsListFilter;
l_Wrap: Ik2TagGeneratorWrap;
l_Filter: Tk2TagGenerator;
begin
inherited;
if (Format = cf_RTF) then
begin
l3Free(Writer);
Writer := TevRTFWriter.Create(nil);
//Format = cf_RTF
end
else
if (Format = cf_OEMText) then
begin
if (Writer Is TevCustomTextFormatter) then
TevCustomTextFormatter(Writer).CodePage := CP_OEMLite;
//Format = cf_OEMText
end
else
if Writer <> nil then
begin
if (Format = cf_Text) OR (Format = cf_OEMText) then Exit;
l_TagFilter := TevTagsListFilter.Make([k2_typBlock, k2_typHyperlink], // - эти теги исключаем
[k2_typSub, k2_typSegment], // - эти теги включаем
[evTagAttr(k2_typTextPara, k2_tiStyle), evTagAttr(k2_typTextPara, k2_tiFont)]);
try
if Supports(l_TagFilter, Ik2TagGeneratorWrap, l_Wrap) then
begin
l_Filter := l_Wrap.Generator;
l_Filter.Link(Writer);
l3Set(Writer, l_Filter);
end;
finally
l3Free(l_TagFilter);
end;{try..finally}
end;
end;
procedure TGetAbolishDataDlg.memoTextStrmemoTextStr_TextSourceGetReader(
Sender: TObject; aFormat: Cardinal; var Reader: TevCustomFileReader);
var
l_Filter : TevTagsListFilter;
begin
inherited;
if (aFormat = cf_RTF) or (aFormat = cf_RTFLite) then
begin
l3Free(Reader);
Reader := TevRTFReader.Create(nil);
if (aFormat = cf_RTFLite) then
TevRTFReader(Reader).LiteVersion := True;
Exit;
end;{aFormat = cf_RTF}
if (Reader <> nil) then
begin
if (aFormat = cf_Text) OR (aFormat = cf_OEMText) then Exit;
l_Filter := TevTagsListFilter.Make([k2_typSub, k2_typSegment], // - эти теги исключаем
[k2_typBlock, k2_typHyperlink], // - эти теги включаем
[evTagAttr(k2_typTextPara, k2_tiStyle)]
);
try
Reader.Generator := l_Filter;
finally
l3Free(l_Filter);
end;{try..finally}
end;{Reader <> nil}
end;
end.
|
unit FileName;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, EditableObjects, Editors;
type
TFilenameEditor =
class(TInPlaceVisualControl)
Panel1: TPanel;
Button1: TButton;
Panel2: TPanel;
edValue: TEdit;
OpenDialog1: TOpenDialog;
procedure Panel2Resize(Sender: TObject);
procedure Panel1Resize(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure edValueChange(Sender: TObject);
public
procedure UpdateObject; override;
protected
procedure setEditableObject( aEditableObject : TEditableObject; options : integer ); override;
end;
implementation
{$R *.DFM}
procedure TFilenameEditor.Panel2Resize(Sender: TObject);
begin
edValue.SetBounds( 0, 0, Panel2.Width, Panel2.Height );
end;
procedure TFilenameEditor.Panel1Resize(Sender: TObject);
begin
Button1.SetBounds( 2, 2, Panel1.Width - 4, Panel1.Height - 4);
end;
procedure TFilenameEditor.UpdateObject;
begin
fEditableObject.Value := edValue.Text;
end;
procedure TFilenameEditor.setEditableObject( aEditableObject : TEditableObject; options : integer );
function Translate( str : string ) : string;
var
p : integer;
appPath : string;
begin
p := pos( '{APP}', str );
if p <> 0
then
begin
appPath := ExtractFilePath( Application.ExeName );
Delete( str, p, length('{APP}\') );
Insert( appPath, str, p );
end;
result := str;
end;
var
obj : TEditableObject;
begin
inherited;
edValue.Text := fEditableObject.Value;
obj := fEditableObject.getProperty( 'ext' );
if obj <> nil
then OpenDialog1.Filter := obj.Value;
obj := fEditableObject.getProperty( 'path' );
if obj <> nil
then OpenDialog1.InitialDir := Translate(obj.Value);
end;
procedure TFilenameEditor.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute
then edValue.Text := OpenDialog1.FileName;
end;
procedure TFilenameEditor.edValueChange(Sender: TObject);
begin
UpdateObject;
end;
end.
|
{
//
// Components : IfcCollection
//
// Copyright (c) 1998 by Woll2Woll Software
//
}
unit fcCollection;
interface
{$i fcIfDef.pas}
uses Classes, Controls, Windows, ActiveX, SysUtils, Dialogs;
type
TfcCollectionItem = class;
TfcCollection = class;
TfcSelectionMethod = procedure(Item: TfcCollectionItem) of object;
TfcCollectionItem = class(TCollectionItem)
private
FPointerTag: Pointer;
FSelectionMethod: TfcSelectionMethod;
FTag: Integer;
FOnRefreshDesign: TNotifyEvent;
protected
procedure SetSelectionMethod(Value: TfcSelectionMethod); virtual;
procedure RefreshDesign; virtual;
public
function GetInstance(const PropertyName: string): TPersistent; virtual;
procedure GotSelected; virtual;
procedure SetButtonName(Sender: TObject);
property PointerTag: Pointer read FPointerTag write FPointerTag;
property SelectionMethod: TfcSelectionMethod read FSelectionMethod write SetSelectionMethod;
property Tag: Integer read FTag write FTag;
property OnRefreshDesign: TNotifyEvent read FOnRefreshDesign write FOnRefreshDesign;
end;
TfcCollection = class(TCollection)
private
FDesigner: TControl;
function GetItems(Index: Integer): TfcCollectionItem;
protected
procedure SetDesigner(Value: TControl); virtual;
public
destructor Destroy; override;
function AddItem: TfcCollectionItem; virtual;
property Designer: TControl read FDesigner write SetDesigner;
property Items[Index: Integer]: TfcCollectionItem read GetItems;
end;
implementation
procedure TfcCollectionItem.RefreshDesign;
begin
if Assigned(FOnRefreshDesign) then FOnRefreshDesign(self);
end;
function TfcCollectionItem.GetInstance(const PropertyName: string): TPersistent;
begin
result := self;
end;
procedure TfcCollectionItem.GotSelected;
begin
end;
procedure TfcCollectionItem.SetSelectionMethod(Value: TfcSelectionMethod);
begin
end;
destructor TfcCollection.Destroy;
begin
if Designer <> nil then Designer.Free;
inherited;
end;
procedure TfcCollectionItem.SetButtonName(Sender: TObject);
begin
with (Collection as TfcCollection) do
if Designer <> nil then Designer.Update;
end;
function TfcCollection.AddItem: TfcCollectionItem;
begin
result := Add as TfcCollectionItem;
end;
function TfcCollection.GetItems(Index: Integer): TfcCollectionItem;
begin
result := TfcCollectionItem(inherited Items[Index]);
end;
procedure TfcCollection.SetDesigner(Value: TControl);
begin
FDesigner := Value;
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 ClpSecP384R1Curve;
{$I ..\..\..\..\Include\CryptoLib.inc}
interface
uses
ClpHex,
ClpBits,
ClpNat,
ClpECCurve,
ClpIECInterface,
ClpISecP384R1FieldElement,
ClpSecP384R1Point,
ClpISecP384R1Curve,
ClpISecP384R1Point,
ClpIECFieldElement,
ClpBigInteger,
ClpCryptoLibTypes;
type
TSecP384R1Curve = class sealed(TAbstractFpCurve, ISecP384R1Curve)
strict private
type
TSecP384R1LookupTable = class sealed(TInterfacedObject,
ISecP384R1LookupTable, IECLookupTable)
strict private
var
Fm_outer: ISecP384R1Curve;
Fm_table: TCryptoLibUInt32Array;
Fm_size: Int32;
function GetSize: Int32; virtual;
public
constructor Create(const outer: ISecP384R1Curve;
const table: TCryptoLibUInt32Array; size: Int32);
function Lookup(index: Int32): IECPoint; virtual;
property size: Int32 read GetSize;
end;
const
SECP384R1_DEFAULT_COORDS = Int32(TECCurve.COORD_JACOBIAN);
SECP384R1_FE_INTS = Int32(12);
class var
Fq: TBigInteger;
class function GetSecP384R1Curve_Q: TBigInteger; static; inline;
class constructor SecP384R1Curve();
strict protected
var
Fm_infinity: ISecP384R1Point;
function GetQ: TBigInteger; virtual;
function GetFieldSize: Int32; override;
function GetInfinity: IECPoint; override;
function CloneCurve(): IECCurve; override;
function CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint; overload; override;
function CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean): IECPoint; overload; override;
public
constructor Create();
function FromBigInteger(const x: TBigInteger): IECFieldElement; override;
function SupportsCoordinateSystem(coord: Int32): Boolean; override;
function CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32)
: IECLookupTable; override;
property Q: TBigInteger read GetQ;
property Infinity: IECPoint read GetInfinity;
property FieldSize: Int32 read GetFieldSize;
class property SecP384R1Curve_Q: TBigInteger read GetSecP384R1Curve_Q;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpSecP384R1FieldElement;
{ TSecP384R1Curve }
class function TSecP384R1Curve.GetSecP384R1Curve_Q: TBigInteger;
begin
result := Fq;
end;
class constructor TSecP384R1Curve.SecP384R1Curve;
begin
Fq := TBigInteger.Create(1,
THex.Decode
('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF')
);
end;
constructor TSecP384R1Curve.Create;
begin
Inherited Create(Fq);
Fm_infinity := TSecP384R1Point.Create(Self as IECCurve, Nil, Nil);
Fm_a := FromBigInteger(TBigInteger.Create(1,
THex.Decode
('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC'))
);
Fm_b := FromBigInteger(TBigInteger.Create(1,
THex.Decode
('B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF'))
);
Fm_order := TBigInteger.Create(1,
THex.Decode
('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973')
);
Fm_cofactor := TBigInteger.One;
Fm_coord := SECP384R1_DEFAULT_COORDS;
end;
function TSecP384R1Curve.CloneCurve: IECCurve;
begin
result := TSecP384R1Curve.Create();
end;
function TSecP384R1Curve.CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32): IECLookupTable;
var
table: TCryptoLibUInt32Array;
pos, i: Int32;
p: IECPoint;
begin
System.SetLength(table, len * SECP384R1_FE_INTS * 2);
pos := 0;
for i := 0 to System.Pred(len) do
begin
p := points[off + i];
TNat.Copy(SECP384R1_FE_INTS, (p.RawXCoord as ISecP384R1FieldElement).x, 0,
table, pos);
pos := pos + SECP384R1_FE_INTS;
TNat.Copy(SECP384R1_FE_INTS, (p.RawYCoord as ISecP384R1FieldElement).x, 0,
table, pos);
pos := pos + SECP384R1_FE_INTS;
end;
result := TSecP384R1LookupTable.Create(Self as ISecP384R1Curve, table, len);
end;
function TSecP384R1Curve.CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint;
begin
result := TSecP384R1Point.Create(Self as IECCurve, x, y, withCompression);
end;
function TSecP384R1Curve.CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean)
: IECPoint;
begin
result := TSecP384R1Point.Create(Self as IECCurve, x, y, zs, withCompression);
end;
function TSecP384R1Curve.FromBigInteger(const x: TBigInteger): IECFieldElement;
begin
result := TSecP384R1FieldElement.Create(x);
end;
function TSecP384R1Curve.GetFieldSize: Int32;
begin
result := Fq.BitLength;
end;
function TSecP384R1Curve.GetInfinity: IECPoint;
begin
result := Fm_infinity;
end;
function TSecP384R1Curve.GetQ: TBigInteger;
begin
result := Fq;
end;
function TSecP384R1Curve.SupportsCoordinateSystem(coord: Int32): Boolean;
begin
case coord of
COORD_JACOBIAN:
result := True
else
result := False;
end;
end;
{ TSecP384R1Curve.TSecP384R1LookupTable }
constructor TSecP384R1Curve.TSecP384R1LookupTable.Create
(const outer: ISecP384R1Curve; const table: TCryptoLibUInt32Array;
size: Int32);
begin
Inherited Create();
Fm_outer := outer;
Fm_table := table;
Fm_size := size;
end;
function TSecP384R1Curve.TSecP384R1LookupTable.GetSize: Int32;
begin
result := Fm_size;
end;
function TSecP384R1Curve.TSecP384R1LookupTable.Lookup(index: Int32): IECPoint;
var
x, y: TCryptoLibUInt32Array;
pos, i, J: Int32;
MASK: UInt32;
begin
x := TNat.Create(SECP384R1_FE_INTS);
y := TNat.Create(SECP384R1_FE_INTS);
pos := 0;
for i := 0 to System.Pred(Fm_size) do
begin
MASK := UInt32(TBits.Asr32((i xor index) - 1, 31));
for J := 0 to System.Pred(SECP384R1_FE_INTS) do
begin
x[J] := x[J] xor (Fm_table[pos + J] and MASK);
y[J] := y[J] xor (Fm_table[pos + SECP384R1_FE_INTS + J] and MASK);
end;
pos := pos + (SECP384R1_FE_INTS * 2);
end;
result := Fm_outer.CreateRawPoint(TSecP384R1FieldElement.Create(x)
as ISecP384R1FieldElement, TSecP384R1FieldElement.Create(y)
as ISecP384R1FieldElement, False);
end;
end.
|
unit eAtasOrais.Model.Consts;
interface
uses
System.SysUtils;
Const
SQL_PERIODOS : string = 'Select Num_per from tbperiodos Where Num_per <> ''9999/9'' order by Num_per Desc';
SQL_LISTA_TURMAS1 : string = 'SELECT DISTINCT Niv.Sgl_niv + ''.'' + cast(Tur.Num_tur as char(10)) as Turma from tbNiveis Niv, tbTurmas Tur ';
SQL_LISTA_TURMAS2 : string = 'WHERE ((niv.Cod_cur = tur.cod_cur) and (niv.num_niv = tur.num_niv)) and (tur.Cod_pro is not null) and (tur.num_per = :periodo) ORDER BY Niv.Sgl_niv + ''.'' + cast(tur.num_tur as char(10))';
SQL_TURMAS1 : string = 'SELECT DISTINCT Tur.Cod_cur, tur.num_niv, tur.Num_tur, tur.hor_ini, tur.hor_fim, tur.flg_diaAul, prof.Nom_cop from tbTurmas Tur, tbNiveis Niv, tbProfessor prof ';
SQL_TURMAS2 : string = 'WHERE ((niv.Cod_cur = tur.cod_cur) and (niv.num_niv = tur.num_niv)) and (prof.Cod_pro = tur.Cod_pro) and (tur.num_per = :periodo) and (Niv.Sgl_niv + ''.'' + cast(Tur.Num_tur as char(10)) = :turma)';
SQL_PROFESSORES1 : string = 'SELECT DISTINCT Prof.Nom_cop FROM tbTurmas Tur, tbProfessor Prof ';
SQL_PROFESSORES2 : string = 'WHERE (Tur.Num_per = :periodo) and (Prof.Cod_pro = Tur.Cod_pro) GROUP BY Prof.Nom_cop ORDER BY Prof.Nom_cop';
implementation
end.
|
unit XcodeUtils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, PlistFile, LazFilesUtils;
const
iPhoneOSplatform = 'iPhoneOS.platform';
// file names should utf8 encoded
// Scanning Xcode platform for available SDKs
type
TSDKFoundEvent = procedure (const Version: String;
const DeviceSDKName, DeviceSDKPath, SimSDKName, SimSDKPath: String) of object;
function ScanForSDK(const PlatformDir: String; FoundProc: TSDKFoundEvent): Boolean;
// Scanning for Templates
function XibTemplateDir(const PlatformDir: AnsiString): AnsiString;
type
TScanTemplateProc = procedure ( const TemplateName, XibFileName,
Description, IconFileName: AnsiString) of object;
procedure ScanForXibTemplates(const TemplateDir: AnsiString; Callback: TScanTemplateProc);
implementation
type
TSDKDescription = record
FullPath : String; {full SDK path}
Name : String;
Alternate : String; {alternate SDK -> iphonesimulator for iphoneos}
Version : String;
isSim : Boolean; {true for real iPhoneOS, false for iPhoneSimulator}
end;
function ReadSDKSettings(const FileName: String; var Descr: TSDKDescription): Boolean;
var
plist : TPListFile;
begin
Result:=False;
plist:=TPListFile.Create;
try
plistfile.LoadFromFile(FileName, plist);
Descr.Name:=plist.GetStrValue('CanonicalName');
Descr.Alternate:=plist.GetStrValue('AlternateSDK');
Descr.Version:=plist.GetStrValue('Version');
finally
plist.Free;
end;
end;
function isSDKDir(const SDKDir: String; var d: TSDKDescription): Boolean;
var
plist : String;
begin
plist := IncludeTrailingPathDelimiter(SDKDir)+'SDKSettings.plist';
Result:=FileExists(plist);
if not Result then Exit;
ReadSDKSettings(plist, d);
d.FullPath:=SDKDir;
end;
function ScanForSDK(const PlatformDir: String; FoundProc: TSDKFoundEvent): Boolean;
const
PlatformName: array [Boolean] of String = ('iPhoneOS.platform','iPhoneSimulator.platform');
SDKSubDir = PathDelim+'Developer'+PathDelim+'SDKs'+PathDelim;
var
isSim : Boolean;
dir : String;
sr : TSearchRec;
sdks : array of TSDKDescription;
descr : TSDKDescription;
cnt : Integer;
simname : String;
simpath : String;
i,j : Integer;
procedure AddDescription(const d: TSDKDescription);
begin
if cnt = length(sdks) then begin
if cnt = 0 then SetLength(sdks, 16)
else SetLength(sdks, cnt*2);
end;
sdks[cnt]:=d;
inc(cnt);
end;
begin
Result:=Assigned(FoundProc);
if not Result then Exit;
cnt:=0;
for isSim:=false to true do begin
dir := IncludeTrailingPathDelimiter(PlatformDir) + PlatformName[isSim] + SDKSubDir;
if FindFirst(dir+'*', faAnyFile, sr)=0 then begin
repeat
if (sr.Attr and faDirectory>0) and (ExtractFileExt(sr.Name) = '.sdk') then
if isSDKDir( dir + sr.Name, descr) then begin
descr.isSim:=isSim;
AddDescription(descr);
end;
until FindNext(sr)<>0;
FindClose(sr);
end;
end;
for i:=0 to cnt-1 do
if not sdks[i].isSim then begin
simname:='';
simpath:='';
for j:=0 to cnt-1 do
if (sdks[j].isSim) and (sdks[i].Alternate=sdks[j].Name) then begin
simname:=sdks[j].Name;
simpath:=sdks[j].FullPath;
end;
FoundProc(sdks[i].Version, sdks[i].Name, sdks[i].FullPath, simname, simpath);
end;
Result:=True;
end;
function XibTemplateDir(const PlatformDir: AnsiString): AnsiString;
const
TemplatePath = 'Developer/Library/Xcode/File Templates/User Interface';
begin
Result:=IncludeTrailingPathDelimiter(PlatformDir)+TemplatePath;
end;
procedure ScanForXibTemplates(const TemplateDir: AnsiString; Callback: TScanTemplateProc);
var
dirs : TStringList;
files : TStringList;
i,j : Integer;
plist : TPListFile;
xib : AnsiString;
name : AnsiString;
descr : AnsiString;
const
XibTemplateMask = '*.pbfiletemplate';
IconFile = 'TemplateIcon.tiff';
begin
if not Assigned(Callback) or not DirectoryExists(TemplateDir) then Exit;
dirs:=TStringList.Create;
files:=TStringList.Create;
try
EnumFilesAtDir( TemplateDir, XibTemplateMask, dirs );
for i:=0 to dirs.Count-1 do begin
if DirectoryExists(dirs[i]) then begin
files.Clear;
EnumFilesAtDir(dirs[i], files);
xib:='';
for j:=0 to files.Count-1 do
if AnsiLowerCase(ExtractFileExt(files[j]))='.plist' then begin
plist:=TPListFile.Create;
plistfile.LoadFromFile(files[j],plist);
xib:=plist.GetStrValue('MainTemplateFile');
descr:=plist.GetStrValue('Description');
name:=ChangeFileExt(xib, '');
Break;
end;
if xib<>'' then begin
xib:=IncludeTrailingPathDelimiter(dirs[i])+xib;
Callback(name, xib, descr, IncludeTrailingPathDelimiter(dirs[i])+IconFile);
end;
end;
end;
finally
dirs.Free;
files.Free;
end;
end;
end.
|
unit UFormReg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFormViewReg = class(TForm)
btnOK: TButton;
boxInfo: TGroupBox;
edName: TEdit;
labName: TLabel;
labKey: TLabel;
edKey: TEdit;
btnCancel: TButton;
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edNameChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses
RegisterProc;
{$R *.dfm}
procedure TFormViewReg.FormShow(Sender: TObject);
begin
edNameChange(Self);
end;
procedure TFormViewReg.btnOKClick(Sender: TObject);
begin
if EnterRegistrationInfo(edName.Text, edKey.Text) then
begin
Application.MessageBox(
'Registered successfully, thank you.',
'NavPanel', mb_ok or mb_iconinformation);
ModalResult := mrOK;
end
else
Application.MessageBox(
'Wrong registration data.',
'NavPanel', mb_ok or mb_iconwarning);
end;
procedure TFormViewReg.edNameChange(Sender: TObject);
begin
btnOK.Enabled := (edName.Text <> '') and (edKey.Text <> '');
end;
//------------------------
var
RegName: string;
DaysLeft: integer;
LicType: TLicType;
initialization
if not ReadRegistrationInfo(RegName, DaysLeft, LicType) then
if DaysLeft <= 0 then
begin
if MessageBox(0, 'Trial period is expired! Press OK to register.',
'NavPanel', mb_okcancel or mb_iconwarning) = IDCANCEL then Halt;
with TFormViewReg.Create(nil) do
try
if ShowModal = mrCancel then Halt;
finally
Release
end
end;
-------form not used
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.3 10/26/2004 9:55:58 PM JPMugaas
Updated refs.
Rev 1.2 4/19/2004 5:06:10 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.1 10/19/2003 3:36:18 PM DSiders
Added localization comments.
Rev 1.0 10/1/2003 12:55:20 AM JPMugaas
New FTP list parsers.
}
unit IdFTPListParseStercomOS390Exp;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase;
type
TIdSterCommExpOS390FTPListItem = class(TIdFTPListItem)
protected
FRecFormat : String;
FRecLength : Integer;
FBlockSize : Integer;
public
property RecFormat : String read FRecFormat write FRecFormat;
property RecLength : Integer read FRecLength write FRecLength;
property BlockSize : Integer read FBlockSize write FBlockSize;
end;
TIdFTPLPSterCommExpOS390 = class(TIdFTPListBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
const
STIRCOMEXPOS390 = 'Connect:Express for OS/390'; {do not localize}
// 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 "IdFTPListParseStercomOS390Exp"'*)
implementation
uses
IdException,
IdGlobal, IdFTPCommon, IdGlobalProtocols,
SysUtils;
{
"Connect:Express OS/390 FTP Guide Version 4.1" Copyright
© 2002, 2003 Sterling Commerce, Inc.
125 LIST Command accepted.
-D 2 T VB 00244 18000 FTPGDG!PSR$TST.GDG.TSTGDG0(+01)
-D 2 * VB 00244 27800 FTPV!PSR$TST.A.VVV.&REQNUMB
-F 1 R - - - FTPVAL1!PSR$TST.A.VVV
250 list completed successfully.
The LIST of symbolic files from Connect:Express Files directory available for
User FTP1 is sent. A number of File attributes are showed. Default profile FTPV
is part of the list. The Following attributes are sent:
- Dynamic or Fixed Allocation
- Allocation rule: 2 = to be created, 1 = pre-allocated, 0=to be created or replaced
- Direction Transmission, Reception, * = both
- File record format (Variable, Fixed, Blocked..)
- Record length
- Block size
}
{ TIdFTPLPSterCommExpOS390 }
class function TIdFTPLPSterCommExpOS390.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LBuf : String;
begin
Result := False;
if AListing.Count > 0 then
begin
if not IdFTPCommon.IsTotalLine(AListing[0]) then
begin
LBuf := AListing[0];
if Length(LBuf) >= 3 then
begin
if CharIsInSet(LBuf, 2, 'DF') and (LBuf[3] = ' ') then {do not localize}
begin
Result := True;
Exit;
end;
end;
if Length(LBuf) >= 5 then
begin
if CharIsInSet(LBuf, 4, '012') and (LBuf[5] = ' ') then {do not localize}
begin
Result := True;
Exit;
end;
end;
end;
end;
end;
class function TIdFTPLPSterCommExpOS390.GetIdent: String;
begin
Result := STIRCOMEXPOS390;
end;
class function TIdFTPLPSterCommExpOS390.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdSterCommExpOS390FTPListItem.Create(AOwner);
end;
class function TIdFTPLPSterCommExpOS390.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
s : TStrings;
LI : TIdSterCommExpOS390FTPListItem;
begin
LI := AItem as TIdSterCommExpOS390FTPListItem;
s := TStringList.Create;
try
SplitColumns(AItem.Data, s);
if s.Count > 3 then
begin
if s[3] <> '-' then begin {do not localize}
LI.RecFormat := s[3];
end;
end;
if s.Count > 4 then begin
LI.RecLength := IndyStrToInt64(s[4], 0);
end;
if s.Count > 5 then begin
LI.BlockSize := IndyStrToInt64(s[5], 0);
end;
if s.Count > 6 then begin
LI.FileName := s[6];
end;
finally
FreeAndNil(s);
end;
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPSterCommExpOS390);
finalization
UnRegisterFTPListParser(TIdFTPLPSterCommExpOS390);
end.
|
unit cCadClasseAluno;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TClasseAluno = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_codigo: Integer;
F_cod_classe: Integer;
F_classe: string;
F_cod_aluno: Integer;
F_aluno: string;
F_cod_congregacao: Integer;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property codigo: Integer read F_codigo
write F_codigo;
property cod_classe: Integer read F_cod_classe
write F_cod_classe;
property classe: string read F_classe
write F_classe;
property cod_aluno: Integer read F_cod_aluno
write F_cod_aluno;
property aluno: string read F_aluno
write F_aluno;
property cod_congregacao: Integer read F_cod_congregacao
write F_cod_congregacao;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TClasseAluno.Create;
begin
ConexaoDB := aConexao;
end;
destructor TClasseAluno.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TClasseAluno.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_codigo) + #13 + 'Descrição: ' + F_aluno,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_classe_aluno WHERE codigo=:codigo');
Qry.ParamByName('codigo').AsInteger := F_codigo;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TClasseAluno.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_classe_aluno SET cod_classe=:cod_classe, '+
' classe=:classe ,cod_aluno=:cod_aluno,aluno=:aluno WHERE codigo=:codigo');
Qry.ParamByName('codigo').AsInteger := F_codigo;
Qry.ParamByName('cod_classe').AsInteger := F_cod_classe;
Qry.ParamByName('classe').AsString := F_classe;
Qry.ParamByName('cod_aluno').AsInteger := F_cod_aluno;
Qry.ParamByName('aluno').AsString := F_aluno;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TClasseAluno.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_classe_aluno (cod_classe,classe,cod_aluno,aluno,cod_congregacao) '+
' VALUES(:cod_classe,:classe,:cod_aluno,:aluno,:cod_congregacao)');
Qry.ParamByName('classe').AsString := Self.F_classe;
Qry.ParamByName('aluno').AsString := Self.F_aluno;
Qry.ParamByName('cod_classe').AsInteger := Self.F_cod_classe;
Qry.ParamByName('cod_aluno').AsInteger := Self.F_cod_aluno;
Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TClasseAluno.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT codigo,cod_classe, classe,cod_aluno,aluno,cod_congregacao '+
' FROM tb_classe_aluno where codigo=:codigo ');
Qry.ParamByName('codigo').AsInteger := id;
try
Qry.Open;
Self.F_codigo := Qry.FieldByName('codigo').AsInteger;
Self.F_cod_classe := Qry.FieldByName('cod_classe').AsInteger;
Self.F_classe := Qry.FieldByName('classe').AsString;
Self.F_cod_aluno := Qry.FieldByName('cod_aluno').AsInteger;
Self.F_aluno := Qry.FieldByName('aluno').AsString;
Self.F_cod_congregacao:= Qry.FieldByName('cod_congregacao').AsInteger;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
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.9 10/26/2004 8:45:26 PM JPMugaas
Should compile.
Rev 1.8 10/26/2004 8:42:58 PM JPMugaas
Should be more portable with new references to TIdStrings and TIdStringList.
Rev 1.7 5/19/2004 10:44:28 PM DSiders
Corrected spelling for TIdIPAddress.MakeAddressObject method.
Rev 1.6 2/3/2004 11:34:26 AM JPMugaas
Should compile.
Rev 1.5.1.0 2/3/2004 11:32:26 AM JPMugaas
Should compile.
Rev 1.5 2/1/2004 2:44:20 AM JPMugaas
Bindings editor should be fully functional including IPv6 support.
Rev 1.4 2/1/2004 1:03:34 AM JPMugaas
This now work properly in both Win32 and DotNET. The behavior had to change
in DotNET because of some missing functionality and because implementing that
functionality creates more problems than it would solve.
Rev 1.3 2003.12.31 10:42:22 PM czhower
Warning removed
Rev 1.2 10/15/2003 10:12:32 PM DSiders
Added localization comments.
Rev 1.1 2003.10.11 5:47:46 PM czhower
-VCL fixes for servers
-Chain suport for servers (Super core)
-Scheduler upgrades
-Full yarn support
Rev 1.0 11/13/2002 08:43:58 AM JPMugaas
}
unit IdDsnPropEdBinding;
{
Design Note: It turns out that in DotNET, there are no services file functions and
IdPorts does not work as expected in DotNET. It is probably possible to read the
services file ourselves but that creates some portability problems as the placement
is different in every operating system.
e.g.
Linux and Unix-like systems - /etc
Windows 95, 98, and ME - c:\windows
Windows NT systems - c:\winnt\system32\drivers\etc
Thus, it will undercut whatever benefit we could get with DotNET.
About the best I could think of is to use an edit control because
we can't offer anything from the services file in DotNET.
TODO: Maybe there might be a way to find the location in a more elegant
manner than what I described.
}
interface
{$I IdCompilerDefines.inc}
{$IFDEF WIDGET_WINFORMS}
{$R 'IdDsnPropEdBindingNET.TIdDsnPropEdBindingNET.resources' 'IdDsnPropEdBindingNET.resx'}
{$ENDIF}
uses
Classes,
IdSocketHandle,
{$IFDEF WIDGET_WINFORMS}
IdDsnPropEdBindingNET;
{$ELSE}
IdDsnPropEdBindingVCL;
{$ENDIF}
{
Design Note: It turns out that in DotNET, there are no services file functions and IdPorts
does not work as expected in DotNET. It is probably possible to read the services
file ourselves but that creates some portability problems as the placement is different
in every operating system.
e.g.
Linux and Unix-like systems - /etc
Windows 95, 98, and ME - c:\windows
Windows NT systems - c:\winnt\system32\drivers\etc
Thus, it will undercut whatever benefit we could get with DotNET.
About the best I could think of is to use an edit control because
we can't offer anything from the services file in DotNET.
TODO: Maybe there might be a way to find the location in a more eligant
manner than what I described.
}
type
{$IFDEF WIDGET_WINFORMS}
TIdPropEdBindingEntry = TIdDsnPropEdBindingNET;
{$ELSE}
TIdPropEdBindingEntry = TIdDsnPropEdBindingVCL;
{$ENDIF}
procedure FillHandleList(const AList: string; ADest: TIdSocketHandles);
function GetListValues(const ASocketHandles : TIdSocketHandles) : String;
implementation
procedure FillHandleList(const AList: string; ADest: TIdSocketHandles);
begin
{$IFDEF WIDGET_WINFORMS}
IdDsnPropEdBindingNET.FillHandleList(AList,ADest);
{$ELSE}
IdDsnPropEdBindingVCL.FillHandleList(AList,ADest);
{$ENDIF}
end;
function GetListValues(const ASocketHandles : TIdSocketHandles) : String;
begin
{$IFDEF WIDGET_WINFORMS}
Result := IdDsnPropEdBindingNET.GetListValues(ASocketHandles);
{$ELSE}
Result := IdDsnPropEdBindingVCL.GetListValues(ASocketHandles);
{$ENDIF}
end;
end.
|
// Configuration dialog for Set Component Properties
// Original Author: Robert Wachtel (rwachtel@gmx.de)
unit GX_SetComponentPropsConfig;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, ActnList, Menus, StdCtrls, ComCtrls, ExtCtrls,
GX_BaseForm;
type
TfmSetComponentPropsConfig = class(TfmBaseForm)
actnAddPropertyType: TAction;
actnAddRule: TAction;
actnClearRules: TAction;
actnDefaultPropertyTypes: TAction;
actnDefaultRules: TAction;
actnDeletePropertyType: TAction;
actnDeleteRule: TAction;
actnHelp: TAction;
Actions: TActionList;
actnModifyPropertyType: TAction;
itmAdd: TMenuItem;
itmClearRules: TMenuItem;
itmDefaultRules: TMenuItem;
itmDefaultTypes: TMenuItem;
itmDelete: TMenuItem;
itmModify: TMenuItem;
itmN1: TMenuItem;
pmuProperties: TPopupMenu;
pnuPropertyTypes: TPopupMenu;
pnlContent: TPanel;
pnlButtons: TPanel;
pnlButtonsRight: TPanel;
pnlOptions: TPanel;
pnlPropDetails: TPanel;
pnlList: TPanel;
pnlPropTypes: TPanel;
pnlPropList: TPanel;
pnlPropListHeader: TPanel;
pnlPropTypesHeader: TPanel;
btnOK: TButton;
btnCancel: TButton;
btnHelp: TButton;
gbxOptions: TGroupBox;
chkSimulate: TCheckBox;
chkVerbose: TCheckBox;
chkOnlyOpenFiles: TCheckBox;
gbxPropertyToSet: TGroupBox;
lblComponent: TLabel;
lblProperty: TLabel;
lblValue: TLabel;
cbxComponents: TComboBox;
cbxProperty: TComboBox;
edtValue: TEdit;
btnAddRule: TButton;
btnDeleteRule: TButton;
lbxPropertyTypes: TListBox;
lvProperties: TListView;
procedure actnAddPropertyTypeExecute(Sender: TObject);
procedure actnAddRuleExecute(Sender: TObject);
procedure actnClearRulesExecute(Sender: TObject);
procedure actnDefaultPropertyTypesExecute(Sender: TObject);
procedure actnDefaultRulesExecute(Sender: TObject);
procedure actnDeletePropertyTypeExecute(Sender: TObject);
procedure actnDeleteRuleExecute(Sender: TObject);
procedure actnHelpExecute(Sender: TObject);
procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
procedure actnModifyPropertyTypeExecute(Sender: TObject);
procedure chkSimulateClick(Sender: TObject);
procedure chkVerboseClick(Sender: TObject);
procedure cbxPropertyEnter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lvPropertiesChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure chkOnlyOpenFilesClick(Sender: TObject);
private
FActualComponent: string;
FActualPropertyNames: TStringList;
FActualPropertyTypes: TStringList;
FSimulateOnly: Boolean;
FVerbose: Boolean;
FOnlyOpenFiles: Boolean;
function AddComponentItem(const ComponentName, ComponentProperty, ComponentValue: string): Integer;
function GetRowIndex(const ComponentName, ComponentProperty: string): Integer;
procedure SetDefaultComponents;
procedure SetDefaultPropertyTypes;
procedure SetSimulateOnly(const Value: Boolean);
procedure SetVerbose(const Value: Boolean);
procedure SetOnlyOpenFiles(const Value: Boolean);
public
procedure GetSettings;
procedure SetSettings;
property SimulateOnly: Boolean read FSimulateOnly write SetSimulateOnly;
property Verbose: Boolean read FVerbose write SetVerbose;
property OnlyOpenFiles: Boolean read FOnlyOpenFiles write SetOnlyOpenFiles;
end;
implementation
{$R *.dfm}
uses
SysUtils, Dialogs,
GX_OtaUtils, GX_GenericUtils, GX_SetComponentProps, GX_GxUtils;
// New property type input
procedure TfmSetComponentPropsConfig.actnAddPropertyTypeExecute(Sender: TObject);
resourcestring
rsAddPropertyTypeCaption = 'New Property Type';
var
NewPropertyType: string;
begin
NewPropertyType := InputBox(rsAddPropertyTypeCaption, '', '');
if (NewPropertyType <> '') and (lbxPropertyTypes.Items.IndexOf(NewPropertyType) < 0) then
lbxPropertyTypes.Items.Add(NewPropertyType);
end;
// A new or modificated rule should be saved
procedure TfmSetComponentPropsConfig.actnAddRuleExecute(Sender: TObject);
var
RowIndex: Integer;
ComponentName, ComponentProperty, ComponentValue: string;
begin
ComponentName := Copy(cbxComponents.Text + #$20, 1, Pos(#$20, cbxComponents.Text + #$20) - 1);
ComponentProperty := Copy(cbxProperty.Text + #$20, 1, Pos(#$20, cbxProperty.Text + #$20) - 1);
ComponentValue := edtValue.Text;
// Look for component name and property in grid
RowIndex := GetRowIndex(ComponentName, ComponentProperty);
// Component/property already in grid, so modify existing item
if RowIndex > -1 then
lvProperties.Items[RowIndex].SubItems[1] := edtValue.Text
else // New rule
RowIndex := AddComponentItem(ComponentName, ComponentProperty, ComponentValue);
// Try to select the item
if RowIndex > -1 then
lvProperties.Items.Item[RowIndex].Selected := True;
end;
// Clear rules
procedure TfmSetComponentPropsConfig.actnClearRulesExecute(Sender: TObject);
begin
if MessageDlg('This will delete all rules. Are you sure?', mtConfirmation, [mbYes, mbNo, mbCancel], 0) = mrYes then
lvProperties.Items.Clear;
end;
// Default property types is selcted
procedure TfmSetComponentPropsConfig.actnDefaultPropertyTypesExecute(Sender: TObject);
begin
SetDefaultPropertyTypes;
end;
// Default rules
procedure TfmSetComponentPropsConfig.actnDefaultRulesExecute(Sender: TObject);
begin
if MessageDlg('This will delete all rules and set them to default values. Are you sure?', mtConfirmation, [mbYes, mbNo, mbCancel], 0) = mrYes then
SetDefaultComponents;
end;
// Delete the selected property type(s)
procedure TfmSetComponentPropsConfig.actnDeletePropertyTypeExecute(Sender: TObject);
var
i: Integer;
begin
for i := Pred(lbxPropertyTypes.Items.Count) downto 0 do
if lbxPropertyTypes.Selected[i] then
lbxPropertyTypes.Items.Delete(i);
end;
// Delete the selected rule
procedure TfmSetComponentPropsConfig.actnDeleteRuleExecute(Sender: TObject);
var
RowIndex: Integer;
ComponentName, ComponentProperty: string;
begin
ComponentName := Copy(cbxComponents.Text + #$20, 1, Pos(#$20, cbxComponents.Text + #$20) - 1);
ComponentProperty := Copy(cbxProperty.Text + #$20, 1, Pos(#$20, cbxProperty.Text + #$20) - 1);
// Look for component name/property in the grid
RowIndex := GetRowIndex(ComponentName, ComponentProperty);
if RowIndex > -1 then
lvProperties.Items.Delete(RowIndex);
cbxComponents.Text := '';
cbxProperty.Text := '';
edtValue.Text := '';
end;
procedure TfmSetComponentPropsConfig.actnHelpExecute(Sender: TObject);
begin
GxContextHelp(Self, 47);
end;
// Enable/disable menu items
procedure TfmSetComponentPropsConfig.ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
begin
actnAddRule.Enabled := (cbxComponents.Text <> '') and (cbxProperty.Text <> '') and (edtValue.Text <> '');
actnDeleteRule.Enabled := (cbxComponents.Text <> '') and (cbxProperty.Text <> '') and (edtValue.Text <> '');
actnDeletePropertyType.Enabled := (lbxPropertyTypes.SelCount > 0);
actnModifyPropertyType.Enabled := (lbxPropertyTypes.SelCount = 1);
Handled := True;
end;
// Modify property type
procedure TfmSetComponentPropsConfig.actnModifyPropertyTypeExecute(Sender: TObject);
resourcestring
rsModifyPropertyTypeCaption = 'Modify Property Type';
var
ModifyPropertyType: string;
IndexPropertyTypes: Integer;
begin
for IndexPropertyTypes := Pred(lbxPropertyTypes.Items.Count) downto 0 do
begin
if lbxPropertyTypes.Selected[IndexPropertyTypes] then
begin
ModifyPropertyType := lbxPropertyTypes.Items[IndexPropertyTypes];
if InputQuery(rsModifyPropertyTypeCaption, '', ModifyPropertyType) then
begin
if ModifyPropertyType <> lbxPropertyTypes.Items[IndexPropertyTypes] then
begin
if (lbxPropertyTypes.Items.IndexOf(ModifyPropertyType) < 0) and (ModifyPropertyType <> '') then
lbxPropertyTypes.Items[IndexPropertyTypes] := ModifyPropertyType
else
lbxPropertyTypes.Items.Delete(IndexPropertyTypes);
end;
end;
end;
end;
end;
// Add a rule
function TfmSetComponentPropsConfig.AddComponentItem(const ComponentName,
ComponentProperty, ComponentValue: string): Integer;
begin
with lvProperties.Items.Add do begin
Caption := ComponentName;
SubItems.Add(ComponentProperty);
SubItems.Add(ComponentValue);
end;
Result := GetRowIndex(ComponentName, ComponentProperty);
end;
// Simulate checkbox is clicked
procedure TfmSetComponentPropsConfig.chkSimulateClick(Sender: TObject);
begin
FSimulateOnly := chkSimulate.Checked;
end;
// Verbose checkbox is clicked
procedure TfmSetComponentPropsConfig.chkVerboseClick(Sender: TObject);
begin
FVerbose := chkVerbose.Checked;
end;
procedure TfmSetComponentPropsConfig.chkOnlyOpenFilesClick(Sender: TObject);
begin
FOnlyOpenFiles := chkOnlyOpenFiles.Checked;
end;
// When entering the Property combobox all properties of the actual selected component are retrieved
procedure TfmSetComponentPropsConfig.cbxPropertyEnter(Sender: TObject);
var
IndexPropertyNames: Integer;
OldSelectedProperty: string;
begin
FActualComponent := cbxComponents.Text;
FActualPropertyNames.Clear;
FActualPropertyTypes.Clear;
if not Assigned(GetClass(FActualComponent)) then
ActivateClassGroup(TControl);
if GetClass(FActualComponent) <> nil then
GetPropertyNames(GetClass(FActualComponent), FActualPropertyNames, FActualPropertyTypes, lbxPropertyTypes.Items);
OldSelectedProperty := cbxProperty.Text;
cbxProperty.Clear;
for IndexPropertyNames := 0 to Pred(FActualPropertyNames.Count) do
cbxProperty.Items.Add(FActualPropertyNames[IndexPropertyNames] + #$20 + '(' + FActualPropertyTypes[IndexPropertyNames] + ')');
cbxProperty.Text := OldSelectedProperty;
end;
procedure TfmSetComponentPropsConfig.FormCreate(Sender: TObject);
begin
GxOtaGetInstalledComponentList(cbxComponents.Items, False);
FActualComponent := '';
FActualPropertyNames := TStringList.Create;
FActualPropertyTypes := TStringList.Create;
end;
procedure TfmSetComponentPropsConfig.FormDestroy(Sender: TObject);
begin
FreeAndNil(FActualPropertyNames);
FreeAndNil(FActualPropertyTypes);
end;
// Look for a given ComponentName and ComponentProperty in the listview and give back the RowIndex
function TfmSetComponentPropsConfig.GetRowIndex(const ComponentName, ComponentProperty: string): Integer;
var
i: Integer;
begin
for i := 0 to Pred(lvProperties.Items.Count) do
begin
if SameText(ComponentName, lvProperties.Items.Item[i].Caption) and SameText(ComponentProperty, lvProperties.Items.Item[i].SubItems[0]) then
begin
Result := i;
Exit;
end;
end;
Result := -1;
end;
// Save all settings in the expert setting container (TGxSetComponentPropsSettings)
procedure TfmSetComponentPropsConfig.GetSettings;
var
i: Integer;
Settings: TSetComponentPropsSettings;
begin
Settings := TSetComponentPropsSettings.GetInstance;
Settings.Components.Clear;
Settings.Properties.Clear;
Settings.Values.Clear;
for i := 0 to Pred(lvProperties.Items.Count) do
begin
Settings.Components.Add(lvProperties.Items[i].Caption);
Settings.Properties.Add(lvProperties.Items[i].SubItems[0]);
Settings.Values.Add(lvProperties.Items[i].SubItems[1]);
end;
Settings.PropertyTypes.Assign(lbxPropertyTypes.Items);
Settings.Simulate := SimulateOnly;
Settings.Verbose := Verbose;
Settings.OnlyOpenFiles := OnlyOpenFiles;
end;
procedure TfmSetComponentPropsConfig.SetDefaultComponents;
const
rsDefaultValues : array[0..2, 0..2] of string = (
('TADOConnection', 'TDatabase', 'TDataSet'),
('Connected', 'Connected', 'Active'),
('False', 'False', 'False'));
var
i: Integer;
begin
lvProperties.Items.Clear;
for i := Low(rsDefaultValues) to High(rsDefaultValues) do
AddComponentItem(rsDefaultValues[0, i], rsDefaultValues[1, i], rsDefaultValues[2, i]);
end;
procedure TfmSetComponentPropsConfig.SetDefaultPropertyTypes;
resourcestring
rsDefaultPropertyTypes = 'Boolean,Integer,String,TCaption';
begin
lbxPropertyTypes.Items.CommaText := rsDefaultPropertyTypes;
end;
// Simulate value is set
procedure TfmSetComponentPropsConfig.SetSimulateOnly(const Value: Boolean);
begin
if FSimulateOnly <> Value then
begin
FSimulateOnly := Value;
chkSimulate.Checked := Value;
end;
end;
procedure TfmSetComponentPropsConfig.SetOnlyOpenFiles(const Value: Boolean);
begin
if FOnlyOpenFiles <> Value then
begin
FOnlyOpenFiles := Value;
chkOnlyOpenFiles.Checked := Value;
end;
end;
// Verbose value is set
procedure TfmSetComponentPropsConfig.SetVerbose(const Value: Boolean);
begin
if FVerbose <> Value then
begin
FVerbose := Value;
chkVerbose.Checked := Value;
end;
end;
// Load all settings from the expert setting container (TGxSetComponentPropsSettings)
procedure TfmSetComponentPropsConfig.SetSettings;
var
i: Integer;
Settings: TSetComponentPropsSettings;
begin
Settings := TSetComponentPropsSettings.GetInstance;
lvProperties.Items.Clear;
for i := 0 to Pred(Settings.Components.Count) do
AddComponentItem(Settings.Components[i], Settings.Properties[i], Settings.Values[i]);
lbxPropertyTypes.Items.Assign(Settings.PropertyTypes);
SimulateOnly := Settings.Simulate;
Verbose := Settings.Verbose;
OnlyOpenFiles := Settings.OnlyOpenFiles;
if lvProperties.Items.Count = 0 then
SetDefaultComponents;
if lbxPropertyTypes.Items.Count = 0 then
SetDefaultPropertyTypes;
end;
// After selecting a cell in the listview the "Rules" groupbox is filled with data
procedure TfmSetComponentPropsConfig.lvPropertiesChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
begin
if Assigned(Item) and (Change = ctState) then
begin
cbxComponents.Text := Item.Caption;
cbxProperty.Text := Item.SubItems[0];
edtValue.Text := Item.SubItems[1];
end;
end;
end.
|
//Exercicio 34: Escreva um algoritmo que receba os três coeficientes de uma Equação do
//2º Grau e calcule e exiba a(s) raiz(es) da equação, se existir(em). Se não existir,
//informar ao usuário. Caso o coeficiente “a” for igual à zero, informar que não se
//trata de uma equação do segundo grau e encerre o algoritmo.
{ Solução em Portugol
Algoritmo Exercicio 34;
Var
a,b,c,delta: real;
Inicio
exiba("Programa que resolve equações do segundo grau.");
exiba("Digite o valor do coeficiente a: ");
leia(a);
exiba("Digite o valor do coeficiente b: ");
leia(b);
exiba("Digite o valor do coeficiente c: ");
leia(c);
delta <- b*b - 4*a*c;
se(a = 0)
então exiba("A equação não é do segundo grau.")
senão se(delta < 0)
então exiba("A equação não tem raízes reais.")
senão se(delta = 0)
então exiba("Raízes iguais e que valem: ", -b/(2*a))
senão exiba("Raiz 1: ", (-b + (delta)^0.5)/(2*a),"Raiz 2: ", (-b - (delta)^0.5)/(2*a));
fimse;
fimse;
fimse;
Fim.
}
// Solução em Pascal
Program Exercicio34;
uses crt;
var
a,b,c,delta: real;
begin
clrscr;
writeln('Programa que resolve equações do segundo grau.');
writeln('Digite o valor do coeficiente a: ');
readln(a);
writeln('Digite o valor do coeficiente b: ');
readln(b);
writeln('Digite o valor do coeficiente c: ');
readln(c);
delta := b*b - 4*a*c;
if(a = 0)
then writeln('A equação não é do segundo grau.')
else if(delta < 0)
then writeln('A equação não tem raízes reais.')
else if(delta = 0)
then writeln('Raízes iguais e que valem: ', -b/(2*a))
else writeln('Raiz 1: ', ((-b + (exp(0.5*ln(delta))))/(2*a)):0:2,' - Raiz 2: ', ((-b - (exp(0.5*ln(delta))))/(2*a)):0:2);
repeat until keypressed;
end. |
unit ncsMessageQueue;
// Модуль: "w:\common\components\rtl\Garant\cs\ncsMessageQueue.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TncsMessageQueue" MUID: (544E3C54031D)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, l3ProtoObject
, ncsPriorityMessageList
, SyncObjs
, ncsMessage
, Windows
;
type
_l3CriticalSectionHolder_Parent_ = Tl3ProtoObject;
{$Include w:\common\components\rtl\Garant\L3\l3CriticalSectionHolder.imp.pas}
TncsMessageQueue = class(_l3CriticalSectionHolder_)
private
f_Data: TncsPriorityMessageList;
f_DataReadyEvent: TEvent;
f_Processing: Boolean;
protected
procedure pm_SetProcessing(aValue: Boolean);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
public
procedure SignalMessageReady;
procedure Push(aMessage: TncsMessage);
function WaitForMessage(aTimeOut: LongWord = Windows.INFINITE): Boolean;
function ExtractMessage(out theMessage: TncsMessage): Boolean;
{* Увеличивает счетчик theMessage! Требуется theMessage.Free }
public
property Processing: Boolean
read f_Processing
write pm_SetProcessing;
end;//TncsMessageQueue
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, SysUtils
, l3Types
, l3Utils
//#UC START# *544E3C54031Dimpl_uses*
//#UC END# *544E3C54031Dimpl_uses*
;
{$Include w:\common\components\rtl\Garant\L3\l3CriticalSectionHolder.imp.pas}
procedure TncsMessageQueue.pm_SetProcessing(aValue: Boolean);
//#UC START# *545A157B02C2_544E3C54031Dset_var*
//#UC END# *545A157B02C2_544E3C54031Dset_var*
begin
//#UC START# *545A157B02C2_544E3C54031Dset_impl*
Lock;
try
f_Processing := aValue;
if not f_Processing then
begin
SignalMessageReady;
f_Data.Clear;
end
else
if f_Data.Count > 0 then
SignalMessageReady
else
f_DataReadyEvent.ResetEvent;
finally
Unlock;
end;
//#UC END# *545A157B02C2_544E3C54031Dset_impl*
end;//TncsMessageQueue.pm_SetProcessing
procedure TncsMessageQueue.SignalMessageReady;
//#UC START# *5451F97902B8_544E3C54031D_var*
//#UC END# *5451F97902B8_544E3C54031D_var*
begin
//#UC START# *5451F97902B8_544E3C54031D_impl*
f_DataReadyEvent.SetEvent;
//#UC END# *5451F97902B8_544E3C54031D_impl*
end;//TncsMessageQueue.SignalMessageReady
procedure TncsMessageQueue.Push(aMessage: TncsMessage);
//#UC START# *544E3DE3032D_544E3C54031D_var*
//#UC END# *544E3DE3032D_544E3C54031D_var*
begin
//#UC START# *544E3DE3032D_544E3C54031D_impl*
Lock;
try
f_Data.Add(aMessage);
SignalMessageReady;
finally
Unlock;
end;
//#UC END# *544E3DE3032D_544E3C54031D_impl*
end;//TncsMessageQueue.Push
function TncsMessageQueue.WaitForMessage(aTimeOut: LongWord = Windows.INFINITE): Boolean;
//#UC START# *5452022F026A_544E3C54031D_var*
//#UC END# *5452022F026A_544E3C54031D_var*
begin
//#UC START# *5452022F026A_544E3C54031D_impl*
if not Processing then
Result := False
else
Result := (f_DataReadyEvent.WaitFor(aTimeOut) = wrSignaled) and Processing;
//#UC END# *5452022F026A_544E3C54031D_impl*
end;//TncsMessageQueue.WaitForMessage
function TncsMessageQueue.ExtractMessage(out theMessage: TncsMessage): Boolean;
{* Увеличивает счетчик theMessage! Требуется theMessage.Free }
//#UC START# *545202810200_544E3C54031D_var*
//#UC END# *545202810200_544E3C54031D_var*
begin
//#UC START# *545202810200_544E3C54031D_impl*
Result := False;
FreeAndNil(theMessage);
if Processing then
begin
Lock;
try
if (f_Data.Count > 0) then
begin
f_Data[0].SetRefTo(theMessage);
f_Data.Delete(0);
Result := True;
end;
if (f_Data.Count = 0) then
f_DataReadyEvent.ResetEvent;
finally
Unlock;
end;
end;
//#UC END# *545202810200_544E3C54031D_impl*
end;//TncsMessageQueue.ExtractMessage
procedure TncsMessageQueue.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_544E3C54031D_var*
//#UC END# *479731C50290_544E3C54031D_var*
begin
//#UC START# *479731C50290_544E3C54031D_impl*
FreeAndNil(f_Data);
FreeAndNil(f_DataReadyEvent);
inherited Cleanup;
//#UC END# *479731C50290_544E3C54031D_impl*
end;//TncsMessageQueue.Cleanup
procedure TncsMessageQueue.InitFields;
//#UC START# *47A042E100E2_544E3C54031D_var*
//#UC END# *47A042E100E2_544E3C54031D_var*
begin
//#UC START# *47A042E100E2_544E3C54031D_impl*
inherited InitFields;
f_Data := TncsPriorityMessageList.Make;
// f_Data := TncsPriorityMessageList.MakeSorted(l3_dupError);
f_DataReadyEvent := TEvent.Create(nil, True, False, l3CreateStringGUID);
//#UC END# *47A042E100E2_544E3C54031D_impl*
end;//TncsMessageQueue.InitFields
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit TelSource;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdServerIOHandler, IdServerIOHandlerSocket, IdBaseComponent,
IdComponent, IdTCPServer, IdTelnetServer, StdCtrls, ExtCtrls, StrUtils,
IdTCPConnection, IdTCPClient, IdTelnet;
type
TCRec = record
IP, Nick: String;
Port: Integer;
Messages: array of String;
end;
TForm1 = class(TForm)
Telnet: TIdTelnetServer;
LOG: TMemo;
CL: TListBox;
PORT: TEdit;
CON: TButton;
Timer: TTimer;
TelnetC: TIdTelnet;
MSG: TEdit;
IP: TEdit;
Button1: TButton;
NICK: TEdit;
Button2: TButton;
procedure TelnetExecute(AThread: TIdPeerThread);
procedure TelnetException(AThread: TIdPeerThread;
AException: Exception);
procedure TelnetConnect(AThread: TIdPeerThread);
procedure FormCreate(Sender: TObject);
procedure TelnetDisconnect(AThread: TIdPeerThread);
procedure MSGKeyPress(Sender: TObject; var Key: Char);
procedure CONClick(Sender: TObject);
procedure TelnetCConnected(Sender: TObject);
procedure TelnetCDisconnected(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure TelnetCDataAvailable(Sender: TIdTelnet;
const Buffer: String);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Clients: array of TCRec;
N: Integer;
Connected: Boolean;
Form1: TForm1;
implementation
{$R *.dfm}
function GetClient(T: TIdPeerThread): Integer;
var I: Integer;
begin
for I:=0 to N-1 do
if (T.Connection.Socket.Binding.IP = Clients[I].IP) and
(T.Connection.Socket.Binding.Port = Clients[I].Port) then Result:=I;
end;
procedure TForm1.TelnetExecute(AThread: TIdPeerThread);
var S,R: String;
I,O: Integer;
T: Boolean;
begin
S:=AThread.Connection.ReadLn();
O:=GetClient(AThread);
{Recieving a message}
if S[1]='$' then begin
R:=RightStr(S,Length(S)-1);
AThread.Connection.WriteLn('!MSG_OK');
LOG.Lines.Add(Format('Message "%s" from client #%d (%s:%d) was recieved',[R,O+1,Clients[O].IP,Clients[O].Port]));
for I:=0 to N-1 do begin
SetLength(Clients[I].Messages, Length(Clients[I].Messages)+1);
Clients[I].Messages[Length(Clients[I].Messages)-1]:=Format('%s: %s',[Clients[O].Nick, R]);
end;
end
{Sending messages to client}
else if S='check' then begin
if Length(Clients[O].Messages)>0 then begin
for I:=0 to Length(Clients[O].Messages)-1 do
AThread.Connection.WriteLn(Clients[O].Messages[I]);
SetLength(Clients[O].Messages,0);
end
else AThread.Connection.WriteLn('!NO_MSGS');
end
{Setting up nickname}
else if S[1]='@' then begin
T:=True;
R:=RightStr(S,Length(S)-1);
for I:=0 to N-1 do
if Clients[I].Nick=R then T:=False;
if T then begin
AThread.Connection.WriteLn('!NICK_OK');
Clients[O].Nick:=R;
end else AThread.Connection.WriteLn('!NICK_FAIL');
end;
end;
procedure TForm1.TelnetException(AThread: TIdPeerThread;
AException: Exception);
begin
AThread.Connection.WriteLn(Format('?Exception: %s',[AException.Message]));
end;
procedure TForm1.TelnetConnect(AThread: TIdPeerThread);
begin
N:=N+1;
SetLength(Clients,N);
Clients[N-1].IP:=AThread.Connection.Socket.Binding.IP;
Clients[N-1].Port:=AThread.Connection.Socket.Binding.Port;
LOG.Lines.Add(Format('Client #%d connected at %s:%d',[N,Clients[N-1].IP,Clients[N-1].Port]));
CL.Items.Add(Format('#%d @ %s:%d',[N,Clients[N-1].IP,Clients[N-1].Port]));
AThread.Connection.WriteLn(Format('You are client #%d. Address: %s:%d',[N,Clients[N-1].IP,Clients[N-1].Port]));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
N:=0;
end;
procedure TForm1.TelnetDisconnect(AThread: TIdPeerThread);
var I,O: Integer;
T: TCRec;
begin
O:=GetClient(AThread);
LOG.Lines.Add(Format('Client #%d (%s:%d) disconnected',[O+1,Clients[O].IP,Clients[O].Port]));
for I:=O+1 to N-1 do begin
T:=Clients[I];
Clients[I]:=Clients[I-1];
Clients[I-1]:=T;
CL.Items.Strings[I-1]:=Format('#%d @ %s:%d',[I,Clients[I-1].IP,Clients[I-1].Port]);
end;
N:=N-1;
CL.Items.Delete(N);
end;
procedure TForm1.MSGKeyPress(Sender: TObject; var Key: Char);
begin
if (Ord(Key)=vk_Return) and Connected then
TelnetC.WriteLn(Format('$%s',[MSG.Text]));
end;
procedure TForm1.CONClick(Sender: TObject);
begin
TelnetC.BoundIP:=IP.Text;
TelnetC.BoundPort:=StrToInt(Port.Text);
TelnetC.Connect();
end;
procedure TForm1.TelnetCConnected(Sender: TObject);
begin
Connected:=True;
MessageBox(256,'Connected!','Telnet chat client',0);
NICK.Enabled:=True;
Button2.Enabled:=True;
MSG.Enabled:=True;
Button2Click(Self);
end;
procedure TForm1.TelnetCDisconnected(Sender: TObject);
begin
Connected:=False;
NICK.Enabled:=False;
Button2.Enabled:=False;
MSG.Enabled:=False;
end;
procedure TForm1.TimerTimer(Sender: TObject);
begin
if Connected then
TelnetC.WriteLn('check');
end;
procedure TForm1.TelnetCDataAvailable(Sender: TIdTelnet;
const Buffer: String);
begin
LOG.Lines.Add(Buffer);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Telnet.Active:=True;
MessageBox(256,'Server started!','Telnet chat server',0);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Connected then
TelnetC.WriteLn(Format('@%s',[NICK.Text]));
end;
end.
|
unit AceSetup;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995-2005 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses AceTypes, classes, AcePSet, winspool, windows;
const
ACEPAPER_USECURRENT = 9999;
{These print quality defines are directly coded in ACE due to a bug in }
{Delphi 5's Windows.PAS file which defines these as LongInts which can }
{cause rangecheck errors}
{ aceDMRES_DRAFT = -1;
aceDMRES_LOW = -2;
aceDMRES_MEDIUM = -3;
aceDMRES_HIGH = -4;
}
type
{ TAcePrinterSetup }
TAcePrinterSetup = class(TObject)
private
FOrientation: Integer;
FPaperSize: Integer;
FLength: Double;
FWidth: Double;
FScale: Integer;
FCopies: Integer;
FSource: Integer;
FPrintQuality: Integer;
FColor: Integer;
FDuplex: Integer;
FYResolution: Integer;
FTTOption: Integer;
FCollatedCopies: Boolean;
FFormName: String;
FLeftPrintArea, FRightPrintArea: Double;
FTopPrintArea, FBottomPrintArea: Double;
FPrinterSettings: TAcePrinterSettings;
FPrintSet: array[0..13] of Boolean;
procedure SetDataWithFlag(Reset: Boolean);
protected
function GetPrinterCount: Integer;
function GetXPixels: Integer;
function GetYPixels: Integer;
procedure SetOrientation(Value: Integer);
procedure SetPaperSize(Value: Integer);
procedure SetLength(Value: Double);
procedure SetWidth(Value: Double);
procedure SetScale(Value: Integer);
procedure SetCopies(Value: Integer);
procedure SetSource(Value: Integer);
procedure SetPrintQuality(Value: Integer);
procedure SetColor(Value: Integer);
procedure SetDuplex(Value: Integer);
procedure SetYResolution(Value: Integer);
procedure SetTTOption(Value: Integer);
procedure SetCollatedCopies(Value: Boolean);
procedure SetFormName(Value: String);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign( Source: TObject); virtual;
procedure CopyToPrinterSettings;
procedure CopyFromPrinterSettings;
procedure ClearSettings;
procedure SetPrintInfo( pinfo: TAceFilePrinterInfo );
procedure GetPrintInfo( var pinfo: TAceFilePrinterInfo );
function ReadFromAceFile(af: TObject): Boolean;
function ReadFromStream(Stream: TStream): Boolean;
procedure WriteToAceFile(af: TObject);
procedure WriteToStream(Stream: TStream);
procedure SetData;
procedure SetDataReset;
procedure GetData;
property PrinterCount: Integer read GetPrinterCount;
property PixelsPerInchX: Integer read GetXPixels;
property PixelsPerInchY: Integer read GetYPixels;
property LeftPrintArea: Double read FLeftPrintArea;
property TopPrintArea: Double read FTopPrintArea;
property RightPrintArea: Double read FRightPrintArea;
property BottomPrintArea: Double read FBottomPrintArea;
property Orientation: Integer read FOrientation write SetOrientation;
property PaperSize: Integer read FPaperSize write SetPaperSize;
property Length: Double read FLength write SetLength;
property Width: Double read FWidth write SetWidth;
property Scale: Integer read FScale write SetScale;
property Copies: Integer read FCopies write SetCopies;
property Source: Integer read FSource write SetSource;
property PrintQuality: Integer read FPrintQuality write SetPrintQuality;
property Color: Integer read FColor write SetColor;
property Duplex: Integer read FDuplex write SetDuplex;
property YResolution: Integer read FYResolution write SetYResolution;
property TTOption: Integer read FTTOption write SetTTOption;
property CollatedCopies: Boolean read FCollatedCopies write SetCollatedCopies;
property FormName: String read FFormName write SetFormName;
function IsEqual(ps: TAcePrinterSetup): Boolean;
function IsRunningEqual(ps: TAcePrinterSetup): Boolean;
end;
implementation
uses printers, aceutil, sysutils, acefile;
constructor TAcePrinterSetup.Create;
var
Spot: Integer;
begin
inherited Create;
FOrientation := DMORIENT_PORTRAIT;
FPaperSize := DMPAPER_LETTER;
FLength := 11;
FWidth := 8.5;
FScale := 100;
FCopies := 1;
FSource := DMBIN_UPPER;
FPrintQuality := Integer(aceDMRES_HIGH);
FColor := DMCOLOR_COLOR;
FDuplex := DMDUP_SIMPLEX;
FYResolution := 0;
FTTOption := DMTT_DOWNLOAD;
FCollatedCopies := True;
FPrinterSettings := TAcePrinterSettings.Create;
FFormName := '';
for Spot := 0 to 13 do FPrintSet[Spot] := False;
end;
destructor TAcePrinterSetup.destroy;
begin
if FPrinterSettings <> nil then FPrinterSettings.Free;
inherited destroy;
end;
procedure TAcePrinterSetup.Assign( Source: TObject );
var
ps: TAcePrinterSetup;
Spot: Integer;
begin
if Source is TAcePrinterSetup then
begin
ps := TAcePrinterSetup( Source );
FOrientation := ps.FOrientation;
FPaperSize := ps.FPaperSize;
FLength := ps.FLength;
FWidth := ps.FWidth;
FScale := ps.FScale;
FCopies := ps.FCopies;
FSource := ps.FSource;
FPrintQuality := ps.FPrintQuality;
FColor := ps.FColor;
FDuplex := ps.FDuplex;
FYResolution := ps.FYResolution;
FTTOption := ps.FTTOption;
FCollatedCopies := ps.FCollatedCopies;
FFormName := ps.FFormName;
for Spot := 0 to 13 do FPrintSet[Spot] := ps.FPrintSet[Spot];
FPrinterSettings.Assign(ps.FPrinterSettings);
end;
end;
procedure TAcePrinterSetup.SetPrintInfo( pinfo: TAceFilePrinterInfo );
var
Spot: Integer;
begin
FOrientation := pinfo.Orientation;
FPaperSize := pinfo.PaperSize;
FLength := pinfo.Length;
FWidth := pinfo.Width;
FScale := pinfo.Scale;
FCopies := pinfo.Copies;
FSource := pinfo.Source;
FPrintQuality := pinfo.PrintQuality;
FColor := pinfo.Color;
FDuplex := pinfo.Duplex;
FYResolution := pinfo.YResolution;
FTTOption := pinfo.TTOption;
FCollatedCopies := pinfo.CollatedCopies;
for Spot := 0 to 13 do FPrintSet[Spot] := True;
end;
procedure TAcePrinterSetup.ClearSettings;
var
Spot: Integer;
begin
for Spot := 0 to 13 do FPrintSet[Spot] := False;
end;
procedure TAcePrinterSetup.GetPrintInfo( var pinfo: TAceFilePrinterInfo );
begin
with pinfo do
begin
Orientation := FOrientation;
PaperSize := FPaperSize;
Length := FLength;
Width := FWidth;
Scale := FScale;
Copies := FCopies;
Source := FSource;
PrintQuality := FPrintQuality;
Color := FColor;
Duplex := FDuplex;
YResolution := FYResolution;
TTOption := FTTOption;
CollatedCopies := FCollatedCopies;
end;
end;
function TAcePrinterSetup.IsEqual(ps: TAcePrinterSetup): Boolean;
begin
Result := True;
if FOrientation <> ps.Orientation then Result := False;
if FPaperSize <> ps.PaperSize then Result := False;
if FLength <> ps.Length then Result := False;
if FWidth <> ps.Width then Result := False;
if FScale <> ps.Scale then Result := False;
if FCopies <> ps.Copies then Result := False;
if FSource <> ps.Source then Result := False;
if FPrintQuality <> ps.PrintQuality then Result := False;
if FColor <> ps.Color then Result := False;
if FDuplex <> ps.Duplex then Result := False;
if FYResolution <> ps.YResolution then Result := False;
if FTTOption <> ps.TTOption then Result := False;
if FCollatedCopies <> ps.CollatedCopies then Result := False;
if FFormName <> ps.FormName then Result := False;
end;
function TAcePrinterSetup.IsRunningEqual(ps: TAcePrinterSetup): Boolean;
begin
Result := True;
if FOrientation <> ps.Orientation then Result := False;
if FPaperSize <> ps.PaperSize then Result := False;
if FLength <> ps.Length then Result := False;
if FWidth <> ps.Width then Result := False;
if FCopies <> ps.Copies then Result := False;
if FSource <> ps.Source then Result := False;
if FDuplex <> ps.Duplex then Result := False;
if FCollatedCopies <> ps.CollatedCopies then Result := False;
if FFormName <> ps.FormName then Result := False;
end;
function TAcePrinterSetup.GetPrinterCount: Integer;
var
DefaultPrinter: array[0..79] of Char;
begin
result := Printers.Printer.Printers.Count;
{ under win95 there was some unknown printer always coming
up when there really was none. I made the asumption that
if there isn't a default printer then there are no printers
defined. This wasn't tested under NT or win3.1 so I don't
know if it was needed under that. }
GetProfileString('windows', 'device', '', DefaultPrinter,
(SizeOf(DefaultPrinter) div SizeOf(Char)) - 1); // added Sizeof 8/8/2016 SCT
if DefaultPrinter[0] = #0 then result := 0;
end;
function TAcePrinterSetup.GetXPixels: Integer;
begin
result := GetDeviceCaps(Printers.Printer.handle, LOGPIXELSX);
end;
function TAcePrinterSetup.GetYPixels: Integer;
begin
result := GetDeviceCaps(Printers.Printer.handle, LOGPIXELSY);
end;
procedure TAcePrinterSetup.CopyFromPrinterSettings;
begin
FOrientation := FPrinterSettings.Orientation;
FPaperSize := FPrinterSettings.PaperSize;
FLength := FPrinterSettings.PaperLength / 254;
FWidth := FPrinterSettings.PaperWidth / 254;
if (FLength <= 0) or (FWidth <= 0) then
begin
FLength := 11;
FWidth := 8.5;
end;
FScale := FPrinterSettings.Scale;
FCopies := FPrinterSettings.Copies;
FSource := FPrinterSettings.DefaultSource;
FPrintQuality := FPrinterSettings.PrintQuality;
FColor := FPrinterSettings.Color;
FDuplex := FPrinterSettings.Duplex;
FYResolution := FPrinterSettings.YResolution;
FTTOption := FPrinterSettings.TTOption;
{ FCollatedCopies := FPrinterSettings.FCollatedCopies;}
FFormName := FPrinterSettings.FormName;
end;
procedure TAcePrinterSetup.CopyToPrinterSettings;
begin
if FPrintSet[0] then FPrinterSettings.Orientation := FOrientation;
if FPrintSet[1] then FPrinterSettings.PaperSize := FPaperSize;
if FPrintSet[2] then FPrinterSettings.PaperLength := Round(FLength * 254);
if FPrintSet[3] then FPrinterSettings.PaperWidth := Round(FWidth * 254);
if FPrintSet[4] then FPrinterSettings.Scale := FScale;
if FPrintSet[5] then FPrinterSettings.Copies := FCopies;
if FPrintSet[6] then FPrinterSettings.DefaultSource := FSource;
if FPrintSet[7] then FPrinterSettings.PrintQuality := FPrintQuality;
if FPrintSet[8] then FPrinterSettings.Color := FColor;
if FPrintSet[9] then FPrinterSettings.Duplex := FDuplex;
if FPrintSet[10] then FPrinterSettings.YResolution := FYResolution;
if FPrintSet[11] then FPrinterSettings.TTOption := FTTOption;
{ FCollatedCopies := FPrinterSettings.FCollatedCopies;}
if FPrintSet[13] then FPrinterSettings.FormName := FFormName;
end;
procedure TAcePrinterSetup.SetDataWithFlag(Reset: Boolean);
begin
CopyToPrinterSettings;
if AceGetPrinterCount > 0 Then
begin
FPrinterSettings.SetValues(Reset);
end;
GetData;
end;
procedure TAcePrinterSetup.SetDataReset;
begin
SetDataWithFlag(true);
end;
procedure TAcePrinterSetup.SetData;
begin
SetDataWithFlag(false);
end;
procedure TAcePrinterSetup.GetData;
var
{ POffset: TPoint;
hres, vres: Integer;
W,L: Double;}
PRect: TRect;
Size, Res: TPoint;
begin
if AceGetPrinterCount > 0 Then
begin
{$ifdef commentout}
FPrinterSettings.GetValues;
CopyFromPrinterSettings;
Escape(Printers.Printer.handle, GETPRINTINGOFFSET, 0, nil, @POffset);
hres := GetDeviceCaps(Printers.Printer.handle, HorzRes);
vres := GetDeviceCaps(Printers.Printer.handle, VertRes);
L := GetDeviceCaps(Printers.Printer.handle, PHYSICALHEIGHT) / PixelsPerInchY;
W := GetDeviceCaps(Printers.Printer.handle, PHYSICALWIDTH) / PixelsPerInchX;
FLeftPrintArea := POffset.x / PixelsPerInchX;
FTopPrintArea := POffset.y / PixelsPerInchY;
FRightPrintArea := W - (hres / PixelsPerInchX) - FLeftPrintArea;
FBottomPrintArea := L - (vres / PixelsPerInchY) - FTopPrintArea;
if FRightPrintArea < 0 then FRightPrintArea := 0;
if FBottomPrintArea < 0 then FBottomPrintArea := 0;
{$endif}
FPrinterSettings.GetValues;
CopyFromPrinterSettings;
PRect := AceGetPrintableArea(Printers.Printer.Handle);
Size := AceGetPhysicalSize(Printers.Printer.Handle);
Res := AceGetResolution(Printers.Printer.Handle);
FLeftPrintArea := PRect.Left / Res.x;
FTopPrintArea := PRect.Top / Res.y;
FRightPrintArea := (Size.x - PRect.Right) / Res.x;
FBottomPrintArea := (Size.y - PRect.Bottom) / Res.y;
end;
end;
procedure TAcePrinterSetup.SetOrientation(Value: Integer);
begin
if Value <> FOrientation then
begin
FOrientation := Value;
FPrintSet[0] := True;
end;
end;
procedure TAcePrinterSetup.SetPaperSize(Value: Integer);
begin
if Value <> FPaperSize then
begin
FPaperSize := Value;
FPrintSet[1] := True;
end;
end;
procedure TAcePrinterSetup.SetLength(Value: Double);
begin
if Value <> FLength then
begin
FLength := Value;
FPrintSet[2] := True;
end;
end;
procedure TAcePrinterSetup.SetWidth(Value: Double);
begin
if Value <> FWidth then
begin
FWidth := Value;
FPrintSet[3] := True;
end;
end;
procedure TAcePrinterSetup.SetScale(Value: Integer);
begin
if Value <> FScale then
begin
FScale := Value;
FPrintSet[4] := True;
end;
end;
procedure TAcePrinterSetup.SetCopies(Value: Integer);
begin
if Value <> FCopies then
begin
FCopies := Value;
FPrintSet[5] := True;
end;
end;
procedure TAcePrinterSetup.SetSource(Value: Integer);
begin
if Value <> FSource then
begin
FSource := Value;
FPrintSet[6] := True;
end;
end;
procedure TAcePrinterSetup.SetPrintQuality(Value: Integer);
begin
if Value <> FPrintQuality then
begin
FPrintQuality := Value;
FPrintSet[7] := True;
end;
end;
procedure TAcePrinterSetup.SetColor(Value: Integer);
begin
if Value <> FColor then
begin
FColor := Value;
FPrintSet[8] := True;
end;
end;
procedure TAcePrinterSetup.SetDuplex(Value: Integer);
begin
if Value <> FDuplex then
begin
FDuplex := Value;
FPrintSet[9] := True;
end;
end;
procedure TAcePrinterSetup.SetYResolution(Value: Integer);
begin
if Value <> FYResolution then
begin
FYResolution := Value;
FPrintSet[10] := True;
end;
end;
procedure TAcePrinterSetup.SetTTOption(Value: Integer);
begin
if Value <> FTTOption then
begin
FTTOption := Value;
FPrintSet[11] := True;
end;
end;
procedure TAcePrinterSetup.SetCollatedCopies(Value: Boolean);
begin
if Value <> FCollatedCopies then
begin
FCollatedCopies := Value;
FPrintSet[12] := True;
end;
end;
procedure TAcePrinterSetup.SetFormName(Value: String);
begin
if Value <> FFormName then
begin
FFormName := Value;
FPrintSet[13] := True;
end;
end;
function TAcePrinterSetup.ReadFromAceFile(af: TObject): Boolean;
begin
Result := ReadFromStream(TAceAceFile(af).Stream);
end;
function TAcePrinterSetup.ReadFromStream(Stream: TStream): Boolean;
var
Len, Spot, LongValue: LongInt;
RecType, SmallValue: SmallInt;
PText: array[0..255] of Char;
procedure ReadSmallInt(var I: SmallInt);
begin
Stream.Read(I, SizeOf(I));
end;
procedure ReadLongInt(var LI: LongInt);
begin
Stream.Read(LI, SizeOf(LI));
end;
begin
Result := False;
Stream.Read(Len, SizeOf(Len));
if Len > 0 then
begin
Result := True;
Spot := Stream.Position;
while (Stream.Position - Spot) < Len do
begin
Stream.Read(RecType, SizeOf(RecType));
case RecType of
AceRT_Orientation:
begin
ReadSmallInt(SmallValue);
Orientation := SmallValue;
end;
AceRT_PaperSize:
begin
ReadSmallInt(SmallValue);
PaperSize := SmallValue;
end;
AceRT_Length:
begin
ReadLongInt(LongValue);
Length := LongValue / 254;
end;
AceRT_Width:
begin
ReadLongInt(LongValue);
Width := LongValue / 254;
end;
AceRT_Scale:
begin
ReadSmallInt(SmallValue);
Scale := SmallValue;
end;
AceRT_Copies:
begin
ReadSmallInt(SmallValue);
Copies := SmallValue;
end;
AceRT_Source:
begin
ReadSmallInt(SmallValue);
Source := SmallValue;
end;
AceRT_PrintQuality:
begin
ReadSmallInt(SmallValue);
PrintQuality := SmallValue;
end;
AceRT_Color:
begin
ReadSmallInt(SmallValue);
Color := SmallValue;
end;
AceRT_Duplex:
begin
ReadSmallInt(SmallValue);
Duplex := SmallValue;
end;
AceRT_YResolution:
begin
ReadSmallInt(SmallValue);
YResolution := SmallValue;
end;
AceRT_TTOption:
begin
ReadSmallInt(SmallValue);
TTOption := SmallValue;
end;
AceRT_CollatedCopies:
begin
Stream.Read(FCollatedCopies, SizeOf(FCollatedCopies));
FPrintSet[12] := True;
end;
AceRT_FormName:
begin
ReadSmallInt(SmallValue);
Stream.Read( PText, SmallValue);
PText[SmallValue] := #0;
FFormName := StrPas(PText);
FPrintSet[13] := True;
end;
else break;
end;
end;
end;
end;
procedure TAcePrinterSetup.WriteToAceFile(af: TObject);
begin
WriteToStream(TAceAceFile(af).Stream);
end;
procedure TAcePrinterSetup.WriteToStream(Stream: TStream);
var
Spot1, Spot2, Spot3: LongInt;
SmallValue: SmallInt;
procedure WriteSmallInt(I: SmallInt);
begin
Stream.Write(I, Sizeof(I));
end;
procedure WriteLongInt(LI: LongInt);
begin
Stream.Write(LI, Sizeof(LI));
end;
begin
WriteSmallInt(AceRT_NewPrinterInfo);
Spot1 := Stream.Position;
WriteLongInt(0); { Come back to write the length }
Spot2 := Stream.Position;
if FPrintSet[0] or True then
begin
WriteSmallInt(AceRT_Orientation);
WriteSmallInt(FOrientation);
end;
if FPrintSet[1] or True then
begin
WriteSmallInt(AceRT_PaperSize);
WriteSmallInt(FPaperSize);
end;
if FPrintSet[2] then
begin
WriteSmallInt(AceRT_Length);
WriteLongInt(Round(FLength * 254));
end;
if FPrintSet[3] then
begin
WriteSmallInt(AceRT_Width);
WriteLongInt(Round(FWidth * 254));
end;
if FPrintSet[4] then
begin
WriteSmallInt(AceRT_Scale);
WriteSmallInt(FScale);
end;
if FPrintSet[5] then
begin
WriteSmallInt(AceRT_Copies);
WriteSmallInt(FCopies);
end;
if FPrintSet[6] or True then
begin
WriteSmallInt(AceRT_Source);
WriteSmallInt(FSource);
end;
if FPrintSet[7] then
begin
WriteSmallInt(AceRT_PrintQuality);
WriteSmallInt(FPrintQuality);
end;
if FPrintSet[8] then
begin
WriteSmallInt(AceRT_Color);
WriteSmallInt(FColor);
end;
if FPrintSet[9] or True then
begin
WriteSmallInt(AceRT_Duplex);
WriteSmallInt(FDuplex);
end;
if FPrintSet[10] then
begin
WriteSmallInt(AceRT_YResolution);
WriteSmallInt(FYResolution);
end;
if FPrintSet[11] then
begin
WriteSmallInt(AceRT_TTOption);
WriteSmallInt(FTTOption);
end;
if FPrintSet[12] then
begin
WriteSmallInt(AceRT_CollatedCopies);
Stream.Write(FCollatedCopies, SizeOf(FCollatedCopies));
end;
if FPrintSet[13] then
begin
WriteSmallInt(AceRT_FormName);
SmallValue := System.Length(FFormName);
WriteSmallInt(SmallValue);
Stream.Write( FFormName[1], SmallValue);
end;
Spot3 := Stream.Position;
Stream.Position := Spot1;
WriteLongInt(Spot3 - Spot2);
Stream.Position := Spot3;
end;
end.
|
namespace Sugar;
interface
uses
Sugar.Collections,
Sugar.IO,
Sugar.Json,
Sugar.Xml;
{ Handy test URLs: http://httpbin.org, http://requestb.in }
type
HttpRequest = public class
public
property Mode: HttpRequestMode := HttpRequestMode.Get;
property Headers: not nullable Dictionary<String,String> := new Dictionary<String,String>; readonly;
property Content: nullable HttpRequestContent;
property Url: not nullable Url;
property FollowRedirects: Boolean := true;
property AllowCellularAccess: Boolean := true;
constructor(aUrl: not nullable Url); // log
constructor(aUrl: not nullable Url; aMode: HttpRequestMode); // log := HttpRequestMode.Ge
operator Implicit(aUrl: not nullable Url): HttpRequest;
[ToString]
method ToString: String;
end;
HttpRequestMode = public enum (Get, Post, Head, Put, Delete, Patch, Options, Trace);
IHttpRequestContent = assembly interface
method GetContentAsBinary(): Binary;
method GetContentAsArray(): array of Byte;
end;
HttpRequestContent = public class
public
operator Implicit(aBinary: not nullable Binary): HttpRequestContent;
operator Implicit(aString: not nullable String): HttpRequestContent;
end;
HttpBinaryRequestContent = public class(HttpRequestContent, IHttpRequestContent)
unit
property Binary: Binary unit read private write;
property &Array: array of Byte unit read private write;
method GetContentAsBinary: Binary;
method GetContentAsArray(): array of Byte;
public
constructor(aBinary: not nullable Binary);
constructor(aArray: not nullable array of Byte);
constructor(aString: not nullable String; aEncoding: Encoding);
end;
HttpResponse = public class
unit
constructor withException(anException: Exception);
{$IF COOPER}
var Connection: java.net.HttpURLConnection;
constructor(aConnection: java.net.HttpURLConnection);
{$ELSEIF ECHOES}
var Response: HttpWebResponse;
constructor(aResponse: HttpWebResponse);
{$ELSEIF TOFFEE}
var Data: NSData;
constructor(aData: NSData; aResponse: NSHTTPURLResponse);
{$ENDIF}
public
property Headers: not nullable Dictionary<String,String>; readonly; //todo: list itself should be read-only
property Code: Int32; readonly;
property Success: Boolean read self.Exception = nil;
property Exception: Exception public read unit write;
method GetContentAsString(aEncoding: Encoding := nil; contentCallback: not nullable HttpContentResponseBlock<String>);
method GetContentAsBinary(contentCallback: not nullable HttpContentResponseBlock<Binary>);
method GetContentAsXml(contentCallback: not nullable HttpContentResponseBlock<XmlDocument>);
method GetContentAsJson(contentCallback: not nullable HttpContentResponseBlock<JsonDocument>);
method SaveContentAsFile(aTargetFile: File; contentCallback: not nullable HttpContentResponseBlock<File>);
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method GetContentAsStringSynchronous(aEncoding: Encoding := nil): not nullable String;
method GetContentAsBinarySynchronous: not nullable Binary;
method GetContentAsXmlSynchronous: not nullable XmlDocument;
method GetContentAsJsonSynchronous: not nullable JsonDocument;
{$ENDIF}
end;
HttpResponseContent<T> = public class
public
property Content: T public read unit write;
property Success: Boolean read self.Exception = nil;
property Exception: Exception public read unit write;
end;
HttpResponseBlock = public block (Response: HttpResponse);
HttpContentResponseBlock<T> = public block (ResponseContent: HttpResponseContent<T>);
Http = public static class
private
{$IF TOFFEE}
property Session := NSURLSession.sessionWithConfiguration(NSURLSessionConfiguration.defaultSessionConfiguration); lazy;
{$ENDIF}
method StringForRequestType(aMode: HttpRequestMode): String;
public
//method ExecuteRequest(aUrl: not nullable Url; ResponseCallback: not nullable HttpResponseBlock);
method ExecuteRequest(aRequest: not nullable HttpRequest; ResponseCallback: not nullable HttpResponseBlock);
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method ExecuteRequestSynchronous(aRequest: not nullable HttpRequest): not nullable HttpResponse;
{$ENDIF}
method ExecuteRequestAsString(aEncoding: Encoding := nil; aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<String>);
method ExecuteRequestAsBinary(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<Binary>);
method ExecuteRequestAsXml(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<XmlDocument>);
method ExecuteRequestAsJson(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<JsonDocument>);
method ExecuteRequestAndSaveAsFile(aRequest: not nullable HttpRequest; aTargetFile: not nullable File; contentCallback: not nullable HttpContentResponseBlock<File>);
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method GetString(aEncoding: Encoding := nil; aRequest: not nullable HttpRequest): not nullable String;
method GetBinary(aRequest: not nullable HttpRequest): not nullable Binary;
method GetXml(aRequest: not nullable HttpRequest): not nullable XmlDocument;
method GetJson(aRequest: not nullable HttpRequest): not nullable JsonDocument;
//todo: method GetAndSaveAsFile(...);
{$ENDIF}
end;
implementation
{$IF ECHOES}
uses System.Net;
{$ENDIF}
{ HttpRequest }
constructor HttpRequest(aUrl: not nullable Url);
begin
Url := aUrl;
Mode := HttpRequestMode.Get;
end;
constructor HttpRequest(aUrl: not nullable Url; aMode: HttpRequestMode);
begin
Url := aUrl;
Mode := aMode;
end;
operator HttpRequest.Implicit(aUrl: not nullable Url): HttpRequest;
begin
result := new HttpRequest(aUrl, HttpRequestMode.Get);
end;
method HttpRequest.ToString: String;
begin
result := Url.ToString();
end;
{ HttpRequestContent }
operator HttpRequestContent.Implicit(aBinary: not nullable Binary): HttpRequestContent;
begin
result := new HttpBinaryRequestContent(aBinary);
end;
operator HttpRequestContent.Implicit(aString: not nullable String): HttpRequestContent;
begin
result := new HttpBinaryRequestContent(aString, Encoding.UTF8);
end;
{ HttpBinaryRequestContent }
constructor HttpBinaryRequestContent(aBinary: not nullable Binary);
begin
Binary := aBinary;
end;
constructor HttpBinaryRequestContent(aArray: not nullable array of Byte);
begin
&Array := aArray;
end;
constructor HttpBinaryRequestContent(aString: not nullable String; aEncoding: Encoding);
begin
if aEncoding = nil then aEncoding := Encoding.Default;
&Array := aString.ToByteArray(aEncoding);
end;
method HttpBinaryRequestContent.GetContentAsBinary(): Binary;
begin
if assigned(Binary) then begin
result := Binary;
end
else if assigned(&Array) then begin
Binary := new Binary(&Array);
result := Binary;
end;
end;
method HttpBinaryRequestContent.GetContentAsArray: array of Byte;
begin
if assigned(&Array) then
result := &Array
else if assigned(Binary) then
result := Binary.ToArray();
end;
{ HttpResponse }
constructor HttpResponse withException(anException: Exception);
begin
self.Exception := anException;
Headers := new Dictionary<String,String>();
end;
{$IF COOPER}
constructor HttpResponse(aConnection: java.net.HttpURLConnection);
begin
Connection := aConnection;
Code := Connection.getResponseCode;
Headers := new Dictionary<String,String>();
var i := 0;
loop begin
var lKey := Connection.getHeaderFieldKey(i);
if not assigned(lKey) then break;
var lValue := Connection.getHeaderField(i);
Headers[lKey] := lValue;
inc(i);
end;
end;
{$ELSEIF ECHOES}
constructor HttpResponse(aResponse: HttpWebResponse);
begin
Response := aResponse;
Code := Int32(aResponse.StatusCode);
Headers := new Dictionary<String,String>();
{$IF WINDOWS_PHONE OR NETFX_CORE}
for each k: String in aResponse.Headers:AllKeys do
Headers[k.ToString] := aResponse.Headers[k];
{$ELSE}
for each k: String in aResponse.Headers:Keys do
Headers[k.ToString] := aResponse.Headers[k];
{$ENDIF}
end;
{$ELSEIF TOFFEE}
constructor HttpResponse(aData: NSData; aResponse: NSHTTPURLResponse);
begin
Data := aData;
Code := aResponse.statusCode;
Headers := aResponse.allHeaderFields as not nullable Dictionary<String,String>; // why is this cast needed?
end;
{$ENDIF}
method HttpResponse.GetContentAsString(aEncoding: Encoding := nil; contentCallback: not nullable HttpContentResponseBlock<String>);
begin
if aEncoding = nil then aEncoding := Encoding.Default;
{$IF COOPER}
GetContentAsBinary( (content) -> begin
if content.Success then
contentCallback(new HttpResponseContent<String>(Content := new String(content.Content.ToArray, aEncoding)))
else
contentCallback(new HttpResponseContent<String>(Exception := content.Exception))
end);
{$ELSEIF ECHOES}
async begin
var responseString := new System.IO.StreamReader(Response.GetResponseStream(), aEncoding).ReadToEnd();
contentCallback(new HttpResponseContent<String>(Content := responseString))
end;
{$ELSEIF TOFFEE}
var s := new Foundation.NSString withData(Data) encoding(aEncoding.AsNSStringEncoding); // todo: test this
if assigned(s) then
contentCallback(new HttpResponseContent<String>(Content := s))
else
contentCallback(new HttpResponseContent<String>(Exception := new SugarException("Invalid Encoding")));
{$ENDIF}
end;
method HttpResponse.GetContentAsBinary(contentCallback: not nullable HttpContentResponseBlock<Binary>);
begin
// maybe delegsate to GetContentAsBinarySynchronous?
{$IF COOPER}
async begin
var allData := new Binary;
var stream := if connection.getResponseCode > 400 then Connection.ErrorStream else Connection.InputStream;
var data := new Byte[4096];
var len := stream.read(data);
while len > 0 do begin
allData.Write(data, len);
len := stream.read(data);
end;
contentCallback(new HttpResponseContent<Binary>(Content := allData));
end;
{$ELSEIF ECHOES}
async begin
var allData := new System.IO.MemoryStream();
Response.GetResponseStream().CopyTo(allData);
contentCallback(new HttpResponseContent<Binary>(Content := allData));
end;
{$ELSEIF TOFFEE}
contentCallback(new HttpResponseContent<Binary>(Content := Data.mutableCopy));
{$ENDIF}
end;
method HttpResponse.GetContentAsXml(contentCallback: not nullable HttpContentResponseBlock<XmlDocument>);
begin
GetContentAsBinary((content) -> begin
if content.Success then begin
try
var document := XmlDocument.FromBinary(content.Content);
contentCallback(new HttpResponseContent<XmlDocument>(Content := document));
except
on E: Exception do
contentCallback(new HttpResponseContent<XmlDocument>(Exception := E));
end;
end else begin
contentCallback(new HttpResponseContent<XmlDocument>(Exception := content.Exception));
end;
end);
end;
method HttpResponse.GetContentAsJson(contentCallback: not nullable HttpContentResponseBlock<JsonDocument>);
begin
GetContentAsBinary((content) -> begin
if content.Success then begin
try
var document := JsonDocument.FromBinary(content.Content);
contentCallback(new HttpResponseContent<JsonDocument>(Content := document));
except
on E: Exception do
contentCallback(new HttpResponseContent<JsonDocument>(Exception := E));
end;
end else begin
contentCallback(new HttpResponseContent<JsonDocument>(Exception := content.Exception));
end;
end);
end;
method HttpResponse.SaveContentAsFile(aTargetFile: File; contentCallback: not nullable HttpContentResponseBlock<File>);
begin
{$IF COOPER}
async begin
var allData := new java.io.FileOutputStream(aTargetFile);
var stream := Connection.InputStream;
var data := new Byte[4096];
var len := stream.read(data);
while len > 0 do begin
allData.write(data, 0, len);
len := stream.read(data);
end;
contentCallback(new HttpResponseContent<File>(Content := aTargetFile));
end;
{$ELSEIF ECHOES}
{$IF WINDOWS_PHONE OR NETFX_CORE}
try
using responseStream := Response.GetResponseStream() do begin
var storageFile := Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(aTargetFile.Name, Windows.Storage.CreationCollisionOption.ReplaceExisting).Await();
using fileStream := await System.IO.WindowsRuntimeStorageExtensions.OpenStreamForWriteAsync(storageFile) do begin
await responseStream.CopyToAsync(fileStream);
end;
end;
contentCallback(new HttpResponseContent<File>(Content := aTargetFile));
except
on E: Exception do
contentCallback(new HttpResponseContent<File>(Exception := E));
end;
{$ELSE}
async begin
try
using responseStream := Response.GetResponseStream() do
using fileStream := System.IO.File.OpenWrite(aTargetFile) do
responseStream.CopyTo(fileStream);
contentCallback(new HttpResponseContent<File>(Content := aTargetFile));
except
on E: Exception do
contentCallback(new HttpResponseContent<File>(Exception := E));
end;
end;
{$ENDIF}
{$ELSEIF TOFFEE}
async begin
var error: NSError;
if Data.writeToFile(aTargetFile) options(NSDataWritingOptions.NSDataWritingAtomic) error(var error) then
contentCallback(new HttpResponseContent<File>(Content := aTargetFile))
else
contentCallback(new HttpResponseContent<File>(Exception := new SugarException withError(error)));
end;
{$ENDIF}
end;
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method HttpResponse.GetContentAsStringSynchronous(aEncoding: Encoding := nil): not nullable String;
begin
if aEncoding = nil then aEncoding := Encoding.Default;
{$IF COOPER}
result := new String(GetContentAsBinarySynchronous().ToArray, aEncoding);
{$ELSEIF ECHOES}
result := new System.IO.StreamReader(Response.GetResponseStream(), aEncoding).ReadToEnd() as not nullable;
{$ELSEIF TOFFEE}
var s := new Foundation.NSString withData(Data) encoding(aEncoding.AsNSStringEncoding); // todo: test this
if assigned(s) then
exit s as not nullable
else
raise new SugarException("Invalid Encoding");
{$ENDIF}
end;
method HttpResponse.GetContentAsBinarySynchronous: not nullable Binary;
begin
{$IF COOPER}
var allData := new Binary;
var stream := Connection.InputStream;
var data := new Byte[4096];
var len := stream.read(data);
while len > 0 do begin
allData.Write(data, len);
len := stream.read(data);
end;
result := allData as not nullable;
{$ELSEIF ECHOES}
var allData := new System.IO.MemoryStream();
Response.GetResponseStream().CopyTo(allData);
result := allData as not nullable;
{$ELSEIF TOFFEE}
result := Data.mutableCopy as not nullable;
{$ENDIF}
end;
method HttpResponse.GetContentAsXmlSynchronous: not nullable XmlDocument;
begin
result := XmlDocument.FromBinary(GetContentAsBinarySynchronous());
end;
method HttpResponse.GetContentAsJsonSynchronous: not nullable JsonDocument;
begin
result := JsonDocument.FromBinary(GetContentAsBinarySynchronous());
end;
{$ENDIF}
{ Http }
method Http.StringForRequestType(aMode: HttpRequestMode): String;
begin
case aMode of
HttpRequestMode.Get: result := 'GET';
HttpRequestMode.Post: result := 'POST';
HttpRequestMode.Head: result := 'HEAD';
HttpRequestMode.Put: result := 'PUT';
HttpRequestMode.Delete: result := 'DELETE';
HttpRequestMode.Patch: result := 'PATCH';
HttpRequestMode.Options: result := 'OPTIONS';
HttpRequestMode.Trace: result := 'TRACE';
end;
end;
method Http.ExecuteRequest(aRequest: not nullable HttpRequest; ResponseCallback: not nullable HttpResponseBlock);
begin
{$IF COOPER}
async try
var lConnection := java.net.URL(aRequest.Url).openConnection as java.net.HttpURLConnection;
lConnection.RequestMethod := StringForRequestType(aRequest.Mode);
for each k in aRequest.Headers.Keys do
lConnection.setRequestProperty(k, aRequest.Headers[k]);
if assigned(aRequest.Content) then begin
lConnection.getOutputStream().write((aRequest.Content as IHttpRequestContent).GetContentAsArray());
lConnection.getOutputStream().flush();
end;
try
var lResponse := if lConnection.ResponseCode >= 300 then new HttpResponse withException(new SugarIOException("Unable to complete request. Error code: {0}", lConnection.responseCode)) else new HttpResponse(lConnection);
responseCallback(lResponse);
except
on E: Exception do
responseCallback(new HttpResponse withException(E));
end;
except
on E: Exception do
ResponseCallback(new HttpResponse withException(E));
end;
{$ELSEIF ECHOES}
using webRequest := System.Net.WebRequest.Create(aRequest.Url) as HttpWebRequest do try
{$IF NOT NETFX_CORE}
webRequest.AllowAutoRedirect := aRequest.FollowRedirects;
{$ENDIF}
webRequest.Method := StringForRequestType(aRequest.Mode);
for each k in aRequest.Headers.Keys do
webRequest.Headers[k] := aRequest.Headers[k];
if assigned(aRequest.Content) then begin
{$IF WINDOWS_PHONE}
// I don't want to mess with BeginGetRequestStream/EndGetRequestStream methods here
// HttpWebRequest.GetRequestStreamAsync() is not available in WP 8.0
var getRequestStreamTask := System.Threading.Tasks.Task<System.IO.Stream>.Factory.FromAsync(@webRequest.BeginGetRequestStream, @webRequest.EndGetRequestStream, nil);
using stream := await getRequestStreamTask do begin
{$ELSEIF NETFX_CORE}
using stream := await webRequest.GetRequestStreamAsync() do begin
{$ELSE}
using stream := webRequest.GetRequestStream() do begin
{$ENDIF}
var data := (aRequest.Content as IHttpRequestContent).GetContentAsArray();
stream.Write(data, 0, data.Length);
stream.Flush();
//webRequest.ContentLength := data.Length;
end;
end;
webRequest.BeginGetResponse( (ar) -> begin
try
var webResponse := webRequest.EndGetResponse(ar) as HttpWebResponse;
var response := if webResponse.StatusCode >= 300 then new HttpResponse withException(new SugarIOException("Unable to complete request. Error code: {0}", webResponse.StatusCode)) else new HttpResponse(webResponse);
ResponseCallback(response);
except
on E: Exception do
ResponseCallback(new HttpResponse withException(E));
end;
end, nil);
except
on E: Exception do
ResponseCallback(new HttpResponse withException(E));
end;
{$ELSEIF TOFFEE}
try
var nsUrlRequest := new NSMutableURLRequest withURL(aRequest.Url) cachePolicy(NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData) timeoutInterval(30);
//nsUrlRequest.AllowAutoRedirect := aRequest.FollowRedirects;
nsUrlRequest.allowsCellularAccess := aRequest.AllowCellularAccess;
nsUrlRequest.HTTPMethod := StringForRequestType(aRequest.Mode);
if assigned(aRequest.Content) then
nsUrlRequest.HTTPBody := (aRequest.Content as IHttpRequestContent).GetContentAsBinary();
for each k in aRequest.Headers.Keys do
nsUrlRequest.setValue(aRequest.Headers[k]) forHTTPHeaderField(k);
var lRequest := Session.dataTaskWithRequest(nsUrlRequest) completionHandler((data, nsUrlResponse, error) -> begin
var nsHttpUrlResponse := NSHTTPURLResponse(nsUrlResponse);
if assigned(data) and assigned(nsHttpUrlResponse) and not assigned(error) then begin
var response := if nsHttpUrlResponse.statusCode >= 300 then new HttpResponse withException(new SugarIOException("Unable to complete request. Error code: {0}", nsHttpUrlResponse.statusCode)) else new HttpResponse(data, nsHttpUrlResponse);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), () -> responseCallback(response));
end else if assigned(error) then begin
var response := new HttpResponse(new SugarException withError(error));
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), () -> responseCallback(response));
end else begin
var response := new HttpResponse(new SugarException("Request failed without providing an error."));
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), () -> responseCallback(response));
end;
end);
lRequest.resume();
except
on E: Exception do
ResponseCallback(new HttpResponse withException(E));
end;
{$ENDIF}
end;
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method Http.ExecuteRequestSynchronous(aRequest: not nullable HttpRequest): not nullable HttpResponse;
begin
{$IF COOPER}
var lConnection := java.net.URL(aRequest.Url).openConnection as java.net.HttpURLConnection;
lConnection.RequestMethod := StringForRequestType(aRequest.Mode);
for each k in aRequest.Headers.Keys do
lConnection.setRequestProperty(k, aRequest.Headers[k]);
if assigned(aRequest.Content) then begin
lConnection.getOutputStream().write((aRequest.Content as IHttpRequestContent).GetContentAsArray());
lConnection.getOutputStream().flush();
end;
result := new HttpResponse(lConnection);
if lConnection.ResponseCode >= 300 then
raise new HttpException(String.Format("Unable to complete request. Error code: {0}", lConnection.responseCode), result);
{$ELSEIF ECHOES}
using webRequest := System.Net.WebRequest.Create(aRequest.Url) as HttpWebRequest do begin
{$IF NOT NETFX_CORE}
webRequest.AllowAutoRedirect := aRequest.FollowRedirects;
{$ENDIF}
webRequest.Method := StringForRequestType(aRequest.Mode);
for each k in aRequest.Headers.Keys do
webRequest.Headers[k] := aRequest.Headers[k];
if assigned(aRequest.Content) then begin
using stream := webRequest.GetRequestStream() do begin
var data := (aRequest.Content as IHttpRequestContent).GetContentAsArray();
stream.Write(data, 0, data.Length);
stream.Flush();
end;
end;
try
var webResponse := webRequest.GetResponse() as HttpWebResponse;
result := new HttpResponse(webResponse);
if webResponse.StatusCode >= 300 then
raise new HttpException(String.Format("Unable to complete request. Error code: {0}", webResponse.StatusCode), result);
except
on E: System.Net.WebException do begin
if E.Response is HttpWebResponse then
raise new HttpException(E.Message, new HttpResponse(E.Response as HttpWebResponse))
else
raise new HttpException(E.Message);
end;
end;
end;
{$ELSEIF TOFFEE}
var nsUrlRequest := new NSMutableURLRequest withURL(aRequest.Url) cachePolicy(NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData) timeoutInterval(30);
//nsUrlRequest.AllowAutoRedirect := aRequest.FollowRedirects;
nsUrlRequest.allowsCellularAccess := aRequest.AllowCellularAccess;
nsUrlRequest.HTTPMethod := StringForRequestType(aRequest.Mode);
if assigned(aRequest.Content) then
nsUrlRequest.HTTPBody := (aRequest.Content as IHttpRequestContent).GetContentAsBinary();
for each k in aRequest.Headers.Keys do
nsUrlRequest.setValue(aRequest.Headers[k]) forHTTPHeaderField(k);
var nsUrlResponse : NSURLResponse;
var error: NSError;
{$HIDE W28}
// we're aware it's deprecated. but async calls do have their use in console apps.
var data := NSURLConnection.sendSynchronousRequest(nsUrlRequest) returningResponse(var nsUrlResponse) error(var error);
{$SHOW W28}
(*
var data : NSData;
var outerExecutionBlock: NSBlockOperation := NSBlockOperation.blockOperationWithBlock(method begin
var semaphore := dispatch_semaphore_create(0);
var session := NSURLSession.sharedSession;
var task := session. dataTaskWithRequest(nsUrlRequest) completionHandler(method (internalData:NSData; internalResponse:NSURLResponse; internalError:NSError)begin
nsUrlResponse := internalResponse;
error := internalError;
data := internalData;
dispatch_semaphore_signal(semaphore);
end);
task.resume;
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
end);
var workerQueue := new NSOperationQueue();
workerQueue.addOperations([outerExecutionBlock]) waitUntilFinished(true);
*)
var nsHttpUrlResponse := NSHTTPURLResponse(nsUrlResponse);
if assigned(data) and assigned(nsHttpUrlResponse) and not assigned(error) then begin
result := new HttpResponse(data, nsHttpUrlResponse);
if nsHttpUrlResponse.statusCode >= 300 then
raise new HttpException(String.Format("Unable to complete request. Error code: {0}", nsHttpUrlResponse.statusCode), result);
end
else if assigned(error) then begin
if assigned(nsHttpUrlResponse) then
raise new HttpException(error.description, new HttpResponse(nil, nsHttpUrlResponse))
else
raise new SugarException withError(error)
end
else begin
if assigned(nsHttpUrlResponse) then
raise new HttpException(String.Format("Request failed without providing an error. Error code: {0}", nsHttpUrlResponse.statusCode), new HttpResponse(nil, nsHttpUrlResponse))
else
raise new SugarException("Request failed without providing an error.");
end;
{$ENDIF}
end;
{$ENDIF}
{method Http.ExecuteRequest(aUrl: not nullable Url; ResponseCallback: not nullable HttpResponseBlock);
begin
ExecuteRequest(new HttpRequest(aUrl, HttpRequestMode.Get), responseCallback);
end;}
method Http.ExecuteRequestAsString(aEncoding: Encoding := nil; aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<String>);
begin
Http.ExecuteRequest(aRequest, (response) -> begin
if response.Success then begin
response.GetContentAsString(aEncoding, (content) -> begin
contentCallback(content)
end);
end else begin
contentCallback(new HttpResponseContent<String>(Exception := response.Exception));
end;
end);
end;
method Http.ExecuteRequestAsBinary(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<Binary>);
begin
Http.ExecuteRequest(aRequest, (response) -> begin
if response.Success then begin
response.GetContentAsBinary( (content) -> begin
contentCallback(content)
end);
end else begin
contentCallback(new HttpResponseContent<Binary>(Exception := response.Exception));
end;
end);
end;
method Http.ExecuteRequestAsXml(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<XmlDocument>);
begin
Http.ExecuteRequest(aRequest, (response) -> begin
if response.Success then begin
response.GetContentAsXml( (content) -> begin
contentCallback(content)
end);
end else begin
contentCallback(new HttpResponseContent<XmlDocument>(Exception := response.Exception));
end;
end);
end;
method Http.ExecuteRequestAsJson(aRequest: not nullable HttpRequest; contentCallback: not nullable HttpContentResponseBlock<JsonDocument>);
begin
Http.ExecuteRequest(aRequest, (response) -> begin
if response.Success then begin
response.GetContentAsJson( (content) -> begin
contentCallback(content)
end);
end else begin
contentCallback(new HttpResponseContent<JsonDocument>(Exception := response.Exception));
end;
end);
end;
method Http.ExecuteRequestAndSaveAsFile(aRequest: not nullable HttpRequest; aTargetFile: not nullable File; contentCallback: not nullable HttpContentResponseBlock<File>);
begin
Http.ExecuteRequest(aRequest, (response) -> begin
if response.Success then begin
response.SaveContentAsFile(aTargetFile, (content) -> begin
contentCallback(content)
end);
end else begin
contentCallback(new HttpResponseContent<File>(Exception := response.Exception));
end;
end);
end;
{$IF NOT ECHOES OR (NOT WINDOWS_PHONE AND NOT NETFX_CORE)}
method Http.GetString(aEncoding: Encoding := nil; aRequest: not nullable HttpRequest): not nullable String;
begin
result := ExecuteRequestSynchronous(aRequest).GetContentAsStringSynchronous(aEncoding);
end;
method Http.GetBinary(aRequest: not nullable HttpRequest): not nullable Binary;
begin
result := ExecuteRequestSynchronous(aRequest).GetContentAsBinarySynchronous;
end;
method Http.GetXml(aRequest: not nullable HttpRequest): not nullable XmlDocument;
begin
result := ExecuteRequestSynchronous(aRequest).GetContentAsXmlSynchronous;
end;
method Http.GetJson(aRequest: not nullable HttpRequest): not nullable JsonDocument;
begin
result := ExecuteRequestSynchronous(aRequest).GetContentAsJsonSynchronous;
end;
{$ENDIF}
(*
{$IF WINDOWS_PHONE}
class method Http.InternalDownload(anUrl: Url): System.Threading.Tasks.Task<System.Net.HttpWebResponse>;
begin
var Request: System.Net.HttpWebRequest := System.Net.WebRequest.CreateHttp(anUrl);
Request.Method := "GET";
Request.AllowReadStreamBuffering := true;
var TaskComplete := new System.Threading.Tasks.TaskCompletionSource<System.Net.HttpWebResponse>;
Request.BeginGetResponse(x -> begin
try
var ResponseRequest := System.Net.HttpWebRequest(x.AsyncState);
var Response := System.Net.HttpWebResponse(ResponseRequest.EndGetResponse(x));
TaskComplete.TrySetResult(Response);
except
on E: Exception do
TaskComplete.TrySetException(E);
end;
end, Request);
exit TaskComplete.Task;
end;
{$ENDIF}
class method Http.Download(anUrl: Url): HttpResponse<Binary>;
begin
try
{$IF COOPER}
{$ELSEIF WINDOWS_PHONE}
var Response := InternalDownload(anUrl).Result;
if Response.StatusCode <> System.Net.HttpStatusCode.OK then
exit new HttpResponse<Binary> withException(new SugarException("Unable to download data, Response: " + Response.StatusDescription));
var Stream := Response.GetResponseStream;
if Stream = nil then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
var Content := new Binary;
var Buffer := new Byte[16 * 1024];
var Readed: Integer := Stream.Read(Buffer, 0, Buffer.Length);
while Readed > 0 do begin
Content.Write(Buffer, Readed);
Readed := Stream.Read(Buffer, 0, Buffer.Length);
end;
if Content.Length = 0 then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
exit new HttpResponse<Binary>(Content);
{$ELSEIF NETFX_CORE}
var Client := new System.Net.Http.HttpClient;
var Content := Client.GetByteArrayAsync(anUrl).Result;
if Content = nil then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
if Content.Length = 0 then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
exit new HttpResponse<Binary>(new Binary(Content));
{$ELSEIF ECHOES}
using lClient: System.Net.WebClient := new System.Net.WebClient() do begin
var Content := lClient.DownloadData(anUrl);
if Content = nil then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
if Content.Length = 0 then
exit new HttpResponse<Binary> withException(new SugarException("Content is empty"));
exit new HttpResponse<Binary>(new Binary(Content));
end;
{$ELSEIF TOFFEE}
var lError: NSError := nil;
var lRequest := new NSURLRequest withURL(anUrl) cachePolicy(NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData) timeoutInterval(30);
var lResponse: NSURLResponse;
var lData := NSURLConnection.sendSynchronousRequest(lRequest) returningResponse(var lResponse) error(var lError);
if lError <> nil then
exit new HttpResponse<Binary> withException(Exception(new SugarNSErrorException(lError)));
if NSHTTPURLResponse(lResponse).statusCode <> 200 then
exit new HttpResponse<Binary> withException(Exception(new SugarIOException("Unable to complete request. Error code: {0}", NSHTTPURLResponse(lResponse).statusCode)));
exit new HttpResponse<Binary>(Binary(NSMutableData.dataWithData(lData)));
{$ENDIF}
except
on E: Exception do begin
var Actual := E;
{$IF WINDOWS_PHONE OR NETFX_CORE}
if E is AggregateException then
Actual := AggregateException(E).InnerException;
{$ENDIF}
exit new HttpResponse<Binary> withException(Actual);
end;
end;
end;
*)
end. |
unit SpoolPackets;
interface
type
TSpooledPacket =
class
public
constructor Create(aBuffer : pchar; aSize : integer; OwnsPacket : boolean);
destructor Destroy; override;
private
fBuffer : pchar;
fSize : integer;
fIndex : integer;
fOwnsPacket : boolean;
public
procedure Move(count : integer);
function GetBuffer : pchar;
function GetCount : integer;
public
property Count : integer read GetCount;
property Buffer : pchar read GetBuffer;
end;
implementation
// TSpooledPacket
constructor TSpooledPacket.Create(aBuffer : pchar; aSize : integer; OwnsPacket : boolean);
begin
inherited Create;
fOwnsPacket := OwnsPacket;
if not OwnsPacket
then fBuffer := aBuffer
else
begin
GetMem(fBuffer, aSize);
System.move(aBuffer[0], fBuffer[0], aSize);
end;
fSize := aSize;
end;
destructor TSpooledPacket.Destroy;
begin
if fOwnsPacket
then FreeMem(fBuffer);
inherited;
end;
procedure TSpooledPacket.Move(count : integer);
begin
inc(fIndex, count);
end;
function TSpooledPacket.GetBuffer : pchar;
begin
if fIndex < fSize
then result := fBuffer + fIndex
else result := nil;
end;
function TSpooledPacket.GetCount : integer;
begin
if fIndex < fSize
then result := fSize - fIndex
else result := 0;
end;
end.
|
{ Subroutine SST_W_C_DTYPE_SIMPLE (DTYPE,NAME,PACK)
*
* Write the data type definition for the data type descriptor DTYPE.
* Only a "simple" data type will be written. If necessary, a hidden
* data type will be created, declared to the not-simple data type, and then
* its name written here. PACK is true to indicate that the data type is
* a declaration for a field in a packed record.
* NAME is the name of the symbol to declare with this data type. The
* symbol name will be written in the appropriate place in the data type
* declaration.
*
* This routine would be used when referencing the data type DTYPE. It would
* not be used when defining the data type DTYPE.
}
module sst_w_c_DTYPE_SIMPLE;
define sst_w_c_dtype_simple;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_dtype_simple ( {write data type def, forced to be simple}
in dtype: sst_dtype_t; {data type descriptor block}
in name: univ string_var_arg_t; {name of symbol to declare with this dtype}
in pack: boolean); {TRUE if part of packed record}
val_param;
var
dt_p: sst_dtype_p_t; {points to base data type of DTYPE}
dtp_p: sst_dtype_p_t; {points to base pointed-to data type}
sym_p: sst_symbol_p_t; {points to name of data type, if any}
scope_old_p: sst_scope_p_t; {saved copy of current scope pointer}
rename: string_var80_t; {renamed NAME for recursive call}
label
write_name, write_long;
begin
rename.max := sizeof(rename.str); {init local var string}
sym_p := dtype.symbol_p; {init pointer to data type's name}
dt_p := addr(dtype); {init pointer to base data type descriptor}
while dt_p^.dtype = sst_dtype_copy_k do begin {resolve base data type descriptor}
if sym_p = nil {name not found yet ?}
then sym_p := dt_p^.copy_symbol_p; {use copied name, if available}
dt_p := dt_p^.copy_dtype_p; {resolve one level of copy}
if sym_p = nil {name not found yet ?}
then sym_p := dt_p^.symbol_p; {try to grab name at this level}
end; {keep looping until DT_P^ is not a copy}
{
* DT_P is pointing to the base data type descriptor. SYM_P is pointing to
* the highest level name symbol for the original data type, if one was found.
}
if dt_p^.dtype = sst_dtype_undef_k then begin {data type is undefined ?}
sst_w.appendn^ ('void', 4);
goto write_name;
end;
{
* If this is a field in a packed record, and it is a simple data type that
* will require a field width specifier, then call the general routine.
* This routine contains the logic for writing the field width specifiers.
}
if pack then begin {this is a field in a packed record ?}
case dt_p^.dtype of {what is base data type of field ?}
sst_dtype_int_k,
sst_dtype_enum_k,
sst_dtype_bool_k,
sst_dtype_char_k,
sst_dtype_set_k,
sst_dtype_range_k: goto write_long; {these data types will require field widths}
end;
end;
{
* Handle case where no name symbol was available anywhere. If the data type
* is a pointer, then add "*" to the front of NAME and call ourselves recursively
* with the pointed-to data type. Otherwise, give this data type a name,
* declare it, and then use the new symbol name.
}
if sym_p = nil then begin {no name symbol available anywhere ?}
if dt_p^.dtype = sst_dtype_proc_k {DTYPE is data type for a routine ?}
then goto write_long; {write long form of routine data types}
if dt_p^.dtype = sst_dtype_pnt_k then begin {data type is a pointer ?}
dtp_p := dt_p^.pnt_dtype_p; {resolve base pointed-to data type}
while dtp_p^.dtype = sst_dtype_copy_k do dtp_p := dtp_p^.copy_dtype_p;
if dtp_p^.dtype = sst_dtype_proc_k {DTYPE is pointer to routine ?}
then goto write_long; {write long form of routine pointer dtypes}
rename.len := 0;
string_append1 (rename, '*');
string_append (rename, name);
sst_w_c_dtype_simple (dt_p^.pnt_dtype_p^, rename, false); {do by recursive call}
return;
end;
scope_old_p := sst_scope_p; {save pointer to current scope}
while sst_scope_p^.parent_p <> nil do begin {loop no further than top scope}
if sst_scope_p^.symbol_p <> nil then begin {this scope has an owning symbol ?}
case sst_scope_p^.symbol_p^.symtype of {what kind of symbol owns this scope ?}
sst_symtype_proc_k,
sst_symtype_prog_k,
sst_symtype_module_k: exit; {this scope is global enough}
end;
end;
sst_scope_p := sst_scope_p^.parent_p; {move to next most local scope}
end;
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {create new symbol descriptor}
sym_p^.name_in_p := nil;
sym_p^.name_out_p := nil;
sym_p^.next_p := nil;
sym_p^.char_h.crange_p := nil;
sym_p^.char_h.ofs := 0;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_used_k, sst_symflag_created_k];
sym_p^.dtype_dtype_p := dt_p;
dt_p^.symbol_p := sym_p; {link data type to its new symbol}
sst_w_c_symbol (sym_p^); {name and declare this data type symbol}
sst_scope_p := scope_old_p; {restore pointer to current scope}
end; {SYM_P definately points to symbol descriptor}
if {need STRUCT or UNION keyword ?}
(dt_p^.dtype = sst_dtype_rec_k) and {data type is record ?}
(not (sst_symflag_written_k in sym_p^.flags)) {data type not fully declared ?}
then begin
if sst_rec_variant(dt_p^)
then sst_w.appendn^ ('union', 5)
else sst_w.appendn^ ('struct', 6);
sst_w.delimit^;
end;
sst_w.append_sym_name^ (sym_p^); {write data type's name}
write_name: {jump here to write just declare var name}
if name.len > 0 then begin {we have a name to declare ?}
sst_w.delimit^;
sst_w.append^ (name); {write name of symbol being declared}
end;
return;
write_long: {jump here for "long" definition of dtype}
sst_w_c_dtype (dt_p^, name, pack); {write full data type declaration}
end;
|
unit MdiChilds.ImportKvartalIndex;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm, ActionHandler;
type
TFmImportKvartalIndex = class(TFmProcess)
edtFile: TLabeledEdit;
btnOpen: TButton;
OpenDialog: TOpenDialog;
rgIndexType: TRadioGroup;
procedure btnOpenClick(Sender: TObject);
private
{ Private declarations }
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean); override;
public
{ Public declarations }
end;
TImportKvartalIndexActionHandler = class (TAbstractActionHandler)
public
procedure ExecuteAction(UserData: Pointer = nil); override;
end;
var
FmImportKvartalIndex: TFmImportKvartalIndex;
implementation
uses
Parsers.Excel.Indexes.Kvartal;
{$R *.dfm}
procedure TFmImportKvartalIndex.btnOpenClick(Sender: TObject);
begin
if OpenDialog.Execute then
edtFile.Text := OpenDialog.FileName;
end;
procedure TFmImportKvartalIndex.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean);
var
Parser: TKvartalIndexParser;
begin
Parser := TKvartalIndexParser.Create;
try
Parser.Suffix := rgIndexType.ItemIndex;
Parser.ParseDoc(edtFile.Text);
finally
Parser.Free;
end;
ShowMessage := True;
end;
{ TImportKvartalIndexActionHandler }
procedure TImportKvartalIndexActionHandler.ExecuteAction;
begin
TFmImportKvartalIndex.Create(Application).Show;
end;
begin
ActionHandlerManager.RegisterActionHandler('≈жеквартальные индексы', hkDefault, TImportKvartalIndexActionHandler);
end.
|
{
Double Commander
-------------------------------------------------------------------------
Functions handling file attributes.
Copyright (C) 2012 Przemysław Nagay (cobines@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit DCFileAttributes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DCBasicTypes;
const
// Windows attributes
FILE_ATTRIBUTE_READONLY = $0001;
FILE_ATTRIBUTE_HIDDEN = $0002;
FILE_ATTRIBUTE_SYSTEM = $0004;
FILE_ATTRIBUTE_DIRECTORY = $0010;
FILE_ATTRIBUTE_ARCHIVE = $0020;
FILE_ATTRIBUTE_NORMAL = $0080;
FILE_ATTRIBUTE_TEMPORARY = $0100;
FILE_ATTRIBUTE_SPARSE_FILE = $0200;
FILE_ATTRIBUTE_REPARSE_POINT = $0400;
FILE_ATTRIBUTE_COMPRESSED = $0800;
FILE_ATTRIBUTE_OFFLINE = $1000;
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = $2000;
FILE_ATTRIBUTE_ENCRYPTED = $4000;
FILE_ATTRIBUTE_VIRTUAL = $20000;
// Unix attributes
{ attributes mask }
S_IFMT = $F000;
{ first-in/first-out (FIFO/pipe) }
S_IFIFO = $1000;
{ character-special file (tty/console) }
S_IFCHR = $2000;
{ directory }
S_IFDIR = $4000;
{ blocking device (unused) }
S_IFBLK = $6000;
{ regular }
S_IFREG = $8000;
{ symbolic link (unused) }
S_IFLNK = $A000;
{ Berkeley socket }
S_IFSOCK = $C000;
{ mode_t possible values }
S_IRUSR = %0100000000; { Read permission for owner }
S_IWUSR = %0010000000; { Write permission for owner }
S_IXUSR = %0001000000; { Exec permission for owner }
S_IRGRP = %0000100000; { Read permission for group }
S_IWGRP = %0000010000; { Write permission for group }
S_IXGRP = %0000001000; { Exec permission for group }
S_IROTH = %0000000100; { Read permission for world }
S_IWOTH = %0000000010; { Write permission for world }
S_IXOTH = %0000000001; { Exec permission for world }
S_IRWXU = S_IRUSR or S_IWUSR or S_IXUSR;
S_IRWXG = S_IRGRP or S_IWGRP or S_IXGRP;
S_IRWXO = S_IROTH or S_IWOTH or S_IXOTH;
S_IXUGO = S_IXUSR or S_IXGRP or S_IXOTH;
{ POSIX setuid(), setgid(), and sticky bit }
S_ISUID = $0800;
S_ISGID = $0400;
S_ISVTX = $0200;
// Generic attributes
{$IF DEFINED(MSWINDOWS)}
GENERIC_ATTRIBUTE_FILE = FILE_ATTRIBUTE_ARCHIVE;
GENERIC_ATTRIBUTE_FOLDER = GENERIC_ATTRIBUTE_FILE or FILE_ATTRIBUTE_DIRECTORY;
{$ELSEIF DEFINED(UNIX)}
GENERIC_ATTRIBUTE_FILE = S_IRUSR or S_IWUSR or S_IRGRP or S_IROTH;
GENERIC_ATTRIBUTE_FOLDER = GENERIC_ATTRIBUTE_FILE or S_IFDIR or S_IXUGO;
{$ENDIF}
function WinToUnixFileAttr(Attr: TFileAttrs): TFileAttrs;
function UnixToWinFileAttr(Attr: TFileAttrs): TFileAttrs;
function UnixToWcxFileAttr(Attr: TFileAttrs): TFileAttrs;
function UnixToWinFileAttr(const FileName: String; Attr: TFileAttrs): TFileAttrs;
function SingleStrToFileAttr(sAttr: String): TFileAttrs;
function WinSingleStrToFileAttr(sAttr: String): TFileAttrs;
function UnixSingleStrToFileAttr(sAttr: String): TFileAttrs;
{en
Convert file attributes from string to number
@param(Attributes File attributes as string)
@returns(File attributes as number)
}
function StrToFileAttr(sAttr: String): TFileAttrs;
{en
Convert file attributes to string in the format of "attr1+attr2+attr3+".
@param(Attributes File attributes)
@returns(File attributes as string)
}
function FileAttrToStr(Attr: TFileAttrs): String;
{en
Convert Windows file attributes from string to number
@param(Attributes File attributes as string)
@returns(File attributes as number)
}
function WinStrToFileAttr(sAttr: String): TFileAttrs;
{en
Convert Unix file attributes from string to number
@param(Attributes File attributes as string)
@returns(File attributes as number)
}
function UnixStrToFileAttr(sAttr: String): TFileAttrs;
function FormatNtfsAttributes(iAttr: TFileAttrs): String;
function FormatUnixAttributes(iAttr: TFileAttrs): String;
function FormatUnixModeOctal(iAttr: TFileAttrs): String;
implementation
uses
DCStrUtils;
type
TAttrStrToFileAttr = record
Str: String;
Attr: TFileAttrs;
end;
const
WinAttrStrToFileAttr: array[0..9] of TAttrStrToFileAttr = (
(Str: 'r'; Attr: FILE_ATTRIBUTE_READONLY),
(Str: 'h'; Attr: FILE_ATTRIBUTE_HIDDEN),
(Str: 's'; Attr: FILE_ATTRIBUTE_SYSTEM),
(Str: 'd'; Attr: FILE_ATTRIBUTE_DIRECTORY),
(Str: 'a'; Attr: FILE_ATTRIBUTE_ARCHIVE),
(Str: 't'; Attr: FILE_ATTRIBUTE_TEMPORARY),
(Str: 'p'; Attr: FILE_ATTRIBUTE_SPARSE_FILE),
(Str: 'l'; Attr: FILE_ATTRIBUTE_REPARSE_POINT),
(Str: 'c'; Attr: FILE_ATTRIBUTE_COMPRESSED),
(Str: 'e'; Attr: FILE_ATTRIBUTE_ENCRYPTED));
UnixAttrStrToFileAttr: array[0..18] of TAttrStrToFileAttr = (
// Permissions
(Str: 'ur'; Attr: S_IRUSR),
(Str: 'uw'; Attr: S_IWUSR),
(Str: 'ux'; Attr: S_IXUSR),
(Str: 'gr'; Attr: S_IRGRP),
(Str: 'gw'; Attr: S_IWGRP),
(Str: 'gx'; Attr: S_IXGRP),
(Str: 'or'; Attr: S_IROTH),
(Str: 'ow'; Attr: S_IWOTH),
(Str: 'ox'; Attr: S_IXOTH),
(Str: 'us'; Attr: S_ISUID),
(Str: 'gs'; Attr: S_ISGID),
(Str: 'sb'; Attr: S_ISVTX),
// File types
(Str: 'f'; Attr: S_IFIFO),
(Str: 'c'; Attr: S_IFCHR),
(Str: 'd'; Attr: S_IFDIR),
(Str: 'b'; Attr: S_IFBLK),
(Str: 'r'; Attr: S_IFREG),
(Str: 'l'; Attr: S_IFLNK),
(Str: 's'; Attr: S_IFSOCK));
function WinToUnixFileAttr(Attr: TFileAttrs): TFileAttrs;
begin
Result := S_IRUSR or S_IRGRP or S_IROTH;
if (Attr and faReadOnly) = 0 then
Result := Result or S_IWUSR;
if (Attr and faDirectory) <> 0 then
Result := Result or S_IFDIR or S_IXUGO
else
Result := Result or S_IFREG;
end;
function UnixToWinFileAttr(Attr: TFileAttrs): TFileAttrs;
begin
Result := 0;
case (Attr and S_IFMT) of
0, S_IFREG:
Result := faArchive;
S_IFLNK:
Result := Result or faSymLink;
S_IFDIR:
Result := Result or faDirectory;
S_IFIFO, S_IFCHR, S_IFBLK, S_IFSOCK:
Result := Result or faSysFile;
end;
if (Attr and S_IWUSR) = 0 then
Result := Result or faReadOnly;
end;
function UnixToWcxFileAttr(Attr: TFileAttrs): TFileAttrs;
begin
{$IF DEFINED(MSWINDOWS)}
Result := UnixToWinFileAttr(Attr);
{$ELSEIF DEFINED(UNIX)}
Result := Attr;
{$ELSE}
Result := 0;
{$ENDIF}
end;
function UnixToWinFileAttr(const FileName: String; Attr: TFileAttrs): TFileAttrs;
begin
Result := UnixToWinFileAttr(Attr);
if (Length(FileName) > 1) and (FileName[1] = '.') and (FileName[2] <> '.') then
Result := Result or faHidden;
end;
function SingleStrToFileAttr(sAttr: String): TFileAttrs;
begin
{$IF DEFINED(MSWINDOWS)}
Result := WinSingleStrToFileAttr(sAttr);
{$ELSEIF DEFINED(UNIX)}
Result := UnixSingleStrToFileAttr(sAttr);
{$ENDIF}
end;
function WinSingleStrToFileAttr(sAttr: String): TFileAttrs;
var
i: Integer;
begin
for i := Low(WinAttrStrToFileAttr) to High(WinAttrStrToFileAttr) do
begin
if sAttr = WinAttrStrToFileAttr[i].Str then
Exit(WinAttrStrToFileAttr[i].Attr);
end;
Result := 0;
end;
function UnixSingleStrToFileAttr(sAttr: String): TFileAttrs;
var
i: Integer;
begin
if Length(sAttr) > 0 then
begin
if sAttr[1] in ['0'..'7'] then
begin
// Octal representation.
Exit(TFileAttrs(OctToDec(sAttr)));
end
else
begin
for i := Low(UnixAttrStrToFileAttr) to High(UnixAttrStrToFileAttr) do
begin
if sAttr = UnixAttrStrToFileAttr[i].Str then
Exit(UnixAttrStrToFileAttr[i].Attr);
end;
end;
end;
Result := 0;
end;
function StrToFileAttr(sAttr: String): TFileAttrs; inline;
begin
{$IF DEFINED(MSWINDOWS)}
Result := WinStrToFileAttr(sAttr);
{$ELSEIF DEFINED(UNIX)}
Result := UnixStrToFileAttr(sAttr);
{$ENDIF}
end;
function FileAttrToStr(Attr: TFileAttrs): String;
var
i: Integer;
begin
Result := '';
{$IF DEFINED(MSWINDOWS)}
for i := Low(WinAttrStrToFileAttr) to High(WinAttrStrToFileAttr) do
begin
if Attr and WinAttrStrToFileAttr[i].Attr <> 0 then
Result := Result + WinAttrStrToFileAttr[i].Str + '+';
end;
{$ELSEIF DEFINED(UNIX)}
for i := Low(UnixAttrStrToFileAttr) to High(UnixAttrStrToFileAttr) do
begin
if Attr and UnixAttrStrToFileAttr[i].Attr <> 0 then
Result := Result + UnixAttrStrToFileAttr[i].Str + '+';
end;
{$ENDIF}
end;
function WinStrToFileAttr(sAttr: String): TFileAttrs;
var
I: LongInt;
begin
Result:= 0;
sAttr:= LowerCase(sAttr);
for I:= 1 to Length(sAttr) do
case sAttr[I] of
'd': Result := Result or FILE_ATTRIBUTE_DIRECTORY;
'l': Result := Result or FILE_ATTRIBUTE_REPARSE_POINT;
'r': Result := Result or FILE_ATTRIBUTE_READONLY;
'a': Result := Result or FILE_ATTRIBUTE_ARCHIVE;
'h': Result := Result or FILE_ATTRIBUTE_HIDDEN;
's': Result := Result or FILE_ATTRIBUTE_SYSTEM;
end;
end;
function UnixStrToFileAttr(sAttr: String): TFileAttrs;
begin
Result:= 0;
if Length(sAttr) < 10 then Exit;
if sAttr[1] = 'd' then Result:= Result or S_IFDIR;
if sAttr[1] = 'l' then Result:= Result or S_IFLNK;
if sAttr[1] = 's' then Result:= Result or S_IFSOCK;
if sAttr[1] = 'f' then Result:= Result or S_IFIFO;
if sAttr[1] = 'b' then Result:= Result or S_IFBLK;
if sAttr[1] = 'c' then Result:= Result or S_IFCHR;
if sAttr[2] = 'r' then Result:= Result or S_IRUSR;
if sAttr[3] = 'w' then Result:= Result or S_IWUSR;
if sAttr[4] = 'x' then Result:= Result or S_IXUSR;
if sAttr[5] = 'r' then Result:= Result or S_IRGRP;
if sAttr[6] = 'w' then Result:= Result or S_IWGRP;
if sAttr[7] = 'x' then Result:= Result or S_IXGRP;
if sAttr[8] = 'r' then Result:= Result or S_IROTH;
if sAttr[9] = 'w' then Result:= Result or S_IWOTH;
if sAttr[10] = 'x' then Result:= Result or S_IXOTH;
if sAttr[4] = 'S' then Result:= Result or S_ISUID;
if sAttr[7] = 'S' then Result:= Result or S_ISGID;
if sAttr[10] = 'T' then Result:= Result or S_ISVTX;
if sAttr[4] = 's' then Result:= Result or S_IXUSR or S_ISUID;
if sAttr[7] = 's' then Result:= Result or S_IXGRP or S_ISGID;
if sAttr[10] = 't' then Result:= Result or S_IXOTH or S_ISVTX;
end;
function FormatNtfsAttributes(iAttr: TFileAttrs): String;
begin
Result:= '--------';
if (iAttr and FILE_ATTRIBUTE_DIRECTORY ) <> 0 then Result[1] := 'd';
if (iAttr and FILE_ATTRIBUTE_REPARSE_POINT) <> 0 then Result[1] := 'l';
if (iAttr and FILE_ATTRIBUTE_READONLY ) <> 0 then Result[2] := 'r';
if (iAttr and FILE_ATTRIBUTE_ARCHIVE ) <> 0 then Result[3] := 'a';
if (iAttr and FILE_ATTRIBUTE_HIDDEN ) <> 0 then Result[4] := 'h';
if (iAttr and FILE_ATTRIBUTE_SYSTEM ) <> 0 then Result[5] := 's';
// These two are exclusive on NTFS.
if (iAttr and FILE_ATTRIBUTE_COMPRESSED ) <> 0 then Result[6] := 'c';
if (iAttr and FILE_ATTRIBUTE_ENCRYPTED ) <> 0 then Result[6] := 'e';
if (iAttr and FILE_ATTRIBUTE_TEMPORARY ) <> 0 then Result[7] := 't';
if (iAttr and FILE_ATTRIBUTE_SPARSE_FILE ) <> 0 then Result[8] := 'p';
end;
function FormatUnixAttributes(iAttr: TFileAttrs): String;
begin
Result:= '----------';
if ((iAttr and S_IFMT) = S_IFDIR) then Result[1] := 'd';
if ((iAttr and S_IFMT) = S_IFLNK) then Result[1] := 'l';
if ((iAttr and S_IFMT) = S_IFSOCK) then Result[1] := 's';
if ((iAttr and S_IFMT) = S_IFIFO) then Result[1] := 'f';
if ((iAttr and S_IFMT) = S_IFBLK) then Result[1] := 'b';
if ((iAttr and S_IFMT) = S_IFCHR) then Result[1] := 'c';
if ((iAttr and S_IRUSR) = S_IRUSR) then Result[2] := 'r';
if ((iAttr and S_IWUSR) = S_IWUSR) then Result[3] := 'w';
if ((iAttr and S_IXUSR) = S_IXUSR) then Result[4] := 'x';
if ((iAttr and S_IRGRP) = S_IRGRP) then Result[5] := 'r';
if ((iAttr and S_IWGRP) = S_IWGRP) then Result[6] := 'w';
if ((iAttr and S_IXGRP) = S_IXGRP) then Result[7] := 'x';
if ((iAttr and S_IROTH) = S_IROTH) then Result[8] := 'r';
if ((iAttr and S_IWOTH) = S_IWOTH) then Result[9] := 'w';
if ((iAttr and S_IXOTH) = S_IXOTH) then Result[10] := 'x';
if ((iAttr and S_ISUID) = S_ISUID) then
begin
if Result[4] = 'x' then
Result[4] := 's'
else
Result[4] := 'S';
end;
if ((iAttr and S_ISGID) = S_ISGID) then
begin
if Result[7] = 'x' then
Result[7] := 's'
else
Result[7] := 'S';
end;
if ((iAttr and S_ISVTX) = S_ISVTX) then
begin
if Result[10] = 'x' then
Result[10] := 't'
else
Result[10] := 'T';
end;
end;
function FormatUnixModeOctal(iAttr: TFileAttrs): String;
begin
Result:= DecToOct(iAttr and $0FFF);
Result:= StringOfChar('0', 4 - Length(Result)) + Result;
end;
end.
|
unit GX_ReplaceComp;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, StdCtrls, ToolsAPI,
RplWizInfo, GX_ReplaceCompData, GX_BaseForm;
type
TfmReplaceComp = class(TfmBaseForm)
lblSeach: TLabel;
cbSearch: TComboBox;
lblReplace: TLabel;
cbReplace: TComboBox;
gbxScope: TGroupBox;
rbAllOnCurrentForm: TRadioButton;
rbAllInProject: TRadioButton;
rbSelectedOnCurrentForm: TRadioButton;
btnOK: TButton;
btnCancel: TButton;
btnHelp: TButton;
gbxOptions: TGroupBox;
chkLogChanges: TCheckBox;
chkOverwriteLog: TCheckBox;
chkShowLogWin: TCheckBox;
chkIgnoreErrors: TCheckBox;
chkLogValues: TCheckBox;
btnSettings: TButton;
procedure btnOKClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure cbSearchChange(Sender: TObject);
procedure cbSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnSettingsClick(Sender: TObject);
private
FController: TCompRepController;
procedure SetOptionsForNoCurrentForm;
procedure SetOptionsForNoComponentsSelected;
procedure LoadComponentList;
procedure ReplaceComponentsOnCurrentForm(OnlySelected: Boolean);
procedure ReplaceComponentsOnAllForms;
procedure ReplaceComponentsOnForm(FormEditor: IOTAFormEditor; OnlySelected: Boolean);
procedure SetupControls;
procedure LoadFormSettings;
procedure SaveFormSettings;
function PrepareController: TCompRepController;
procedure ShowLogWin(const SourceClassName, DestClassName: string; LogEvents: TCompRepEventList);
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
SysUtils, Windows, Dialogs, ActnList,
GX_Experts, GX_GxUtils, GX_OtaUtils, GX_GenericUtils, GX_GenericClasses,
GX_ReplaceCompMapList, GX_ConfigurationInfo, GX_ReplaceCompLog, GX_ReplaceCompUtils;
type
TMapScoreList = class;
TCompRepControllerReal = class(TCompRepController)
private
FOverwriteLog: Boolean;
FLogChanges: Boolean;
FIgnoreErrors: Boolean;
FShowLogWin: Boolean;
FLogValues: Boolean;
FConfigData: TReplaceCompData;
FLogEvents: TCompRepEventList;
FFileName: string;
FNameStack: TStringList;
FObjectStack: TStringList;
FLog: TStringList;
procedure AssignContext(Event: TCompRepEvent);
function NewEvent: TCompRepEvent;
function StackText: string;
procedure GetCurrentObject(var ObjectName: string; var ObjectPtr: TObject);
function GetLogFileName: string;
procedure StartLog;
procedure SaveLog;
procedure DeleteLog;
procedure SaveEventToLog(AEvent: TCompRepEvent);
function FormatEventForMessage(AEvent: TCompRepEvent): string;
function TryAddMapping(MapItem: TCompRepMapItem; const ASrcClassName, ADestClassName, APropName,
AMapPropName: string; Scores: TMapScoreList; Mappings: TCompRepMapList): Boolean;
public
constructor Create;
destructor Destroy; override;
procedure HandleException(E: Exception; const Context: string); override;
procedure LogMsg(const AMsg: string); override;
procedure SignalBegin; override;
procedure SignalEnd; override;
procedure SignalFileBegin(const AFileName: string); override;
procedure SignalFileEnd(const AFileName: string); override;
procedure SignalStackBegin(const AName: string); override;
procedure SignalStackEnd(const AName: string); override;
procedure SignalObjectBegin(const AName: string; AObject: TObject); override;
procedure SignalObjectEnd(const AName: string; AObject: TObject); override;
procedure PrepareMappingForProp(const AClassName, APropName: string; Mappings: TCompRepMapList); override;
procedure PrepareConstMappingForProp(const AClassName, APropName: string; Mappings: TCompRepMapList); override;
function IsLogValuesForced: Boolean; override;
property ConfigData: TReplaceCompData read FConfigData write FConfigData;
property IgnoreErrors: Boolean read FIgnoreErrors write FIgnoreErrors;
property LogChanges: Boolean read FLogChanges write FLogChanges;
property OverwriteLog: Boolean read FOverwriteLog write FOverwriteLog;
property ShowLogWin: Boolean read FShowLogWin write FShowLogWin;
property LogValues: Boolean read FLogValues write FLogValues;
property LogEvents: TCompRepEventList read FLogEvents;
end;
TReplaceCompExpert = class(TGX_Expert)
private
FCROShowLogWin: Boolean;
FCROIgnoreErrors: Boolean;
FCROLogChanges: Boolean;
FCROOverwriteLog: Boolean;
FConfigData: TReplaceCompData;
FCROLogValues: Boolean;
FLastReplaceClass: string;
procedure PrepareConfigData;
procedure UnprepareConfigData;
protected
procedure UpdateAction(Action: TCustomAction); override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
public
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
class function ConfigurationKey: string; override;
procedure Execute(Sender: TObject); override;
function HasConfigOptions: Boolean; override;
procedure Configure; override;
procedure SetActive(New: Boolean); override;
function HasDesignerMenuItem: Boolean; override;
property CROIgnoreErrors: Boolean read FCROIgnoreErrors write FCROIgnoreErrors;
property CROLogChanges: Boolean read FCROLogChanges write FCROLogChanges;
property CROOverwriteLog: Boolean read FCROOverwriteLog write FCROOverwriteLog;
property CROShowLogWin: Boolean read FCROShowLogWin write FCROShowLogWin;
property CROLogValues: Boolean read FCROLogValues write FCROLogValues;
property LastReplaceClass: string read FLastReplaceClass write FLastReplaceClass;
end;
TMapScore = class
SourceDepth: Integer;
DestDepth: Integer;
Item: TCompRepMapItem;
end;
TMapScoreList = class(TGxObjectDictionary)
public
procedure AddScore(const APropName: string; ASourceDepth, ADestDepth: Integer; MapItem: TCompRepMapItem);
procedure GetScore(const APropName: string; var SourceDepth, DestDepth: Integer; var MapItem: TCompRepMapItem);
end;
var
ReplaceCompExpert: TReplaceCompExpert = nil;
procedure TfmReplaceComp.LoadComponentList;
var
OldGroup: TPersistentClass;
begin
cbSearch.Items.BeginUpdate;
cbReplace.Items.BeginUpdate;
try
if GxOtaActiveDesignerIsVCL then
OldGroup := ActivateClassGroup(TControl)
else
OldGroup := nil; // Not necessary?: ActivateClassGroup(QControls.TControl);
try
GxOtaGetInstalledComponentList(cbSearch.Items, True);
cbReplace.Items.Text := cbSearch.Items.Text;
finally
if OldGroup <> nil then
ActivateClassGroup(OldGroup);
end;
finally
cbReplace.Items.EndUpdate;
cbSearch.Items.EndUpdate;
end;
end;
procedure TfmReplaceComp.SetOptionsForNoCurrentForm;
begin
// There is no "current" form, so the only settings
// that make sense are as follows:
rbSelectedOnCurrentForm.Enabled := False;
rbAllOnCurrentForm.Enabled := False;
rbAllInProject.Checked := True;
end;
procedure TfmReplaceComp.SetOptionsForNoComponentsSelected;
begin
// No components are selected on the "current" form,
// so the only settings that make sense are as follows:
rbSelectedOnCurrentForm.Enabled := False;
rbAllOnCurrentForm.Enabled := True;
rbAllOnCurrentForm.Checked := True;
end;
procedure TfmReplaceComp.btnHelpClick(Sender: TObject);
begin
GxContextHelp(Self, 19);
end;
procedure TfmReplaceComp.btnOKClick(Sender: TObject);
resourcestring
SComponentNotSelectedForSearch = 'You have not selected a component to search for.';
SComponentNotSelectedForReplace = 'You have not selected a component to replace.';
SUnknComponentNameForSearch = '%s is not a valid component class to search for.';
SUnknComponentNameForRep = '%s is not a valid component class to replace with.';
var
SearchComponent: string;
ReplaceComponent: string;
begin
SearchComponent := Trim(cbSearch.Text);
if SearchComponent = '' then
raise Exception.Create(SComponentNotSelectedForSearch);
ReplaceComponent := Trim(cbReplace.Text);
if ReplaceComponent = '' then
raise Exception.Create(SComponentNotSelectedForReplace);
if (GetClass(SearchComponent) = nil) or (GetClass(ReplaceComponent) = nil) then
ActivateClassGroup(TControl); // This isn't actually right, but probably saves some errors for the most common VCL projects
if GetClass(SearchComponent) = nil then
raise Exception.CreateFmt(SUnknComponentNameForSearch, [SearchComponent]);
if GetClass(ReplaceComponent) = nil then
raise Exception.CreateFmt(SUnknComponentNameForRep, [ReplaceComponent]);
SaveFormSettings;
ModalResult := mrOk;
Screen.Cursor := crHourglass;
try
FController := PrepareController;
try
FController.SourceClassName := SearchComponent;
FController.DestClassName := ReplaceComponent;
FController.SignalBegin;
try
if rbSelectedOnCurrentForm.Checked then
ReplaceComponentsOnCurrentForm(True)
else if rbAllOnCurrentForm.Checked then
ReplaceComponentsOnCurrentForm(False)
else if rbAllInProject.Checked then
ReplaceComponentsOnAllForms;
finally
FController.SignalEnd;
end;
// Refresh the object inspector, since some properties have changed
GxOtaRefreshCurrentDesigner;
if TCompRepControllerReal(FController).ShowLogWin then
ShowLogWin(SearchComponent, ReplaceComponent, TCompRepControllerReal(FController).LogEvents);
finally
FreeAndNil(FController);
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfmReplaceComp.ShowLogWin(const SourceClassName, DestClassName: string; LogEvents: TCompRepEventList);
var
Dlg: TfmReplaceCompLog;
begin
Assert(Assigned(ReplaceCompExpert));
ReplaceCompExpert.PrepareConfigData;
Dlg := TfmReplaceCompLog.Create(nil, ReplaceCompExpert.FConfigData, SourceClassName, DestClassName, LogEvents);
try
Dlg.Icon := Self.Icon;
Dlg.ShowModal;
finally
FreeAndNil(Dlg);
end;
end;
procedure TfmReplaceComp.cbSearchChange(Sender: TObject);
var
OkIsEnabled: Boolean;
SearchComponent: string;
ReplaceComponent: string;
begin
SearchComponent := Trim(cbSearch.Text);
ReplaceComponent := Trim(cbReplace.Text);
OkIsEnabled := (Length(SearchComponent) > 0) and
(Length(ReplaceComponent) > 0) and
not SameText(SearchComponent, ReplaceComponent);
btnOK.Enabled := OkIsEnabled;
end;
procedure TfmReplaceComp.cbSearchKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
SendingComboBox: TComboBox;
begin
if Key = VK_BACK then
begin
SendingComboBox := Sender as TComboBox;
Assert(Assigned(SendingComboBox));
SendingComboBox.Text := Copy(SendingComboBox.Text, 1, SendingComboBox.SelStart-1);
Key := 0;
cbSearchChange(SendingComboBox);
end;
end;
function TfmReplaceComp.PrepareController: TCompRepController;
var
NativeResult: TCompRepControllerReal;
begin
Assert(Assigned(ReplaceCompExpert));
Result := TCompRepControllerReal.Create;
NativeResult := TCompRepControllerReal(Result);
ReplaceCompExpert.PrepareConfigData;
NativeResult.ConfigData := ReplaceCompExpert.FConfigData;
NativeResult.IgnoreErrors := ReplaceCompExpert.CROIgnoreErrors;
NativeResult.LogChanges := ReplaceCompExpert.CROLogChanges;
NativeResult.OverwriteLog := ReplaceCompExpert.CROOverwriteLog;
NativeResult.ShowLogWin := ReplaceCompExpert.CROShowLogWin;
NativeResult.LogValues := ReplaceCompExpert.CROLogValues;
end;
procedure TfmReplaceComp.ReplaceComponentsOnForm(FormEditor: IOTAFormEditor; OnlySelected: Boolean);
resourcestring
SFileStart = 'Start of file processing';
SFileProc = 'File processing';
SFileFreeInfo = 'Destroying module information';
SCompSearch = 'Component search';
SReplaceComp = 'Component replacing';
var
FormInfo: TFormInfo;
CompList: TStringList;
FileName: string;
Context: string;
begin
Assert(Assigned(FormEditor));
FileName := '';
try
try
FileName := FormEditor.FileName;
FController.SignalFileBegin(FileName);
except
on E: Exception do
begin
FController.SignalFileBegin(FileName);
FController.HandleException(E, SFileStart);
end;
end;
CompList := nil;
Context := SFileProc;
try
CompList := nil;
FormInfo := TFormInfo.Create(FController, FormEditor);
try
CompList := TStringList.Create;
Context := SCompSearch;
if OnlySelected then
FormInfo.GetSelectedComponents(CompList, cbSearch.Text)
else
FormInfo.GetMatchingComponents(CompList, cbSearch.Text);
Context := SReplaceComp;
FormInfo.ReplaceComponents(CompList, cbReplace.Text);
Context := SFileFreeInfo;
finally
FreeAndNil(CompList);
FreeAndNil(FormInfo);
end;
except
on e: Exception do
FController.HandleException(E, Context);
end;
finally
FController.SignalFileEnd(FileName);
end;
end;
procedure TfmReplaceComp.ReplaceComponentsOnCurrentForm(OnlySelected: Boolean);
var
CurrentForm: IOTAFormEditor;
begin
CurrentForm := GxOtaGetCurrentFormEditor;
Assert(Assigned(CurrentForm));
ReplaceComponentsOnForm(CurrentForm, OnlySelected);
end;
procedure TfmReplaceComp.ReplaceComponentsOnAllForms;
var
CurrentProject: IOTAProject;
ModuleInfo: IOTAModuleInfo;
Module: IOTAModule;
FormEditor: IOTAFormEditor;
i: Integer;
begin
CurrentProject := GxOtaGetCurrentProject;
Assert(Assigned(CurrentProject));
for i := 0 to CurrentProject.GetModuleCount - 1 do
begin
ModuleInfo := CurrentProject.GetModule(i);
Assert(Assigned(ModuleInfo));
// Ignore non-project units like Forms.pas and .dcp files
if (Trim(ModuleInfo.FileName) = '') or IsDcp(ModuleInfo.FileName) or IsExecutable(ModuleInfo.FileName) then
Continue;
Module := ModuleInfo.OpenModule;
if not Assigned(Module) then
Continue;
FormEditor := GxOtaGetFormEditorFromModule(Module);
if Assigned(FormEditor) then
ReplaceComponentsOnForm(FormEditor, False);
end;
end;
constructor TfmReplaceComp.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
LoadFormSettings;
SetupControls;
end;
procedure TfmReplaceComp.SetupControls;
resourcestring
SOpenSomethingFirst = 'Please open a project or unit first.';
var
FirstSelectedComponentTypeName: string;
FormEditor: IOTAFormEditor;
SelCount: Integer;
CurrentComponent: IOTAComponent;
i: Integer;
begin
LoadComponentList;
if not GxOtaTryGetCurrentFormEditor(FormEditor) then
begin
if GxOtaGetCurrentProject = nil then
raise Exception.Create(SOpenSomethingFirst);
SetOptionsForNoCurrentForm;
Exit;
end;
if GxOtaSelectedComponentIsRoot(FormEditor) then
begin
// The "selected component" is the form itself - hence there are
// no components on that form that are selected.
SetOptionsForNoComponentsSelected;
Exit;
end;
SelCount := FormEditor.GetSelCount;
if not (SelCount > 0) then
Exit;
CurrentComponent := FormEditor.GetSelComponent(0);
Assert(Assigned(CurrentComponent));
FirstSelectedComponentTypeName := CurrentComponent.GetComponentType;
i := cbSearch.Items.IndexOf(FirstSelectedComponentTypeName);
if i > -1 then
begin
cbSearch.ItemIndex := i;
ActiveControl := cbReplace;
end;
cbSearchChange(cbSearch);
end;
procedure TfmReplaceComp.LoadFormSettings;
begin
if ReplaceCompExpert = nil then
Exit;
chkIgnoreErrors.Checked := ReplaceCompExpert.CROIgnoreErrors;
chkLogChanges.Checked := ReplaceCompExpert.CROLogChanges;
chkOverwriteLog.Checked := ReplaceCompExpert.CROOverwriteLog;
chkShowLogWin.Checked := ReplaceCompExpert.CROShowLogWin;
chkLogValues.Checked := ReplaceCompExpert.CROLogValues;
cbReplace.Text := ReplaceCompExpert.LastReplaceClass;
end;
procedure TfmReplaceComp.SaveFormSettings;
begin
if ReplaceCompExpert = nil then
Exit;
ReplaceCompExpert.CROIgnoreErrors := chkIgnoreErrors.Checked;
ReplaceCompExpert.CROLogChanges := chkLogChanges.Checked;
ReplaceCompExpert.CROOverwriteLog := chkOverwriteLog.Checked;
ReplaceCompExpert.CROShowLogWin := chkShowLogWin.Checked;
ReplaceCompExpert.CROLogValues := chkLogValues.Checked;
ReplaceCompExpert.LastReplaceClass := cbReplace.Text;
ReplaceCompExpert.SaveSettings;
end;
{ TReplaceCompExpert }
procedure TReplaceCompExpert.UpdateAction(Action: TCustomAction);
var
FormEditor: IOTAFormEditor;
begin
Action.Enabled := GxOtaTryGetCurrentFormEditor(FormEditor) or (GxOtaHaveCurrentProject);
end;
procedure TReplaceCompExpert.Execute(Sender: TObject);
resourcestring
NoSupportError = 'Due to limitations of the IDE, Replace Components can not support VCL.NET projects.';
begin
// Replace components requires IOTAComponent interfaces and access to native TPersistent objects
if GxOtaActiveDesignerIsNFM then
raise Exception.Create(NoSupportError);
with TfmReplaceComp.Create(nil) do
try
ShowModal;
finally
Free;
end;
end;
function TReplaceCompExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Replace &Components...';
begin
Result := SMenuCaption;
end;
class function TReplaceCompExpert.GetName: string;
begin
Result := 'ReplaceComponents';
end;
function TReplaceCompExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
procedure TReplaceCompExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited InternalLoadSettings(Settings);
// Do not localize any of the following lines
FCROIgnoreErrors := Settings.ReadBool('IgnoreErrors', False);
FCROLogChanges := Settings.ReadBool('LogChanges', False);
FCROOverwriteLog := Settings.ReadBool('OverwriteLog', False);
FCROShowLogWin := Settings.ReadBool('ShowLogWin', False);
FCROLogValues := Settings.ReadBool('LogValues', False);
FLastReplaceClass := Settings.ReadString('LastReplaceClass', '');
end;
procedure TReplaceCompExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited InternalSaveSettings(Settings);
// Do not localize any of the following lines
Settings.WriteBool('IgnoreErrors', FCROIgnoreErrors);
Settings.WriteBool('LogChanges', FCROLogChanges);
Settings.WriteBool('OverwriteLog', FCROOverwriteLog);
Settings.WriteBool('ShowLogWin', FCROShowLogWin);
Settings.WriteBool('LogValues', FCROLogValues);
Settings.WriteString('LastReplaceClass', FLastReplaceClass);
end;
constructor TReplaceCompExpert.Create;
begin
inherited;
if ReplaceCompExpert = nil then
ReplaceCompExpert := Self;
end;
destructor TReplaceCompExpert.Destroy;
begin
UnprepareConfigData;
if ReplaceCompExpert = Self then
ReplaceCompExpert := nil;
inherited;
end;
class function TReplaceCompExpert.ConfigurationKey: string;
begin
Result := 'ReplaceComponents';
end;
procedure TReplaceCompExpert.PrepareConfigData;
begin
if not Assigned(FConfigData) then
begin
FConfigData := TReplaceCompData.Create;
FConfigData.RootConfigurationKey := ConfigurationKey;
FConfigData.ReloadData;
end;
end;
procedure TReplaceCompExpert.UnprepareConfigData;
begin
FreeAndNil(FConfigData);
end;
procedure TReplaceCompExpert.Configure;
var
Dlg: TfmReplaceCompMapList;
begin
PrepareConfigData;
Dlg := TfmReplaceCompMapList.Create(nil, FConfigData);
try
SetFormIcon(Dlg);
Dlg.ShowModal;
finally
FreeAndNil(Dlg);
end;
end;
procedure TReplaceCompExpert.SetActive(New: Boolean);
begin
inherited SetActive(New);
if Active then
PrepareConfigData
else
UnprepareConfigData;
end;
function TReplaceCompExpert.HasDesignerMenuItem: Boolean;
begin
Result := True;
end;
{ TCompRepControllerReal }
constructor TCompRepControllerReal.Create;
begin
inherited Create;
FLogEvents := TCompRepEventList.Create;
FNameStack := TStringList.Create;
FObjectStack := TStringList.Create;
FLog := TStringList.Create;
end;
destructor TCompRepControllerReal.Destroy;
begin
FreeAndNil(FLog);
FreeAndNil(FObjectStack);
FreeAndNil(FNameStack);
FreeAndNil(FLogEvents);
inherited;
end;
function TCompRepControllerReal.NewEvent: TCompRepEvent;
begin
Result := TCompRepEvent.Create;
FLogEvents.Add(Result);
Result.When := Now;
AssignContext(Result);
end;
procedure TCompRepControllerReal.HandleException(E: Exception; const Context: string);
resourcestring
SErrorPfx = 'Error occurred: ';
SErrorSuff = #10+#10+'Ignore this error and continue?';
var
Event: TCompRepEvent;
MrRes: Integer;
Msg: string;
begin
if E is EAbort then
Abort;
Event := NewEvent;
Event.ErrorClass := E.ClassName;
Event.Text := SErrorPfx+E.Message;
Event.Context := Context;
if LogChanges then
SaveEventToLog(Event);
if not IgnoreErrors then
begin
Msg := FormatEventForMessage(Event)+SErrorSuff;
MrRes := MessageDlg(Msg, mtError, [mbYes, mbAbort, mbYesToAll], 0);
if MrRes = mrAbort then
Abort;
if MrRes = mrYesToAll then
IgnoreErrors := True;
end;
end;
procedure TCompRepControllerReal.LogMsg(const AMsg: string);
var
Event: TCompRepEvent;
begin
Event := NewEvent;
Event.Text := AMsg;
if LogChanges then
SaveEventToLog(Event);
end;
procedure TCompRepControllerReal.AssignContext(Event: TCompRepEvent);
resourcestring
SInvalid = 'Invalid';
var
ObjectName: string;
ObjectPtr: TObject;
begin
Event.FileName := FFileName;
Event.SourceClassName := Self.SourceClassName;
Event.DestClassName := Self.DestClassName;
Event.StackText := Self.StackText;
GetCurrentObject(ObjectName, ObjectPtr);
Event.ObjectSearchName := ObjectName;
if Assigned(ObjectPtr) then
begin
try
Event.ObjectClass := ObjectPtr.ClassName;
if ObjectPtr is TComponent then
Event.ComponentName := TComponent(ObjectPtr).Name;
except
on E: Exception do
begin
Event.ObjectClass := SInvalid;
end;
end;
end;
end;
procedure TCompRepControllerReal.GetCurrentObject(var ObjectName: string;
var ObjectPtr: TObject);
begin
if FObjectStack.Count>0 then
begin
ObjectName := FObjectStack[FObjectStack.Count-1];
ObjectPtr := FObjectStack.Objects[FObjectStack.Count-1];
end
else
begin
ObjectName := '';
ObjectPtr := nil;
end;
end;
function TCompRepControllerReal.StackText: string;
var
i: Integer;
begin
Result := '';
for i := 0 to FNameStack.Count-1 do
if i > 0 then
Result := Result + '\'+ FNameStack[i]
else
Result := FNameStack[i];
end;
procedure TCompRepControllerReal.SignalFileBegin(const AFileName: string);
begin
FFileName := AFileName;
end;
procedure TCompRepControllerReal.SignalFileEnd(const AFileName: string);
begin
FFileName := '';
end;
procedure TCompRepControllerReal.SignalObjectBegin(const AName: string;
AObject: TObject);
begin
FObjectStack.AddObject(AName, AObject);
end;
procedure TCompRepControllerReal.SignalObjectEnd(const AName: string; AObject: TObject);
begin
with FObjectStack do
if (Count > 0) and (FObjectStack[Count-1] = AName) then
Delete(Count-1);
end;
procedure TCompRepControllerReal.SignalStackBegin(const AName: string);
begin
FNameStack.Add(AName);
end;
procedure TCompRepControllerReal.SignalStackEnd(const AName: string);
begin
with FNameStack do
if (Count > 0) and (FNameStack[Count-1] = AName) then
Delete(Count-1);
end;
function TCompRepControllerReal.TryAddMapping(MapItem: TCompRepMapItem;
const ASrcClassName, ADestClassName, APropName, AMapPropName: string;
Scores: TMapScoreList; Mappings: TCompRepMapList): Boolean;
var
OldScoreSrc, OldScoreDest: Integer;
NewScoreSrc, NewScoreDest: Integer;
NewMapItem: TCompRepMapItem;
begin
Result := False;
if MapItem.ExtractCorePropName(AMapPropName) <> APropName then
Exit;
NewScoreSrc := ClassLevel(GetClass(MapItem.SourceClassName),
GetClass(ASrcClassName));
NewScoreDest := ClassLevel(GetClass(MapItem.DestClassName),
GetClass(ADestClassName));
Scores.GetScore(AMapPropName, OldScoreSrc, OldScoreDest, NewMapItem);
if ((OldScoreSrc >= NewScoreSrc) or (OldScoreSrc = -1)) and
((OldScoreDest >= NewScoreDest) or (OldScoreDest = -1)) and
(NewScoreSrc >= 0) and
(NewScoreDest >= 0)
then
begin
Result := True;
if NewMapItem = nil then
begin
NewMapItem := TCompRepMapItem.Create;
Mappings.Add(NewMapItem)
end;
NewMapItem.AssignMapping(MapItem);
Scores.AddScore(AMapPropName, NewScoreSrc, NewScoreDest, NewMapItem);
end;
end;
{ Prepare all relevant mappings for DestClassName and specified params }
procedure TCompRepControllerReal.PrepareMappingForProp(const AClassName,
APropName: string; Mappings: TCompRepMapList);
var
i, j: Integer;
MapItem, WorkItem: TCompRepMapItem;
Scores: TMapScoreList;
begin
WorkItem := TCompRepMapItem.Create;
try
Scores := TMapScoreList.Create;
try
for i := 0 to FConfigData.MapGroupList.Count-1 do
for j := 0 to FConfigData.MapGroupList[i].Items.Count-1 do
begin
MapItem := FConfigData.MapGroupList[i].Items[j];
if (not TryAddMapping(MapItem, AClassName, DestClassName, APropName,
MapItem.SourcePropName, Scores, Mappings))
and
MapItem.BiDirEnabled
then
begin
WorkItem.AssignMapping(MapItem);
WorkItem.Reverse;
TryAddMapping(WorkItem, AClassName, DestClassName, APropName,
WorkItem.SourcePropName, Scores, Mappings);
end;
end;
finally
FreeAndNil(Scores);
end;
finally
FreeAndNil(WorkItem);
end;
end;
{ Prepare all relevant mappings with constant assignment }
procedure TCompRepControllerReal.PrepareConstMappingForProp(
const AClassName, APropName: string; Mappings: TCompRepMapList);
var
i, j: Integer;
MapItem, WorkItem: TCompRepMapItem;
Scores: TMapScoreList;
begin
WorkItem := TCompRepMapItem.Create;
try
Scores := TMapScoreList.Create;
try
for i := 0 to FConfigData.MapGroupList.Count-1 do
for j := 0 to FConfigData.MapGroupList[i].Items.Count-1 do
begin
MapItem := FConfigData.MapGroupList[i].Items[j];
if not MapItem.UseConstValue then
Continue;
if (not TryAddMapping(MapItem, SourceClassName, AClassName, APropName,
MapItem.DestPropName, Scores, Mappings))
and
MapItem.BiDirEnabled
then
begin
WorkItem.AssignMapping(MapItem);
WorkItem.Reverse;
TryAddMapping(WorkItem, SourceClassName, AClassName, APropName,
MapItem.DestPropName, Scores, Mappings);
end;
end;
finally
FreeAndNil(Scores);
end;
finally
FreeAndNil(WorkItem);
end;
end;
function TCompRepControllerReal.GetLogFileName: string;
begin
Result := AddSlash(ConfigInfo.ConfigPath) + 'ReplaceComp.log'
end;
procedure TCompRepControllerReal.StartLog;
var
FileName: string;
begin
if not LogChanges then Exit;
if OverwriteLog then
DeleteLog;
FLog.Clear;
FileName := GetLogFileName;
if FileExists(FileName) then
FLog.LoadFromFile(FileName);
end;
procedure TCompRepControllerReal.DeleteLog;
begin
DeleteFile(PChar(GetLogFileName));
end;
procedure TCompRepControllerReal.SaveLog;
begin
FLog.SaveToFile(GetLogFileName);
end;
procedure TCompRepControllerReal.SignalBegin;
begin
if LogChanges then
StartLog;
end;
procedure TCompRepControllerReal.SignalEnd;
begin
if LogChanges then
SaveLog;
end;
function TCompRepControllerReal.FormatEventForMessage(AEvent: TCompRepEvent): string;
resourcestring
SLayout =
'Error occurred during replace:'+#10+
#10+
'Message: %Text%'+#10+
#10+
'Error class: %ErrorClass%'+#10+
'FileName: %FileName%'+#10+
'Source class: %SourceClassName%, Destination class: %DestClassName%'+#10+
'Object: %ObjectClass%, %ObjectSearchName%'+#10+
'Context: %Context%';
begin
Result := AEvent.FormatEventAsText(SLayout);
end;
procedure TCompRepControllerReal.SaveEventToLog(AEvent: TCompRepEvent);
resourcestring
SLayout =
'--> [%When%] %EventType%'+#10+
'>Message:'+#10+
'%Text%'+#10+
'>Context:'+#10+
'FileName: %FileName%'+#10+
'Source class: %SourceClassName%, Destination class: %DestClassName%'+#10+
'Object: %ObjectClass%, %ObjectSearchName%'+#10+
'%ErrorPart%'+
'Context: %Context%'+#10+
'-->';
var
Items: TStringList;
EventText: string;
begin
EventText := AEvent.FormatEventAsText(SLayout);
Items := TStringList.Create;
try
Items.Text := EventText;
FLog.AddStrings(Items);
finally
FreeAndNil(Items);
end;
SaveLog;
end;
function TCompRepControllerReal.IsLogValuesForced: Boolean;
begin
Result := FLogValues;
end;
{ TMapScoreList }
procedure TMapScoreList.AddScore(const APropName: string; ASourceDepth,
ADestDepth: Integer; MapItem: TCompRepMapItem);
var
NewScore: TMapScore;
begin
NewScore := FindObject(APropName) as TMapScore;
if not Assigned(NewScore) then
begin
NewScore := TMapScore.Create;
inherited AddWithCode(APropName, NewScore);
end;
NewScore.SourceDepth := ASourceDepth;
NewScore.DestDepth := ADestDepth;
NewScore.Item := MapItem;
end;
procedure TMapScoreList.GetScore(const APropName: string; var SourceDepth,
DestDepth: Integer; var MapItem: TCompRepMapItem);
var
MapScore: TMapScore;
begin
MapScore := FindObject(APropName) as TMapScore;
if Assigned(MapScore) then
begin
SourceDepth := MapScore.SourceDepth;
DestDepth := MapScore.DestDepth;
MapItem := MapScore.Item;
end
else
begin
SourceDepth := -1;
DestDepth := -1;
MapItem := nil;
end;
end;
procedure TfmReplaceComp.btnSettingsClick(Sender: TObject);
begin
ReplaceCompExpert.Configure;
end;
initialization
ReplaceCompExpert := nil;
RegisterGX_Expert(TReplaceCompExpert);
end.
|
unit CompInfoKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы CompInfo }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\CompInfoKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "CompInfoKeywordsPack" MUID: (FD9964108640)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, nscTreeViewWithAdapterDragDrop
, vtPanel
, vtLabel
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, CompInfo_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_CompInfo = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы CompInfo
----
*Пример использования*:
[code]
'aControl' форма::CompInfo TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_CompInfo
Tkw_CompInfo_Control_tvComplectInfo = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола tvComplectInfo
----
*Пример использования*:
[code]
контрол::tvComplectInfo TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_tvComplectInfo
Tkw_CompInfo_Control_tvComplectInfo_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола tvComplectInfo
----
*Пример использования*:
[code]
контрол::tvComplectInfo:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_tvComplectInfo_Push
Tkw_CompInfo_Control_pnBottom = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола pnBottom
----
*Пример использования*:
[code]
контрол::pnBottom TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnBottom
Tkw_CompInfo_Control_pnBottom_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола pnBottom
----
*Пример использования*:
[code]
контрол::pnBottom:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnBottom_Push
Tkw_CompInfo_Control_pnVisualRepresentationData = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола pnVisualRepresentationData
----
*Пример использования*:
[code]
контрол::pnVisualRepresentationData TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnVisualRepresentationData
Tkw_CompInfo_Control_pnVisualRepresentationData_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола pnVisualRepresentationData
----
*Пример использования*:
[code]
контрол::pnVisualRepresentationData:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnVisualRepresentationData_Push
Tkw_CompInfo_Control_pnVisualRepresentationDataCaption = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола pnVisualRepresentationDataCaption
----
*Пример использования*:
[code]
контрол::pnVisualRepresentationDataCaption TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption
Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола pnVisualRepresentationDataCaption
----
*Пример использования*:
[code]
контрол::pnVisualRepresentationDataCaption:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push
Tkw_CompInfo_Control_lblVisualRepresentationData = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола lblVisualRepresentationData
----
*Пример использования*:
[code]
контрол::lblVisualRepresentationData TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_lblVisualRepresentationData
Tkw_CompInfo_Control_lblVisualRepresentationData_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола lblVisualRepresentationData
----
*Пример использования*:
[code]
контрол::lblVisualRepresentationData:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_CompInfo_Control_lblVisualRepresentationData_Push
TkwEnCompInfoTvComplectInfo = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenCompInfo.tvComplectInfo }
private
function tvComplectInfo(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TenCompInfo.tvComplectInfo }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCompInfoTvComplectInfo
TkwEnCompInfoPnBottom = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenCompInfo.pnBottom }
private
function pnBottom(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnBottom }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCompInfoPnBottom
TkwEnCompInfoPnVisualRepresentationData = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenCompInfo.pnVisualRepresentationData }
private
function pnVisualRepresentationData(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnVisualRepresentationData }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCompInfoPnVisualRepresentationData
TkwEnCompInfoPnVisualRepresentationDataCaption = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenCompInfo.pnVisualRepresentationDataCaption }
private
function pnVisualRepresentationDataCaption(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnVisualRepresentationDataCaption }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCompInfoPnVisualRepresentationDataCaption
TkwEnCompInfoLblVisualRepresentationData = {final} class(TtfwPropertyLike)
{* Слово скрипта .TenCompInfo.lblVisualRepresentationData }
private
function lblVisualRepresentationData(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtLabel;
{* Реализация слова скрипта .TenCompInfo.lblVisualRepresentationData }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnCompInfoLblVisualRepresentationData
function Tkw_Form_CompInfo.GetString: AnsiString;
begin
Result := 'enCompInfo';
end;//Tkw_Form_CompInfo.GetString
class function Tkw_Form_CompInfo.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::CompInfo';
end;//Tkw_Form_CompInfo.GetWordNameForRegister
function Tkw_CompInfo_Control_tvComplectInfo.GetString: AnsiString;
begin
Result := 'tvComplectInfo';
end;//Tkw_CompInfo_Control_tvComplectInfo.GetString
class procedure Tkw_CompInfo_Control_tvComplectInfo.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_CompInfo_Control_tvComplectInfo.RegisterInEngine
class function Tkw_CompInfo_Control_tvComplectInfo.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::tvComplectInfo';
end;//Tkw_CompInfo_Control_tvComplectInfo.GetWordNameForRegister
procedure Tkw_CompInfo_Control_tvComplectInfo_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('tvComplectInfo');
inherited;
end;//Tkw_CompInfo_Control_tvComplectInfo_Push.DoDoIt
class function Tkw_CompInfo_Control_tvComplectInfo_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::tvComplectInfo:push';
end;//Tkw_CompInfo_Control_tvComplectInfo_Push.GetWordNameForRegister
function Tkw_CompInfo_Control_pnBottom.GetString: AnsiString;
begin
Result := 'pnBottom';
end;//Tkw_CompInfo_Control_pnBottom.GetString
class procedure Tkw_CompInfo_Control_pnBottom.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_CompInfo_Control_pnBottom.RegisterInEngine
class function Tkw_CompInfo_Control_pnBottom.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnBottom';
end;//Tkw_CompInfo_Control_pnBottom.GetWordNameForRegister
procedure Tkw_CompInfo_Control_pnBottom_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('pnBottom');
inherited;
end;//Tkw_CompInfo_Control_pnBottom_Push.DoDoIt
class function Tkw_CompInfo_Control_pnBottom_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnBottom:push';
end;//Tkw_CompInfo_Control_pnBottom_Push.GetWordNameForRegister
function Tkw_CompInfo_Control_pnVisualRepresentationData.GetString: AnsiString;
begin
Result := 'pnVisualRepresentationData';
end;//Tkw_CompInfo_Control_pnVisualRepresentationData.GetString
class procedure Tkw_CompInfo_Control_pnVisualRepresentationData.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_CompInfo_Control_pnVisualRepresentationData.RegisterInEngine
class function Tkw_CompInfo_Control_pnVisualRepresentationData.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnVisualRepresentationData';
end;//Tkw_CompInfo_Control_pnVisualRepresentationData.GetWordNameForRegister
procedure Tkw_CompInfo_Control_pnVisualRepresentationData_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('pnVisualRepresentationData');
inherited;
end;//Tkw_CompInfo_Control_pnVisualRepresentationData_Push.DoDoIt
class function Tkw_CompInfo_Control_pnVisualRepresentationData_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnVisualRepresentationData:push';
end;//Tkw_CompInfo_Control_pnVisualRepresentationData_Push.GetWordNameForRegister
function Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.GetString: AnsiString;
begin
Result := 'pnVisualRepresentationDataCaption';
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.GetString
class procedure Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.RegisterInEngine
class function Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnVisualRepresentationDataCaption';
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.GetWordNameForRegister
procedure Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('pnVisualRepresentationDataCaption');
inherited;
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push.DoDoIt
class function Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnVisualRepresentationDataCaption:push';
end;//Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push.GetWordNameForRegister
function Tkw_CompInfo_Control_lblVisualRepresentationData.GetString: AnsiString;
begin
Result := 'lblVisualRepresentationData';
end;//Tkw_CompInfo_Control_lblVisualRepresentationData.GetString
class procedure Tkw_CompInfo_Control_lblVisualRepresentationData.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_CompInfo_Control_lblVisualRepresentationData.RegisterInEngine
class function Tkw_CompInfo_Control_lblVisualRepresentationData.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lblVisualRepresentationData';
end;//Tkw_CompInfo_Control_lblVisualRepresentationData.GetWordNameForRegister
procedure Tkw_CompInfo_Control_lblVisualRepresentationData_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('lblVisualRepresentationData');
inherited;
end;//Tkw_CompInfo_Control_lblVisualRepresentationData_Push.DoDoIt
class function Tkw_CompInfo_Control_lblVisualRepresentationData_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::lblVisualRepresentationData:push';
end;//Tkw_CompInfo_Control_lblVisualRepresentationData_Push.GetWordNameForRegister
function TkwEnCompInfoTvComplectInfo.tvComplectInfo(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TenCompInfo.tvComplectInfo }
begin
Result := aenCompInfo.tvComplectInfo;
end;//TkwEnCompInfoTvComplectInfo.tvComplectInfo
class function TkwEnCompInfoTvComplectInfo.GetWordNameForRegister: AnsiString;
begin
Result := '.TenCompInfo.tvComplectInfo';
end;//TkwEnCompInfoTvComplectInfo.GetWordNameForRegister
function TkwEnCompInfoTvComplectInfo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwEnCompInfoTvComplectInfo.GetResultTypeInfo
function TkwEnCompInfoTvComplectInfo.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCompInfoTvComplectInfo.GetAllParamsCount
function TkwEnCompInfoTvComplectInfo.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenCompInfo)]);
end;//TkwEnCompInfoTvComplectInfo.ParamsTypes
procedure TkwEnCompInfoTvComplectInfo.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству tvComplectInfo', aCtx);
end;//TkwEnCompInfoTvComplectInfo.SetValuePrim
procedure TkwEnCompInfoTvComplectInfo.DoDoIt(const aCtx: TtfwContext);
var l_aenCompInfo: TenCompInfo;
begin
try
l_aenCompInfo := TenCompInfo(aCtx.rEngine.PopObjAs(TenCompInfo));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenCompInfo: TenCompInfo : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(tvComplectInfo(aCtx, l_aenCompInfo));
end;//TkwEnCompInfoTvComplectInfo.DoDoIt
function TkwEnCompInfoPnBottom.pnBottom(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnBottom }
begin
Result := aenCompInfo.pnBottom;
end;//TkwEnCompInfoPnBottom.pnBottom
class function TkwEnCompInfoPnBottom.GetWordNameForRegister: AnsiString;
begin
Result := '.TenCompInfo.pnBottom';
end;//TkwEnCompInfoPnBottom.GetWordNameForRegister
function TkwEnCompInfoPnBottom.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEnCompInfoPnBottom.GetResultTypeInfo
function TkwEnCompInfoPnBottom.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCompInfoPnBottom.GetAllParamsCount
function TkwEnCompInfoPnBottom.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenCompInfo)]);
end;//TkwEnCompInfoPnBottom.ParamsTypes
procedure TkwEnCompInfoPnBottom.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству pnBottom', aCtx);
end;//TkwEnCompInfoPnBottom.SetValuePrim
procedure TkwEnCompInfoPnBottom.DoDoIt(const aCtx: TtfwContext);
var l_aenCompInfo: TenCompInfo;
begin
try
l_aenCompInfo := TenCompInfo(aCtx.rEngine.PopObjAs(TenCompInfo));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenCompInfo: TenCompInfo : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(pnBottom(aCtx, l_aenCompInfo));
end;//TkwEnCompInfoPnBottom.DoDoIt
function TkwEnCompInfoPnVisualRepresentationData.pnVisualRepresentationData(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnVisualRepresentationData }
begin
Result := aenCompInfo.pnVisualRepresentationData;
end;//TkwEnCompInfoPnVisualRepresentationData.pnVisualRepresentationData
class function TkwEnCompInfoPnVisualRepresentationData.GetWordNameForRegister: AnsiString;
begin
Result := '.TenCompInfo.pnVisualRepresentationData';
end;//TkwEnCompInfoPnVisualRepresentationData.GetWordNameForRegister
function TkwEnCompInfoPnVisualRepresentationData.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEnCompInfoPnVisualRepresentationData.GetResultTypeInfo
function TkwEnCompInfoPnVisualRepresentationData.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCompInfoPnVisualRepresentationData.GetAllParamsCount
function TkwEnCompInfoPnVisualRepresentationData.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenCompInfo)]);
end;//TkwEnCompInfoPnVisualRepresentationData.ParamsTypes
procedure TkwEnCompInfoPnVisualRepresentationData.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству pnVisualRepresentationData', aCtx);
end;//TkwEnCompInfoPnVisualRepresentationData.SetValuePrim
procedure TkwEnCompInfoPnVisualRepresentationData.DoDoIt(const aCtx: TtfwContext);
var l_aenCompInfo: TenCompInfo;
begin
try
l_aenCompInfo := TenCompInfo(aCtx.rEngine.PopObjAs(TenCompInfo));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenCompInfo: TenCompInfo : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(pnVisualRepresentationData(aCtx, l_aenCompInfo));
end;//TkwEnCompInfoPnVisualRepresentationData.DoDoIt
function TkwEnCompInfoPnVisualRepresentationDataCaption.pnVisualRepresentationDataCaption(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtPanel;
{* Реализация слова скрипта .TenCompInfo.pnVisualRepresentationDataCaption }
begin
Result := aenCompInfo.pnVisualRepresentationDataCaption;
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.pnVisualRepresentationDataCaption
class function TkwEnCompInfoPnVisualRepresentationDataCaption.GetWordNameForRegister: AnsiString;
begin
Result := '.TenCompInfo.pnVisualRepresentationDataCaption';
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.GetWordNameForRegister
function TkwEnCompInfoPnVisualRepresentationDataCaption.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.GetResultTypeInfo
function TkwEnCompInfoPnVisualRepresentationDataCaption.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.GetAllParamsCount
function TkwEnCompInfoPnVisualRepresentationDataCaption.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenCompInfo)]);
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.ParamsTypes
procedure TkwEnCompInfoPnVisualRepresentationDataCaption.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству pnVisualRepresentationDataCaption', aCtx);
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.SetValuePrim
procedure TkwEnCompInfoPnVisualRepresentationDataCaption.DoDoIt(const aCtx: TtfwContext);
var l_aenCompInfo: TenCompInfo;
begin
try
l_aenCompInfo := TenCompInfo(aCtx.rEngine.PopObjAs(TenCompInfo));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenCompInfo: TenCompInfo : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(pnVisualRepresentationDataCaption(aCtx, l_aenCompInfo));
end;//TkwEnCompInfoPnVisualRepresentationDataCaption.DoDoIt
function TkwEnCompInfoLblVisualRepresentationData.lblVisualRepresentationData(const aCtx: TtfwContext;
aenCompInfo: TenCompInfo): TvtLabel;
{* Реализация слова скрипта .TenCompInfo.lblVisualRepresentationData }
begin
Result := aenCompInfo.lblVisualRepresentationData;
end;//TkwEnCompInfoLblVisualRepresentationData.lblVisualRepresentationData
class function TkwEnCompInfoLblVisualRepresentationData.GetWordNameForRegister: AnsiString;
begin
Result := '.TenCompInfo.lblVisualRepresentationData';
end;//TkwEnCompInfoLblVisualRepresentationData.GetWordNameForRegister
function TkwEnCompInfoLblVisualRepresentationData.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEnCompInfoLblVisualRepresentationData.GetResultTypeInfo
function TkwEnCompInfoLblVisualRepresentationData.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnCompInfoLblVisualRepresentationData.GetAllParamsCount
function TkwEnCompInfoLblVisualRepresentationData.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TenCompInfo)]);
end;//TkwEnCompInfoLblVisualRepresentationData.ParamsTypes
procedure TkwEnCompInfoLblVisualRepresentationData.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству lblVisualRepresentationData', aCtx);
end;//TkwEnCompInfoLblVisualRepresentationData.SetValuePrim
procedure TkwEnCompInfoLblVisualRepresentationData.DoDoIt(const aCtx: TtfwContext);
var l_aenCompInfo: TenCompInfo;
begin
try
l_aenCompInfo := TenCompInfo(aCtx.rEngine.PopObjAs(TenCompInfo));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aenCompInfo: TenCompInfo : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(lblVisualRepresentationData(aCtx, l_aenCompInfo));
end;//TkwEnCompInfoLblVisualRepresentationData.DoDoIt
initialization
Tkw_Form_CompInfo.RegisterInEngine;
{* Регистрация Tkw_Form_CompInfo }
Tkw_CompInfo_Control_tvComplectInfo.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_tvComplectInfo }
Tkw_CompInfo_Control_tvComplectInfo_Push.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_tvComplectInfo_Push }
Tkw_CompInfo_Control_pnBottom.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnBottom }
Tkw_CompInfo_Control_pnBottom_Push.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnBottom_Push }
Tkw_CompInfo_Control_pnVisualRepresentationData.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnVisualRepresentationData }
Tkw_CompInfo_Control_pnVisualRepresentationData_Push.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnVisualRepresentationData_Push }
Tkw_CompInfo_Control_pnVisualRepresentationDataCaption.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnVisualRepresentationDataCaption }
Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_pnVisualRepresentationDataCaption_Push }
Tkw_CompInfo_Control_lblVisualRepresentationData.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_lblVisualRepresentationData }
Tkw_CompInfo_Control_lblVisualRepresentationData_Push.RegisterInEngine;
{* Регистрация Tkw_CompInfo_Control_lblVisualRepresentationData_Push }
TkwEnCompInfoTvComplectInfo.RegisterInEngine;
{* Регистрация enCompInfo_tvComplectInfo }
TkwEnCompInfoPnBottom.RegisterInEngine;
{* Регистрация enCompInfo_pnBottom }
TkwEnCompInfoPnVisualRepresentationData.RegisterInEngine;
{* Регистрация enCompInfo_pnVisualRepresentationData }
TkwEnCompInfoPnVisualRepresentationDataCaption.RegisterInEngine;
{* Регистрация enCompInfo_pnVisualRepresentationDataCaption }
TkwEnCompInfoLblVisualRepresentationData.RegisterInEngine;
{* Регистрация enCompInfo_lblVisualRepresentationData }
TtfwTypeRegistrator.RegisterType(TypeInfo(TenCompInfo));
{* Регистрация типа TenCompInfo }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel));
{* Регистрация типа TvtLabel }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
end.
|
unit rocnrope_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,konami_decrypt,konami_snd,sound_engine;
function iniciar_rocnrope:boolean;
implementation
const
rocnrope_rom:array[0..4] of tipo_roms=(
(n:'rr1.1h';l:$2000;p:$6000;crc:$83093134),(n:'rr2.2h';l:$2000;p:$8000;crc:$75af8697),
(n:'rr3.3h';l:$2000;p:$a000;crc:$b21372b1),(n:'rr4.4h';l:$2000;p:$c000;crc:$7acb2a05),
(n:'rnr_h5.vid';l:$2000;p:$e000;crc:$150a6264));
rocnrope_snd:array[0..1] of tipo_roms=(
(n:'rnr_7a.snd';l:$1000;p:0;crc:$75d2c4e2),(n:'rnr_8a.snd';l:$1000;p:$1000;crc:$ca4325ae));
rocnrope_sprites:array[0..3] of tipo_roms=(
(n:'rnr_a11.vid';l:$2000;p:0;crc:$afdaba5e),(n:'rnr_a12.vid';l:$2000;p:$2000;crc:$054cafeb),
(n:'rnr_a9.vid';l:$2000;p:$4000;crc:$9d2166b2),(n:'rnr_a10.vid';l:$2000;p:$6000;crc:$aff6e22f));
rocnrope_chars:array[0..1] of tipo_roms=(
(n:'rnr_h12.vid';l:$2000;p:0;crc:$e2114539),(n:'rnr_h11.vid';l:$2000;p:$2000;crc:$169a8f3f));
rocnrope_pal:array[0..2] of tipo_roms=(
(n:'a17_prom.bin';l:$20;p:0;crc:$22ad2c3e),(n:'b16_prom.bin';l:$100;p:$20;crc:$750a9677),
(n:'rocnrope.pr3';l:$100;p:$120;crc:$b5c75a27));
//Dip
rocnrope_dip_a:array [0..2] of def_dip=(
(mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),
(mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),())),());
rocnrope_dip_b:array [0..4] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'255'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$78;name:'Difficulty';number:16;dip:((dip_val:$78;dip_name:'1 Easy'),(dip_val:$70;dip_name:'2'),(dip_val:$68;dip_name:'3'),(dip_val:$60;dip_name:'4'),(dip_val:$58;dip_name:'5'),(dip_val:$50;dip_name:'6'),(dip_val:$48;dip_name:'7'),(dip_val:$40;dip_name:'8'),(dip_val:$38;dip_name:'9'),(dip_val:$30;dip_name:'10'),(dip_val:$28;dip_name:'11'),(dip_val:$20;dip_name:'12'),(dip_val:$18;dip_name:'13'),(dip_val:$10;dip_name:'14'),(dip_val:$8;dip_name:'15'),(dip_val:$0;dip_name:'16 Difficult'))),
(mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
rocnrope_dip_c:array [0..3] of def_dip=(
(mask:$7;name:'First Bonus';number:6;dip:((dip_val:$6;dip_name:'20K'),(dip_val:$5;dip_name:'30K'),(dip_val:$4;dip_name:'40K'),(dip_val:$3;dip_name:'50K'),(dip_val:$2;dip_name:'60K'),(dip_val:$1;dip_name:'70K'),(dip_val:$0;dip_name:'80K'),(),(),(),(),(),(),(),(),())),
(mask:$38;name:'Repeated Bonus';number:5;dip:((dip_val:$20;dip_name:'40K'),(dip_val:$18;dip_name:'50K'),(dip_val:$10;dip_name:'60K'),(dip_val:$8;dip_name:'70K'),(dip_val:$0;dip_name:'80K'),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Grant Repeated Bonus';number:2;dip:((dip_val:$40;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
irq_ena:boolean;
mem_opcodes:array[0..$9fff] of byte;
procedure update_video_rocnrope;
var
x,y,atrib:byte;
f:word;
nchar,color:word;
flip_x,flip_y:boolean;
begin
for f:=0 to $3ff do begin
if gfx[0].buffer[f] then begin
x:=f div 32;
y:=31-(f mod 32);
atrib:=memoria[$4800+f];
nchar:=memoria[$4c00+f]+((atrib and $80) shl 1);
color:=(atrib and $f) shl 4;
put_gfx_flip(x*8,y*8,nchar,color+256,1,0,(atrib and $20)<>0,(atrib and $40)<>0);
gfx[0].buffer[f]:=false;
end;
end;
actualiza_trozo(0,0,256,256,1,0,0,256,256,2);
for f:=$17 downto 0 do begin
atrib:=memoria[$4000+(f*2)];
nchar:=memoria[$4401+(f*2)];
color:=(atrib and $f) shl 4;
if not(main_screen.flip_main_screen) then begin
x:=memoria[$4001+(f*2)];
y:=memoria[$4400+(f*2)];
flip_x:=(atrib and $80)=0;
flip_y:=(atrib and $40)<>0;
end else begin
x:=241-memoria[$4001+(f*2)];
y:=240-memoria[$4400+(f*2)];
flip_x:=(atrib and $80)<>0;
flip_y:=(atrib and $40)=0;
end;
put_gfx_sprite_mask(nchar,color,flip_x,flip_y,1,0,$f);
actualiza_gfx_sprite(x,y,2,1);
end;
actualiza_trozo_final(16,0,224,256,2);
end;
procedure eventos_rocnrope;
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.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.down[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.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.down[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);
//misc
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
end;
end;
procedure rocnrope_principal;
var
frame_m:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
//snd
konamisnd_0.run;
if f=239 then begin
update_video_rocnrope;
if irq_ena then m6809_0.change_irq(ASSERT_LINE);
end;
end;
eventos_rocnrope;
video_sync;
end;
end;
function rocnrope_getbyte(direccion:word):byte;
begin
case direccion of
$3000:rocnrope_getbyte:=marcade.dswb; //dsw2
$3080:rocnrope_getbyte:=marcade.in2;
$3081:rocnrope_getbyte:=marcade.in0;
$3082:rocnrope_getbyte:=marcade.in1;
$3083:rocnrope_getbyte:=marcade.dswa; //dsw1
$3100:rocnrope_getbyte:=marcade.dswc; //dsw3
$4000..$5fff:rocnrope_getbyte:=memoria[direccion];
$6000..$ffff:if m6809_0.opcode then rocnrope_getbyte:=mem_opcodes[direccion-$6000]
else rocnrope_getbyte:=memoria[direccion];
end;
end;
procedure rocnrope_putbyte(direccion:word;valor:byte);
begin
case direccion of
$4000..$47ff,$5000..$5fff:memoria[direccion]:=valor;
$4800..$4fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$6000..$807f,$8190..$ffff:; //ROM
$8080:main_screen.flip_main_screen:=(valor and 1)=0;
$8081:if valor<>0 then konamisnd_0.pedir_irq:=HOLD_LINE;
$8087:begin
irq_ena:=(valor and $1)<>0;
if not(irq_ena) then m6809_0.change_irq(CLEAR_LINE);
end;
$8100:konamisnd_0.sound_latch:=valor;
$8182..$818d:memoria[$fff2+(direccion-$8182)]:=valor;
end;
end;
//Main
procedure reset_rocnrope;
begin
m6809_0.reset;
konamisnd_0.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
irq_ena:=false;
end;
function iniciar_rocnrope:boolean;
var
colores:tpaleta;
bit0,bit1,bit2:byte;
f:word;
memoria_temp:array[0..$ffff] of byte;
rweights,gweights,bweights:array[0..3] of single;
const
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8);
resistances_rg:array[0..2] of integer=(1000,470,220);
resistances_b:array [0..1] of integer=(470,220);
begin
llamadas_maquina.bucle_general:=rocnrope_principal;
llamadas_maquina.reset:=reset_rocnrope;
iniciar_rocnrope:=false;
iniciar_audio(false);
screen_init(1,256,256);
screen_init(2,256,256,false,true);
iniciar_video(224,256);
//Main CPU
m6809_0:=cpu_m6809.Create(18432000 div 3 div 4,$100,TCPU_M6809);
m6809_0.change_ram_calls(rocnrope_getbyte,rocnrope_putbyte);
//Sound Chip
konamisnd_0:=konamisnd_chip.create(4,TIPO_TIMEPLT,1789772,$100);
if not(roms_load(@konamisnd_0.memoria,rocnrope_snd)) then exit;
//cargar roms y desencriptarlas
if not(roms_load(@memoria,rocnrope_rom)) then exit;
konami1_decode(@memoria[$6000],@mem_opcodes[0],$a000);
mem_opcodes[$703d-$6000]:=$98; //Patch
//convertir chars
if not(roms_load(@memoria_temp,rocnrope_chars)) then exit;
init_gfx(0,8,8,512);
gfx_set_desc_data(4,0,16*8,$2000*8+4,$2000*8+0,4,0);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,true);
//sprites
if not(roms_load(@memoria_temp,rocnrope_sprites)) then exit;
init_gfx(1,16,16,256);
gfx_set_desc_data(4,0,64*8,$4000*8+4,$4000*8+0,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,true);
//paleta
if not(roms_load(@memoria_temp,rocnrope_pal)) then exit;
compute_resistor_weights(0, 255, -1.0,
3,@resistances_rg,@rweights,1000,0,
3,@resistances_rg,@gweights,1000,0,
2,@resistances_b,@bweights,1000,0);
for f:=0 to $1f do begin
// red component
bit0:=(memoria_temp[f] shr 0) and $01;
bit1:=(memoria_temp[f] shr 1) and $01;
bit2:=(memoria_temp[f] shr 2) and $01;
colores[f].r:=combine_3_weights(@rweights, bit0, bit1, bit2);
// green component
bit0:=(memoria_temp[f] shr 3) and $01;
bit1:=(memoria_temp[f] shr 4) and $01;
bit2:=(memoria_temp[f] shr 5) and $01;
colores[f].g:=combine_3_weights(@gweights, bit0, bit1, bit2);
// blue component
bit0:=(memoria_temp[f] shr 6) and $01;
bit1:=(memoria_temp[f] shr 7) and $01;
colores[f].b:=combine_2_weights(@bweights, bit0, bit1);
end;
set_pal(colores,$20);
for f:=0 to $1ff do begin
gfx[0].colores[f]:=memoria_temp[$20+f] and $f; //chars
gfx[1].colores[f]:=memoria_temp[$20+f] and $f; //sprites
end;
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$5b;
marcade.dswc:=$96;
marcade.dswa_val:=@rocnrope_dip_a;
marcade.dswb_val:=@rocnrope_dip_b;
marcade.dswc_val:=@rocnrope_dip_c;
//final
reset_rocnrope;
iniciar_rocnrope:=true;
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_Matrix3x3
* Implements a 3x3 matrix
***********************************************************************************************************************
}
Unit TERRA_Matrix3x3;
{$I terra.inc}
Interface
Uses TERRA_Vector2D, TERRA_Vector3D, TERRA_Matrix4x4;
Type
PMatrix3x3 = ^Matrix3x3;
Matrix3x3=Packed {$IFDEF USE_OLD_OBJECTS}Object{$ELSE}Record{$ENDIF}
V:Array [0..8] Of Single;
Function Transform(Const P:Vector2D):Vector2D; Overload;
Function Transform(Const P:Vector3D):Vector3D; Overload;
Procedure Init(Const M:Matrix4x4);
End;
Const
MatrixIdentity3x3:Matrix3x3= (V:(1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0));
// Returns a rotation matrix
Function MatrixRotation2D(Const Angle:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixRotationAndScale2D(Const Angle, ScaleX, ScaleY:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixTransformAroundPoint2D(Const Center:Vector2D; Const Mat:Matrix3x3):Matrix3x3;
// Returns a translation matrix
Function MatrixTranslation2D(Const Translation:Vector2D):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixTranslation2D(Const X,Y:Single):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixScale2D(Const Scale:Vector2D):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixScale2D(Const X,Y:Single):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixScale2D(Const Scale:Single):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Function MatrixInverse2D(Const Mat:Matrix3x3):Matrix3x3;
Function MatrixSkew2D(TX, TY:Single):Matrix3x3;
// Multiplys two matrices
Function MatrixMultiply3x3(Const A,B:Matrix3x3):Matrix3x3;
Implementation
Uses Math{$IFDEF NEON_FPU},TERRA_NEON{$ENDIF};
Function Matrix3x3.Transform(Const P:Vector2D):Vector2D;
Begin
Result.X := P.X * V[0] + P.Y * V[1] + V[2];
Result.Y := P.X * V[3] + P.Y * V[4] + V[5];
End;
Procedure Matrix3x3.Init(Const M: Matrix4x4);
Begin
V[0] := M.V[0];
V[1] := M.V[1];
V[2] := M.V[2];
V[3] := M.V[4];
V[4] := M.V[5];
V[5] := M.V[6];
V[6] := M.V[8];
V[7] := M.V[9];
V[8] := M.V[10];
End;
Function Matrix3x3.Transform(Const P:Vector3D):Vector3D;
Begin
Result.X := P.X * V[0] + P.Y * V[1] + V[2];
Result.Y := P.X * V[3] + P.Y * V[4] + V[5];
Result.Z := P.Z;
End;
{
0 1 2
3 4 5
6 7 8
}
//http://www.cg.info.hiroshima-cu.ac.jp/~miyazaki/knowledge/teche23.html
Function MatrixInverse2D(Const Mat:Matrix3x3):Matrix3x3;
Var
InvDet, Det:Double;
Begin
Det := Mat.V[0] * Mat.V[4] * Mat.V[8]+
Mat.V[3] * Mat.V[7] * Mat.V[2] +
Mat.V[6] * Mat.V[1] * Mat.V[5] -
Mat.V[0] * Mat.V[7] * Mat.V[5] -
Mat.V[6] * Mat.V[4] * Mat.V[2] -
Mat.V[3] * Mat.V[1] * Mat.V[8];
InvDet := 1.0 / Det;
Result.V[0] := ((Mat.V[4] * Mat.V[8]) - (Mat.V[5] * Mat.V[7])) * InvDet;
Result.V[1] := ((Mat.V[2] * Mat.V[7]) - (Mat.V[1] * Mat.V[8])) * InvDet;
Result.V[2] := ((Mat.V[1] * Mat.V[5]) - (Mat.V[2] * Mat.V[4])) * InvDet;
Result.V[3] := ((Mat.V[5] * Mat.V[6]) - (Mat.V[3] * Mat.V[8])) * InvDet;
Result.V[4] := ((Mat.V[0] * Mat.V[8]) - (Mat.V[2] * Mat.V[6])) * InvDet;
Result.V[5] := ((Mat.V[2] * Mat.V[3]) - (Mat.V[0] * Mat.V[5])) * InvDet;
Result.V[6] := ((Mat.V[3] * Mat.V[7]) - (Mat.V[4] * Mat.V[6])) * InvDet;
Result.V[7] := ((Mat.V[1] * Mat.V[6]) - (Mat.V[0] * Mat.V[7])) * InvDet;
Result.V[8] := ((Mat.V[0] * Mat.V[4]) - (Mat.V[1] * Mat.V[3])) * InvDet;
End;
Function MatrixRotation2D(Const Angle:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Var
S,C:Single;
Begin
C := Cos(Angle);
S := Sin(Angle);
Result.V[0] := C;
Result.V[1] := S;
Result.V[2] := 0.0;
Result.V[3] := -S;
Result.V[4] := C;
Result.V[5] := 0.0;
Result.V[6] := 0.0;
Result.V[7] := 0.0;
Result.V[8] := 1.0;
End;
Function MatrixRotationAndScale2D(Const Angle, ScaleX, ScaleY:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Var
S,C:Single;
Begin
C := Cos(Angle);
S := Sin(Angle);
Result.V[0] := C * ScaleX;
Result.V[1] := S * ScaleX;
Result.V[2] := 0.0;
Result.V[3] := -S * ScaleY;
Result.V[4] := C * ScaleY;
Result.V[5] := 0.0;
Result.V[6] := 0.0;
Result.V[7] := 0.0;
Result.V[8] := 1.0;
End;
Function MatrixTransformAroundPoint2D(Const Center:Vector2D; Const Mat:Matrix3x3):Matrix3x3;
Var
A,B:Matrix3x3;
Begin
A := MatrixTranslation2D(-Center.X, -Center.Y);
B := MatrixTranslation2D(Center);
Result := MatrixMultiply3x3(A, MatrixMultiply3x3(Mat, B));
End;
Function MatrixTranslation2D(Const Translation:Vector2D):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Begin
Result := MatrixTranslation2D(Translation.X,Translation.Y);
End;
Function MatrixTranslation2D(Const X,Y:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Begin
Result.V[0] := 1.0;
Result.V[1] := 0.0;
Result.V[2] := X;
Result.V[3] := 0.0;
Result.V[4] := 1.0;
Result.V[5] := Y;
Result.V[6] := 0.0;
Result.V[7] := 0.0;
Result.V[8] := 1.0;
End;
Function MatrixScale2D(Const Scale:Vector2D):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Begin
Result := MatrixScale2D(Scale.X, Scale.Y);
End;
Function MatrixScale2D(Const Scale:Single):Matrix3x3;Overload; {$IFDEF FPC}Inline;{$ENDIF}
Begin
Result := MatrixScale2D(Scale, Scale);
End;
Function MatrixScale2D(Const X,Y:Single):Matrix3x3; {$IFDEF FPC}Inline;{$ENDIF}
Begin
Result.V[0] := X;
Result.V[1] := 0.0;
Result.V[2] := 0.0;
Result.V[3] := 0.0;
Result.V[4] := Y;
Result.V[5] := 0.0;
Result.V[6] := 0.0;
Result.V[7] := 0.0;
Result.V[8] := 1.0;
End;
{
0 1 2
3 4 5
6 7 8
}
Function MatrixMultiply3x3(Const A,B:Matrix3x3):Matrix3x3;
Begin
{$IFDEF NEON_FPU}
matmul3_neon(@A,@B,@Result);
{$ELSE}
Result.V[0] := A.V[0]*B.V[0] + A.V[3]*B.V[1] + A.V[6]*B.V[2];
Result.V[1] := A.V[1]*B.V[0] + A.V[4]*B.V[1] + A.V[7]*B.V[2];
Result.V[2] := A.V[2]*B.V[0] + A.V[5]*B.V[1] + A.V[8]*B.V[2];
Result.V[3] := A.V[0]*B.V[3] + A.V[3]*B.V[4] + A.V[6]*B.V[5];
Result.V[4] := A.V[1]*B.V[3] + A.V[4]*B.V[4] + A.V[7]*B.V[5];
Result.V[5] := A.V[2]*B.V[3] + A.V[5]*B.V[4] + A.V[8]*B.V[5];
Result.V[6] := A.V[0]*B.V[6] + A.V[3]*B.V[7] + A.V[6]*B.V[8];
Result.V[7] := A.V[1]*B.V[6] + A.V[4]*B.V[7] + A.V[7]*B.V[8];
Result.V[8] := A.V[2]*B.V[6] + A.V[5]*B.V[7] + A.V[8]*B.V[8];
{$ENDIF}
End;
Function MatrixSkew2D(TX, TY:Single):Matrix3x3;
Begin
If (TX<>0) Then
TX := Tan(TX);
If (TY<>0) Then
TY := Tan(TY);
Result.V[0] := 1.0;
Result.V[1] := TX;
Result.V[2] := 0.0;
Result.V[3] := TY;
Result.V[4] := 1.0;
Result.V[5] := 0.0;
Result.V[6] := 0.0;
Result.V[7] := 0.0;
Result.V[8] := 1.0;
End;
End.
|
unit nsTagString;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "f1DocumentTagsImplementation"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/f1DocumentTagsImplementation/nsTagString.pas"
// Начат: 2005/06/23 16:38:20
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::f1DocumentTagsImplementation::TagDataProviders::TnsTagString
//
// Строка, представляющая строковый атрибут тега
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
nsString
;
type
TnsTagString = class(TnsNewString)
{* Строка, представляющая строковый атрибут тега }
public
// overridden public methods
function Clone(anOwner: TObject = nil): Pointer; override;
{* Создайт копию строки. }
end;//TnsTagString
implementation
uses
l3_String
;
// start class TnsTagString
function TnsTagString.Clone(anOwner: TObject = nil): Pointer;
//#UC START# *47BC3FC40111_467FCA0F01C6_var*
//#UC END# *47BC3FC40111_467FCA0F01C6_var*
begin
//#UC START# *47BC3FC40111_467FCA0F01C6_impl*
Result := Tl3_String.Create;
Tl3_String(Result).AssignString(Self);
//#UC END# *47BC3FC40111_467FCA0F01C6_impl*
end;//TnsTagString.Clone
end. |
unit glr_ogl;
interface
type
TGLConst = (
// Boolean
GL_FALSE = 0, GL_TRUE,
// AttribMask
GL_DEPTH_BUFFER_BIT = $0100, GL_STENCIL_BUFFER_BIT = $0400, GL_COLOR_BUFFER_BIT = $4000,
// Begin Mode
GL_POINTS = 0, GL_LINES, GL_LINE_LOOP, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_POLYGON,
// Alpha Function
GL_NEVER = $0200, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS,
// Blending Factor
GL_ZERO = 0, GL_ONE, GL_SRC_COLOR = $0300, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_DST_COLOR = $0306, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA_SATURATE,
// DrawBuffer Mode
GL_NONE = 0, GL_FRONT = $0404, GL_BACK, GL_FRONT_AND_BACK = $0408,
// Pixel params
GL_UNPACK_ALIGNMENT = $0CF5,
// Tests
GL_DEPTH_TEST = $0B71, GL_STENCIL_TEST = $0B90, GL_ALPHA_TEST = $0BC0, GL_SCISSOR_TEST = $0C11,
// GetTarget
GL_CULL_FACE = $0B44, GL_BLEND = $0BE2,
// Data Types
GL_BYTE = $1400, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, GL_HALF_FLOAT = $140B, GL_UNSIGNED_SHORT_5_6_5 = $8363, GL_UNSIGNED_SHORT_4_4_4_4_REV = $8365, GL_UNSIGNED_SHORT_1_5_5_5_REV,
// Matrix Mode
GL_MODELVIEW = $1700, GL_PROJECTION, GL_TEXTURE,
// Pixel Format
GL_DEPTH_COMPONENT = $1902, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_LUMINANCE_ALPHA,
GL_DEPTH_COMPONENT16 = $81A5, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32, GL_ALPHA8 = $803C, GL_LUMINANCE8 = $8040,
GL_LUMINANCE8_ALPHA8 = $8045, GL_RGB8 = $8051, GL_RGBA8 = $8058, GL_BGR = $80E0, GL_BGRA, GL_RGB5 = $8050,
GL_RGBA4 = $8056, GL_RGB5_A1 = $8057, GL_RG = $8227, GL_R16F = $822D, GL_R32F, GL_RG16F, GL_RG32F, GL_RGBA32F = $8814,
GL_RGBA16F = $881A,
GL_LUMINANCE16 = $8042,
GL_LUMINANCE16_ALPHA16 = $8048,
GL_RGB16 = $8054,
GL_RGBA16 = $805B,
// PolygonMode
GL_POINT = $1B00, GL_LINE, GL_FILL,
// Smooth
GL_POINT_SMOOTH = $0B10, GL_LINE_SMOOTH = $0B20, GL_POLYGON_SMOOTH = $0B41,
// List mode
GL_COMPILE = $1300, GL_COMPILE_AND_EXECUTE,
// Lighting
GL_LIGHTING = $0B50, GL_LIGHT0 = $4000, GL_AMBIENT = $1200, GL_DIFFUSE, GL_SPECULAR, GL_POSITION, GL_SPOT_DIRECTION, GL_SPOT_EXPONENT, GL_SPOT_CUTOFF, GL_CONSTANT_ATTENUATION, GL_LINEAR_ATTENUATION, GL_QUADRATIC_ATTENUATION,
// StencilOp
GL_KEEP = $1E00, GL_REPLACE, GL_INCR, GL_DECR,
// GetString Parameter
GL_VENDOR = $1F00, GL_RENDERER, GL_VERSION, GL_EXTENSIONS, GL_SHADING_LANGUAGE_VERSION = $8B8C,
// TextureEnvParameter
GL_TEXTURE_ENV_MODE = $2200, GL_TEXTURE_ENV_COLOR,
// TextureEnvTarget
GL_TEXTURE_ENV = $2300,
// Texture Filter
GL_NEAREST = $2600, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST = $2700, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_TEXTURE_MAG_FILTER = $2800, GL_TEXTURE_MIN_FILTER,
// Texture Wrap Mode
GL_TEXTURE_WRAP_S = $2802, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_R = $8072,
GL_CLAMP = $2900, GL_REPEAT = $2901, GL_CLAMP_TO_EDGE = $812F, GL_CLAMP_TO_BORDER = $812D, GL_MIRRORED_REPEAT = $8370,
GL_TEXTURE_BASE_LEVEL = $813C, GL_TEXTURE_MAX_LEVEL,
// Textures
GL_TEXTURE_1D = $0DE0, GL_TEXTURE_2D = $0DE1, GL_TEXTURE_3D = $806F, GL_TEXTURE0 = $84C0, GL_TEXTURE_MAX_ANISOTROPY = $84FE, GL_MAX_TEXTURE_MAX_ANISOTROPY, GL_GENERATE_MIPMAP = $8191,
GL_TEXTURE_CUBE_MAP = $8513, GL_TEXTURE_CUBE_MAP_POSITIVE_X = $8515, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
// Compressed Textures
GL_COMPRESSED_RGB_S3TC_DXT1 = $83F0, GL_COMPRESSED_RGBA_S3TC_DXT1, GL_COMPRESSED_RGBA_S3TC_DXT3, GL_COMPRESSED_RGBA_S3TC_DXT5,
// FBO
GL_FRAMEBUFFER = $8D40, GL_RENDERBUFFER, GL_COLOR_ATTACHMENT0 = $8CE0, GL_DEPTH_ATTACHMENT = $8D00, GL_FRAMEBUFFER_BINDING = $8CA6, GL_FRAMEBUFFER_COMPLETE = $8CD5,
// Shaders
GL_FRAGMENT_SHADER = $8B30, GL_VERTEX_SHADER, GL_GEOMETRY_SHADER = $8DD9, GL_GEOMETRY_VERTICES_OUT = $8DDA, GL_GEOMETRY_INPUT_TYPE, GL_GEOMETRY_OUTPUT_TYPE, GL_MAX_GEOMETRY_OUTPUT_VERTICES = $8DE0, GL_COMPILE_STATUS = $8B81, GL_LINK_STATUS, GL_VALIDATE_STATUS, GL_INFO_LOG_LENGTH,
// VBO
GL_VERTEX_ARRAY = $8074, GL_NORMAL_ARRAY, GL_COLOR_ARRAY, GL_INDEX_ARRAY_EXT, GL_TEXTURE_COORD_ARRAY,
GL_ARRAY_BUFFER = $8892, GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY = $88B8, GL_WRITE_ONLY = $88B9, GL_READ_WRITE = $88BA,
GL_STREAM_DRAW = $88E0, GL_STREAM_READ, GL_STREAM_COPY,
GL_STATIC_DRAW = $88E4, GL_STATIC_READ, GL_STATIC_COPY,
GL_DYNAMIC_DRAW = $88E8, GL_DYNAMIC_READ, GL_DYNAMIC_COPY,
// Queries
GL_SAMPLES_PASSED = $8914, GL_QUERY_COUNTER_BITS = $8864, GL_CURRENT_QUERY, GL_QUERY_RESULT, GL_QUERY_RESULT_AVAILABLE,
//GL_MAX_CONST = High(LongInt),
GL_COLOR = $1800,
GL_POINT_SPRITE = $8861,
GL_COORD_REPLACE = $8862,
GL_POINT_DISTANCE_ATTENUATION = $8129,
GL_POINT_SIZE_MIN = $8126,
GL_POINT_SIZE_MAX = $8127,
GL_POINT_FADE_THRESHOLD_SIZE = $8128,
//GL_MODULATE = $2100, GL_DECAL = $2101, GL_ADD = $0104,
GL_MULTISAMPLE = $809D
//wgl Choose pixel format
// WGL_DRAW_TO_WINDOW_ARB = $2001,
// WGL_ACCELERATION_ARB = $2003,
// WGL_SUPPORT_OPENGL_ARB = $2010,
// WGL_DOUBLE_BUFFER_ARB = $2011,
// WGL_COLOR_BITS_ARB = $2014,
// WGL_ALPHA_BITS_ARB = $201B,
// WGL_DEPTH_BITS_ARB = $2022,
// WGL_STENCIL_BITS_ARB = $2023,
// WGL_FULL_ACCELERATION_ARB = $2027,
// WGL_SAMPLE_BUFFERS_ARB = $2041,
// WGL_SAMPLES_ARB = $2042
);
PGLConst = ^TGLConst;
{ TglrGL }
TglrGL = record
private
Lib : LongWord;
public
{$IFDEF WINDOWS}
GetProc : function (ProcName: PAnsiChar): Pointer; stdcall;
SwapInterval : function (Interval: LongInt): LongInt; stdcall;
ChoosePixelFormat: function(DC: LongWord; const piAttribIList: PInteger; const pfAttribFList: PSingle;
nMaxFormats: Cardinal; piFormats: PInteger; nNumFormats: PCardinal) : LongBool; stdcall;
{$ENDIF}
GetIntegerv : procedure (pname: TGLConst; params: Pointer); stdcall;
GetFloatv : procedure (pname: TGLConst; params: Pointer); stdcall;
GetString : function (name: TGLConst): PAnsiChar; stdcall;
GetError : function (): LongWord; stdcall;
Flush : procedure;
Finish : procedure;
PixelStorei : procedure (pname: TGLConst; param: LongInt); stdcall;
GenTextures : procedure (n: LongInt; textures: Pointer); stdcall;
DeleteTextures : procedure (n: LongInt; textures: Pointer); stdcall;
BindTexture : procedure (target: TGLConst; texture: LongWord); stdcall;
TexParameteri : procedure (target, pname: TGLConst; param: LongInt); stdcall;
TexParameterf : procedure (target, pname: TGLConst; param: Single);
TexImage2D : procedure (target: TGLConst; level: LongInt; internalformat: TGLConst; width, height, border: LongInt; format, _type: TGLConst; data: Pointer); stdcall;
TexSubImage2D : procedure (target: TGLConst; level, x, y, width, height: LongInt; format, _type: TGLConst; data: Pointer); stdcall;
GetTexImage : procedure (target: TGLConst; level: LongInt; format, _type: TGLConst; data: Pointer); stdcall;
GenerateMipmap : procedure (target: TGLConst); stdcall;
CopyTexSubImage2D : procedure (target: TGLConst; level, xoffset, yoffset, x, y, width, height: LongInt); stdcall;
CompressedTexImage2D : procedure (target: TGLConst; level: LongInt; internalformat: TGLConst; width, height, border, imageSize: LongInt; data: Pointer); stdcall;
ActiveTexture : procedure (texture: LongWord); stdcall;
ClientActiveTexture : procedure (texture: TGLConst); stdcall;
Clear : procedure (mask: TGLConst); stdcall;
ClearColor : procedure (red, green, blue, alpha: Single); stdcall;
ColorMask : procedure (red, green, blue, alpha: Boolean); stdcall;
DepthMask : procedure (flag: Boolean); stdcall;
StencilMask : procedure (mask: LongWord); stdcall;
Enable : procedure (cap: TGLConst); stdcall;
Disable : procedure (cap: TGLConst); stdcall;
CullFace : procedure (mode: TGLConst); stdcall;
PolygonMode : procedure (face, mode: TGLConst); stdcall;
AlphaFunc : procedure (func: TGLConst; factor: Single); stdcall;
BlendFunc : procedure (sfactor, dfactor: TGLConst); stdcall;
StencilFunc : procedure (func: TGLConst; ref: LongInt; mask: LongWord); stdcall;
DepthFunc : procedure (func: TGLConst); stdcall;
StencilOp : procedure (fail, zfail, zpass: TGLConst); stdcall;
Viewport : procedure (x, y, width, height: LongInt); stdcall;
Scissor : procedure (x, y, width, height: LongInt); stdcall;
PointSize : procedure (size: Single); stdcall;
DrawElements : procedure (mode: TGLConst; count: LongInt; _type: TGLConst; const indices: Pointer); stdcall;
Ortho : procedure (left, right, bottom, top, zNear, zFar: Double); stdcall;
Frustum : procedure (left, right, bottom, top, zNear, zFar: Double); stdcall;
ReadPixels : procedure (x, y, width, height: LongInt; format, _type: TGLConst; pixels: Pointer); stdcall;
DrawBuffer : procedure (mode: TGLConst); stdcall;
ReadBuffer : procedure (mode: TGLConst); stdcall;
// VBO
GenBuffers : procedure (n: LongInt; buffers: Pointer); stdcall;
DeleteBuffers : procedure (n: LongInt; const buffers: Pointer); stdcall;
BindBuffer : procedure (target: TGLConst; buffer: LongWord); stdcall;
BufferData : procedure (target: TGLConst; size: LongInt; const data: Pointer; usage: TGLConst); stdcall;
BufferSubData : procedure (target: TGLConst; offset, size: LongInt; const data: Pointer); stdcall;
MapBuffer : function (target, access: TGLConst): Pointer; stdcall;
UnmapBuffer : function (target: TGLConst): Boolean; stdcall;
// GLSL Shaders
GetProgramiv : procedure (_program: LongWord; pname: TGLConst; params: Pointer); stdcall;
CreateProgram : function: LongWord;
DeleteProgram : procedure (_program: LongWord); stdcall;
LinkProgram : procedure (_program: LongWord); stdcall;
ValidateProgram : procedure (_program: LongWord); stdcall;
UseProgram : procedure (_program: LongWord); stdcall;
GetProgramInfoLog : procedure (_program: LongWord; maxLength: LongInt; var length: LongInt; infoLog: PAnsiChar); stdcall;
GetShaderiv : procedure (_shader: LongWord; pname: TGLConst; params: Pointer); stdcall;
CreateShader : function (shaderType: TGLConst): LongWord; stdcall;
DeleteShader : procedure (_shader: LongWord); stdcall;
ShaderSource : procedure (_shader: LongWord; count: LongInt; src: Pointer; len: Pointer); stdcall;
AttachShader : procedure (_program, _shader: LongWord); stdcall;
CompileShader : procedure (_shader: LongWord); stdcall;
GetShaderInfoLog : procedure (_shader: LongWord; maxLength: LongInt; var length: LongInt; infoLog: PAnsiChar); stdcall;
GetUniformLocation : function (_program: LongWord; const ch: PAnsiChar): LongInt; stdcall;
Uniform1iv : procedure (location, count: LongInt; value: Pointer); stdcall;
Uniform1fv : procedure (location, count: LongInt; value: Pointer); stdcall;
Uniform2fv : procedure (location, count: LongInt; value: Pointer); stdcall;
Uniform3fv : procedure (location, count: LongInt; value: Pointer); stdcall;
Uniform4fv : procedure (location, count: LongInt; value: Pointer); stdcall;
UniformMatrix3fv : procedure (location, count: LongInt; transpose: Boolean; value: Pointer); stdcall;
UniformMatrix4fv : procedure (location, count: LongInt; transpose: Boolean; value: Pointer); stdcall;
GetAttribLocation : function (_program: LongWord; const ch: PAnsiChar): LongInt; stdcall;
EnableVertexAttribArray : procedure (index: LongWord); stdcall;
DisableVertexAttribArray : procedure (index: LongWord); stdcall;
VertexAttribPointer : procedure (index: LongWord; size: LongInt; _type: TGLConst; normalized: Boolean; stride: LongInt; const ptr: Pointer); stdcall;
BindAttribLocation : procedure (_program: LongWord; index: LongWord; const name: PAnsiChar); stdcall;
// FBO
DrawBuffers : procedure (n: LongInt; bufs: Pointer); stdcall;
GenFramebuffers : procedure (n: LongInt; framebuffers: Pointer); stdcall;
DeleteFramebuffers : procedure (n: LongInt; framebuffers: Pointer); stdcall;
BindFramebuffer : procedure (target: TGLConst; framebuffer: LongWord); stdcall;
FramebufferTexture2D : procedure (target, attachment, textarget: TGLConst; texture: LongWord; level: LongInt); stdcall;
FramebufferRenderbuffer : procedure (target, attachment, renderbuffertarget: TGLConst; renderbuffer: LongWord); stdcall;
CheckFramebufferStatus : function (target: TGLConst): TGLConst; stdcall;
GenRenderbuffers : procedure (n: LongInt; renderbuffers: Pointer); stdcall;
DeleteRenderbuffers : procedure (n: LongInt; renderbuffers: Pointer); stdcall;
BindRenderbuffer : procedure (target: TGLConst; renderbuffer: LongWord); stdcall;
RenderbufferStorage : procedure (target, internalformat: TGLConst; width, height: LongInt); stdcall;
// Multisample
SampleCoverage : procedure (value: Single; invert: Boolean); stdcall;
PointParameterfv : procedure (pname: TGLConst; const params: Pointer); stdcall;
PointParameterf : procedure (pname: TGLConst; param: Single); stdcall;
TexEnvf : procedure (target, pname: TGLConst; param: Single); stdcall;
TexEnvi : procedure (target, pname: TGLConst; param: TGLConst); stdcall;
procedure Init;
procedure Free;
function IsExtensionSupported(const Extension: String): Boolean;
end;
var
gl: TglrGL;
implementation
uses
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
glr_utils;
procedure TglrGL.Init;
type
TProcArray = array [-1..(SizeOf(TglrGL) - SizeOf(Lib)) div 4 - 1] of Pointer;
const
ProcName : array [0..(SizeOf(TglrGL) - SizeOf(Lib)) div 4 - 1] of PAnsiChar = (
{$IFDEF WINDOWS}
'wglGetProcAddress',
'wglSwapIntervalEXT',
'wglChoosePixelFormatARB',
{$ENDIF}
'glGetIntegerv',
'glGetFloatv',
'glGetString',
'glGetError',
'glFlush',
'glFinish',
'glPixelStorei',
'glGenTextures',
'glDeleteTextures',
'glBindTexture',
'glTexParameteri',
'glTexParameterf',
'glTexImage2D',
'glTexSubImage2D',
'glGetTexImage',
'glGenerateMipmapEXT',
'glCopyTexSubImage2D',
'glCompressedTexImage2DARB',
'glActiveTextureARB',
'glClientActiveTextureARB',
'glClear',
'glClearColor',
'glColorMask',
'glDepthMask',
'glStencilMask',
'glEnable',
'glDisable',
'glCullFace',
'glPolygonMode',
'glAlphaFunc',
'glBlendFunc',
'glStencilFunc',
'glDepthFunc',
'glStencilOp',
'glViewport',
'glScissor',
'glPointSize',
'glDrawElements',
'glOrtho',
'glFrustum',
'glReadPixels',
'glDrawBuffer',
'glReadBuffer',
'glGenBuffers',
'glDeleteBuffers',
'glBindBuffer',
'glBufferData',
'glBufferSubData',
'glMapBuffer',
'glUnmapBuffer',
'glGetProgramiv',
'glCreateProgram',
'glDeleteProgram',
'glLinkProgram',
'glValidateProgram',
'glUseProgram',
'glGetProgramInfoLog',
'glGetShaderiv',
'glCreateShader',
'glDeleteShader',
'glShaderSource',
'glAttachShader',
'glCompileShader',
'glGetShaderInfoLog',
'glGetUniformLocation',
'glUniform1iv',
'glUniform1fv',
'glUniform2fv',
'glUniform3fv',
'glUniform4fv',
'glUniformMatrix3fv',
'glUniformMatrix4fv',
'glGetAttribLocation',
'glEnableVertexAttribArray',
'glDisableVertexAttribArray',
'glVertexAttribPointer',
'glBindAttribLocation',
'glDrawBuffers',
'glGenFramebuffersEXT',
'glDeleteFramebuffersEXT',
'glBindFramebufferEXT',
'glFramebufferTexture2DEXT',
'glFramebufferRenderbufferEXT',
'glCheckFramebufferStatusEXT',
'glGenRenderbuffersEXT',
'glDeleteRenderbuffersEXT',
'glBindRenderbufferEXT',
'glRenderbufferStorageEXT',
'glSampleCoverage',
'glPointParameterfv',
'glPointParameterf',
'glTexEnvf',
'glTexEnvi'
);
var
i : LongInt;
Proc : ^TProcArray;
begin
{$IFDEF WINDOWS}
Lib := LoadLibraryA(opengl32);
{$ELSE}
{$ENDIF}
if Lib <> 0 then
begin
Proc := @Self;
{$IFDEF WINDOWS}
Proc^[0] := GetProcAddress(Lib, ProcName[0]); // gl.GetProc
{$ENDIF}
for i := 1 to High(ProcName) do
begin
Proc^[i] := GetProc(ProcName[i]);
if Proc^[i] = nil then
Proc^[i] := GetProcAddress(Lib, ProcName[i]);
if Proc^[i] = nil then
Log.Write(lWarning, 'Pointer for "' + ProcName[i] + '" is nil');
end;
end;
Set8087CW($133F); //Предотвращает EInvalidOp при 1/0, 0/0, -1/0
end;
function TglrGL.IsExtensionSupported(const Extension: String): Boolean;
var
extensions: PAnsiChar;
begin
extensions := gl.GetString(TGLConst.GL_EXTENSIONS);
Result := Pos(Extension, extensions) <> 0;
end;
procedure TglrGL.Free;
begin
{$IFDEF WINDOWS}
FreeLibrary(Lib);
{$ENDIF}
end;
end.
|
unit CleanArch_EmbrConf.Core.Entity.Interfaces;
interface
type
iParkingLot = interface
function Code(Value : String) : iParkingLot; overload;
function Code : String; overload;
function Capacity(Value : Integer) : iParkingLot; overload;
function Capacity : Integer; overload;
function OpenHour(Value : Integer) : iParkingLot; overload;
function OpenHour : Integer; overload;
function CloseHour(Value : Integer) : iParkingLot; overload;
function CloseHour : Integer; overload;
function OccupiedSpaces(Value : Integer) : iParkingLot; overload;
function OccupiedSpaces : Integer; overload;
function isOpen(Data : String) : Boolean;
function isFull : Boolean;
end;
iParkedCar = interface
function Code(Value : String) : iParkedCar; overload;
function Code : String; overload;
function Plate(Value : String) : iParkedCar; overload;
function Plate : String; overload;
function Data(Value : String) : iParkedCar; overload;
function Data : String; overload;
end;
implementation
end.
|
{ Module of wrapper routines that make various forms of common expressions.
}
module sst_exp_make;
define sst_exp_make_var;
%include 'sst2.ins.pas';
{
******************************************
}
function sst_exp_make_var ( {make expression that references a variable}
in sym: sst_symbol_t) {symbol of variable to make expression from}
:sst_exp_p_t; {returned pointer to new expression}
var
var_p: sst_var_p_t; {scratch pointer to variable descriptor}
exp_p: sst_exp_p_t; {pointer to returned expression}
begin
{
* Create variable descriptor for reference to SYM.
}
sst_mem_alloc_scope (sizeof(var_p^), var_p); {allocate mem for var descriptor}
var_p^.mod1.next_p := nil;
var_p^.mod1.modtyp := sst_var_modtyp_top_k;
var_p^.mod1.top_str_h.first_char := sym.char_h;
var_p^.mod1.top_str_h.last_char := sym.char_h;
var_p^.mod1.top_sym_p := addr(sym);
var_p^.dtype_p := sym.var_dtype_p;
if sym.var_arg_p = nil
then begin {variable is not a dummy argument}
var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
end
else begin {variable is a dummy argument}
var_p^.rwflag := sym.var_arg_p^.rwflag_int;
end
;
var_p^.vtype := sst_vtype_var_k;
{
* Create expression descriptor.
}
sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {allocate mem for exp descriptor}
exp_p^.term1.next_p := nil;
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.term1.op1 := sst_op1_none_k;
exp_p^.term1.ttype := sst_term_var_k;
exp_p^.term1.str_h := var_p^.mod1.top_str_h;
exp_p^.term1.dtype_p := var_p^.dtype_p;
exp_p^.term1.dtype_hard := true;
exp_p^.term1.val_eval := false;
exp_p^.term1.val_fnd := false;
exp_p^.term1.rwflag := var_p^.rwflag;
exp_p^.term1.var_var_p := var_p;
exp_p^.str_h := exp_p^.term1.str_h;
exp_p^.dtype_p := exp_p^.term1.dtype_p;
exp_p^.dtype_hard := exp_p^.term1.dtype_hard;
exp_p^.val_eval := false;
exp_p^.val_fnd := false;
exp_p^.rwflag := exp_p^.term1.rwflag;
sst_exp_eval (exp_p^, false); {evaluate expression}
sst_exp_make_var := exp_p; {pass back expression pointer}
end;
|
unit Filters;
interface
uses
Classes, ColorTableMgr, GDI;
type
TPaletteFilter = (pfReddenPalette, pfTintPalette, pfColorToGray, pfRedFilter, pfGreenFilter, pfDarkenPalette);
function FilterPalette(OrgPalette : TPaletteInfo; Filter : TPaletteFilter; Data : array of const) : TPaletteInfo;
function CheckParams(Filter : TPaletteFilter; OldParams, NewParams : array of const) : boolean;
implementation
uses
Windows;
type
TFilterRoutine = function (Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
TCheckParamsRoutine = function (OldParams, NewParams : array of const) : boolean;
type
TFilterInfo =
record
FilterRoutine : TFilterRoutine;
CheckParamsRoutine : TCheckParamsRoutine;
end;
function ReddenPalette(Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
var
ReddedPalette : PRGBPalette;
i : integer;
begin
getmem(ReddedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(ReddedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
ReddedPalette[i].rgbRed := $FF;
ReddedPalette[i].rgbGreen := Palette.RGBPalette[i].rgbGreen;
ReddedPalette[i].rgbBlue := Palette.RGBPalette[i].rgbBlue;
end;
Result := ReddedPalette;
end;
function CheckReddenPaletteParams(OldParams, NewParams : array of const) : boolean;
begin
Result := true;
end;
function TintPalette(Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
var
TintedPalette : PRGBPalette;
i : integer;
red, green, blue : byte;
tintweight : extended;
begin
red := Data[0].VInteger;
green := Data[1].VInteger;
blue := Data[2].VInteger;
tintweight := Data[3].VExtended^;
getmem(TintedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(TintedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
TintedPalette[i].rgbRed := round(Palette.RGBPalette[i].rgbRed*(1 - tintweight) + red*tintweight);
TintedPalette[i].rgbGreen := round(Palette.RGBPalette[i].rgbGreen*(1 - tintweight) + green*tintweight);
TintedPalette[i].rgbBlue := round(Palette.RGBPalette[i].rgbBlue*(1 - tintweight) + blue*tintweight);
end;
Result := TintedPalette;
end;
function CheckTintPaletteParams(OldParams, NewParams : array of const) : boolean;
var
oldred, oldgreen, oldblue : byte;
oldtintweight : extended;
newred, newgreen, newblue : byte;
newtintweight : extended;
begin
if high(OldParams) = high(NewParams)
then
begin
oldred := OldParams[0].VInteger;
oldgreen := OldParams[1].VInteger;
oldblue := OldParams[2].VInteger;
oldtintweight := OldParams[3].VExtended^;
newred := NewParams[0].VInteger;
newgreen := NewParams[1].VInteger;
newblue := NewParams[2].VInteger;
newtintweight := NewParams[3].VExtended^;
Result := (oldred = newred) and (oldgreen = newgreen) and (oldblue = newblue) and (oldtintweight = newtintweight);
end
else Result := false;
end;
function ColorToGray(Palette : TPaletteInfo; Data : array of const) : PRGBPalette;
var
GrayPalette : PRGBPalette;
i : integer;
gray : integer;
begin
getmem(GrayPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(GrayPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
gray := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
GrayPalette[i].rgbRed := gray;
GrayPalette[i].rgbGreen := gray;
GrayPalette[i].rgbBlue := gray;
end;
Result := GrayPalette;
end;
function CheckColorToGrayParams(OldParams, NewParams : array of const) : boolean;
begin
Result := true;
end;
function RedFilter(Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
var
RedPalette : PRGBPalette;
i : integer;
begin
getmem(RedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(RedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
RedPalette[i].rgbRed := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
RedPalette[i].rgbGreen := 0;
RedPalette[i].rgbBlue := 0;
end;
Result := RedPalette;
end;
function CheckRedFilterParams(OldParams, NewParams : array of const) : boolean;
begin
Result := true;
end;
function GreenFilter(Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
var
GreenPalette : PRGBPalette;
i : integer;
begin
getmem(GreenPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(GreenPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
GreenPalette[i].rgbRed := 0;
GreenPalette[i].rgbGreen := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
GreenPalette[i].rgbBlue := 0;
end;
Result := GreenPalette;
end;
function CheckGreenFilterParams(OldParams, NewParams : array of const) : boolean;
begin
Result := true;
end;
function DarkenPalette(Palette : TPaletteInfo; Data : array of const) : PRgbPalette;
var
DarkenedPalette : PRGBPalette;
i : integer;
begin
getmem(DarkenedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(DarkenedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
DarkenedPalette[i].rgbRed := Palette.RGBPalette[i].rgbRed div 2;
DarkenedPalette[i].rgbGreen := Palette.RGBPalette[i].rgbGreen div 2;
DarkenedPalette[i].rgbBlue := Palette.RGBPalette[i].rgbBlue div 2;
end;
Result := DarkenedPalette;
end;
function CheckDarkenPaletteParams(OldParams, NewParams : array of const) : boolean;
begin
Result := true;
end;
const
AvailableFilters : array[TPaletteFilter] of TFilterInfo =
(
(FilterRoutine : ReddenPalette; CheckParamsRoutine : CheckReddenPaletteParams),
(FilterRoutine : TintPalette; CheckParamsRoutine : CheckTintPaletteParams),
(FilterRoutine : ColorToGray; CheckParamsRoutine : CheckColorToGrayParams),
(FilterRoutine : RedFilter; CheckParamsRoutine : CheckRedFilterParams),
(FilterRoutine : GreenFilter; CheckParamsRoutine : CheckGreenFilterParams),
(FilterRoutine : DarkenPalette; CheckParamsRoutine : CheckDarkenPaletteParams)
);
function FilterPalette(OrgPalette : TPaletteInfo; Filter : TPaletteFilter; Data : array of const) : TPaletteInfo;
begin
Result := OrgPalette.FilteredPalette(AvailableFilters[Filter].FilterRoutine, Data);
end;
function CheckParams(Filter : TPaletteFilter; OldParams, NewParams : array of const) : boolean;
begin
Result := AvailableFilters[Filter].CheckParamsRoutine(OldParams, NewParams);
end;
end.
|
unit XOPoint;
interface
type TXOPoint = class
public
X: integer;
Y: integer;
constructor Create(x:integer; y:integer);
end;
implementation
constructor TXOPoint.Create(x, y: integer);
begin
self.X := x;
self.Y := y;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.Functions;
interface
uses
System.Classes, System.JSON, System.SysUtils,
System.Net.HttpClient, System.Net.URLClient, System.Generics.Collections,
REST.Types,
FB4D.Interfaces, FB4D.Response, FB4D.Request;
type
TFirebaseFunctions = class(TInterfacedObject, IFirebaseFunctions)
private
fProjectID: string;
fServerRegion: string;
fAuth: IFirebaseAuthentication;
function BaseURL: string;
procedure OnResp(const RequestID: string; Response: IFirebaseResponse);
public
constructor Create(const ProjectID: string;
Auth: IFirebaseAuthentication = nil;
const ServerRegion: string = cRegionUSCent1);
procedure CallFunction(OnSuccess: TOnFunctionSuccess;
OnRequestError: TOnRequestError; const FunctionName: string;
Params: TJSONObject = nil);
function CallFunctionSynchronous(const FunctionName: string;
Params: TJSONObject = nil): TJSONObject;
end;
implementation
uses
FB4D.Helpers;
const
GOOGLE_CLOUD_FUNCTIONS_URL = 'https://%s-%s.cloudfunctions.net';
resourcestring
rsFunctionCall = 'Function call %s';
rsUnexpectedResult = 'Unexpected result of %s received: %s';
{ TFirestoreFunctions }
constructor TFirebaseFunctions.Create(const ProjectID: string;
Auth: IFirebaseAuthentication; const ServerRegion: string);
begin
inherited Create;
fProjectID := ProjectID;
fAuth := Auth;
fServerRegion := ServerRegion;
end;
function TFirebaseFunctions.BaseURL: string;
begin
result := Format(GOOGLE_CLOUD_FUNCTIONS_URL, [fServerRegion, fProjectID]);
end;
procedure TFirebaseFunctions.CallFunction(OnSuccess: TOnFunctionSuccess;
OnRequestError: TOnRequestError; const FunctionName: string;
Params: TJSONObject);
var
Request: IFirebaseRequest;
Data: TJSONObject;
begin
Data := TJSONObject.Create;
try
Data.AddPair('data', Params);
Request := TFirebaseRequest.Create(BaseURL,
Format(rsFunctionCall, [FunctionName]), fAuth);
Request.SendRequest([FunctionName], rmPost, Data, nil, tmBearer,
OnResp, OnRequestError, TOnSuccess.CreateFunctionSuccess(OnSuccess));
finally
Data.Free;
end;
end;
procedure TFirebaseFunctions.OnResp(const RequestID: string;
Response: IFirebaseResponse);
var
Msg: string;
ResultVal: TJSONValue;
Obj, ResultObj: TJSONObject;
begin
try
if not Response.StatusOk then
begin
Msg := Response.ErrorMsg;
if Msg.IsEmpty then
Msg := Response.StatusText;
if assigned(Response.OnError) then
Response.OnError(RequestID, Msg);
end else begin
Obj := Response.GetContentAsJSONObj;
try
if Obj.TryGetValue('result', ResultVal) and
assigned(Response.OnSuccess.OnFunctionSuccess) then
begin
if ResultVal is TJSONObject then
begin
ResultObj := ResultVal as TJSONObject;
Response.OnSuccess.OnFunctionSuccess(RequestID, ResultObj);
end
else if ResultVal is TJSONArray then
begin
ResultObj := TJSONObject.Create(
TJSONPair.Create('result', ResultVal as TJSONArray));
Response.OnSuccess.OnFunctionSuccess(RequestID, ResultObj);
end else begin
if assigned(Response.OnError) then
Response.OnError(RequestID, Format(rsUnexpectedResult,
[RequestID, Response.ContentAsString]));
end;
end
else if assigned(Response.OnError) then
Response.OnError(RequestID, Format(rsUnexpectedResult,
[RequestID, Response.ContentAsString]));
finally
Obj.Free;
end;
end;
except
on e: exception do
if assigned(Response.OnError) then
Response.OnError(RequestID, e.Message)
else
TFirebaseHelpers.Log('Exception in OnResponse: ' + e.Message);
end;
end;
function TFirebaseFunctions.CallFunctionSynchronous(const FunctionName: string;
Params: TJSONObject): TJSONObject;
var
Request: IFirebaseRequest;
Response: IFirebaseResponse;
Data: TJSONObject;
Obj: TJSONObject;
ResultVal: TJSONValue;
begin
Data := TJSONObject.Create;
try
Data.AddPair('data', Params);
Request := TFirebaseRequest.Create(BaseURL, '', fAuth);
Response := Request.SendRequestSynchronous([FunctionName], rmPost, Data,
nil, tmBearer);
Response.CheckForJSONObj;
Obj := Response.GetContentAsJSONObj;
try
if not Obj.TryGetValue('result', ResultVal) then
raise EFirebaseFunctions.CreateFmt(rsUnexpectedResult,
[FunctionName, Obj.ToJSON])
else if ResultVal is TJSONObject then
result := ResultVal.Clone as TJSONObject
else if ResultVal is TJSONArray then
result := TJSONObject.Create(
TJSONPair.Create('result', ResultVal.Clone as TJSONArray))
else
raise EFirebaseFunctions.CreateFmt(rsUnexpectedResult,
[FunctionName, Obj.ToJSON])
finally
Obj.Free;
end;
finally
Data.Free;
end;
end;
end.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, frxClass;
type
TForm2 = class(TForm)
frxReport1: TfrxReport;
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses
WinSpool, frxPrinter;
{$R *.dfm}
procedure WriteRawStringToPrinter(const aPrinterName, aDocument, aData: string);
var
h: THandle;
N: DWORD;
docInfo: TDocInfo1;
begin
if not OpenPrinter(PChar(aPrinterName), h, nil) then Assert(false);
try
with docInfo do
begin
pDocName := PChar(aDocument);
pOutputFile := nil;
pDataType := 'RAW';
end;
if StartDocPrinter(h, 1, @docInfo) = 0 then Assert(false);
if not StartPagePrinter(h) then Assert(false);
if not WritePrinter(h, PAnsiChar(AnsiString(aData)), Length(AnsiString(aData)), N) then Assert(false);
if not EndPagePrinter(h) then Assert(false);
if not EndDocPrinter(h) then Assert(false);
finally
ClosePrinter(h);
end;
end;
procedure TForm2.Button1Click(Sender: TObject);
var
i,j: Integer;
page: TfrxPage;
c: TfrxComponent;
fm: TfrxMemoView;
x,y,w,h: Double;
begin
frxReport1.PrepareReport();
if frxPrinters.Printers.Count <= 0 then
frxPrinters.FillPrinters;
//frxPrinters.PrinterIndex := frxPrinters.IndexOf('FinePrint');
Memo1.Clear;
Memo1.Lines.Add('^XA');
for i := 0 to frxReport1.PagesCount-1 do
begin
page := frxReport1.Pages[i];
if page.BaseName <> 'Page' then Continue;
for j := 0 to page.Objects.Count - 1 do
begin
c := TObject(page.Objects[j]) as TfrxComponent;
if c is TfrxMemoView then
begin
fm := (c as TfrxMemoView);
x := fm.Left; //is in pixels
y := fm.Top;
//recalc from FR dpi (96dpi) to e.g. 200dpi of Zebra printer
x := (x * frxPrinters.Printer.DPI.X) / 96;
y := (y * frxPrinters.Printer.DPI.Y) / 96;
//12 points = 12/72 logical inch = 1/6 logical inch = 96/6 pixels = 16 pixels
//http://msdn.microsoft.com/en-us/library/windows/desktop/ff684173(v=vs.85).aspx
h := Round( Abs(fm.Font.Height) * frxPrinters.Printer.DPI.Y / 72 );
w := h * (12/15); //default scale of font width vs height?
//http://www.zebra.com/id/zebra/na/en/documentlibrary/manuals/en/zpl_ii_programming2.File.tmp/45541L-002_RA.pdf
Memo1.Lines.Add(
Format('^FO%0.0f,%0.0f^A0N,%0.0f,%0.0f^FD%s^FS',
[x, y, w, h, fm.Text]) );
end
end;
end;
Memo1.Lines.Add('^XZ');
frxReport1.Print;
//preview generated code with zplviewer
// http://sourceforge.net/projects/zplviewer/
//or preview on printer:
// https://km.zebra.com/kb/index?page=content&id=SO8374
end;
end.
|
unit AceAlign;
{ ----------------------------------------------------------------
Ace Reporter
Copyright 1995,2004 SCT Associates, Inc.
Written by Kevin Maher, Steve Tyrakowski
---------------------------------------------------------------- }
interface
{$I ace.inc}
uses windows, SysUtils, Messages, Classes, Graphics, Controls,
StdCtrls, sctrep;
{-------------------------------------------------------------------
AlignType is the tag value assigned to the 4 alignment buttons
0: Left
1: Center
2: Right
3: Page Center
--------------------------------------------------------------------}
const NULLTARGET = -12345;
{$ifdef VCL140PLUS}
procedure AceAlignLabel(pg: TSctPage; AlignType: integer);
{$else}
type
TAceAlign = class(TObject)
private
FControls: TList;
protected
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddControl(Control: TControl);
procedure DeleteControl(Control: TControl);
procedure AlignLabels(pg: TSctPage; AlignType: integer);
end;
var
AceAlignLabels: TAceAlign;
{$endif}
implementation
uses Dialogs, Forms, sctctrl {$ifdef VCL140PLUS}, designintf{$endif};
{------------------------------------------------------------}
procedure MyAlign(pg: TSctPage; lb: TSctLabel; var Target: integer; AlignType: integer);
var
adj: integer;
begin
if (lb.Parent.Parent as TSctPage) = pg then
begin
adj := 0;
case AlignType of
0: adj := 0;
1: adj := lb.Width div 2;
2: adj := lb.Width;
3: adj := -lb.left;
end;
if (Target = NULLTARGET) then Target := lb.Left + adj;
lb.Left := Target - adj;
end;
end;
{------------------------------------------------------------}
procedure CalcMax(pg: TSctPage; lb: TSctLabel; var MaxLeft, MaxRight: integer);
begin
if (lb.Parent.Parent as TSctPage) = pg then
begin
if MaxLeft = NULLTARGET then
begin
MaxLeft := lb.Left;
MaxRight := lb.Left + lb.Width;
end;
if MaxLeft > lb.Left then
MaxLeft := lb.Left;
if MaxRight < lb.Left + lb.Width then
MaxRight := lb.Left + lb.Width;
end;
end;
{$ifdef VCL140PLUS}
{------------------------------------------------------------}
procedure AceAlignLabel(pg: TSctPage; AlignType: integer);
var
Center, MaxLeft, MaxRight, i, Target: integer;
MyList: IDesignerSelections;
begin
MyList := CreateSelectionList;
((pg.Owner as TForm).Designer as IDesigner).GetSelections(MyList);
if AlignType = 3 then
begin
Center := pg.PageWidth div 2;
MaxLeft := NULLTARGET;
MaxRight := 0;
for i := 0 to MyList.Count -1 do
if MyList.Items[i] is TSctLabel then
CalcMax(pg,(MyList.Items[i] as TSctLabel),MaxLeft,MaxRight);
Target := Center - (((MaxRight - MaxLeft) div 2) + MaxLeft);
end
else Target := NULLTARGET;
for i := 0 to MyList.Count - 1 do
if MyList.Items[i] is TSctLabel then
MyAlign(pg,(MyList.Items[i] as TSctLabel), Target, AlignType);
(pg.Owner as TForm).Designer.Modified;
end;
{$else}
{------------------------------------------------------------}
constructor TAceAlign.Create;
begin
FControls := TList.Create;
end;
{------------------------------------------------------------}
destructor TAceAlign.Destroy;
begin
if FControls <> nil then FControls.Free;
inherited Destroy;
end;
{------------------------------------------------------------}
procedure TAceAlign.AddControl(Control: TControl);
begin
FControls.Add(Control);
end;
{------------------------------------------------------------}
procedure TAceAlign.DeleteControl(Control: TControl);
begin
FControls.Remove(Control);
end;
{------------------------------------------------------------}
procedure ExitAceAlignUnit; far;
begin
if AceAlignLabels <> nil then AceAlignLabels.Free;
end;
{------------------------------------------------------------}
procedure TAceAlign.AlignLabels(pg: TSctPage; AlignType: integer);
var
Center, MaxLeft, MaxRight, i, Target: integer;
begin
if AlignType = 3 then
begin
Center := pg.PageWidth div 2;
MaxLeft := NULLTARGET;
MaxRight := 0;
for i := 0 to FControls.Count -1 do
CalcMax(pg,TSctLabel(FControls.Items[i]),MaxLeft,MaxRight);
Target := Center - (((MaxRight - MaxLeft) div 2) + MaxLeft);
end
else Target := NULLTARGET;
for i := 0 to FControls.Count - 1 do
MyAlign(pg,TSctLabel(FControls.Items[i]), Target, AlignType);
(pg.Owner as TForm).Designer.Modified;
end;
initialization
AceAlignLabels := TAceAlign.Create;
finalization
ExitAceAlignUnit;
{$ENDIF}
end.
|
unit Thread.AnaliseRoteiroExpressas;
interface
uses
System.Classes, System.SysUtils, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Control.PlanilhaEntradaDIRECT,
Control.RoteirosExpressas;
type
Thread_AnaliseRoteirosExpressas = class(TThread)
private
FPlanilha : TPlanilhaEntradaDIRECTControl;
FArquivo: String;
FProcesso: Boolean;
FLog: String;
FTotalRegistros: Integer;
FProgresso: Double;
FCancelar: Boolean;
FMemTab: TFDMemTable;
FMemTabEntregas: TFDMemTable;
FMemTabResumo: TFDMemTable;
FMensagemSistema: String;
FCliente: Integer;
procedure UpdateEntregas(i: integer);
procedure UpdateLOG(sMensagem: String);
{ Private declarations }
protected
procedure Execute; override;
public
property Arquivo: String read FArquivo write FArquivo;
property Processo: Boolean read FProcesso write FProcesso;
property Log: String read FLog write FLog;
property Progresso: Double read FProgresso write FProgresso;
property TotalRegistros: Integer read FTotalRegistros write FTotalRegistros;
property Cliente: Integer read FCliente write FCliente;
property Cancelar: Boolean read FCancelar write FCancelar;
property MemTabResumo: TFDMemTable read FMemTabResumo write FMemTabResumo;
property MemTabEntregas: TFDMemTable read FMemTabEntregas write FMemTabEntregas;
property MensagemSistema: String read FMensagemSistema write FMensagemSistema;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Thread_CapaDirect.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses Common.ENum;
{ Thread_AnaliseRoteirosExpressas }
procedure Thread_AnaliseRoteirosExpressas.Execute;
var
aParam : Array of variant;
iPos, i, iTipo: Integer;
sMensagem, sCodigoRoteiro, sNomeRoteiro, sFiltro: String;
FRoteiro : TRoteirosExpressasControl;
fdQuery : TFDQuery;
begin
{ Place thread code here }
try
FProcesso := True;
FCancelar := False;
FPlanilha := TPlanilhaEntradaDIRECTControl.Create;
FRoteiro := TRoteirosExpressasControl.Create;
if FPLanilha.GetPlanilha(FArquivo) then
begin
iPos := 0;
FTotalRegistros := FPlanilha.Planilha.Planilha.Count;
FProgresso := 0;
for i := 0 to Pred(FTotalRegistros) do
begin
sFiltro := 'num_cep_inicial = ' + QuotedStr(FPlanilha.Planilha.Planilha[i].CEP) + ' and cod_cliente = ' + FCliente.ToString;
if FPlanilha.Planilha.Planilha[i].PesoNominal > 30 then
sFiltro := sFiltro + ' and (cod_tipo = 2 or 3)'
else
sFiltro := sFiltro + ' and (cod_tipo = 1 or 3)';
SetLength(aParam,4);
aParam := ['FILTRO', sFiltro];
fdQuery := FRoteiro.Localizar(aParam);
if fdQuery.IsEmpty then
begin
UpdateEntregas(i);
fdQuery.Close;
end
else
begin
if FRoteiro.SetupModel(fdQuery) then
begin
fdQuery.Close;
sCodigoRoteiro := FRoteiro.Roteiros.CCEP5;
sNomeRoteiro := FRoteiro.Roteiros.Descricao;
if sCodigoRoteiro = '000' then
begin
UpdateEntregas(i);
end
else
begin
if MemTabResumo.Locate('cod_roteiro', sCodigoRoteiro,[]) then
begin
MemTabResumo.Edit;
if FPlanilha.Planilha.Planilha[i].PesoNominal <= 30 then
begin
MemTabResumo.FieldByName('qtd_volumes_leves').AsInteger := MemTabResumo.FieldByName('qtd_volumes_leves').AsInteger +
FPlanilha.Planilha.Planilha[i].Volumes;
MemTabResumo.FieldByName('qtd_remessas_leves').AsInteger:= MemTabResumo.FieldByName('qtd_remessas_leves').AsInteger + 1;
MemTabResumo.FieldByName('val_pgr_leves').AsFloat := MemTabResumo.FieldByName('val_pgr_leves').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
end
else
begin
MemTabResumo.FieldByName('qtd_volumes_pesado').AsInteger := MemTabResumo.FieldByName('qtd_volumes_pesado').AsInteger +
FPlanilha.Planilha.Planilha[i].Volumes;
MemTabResumo.FieldByName('qtd_remessas_pesado').AsInteger:= MemTabResumo.FieldByName('qtd_remessas_pesado').AsInteger + 1;
MemTabResumo.FieldByName('val_pgr_pesado').AsFloat := MemTabResumo.FieldByName('val_pgr_pesado').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
end;
MemTabResumo.FieldByName('val_total_pgr').AsFloat := MemTabResumo.FieldByName('val_total_pgr').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
MemTabResumo.Post;
end
else
begin
MemTabResumo.Insert;
MemTabResumo.FieldByName('cod_roteiro').AsString := sCodigoRoteiro;
MemTabResumo.FieldByName('des_roteiro').AsString := sNomeRoteiro;
if FPlanilha.Planilha.Planilha[i].PesoNominal <= 30 then
begin
MemTabResumo.FieldByName('qtd_volumes_leves').AsInteger := MemTabResumo.FieldByName('qtd_volumes_leves').AsInteger +
FPlanilha.Planilha.Planilha[i].Volumes + 0;
MemTabResumo.FieldByName('qtd_remessas_leves').AsInteger:= MemTabResumo.FieldByName('qtd_remessas_leves').AsInteger + 1;
MemTabResumo.FieldByName('val_pgr_leves').AsFloat := MemTabResumo.FieldByName('val_pgr_leves').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
end
else
begin
MemTabResumo.FieldByName('qtd_volumes_pesado').AsInteger := MemTabResumo.FieldByName('qtd_volumes_pesado').AsInteger +
FPlanilha.Planilha.Planilha[i].Volumes + 0;
MemTabResumo.FieldByName('qtd_remessas_pesado').AsInteger:= MemTabResumo.FieldByName('qtd_remessas_pesado').AsInteger + 1;
MemTabResumo.FieldByName('val_pgr_pesado').AsFloat := MemTabResumo.FieldByName('val_pgr_pesado').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
end;
MemTabResumo.FieldByName('val_total_pgr').AsFloat := MemTabResumo.FieldByName('val_total_pgr').AsFloat +
FPlanilha.Planilha.Planilha[i].Valor;
MemTabResumo.Post;
end;
end;
end;
end;
Finalize(aParam);
iPos := i;
FProgresso := (iPos / FTotalRegistros) * 100;
if Self.Terminated then Abort;
end;
fdQuery.Free;
FProcesso := False;
end
else
begin
UpdateLOG(FPlanilha.Planilha.Mensagem);
end;
Except on E: Exception do
begin
sMensagem := '** ERROR **' + 'Classe:' + E.ClassName + chr(13) + 'Mensagem:' + E.Message;
UpdateLOG(sMensagem);
FProcesso := False;
end;
end;
end;
procedure Thread_AnaliseRoteirosExpressas.UpdateEntregas(i: integer);
var
sTipo: String;
begin
MemTabEntregas.Insert;
MemTabEntregas.FieldByName('num_nossonumero').AsString := FPlanilha.Planilha.Planilha[i].Remessa;
MemTabEntregas.FieldByName('num_nf').AsString := FPlanilha.Planilha.Planilha[i].NF;
MemTabEntregas.FieldByName('nom_consumidor').AsString := FPlanilha.Planilha.Planilha[i].NomeConsumidor;
MemTabEntregas.FieldByName('des_bairro').AsString := FPlanilha.Planilha.Planilha[i].Bairro;
MemTabEntregas.FieldByName('nom_cidade').AsString := FPlanilha.Planilha.Planilha[i].Municipio;
MemTabEntregas.FieldByName('num_cep').AsString := FPlanilha.Planilha.Planilha[i].CEP;
MemTabEntregas.FieldByName('qtd_peso_real').AsFloat := FPlanilha.Planilha.Planilha[i].PesoNominal;
MemTabEntregas.FieldByName('qtd_peso_franquia').AsFloat := 0;
MemTabEntregas.FieldByName('qtd_peso_cobrado').AsFloat := FPlanilha.Planilha.Planilha[i].PesoCubado;
if FPlanilha.Planilha.Planilha[i].PesoNominal <= 30 then
sTipo := 'LEVE'
else
sTipo := 'PESADO';
MemTabEntregas.FieldByName('des_tipo_peso').AsString := sTipo;
MemTabEntregas.FieldByName('val_produto').AsFloat := FPlanilha.Planilha.Planilha[i].Valor;
MemTabEntregas.FieldByName('qtd_altura').AsInteger := 0;
MemTabEntregas.FieldByName('qtd_largura').AsInteger := 0;
MemTabEntregas.FieldByName('qtd_comprimento').AsInteger := 0;
MemTabEntregas.FieldByName('qtd_volumes').AsInteger := FPlanilha.Planilha.Planilha[i].Volumes;
MemTabEntregas.FieldByName('num_pedido').AsString := FPlanilha.Planilha.Planilha[i].Pedido;
MemTabEntregas.Post;
end;
procedure Thread_AnaliseRoteirosExpressas.UpdateLOG(sMensagem: String);
begin
FMensagemSistema := sMensagem;
end;
end.
|
unit uClienteModuloVO;
interface
uses System.SysUtils, uProdutoVO, uModuloVO, uKeyField, uTableName;
type
[TableName('Cliente_Modulo')]
TClienteModuloVO = class
private
FProduto: TProduto;
FId: Integer;
FModulo: TModuloVO;
FIdCliente: Integer;
FIdModulo: Integer;
FIdProduto: Integer;
procedure SetModulo(const Value: TModuloVO);
procedure SetIdCliente(const Value: Integer);
public
[KeyField('CliMod_Id')]
property Id: Integer read FId write FId;
[FieldNull('CliMod_Modulo')]
property IdModulo: Integer read FIdModulo write FIdModulo;
[FieldNull('CliMod_Produto')]
property IdProduto: Integer read FIdProduto write FIdProduto;
[FieldNull('CliMod_Cliente')]
property IdCliente: Integer read FIdCliente write SetIdCliente;
property Produto: TProduto read FProduto write FProduto;
property Modulo: TModuloVO read FModulo write SetModulo;
constructor Create();
destructor Destroy; override;
end;
implementation
{ TClienteModulo }
constructor TClienteModuloVO.Create;
begin
FProduto := TProduto.Create;
FModulo := TModuloVO.Create;
end;
destructor TClienteModuloVO.Destroy;
begin
FreeAndNil(FProduto);
FreeAndNil(FModulo);
inherited;
end;
procedure TClienteModuloVO.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TClienteModuloVO.SetModulo(const Value: TModuloVO);
begin
FModulo := Value;
end;
end.
|
unit ErrorResponseUnit;
interface
uses
REST.Json.Types, SysUtils,
JSONNullableAttributeUnit,
CommonTypesUnit;
type
/// <summary>
/// Errors data-structure
/// </summary>
TErrorResponse = class
private
[JSONName('errors')]
FErrors: TStringArray;
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create;
destructor Destroy; override;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// Errors
/// </summary>
property Errors: TStringArray read FErrors write FErrors;
end;
implementation
{ TErrorResponse }
uses UtilsUnit;
constructor TErrorResponse.Create;
begin
Inherited;
SetLength(FErrors, 0);
end;
destructor TErrorResponse.Destroy;
begin
Finalize(FErrors);
inherited;
end;
function TErrorResponse.Equals(Obj: TObject): Boolean;
var
Other: TErrorResponse;
SortedErrors1, SortedErrors2: TStringArray;
i: integer;
begin
Result := False;
if not (Obj is TErrorResponse) then
Exit;
Other := TErrorResponse(Obj);
if (Length(FErrors) = Length(Other.FErrors)) then
begin
SortedErrors1 := TUtils.SortStringArray(FErrors);
SortedErrors2 := TUtils.SortStringArray(Other.FErrors);
for i := 0 to Length(SortedErrors1) - 1 do
if not SortedErrors1[i].Equals(SortedErrors2[i]) then
Exit;
end;
Result := True;
end;
end.
|
unit wwfsuperstars_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,ym_2151,rom_engine,
pal_engine,sound_engine,oki6295;
function iniciar_wwfsstar:boolean;
implementation
const
wwfsstar_rom:array[0..1] of tipo_roms=(
(n:'24ac-0_j-1.34';l:$20000;p:0;crc:$ec8fd2c9),(n:'24ad-0_j-1.35';l:$20000;p:$1;crc:$54e614e4));
wwfsstar_sound:tipo_roms=(n:'24ab-0.12';l:$8000;p:0;crc:$1e44f8aa);
wwfsstar_oki:array[0..1] of tipo_roms=(
(n:'24a9-0.46';l:$20000;p:0;crc:$703ff08f),(n:'24j8-0.45';l:$20000;p:$20000;crc:$61138487));
wwfsstar_char:tipo_roms=(n:'24aa-0_j.58';l:$20000;p:0;crc:$b9201b36);
wwfsstar_sprites:array[0..5] of tipo_roms=(
(n:'c951.114';l:$80000;p:0;crc:$fa76d1f0),(n:'24j4-0.115';l:$40000;p:$80000;crc:$c4a589a3),
(n:'24j5-0.116';l:$40000;p:$0c0000;crc:$d6bca436),(n:'c950.117';l:$80000;p:$100000;crc:$cca5703d),
(n:'24j2-0.118';l:$40000;p:$180000;crc:$dc1b7600),(n:'24j3-0.119';l:$40000;p:$1c0000;crc:$3ba12d43));
wwfsstar_bg:array[0..1] of tipo_roms=(
(n:'24j7-0.113';l:$40000;p:0;crc:$e0a1909e),(n:'24j6-0.112';l:$40000;p:$40000;crc:$77932ef8));
//DIP
wwfsstar_dip_a:array [0..3] of def_dip=(
(mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
wwfsstar_dip_b:array [0..5] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$2;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$4;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Super Techniques';number:2;dip:((dip_val:$8;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Time';number:4;dip:((dip_val:$20;dip_name:'+2:30'),(dip_val:$30;dip_name:'Default'),(dip_val:$10;dip_name:'-2:30'),(dip_val:$0;dip_name:'-5:00'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Health for Winning';number:2;dip:((dip_val:$80;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
scroll_x,scroll_y:word;
rom:array[0..$1ffff] of word;
fg_ram,bg_ram:array[0..$7ff] of word;
ram:array[0..$1fff] of word;
sound_latch:byte;
procedure update_video_wwfsstar;
var
f,x,y,nchar,pos,atrib,atrib2:word;
a,color:byte;
flipx,flipy:boolean;
begin
//background
for f:=$0 to $3ff do begin
x:=f and $1f;
y:=f shr 5;
pos:=(x and $0f)+((y and $0f) shl 4)+((x and $10) shl 4)+((y and $10) shl 5);
atrib:=(bg_ram[pos*2] and $ff) shr 4;
color:=atrib and $7;
if (gfx[1].buffer[pos] or buffer_color[color+$10]) then begin
nchar:=(bg_ram[(pos*2)+1] and $ff) or ((bg_ram[pos*2] and $f) shl 8);
put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+256,3,1,(atrib and $8)<>0,false);
gfx[1].buffer[pos]:=false;
end;
//text
color:=(fg_ram[f*2] and $ff) shr 4;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
nchar:=(fg_ram[(f*2)+1] and $ff) or ((fg_ram[f*2] and $f) shl 8);
put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0);
gfx[0].buffer[f]:=false;
end;
end;
scroll_x_y(3,2,scroll_x,scroll_y);
//Sprites
for f:=0 to $65 do begin
atrib:=buffer_sprites_w[(f*5)+1];
if (atrib and 1)<>0 then begin
y:=(buffer_sprites_w[f*5] and $00ff) or ((atrib and $0004) shl 6);
y:=(((256-y) and $1ff)-32);
x:=(buffer_sprites_w[(f*5)+4] and $00ff) or ((atrib and $0008) shl 5);
x:=(((256-x) and $1ff)-16);
atrib2:=buffer_sprites_w[(f*5)+2];
flipx:=(atrib2 and $0080)<>0;
flipy:=(atrib2 and $0040)<>0;
nchar:=(buffer_sprites_w[(f*5)+3] and $00ff) or ((atrib2 and $003f) shl 8);
color:=atrib and $00f0;
if (atrib and $0002)<>0 then begin //16x32
nchar:=nchar and $3ffe;
if flipy then a:=16
else a:=0;
put_gfx_sprite_diff(nchar,color+128,flipx,flipy,2,0,a);
put_gfx_sprite_diff(nchar+1,color+128,flipx,flipy,2,0,a xor 16);
actualiza_gfx_sprite_size(x,y,2,16,32);
end else begin //16x16
put_gfx_sprite(nchar,color+128,flipx,flipy,2);
actualiza_gfx_sprite(x,y+16,2,2);
end;
end;
end;
actualiza_trozo(0,0,256,256,1,0,0,256,256,2);
actualiza_trozo_final(0,8,256,240,2);
fillchar(buffer_color[0],MAX_COLOR_BUFFER,0);
end;
procedure eventos_wwfsstar;
begin
if event.arcade then begin
//p1
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.down[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);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
//p2
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.down[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);
if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80);
//system
if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
end;
end;
procedure wwfsstar_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 271 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
case f of
15,31,47,63,79,95,111,127,143,159,175,191,207,223,255:m68000_0.irq[5]:=ASSERT_LINE;
239:begin
m68000_0.irq[5]:=ASSERT_LINE;
m68000_0.irq[6]:=ASSERT_LINE;
update_video_wwfsstar;
marcade.in2:=marcade.in2 or 1;
end;
271:marcade.in2:=marcade.in2 and $fe;
end;
end;
eventos_wwfsstar;
video_sync;
end;
end;
function wwfsstar_getword(direccion:dword):word;
begin
case direccion of
0..$3ffff:wwfsstar_getword:=rom[direccion shr 1];
$080000..$080fff:wwfsstar_getword:=fg_ram[(direccion and $fff) shr 1];
$0c0000..$0c0fff:wwfsstar_getword:=bg_ram[(direccion and $fff) shr 1];
$100000..$1003ff:wwfsstar_getword:=buffer_sprites_w[(direccion and $3ff) shr 1];
$180000..$180001:wwfsstar_getword:=marcade.dswa;
$180002..$180003:wwfsstar_getword:=marcade.dswb;
$180004..$180005:wwfsstar_getword:=marcade.in0;
$180006..$180007:wwfsstar_getword:=marcade.in1;
$180008..$180009:wwfsstar_getword:=marcade.in2;
$1c0000..$1c3fff:wwfsstar_getword:=ram[(direccion and $3fff) shr 1];
end;
end;
procedure wwfsstar_putword(direccion:dword;valor:word);
procedure cambiar_color(pos,data:word);
var
color:tcolor;
begin
color.b:=pal4bit(data shr 8);
color.g:=pal4bit(data shr 4);
color.r:=pal4bit(data);
set_pal_color(color,pos);
case pos of
$000..$0ff:buffer_color[pos shr 4]:=true;
$100..$1ff:buffer_color[((pos shr 4) and $7)+$10]:=true;
end;
end;
begin
case direccion of
0..$3ffff:;
$80000..$80fff:if fg_ram[(direccion and $fff) shr 1]<>valor then begin
fg_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 2]:=true;
end;
$c0000..$c0fff:if bg_ram[(direccion and $fff) shr 1]<>valor then begin
bg_ram[(direccion and $fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $fff) shr 2]:=true;
end;
$100000..$1003ff:buffer_sprites_w[(direccion and $3ff) shr 1]:=valor;
$140000..$140fff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin
buffer_paleta[(direccion and $fff) shr 1]:=valor;
cambiar_color((direccion and $fff) shr 1,valor);
end;
$180000:m68000_0.irq[6]:=CLEAR_LINE;
$180002:m68000_0.irq[5]:=CLEAR_LINE;
$180004:scroll_x:=valor and $1ff;
$180006:scroll_y:=valor and $1ff;
$180008:begin
z80_0.change_nmi(PULSE_LINE);
sound_latch:=valor and $ff;
end;
$18000a:main_screen.flip_main_screen:=(valor and 1)<>0;
$1c0000..$1c3fff:ram[(direccion and $3fff) shr 1]:=valor;
end;
end;
function wwfsstar_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff:wwfsstar_snd_getbyte:=mem_snd[direccion];
$8801:wwfsstar_snd_getbyte:=ym2151_0.status;
$9800:wwfsstar_snd_getbyte:=oki_6295_0.read;
$a000:wwfsstar_snd_getbyte:=sound_latch;
end;
end;
procedure wwfsstar_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:;
$8000..$87ff:mem_snd[direccion]:=valor;
$8800:ym2151_0.reg(valor);
$8801:ym2151_0.write(valor);
$9800:oki_6295_0.write(valor);
end;
end;
procedure ym2151_snd_irq(irqstate:byte);
begin
z80_0.change_irq(irqstate);
end;
procedure wwfsstar_sound_update;
begin
ym2151_0.update;
oki_6295_0.update;
end;
//Main
procedure reset_wwfsstar;
begin
m68000_0.reset;
z80_0.reset;
ym2151_0.reset;
oki_6295_0.reset;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$fe;
scroll_x:=0;
scroll_y:=0;
sound_latch:=0;
end;
function iniciar_wwfsstar:boolean;
var
memoria_temp:pbyte;
const
pc_x:array[0..7] of dword=(1, 0, 8*8+1, 8*8+0, 16*8+1, 16*8+0, 24*8+1, 24*8+0);
ps_x:array[0..15] of dword=(3, 2, 1, 0, 16*8+3, 16*8+2, 16*8+1, 16*8+0,
32*8+3, 32*8+2, 32*8+1, 32*8+0, 48*8+3, 48*8+2, 48*8+1, 48*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,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8);
begin
llamadas_maquina.bucle_general:=wwfsstar_principal;
llamadas_maquina.reset:=reset_wwfsstar;
llamadas_maquina.fps_max:=57.444853;
iniciar_wwfsstar:=false;
iniciar_audio(false);
screen_init(1,256,256,true);
screen_init(2,512,512,false,true);
screen_init(3,512,512);
screen_mod_scroll(3,512,256,511,512,256,511);
iniciar_video(256,240);
//Main CPU
m68000_0:=cpu_m68000.create(10000000,272);
m68000_0.change_ram16_calls(wwfsstar_getword,wwfsstar_putword);
//Sound CPU
z80_0:=cpu_z80.create(3579545,272);
z80_0.change_ram_calls(wwfsstar_snd_getbyte,wwfsstar_snd_putbyte);
z80_0.init_sound(wwfsstar_sound_update);
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
ym2151_0.change_irq_func(ym2151_snd_irq);
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH);
//Cargar ADPCM ROMS
if not(roms_load(oki_6295_0.get_rom_addr,wwfsstar_oki)) then exit;
//cargar roms
if not(roms_load16w(@rom,wwfsstar_rom)) then exit;
//cargar sonido
if not(roms_load(@mem_snd,wwfsstar_sound)) then exit;
getmem(memoria_temp,$200000);
//convertir chars
if not(roms_load(memoria_temp,wwfsstar_char)) then exit;
init_gfx(0,8,8,$1000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,32*8,0,2,4,6);
convert_gfx(0,0,memoria_temp,@pc_x,@ps_y,false,false);
//convertir background
if not(roms_load(memoria_temp,wwfsstar_bg)) then exit;
init_gfx(1,16,16,$1000);
gfx_set_desc_data(4,0,64*8,$40000*8+0,$40000*8+4,0,4);
convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false);
//convertir sprites
if not(roms_load(memoria_temp,wwfsstar_sprites)) then exit;
init_gfx(2,16,16,$4000);
gfx[2].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,$100000*8+0,$100000*8+4,0,4);
convert_gfx(2,0,memoria_temp,@ps_x,@ps_y,false,false);
//DIP
marcade.dswa:=$ff;
marcade.dswa_val:=@wwfsstar_dip_a;
marcade.dswb:=$ff;
marcade.dswb_val:=@wwfsstar_dip_b;
//final
freemem(memoria_temp);
reset_wwfsstar;
iniciar_wwfsstar:=true;
end;
end.
|
unit ConfigValueResponseUnit;
interface
uses
REST.Json.Types,
NullableBasicTypesUnit, GenericParametersUnit, JSONNullableAttributeUnit;
type
TConfigValueResponse = class(TGenericParameters)
private
[JSONName('result')]
[Nullable]
FResult: NullableString;
[JSONName('affected')]
[Nullable]
FAffected: NullableInteger;
public
property Result: NullableString read FResult;
property Affected: NullableInteger read FAffected;
end;
implementation
end.
|
unit RESTRequest4D.Request.Response;
interface
uses RESTRequest4D.Request.Response.Intf, REST.Client, System.SysUtils, System.JSON;
type
TRequestResponse = class(TInterfacedObject, IRequestResponse)
private
FRESTResponse: TRESTResponse;
function GetContent: string;
function GetContentLength: Cardinal;
function GetContentType: string;
function GetContentEncoding: string;
function GetStatusCode: Integer;
function GetRawBytes: TBytes;
function GetJSONValue: TJSONValue;
public
constructor Create(const ARESTResponse: TRESTResponse);
end;
implementation
{ TRequestResponse }
constructor TRequestResponse.Create(const ARESTResponse: TRESTResponse);
begin
FRESTResponse := ARESTResponse;
end;
function TRequestResponse.GetContent: string;
begin
Result := FRESTResponse.Content;
end;
function TRequestResponse.GetContentEncoding: string;
begin
Result := FRESTResponse.ContentEncoding;
end;
function TRequestResponse.GetContentLength: Cardinal;
begin
Result := FRESTResponse.ContentLength;
end;
function TRequestResponse.GetContentType: string;
begin
Result := FRESTResponse.ContentType;
end;
function TRequestResponse.GetJSONValue: TJSONValue;
begin
Result := FRESTResponse.JSONValue;
end;
function TRequestResponse.GetRawBytes: TBytes;
begin
Result := FRESTResponse.RawBytes;
end;
function TRequestResponse.GetStatusCode: Integer;
begin
Result := FRESTResponse.StatusCode;
end;
end.
|
unit DialogFrm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit, FMX.Objects;
type
TfrmDialog = class(TForm)
DialogLayout: TLayout;
FaderRectangle: TRectangle;
CenterLayout: TPanel;
Edit1: TEdit;
CheckBox1: TCheckBox;
ButtonsLayout: TPanel;
CancelButton: TButton;
OKButton: TButton;
procedure OKButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
FResultMethod: TProc<TModalResult>;
procedure CloseDialog(const AResult: TModalResult);
public
procedure ShowDialog(const AResultMethod: TProc<TModalResult> = nil);
end;
var
frmDialog: TfrmDialog;
implementation
{$R *.fmx}
uses
FMX.Ani;
{ TfrmDialog }
procedure TfrmDialog.ShowDialog(const AResultMethod: TProc<TModalResult> = nil);
begin
// A fader is used to convey to the user that the controls under it are not accessible
FaderRectangle.Opacity := 0;
FResultMethod := AResultMethod;
// Instead of showing the whole form, DialogLayout is just parented to the active form..
DialogLayout.Parent := Screen.ActiveForm;
// ..then the fader is "faded in"
TAnimator.AnimateFloat(FaderRectangle, 'Opacity', 0.3);
end;
procedure TfrmDialog.CloseDialog(const AResult: TModalResult);
begin
// The result method is called if one was passed in..
if Assigned(FResultMethod) then
FResultMethod(AResult);
// ..and the DialogLayout is "unparented"
DialogLayout.Parent := nil;
end;
procedure TfrmDialog.OKButtonClick(Sender: TObject);
begin
CloseDialog(mrOk);
end;
procedure TfrmDialog.CancelButtonClick(Sender: TObject);
begin
CloseDialog(mrCancel);
end;
end.
|
unit TextLoadKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы TextLoad }
// Модуль: "w:\common\components\gui\Garant\Daily\Forms\TextLoadKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "TextLoadKeywordsPack" MUID: (C4540386893A)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, evEditor
, evTextSource
, evLoadDocumentManager
;
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TextLoad_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_TextLoad = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы TextLoad
----
*Пример использования*:
[code]
'aControl' форма::TextLoad TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_TextLoad
Tkw_TextLoad_Control_Text = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола Text
----
*Пример использования*:
[code]
контрол::Text TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TextLoad_Control_Text
Tkw_TextLoad_Control_Text_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола Text
----
*Пример использования*:
[code]
контрол::Text:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TextLoad_Control_Text_Push
Tkw_TextLoad_Component_TextSource = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола TextSource
----
*Пример использования*:
[code]
компонент::TextSource TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TextLoad_Component_TextSource
Tkw_TextLoad_Component_LoadManager = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола LoadManager
----
*Пример использования*:
[code]
компонент::LoadManager TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TextLoad_Component_LoadManager
TkwTextLoadFormText = {final} class(TtfwPropertyLike)
{* Слово скрипта .TTextLoadForm.Text }
private
function Text(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevEditor;
{* Реализация слова скрипта .TTextLoadForm.Text }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwTextLoadFormText
TkwTextLoadFormTextSource = {final} class(TtfwPropertyLike)
{* Слово скрипта .TTextLoadForm.TextSource }
private
function TextSource(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevTextSource;
{* Реализация слова скрипта .TTextLoadForm.TextSource }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwTextLoadFormTextSource
TkwTextLoadFormLoadManager = {final} class(TtfwPropertyLike)
{* Слово скрипта .TTextLoadForm.LoadManager }
private
function LoadManager(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevLoadDocumentManager;
{* Реализация слова скрипта .TTextLoadForm.LoadManager }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwTextLoadFormLoadManager
function Tkw_Form_TextLoad.GetString: AnsiString;
begin
Result := 'TextLoadForm';
end;//Tkw_Form_TextLoad.GetString
class function Tkw_Form_TextLoad.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::TextLoad';
end;//Tkw_Form_TextLoad.GetWordNameForRegister
function Tkw_TextLoad_Control_Text.GetString: AnsiString;
begin
Result := 'Text';
end;//Tkw_TextLoad_Control_Text.GetString
class procedure Tkw_TextLoad_Control_Text.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TevEditor);
end;//Tkw_TextLoad_Control_Text.RegisterInEngine
class function Tkw_TextLoad_Control_Text.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Text';
end;//Tkw_TextLoad_Control_Text.GetWordNameForRegister
procedure Tkw_TextLoad_Control_Text_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('Text');
inherited;
end;//Tkw_TextLoad_Control_Text_Push.DoDoIt
class function Tkw_TextLoad_Control_Text_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Text:push';
end;//Tkw_TextLoad_Control_Text_Push.GetWordNameForRegister
function Tkw_TextLoad_Component_TextSource.GetString: AnsiString;
begin
Result := 'TextSource';
end;//Tkw_TextLoad_Component_TextSource.GetString
class procedure Tkw_TextLoad_Component_TextSource.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TevTextSource);
end;//Tkw_TextLoad_Component_TextSource.RegisterInEngine
class function Tkw_TextLoad_Component_TextSource.GetWordNameForRegister: AnsiString;
begin
Result := 'компонент::TextSource';
end;//Tkw_TextLoad_Component_TextSource.GetWordNameForRegister
function Tkw_TextLoad_Component_LoadManager.GetString: AnsiString;
begin
Result := 'LoadManager';
end;//Tkw_TextLoad_Component_LoadManager.GetString
class procedure Tkw_TextLoad_Component_LoadManager.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TevLoadDocumentManager);
end;//Tkw_TextLoad_Component_LoadManager.RegisterInEngine
class function Tkw_TextLoad_Component_LoadManager.GetWordNameForRegister: AnsiString;
begin
Result := 'компонент::LoadManager';
end;//Tkw_TextLoad_Component_LoadManager.GetWordNameForRegister
function TkwTextLoadFormText.Text(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevEditor;
{* Реализация слова скрипта .TTextLoadForm.Text }
begin
Result := aTextLoadForm.Text;
end;//TkwTextLoadFormText.Text
class function TkwTextLoadFormText.GetWordNameForRegister: AnsiString;
begin
Result := '.TTextLoadForm.Text';
end;//TkwTextLoadFormText.GetWordNameForRegister
function TkwTextLoadFormText.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TevEditor);
end;//TkwTextLoadFormText.GetResultTypeInfo
function TkwTextLoadFormText.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwTextLoadFormText.GetAllParamsCount
function TkwTextLoadFormText.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TTextLoadForm)]);
end;//TkwTextLoadFormText.ParamsTypes
procedure TkwTextLoadFormText.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Text', aCtx);
end;//TkwTextLoadFormText.SetValuePrim
procedure TkwTextLoadFormText.DoDoIt(const aCtx: TtfwContext);
var l_aTextLoadForm: TTextLoadForm;
begin
try
l_aTextLoadForm := TTextLoadForm(aCtx.rEngine.PopObjAs(TTextLoadForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTextLoadForm: TTextLoadForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Text(aCtx, l_aTextLoadForm));
end;//TkwTextLoadFormText.DoDoIt
function TkwTextLoadFormTextSource.TextSource(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevTextSource;
{* Реализация слова скрипта .TTextLoadForm.TextSource }
begin
Result := aTextLoadForm.TextSource;
end;//TkwTextLoadFormTextSource.TextSource
class function TkwTextLoadFormTextSource.GetWordNameForRegister: AnsiString;
begin
Result := '.TTextLoadForm.TextSource';
end;//TkwTextLoadFormTextSource.GetWordNameForRegister
function TkwTextLoadFormTextSource.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TevTextSource);
end;//TkwTextLoadFormTextSource.GetResultTypeInfo
function TkwTextLoadFormTextSource.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwTextLoadFormTextSource.GetAllParamsCount
function TkwTextLoadFormTextSource.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TTextLoadForm)]);
end;//TkwTextLoadFormTextSource.ParamsTypes
procedure TkwTextLoadFormTextSource.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству TextSource', aCtx);
end;//TkwTextLoadFormTextSource.SetValuePrim
procedure TkwTextLoadFormTextSource.DoDoIt(const aCtx: TtfwContext);
var l_aTextLoadForm: TTextLoadForm;
begin
try
l_aTextLoadForm := TTextLoadForm(aCtx.rEngine.PopObjAs(TTextLoadForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTextLoadForm: TTextLoadForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(TextSource(aCtx, l_aTextLoadForm));
end;//TkwTextLoadFormTextSource.DoDoIt
function TkwTextLoadFormLoadManager.LoadManager(const aCtx: TtfwContext;
aTextLoadForm: TTextLoadForm): TevLoadDocumentManager;
{* Реализация слова скрипта .TTextLoadForm.LoadManager }
begin
Result := aTextLoadForm.LoadManager;
end;//TkwTextLoadFormLoadManager.LoadManager
class function TkwTextLoadFormLoadManager.GetWordNameForRegister: AnsiString;
begin
Result := '.TTextLoadForm.LoadManager';
end;//TkwTextLoadFormLoadManager.GetWordNameForRegister
function TkwTextLoadFormLoadManager.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TevLoadDocumentManager);
end;//TkwTextLoadFormLoadManager.GetResultTypeInfo
function TkwTextLoadFormLoadManager.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwTextLoadFormLoadManager.GetAllParamsCount
function TkwTextLoadFormLoadManager.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TTextLoadForm)]);
end;//TkwTextLoadFormLoadManager.ParamsTypes
procedure TkwTextLoadFormLoadManager.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству LoadManager', aCtx);
end;//TkwTextLoadFormLoadManager.SetValuePrim
procedure TkwTextLoadFormLoadManager.DoDoIt(const aCtx: TtfwContext);
var l_aTextLoadForm: TTextLoadForm;
begin
try
l_aTextLoadForm := TTextLoadForm(aCtx.rEngine.PopObjAs(TTextLoadForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTextLoadForm: TTextLoadForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(LoadManager(aCtx, l_aTextLoadForm));
end;//TkwTextLoadFormLoadManager.DoDoIt
initialization
Tkw_Form_TextLoad.RegisterInEngine;
{* Регистрация Tkw_Form_TextLoad }
Tkw_TextLoad_Control_Text.RegisterInEngine;
{* Регистрация Tkw_TextLoad_Control_Text }
Tkw_TextLoad_Control_Text_Push.RegisterInEngine;
{* Регистрация Tkw_TextLoad_Control_Text_Push }
Tkw_TextLoad_Component_TextSource.RegisterInEngine;
{* Регистрация Tkw_TextLoad_Component_TextSource }
Tkw_TextLoad_Component_LoadManager.RegisterInEngine;
{* Регистрация Tkw_TextLoad_Component_LoadManager }
TkwTextLoadFormText.RegisterInEngine;
{* Регистрация TextLoadForm_Text }
TkwTextLoadFormTextSource.RegisterInEngine;
{* Регистрация TextLoadForm_TextSource }
TkwTextLoadFormLoadManager.RegisterInEngine;
{* Регистрация TextLoadForm_LoadManager }
TtfwTypeRegistrator.RegisterType(TypeInfo(TTextLoadForm));
{* Регистрация типа TTextLoadForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TevEditor));
{* Регистрация типа TevEditor }
TtfwTypeRegistrator.RegisterType(TypeInfo(TevTextSource));
{* Регистрация типа TevTextSource }
TtfwTypeRegistrator.RegisterType(TypeInfo(TevLoadDocumentManager));
{* Регистрация типа TevLoadDocumentManager }
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM) AND NOT Defined(NoScripts)
end.
|
unit DAO.VerbaFixa;
interface
uses DAO.Base, Model.VerbaFixa, Generics.Collections, System.Classes;
type
TVerbaFixaDAO = class(TDAO)
public
function Insert(aVerbas: Model.VerbaFixa.TVerbaFixa): Boolean;
function Update(aVerbas: Model.VerbaFixa.TVerbaFixa): Boolean;
function Delete(sFiltro: String): Boolean;
function FindVerba(sFiltro: String): TObjectList<Model.VerbaFixa.TVerbaFixa>;
function RetornaVerba(iGrupo: Integer; dtData: TDate): Double;
end;
const
TABLENAME = 'tbverbafixa';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TVerbaFixaDAO.Insert(aVerbas: TVerbaFixa): Boolean;
var
sSQL : System.string;
begin
Result := False;
aVerbas.ID := GetKeyValue(TABLENAME,'ID_VERBA_FIXA');
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(ID_VERBA_FIXA, ID_GRUPO, DAT_VERBA_FIXA, DES_VERBA_FIXA, VAL_VERBA_FIXA, DOM_ATIVO, DES_LOG) ' +
'VALUES ' +
'(:ID, :GRUPO, :DATA, :DESCRICAO, :VALOR, :ATIVO, :LOG);';
Connection.ExecSQL(sSQL,[aVerbas.ID, aVerbas.Grupo, aVerbas.Data, aVerbas.Descricao, aVerbas.Valor, aVerbas.Ativo, aVerbas.Log],
[ftInteger, ftInteger, ftDate, ftString, ftFloat, ftInteger, ftString]);
Result := True;
end;
function TVerbaFixaDAO.Update(aVerbas: TVerbaFixa): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'ID_GRUPO = :GRUPO, DAT_VERBA_FIXA = :DATA, DES_VERBA_FIXA = :DESCRICAO, VAL_VERBA_FIXA = :VALOR, DOM_ATIVO = :ATIVO, ' +
'DES_LOG = :LOG ' +
'WHERE ID_VERBA_FIXA = :ID;';
Connection.ExecSQL(sSQL,[aVerbas.Grupo, aVerbas.Data, aVerbas.Descricao, aVerbas.Valor, aVerbas.Ativo, aVerbas.Log, aVerbas.ID],
[ftInteger, ftDate, ftString, ftFloat, ftInteger, ftString, ftInteger]);
Result := True;
end;
function TVerbaFixaDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Connection.ExecSQL(sSQL);
Result := True;
end;
function TVerbaFixaDAO.FindVerba(sFiltro: string): TObjectList<Model.VerbaFixa.TVerbaFixa>;
var
FDQuery: TFDQuery;
verbas: TObjectList<TVerbaFixa>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
verbas := TObjectList<TVerbaFixa>.Create();
while not FDQuery.Eof do
begin
verbas.Add(TVerbafixa.Create(FDQuery.FieldByName('ID_VERBA_FIXA').AsInteger, FDQuery.FieldByName('ID_GRUPO').AsInteger,
FDQuery.FieldByName('DAT_VERBA_FIXA').AsDateTime,
FDQuery.FieldByName('DES_VERBA_FIXA').AsString, FDQuery.FieldByName('VAL_VERBA_FIXA').AsFloat,
FDQuery.FieldByName('DOM_ATIVO').AsInteger, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := verbas;
end;
function TVerbaFixaDAO.RetornaVerba(iGrupo: Integer; dtData: TDate): Double;
var
FDQuery: TFDQuery;
sSQL : String;
dValor : Double;
begin
FDQuery := TFDQuery.Create(nil);
try
dValor := 0;
sSQL := 'SELECT DAT_VERBA_FIXA, VAL_VERBA_FIXA FROM ' + TABLENAME +
' WHERE ID_GRUPO = :GRUPO AND DAT_VERBA_FIXA <= :DATA ORDER BY DAT_VERBA_FIXA';
FDQuery.Connection := Connection;
FDQuery.Open(sSQL,[iGrupo, dtData],[ftInteger, ftDate]);
if not FDQuery.IsEmpty then
begin
FDQuery.Last;
dValor := FDQuery.FieldByName('VAL_VERBA_FIXA').AsFloat;
end;
Result := dValor;
finally
FDQuery.Free;
end;
end;
end.
|
program ProgramName;
uses Math;
var
n : integer;
function power2(n:integer): integer;
var k : integer;
begin
k := 0;
while (n mod 2 = 0) do
begin
k := succ(k);
n := n div 2;
end;
power2 := k
end;
begin
write('N: ');
read(n);
writeln('max(k) such that (2^k | ', n, ') = ', power2(n));
end.
|
unit fmGroupSelection;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Winapi.ActiveX,
Winapi.CommCtrl, Winapi.UxTheme, Vcl.StdCtrls, Vcl.ImgList, ActiveDS_TLB, ADC.Types,
ADC.GlobalVar, ADC.Common, ADC.AD, ADC.LDAP, ADC.ImgProcessor, Vcl.ToolWin,
System.ImageList, System.StrUtils, Vcl.ExtCtrls;
type
TForm_GroupSelect = class(TForm)
ListView_Groups: TListView;
Label_Search: TLabel;
Button_Cancel: TButton;
Button_OK: TButton;
ToolBar: TToolBar;
ToolButton_Refresh: TToolButton;
ToolButton_Separator1: TToolButton;
ToolButton_SelectAll: TToolButton;
ImageList_ToolBar: TImageList;
ToolButton_SelectNone: TToolButton;
Edit_Search: TButtonedEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ListView_GroupsData(Sender: TObject; Item: TListItem);
procedure ListView_GroupsDrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ListView_GroupsResize(Sender: TObject);
procedure Button_CancelClick(Sender: TObject);
procedure ListView_GroupsClick(Sender: TObject);
procedure ListView_GroupsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ListView_GroupsMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ToolButton_RefreshClick(Sender: TObject);
procedure ToolButton_SelectAllClick(Sender: TObject);
procedure ToolButton_SelectNoneClick(Sender: TObject);
procedure Edit_SearchChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Button_OKClick(Sender: TObject);
procedure Edit_SearchRightButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FCallingForm: TForm;
FGroups: TADGroupList;
FGroupList: TADGroupList;
FBaseList: TADGroupList;
FStateImages: TImageList;
FListViewWndProc: TWndMethod;
FOnGroupsApply: TSelectGroupProc;
procedure ListViewWndProc(var Msg: TMessage);
procedure ClearFields;
procedure GetGroupList(ALDAP: PLDAP; AList: TADGroupList); overload;
procedure GetGroupList(ARootDSE: IAds; AList: TADGroupList); overload;
procedure SetCallingForm(const Value: TForm);
function _GroupType(AValue: Integer): Integer;
public
procedure SetBaseGroupList(const AGroupList: TADGroupList);
procedure RefreshGroupList;
property CallingForm: TForm write SetCallingForm;
property OnGroupsApply: TSelectGroupProc read FOnGroupsApply write FOnGroupsApply;
end;
var
Form_GroupSelect: TForm_GroupSelect;
implementation
{$R *.dfm}
uses dmDataModule;
function SortGropListByName(Item1, Item2: Pointer): Integer;
var
m1, m2: TADGroup;
begin
m1 := PADGroup(Item1)^;
m2 := PADGroup(Item2)^;
Result := AnsiCompareText(m1.name, m2.name);
end;
procedure TForm_GroupSelect.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_GroupSelect.Button_OKClick(Sender: TObject);
var
i: Integer;
idx: Integer;
begin
{ Если группа присутсвует в базовом списке групп, то изменяем значения ее }
{ полей. Если же группа в базовом списке не присутствовала и она выбрана }
{ для добавления, то добавляем ее в базовый список. Возвращаем измененный }
{ базовый список в событии OnGroupsApply }
for i := FGroupList.Count - 1 downto 0 do
begin
idx := FBaseList.IndexOf(FGroupList[i]^.primaryGroupToken);
if idx > -1 then
begin
FBaseList[idx]^ := FGroupList[i]^;
end else if FGroupList[i]^.Selected then
begin
ListView_Groups.Items.Count := ListView_Groups.Items.Count - 1;
FBaseList.Add(FGroupList.Extract(FGroupList[i]));
end;
end;
if Assigned(FOnGroupsApply)
then FOnGroupsApply(Self, FBaseList);
Close;
end;
procedure TForm_GroupSelect.ClearFields;
begin
ListView_Groups.Clear;
FBaseList.Clear;
FGroups.Clear;
FGroupList.Clear;
Edit_Search.Clear;
FOnGroupsApply := nil;
end;
procedure TForm_GroupSelect.Edit_SearchChange(Sender: TObject);
var
g: PADGroup;
begin
Edit_Search.RightButton.Visible := Edit_Search.Text <> '';
ListView_Groups.Clear;
FGroups.Clear;
if Edit_Search.Text = '' then
begin
for g in FGroupList do
FGroups.Add(g);
end else
for g in FGroupList do
begin
if ContainsText(g^.name, Edit_Search.Text)
or ContainsText(g^.description, Edit_Search.Text)
then FGroups.Add(g);
end;
ListView_Groups.Items.Count := FGroups.Count;
end;
procedure TForm_GroupSelect.Edit_SearchRightButtonClick(Sender: TObject);
begin
Edit_Search.Clear;
end;
procedure TForm_GroupSelect.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ClearFields;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_GroupSelect.FormCreate(Sender: TObject);
begin
FGroups := TADGroupList.Create(False);
FGroupList := TADGroupList.Create;
FBaseList := TADGroupList.Create;
FStateImages := TImageList.Create(Self);
FStateImages.ColorDepth := cd32Bit;
TImgProcessor.GetThemeButtons(
Self.Handle,
ListView_Groups.Canvas.Handle,
BP_CHECKBOX,
ListView_Groups.Color,
FStateImages
);
ListView_Groups.StateImages := FStateImages;
FListViewWndProc := ListView_Groups.WindowProc;
ListView_Groups.WindowProc := ListViewWndProc;
end;
procedure TForm_GroupSelect.FormDestroy(Sender: TObject);
begin
FGroups.Free;
FGroupList.Free;
FBaseList.Free;
end;
procedure TForm_GroupSelect.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F5: begin
ToolButton_RefreshClick(Self);
end;
Ord('F'): begin
if ssCtrl in Shift
then Edit_Search.SetFocus;
end;
VK_ESCAPE: begin
Close;
end;
end;
end;
procedure TForm_GroupSelect.FormShow(Sender: TObject);
begin
Edit_Search.SetFocus;
end;
procedure TForm_GroupSelect.GetGroupList(ALDAP: PLDAP; AList: TADGroupList);
var
ldapBase: AnsiString;
ldapFilter: AnsiString;
ldapCookie: PLDAPBerVal;
ldapPage: PLDAPControl;
ldapControls: array[0..1] of PLDAPControl;
ldapServerControls: PPLDAPControl;
ldapEntry: PLDAPMessage;
ldapValue: PPAnsiChar;
ldapCount: ULONG;
searchResult: PLDAPMessage;
attrArray: array of PAnsiChar;
errorCode: ULONG;
returnCode: ULONG;
morePages: Boolean;
dn: PAnsiChar;
g: PADGroup;
begin
AList.Clear;
SetLength(attrArray, 2);
attrArray[0] := PAnsiChar('defaultNamingContext');
attrArray[1] := nil;
returnCode := ldap_search_ext_s(
ALDAP,
nil,
LDAP_SCOPE_BASE,
PAnsiChar('(objectclass=*)'),
PAnsiChar(@attrArray[0]),
0,
nil,
nil,
nil,
0,
searchResult
);
if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(ALDAP, searchResult) > 0 ) then
begin
ldapEntry := ldap_first_entry(ALDAP, searchResult);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[0]);
if ldapValue <> nil
then ldapBase := ldapValue^;
ldap_value_free(ldapValue);
end;
if searchResult <> nil
then ldap_msgfree(searchResult);
SetLength(attrArray, 5);
attrArray[0] := PAnsiChar('primaryGroupToken');
attrArray[1] := PAnsiChar('name');
attrArray[2] := PAnsiChar('description');
attrArray[3] := PAnsiChar('groupType');
attrArray[4] := nil;
try
{ Формируем фильтр объектов AD }
ldapFilter := '(objectclass=group)';
ldapCookie := nil;
{ Постраничный поиск объектов AD }
repeat
returnCode := ldap_create_page_control(
ALDAP,
ADC_SEARCH_PAGESIZE,
ldapCookie,
1,
ldapPage
);
if returnCode <> LDAP_SUCCESS
then raise Exception.Create('Failure during ldap_create_page_control: ' + ldap_err2string(returnCode));
ldapControls[0] := ldapPage;
ldapControls[1] := nil;
returnCode := ldap_search_ext_s(
ALDAP,
PAnsiChar(ldapBase),
LDAP_SCOPE_SUBTREE,
PAnsiChar(ldapFilter),
PAnsiChar(@attrArray[0]),
0,
@ldapControls,
nil,
nil,
0,
SearchResult
);
if not (returnCode in [LDAP_SUCCESS, LDAP_PARTIAL_RESULTS])
then raise Exception.Create('Failure during ldap_search_ext_s: ' + ldap_err2string(returnCode));
returnCode := ldap_parse_result(
ALDAP^,
SearchResult,
@errorCode,
nil,
nil,
nil,
ldapServerControls,
False
);
if ldapCookie <> nil then
begin
ber_bvfree(ldapCookie);
ldapCookie := nil;
end;
returnCode := ldap_parse_page_control(
ALDAP,
ldapServerControls,
ldapCount,
ldapCookie
);
if (ldapCookie <> nil) and (ldapCookie^.bv_val <> nil) and (System.SysUtils.StrLen(ldapCookie^.bv_val) > 0)
then morePages := True
else morePages := False;
if ldapServerControls <> nil then
begin
ldap_controls_free(ldapServerControls);
ldapServerControls := nil;
end;
ldapControls[0]:= nil;
ldap_control_free(ldapPage);
ldapPage := nil;
ldapEntry := ldap_first_entry(ALDAP, searchResult);
while ldapEntry <> nil do
begin
New(g);
g^.Selected := False;
g^.IsMember := False;
g^.IsPrimary := False;
g^.ImageIndex := 6;
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[0]);
if ldapValue <> nil
then g^.primaryGroupToken := StrToIntDef(ldapValue^, 0);
ldap_value_free(ldapValue);
dn := ldap_get_dn(ALDAP, ldapEntry);
if dn <> nil
then g^.distinguishedName := dn;
ldap_memfree(dn);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[1]);
if ldapValue <> nil
then g^.name := ldapValue^;
ldap_value_free(ldapValue);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[2]);
if ldapValue <> nil
then g^.description := ldapValue^;
ldap_value_free(ldapValue);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[3]);
if ldapValue <> nil
then g^.groupType := _GroupType(StrToIntDef(ldapValue^, 0));
ldap_value_free(ldapValue);
AList.Add(g);
ldapEntry := ldap_next_entry(ALDAP, ldapEntry);
end;
ldap_msgfree(SearchResult);
SearchResult := nil;
until (morePages = False);
ber_bvfree(ldapCookie);
ldapCookie := nil;
finally
if searchResult <> nil
then ldap_msgfree(searchResult);
end;
end;
procedure TForm_GroupSelect.GetGroupList(ARootDSE: IAds; AList: TADGroupList);
const
S_ADS_NOMORE_ROWS = HRESULT($00005012);
var
hostName: string;
hr: HRESULT;
objFilter: string;
hRes: HRESULT;
SearchBase: string;
SearchPrefs: array of ADS_SEARCHPREF_INFO;
SearchResult: IDirectorySearch;
SearchHandle: PHandle;
col: ADS_SEARCH_COLUMN;
attrArray: array of WideString;
v: OleVariant;
g: PADGroup;
begin
AList.Clear;
CoInitialize(nil);
try
v := ARootDSE.Get('defaultNamingContext');
if not VarIsNull(v)
then SearchBase := VariantToStringWithDefault(v, '');
VariantClear(v);
v := ARootDSE.Get('dnsHostName');
if not VarIsNull(v)
then hostName := VariantToStringWithDefault(v, '');
VariantClear(v);
{ Получаем список групп в которых состоит пользователь }
SetLength(attrArray, 5);
attrArray[0] := PAnsiChar('primaryGroupToken');
attrArray[1] := PAnsiChar('distinguishedName');
attrArray[2] := PAnsiChar('name');
attrArray[3] := PAnsiChar('description');
attrArray[4] := PAnsiChar('groupType');
hRes := ADsOpenObject(
PChar('LDAP://' + hostName + '/' + SearchBase),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IDirectorySearch,
@SearchResult
);
if Succeeded(hRes) then
begin
SetLength(SearchPrefs, 3);
with SearchPrefs[0] do
begin
dwSearchPref := ADS_SEARCHPREF_PAGESIZE;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADC_SEARCH_PAGESIZE;
end;
with SearchPrefs[1] do
begin
dwSearchPref := ADS_SEARCHPREF_PAGED_TIME_LIMIT;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 60;
end;
with SearchPrefs[2] do
begin
dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE;
vValue.dwType := ADSTYPE_INTEGER;
vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADS_SCOPE_SUBTREE;
end;
hRes := SearchResult.SetSearchPreference(SearchPrefs[0], Length(SearchPrefs));
if not Succeeded(hRes)
then raise Exception.Create(ADSIErrorToString);
objFilter := '(objectclass=group)';
hRes := SearchResult.ExecuteSearch(
PWideChar(objFilter),
PWideChar(@attrArray[0]),
Length(attrArray),
Pointer(SearchHandle)
);
if not Succeeded(hRes)
then raise Exception.Create(ADSIErrorToString);
hRes := SearchResult.GetNextRow(SearchHandle);
while (hRes <> S_ADS_NOMORE_ROWS) do
begin
New(g);
g^.Selected := False;
g^.IsMember := False;
g^.IsPrimary := False;
g^.ImageIndex := 6;
hRes := SearchResult.GetColumn(SearchHandle, PWideChar(attrArray[0]), col);
if Succeeded(hRes)
then g^.primaryGroupToken := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.Integer;
SearchResult.FreeColumn(col);
hRes := SearchResult.GetColumn(SearchHandle, PWideChar(attrArray[1]), col);
if Succeeded(hRes)
then g^.distinguishedName := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.DNString;
SearchResult.FreeColumn(col);
hRes := SearchResult.GetColumn(SearchHandle, PWideChar(attrArray[2]), col);
if Succeeded(hRes)
then g^.name := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
SearchResult.FreeColumn(col);
hRes := SearchResult.GetColumn(SearchHandle, PWideChar(attrArray[3]), col);
if Succeeded(hRes)
then g^.description := col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.CaseIgnoreString;
SearchResult.FreeColumn(col);
hRes := SearchResult.GetColumn(SearchHandle, PWideChar(attrArray[4]), col);
if Succeeded(hRes)
then g^.groupType := _GroupType(col.pAdsvalues^.__MIDL____MIDL_itf_ads_0000_00000000.Integer);
SearchResult.FreeColumn(col);
AList.Add(g);
hRes := SearchResult.GetNextRow(Pointer(SearchHandle));
end;
end else raise Exception.Create(ADSIErrorToString);
finally
SearchResult.CloseSearchHandle(Pointer(SearchHandle));
end;
end;
procedure TForm_GroupSelect.ListViewWndProc(var Msg: TMessage);
begin
ShowScrollBar(ListView_Groups.Handle, SB_HORZ, False);
// ShowScrollBar(ListView_MemberOf.Handle, SB_VERT, True);
FListViewWndProc(Msg);
end;
procedure TForm_GroupSelect.ListView_GroupsClick(Sender: TObject);
var
hts : THitTests;
lvCursosPos : TPoint;
li : TListItem;
R: TRect;
Key: Word;
begin
inherited;
Key := VK_SPACE;
//position of the mouse cursor related to ListView
lvCursosPos := ListView_Groups.ScreenToClient(Mouse.CursorPos) ;
//click where?
hts := ListView_Groups.GetHitTestInfoAt(lvCursosPos.X, lvCursosPos.Y);
//locate the state-clicked item
if htOnItem in hts then
begin
li := ListView_Groups.GetItemAt(lvCursosPos.X, lvCursosPos.Y);
if li <> nil then
begin
ListView_GetItemRect(ListView_Groups.Handle, li.Index, R, LVIR_BOUNDS);
{ Величины R.Width и R.Offset см. в отрисовке значка состояния атрибута }
{ в процедуре ListView_AttributesDrawItem }
R.Width := 16;
R.Offset(6, 0);
if PtInRect(R, lvCursosPos)
then ListView_GroupsKeyDown(ListView_Groups, Key, []);
end;
end;
end;
procedure TForm_GroupSelect.ListView_GroupsData(Sender: TObject;
Item: TListItem);
begin
while Item.SubItems.Count < ListView_Groups.Columns.Count - 1 do
Item.SubItems.Add('');
if FGroups[Item.Index]^.Selected
then Item.StateIndex := 1
else Item.StateIndex := 0;
if FGroupList[Item.Index]^.IsPrimary
then Item.StateIndex := 3;
Item.ImageIndex := FGroups[Item.Index]^.ImageIndex;
Item.Caption := FGroups[Item.Index]^.name;
Item.SubItems[0] := FGroups[Item.Index]^.description;
end;
procedure TForm_GroupSelect.ListView_GroupsDrawItem(Sender: TCustomListView;
Item: TListItem; Rect: TRect; State: TOwnerDrawState);
var
C: TCanvas;
R: TRect;
S: string;
ColOrder: array of Integer;
SubIndex: Integer;
txtAlign: UINT;
i: Integer;
attr: PADAttribute;
begin
C := Sender.Canvas;
if (odSelected in State) or (FGroups[Item.Index].Selected)
then C.Brush.Color := IncreaseBrightness(COLOR_SELBORDER, 95);
C.FillRect(Rect);
{ Выводим CheckBox }
R := Rect;
R.Width := 16;
R.Offset(5, 0);
ListView_Groups.StateImages.Draw(c, R.TopLeft.X, R.TopLeft.Y, Item.StateIndex);
{ Выводим значек объекта AD }
R.Offset(R.Width + 6, 0);
if Item.ImageIndex > -1
then DM1.ImageList_Accounts.Draw(c, R.TopLeft.X, R.TopLeft.Y + 1, Item.ImageIndex);
{ Выводим name }
R.Offset(R.Width + 6, 0);
R.Right := R.Left + (Sender.Column[0].Width - R.Left - 6);
if FGroups[Item.Index].IsPrimary
then C.Font.Style := C.Font.Style + [fsBold]
else C.Font.Style := C.Font.Style - [fsBold];
C.Refresh;
S := Item.Caption;
DrawText(
C.Handle,
S,
Length(S),
R,
DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS
);
{ Выводим description }
ListView_GetSubItemRect(Sender.Handle, Item.Index, 1, 0, @R);
R.Inflate(-6, 0);
C.Refresh;
S := Item.SubItems[0];
DrawText(
C.Handle,
S,
Length(S),
R,
DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS
);
{ Отрисовываем рамку вокруг записи }
R := Rect;
R.Height := R.Height - 1;
R.Width := R.Width - 1;
if odFocused in State then
begin
C.Pen.Color := COLOR_SELBORDER;
C.Pen.Width := 1;
C.Refresh;
C.Polyline(
[
R.TopLeft,
Point(R.BottomRight.X, R.TopLeft.Y),
R.BottomRight,
Point(R.TopLeft.X, R.BottomRight.Y),
R.TopLeft
]
);
end else
begin
C.Pen.Color := IncreaseBrightness(clBtnFace, 35);
C.Pen.Width := 1;
C.Refresh;
C.Polyline(
[
Point(R.TopLeft.X, R.BottomRight.Y),
R.BottomRight
]
)
end;
end;
procedure TForm_GroupSelect.ListView_GroupsKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
li: TListItem;
begin
case Key of
VK_SPACE: begin
li := ListView_Groups.Selected;
if li <> nil then
begin
if not FGroups[li.Index]^.IsPrimary
then FGroups.SetSelected(li.Index, not FGroups[li.Index].Selected);
ListView_Groups.Invalidate
end;
end;
end;
end;
procedure TForm_GroupSelect.ListView_GroupsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
k: Word;
li: TListItem;
HitPoint: TPoint;
HitInfo: TLVHitTestInfo;
MsgRes: Integer;
begin
if (Button = mbLeft) and (ssDouble in Shift)
or (Button = mbLeft) and (ssCtrl in Shift) then
begin
HitPoint := ListView_Groups.ScreenToClient(Mouse.Cursorpos);
FillChar(HitInfo, SizeOf(TLVHitTestInfo), 0);
HitInfo.pt := HitPoint;
MsgRes := ListView_Groups.Perform(LVM_SUBITEMHITTEST, 0, LPARAM(@HitInfo));
if MsgRes <> -1 then
begin
ListView_Groups.Selected := ListView_Groups.Items[HitInfo.iItem];
k := VK_SPACE;
ListView_GroupsKeyDown(Sender, k, []);
end;
end;
end;
procedure TForm_GroupSelect.ListView_GroupsResize(Sender: TObject);
var
w: Integer;
begin
w := ListView_Groups.ClientWidth;
ListView_Groups.Columns[0].Width := Round(w * 55 / 100);
ListView_Groups.Columns[1].Width := w - ListView_Groups.Columns[0].Width;
end;
procedure TForm_GroupSelect.RefreshGroupList;
var
g: PADGroup;
i: Integer;
begin
ListView_Groups.Items.Clear;
FGroups.Clear;
try
case apAPI of
ADC_API_LDAP: GetGroupList(LDAPBinding, FGroupList);
ADC_API_ADSI: GetGroupList(ADSIBinding, FGroupList);
end;
for g in FGroupList do
begin
i := FBaseList.IndexOf(g^.primaryGroupToken);
if i > -1 then
begin
g^.Selected := FBaseList[i]^.Selected;
g^.IsMember := FBaseList[i]^.IsMember;
g^.IsPrimary := FBaseList[i]^.IsPrimary;
end;
end;
FGroupList.Sort(SortGropListByName);
Edit_SearchChange(Self);
except
end;
end;
procedure TForm_GroupSelect.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
end;
procedure TForm_GroupSelect.SetBaseGroupList(const AGroupList: TADGroupList);
var
src: PADGroup;
dst: PADGroup;
begin
FBaseList.Clear;
for src in AGroupList do
begin
New(dst);
dst^ := src^;
FBaseList.Add(dst);
end;
RefreshGroupList;
end;
procedure TForm_GroupSelect.ToolButton_RefreshClick(Sender: TObject);
begin
RefreshGroupList;
end;
procedure TForm_GroupSelect.ToolButton_SelectAllClick(Sender: TObject);
var
g: PADGroup;
begin
for g in FGroups do
g^.Selected := True;
ListView_Groups.Invalidate;
end;
procedure TForm_GroupSelect.ToolButton_SelectNoneClick(Sender: TObject);
var
g: PADGroup;
begin
for g in FGroups do
if not g^.IsPrimary then g^.Selected := False;
ListView_Groups.Invalidate;
end;
function TForm_GroupSelect._GroupType(AValue: Integer): Integer;
begin
if AValue = -2147483640
then Result := 8
else if AValue = -2147483646
then Result := 2
else Result := AValue;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.