text stringlengths 14 6.51M |
|---|
unit fMyPeriod;
interface
uses
SysUtils, DateUtils;
const
psStart = 0;
psEnd = 1;
type
TMyPeriod = class(TObject)
strict private
fsDay: byte;
fsMonth: byte;
fsYear: smallInt;
feDay: byte;
feMonth: byte;
feYear: smallInt;
fcDay: byte;
fcMonth: byte;
fcYear: smallInt;
function DoSetDate(Date: string; DateSelector: byte): byte; overload;
function DoSetDate(Day, Month: byte; Year: smallInt; DateSelector: byte): byte; overload;
function GetEof: boolean;
function GetNoOfDays: integer;
function GetNoOfMonths: integer;
published
property Eof: boolean read GetEof;
property Days: integer read GetNoOfDays;
property Months: integer read GetNoOfMonths;
function SetSDate(Date: string; DateSelector: byte): byte;
function SetDate(Day, Month: byte; Year: smallInt; DateSelector: byte): byte;
function GetCurrentDate(const Length: byte = 8): string;
function GetFirst(const Length: byte = 8): string;
function GetNext(const Length: byte = 8): string;
function GetPrev(const Length: byte = 8): string;
function GetLast(const Length: byte = 8): string;
procedure First;
procedure Next;
procedure Prev;
procedure Last;
end;
implementation
function TMyPeriod.GetEof: boolean;
begin
if fcYear * 10000 + fcMonth * 100 + fcDay >
feYear * 10000 + feMonth * 100 + feDay then Result := True
else Result := False;
end;
function TMyPeriod.GetNoOfDays: integer;
begin
if fsDay * fsMonth * fsYear * feDay * feMonth * feYear = 0 then Exit;
try
Result := DaysBetween(EncodeDate(feYear, feMonth, feDay), EncodeDate(fsYear, fsMonth, fsDay));
except
Result := 1;
end;
end;
function TMyPeriod.GetNoOfMonths: integer;
begin
Result := feYear * 12 + feMonth - fsYear * 12 - fsMonth + 1;
end;
function TMyPeriod.DoSetDate(Date: string; DateSelector: byte): byte;
var
aDay: byte;
aMonth: byte;
aYear: smallInt;
begin
Result := 1;
case Length(Date) of
4 : begin
aDay := 1;
aMonth := StrToInt(Date[1] + Date[2]);
if Date[3] = #57 then aYear := 1900 + StrToInt(Date[3] + Date[4])
else aYear := 2000 + StrToInt(Date[3] + Date[4]);
end;
6 : begin
aDay := StrToInt(Date[1] + Date[2]);
aMonth := StrToInt(Date[3] + Date[4]);
if Date[5] = #57 then aYear := 1900 + StrToInt(Date[5] + Date[6])
else aYear := 2000 + StrToInt(Date[5] + Date[6]);
end;
8 : begin
aDay := StrToInt(Date[1] + Date[2]);
aMonth := StrToInt(Date[3] + Date[4]);
aYear := StrToInt(Date[5] + Date[6] + Date[7] + Date[8]);
end;
end;
if DoSetDate(aDay, aMonth, aYear, DateSelector) <> 0 then Exit;
Result := 0
end;
function TMyPeriod.DoSetDate(Day, Month: byte; Year: smallInt; DateSelector: byte): byte;
begin
Result := 1;
if Day * Month * Year = 0 then Exit;
if DateSelector = psStart then begin
fsDay := Day;
fsMonth := Month;
fsYear := Year;
fcDay := Day;
fcMonth := Month;
fcYear := Year;
end;
if DateSelector = psEnd then begin
feDay := Day;
feMonth := Month;
feYear := Year;
end;
Result := 0
end;
{published methods}
function TMyPeriod.SetSDate(Date: string; DateSelector: byte): byte;
begin
Result := DoSetDate(Date, DateSelector);
end;
function TMyPeriod.SetDate(Day, Month: byte; Year: smallInt; DateSelector: byte): byte;
begin
Result := DoSetDate(Day, Month, Year, DateSelector);
end;
function TMyPeriod.GetCurrentDate(const Length: byte = 8): string;
begin
Result := '';
if Length <> 4 then
Result := Chr(48 + fcDay div 10) + Chr(48 + fcDay mod 10);
if Length = 10 then Result := Result + '.';
Result := Result + Chr(48 + fcMonth div 10) + Chr(48 + fcMonth mod 10);
if Length = 10 then Result := Result + '.';
if Length >= 8 then begin
if fcYear < 2000 then Result := Result + '19'
else Result := Result + '20';
end;
Result := Result + Chr(48 + (fcYear mod 100) div 10) + Chr(48 + (fcYear mod 100) mod 10);
end;
function TMyPeriod.GetFirst(const Length: byte = 8): string;
begin
First;
Result := GetCurrentDate(Length);
end;
function TMyPeriod.GetNext(const Length: byte = 8): string;
begin
Next;
Result := GetCurrentDate(Length);
end;
function TMyPeriod.GetPrev(const Length: byte = 8): string;
begin
Prev;
Result := GetCurrentDate(Length);
end;
function TMyPeriod.GetLast(const Length: byte = 8): string;
begin
Last;
Result := GetCurrentDate(Length);
end;
procedure TMyPeriod.First;
begin
fcDay := fsDay;
fcMonth := fsMonth;
fcYear := fsYear;
end;
procedure TMyPeriod.Next;
begin
if GetEof then Exit;
fcMonth := fcMonth + 1;
if fcMonth = 13 then begin
fcMonth := 1;
Inc(fcYear)
end
end;
procedure TMyPeriod.Prev;
begin
{if fcYear * 10000 + fcMonth * 100 + fcDay =
fsYear * 10000 + fsMonth * 100 + fsDay then Exit; }
Dec(fcMonth);
if fcMonth = 0 then begin
fcMonth := 12;
Dec(fcYear)
end
end;
procedure TMyPeriod.Last;
begin
fcDay := feDay;
fcMonth := feMonth;
fcYear := feYear;
end;
end.
|
unit LoanData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, System.Rtti, StrUtils,
System.Variants;
type
TdmLoan = class(TDataModule)
dstLoan: TADODataSet;
dscLoan: TDataSource;
dstLoanClass: TADODataSet;
dscLoanClass: TDataSource;
dstClients: TADODataSet;
dscClients: TDataSource;
dstLoanComaker: TADODataSet;
dscLoanComaker: TDataSource;
dstAlerts: TADODataSet;
dscAlerts: TDataSource;
dscComakers: TDataSource;
dstComakers: TADODataSet;
dscFinInfo: TDataSource;
dstFinInfo: TADODataSet;
dscMonExp: TDataSource;
dstMonExp: TADODataSet;
dstLoanAss: TADODataSet;
dscLoanAss: TDataSource;
dstLoanAppv: TADODataSet;
dscLoanAppv: TDataSource;
dstLoanCancel: TADODataSet;
dscLoanCancel: TDataSource;
dstLoanReject: TADODataSet;
dscLoanReject: TDataSource;
dstLoanRelease: TADODataSet;
dscLoanRelease: TDataSource;
dstLoanCharge: TADODataSet;
dscLoanCharge: TDataSource;
dscLoanClassCharges: TDataSource;
dstLoanClassCharges: TADODataSet;
dstLoanReleaseloan_id: TStringField;
dstLoanReleaserecipient: TStringField;
dstLoanReleaserel_method: TStringField;
dstLoanReleaserel_amt: TBCDField;
dstLoanReleasedate_rel: TDateTimeField;
dstLoanReleaserel_by: TStringField;
dstLoanReleaseloc_code: TStringField;
dstLoanReleaserel_amt_f: TStringField;
dstLoanReleasedate_rel_f: TStringField;
dstLoanReleasemethod_name: TStringField;
dstLoanReleaserecipient_name: TStringField;
dstLoanReleaseloc_name: TStringField;
dstClientLoans: TADODataSet;
dscLedger: TDataSource;
dstLedger: TADODataSet;
dstLedgerdue: TDateTimeField;
dstLedgerdebit_amt_p: TBCDField;
dstLedgercredit_amt_p: TBCDField;
dstLedgerbalance_p: TBCDField;
dstLedgerdebit_amt_i: TBCDField;
dstLedgercredit_amt_i: TBCDField;
dstLedgerbalance_i: TBCDField;
dstLedgersort_order: TSmallintField;
dstLedgerdocument_no: TStringField;
dstLoanClose: TADODataSet;
dscLoanClose: TDataSource;
dstAdvancePayment: TADODataSet;
dstLoanClassAdvance: TADODataSet;
dscPromissoryNotes: TDataSource;
dstPromissoryNotes: TADODataSet;
dstLedgerid: TStringField;
dstLedgerprincipal_deficit: TBCDField;
dstLedgerinterest_deficit: TBCDField;
dstSchedule: TADODataSet;
procedure dstLoanBeforeOpen(DataSet: TDataSet);
procedure dstLoanClassBeforeOpen(DataSet: TDataSet);
procedure dstLoanBeforePost(DataSet: TDataSet);
procedure dstLoanNewRecord(DataSet: TDataSet);
procedure dstLoanAfterPost(DataSet: TDataSet);
procedure dstLoanClassAfterScroll(DataSet: TDataSet);
procedure dstLoanAfterOpen(DataSet: TDataSet);
procedure dstLoanComakerBeforeOpen(DataSet: TDataSet);
procedure dstLoanComakerAfterOpen(DataSet: TDataSet);
procedure dstAlertsBeforeOpen(DataSet: TDataSet);
procedure dstFinInfoBeforeOpen(DataSet: TDataSet);
procedure dstFinInfoAfterOpen(DataSet: TDataSet);
procedure dstMonExpAfterOpen(DataSet: TDataSet);
procedure dstLoanClassAfterOpen(DataSet: TDataSet);
procedure dstFinInfoBeforePost(DataSet: TDataSet);
procedure dstLoanAssBeforeOpen(DataSet: TDataSet);
procedure dstLoanAppvBeforeOpen(DataSet: TDataSet);
procedure dstLoanAppvBeforePost(DataSet: TDataSet);
procedure dstStatusesBeforeOpen(DataSet: TDataSet);
procedure dstLoanAssBeforePost(DataSet: TDataSet);
procedure dstMonExpBeforeOpen(DataSet: TDataSet);
procedure dstMonExpBeforePost(DataSet: TDataSet);
procedure dstLoanAssAfterOpen(DataSet: TDataSet);
procedure dstLoanAppvAfterOpen(DataSet: TDataSet);
procedure dstLoanCancelBeforeOpen(DataSet: TDataSet);
procedure dstLoanCancelBeforePost(DataSet: TDataSet);
procedure dstLoanCancelAfterOpen(DataSet: TDataSet);
procedure dstLoanAssAfterPost(DataSet: TDataSet);
procedure dstLoanAppvAfterPost(DataSet: TDataSet);
procedure dstLoanCancelAfterPost(DataSet: TDataSet);
procedure dstLoanRejectAfterOpen(DataSet: TDataSet);
procedure dstLoanRejectAfterPost(DataSet: TDataSet);
procedure dstLoanRejectBeforeOpen(DataSet: TDataSet);
procedure dstLoanRejectBeforePost(DataSet: TDataSet);
procedure dstAlertsAfterOpen(DataSet: TDataSet);
procedure dstLoanComakerNewRecord(DataSet: TDataSet);
procedure dstLoanReleaseAfterOpen(DataSet: TDataSet);
procedure dstLoanReleaseBeforeOpen(DataSet: TDataSet);
procedure dstLoanReleaseBeforePost(DataSet: TDataSet);
procedure dstLoanChargeBeforeOpen(DataSet: TDataSet);
procedure dstLoanChargeAfterOpen(DataSet: TDataSet);
procedure dstLoanReleaseNewRecord(DataSet: TDataSet);
procedure dstLoanClassChargesBeforeOpen(DataSet: TDataSet);
procedure dstLoanReleaseCalcFields(DataSet: TDataSet);
procedure dstClientLoansBeforeOpen(DataSet: TDataSet);
procedure dstLedgerBeforeOpen(DataSet: TDataSet);
procedure dstLoanCloseAfterOpen(DataSet: TDataSet);
procedure dstLoanCloseAfterPost(DataSet: TDataSet);
procedure dstLoanCloseBeforeOpen(DataSet: TDataSet);
procedure dstLoanCloseBeforePost(DataSet: TDataSet);
procedure dstAdvancePaymentBeforeOpen(DataSet: TDataSet);
procedure dstAdvancePaymentAfterOpen(DataSet: TDataSet);
procedure dstLoanClassAdvanceBeforeOpen(DataSet: TDataSet);
procedure dstPromissoryNotesBeforeOpen(DataSet: TDataSet);
private
{ Private declarations }
procedure SetLoanClassProperties;
procedure AddLoanClassCharges;
procedure AddLoanClassAdvancePayment;
public
{ Public declarations }
end;
var
dmLoan: TdmLoan;
implementation
uses
AppData, Loan, DBUtil, IFinanceGlobal, LoanClassification, Comaker, FinInfo,
MonthlyExpense, Alert, ReleaseRecipient, Recipient, LoanCharge, LoanClassCharge,
LoanType, Assessment, Location, Group, AppConstants, LoanClassAdvance;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TdmLoan.SetLoanClassProperties;
begin
with dstLoan do
begin
ln.Status := FieldByName('status_id').AsString;
ln.AppliedAmount := FieldByName('amt_appl').AsCurrency;
ln.DesiredTerm := FieldByName('des_term').AsInteger;
ln.DateApplied := FieldByName('date_appl').AsDateTime;
ln.Balance := FieldByName('balance').AsCurrency;
ln.InterestDeficit := FieldByName('int_deficit').AsCurrency;
ln.LastInterestPostDate := FieldByName('last_interest_post_date').AsDateTime;
if FieldByName('last_trans_date').AsString = '' then ln.LastTransactionDate := ifn.AppDate
else ln.LastTransactionDate := FieldByName('last_trans_date').AsDateTime;
end;
end;
procedure TdmLoan.AddLoanClassAdvancePayment;
var
LLoanClassAdvance: TLoanClassAdvance;
begin
with dstLoanClassAdvance do
begin
ln.LoanClass.RemoveAdvancePayment;
Filter := 'class_id = ' + QuotedStr(IntToStr(ln.LoanClass.ClassificationId));
if RecordCount > 0 then
begin
LLoanClassAdvance := TLoanClassAdvance.Create;
LLoanClassAdvance.Interest := FieldByName('int').AsInteger;
LLoanClassAdvance.Principal := FieldByName('principal').AsInteger;
LLoanClassAdvance.AdvanceMethod := TAdvanceMethod(FieldByName('advance_method').AsInteger);
LLoanClassAdvance.IncludePrincipal := FieldByName('include_principal').AsBoolean;
ln.LoanClass.AdvancePayment := LLoanClassAdvance;
end;
end;
end;
procedure TdmLoan.AddLoanClassCharges;
var
ct, cn: string;
cv, ratio, max: real;
vt: TValueType;
maxType: TMaxValueType;
forNew, forRenewal, forRestructure, forReloan: boolean;
begin
with dstLoanClassCharges, ln do
begin
Filter := 'class_id = ' + QuotedStr(IntToStr(ln.LoanClass.ClassificationId));
First;
while not Eof do
begin
ct := FieldByName('charge_type').AsString;
cn := FieldByName('charge_name').AsString;
cv := FieldByName('charge_value').AsCurrency;
vt := TValueType(FieldByName('value_type').AsInteger);
ratio := FieldByName('ratio_amt').AsCurrency;
max := FieldByName('max_value').AsCurrency;
maxType := TMaxValueType(FieldByName('max_value_type').AsInteger);
forNew := FieldByName('for_new').AsInteger = 1;
forRenewal := FieldByName('for_renew').AsInteger = 1;
forRestructure := FieldByName('for_restructure').AsInteger = 1;
forReloan := FieldByName('for_reloan').AsInteger = 1;
LoanClass.AddClassCharge(TLoanClassCharge.Create(ct,cn,cv,vt,ratio,max,maxType,
forNew, forRenewal, forRestructure, forReloan));
Next;
end;
end;
end;
procedure TdmLoan.dstAdvancePaymentAfterOpen(DataSet: TDataSet);
var
adv: TAdvancePayment;
paymentType: string;
begin
try
with DataSet do
begin
ln.ClearAdvancePayments;
First;
while not Eof do
begin
adv := TAdvancePayment.Create;
// interest
paymentType := FieldByName('payment_type').AsString;
if paymentType = TRttiEnumerationType.GetName<TPaymentTypes>(TPaymentTypes.INT) then
adv.Interest := FieldByName('payment_amt').AsCurrency;
Next;
// principal
paymentType := FieldByName('payment_type').AsString;
if paymentType = TRttiEnumerationType.GetName<TPaymentTypes>(TPaymentTypes.PRN) then
begin
adv.Principal := FieldByName('payment_amt').AsCurrency;
Next;
end;
ln.AddAdvancePayment(adv);
end;
end;
finally
DataSet.Close;
end;
end;
procedure TdmLoan.dstAdvancePaymentBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstAlertsAfterOpen(DataSet: TDataSet);
begin
try
alrt := TAlert.Create;
with DataSet, alrt do
begin
while not Eof do
begin
Add(FieldByName('alert').AsString);
Next;
end;
end;
finally
DataSet.Close;
end;
end;
procedure TdmLoan.dstAlertsBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstClientLoansBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
end;
procedure TdmLoan.dstFinInfoAfterOpen(DataSet: TDataSet);
var
compId: string;
compName, balance, monthly: string;
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'LoanAssFinInfo';
ln.ClearFinancialInfo;
with DataSet do
begin
while not Eof do
begin
compId := FieldByName('comp_id').AsString;
compName := FieldByName('comp_name').AsString;
balance := FieldByName('loan_bal_f').AsString;
monthly := FieldByName('mon_due_f').AsString;
ln.AddFinancialInfo(TFinInfo.Create(compId,compName,monthly,balance));
Next;
end;
end;
end;
procedure TdmLoan.dstFinInfoBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstFinInfoBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
end;
procedure TdmLoan.dstLedgerBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
(DataSet as TADODataSet).Parameters.ParamByName('@as_of_date').Value := ifn.AppDate;
end;
procedure TdmLoan.dstLoanAfterOpen(DataSet: TDataSet);
begin
SetLoanClassProperties;
end;
procedure TdmLoan.dstLoanAfterPost(DataSet: TDataSet);
begin
SetLoanClassProperties;
end;
procedure TdmLoan.dstLoanAppvAfterOpen(DataSet: TDataSet);
begin
if not DataSet.IsEmpty then
begin
ln.AddLoanState(lsApproved);
ln.ApprovedAmount := DataSet.FieldByName('amt_appv').AsCurrency;
ln.ApprovedTerm := DataSet.FieldByName('terms').AsInteger;
end;
end;
procedure TdmLoan.dstLoanAppvAfterPost(DataSet: TDataSet);
begin
with DataSet do
begin
if not ln.IsBacklog then
begin
if not ln.HasLoanState(lsApproved) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsApproved);
end;
end;
ln.ApprovedAmount := FieldByName('amt_appv').AsCurrency;
ln.ApprovedTerm := FieldByName('terms').AsInteger;
end;
end;
procedure TdmLoan.dstLoanAppvBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanAppvBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
DataSet.FieldByName('appv_by').AsString := ifn.User.UserId;
SetCreatedFields(DataSet);
end;
procedure TdmLoan.dstLoanAssAfterOpen(DataSet: TDataSet);
begin
if not DataSet.IsEmpty then
begin
ln.AddLoanState(lsAssessed);
ln.Assessment := TAssessment.Create(DataSet.FieldByName('rec_code').AsInteger,
DataSet.FieldByName('rec_amt').AsCurrency);
end;
end;
procedure TdmLoan.dstLoanAssAfterPost(DataSet: TDataSet);
begin
with DataSet do
begin
if not ln.IsBacklog then
begin
if not ln.HasLoanState(lsAssessed) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsAssessed);
end;
ln.Assessment := TAssessment.Create(DataSet.FieldByName('rec_code').AsInteger,
DataSet.FieldByName('rec_amt').AsCurrency);
end;
end;
end;
procedure TdmLoan.dstLoanAssBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanAssBeforePost(DataSet: TDataSet);
begin
if DataSet.State = dsInsert then
begin
if not ln.IsBacklog then
if ln.Assessment.Recommendation = rcReject then
DataSet.FieldByName('rec_amt').Value := null;
DataSet.FieldByName('loan_id').AsString := ln.Id;
DataSet.FieldByName('ass_by').AsString := ifn.User.UserId;
SetCreatedFields(DataSet);
end;
end;
procedure TdmLoan.dstLoanBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanBeforePost(DataSet: TDataSet);
var
id: string;
begin
with DataSet do
begin
if State = dsInsert then
begin
id := GetLoanId;
FieldByName('loan_id').AsString := id;
FieldByName('entity_id').AsString := ln.Client.Id;
SetCreatedFields(DataSet);
ln.Id := id;
end
end;
end;
procedure TdmLoan.dstLoanCancelAfterOpen(DataSet: TDataSet);
begin
if not DataSet.IsEmpty then ln.AddLoanState(lsCancelled);
end;
procedure TdmLoan.dstLoanCancelAfterPost(DataSet: TDataSet);
begin
if not ln.HasLoanState(lsCancelled) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsCancelled);
end;
end;
procedure TdmLoan.dstLoanCancelBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanCancelBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
DataSet.FieldByName('cancelled_by').AsString := ifn.User.UserId;
end;
procedure TdmLoan.dstLoanChargeAfterOpen(DataSet: TDataSet);
var
chargeType, chargeName: string;
amt: real;
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'LoanCharge';
ln.ClearLoanCharges;
with DataSet do
begin
while not Eof do
begin
chargeType := FieldByName('charge_type').AsString;
chargeName := FieldByName('charge_name').AsString;
amt := FieldByName('charge_amt').AsCurrency;
ln.AddLoanCharge(TLoanCharge.Create(chargeType,chargeName,amt));
Next;
end;
end;
end;
procedure TdmLoan.dstLoanChargeBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanClassAdvanceBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
end;
procedure TdmLoan.dstLoanClassAfterOpen(DataSet: TDataSet);
begin
// select the topmost loan class as default
if ln.Action = laCreating then
if DataSet.RecordCount > 0 then
dstLoan.FieldByName('class_id').AsInteger := DataSet.FieldByName('class_id').AsInteger;
end;
procedure TdmLoan.dstLoanClassAfterScroll(DataSet: TDataSet);
var
clId, trm, cmakersMin, cmakersMax, age, loanType, idDocs: integer;
clName, loanTypeName, intCompMethod: string;
intrst, maxLn: currency;
validFr, validUn: TDate;
gp: TGroup;
gpa: TGroupAttributes;
dimType: TDiminishingType;
begin
with DataSet do
begin
clId := FieldByName('class_id').AsInteger;
clName := FieldByName('class_name').AsString;
intrst := FieldByName('int_rate').AsCurrency;
trm := FieldByName('term').AsInteger;
maxLn := FieldByName('max_loan').AsCurrency;
cmakersMin := FieldByName('comakers_min').AsInteger;
cmakersMax := FieldByName('comakers_max').AsInteger;
validFr := FieldByName('valid_from').AsDateTime;
validUn := FieldByName('valid_until').AsDateTime;
age := FieldByName('max_age').AsInteger;
intCompMethod := FieldByName('int_comp_method').Asstring;
dimType := TDiminishingType(FieldByName('dim_type').AsInteger);
// loan type variables
loanType := FieldByName('loan_type').AsInteger;
loanTypeName := FieldByName('loan_type_name').AsString;
// concurrent := FieldByName('max_concurrent').AsInteger;
// maxLoanTypeAmt := FieldByName('max_loantype_amount').AsCurrency;
idDocs := FieldByName('ident_docs').AsInteger;
ltype := TLoanType.Create(loanType,loanTypeName);
// group
gp := TGroup.Create;
gp.GroupId := FieldByName('grp_id').AsString;
gp.GroupName := FieldByName('grp_name').AsString;
// group attributes
gpa := TGroupAttributes.Create;
gpa.MaxConcurrent := FieldByName('concurrent').AsInteger;
gpa.MaxTotalAmount := FieldByName('max_group_amount').AsCurrency;
gpa.IdentityDocs := idDocs;
gp.Attributes := gpa;
end;
if not Assigned(ln.LoanClass) then
ln.LoanClass := TLoanClassification.Create(clId, clName, intrst,
trm, maxLn, cmakersMin, cmakersMax, validFr, validUn, age, ltype, gp,
intCompMethod, dimType)
else
begin
with ln.LoanClass do
begin
ClassificationId := clId;
ClassificationName := clName;
Interest := intrst;
Term := trm;
MaxLoan := maxLn;
ComakersMin := cmakersMin;
ComakersMax := cmakersMax;
ValidFrom := validFr;
ValidUntil := validUn;
MaxAge := age;
LoanType := ltype;
Group := gp;
InterestComputationMethod := intCompMethod;
DiminishingType := dimType;
end;
end;
AddLoanClassCharges;
AddLoanClassAdvancePayment;
end;
procedure TdmLoan.dstLoanClassBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
(DataSet as TADODataSet).Parameters.ParamByName('@new_loan').Value :=
StrToInt(IfThen((ln.New) or (ln.IsPending),'1','0'));
// open class charges
dstLoanClassCharges.Close;
dstLoanClassCharges.Open;
// advance payment details
dstLoanClassAdvance.Close;
dstLoanClassAdvance.Open;
end;
procedure TdmLoan.dstLoanClassChargesBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
end;
procedure TdmLoan.dstLoanCloseAfterOpen(DataSet: TDataSet);
begin
if not DataSet.IsEmpty then ln.AddLoanState(lsClosed);
end;
procedure TdmLoan.dstLoanCloseAfterPost(DataSet: TDataSet);
begin
if not ln.HasLoanState(lsClosed) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsClosed);
end;
end;
procedure TdmLoan.dstLoanCloseBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanCloseBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
end;
procedure TdmLoan.dstLoanComakerAfterOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'LoanComaker';
with DataSet do
begin
First;
while not Eof do
begin
ln.AddComaker(TComaker.Create(FieldByName('name').AsString,
FieldByName('entity_id').AsString));
Next;
end;
end;
end;
procedure TdmLoan.dstLoanComakerBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanComakerNewRecord(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
end;
procedure TdmLoan.dstLoanNewRecord(DataSet: TDataSet);
begin
DataSet.FieldByName('orig_branch').AsString := ifn.LocationCode;
DataSet.FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.P);
DataSet.FieldByName('date_appl').AsDateTime := ifn.AppDate;
end;
procedure TdmLoan.dstLoanRejectAfterOpen(DataSet: TDataSet);
begin
if not DataSet.IsEmpty then ln.AddLoanState(lsRejected);
end;
procedure TdmLoan.dstLoanRejectAfterPost(DataSet: TDataSet);
begin
if not ln.HasLoanState(lsRejected) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsRejected);
end;
end;
procedure TdmLoan.dstLoanRejectBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanRejectBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
end;
procedure TdmLoan.dstLoanReleaseAfterOpen(DataSet: TDataSet);
var
amt, total: currency;
dt: TDate;
relId, relName: string;
recipientId, recipientName, locCode: string;
begin
if not ln.IsBacklog then
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'LoanRelease';
if not DataSet.IsEmpty then ln.AddLoanState(lsActive);
ln.ClearReleaseRecipients;
total := 0;
with DataSet do
begin
while not Eof do
begin
amt := FieldByName('rel_amt').AsCurrency;
dt := FieldByName('date_rel').AsDateTime;
locCode := FieldByName('loc_code').AsString;
relId := FieldByName('rel_method').AsString;
relName := FieldByName('method_name').AsString;
recipientId := FieldByName('recipient').AsString;
recipientName := FieldByName('recipient_name').AsString;
ln.AddReleaseRecipient(TReleaseRecipient.Create(
TRecipient.Create(recipientId,recipientName),
TReleaseMethod.Create(relId,relName),
locCode,ifn.GetLocationNameByCode(locCode),
amt,dt));
total := total + amt;
Next;
end;
end;
ln.ReleaseAmount := total;
end;
end;
procedure TdmLoan.dstLoanReleaseBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstLoanReleaseBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
DataSet.FieldByName('rel_by').AsString := ifn.User.UserId;
end;
procedure TdmLoan.dstLoanReleaseCalcFields(DataSet: TDataSet);
begin
with DataSet do
FieldByName('loc_name').AsString :=
ifn.GetLocationNameByCode(Trim(FieldByName('loc_code').AsString));
end;
procedure TdmLoan.dstLoanReleaseNewRecord(DataSet: TDataSet);
begin
with DataSet do
begin
FieldByName('date_rel').AsDateTime := ifn.AppDate;
FieldByName('rel_by').AsString := ifn.User.UserId;
FieldByName('loc_code').AsString := ifn.LocationCode;
end;
end;
procedure TdmLoan.dstMonExpAfterOpen(DataSet: TDataSet);
var
expType, expName, expAmount: string;
begin
(DataSet as TADODataSet).Properties['Unique table'].Value := 'LoanAssMonExp';
ln.ClearMonthlyExpenses;
with DataSet do
begin
while not Eof do
begin
expType := FieldByName('exp_type').AsString;
expName := FieldByName('exp_name').AsString;
expAmount := FieldByName('monthly_f').AsString;
ln.AddMonthlyExpense(TMonthlyExpense.Create(expType,expName,expAmount));
Next;
end;
end;
end;
procedure TdmLoan.dstMonExpBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
procedure TdmLoan.dstMonExpBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('loan_id').AsString := ln.Id;
end;
procedure TdmLoan.dstPromissoryNotesBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := ln.Client.Id;
end;
procedure TdmLoan.dstStatusesBeforeOpen(DataSet: TDataSet);
begin
(DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := ln.Id;
end;
end.
|
unit UnProdutoRegistroView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, ExtCtrls, DB, ImgList, Menus, StdCtrls, Mask, DBCtrls,
JvExControls, JvButton, JvTransparentButton, DBClient, Grids, DBGrids,
JvExDBGrids, JvDBGrid, JvDBUltimGrid,
{ helsonsant }
Util, DataUtil, UnModelo, UnProdutoRegistroModelo, Componentes, UnAplicacao,
ConectorDeControles, UnMenuView, JvExStdCtrls, JvEdit, JvValidateEdit;
type
TProdutoRegistroView = class(TForm, ITela)
Panel1: TPanel;
ExtPRO_COD: TDBEdit;
EdtPRO_DES: TDBEdit;
EdtPRO_CUSTO: TDBEdit;
EdtPRO_VENDA: TDBEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
btnGravar: TJvTransparentButton;
btnMaisOpcoes: TJvTransparentButton;
Label6: TLabel;
GroupBox1: TGroupBox;
gIngredientes: TJvDBUltimGrid;
JvTransparentButton1: TJvTransparentButton;
Label5: TLabel;
EdtSaldoEstoque: TJvValidateEdit;
procedure btnGravarClick(Sender: TObject);
procedure btnMaisOpcoesClick(Sender: TObject);
private
FControlador: IResposta;
FProdutoRegistroModelo: TProdutoRegistroModelo;
protected
procedure Excluir;
procedure Inativar;
public
function BindControls: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Descarregar: ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
end;
implementation
{$R *.dfm}
{ TProdutoRegistroView }
function TProdutoRegistroView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FProdutoRegistroModelo := nil;
Result := Self;
end;
function TProdutoRegistroView.Modelo(const Modelo: TModelo): ITela;
begin
Self.FProdutoRegistroModelo := (Modelo as TProdutoRegistroModelo);
Result := Self;
end;
function TProdutoRegistroView.Preparar: ITela;
begin
Result := Self.BindControls;
Self.EdtSaldoEstoque.Value := Self.FProdutoRegistroModelo.retornarSaldoEstoque;
Self.gIngredientes.DataSource := Self.FProdutoRegistroModelo.DataSource('procom');
end;
function TProdutoRegistroView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TProdutoRegistroView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TProdutoRegistroView.BindControls: ITela;
begin
TConectorDeControles.ConectarControles(Self,
Self.FProdutoRegistroModelo.DataSource);
Result := Self;
end;
procedure TProdutoRegistroView.btnGravarClick(Sender: TObject);
begin
if Self.FProdutoRegistroModelo.EhValido then
begin
Self.FProdutoRegistroModelo.Salvar;
Self.ModalResult := mrOk;
end
else
TMessages.MensagemErro('Erro ao incluir produto!');
end;
procedure TProdutoRegistroView.Excluir;
begin
Self.FProdutoRegistroModelo.Excluir;
Self.ModalResult := mrOk;
end;
procedure TProdutoRegistroView.Inativar;
begin
Self.FProdutoRegistroModelo.Inativar;
Self.ModalResult := mrOk;
end;
procedure TProdutoRegistroView.btnMaisOpcoesClick(Sender: TObject);
var
_resposta: string;
_menu: TMenuView;
begin
_menu := TMenuView.Create(nil)
.Legenda('Selecione sua Opção:')
.Mensagem('Aqui você pode excluir ou inativar um produto.')
.AdicionarOpcao('excluir',
'Excluir', 'Excluir um produto já cadastrado.')
.AdicionarOpcao('inativar',
'Inativar', 'Alterar o status de um produto para inativo.');
try
_resposta := _menu.Exibir;
if _resposta = 'excluir' then
Self.Excluir
else
if _resposta = 'inativar' then
Self.Inativar;
finally
FreeAndNil(_menu);
end;
end;
end.
|
unit untConfiguracao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.Mask, Vcl.DBCtrls;
type
TfrmConfiguracao = class(TForm)
pnlRodape: TPanel;
btnGravar: TBitBtn;
btnFechar: TBitBtn;
pnlPrincipal: TPanel;
lblCaminhoFoto: TLabel;
edtCaminhoFoto: TEdit;
GroupBox1: TGroupBox;
edtDescrProduto: TEdit;
btnPesqProduto: TBitBtn;
edtCodProduto: TEdit;
lblProduto: TLabel;
edtCodServico: TEdit;
lblServico: TLabel;
edtCodVet: TEdit;
lblVeterinario: TLabel;
btnPesqVet: TBitBtn;
edtDescrVeterinario: TEdit;
btnPesqServico: TBitBtn;
edtDescrServico: TEdit;
procedure btnFecharClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnPesqVetClick(Sender: TObject);
procedure btnPesqServicoClick(Sender: TObject);
procedure btnPesqProdutoClick(Sender: TObject);
procedure edtCodVetExit(Sender: TObject);
procedure edtCodServicoExit(Sender: TObject);
procedure edtCodProdutoExit(Sender: TObject);
private
{ Private declarations }
procedure CarregaConfiguracao;
public
{ Public declarations }
procedure PesquisaServico(vStatus : boolean);
procedure PesquisaVeterinario(vStatus : boolean);
procedure PesquisaProduto(vStatus : boolean);
end;
var
frmConfiguracao: TfrmConfiguracao;
implementation
{$R *.dfm}
uses untPesquisa, untFuncoes, untDM, untPrincipal;
procedure TfrmConfiguracao.btnFecharClick(Sender: TObject);
begin
close;
end;
procedure TfrmConfiguracao.btnGravarClick(Sender: TObject);
begin
dm.qryConfiguracao.Edit;
dm.qryConfiguracao.FieldByName('veterinario_padrao').AsString := edtCodVet.Text;
dm.qryConfiguracao.FieldByName('produto_inseminacao').AsString := edtCodProduto.Text;
dm.qryConfiguracao.FieldByName('servico_padrao').AsString := edtCodServico.Text;
dm.qryConfiguracao.FieldByName('caminho_foto').AsString := edtCaminhoFoto.Text;
dm.qryConfiguracao.FieldByName('usuario').AsInteger := StrToInt(frmFuncoes.LerArquivoUsuario);
dm.qryConfiguracao.FieldByName('alteracao').AsDateTime := Date+Time;
dm.qryConfiguracao.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
frmFuncoes.Botoes('Gravar', dm.qryConfiguracao);
end;
procedure TfrmConfiguracao.btnPesqProdutoClick(Sender: TObject);
begin
PesquisaProduto(False);
end;
procedure TfrmConfiguracao.btnPesqServicoClick(Sender: TObject);
begin
PesquisaServico(False);
end;
procedure TfrmConfiguracao.btnPesqVetClick(Sender: TObject);
begin
PesquisaVeterinario(False);
end;
procedure TfrmConfiguracao.CarregaConfiguracao;
begin
frmFuncoes.ExecutaSQL('Select * from CONFIGURACAO', 'Abrir', dm.qryConfiguracao);
edtCodVet.Text := dm.qryConfiguracao.FieldByName('veterinario_padrao').AsString;
PesquisaVeterinario(True);
edtCodProduto.Text := dm.qryConfiguracao.FieldByName('produto_inseminacao').AsString;
PesquisaProduto(True);
edtCodServico.Text := dm.qryConfiguracao.FieldByName('servico_padrao').AsString;
PesquisaServico(True);
edtCaminhoFoto.Text := dm.qryConfiguracao.FieldByName('caminho_foto').AsString;
end;
procedure TfrmConfiguracao.edtCodProdutoExit(Sender: TObject);
begin
if edtCodProduto.Text <> '' then
PesquisaProduto(True);
end;
procedure TfrmConfiguracao.edtCodServicoExit(Sender: TObject);
begin
if edtCodServico.Text <> '' then
PesquisaServico(True);
end;
procedure TfrmConfiguracao.edtCodVetExit(Sender: TObject);
begin
if edtCodVet.Text <> '' then
PesquisaVeterinario(True);
end;
procedure TfrmConfiguracao.FormActivate(Sender: TObject);
begin
CarregaConfiguracao;
end;
procedure TfrmConfiguracao.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmConfiguracao.PesquisaProduto(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodProduto.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from PRODUTO where ID = ' + QuotedStr(edtCodProduto.Text), 'Abrir', dm.qryProduto);
if dm.qryProduto.RecordCount > 0 then
begin
edtDescrProduto.Text := dm.qryProduto.FieldByName('DESCRICAO').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodProduto.SetFocus;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'PRODUTO';
frmPesquisa.vComando := 'Select ID, DESCRICAO, UNIDADE, VALOR, ESTOQUE from PRODUTO';
frmPesquisa.vTela := 'CONFIG';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmConfiguracao.PesquisaServico(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodServico.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from SERVICO where ID = ' + QuotedStr(edtCodServico.Text), 'Abrir', DM.qryProprietario);
if DM.qryProprietario.RecordCount > 0 then
begin
edtDescrServico.Text := DM.qryProprietario.FieldByName('DESCRICAO').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodServico.SetFocus;
edtCodServico.Clear;
edtDescrServico.Clear;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'SERVICO';
frmPesquisa.vTela := 'CONFIG';
frmPesquisa.vComando := 'Select ID, DESCRICAO, VALOR from SERVICO ORDER BY DESCRICAO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmConfiguracao.PesquisaVeterinario(vStatus: boolean);
begin
if vStatus = True then
begin
frmFuncoes.ExecutaSQL('Select * from VETERINARIO where ID = ' + QuotedStr(edtCodVet.Text), 'Abrir', DM.qryVeterinario);
if DM.qryVeterinario.RecordCount > 0 then
begin
edtDescrVeterinario.Text := DM.qryVeterinario.FieldByName('nome').AsString;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodVet.SetFocus;
edtCodVet.Clear;
edtDescrVeterinario.Clear;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'VETERINARIO';
frmPesquisa.vTela := 'CONFIG';
frmPesquisa.vComando := 'Select ID, NOME from VETERINARIO ORDER BY NOME';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
end.
|
unit ServerMethodsUnit1;
interface
uses System.SysUtils, System.Classes, System.Json,
Datasnap.DSServer, Datasnap.DSAuth, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
Data.FireDACJSONReflect,
TBGFirebaseConnection.View.Connection;
type
{$METHODINFO ON}
TServerMethods1 = class(TDataModule)
MemData: TFDMemTable;
FDStanStorageBinLink1: TFDStanStorageBinLink;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
FBGFirebase : TTBGFirebaseConnection;
procedure GetTicketsFromFirebase(const ATicket: string = '');
public
{ Public declarations }
function GetTickets(const ATicket : string = ''): TFDJSONDataSets;
end;
{$METHODINFO OFF}
implementation
const
C_BaseURLFirebase = '...';
C_UUID = '...';
C_TICKET = 'tickets';
{$R *.dfm}
procedure TServerMethods1.DataModuleCreate(Sender: TObject);
begin
if not Assigned(FBGFirebase) then
FBGFirebase := TTBGFirebaseConnection.Create;
end;
procedure TServerMethods1.DataModuleDestroy(Sender: TObject);
begin
if Assigned(FBGFirebase) then
FBGFirebase.Free;
end;
function TServerMethods1.GetTicketS(const ATicket: string): TFDJSONDataSets;
begin
MemData.Active := False;
GetTicketsFromFirebase(ATicket);
Result := TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(Result, MemData);
end;
procedure TServerMethods1.GetTicketsFromFirebase(const ATicket: string);
begin
FBGFirebase
.Connect
.BaseURL(C_BaseURLFirebase)
.Auth('anonymous')
.uId(C_UUID)
.&End
.Get
.DataSet(MemData)
.Resource(Format('%s/%s', [C_TICKET, ATicket]))
.&End
.Exec;
end;
end.
|
unit User;
interface
uses
StrUtils, SysUtils, System.Rtti, Classes, Right;
type
TSuperUser = class
strict private
FName: string;
FPasskey: string;
public
property Name: string read FName write FName;
property Passkey: string read FPasskey write FPasskey;
end;
TUser = class
private
FPasskey: string;
FRoleCode: string;
FRights: array of string;
FSuperUser: TSuperUser;
FLastName: string;
FFirstName: string;
FUserId: string;
FCreditLimit: currency;
function GetHasName: boolean;
function GetHasPasskey: boolean;
function GetHasRole: boolean;
function GetIsSuperUser: boolean;
function GetName: string;
public
property Passkey: string read FPasskey write FPasskey;
property RoleCode: string read FRoleCode write FRoleCode;
property HasName: boolean read GetHasName;
property HasPasskey: boolean read GetHasPasskey;
property HasRole: boolean read GetHasRole;
property SuperUser: TSuperUser read FSuperUser write FSuperUser;
property IsSuperUser: boolean read GetIsSuperUser;
property UserId: string read FUserId write FUserId;
property FirstName: string write FFirstName;
property LastName: string write FLastName;
property Name: string read GetName;
property CreditLimit: currency read FCreditLimit write FCreditLimit;
procedure SetRight(const right: string);
procedure AddRight(const code: string);
procedure ClearSuperUser;
function HasRights(const ARights: array of string; const AWarn: boolean = false): boolean;
function ChangePassword(ANewPasskey: AnsiString): Boolean;
constructor Create; overload;
constructor Create(const AName: string); overload;
destructor Destroy; override;
end;
implementation
{ TUser }
uses
DBUtil, IFinanceDialogs;
procedure TUser.AddRight(const code: string);
begin
SetLength(FRights, Length(FRights) + 1);
FRights[Length(FRights) - 1] := code;
end;
function TUser.ChangePassword(ANewPasskey: AnsiString): Boolean;
var
sql: string;
begin
Result := false;
try
sql := 'UPDATE SYSUSER SET PASSWORD = ' + QuotedStr(Trim(ANewPasskey)) +
' WHERE ID_NUM = ' + QuotedStr(FUserId);
ExecuteSQL(sql,true);
Result := true;
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
procedure TUser.ClearSuperUser;
begin
FreeAndNil(FSuperUser);
end;
constructor TUser.Create(const AName: string);
begin
FUserId := AName;
end;
destructor TUser.Destroy;
begin
inherited;
end;
function TUser.GetHasName: boolean;
begin
Result := FUserId <> '';
end;
function TUser.GetHasPasskey: boolean;
begin
Result := FPasskey <> '';
end;
function TUser.GetHasRole: boolean;
begin
Result := RoleCode <> '';
end;
function TUser.GetIsSuperUser: boolean;
begin
Result := Assigned(FSuperUser);
end;
function TUser.GetName: string;
begin
Result := FLastName + ', ' + FFirstName;
end;
constructor TUser.Create;
begin
inherited Create;
end;
function TUser.HasRights(const ARights: array of string;
const AWarn: boolean = false): boolean;
var
sl: TStringList;
i, cnt, rightCnt: integer;
begin
rightCnt := 0;
cnt := Length(ARights) - 1;
for i := 0 to cnt do
begin
sl := TStringList.Create;
sl.Delimiter := ';';
sl.DelimitedText := ARights[i];
if MatchStr(sl[0],FRights) then Inc(rightCnt);
sl.Free;
end;
Result := rightCnt > 0;
if (not Result) and (AWarn) then ShowErrorBox('Access is denied. Please contact system administrator.');
end;
procedure TUser.SetRight(const right: string);
var
len: integer;
begin
len := Length(FRights);
SetLength(FRights, len + 1);
FRights[len] := right;
end;
end.
|
program t_hmack1;
{-HMAC-Keccak known answer tests, WE Nov.2012}
{$i std.inc}
{$ifdef APPCONS}
{$apptype console}
{$endif}
uses
{$ifdef WINCRT} WinCRT, {$endif}
BTypes, mem_util, keccak_n, hmackecc;
var
ctx: THMACKec_Context;
mac: TKeccakMaxDigest;
{Vectors from http://www.di-mgt.com.au/hmac_sha3_testvectors.html}
{---------------------------------------------------------------------------}
procedure test_case_1;
const
key : array[0.. 19] of byte = ($0b,$0b,$0b,$0b,$0b,$0b,$0b,$0b,
$0b,$0b,$0b,$0b,$0b,$0b,$0b,$0b,
$0b,$0b,$0b,$0b);
data: array[0.. 7] of byte = ($48,$69,$20,$54,$68,$65,$72,$65);
d224: array[0.. 27] of byte = ($b7,$3d,$59,$5a,$2b,$a9,$af,$81,
$5e,$9f,$2b,$4e,$53,$e7,$85,$81,
$eb,$d3,$4a,$80,$b3,$bb,$aa,$c4,
$e7,$02,$c4,$cc);
d256: array[0.. 31] of byte = ($96,$63,$d1,$0c,$73,$ee,$29,$40,
$54,$dc,$9f,$af,$95,$64,$7c,$b9,
$97,$31,$d1,$22,$10,$ff,$70,$75,
$fb,$3d,$33,$95,$ab,$fb,$98,$21);
d384: array[0.. 31] of byte = ($89,$2d,$fd,$f5,$d5,$1e,$46,$79,
$bf,$32,$0c,$d1,$6d,$4c,$9d,$c6,
$f7,$49,$74,$46,$08,$e0,$03,$ad,
$d7,$fb,$a8,$94,$ac,$ff,$87,$36);
d512: array[0.. 63] of byte = ($88,$52,$c6,$3b,$e8,$cf,$c2,$15,
$41,$a4,$ee,$5e,$5a,$9a,$85,$2f,
$c2,$f7,$a9,$ad,$ec,$2f,$f3,$a1,
$37,$18,$ab,$4e,$d8,$1a,$ae,$a0,
$b8,$7b,$7e,$b3,$97,$32,$35,$48,
$e2,$61,$a6,$4e,$7f,$c7,$51,$98,
$f6,$66,$3a,$11,$b2,$2c,$d9,$57,
$f7,$c8,$ec,$85,$8a,$1c,$77,$55);
begin
writeln('Test case 1:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_2;
const
key : array[0.. 3] of byte = ($4a,$65,$66,$65);
data: array[0.. 27] of byte = ($77,$68,$61,$74,$20,$64,$6f,$20,
$79,$61,$20,$77,$61,$6e,$74,$20,
$66,$6f,$72,$20,$6e,$6f,$74,$68,
$69,$6e,$67,$3f);
d224: array[0.. 27] of byte = ($e8,$24,$fe,$c9,$6c,$07,$4f,$22,
$f9,$92,$35,$bb,$94,$2d,$a1,$98,
$26,$64,$ab,$69,$2c,$a8,$50,$10,
$53,$cb,$d4,$14);
d256: array[0.. 31] of byte = ($aa,$9a,$ed,$44,$8c,$7a,$bc,$8b,
$5e,$32,$6f,$fa,$6a,$01,$cd,$ed,
$f7,$b4,$b8,$31,$88,$14,$68,$c0,
$44,$ba,$8d,$d4,$56,$63,$69,$a1);
d384: array[0.. 47] of byte = ($5a,$f5,$c9,$a7,$7a,$23,$a6,$a9,
$3d,$80,$64,$9e,$56,$2a,$b7,$7f,
$4f,$35,$52,$e3,$c5,$ca,$ff,$d9,
$3b,$df,$8b,$3c,$fc,$69,$20,$e3,
$02,$3f,$c2,$67,$75,$d9,$df,$1f,
$3c,$94,$61,$31,$46,$ad,$2c,$9d);
d512: array[0.. 63] of byte = ($c2,$96,$2e,$5b,$be,$12,$38,$00,
$78,$52,$f7,$9d,$81,$4d,$bb,$ec,
$d4,$68,$2e,$6f,$09,$7d,$37,$a3,
$63,$58,$7c,$03,$bf,$a2,$eb,$08,
$59,$d8,$d9,$c7,$01,$e0,$4c,$ec,
$ec,$fd,$3d,$d7,$bf,$d4,$38,$f2,
$0b,$8b,$64,$8e,$01,$bf,$8c,$11,
$d2,$68,$24,$b9,$6c,$eb,$bd,$cb);
begin
writeln('Test case 2:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_3;
const
key : array[0.. 19] of byte = ($aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa);
data: array[0.. 49] of byte = ($dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd,$dd,$dd,$dd,$dd,$dd,$dd,
$dd,$dd);
d224: array[0.. 27] of byte = ($77,$0d,$f3,$8c,$99,$d6,$e2,$ba,
$cd,$68,$05,$6d,$cf,$e0,$7d,$4c,
$89,$ae,$20,$b2,$68,$6a,$61,$85,
$e1,$fa,$a4,$49);
d256: array[0.. 31] of byte = ($95,$f4,$3e,$50,$f8,$df,$80,$a2,
$19,$77,$d5,$1a,$8d,$b3,$ba,$57,
$2d,$cd,$71,$db,$24,$68,$7e,$6f,
$86,$f4,$7c,$11,$39,$b2,$62,$60);
d384: array[0.. 47] of byte = ($42,$43,$c2,$9f,$22,$01,$99,$2f,
$f9,$64,$41,$e3,$b9,$1f,$f8,$1d,
$8c,$60,$1d,$70,$6f,$bc,$83,$25,
$26,$84,$a4,$bc,$51,$10,$1c,$a9,
$b2,$c0,$6d,$dd,$03,$67,$73,$03,
$c5,$02,$ac,$53,$31,$75,$2a,$3c);
d512: array[0.. 63] of byte = ($eb,$0e,$d9,$58,$0e,$0e,$c1,$1f,
$c6,$6c,$bb,$64,$6b,$1b,$e9,$04,
$ea,$ff,$6d,$a4,$55,$6d,$93,$34,
$f6,$5e,$e4,$b2,$c8,$57,$39,$15,
$7b,$ae,$90,$27,$c5,$15,$05,$e4,
$9d,$1b,$b8,$1c,$fa,$55,$e6,$82,
$2d,$b5,$52,$62,$d5,$a2,$52,$c0,
$88,$a2,$9a,$5e,$95,$b8,$4a,$66);
begin
writeln('Test case 3:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_4;
const
key : array[0.. 24] of byte = ($01,$02,$03,$04,$05,$06,$07,$08,
$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,
$11,$12,$13,$14,$15,$16,$17,$18,
$19);
data: array[0.. 49] of byte = ($cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd,$cd,$cd,$cd,$cd,$cd,$cd,
$cd,$cd);
d224: array[0.. 27] of byte = ($30,$5a,$8f,$2d,$fb,$94,$ba,$d2,
$88,$61,$a0,$3c,$bc,$4d,$59,$0f,
$eb,$e7,$75,$c5,$8c,$b4,$96,$1c,
$28,$42,$8a,$0b);
d256: array[0.. 31] of byte = ($63,$31,$ba,$9b,$4a,$f5,$80,$4a,
$68,$72,$5b,$36,$63,$eb,$74,$81,
$44,$94,$b6,$3c,$60,$93,$e3,$5f,
$b3,$20,$a8,$5d,$50,$79,$36,$fd);
d384: array[0.. 47] of byte = ($b7,$30,$72,$4d,$3d,$40,$90,$cd,
$a1,$be,$79,$9f,$63,$ac,$bb,$e3,
$89,$fe,$f7,$79,$2f,$c1,$86,$76,
$fa,$54,$53,$aa,$b3,$98,$66,$46,
$50,$ed,$02,$9c,$34,$98,$bb,$e8,
$05,$6f,$06,$c6,$58,$e1,$e6,$93);
d512: array[0.. 63] of byte = ($b4,$61,$93,$bb,$59,$f4,$f6,$96,
$bf,$70,$25,$97,$61,$6d,$a9,$1e,
$2a,$45,$58,$a5,$93,$f4,$b0,$15,
$e6,$91,$41,$ba,$81,$e1,$e5,$0e,
$a5,$80,$83,$4c,$2b,$87,$f8,$7b,
$aa,$25,$a3,$a0,$3b,$fc,$9b,$b3,
$89,$84,$7f,$2d,$c8,$20,$be,$ae,
$69,$d3,$0c,$4b,$b7,$53,$69,$cb);
begin
writeln('Test case 4:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_5;
const
key : array[0.. 19] of byte = ($0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,
$0c,$0c,$0c,$0c,$0c,$0c,$0c,$0c,
$0c,$0c,$0c,$0c);
data: array[0.. 19] of byte = ($54,$65,$73,$74,$20,$57,$69,$74,
$68,$20,$54,$72,$75,$6e,$63,$61,
$74,$69,$6f,$6e);
d224: array[0.. 15] of byte = ($f5,$2b,$bc,$fd,$65,$42,$64,$e7,
$13,$30,$85,$c5,$e6,$9b,$72,$c3);
d256: array[0.. 15] of byte = ($74,$5e,$7e,$68,$7f,$83,$35,$28,
$0d,$54,$20,$2e,$f1,$3c,$ec,$c6);
d384: array[0.. 15] of byte = ($fa,$9a,$ea,$2b,$c1,$e1,$81,$e4,
$7c,$bb,$8c,$3d,$f2,$43,$81,$4d);
d512: array[0.. 15] of byte = ($04,$c9,$29,$fe,$ad,$43,$4b,$ba,
$19,$0d,$ac,$fa,$55,$4c,$e3,$f5);
begin
writeln('Test case 5:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_6;
const
key : array[0..130] of byte = ($aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa);
data: array[0.. 53] of byte = ($54,$65,$73,$74,$20,$55,$73,$69,
$6e,$67,$20,$4c,$61,$72,$67,$65,
$72,$20,$54,$68,$61,$6e,$20,$42,
$6c,$6f,$63,$6b,$2d,$53,$69,$7a,
$65,$20,$4b,$65,$79,$20,$2d,$20,
$48,$61,$73,$68,$20,$4b,$65,$79,
$20,$46,$69,$72,$73,$74);
d224: array[0.. 27] of byte = ($e7,$a5,$2d,$fa,$45,$f9,$5a,$21,
$7c,$10,$00,$66,$b2,$39,$aa,$8a,
$d5,$19,$be,$9b,$35,$d6,$67,$26,
$8b,$1b,$57,$ff);
d256: array[0.. 31] of byte = ($b4,$d0,$cd,$ee,$7e,$c2,$ba,$81,
$a8,$8b,$86,$91,$89,$58,$31,$23,
$00,$a1,$56,$22,$37,$79,$29,$a0,
$54,$a9,$ce,$3a,$e1,$fa,$c2,$b6);
d384: array[0.. 47] of byte = ($d6,$24,$82,$ef,$60,$1d,$78,$47,
$43,$9b,$55,$23,$6e,$96,$79,$38,
$8f,$fc,$d5,$3c,$62,$cd,$12,$6f,
$39,$be,$6e,$a6,$3d,$e7,$62,$e2,
$6c,$d5,$97,$4c,$b9,$a8,$de,$40,
$1b,$78,$6b,$55,$55,$04,$0f,$6f);
d512: array[0.. 63] of byte = ($d0,$58,$88,$a6,$eb,$f8,$46,$04,
$23,$ea,$7b,$c8,$5e,$a4,$ff,$da,
$84,$7b,$32,$df,$32,$29,$1d,$2c,
$e1,$15,$fd,$18,$77,$07,$32,$5c,
$7c,$e4,$f7,$18,$80,$d9,$10,$08,
$08,$4c,$e2,$4a,$38,$79,$5d,$20,
$e6,$a2,$83,$28,$a0,$f0,$71,$2d,
$c3,$82,$53,$37,$0d,$a3,$eb,$b5);
begin
writeln('Test case 6:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_6a;
const
key : array[0..146] of byte = ($aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa);
data: array[0.. 53] of byte = ($54,$65,$73,$74,$20,$55,$73,$69,
$6e,$67,$20,$4c,$61,$72,$67,$65,
$72,$20,$54,$68,$61,$6e,$20,$42,
$6c,$6f,$63,$6b,$2d,$53,$69,$7a,
$65,$20,$4b,$65,$79,$20,$2d,$20,
$48,$61,$73,$68,$20,$4b,$65,$79,
$20,$46,$69,$72,$73,$74);
d224: array[0.. 27] of byte = ($4d,$c9,$ce,$18,$32,$81,$ce,$75,
$1b,$fc,$55,$66,$7c,$07,$4a,$07,
$7e,$07,$51,$bf,$40,$c5,$3f,$9e,
$6a,$83,$25,$0f);
d256: array[0.. 31] of byte = ($ea,$68,$d6,$57,$1d,$cb,$46,$69,
$fd,$97,$c5,$95,$32,$69,$c7,$41,
$26,$a1,$02,$b1,$f9,$7a,$f6,$bd,
$ba,$55,$33,$cd,$e5,$1e,$8a,$cc);
d384: array[0.. 47] of byte = ($0c,$08,$17,$f7,$4b,$18,$2b,$ae,
$b9,$33,$e4,$e7,$07,$4a,$0c,$b1,
$c6,$19,$dc,$e7,$f1,$15,$49,$ec,
$95,$05,$d2,$d6,$c8,$29,$59,$d4,
$51,$bd,$31,$65,$4f,$58,$eb,$d5,
$69,$ac,$63,$23,$dc,$62,$d4,$08);
d512: array[0.. 63] of byte = ($0f,$01,$da,$58,$d5,$2a,$7e,$4e,
$f3,$38,$6b,$f7,$ed,$b6,$66,$25,
$ff,$5c,$25,$38,$5c,$38,$87,$d3,
$ac,$99,$18,$c0,$82,$8b,$a8,$0c,
$0d,$b2,$de,$5b,$ca,$33,$98,$f9,
$69,$4f,$7f,$d5,$15,$35,$20,$3a,
$9e,$1f,$73,$ac,$4d,$90,$19,$38,
$3b,$55,$20,$bc,$26,$d2,$d6,$54);
begin
writeln('Test case 6a:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_7;
const
key : array[0..130] of byte = ($aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa);
data: array[0..151] of byte = ($54,$68,$69,$73,$20,$69,$73,$20,
$61,$20,$74,$65,$73,$74,$20,$75,
$73,$69,$6e,$67,$20,$61,$20,$6c,
$61,$72,$67,$65,$72,$20,$74,$68,
$61,$6e,$20,$62,$6c,$6f,$63,$6b,
$2d,$73,$69,$7a,$65,$20,$6b,$65,
$79,$20,$61,$6e,$64,$20,$61,$20,
$6c,$61,$72,$67,$65,$72,$20,$74,
$68,$61,$6e,$20,$62,$6c,$6f,$63,
$6b,$2d,$73,$69,$7a,$65,$20,$64,
$61,$74,$61,$2e,$20,$54,$68,$65,
$20,$6b,$65,$79,$20,$6e,$65,$65,
$64,$73,$20,$74,$6f,$20,$62,$65,
$20,$68,$61,$73,$68,$65,$64,$20,
$62,$65,$66,$6f,$72,$65,$20,$62,
$65,$69,$6e,$67,$20,$75,$73,$65,
$64,$20,$62,$79,$20,$74,$68,$65,
$20,$48,$4d,$41,$43,$20,$61,$6c,
$67,$6f,$72,$69,$74,$68,$6d,$2e);
d224: array[0.. 27] of byte = ($ba,$13,$00,$94,$05,$a9,$29,$f3,
$98,$b3,$48,$88,$5c,$aa,$54,$19,
$19,$1b,$b9,$48,$ad,$a3,$21,$94,
$af,$c8,$41,$04);
d256: array[0.. 31] of byte = ($1f,$dc,$8c,$b4,$e2,$7d,$07,$c1,
$0d,$89,$7d,$ec,$39,$c2,$17,$79,
$2a,$6e,$64,$fa,$9c,$63,$a7,$7c,
$e4,$2a,$d1,$06,$ef,$28,$4e,$02);
d384: array[0.. 47] of byte = ($48,$60,$ea,$19,$1a,$c3,$49,$94,
$cf,$88,$95,$7a,$fe,$5a,$83,$6e,
$f3,$6e,$4c,$c1,$a6,$6d,$75,$bf,
$77,$de,$fb,$75,$76,$12,$2d,$75,
$f6,$06,$60,$e4,$cf,$73,$1c,$6e,
$ff,$ac,$06,$40,$27,$87,$e2,$b9);
d512: array[0.. 63] of byte = ($2c,$6b,$97,$48,$d3,$5c,$4c,$8d,
$b0,$b4,$40,$7d,$d2,$ed,$23,$81,
$f1,$33,$bd,$bd,$1d,$fa,$a6,$9e,
$30,$05,$1e,$b6,$ba,$df,$cc,$a6,
$42,$99,$b8,$8a,$e0,$5f,$db,$d3,
$dd,$3d,$d7,$fe,$62,$7e,$42,$e3,
$9e,$48,$b0,$fe,$8c,$7f,$1e,$85,
$f2,$db,$d5,$2c,$2d,$75,$35,$72);
begin
writeln('Test case 7:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
{---------------------------------------------------------------------------}
procedure test_case_7a;
const
key : array[0..146] of byte = ($aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa,$aa,$aa,$aa,$aa,$aa,
$aa,$aa,$aa);
data: array[0..151] of byte = ($54,$68,$69,$73,$20,$69,$73,$20,
$61,$20,$74,$65,$73,$74,$20,$75,
$73,$69,$6e,$67,$20,$61,$20,$6c,
$61,$72,$67,$65,$72,$20,$74,$68,
$61,$6e,$20,$62,$6c,$6f,$63,$6b,
$2d,$73,$69,$7a,$65,$20,$6b,$65,
$79,$20,$61,$6e,$64,$20,$61,$20,
$6c,$61,$72,$67,$65,$72,$20,$74,
$68,$61,$6e,$20,$62,$6c,$6f,$63,
$6b,$2d,$73,$69,$7a,$65,$20,$64,
$61,$74,$61,$2e,$20,$54,$68,$65,
$20,$6b,$65,$79,$20,$6e,$65,$65,
$64,$73,$20,$74,$6f,$20,$62,$65,
$20,$68,$61,$73,$68,$65,$64,$20,
$62,$65,$66,$6f,$72,$65,$20,$62,
$65,$69,$6e,$67,$20,$75,$73,$65,
$64,$20,$62,$79,$20,$74,$68,$65,
$20,$48,$4d,$41,$43,$20,$61,$6c,
$67,$6f,$72,$69,$74,$68,$6d,$2e);
d224: array[0.. 27] of byte = ($92,$64,$94,$68,$be,$23,$6c,$3c,
$72,$c1,$89,$90,$9c,$06,$3b,$13,
$f9,$94,$be,$05,$74,$9d,$c9,$13,
$10,$db,$63,$9e);
d256: array[0.. 31] of byte = ($fd,$aa,$10,$a0,$29,$9a,$ec,$ff,
$9b,$b4,$11,$cf,$2d,$77,$48,$a4,
$02,$2e,$4a,$26,$be,$3f,$b5,$b1,
$1b,$33,$d8,$c2,$b7,$ef,$54,$84);
d384: array[0.. 47] of byte = ($fe,$93,$57,$e3,$cf,$a5,$38,$eb,
$03,$73,$a2,$ce,$8f,$1e,$26,$ad,
$65,$90,$af,$da,$f2,$66,$f1,$30,
$05,$22,$e8,$89,$6d,$27,$e7,$3f,
$65,$4d,$06,$31,$c8,$fa,$59,$8d,
$4b,$b8,$2a,$f6,$b7,$44,$f4,$f5);
d512: array[0.. 63] of byte = ($6a,$dc,$50,$2f,$14,$e2,$78,$12,
$40,$2f,$c8,$1a,$80,$7b,$28,$bf,
$8a,$53,$c8,$7b,$ea,$7a,$1d,$f6,
$25,$6b,$f6,$6f,$5d,$e1,$a4,$cb,
$74,$14,$07,$ad,$15,$ab,$8a,$bc,
$13,$68,$46,$05,$7f,$88,$19,$69,
$fb,$b1,$59,$c3,$21,$c9,$04,$bf,
$b5,$57,$b7,$7a,$fb,$77,$78,$c8);
begin
writeln('Test case 7a:');
hmac_keccak_init(ctx, 224, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-224: ', compmem(@mac, @d224, sizeof(d224)));
hmac_keccak_init(ctx, 256, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-256: ', compmem(@mac, @d256, sizeof(d256)));
hmac_keccak_init(ctx, 384, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-384: ', compmem(@mac, @d384, sizeof(d384)));
hmac_keccak_init(ctx, 512, @key, sizeof(key));
hmac_keccak_update(ctx, @data, sizeof(data));
hmac_keccak_final(ctx, mac);
writeln(' HMAC-Keccak-512: ', compmem(@mac, @d512, sizeof(d512)));
end;
begin
writeln('HMAC-Keccak tests using David Ireland''s "Test vectors for HMAC-SHA-3"');
test_case_1;
test_case_2;
test_case_3;
test_case_4;
test_case_5;
test_case_6;
test_case_6a;
test_case_7;
test_case_7a;
end.
|
program EARTHSHAKERMODE;
const
arrayLength = 16;
var
inputArray : array [1..arrayLength] of char;
i: integer;
firstIndex, lastIndex : integer;
tempValue: char;
begin
randomize;
writeln ('Исходный массив: ');
for i := 1 to arrayLength do
begin
inputArray[i] := chr(random(100));
write (ord(inputArray[i]):4);
end;
writeln;
firstIndex := 1;
lastIndex := arrayLength;
while firstIndex < lastIndex do
begin
for i:= firstIndex to lastIndex-1 do
if ord(inputArray[i]) > ord(inputArray[i+1]) then
begin
tempValue := inputArray[i];
inputArray[i] := inputArray[i+1];
inputArray[i+1] := tempValue;
end;
for i:= lastIndex downto firstIndex+1 do
if ord(inputArray[i]) < ord(inputArray[i-1]) then
begin
tempValue := inputArray[i];
inputArray[i] := inputArray[i-1];
inputArray[i-1] := tempValue;
end;
firstIndex := firstIndex + 1;
lastIndex := lastIndex - 1;
end;
writeln ('Отсортированный массив: ');
for i := 1 to arrayLength do
write(ord(inputArray[i]):4);
end. |
unit UnitFormWorkLogRecords;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ExtCtrls;
type
TFormWorkLogRecords = class(TForm)
StringGrid1: TStringGrid;
Panel1: TPanel;
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure FormResize(Sender: TObject);
procedure StringGrid1DblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure setup;
end;
var
FormWorkLogRecords: TFormWorkLogRecords;
implementation
{$R *.dfm}
uses stringgridutils, dateutils, UnitAToolMainForm, Thrift.Collections,
apitypes, UnitApiClient;
procedure TFormWorkLogRecords.setup;
var
xs: IThriftList<IWorkLogRecord>;
i: Integer;
X: IWorkLogRecord;
begin
xs := CurrFileClient.listWorkLogRecords;
if xs.Count = 0 then
begin
Panel1.Show;
StringGrid1.Hide;
Show;
exit;
end;
Panel1.Hide;
StringGrid1.Show;
StringGrid_Clear(StringGrid1);
with StringGrid1 do
begin
RowCount := xs.Count;
for i := 0 to xs.Count - 1 do
begin
X := xs[i];
Cells[0, i] := X.StrtedAt;
Cells[1, i] := X.CompletedAt;
Cells[2, i] := X.WorkName;
end;
end;
FormResize(self);
Show;
end;
procedure TFormWorkLogRecords.FormResize(Sender: TObject);
begin
with StringGrid1 do
begin
ColWidths[2] := self.ClientWidth - 50 - ColWidths[1] - ColWidths[0];
end;
end;
procedure TFormWorkLogRecords.StringGrid1DblClick(Sender: TObject);
var
t1, t2: TDateTime;
begin
try
with StringGrid1 do
begin
t1 := ISO8601ToDate(Cells[0, Row], false);
t2 := ISO8601ToDate(Cells[1, Row], false);
end;
except
exit;
end;
AToolMainForm.SetupChartsXAxisOrder(t1, t2);
end;
procedure TFormWorkLogRecords.StringGrid1DrawCell(Sender: TObject;
ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
grd: TStringGrid;
cnv: TCanvas;
ta: TAlignment;
AText: string;
floatValue: double;
begin
grd := StringGrid1;
cnv := grd.Canvas;
cnv.Brush.Color := clWhite;
cnv.Font.Assign(grd.Font);
AText := grd.Cells[ACol, ARow];
if (gdSelected in State) then
begin
cnv.Brush.Color := clGradientInactiveCaption;
end;
ta := taCenter;
if ACol = 2 then
begin
ta := taLeftJustify;
cnv.Font.Color := clNavy;
end;
if ACol in [0, 1] then
begin
AText := FormatDateTime('dd.MM.yy hh:nn', ISO8601ToDate(AText, false));
cnv.Font.Color := clGreen;
end;
StringGrid_DrawCellText(StringGrid1, ACol, ARow, Rect, ta, AText);
StringGrid_DrawCellBounds(cnv, ACol, ARow, Rect);
end;
end.
|
// /////////////////////////////////////////////////////////////////////////////
//
// NetCom7 Package
//
// This unit implements a TncLine, which is all the WinSock API commands for a
// socket, organised in an object which contains the handle of the socket,
// and also makes sure it checks every API command for errors
//
// 9/8/2020
// - Completed multiplatform support, now NetCom can be compiled in all
// platforms
// - Made custom fdset manipulation so that our sockets can handle more than
// 1024 concurrent connections in Linux/Mac/Android!
// See Readable function for implementation
//
// 8/8/2020
// - Created this unit by breaking the code from ncSockets where it was
// initially situated
// - Increased number of concurrent conections from 65536 to infinite
// (to as much memory as the computer has)
// - Added Win64 support
//
// Written by Demos Bill
//
// /////////////////////////////////////////////////////////////////////////////
unit ncLines;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows, Winapi.Winsock2,
{$ELSE}
Posix.SysTypes, Posix.SysSelect, Posix.SysSocket, Posix.NetDB, Posix.SysTime,
Posix.Unistd, {Posix.ArpaInet,}
{$ENDIF}
System.SyncObjs,
System.Math,
System.SysUtils,
System.Diagnostics;
const
// Flag that indicates that the socket is intended for bind() + listen() when constructing it
AI_PASSIVE = 1;
{$IFDEF MSWINDOWS}
InvalidSocket = Winapi.Winsock2.INVALID_SOCKET;
SocketError = SOCKET_ERROR;
{$ELSE}
InvalidSocket = -1;
SocketError = -1;
IPPROTO_TCP = 6;
TCP_NODELAY = $0001;
{$ENDIF}
type
{$IFDEF MSWINDOWS}
TSocketHandle = Winapi.Winsock2.TSocket;
{$ELSE}
TSocketHandle = Integer;
{$ENDIF}
TSocketHandleArray = array of TSocketHandle;
EncLineException = class(Exception);
TncLine = class; // Forward declaration
TncLineOnConnectDisconnect = procedure(aLine: TncLine) of object;
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TncLine
// Bring in all functionality from WinSock API, with appropriate exception raising on errors
TncLine = class(TObject)
private
FActive: Boolean;
FLastSent: Int64;
FLastReceived: Int64;
FPeerIP: string;
FDataObject: TObject;
FOnConnected: TncLineOnConnectDisconnect;
FOnDisconnected: TncLineOnConnectDisconnect;
private
PropertyLock: TCriticalSection;
FHandle: TSocketHandle;
procedure SetConnected;
procedure SetDisconnected;
function GetLastReceived: Int64;
function GetLastSent: Int64;
procedure SetLastReceived(const Value: Int64);
procedure SetLastSent(const Value: Int64);
protected
function CreateLineObject: TncLine; virtual;
procedure Check(aCmdRes: Integer); inline;
// API functions
procedure CreateClientHandle(const aHost: string; const aPort: Integer);
procedure CreateServerHandle(const aPort: Integer);
procedure DestroyHandle;
function AcceptLine: TncLine; inline;
function SendBuffer(const aBuf; aLen: Integer): Integer; inline;
function RecvBuffer(var aBuf; aLen: Integer): Integer; inline;
procedure EnableNoDelay; inline;
procedure EnableKeepAlive; inline;
procedure EnableReuseAddress; inline;
property OnConnected: TncLineOnConnectDisconnect read FOnConnected write FOnConnected;
property OnDisconnected: TncLineOnConnectDisconnect read FOnDisconnected write FOnDisconnected;
public
constructor Create; overload; virtual;
destructor Destroy; override;
property Handle: TSocketHandle read FHandle;
property Active: Boolean read FActive;
property LastSent: Int64 read GetLastSent write SetLastSent;
property LastReceived: Int64 read GetLastReceived write SetLastReceived;
property PeerIP: string read FPeerIP;
property DataObject: TObject read FDataObject write FDataObject;
end;
function Readable(const aSocketHandleArray: TSocketHandleArray; const aTimeout: Cardinal): TSocketHandleArray;
function ReadableAnySocket(const aSocketHandleArray: TSocketHandleArray; const aTimeout: Cardinal): Boolean; inline;
implementation
// Readable checks to see if any socket handles have data
// and if so, overwrites aReadFDS with the data
function Readable(const aSocketHandleArray: TSocketHandleArray; const aTimeout: Cardinal): TSocketHandleArray;
{$IFDEF MSWINDOWS}
var
TimeoutValue: timeval;
FDSetPtr: PFdSet;
SocketArrayLength, SocketArrayBytes: Integer;
begin
TimeoutValue.tv_sec := aTimeout div 1000;
TimeoutValue.tv_usec := (aTimeout mod 1000) * 1000;
SocketArrayLength := Length(aSocketHandleArray);
SocketArrayBytes := SocketArrayLength * SizeOf(TSocketHandle);
// + 32 is there in case of compiler record field aligning
GetMem(FDSetPtr, SizeOf(FDSetPtr^.fd_count) + SocketArrayBytes + 32);
try
FDSetPtr^.fd_count := SocketArrayLength;
move(aSocketHandleArray[0], FDSetPtr^.fd_array[0], SocketArrayBytes);
Select(0, FDSetPtr, nil, nil, @TimeoutValue);
if FDSetPtr^.fd_count > 0 then
begin
SetLength(Result, FDSetPtr^.fd_count);
move(FDSetPtr^.fd_array[0], Result[0], FDSetPtr^.fd_count * SizeOf(TSocketHandle));
end
else
SetLength(Result, 0); // This is needed with newer compilers
finally
FreeMem(FDSetPtr);
end;
end;
{$ELSE}
var
TimeoutValue: timeval;
i: Integer;
SocketHandle: TSocketHandle;
FDSetPtr: Pfd_set;
FDArrayLen, FDNdx, ReadySockets, ResultNdx: Integer;
begin
TimeoutValue.tv_sec := aTimeout div 1000;
TimeoutValue.tv_usec := (aTimeout mod 1000) * 1000;
// Find max socket handle
SocketHandle := 0;
for i := 0 to High(aSocketHandleArray) do
if SocketHandle < aSocketHandleArray[i] then
SocketHandle := aSocketHandleArray[i];
// NFDBITS is SizeOf(fd_mask) in bits (i.e. SizeOf(fd_mask) * 8))
FDArrayLen := SocketHandle div NFDBITS + 1;
GetMem(FDSetPtr, FDArrayLen * SizeOf(fd_mask));
try
FillChar(FDSetPtr^.fds_bits[0], FDArrayLen * SizeOf(fd_mask), 0);
for i := 0 to High(aSocketHandleArray) do
begin
SocketHandle := aSocketHandleArray[i];
FDNdx := SocketHandle div NFDBITS;
FDSetPtr.fds_bits[FDNdx] := FDSetPtr.fds_bits[FDNdx] or (1 shl (SocketHandle mod NFDBITS));
end;
ReadySockets := Select(FDArrayLen * NFDBITS, FDSetPtr, nil, nil, @TimeoutValue);
if ReadySockets > 0 then
begin
SetLength(Result, ReadySockets);
ResultNdx := 0;
for i := 0 to High(aSocketHandleArray) do
begin
SocketHandle := aSocketHandleArray[i];
FDNdx := SocketHandle div NFDBITS;
if FDSetPtr.fds_bits[FDNdx] and (1 shl (SocketHandle mod NFDBITS)) <> 0 then
begin
Result[ResultNdx] := SocketHandle;
ResultNdx := ResultNdx + 1;
end;
end;
end
else
SetLength(Result, 0);
finally
FreeMem(FDSetPtr);
end;
end;
{$ENDIF}
function ReadableAnySocket(const aSocketHandleArray: TSocketHandleArray; const aTimeout: Cardinal): Boolean;
begin
Result := Length(Readable(aSocketHandleArray, aTimeout)) > 0;
end;
{$IFDEF MSWINDOWS}
type
PAddrInfoW = ^TAddrInfoW;
PPAddrInfoW = ^PAddrInfoW;
TAddrInfoW = record
ai_flags: Integer;
ai_family: Integer;
ai_socktype: Integer;
ai_protocol: Integer;
ai_addrlen: ULONG; // is NativeUInt
ai_canonname: PWideChar;
ai_addr: PSOCKADDR;
ai_next: PAddrInfoW;
end;
TGetAddrInfoW = function(NodeName: PWideChar; ServiceName: PWideChar; Hints: PAddrInfoW; ppResult: PPAddrInfoW): Integer; stdcall;
TFreeAddrInfoW = procedure(ai: PAddrInfoW); stdcall;
var
DllGetAddrInfo: TGetAddrInfoW = nil;
DllFreeAddrInfo: TFreeAddrInfoW = nil;
procedure GetAddressInfo(NodeName: PWideChar; ServiceName: PWideChar; Hints: PAddrInfoW; ppResult: PPAddrInfoW);
var
iRes: Integer;
begin
if LowerCase(string(NodeName)) = 'localhost' then
NodeName := '127.0.0.1';
iRes := DllGetAddrInfo(NodeName, ServiceName, Hints, ppResult);
if iRes <> 0 then
raise EncLineException.Create(SysErrorMessage(iRes));
end;
procedure FreeAddressInfo(ai: PAddrInfoW);
begin
DllFreeAddrInfo(ai);
end;
{$ENDIF}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{ TncLine }
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
constructor TncLine.Create;
begin
inherited Create;
PropertyLock := TCriticalSection.Create;
FHandle := InvalidSocket;
FActive := False;
FLastSent := TStopWatch.GetTimeStamp;
FLastReceived := FLastSent;
FPeerIP := '127.0.0.1';
FDataObject := nil;
FOnConnected := nil;
FOnDisconnected := nil;
end;
destructor TncLine.Destroy;
begin
if FActive then
DestroyHandle;
PropertyLock.Free;
inherited Destroy;
end;
function TncLine.CreateLineObject: TncLine;
begin
Result := TncLine.Create;
end;
/// /////////////////////////////////////////////////////////////////////////////
procedure TncLine.Check(aCmdRes: Integer);
begin
if aCmdRes = SocketError then
{$IFDEF MSWINDOWS}
raise EncLineException.Create(SysErrorMessage(WSAGetLastError));
{$ELSE}
raise EncLineException.Create(SysErrorMessage(GetLastError));
{$ENDIF}
end;
procedure TncLine.CreateClientHandle(const aHost: string; const aPort: Integer);
var
{$IFDEF MSWINDOWS}
Hints: TAddrInfoW;
AddrResult: PAddrInfoW;
{$ELSE}
Hints: addrinfo;
AddrResult: Paddrinfo;
AnsiHost, AnsiPort: RawByteString;
{$ENDIF}
begin
try
FillChar(Hints, SizeOf(Hints), 0);
Hints.ai_family := AF_INET;
Hints.ai_socktype := SOCK_STREAM;
Hints.ai_protocol := IPPROTO_TCP;
// Resolve the server address and port
{$IFDEF MSWINDOWS}
GetAddressInfo(PChar(aHost), PChar(IntToStr(aPort)), @Hints, @AddrResult);
{$ELSE}
AnsiHost := RawByteString(aHost);
AnsiPort := RawByteString(IntToStr(aPort));
GetAddrInfo(MarshaledAString(AnsiHost), MarshaledAString(AnsiPort), Hints, AddrResult);
{$ENDIF}
try
// Create a SOCKET for connecting to server
FHandle := Socket(AddrResult^.ai_family, AddrResult^.ai_socktype, AddrResult^.ai_protocol);
Check(FHandle);
try
{$IFNDEF MSWINDOWS}
EnableReuseAddress;
{$ENDIF}
// Connect to server
Check(Connect(FHandle, AddrResult^.ai_addr^, AddrResult^.ai_addrlen));
SetConnected;
except
DestroyHandle;
raise;
end;
finally
{$IFDEF MSWINDOWS}
FreeAddressInfo(AddrResult);
{$ELSE}
freeaddrinfo(AddrResult^);
{$ENDIF}
end;
except
FHandle := InvalidSocket;
raise;
end;
end;
procedure TncLine.CreateServerHandle(const aPort: Integer);
var
{$IFDEF MSWINDOWS}
Hints: TAddrInfoW;
AddrResult: PAddrInfoW;
{$ELSE}
Hints: addrinfo;
AddrResult: Paddrinfo;
AnsiPort: RawByteString;
{$ENDIF}
begin
FillChar(Hints, SizeOf(Hints), 0);
Hints.ai_family := AF_INET;
Hints.ai_socktype := SOCK_STREAM;
Hints.ai_protocol := IPPROTO_TCP;
Hints.ai_flags := AI_PASSIVE; // Inform GetAddrInfo to return a server socket
// Resolve the server address and port
{$IFDEF MSWINDOWS}
GetAddressInfo(nil, PChar(IntToStr(aPort)), @Hints, @AddrResult);
{$ELSE}
AnsiPort := RawByteString(IntToStr(aPort));
GetAddrInfo(nil, MarshaledAString(AnsiPort), Hints, AddrResult);
{$ENDIF}
try
// Create a server listener socket
FHandle := Socket(AddrResult^.ai_family, AddrResult^.ai_socktype, AddrResult^.ai_protocol);
Check(FHandle);
try
{$IFNDEF MSWINDOWS}
EnableReuseAddress;
{$ENDIF}
// Setup the TCP listening socket
Check(Bind(FHandle, AddrResult^.ai_addr^, AddrResult^.ai_addrlen));
Check(Listen(FHandle, SOMAXCONN));
SetConnected;
except
DestroyHandle;
raise;
end;
finally
{$IFDEF MSWINDOWS}
FreeAddressInfo(AddrResult);
{$ELSE}
freeaddrinfo(AddrResult^);
{$ENDIF}
end;
end;
procedure TncLine.DestroyHandle;
begin
if FActive then
begin
try
{$IFDEF MSWINDOWS}
Shutdown(FHandle, SD_BOTH);
CloseSocket(FHandle);
{$ELSE}
Shutdown(FHandle, SHUT_RDWR);
Posix.Unistd.__Close(FHandle);
{$ENDIF}
except
end;
try
SetDisconnected;
except
end;
FHandle := InvalidSocket;
end;
end;
function TncLine.AcceptLine: TncLine;
var
NewHandle: TSocketHandle;
{$IFNDEF MSWINDOWS}
Addr: sockaddr;
AddrLen: socklen_t;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
NewHandle := Accept(FHandle, nil, nil);
{$ELSE}
NewHandle := Accept(FHandle, Addr, AddrLen);
{$ENDIF}
if NewHandle = InvalidSocket then
Abort; // raise silent exception
Result := CreateLineObject;
Result.FHandle := NewHandle;
Result.OnConnected := OnConnected;
Result.OnDisconnected := OnDisconnected;
Result.SetConnected;
end;
function TncLine.SendBuffer(const aBuf; aLen: Integer): Integer;
begin
// Send all buffer in one go, the most optimal by far
Result := Send(FHandle, aBuf, aLen, 0);
try
if Result = SocketError then
Abort; // raise silent exception instead of Check
LastSent := TStopWatch.GetTimeStamp;
except
DestroyHandle;
raise;
end;
end;
function TncLine.RecvBuffer(var aBuf; aLen: Integer): Integer;
begin
Result := recv(FHandle, aBuf, aLen, 0);
try
if (Result = SocketError) or (Result = 0) then
Abort; // raise silent exception instead of Check, something has disconnected
LastReceived := TStopWatch.GetTimeStamp;
except
DestroyHandle;
raise;
end;
end;
procedure TncLine.EnableNoDelay;
var
optval: Integer;
begin
optval := 1;
{$IFDEF MSWINDOWS}
Check(SetSockOpt(FHandle, IPPROTO_TCP, TCP_NODELAY, PAnsiChar(@optval), SizeOf(optval)));
{$ELSE}
Check(SetSockOpt(FHandle, IPPROTO_TCP, TCP_NODELAY, optval, SizeOf(optval)));
{$ENDIF}
end;
procedure TncLine.EnableKeepAlive;
var
optval: Integer;
begin
optval := 1; // any non zero indicates true
{$IFDEF MSWINDOWS}
Check(SetSockOpt(FHandle, SOL_SOCKET, SO_KEEPALIVE, PAnsiChar(@optval), SizeOf(optval)));
{$ELSE}
Check(SetSockOpt(FHandle, SOL_SOCKET, SO_KEEPALIVE, optval, SizeOf(optval)));
{$ENDIF}
end;
procedure TncLine.EnableReuseAddress;
var
optval: Integer;
begin
optval := 1;
{$IFDEF MSWINDOWS}
Check(SetSockOpt(FHandle, SOL_SOCKET, SO_REUSEADDR, PAnsiChar(@optval), SizeOf(optval)));
{$ELSE}
Check(SetSockOpt(FHandle, SOL_SOCKET, SO_REUSEADDR, optval, SizeOf(optval)));
{$ENDIF}
end;
procedure TncLine.SetConnected;
var
Addr: sockaddr;
{$IFDEF MSWINDOWS}
AddrSize: Integer;
{$ELSE}
AddrSize: socklen_t;
{$ENDIF}
begin
if not FActive then
begin
FActive := True;
LastSent := TStopWatch.GetTimeStamp;
LastReceived := LastSent;
AddrSize := SizeOf(Addr);
if GetPeerName(FHandle, Addr, AddrSize) <> SocketError then
begin
// FPeerIP := IntToStr(Ord(addr.sin_addr.S_un_b.s_b1)) + '.' + IntToStr(Ord(addr.sin_addr.S_un_b.s_b2)) + '.' + IntToStr(Ord(addr.sin_addr.S_un_b.s_b3)) +
// '.' + IntToStr(Ord(addr.sin_addr.S_un_b.s_b4));
FPeerIP :=
IntToStr(Ord(Addr.sa_data[2])) + '.' +
IntToStr(Ord(Addr.sa_data[3])) + '.' +
IntToStr(Ord(Addr.sa_data[4])) + '.' +
IntToStr(Ord(Addr.sa_data[5]));
end;
if Assigned(OnConnected) then
try
OnConnected(Self);
except
end;
end;
end;
procedure TncLine.SetDisconnected;
begin
if FActive then
begin
FActive := False;
if Assigned(FOnDisconnected) then
try
OnDisconnected(Self);
except
end;
end;
end;
function TncLine.GetLastReceived: Int64;
begin
PropertyLock.Acquire;
try
Result := FLastReceived;
finally
PropertyLock.Release;
end;
end;
procedure TncLine.SetLastReceived(const Value: Int64);
begin
PropertyLock.Acquire;
try
FLastReceived := Value;
finally
PropertyLock.Release;
end;
end;
function TncLine.GetLastSent: Int64;
begin
PropertyLock.Acquire;
try
Result := FLastSent;
finally
PropertyLock.Release;
end;
end;
procedure TncLine.SetLastSent(const Value: Int64);
begin
PropertyLock.Acquire;
try
FLastSent := Value;
finally
PropertyLock.Release;
end;
end;
{$IFDEF MSWINDOWS}
var
ExtDllHandle: THandle = 0;
procedure AttachAddrInfo;
procedure SafeLoadFrom(aDll: string);
begin
if not Assigned(DllGetAddrInfo) then
begin
ExtDllHandle := SafeLoadLibrary(aDll);
if ExtDllHandle <> 0 then
begin
DllGetAddrInfo := GetProcAddress(ExtDllHandle, 'GetAddrInfoW');
DllFreeAddrInfo := GetProcAddress(ExtDllHandle, 'FreeAddrInfoW');
if not Assigned(DllGetAddrInfo) then
begin
FreeLibrary(ExtDllHandle);
ExtDllHandle := 0;
end;
end;
end;
end;
begin
SafeLoadFrom('ws2_32.dll'); // WinSock2 dll
SafeLoadFrom('wship6.dll'); // WshIp6 dll
end;
var
WSAData: TWSAData;
initialization
WSAStartup(MakeWord(2, 2), WSAData); // Require WinSock 2 version
AttachAddrInfo;
finalization
if ExtDllHandle <> 0 then
FreeLibrary(ExtDllHandle);
WSACleanup;
{$ENDIF}
end.
|
unit UHref;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs;
type
THrefParam = class(TObject)
public
name: string;
value: string;
end;
THref = class(TObject)
private
fList: TList;
function getCount: Integer;
function getGet(name:string): THrefParam;
function getItem(Index: Integer): THrefParam;
procedure setGet(name:string; Value: THrefParam);
public
constructor Create;
destructor Destroy; override;
function Add(const name, value: string): THrefParam; overload;
function Add(param: THrefParam): THrefParam; overload;
procedure Clear;
procedure Delete(aIndex: Integer = -1);
function Exists(param: THrefParam): Boolean;
function IndexOf(aObject: THrefParam): Integer;
procedure Remove(aObject:THrefParam);
property Count: Integer read getCount;
property Get[name:string]: THrefParam read getGet write setGet; default;
property Item[Index: Integer]: THrefParam read getItem;
end;
implementation
{
************************************ THref *************************************
}
constructor THref.Create;
begin
fList :=TList.Create;
end;
destructor THref.Destroy;
begin
Clear();
fList.Free();
end;
function THref.Add(const name, value: string): THrefParam;
begin
result:= THrefParam.create();
try try
result.name := name;
result.value := value;
result := self.Add(result);
except on e:Exception do
begin
result
end;
end;
finally
end;
end;
function THref.Add(param: THrefParam): THrefParam;
begin
try
result:=param;
fList.Add(result);
except
result:=nil;
end;
end;
procedure THref.Clear;
begin
Delete(-1);
end;
procedure THref.Delete(aIndex: Integer = -1);
var
obj: THrefParam;
begin
if aIndex = -1 then
begin
while fList .Count>0 do
begin
obj:=THrefParam(fList.Items[fList.Count-1]);
obj.Free;
fList.Delete(fList.Count -1);
end
end
else begin
obj:=THrefParam(fList.Items[aIndex]);
obj.Free;
fList.Delete(aIndex);
end;
end;
function THref.Exists(param: THrefParam): Boolean;
begin
result:=(IndexOf(param)<>-1);
end;
function THref.getCount: Integer;
begin
result:=fList .Count;
end;
function THref.getGet(name:string): THrefParam;
begin
end;
function THref.getItem(Index: Integer): THrefParam;
begin
result:=THrefParam(fList.Items[Index]);
end;
function THref.IndexOf(aObject: THrefParam): Integer;
begin
result:=fList.IndexOf(aObject);
end;
procedure THref.Remove(aObject:THrefParam);
begin
fList .Remove(aObject);
end;
procedure THref.setGet(name:string; Value: THrefParam);
begin
end;
end.
|
unit ini_util;
interface
uses
SysUtils, Classes, Windows, IniFiles, Menus, StdCtrls, forms;
type
TIniList = class; //前方宣言
TIniVarType = class
protected
ini: TIniList;
public
Section,
Ident: string;
constructor Create(ini: TIniList; sec, ide: string);
procedure Read; virtual; abstract;
procedure Write; virtual; abstract;
end;
TIniMenu = class(TIniVarType)
private
FMenu: TMenuItem;
Default: Boolean;
public
constructor Create(ini: TIniList; mnu: TMenuItem; sec, ide: string; def:Boolean);
procedure Read; override;
procedure Write; override;
end;
TIniEdit = class(TIniVarType)
private
Obj: TEdit;
Default: string;
public
constructor Create(ini: TIniList; o: TEdit; sec, ide: string; def:string);
procedure Read; override;
procedure Write; override;
end;
TIniScroll = class(TIniVarType)
private
Obj: TScrollBar;
Default: Integer;
public
constructor Create(ini: TIniList; o: TScrollBar; sec, ide: string; def:Integer);
procedure Read; override;
procedure Write; override;
end;
TIniForm = class(TIniVarType)
private
Obj: TForm;
public
constructor Create(ini: TIniList; o: TForm; sec, ide: string);
procedure Read; override;
procedure Write; override;
end;
TIniCheckBox = class(TIniVarType)
private
FCheck: TCheckBox;
Default: Boolean;
public
constructor Create(ini: TIniList; chk: TCheckBox; sec, ide: string; def:Boolean);
procedure Read; override;
procedure Write; override;
end;
TIniComboBox = class(TIniVarType)
private
FCombo: TComboBox;
Default: Integer;
public
constructor Create(ini: TIniList; cmb: TComboBox; sec, ide: string; def:Integer);
procedure Read; override;
procedure Write; override;
end;
TIniListBox = class(TIniVarType)
private
FList: TListBox;
Default: Integer;
public
constructor Create(ini: TIniList; lst: TListBox; sec, ide: string; def:Integer);
procedure Read; override;
procedure Write; override;
end;
PStr = ^AnsiString;
TIniString = class(TIniVarType)
private
Ptr: PStr;
Default: string;
public
constructor Create(ini: TIniList; p: PStr; sec, ide: string; def:string);
procedure Read; override;
procedure Write; override;
end;
PInt = ^Integer;
TIniInteger = class(TIniVarType)
private
Ptr: Pointer;
Default: Integer;
public
constructor Create(ini: TIniList; p: Pointer; sec, ide: string; def:Integer);
procedure Read; override;
procedure Write; override;
end;
PBool = ^Boolean;
TIniBool = class(TIniVarType)
private
Ptr: PBool;
Default: Boolean;
public
constructor Create(ini: TIniList; p: PBool; sec, ide: string; def:Boolean);
procedure Read; override;
procedure Write; override;
end;
TIniList = class(TIniFile)
private
list: TList;
public
constructor Create(FileName: string);
destructor Destroy; override;
procedure Clear;
procedure LoadAll;
procedure SaveAll;
procedure SaveForm(obj: TForm);
function LoadForm(obj: TForm): Boolean; // 最大化なら TRUE を返す
procedure Load(Section: string); //特定のセクションだけロード
procedure Save(Section: string);
function AddInt ( p: Pointer; sec, ide: string; def: Integer): Integer;
function AddStr ( p: Pointer; sec, ide: string; def: string): Integer;
function AddBool ( p: Pointer; sec, ide: string; def: Boolean): Integer;
function AddMenu ( mnu: TMenuItem; sec, ide: string; def: Boolean ): Integer;
function AddCheck ( chk: TCheckBox; sec, ide: string; def: Boolean ): Integer;
function AddForm ( obj: TForm; sec, ide: string): Integer; // サブフォームは追加できない
function AddScroll( obj: TScrollbar; sec, ide: string; def: Integer ): Integer;
function AddList ( obj: TListBox; sec, ide: string; def: Integer ): Integer;
function AddCombo ( obj: TComboBox; sec, ide: string; def: Integer ): Integer;
function AddEdit ( obj: TEdit; sec, ide: string; def: string ): Integer;
end;
implementation
{ TIniList }
function TIniList.AddBool(p: Pointer; sec, ide: string;
def: Boolean): Integer;
var
c: TIniBool ;
begin
c := TIniBool.Create(Self, p, sec, ide, def);
Result := list.Add(c);
end;
function TIniList.AddCheck(chk: TCheckBox; sec, ide: string;
def: Boolean): Integer;
var
m: TIniCheckBox;
begin
m := TIniCheckBox.Create(Self, chk, sec, ide, def);
Result := list.Add(m);
end;
function TIniList.AddCombo(obj: TComboBox; sec, ide: string;
def: Integer): Integer;
var
c: TIniComboBox;
begin
c := TIniComboBox.Create(Self, obj, sec, ide, def);
Result := list.Add(c);
end;
function TIniList.AddEdit(obj: TEdit; sec, ide, def: string): Integer;
var
c: TIniEdit;
begin
c := TIniEdit.Create(Self, obj, sec, ide, def);
Result := list.Add(c);
end;
function TIniList.AddForm(obj: TForm; sec, ide: string): Integer;
var
c: TIniForm;
begin
c := TIniForm.Create(Self, obj, sec,ide);
Result := list.Add(c);
end;
function TIniList.AddInt(p: Pointer; sec, ide: string;
def: Integer): Integer;
var
i: TIniInteger;
begin
i := TIniInteger.Create(Self, p, sec,ide, def);
Result := list.Add(i);
end;
function TIniList.AddList(obj: TListBox; sec, ide: string;
def: Integer): Integer;
var
c: TIniListBox;
begin
c := TIniListBox.Create(Self, obj, sec, ide, def);
Result := list.Add(c);
end;
function TIniList.AddMenu(mnu: TMenuItem; sec, ide: string;
def: Boolean): Integer;
var
m: TIniMenu;
begin
m := TIniMenu.Create(Self, mnu, sec, ide, def);
Result := list.Add(m);
end;
function TIniList.AddScroll(obj: TScrollbar; sec, ide: string;
def: Integer): Integer;
var
c: TIniScroll;
begin
c := TIniScroll.Create(Self, obj, sec, ide, def);
Result := list.Add(c);
end;
function TIniList.AddStr(p: Pointer; sec, ide: string;
def: string): Integer;
var
i: TIniString;
begin
i := TIniString.Create(Self, p, sec,ide, def);
Result := list.Add(i);
end;
procedure TIniList.Clear;
var
i: Integer;
p: TIniVarType;
begin
for i:=0 to list.Count-1 do
begin
p := list.Items[i];
if p<>nil then p.Free ;
end;
list.Clear;
end;
constructor TIniList.Create(FileName: string);
begin
list := TList.Create ;
inherited Create(FileName);
end;
destructor TIniList.Destroy;
begin
Self.Clear ;
list.Free ;
inherited;
end;
procedure TIniList.Load(Section: string);
var
i: Integer;
p: TIniVarType;
begin
for i:=0 to list.Count -1 do
begin
p := list.Items[i];
if p.Section = Section then p.Read ;
end;
end;
procedure TIniList.LoadAll;
var
i: Integer;
p: TIniVarType;
begin
for i:=0 to list.Count -1 do
begin
p := list.Items[i];
p.Read ;
end;
end;
function TIniList.LoadForm(obj: TForm): Boolean;
var
Section: string; i: Integer;
begin
Section := obj.Name ;
i := ReadInteger(Section, 'state', Ord(obj.WindowState));
if i = 2 then // Maximize
begin
{
obj.Width := Trunc(Screen.Width * 0.8);
obj.Height := Trunc(Screen.Height * 0.8);
//
obj.Top := (Screen.Height - obj.Height) div 2;
obj.Left := (Screen.Width - obj.Width) div 2;
}
obj.WindowState := wsMaximized ;
Result := True;
end else
begin
obj.Top := ReadInteger(Section, 'top', obj.Top );
obj.Left := ReadInteger(Section, 'left', obj.Left );
obj.Width := ReadInteger(Section, 'width', obj.Width );
obj.Height := ReadInteger(Section, 'height', obj.Height);
obj.WindowState := wsNormal ;
Result := False;
end;
end;
procedure TIniList.Save(Section: string);
var
i: Integer;
p: TIniVarType;
begin
for i:=0 to list.Count -1 do
begin
p := list.Items[i];
if p.Section = Section then p.Write ;
end;
end;
procedure TIniList.SaveAll;
var
i: Integer;
p: TIniVarType;
begin
for i:=0 to list.Count -1 do
begin
p := list.Items[i];
p.Write ;
end;
end;
procedure TIniList.SaveForm(obj: TForm);
var
Section: string;
begin
Section := obj.Name ;
WriteInteger(Section, 'top', obj.Top );
WriteInteger(Section, 'left', obj.Left );
WriteInteger(Section, 'width', obj.Width );
WriteInteger(Section, 'height', obj.Height);
WriteInteger(Section, 'state', Ord(obj.WindowState));
end;
{ TIniVarType }
constructor TIniVarType.Create(ini: TIniList; sec, ide: string);
begin
Section := sec;
Ident := ide;
Self.ini := ini;
end;
{ TIniMenu }
constructor TIniMenu.Create(ini: TIniList; mnu: TMenuItem; sec, ide: string;
def: Boolean);
begin
FMenu := mnu;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniMenu.Read;
begin
FMenu.Checked := ini.ReadBool(Section, Ident, Default);
end;
procedure TIniMenu.Write;
begin
ini.WriteBool(Section, Ident, FMenu.Checked);
end;
{ TIniCheckBox }
constructor TIniCheckBox.Create(ini: TIniList; chk: TCheckBox; sec,
ide: string; def: Boolean);
begin
FCheck := chk;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniCheckBox.Read;
begin
FCheck.Checked := ini.ReadBool(Section, Ident, Default);
end;
procedure TIniCheckBox.Write;
begin
ini.WriteBool(Section, Ident, FCheck.Checked);
end;
{ TIniString }
constructor TIniString.Create(ini: TIniList; p: PStr; sec, ide,
def: string);
begin
Ptr := p;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniString.Read;
begin
PStr(Ptr)^ := ini.ReadString(Section, Ident, Default);
end;
procedure TIniString.Write;
begin
ini.WriteString(Section, Ident, PStr(Ptr)^);
end;
{ TIniInteger }
constructor TIniInteger.Create(ini: TIniList; p: Pointer; sec, ide: string;
def: Integer);
begin
Ptr := p;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniInteger.Read;
begin
PInt(Ptr)^ := ini.ReadInteger(Section, Ident, Default);
end;
procedure TIniInteger.Write;
begin
ini.WriteInteger(Section, Ident, PInt(Ptr)^);
end;
{ TIniComboBox }
constructor TIniComboBox.Create(ini: TIniList; cmb: TComboBox; sec,
ide: string; def: Integer);
begin
FCombo := cmb;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniComboBox.Read;
begin
FCombo.ItemIndex := ini.ReadInteger(Section, Ident, Default);
end;
procedure TIniComboBox.Write;
begin
ini.WriteInteger(Section, Ident, FCombo.ItemIndex);
end;
{ TIniListBox }
constructor TIniListBox.Create(ini: TIniList; lst: TListBox; sec,
ide: string; def: Integer);
begin
FList := lst;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniListBox.Read;
begin
FList.ItemIndex := ini.ReadInteger(Section, Ident, Default);
end;
procedure TIniListBox.Write;
begin
ini.WriteInteger(Section, Ident, FList.ItemIndex);
end;
{ TIniBool }
constructor TIniBool.Create(ini: TIniList; p: PBool; sec, ide: string;
def: Boolean);
begin
ptr := p;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniBool.Read;
begin
ptr^ := ini.ReadBool(Section, Ident, Default);
end;
procedure TIniBool.Write;
begin
ini.WriteBool(Section, Ident, ptr^);
end;
{ TIniEdit }
constructor TIniEdit.Create(ini: TIniList; o: TEdit; sec, ide,
def: string);
begin
obj := o;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniEdit.Read;
begin
obj.Text := ini.ReadString(Section, Ident, Default);
end;
procedure TIniEdit.Write;
begin
ini.WriteString(Section, Ident, obj.Text);
end;
{ TIniScroll }
constructor TIniScroll.Create(ini: TIniList; o: TScrollBar; sec,
ide: string; def: Integer);
begin
obj := o;
Default := def;
inherited Create(ini, sec, ide);
end;
procedure TIniScroll.Read;
begin
obj.Position := ini.ReadInteger(Section, Ident, Default);
end;
procedure TIniScroll.Write;
begin
ini.WriteInteger(Section, Ident, obj.Position);
end;
{ TIniForm }
constructor TIniForm.Create(ini: TIniList; o: TForm; sec, ide: string);
begin
obj := o;
inherited Create(ini, sec, ide);
end;
procedure TIniForm.Read;
begin
obj.Top := ini.ReadInteger(Section, Ident+'.top', obj.Top );
obj.Left := ini.ReadInteger(Section, Ident+'.left', obj.Left );
obj.Width := ini.ReadInteger(Section, Ident+'.width', obj.Width );
obj.Height := ini.ReadInteger(Section, Ident+'.height', obj.Height);
end;
procedure TIniForm.Write;
begin
ini.WriteInteger(Section, Ident+'.top', obj.Top );
ini.WriteInteger(Section, Ident+'.left', obj.Left );
ini.WriteInteger(Section, Ident+'.width', obj.Width );
ini.WriteInteger(Section, Ident+'.height', obj.Height);
end;
end.
|
unit ADAPT.UnitTests.Generics.Common;
interface
{$I ADAPT.inc}
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
DUnitX.TestFramework;
type
TDummyObject = class(TObject)
private
FFoo: String;
public
constructor Create(const AFoo: String);
property Foo: String read FFoo;
end;
const
BASIC_ITEMS: Array[0..9] of String = (
'Bob',
'Terry',
'Andy',
'Rick',
'Sarah',
'Ellen',
'Hugh',
'Jack',
'Marie',
'Ninette'
);
NAMES_IN_ORDER: Array[0..9] of String = ('Andy', 'Bob', 'Ellen', 'Hugh', 'Jack', 'Marie', 'Ninette', 'Rick', 'Sarah', 'Terry');
LETTERS: Array[0..9] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
ALPHABET: Array[0..25] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
BASIC_INTEGER_ITEMS: Array[0..9] of Integer = (
1337,
9001,
10,
1,
20,
2,
21,
30,
55,
666
);
NUMBERS_IN_ORDER: Array[0..9] of Integer = (1, 2, 10, 20, 21, 30, 55, 666, 1337, 9001);
implementation
{ TDummyObject }
constructor TDummyObject.Create(const AFoo: String);
begin
inherited Create;
FFoo := AFoo;
end;
end.
|
(**
This module contains a class ewhich represents a form for editing the font styles and
colours used in the messages that are output by the expert.
@Author David Hoyle
@Version 1.0
@Date 05 Jan 2018
**)
Unit ITHelper.FontDialogue;
Interface
Uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
Buttons,
ITHelper.Types,
ITHelper.Interfaces;
Type
(** A class to represent the form interface. **)
TfrmITHFontDialogue = Class(TForm)
lblHeaderFontName: TLabel;
lblToolFontName: TLabel;
gbxMessageColours: TGroupBox;
clbxFontColour: TColorBox;
chkFontStyleBold: TCheckBox;
chkFontStyleItalic: TCheckBox;
chkFontStyleUnderline: TCheckBox;
chkFontStyleStrikeout: TCheckBox;
cbxHeaderFontName: TComboBox;
cbxToolFontName: TComboBox;
cbxMessageType: TComboBox;
lblMessageType: TLabel;
btnOK: TBitBtn;
btnCancel: TBitBtn;
lblMessageFontClour: TLabel;
btnHelp: TBitBtn;
Procedure FontStyleClick(Sender: TObject);
Procedure cbxMessageTypeClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure clbxFontColourClick(Sender: TObject);
Private
{ Private declarations }
FFontColour: Array [Low(TITHFonts) .. High(TITHFonts)] Of TColor;
FFontStyle : Array [Low(TITHFonts) .. High(TITHFonts)] Of TFontStyles;
FUpdating : Boolean;
Procedure InitialiseMessageOptions(Const GlobalOps: IITHGlobalOptions);
Procedure SaveMessageOptions(Const GlobalOps: IITHGlobalOptions);
Public
{ Public declarations }
Class Procedure Execute(Const GlobalOptions: IITHGlobalOptions);
End;
Implementation
{$R *.dfm}
Uses
ITHelper.TestingHelperUtils;
(**
This is an on click event handler for the Help button.
@precon None.
@postcon Displays the Message Fonts help page.
@param Sender as a TObject
**)
Procedure TfrmITHFontDialogue.btnHelpClick(Sender: TObject);
Const
strMessageFonts = 'MessageFonts';
Begin
HTMLHelp(0, PChar(ITHHTMLHelpFile(strMessageFonts)), HH_DISPLAY_TOPIC, 0);
End;
(**
This is an on click event handler for the Message Type combo box.
@precon None.
@postcon Updates the font colour and styles based on the selected message type.
@param Sender as a TObject
**)
Procedure TfrmITHFontDialogue.cbxMessageTypeClick(Sender: TObject);
Var
iMessageType: TITHFonts;
Begin
FUpdating := True;
Try
iMessageType := TITHFonts(Byte(cbxMessageType.ItemIndex));
clbxFontColour.Selected := FFontColour[iMessageType];
chkFontStyleBold.Checked := fsBold In FFontStyle[iMessageType];
chkFontStyleItalic.Checked := fsItalic In FFontStyle[iMessageType];
chkFontStyleUnderline.Checked := fsUnderline In FFontStyle[iMessageType];
chkFontStyleStrikeout.Checked := fsStrikeOut In FFontStyle[iMessageType];
Finally
FUpdating := False;
End;
End;
(**
This is an on click event handler for the Colour drop down control.
@precon None.
@postcon Updates the appropriate Font colour with the selected colour.
@param Sender as a TObject
**)
Procedure TfrmITHFontDialogue.clbxFontColourClick(Sender: TObject);
Var
iMessageType : TITHFonts;
Begin
If Not FUpdating Then
Begin
iMessageType := TITHFonts(Byte(cbxMessageType.ItemIndex));
FFontColour[iMessageType] := clbxFontColour.Selected;
End;
End;
(**
This is the forms main interface method for invoking the dialogue.
@precon GlobalOptions must be a valid instance.
@postcon Displays the dialogue.
@param GlobalOptions as a IITHGlobalOptions as a constant
**)
Class Procedure TfrmITHFontDialogue.Execute(Const GlobalOptions: IITHGlobalOptions);
Var
frm: TfrmITHFontDialogue;
Begin
frm := TfrmITHFontDialogue.Create(Nil);
Try
frm.InitialiseMessageOptions(GlobalOptions);
If frm.ShowModal = mrOK Then
frm.SaveMessageOptions(GlobalOptions);
Finally
frm.Free;
End;
End;
(**
This is an on click event handler for the Font Style check boxes.
@precon None.
@postcon Updates the internal font style array with the changes.
@param Sender as a TObject
**)
Procedure TfrmITHFontDialogue.FontStyleClick(Sender: TObject);
Var
iMessageType: TITHFonts;
Begin
If Not FUpdating Then
Begin
iMessageType := TITHFonts(Byte(cbxMessageType.ItemIndex));
FFontStyle[iMessageType] := [];
If chkFontStyleBold.Checked Then
Include(FFontStyle[iMessageType], fsBold);
If chkFontStyleItalic.Checked Then
Include(FFontStyle[iMessageType], fsItalic);
If chkFontStyleUnderline.Checked Then
Include(FFontStyle[iMessageType], fsUnderline);
If chkFontStyleStrikeout.Checked Then
Include(FFontStyle[iMessageType], fsStrikeOut);
End;
End;
(**
This method initialises the message font checkboxes in the dialogue.
@precon None.
@postcon Initialises the message font checkboxes in the dialogue.
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Procedure TfrmITHFontDialogue.InitialiseMessageOptions(Const GlobalOps: IITHGlobalOptions);
Const
strFontDescriptions: Array [Low(TITHFonts) .. High(TITHFonts)
] Of String = ('Header Messages', 'Default Messages', 'Success Messages',
'Failure Messages', 'Warning Messages');
Var
iMessageType: TITHFonts;
Begin
FUpdating := False;
cbxHeaderFontName.Items.Assign(Screen.Fonts);
cbxHeaderFontName.ItemIndex := cbxHeaderFontName.Items.IndexOf
(GlobalOps.FontName[fnHeader]);
cbxToolFontName.Items.Assign(Screen.Fonts);
cbxToolFontName.ItemIndex := cbxToolFontName.Items.IndexOf(GlobalOps.FontName[fnTools]);
For iMessageType := Low(TITHFonts) To High(TITHFonts) Do
Begin
FFontColour[iMessageType] := GlobalOps.FontColour[iMessageType];
FFontStyle[iMessageType] := GlobalOps.FontStyles[iMessageType];
cbxMessageType.Items.Add(strFontDescriptions[iMessageType]);
End;
cbxMessageType.ItemIndex := 0;
cbxMessageTypeClick(Nil);
End;
(**
This method saves the message options to the Options record structure.
@precon None.
@postcon Saves the message options to the Options record structure.
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Procedure TfrmITHFontDialogue.SaveMessageOptions(Const GlobalOps: IITHGlobalOptions);
Var
iMessageType: TITHFonts;
Begin
GlobalOps.FontName[fnHeader] := cbxHeaderFontName.Text;
GlobalOps.FontName[fnTools] := cbxToolFontName.Text;
For iMessageType := Low(TITHFonts) To High(TITHFonts) Do
Begin
GlobalOps.FontColour[iMessageType] := FFontColour[iMessageType];
GlobalOps.FontStyles[iMessageType] := FFontStyle[iMessageType];
End;
End;
End.
|
unit SourceToken;
interface
uses
SourceLocation;
type
TTokenKind = (tkIdentifier, tkSymbol, tkNumber, tkString, tkCharacter, tkComment, tkError, tkEof);
TToken = record
Position: TLocation;
Data: String;
Kind: TTokenKind;
end;
PToken = ^TToken;
function DescribeToken(const Token: TToken): String;
implementation
function DescribeToken(const Token: TToken): String;
begin
Result := 'Token ';
case Token.Kind of
tkIdentifier:
Result := Result + 'identifier ';
tkSymbol:
Result := Result + 'symbol ';
tkNumber:
Result := Result + 'number ';
tkString:
Result := Result + 'string ';
tkCharacter:
Result := Result + 'character ';
tkComment:
Result := Result + 'comment ';
tkError:
Result := Result + 'error ';
tkEof:
Result := Result + 'eof ';
end;
Result := Result + Token.Data;
Result := Result + ' ' + DescribeLocation(Token.Position);
end;
end.
|
unit uMonster;
interface
uses
SysUtils, Dialogs, uCommon;
type
TMonster = class
private
fId: integer;
//monData: string;
fName: string;
fAwareness:integer;
fMovBorder: integer;
fDimention: integer;
fHorrorRate: integer;
fHorrorDmg: integer;
fToughness: integer;
fCmbtRate: integer;
fCmbtDmg: integer;
fSpec: string[6];
fLocationId: integer;
fAmbush: boolean; // Засада
fEndless: boolean; // Неисчислимость
fPhysical: integer; // Физ. сопр/иммун
fMagical: integer; // Маг. сопр/иммун
fNightmarish: Integer; // Кошмар
fOverwhelming: integer; // Сокрушение
public
property Id: Integer read fId write fId;
property Name: string read fName write fName;
property Awareness:integer read fAwareness write fAwareness;
property MovBorder: integer read fMovBorder write fMovBorder;
property Dimention: integer read fDimention write fDimention;
property HorrorRate: integer read fHorrorRate write fHorrorRate;
property HorrorDmg: integer read fHorrorDmg write fHorrorDmg;
property Toughness: integer read fToughness write fToughness;
property CmbtRate: integer read fCmbtRate write fCmbtRate;
property CmbtDmg: integer read fCmbtDmg write fCmbtDmg;
property Ambush: boolean read fAmbush write fAmbush;
property Endless: boolean read fEndless write fEndless;
property Physical: integer read fPhysical write fPhysical;
property Magical: integer read fMagical write fMagical;
property Nightmarish: Integer read fNightmarish write fNightmarish;
property Overwhelming: Integer read fOverwhelming write fOverwhelming;
//property fSpec: string[6] read fId write fId;
property LocationId: integer read fLocationId write fLocationId;
constructor Create();
function Move(const MobMoveWhite: array of integer; const MobMoveBlack: array of integer): integer;
end;
TMonsterArray = array of TMonster;
function LoadMonsterCards(var monsters: TMonsterArray; file_path: string): integer;
function DrawMonsterCard(monsters: TMonsterArray): TMonster;
procedure ShuffleMonsterDeck(var monsters_deck: TMonsterArray);
//procedure MoveMonster(); // TODO: moving of the monsters
function GetMonsterNameByID(id: integer): string;
function GetMonsterByID(const monsters: TMonsterArray; id: integer): TMonster; // Get mob from pool
function GetMonsterCount(const monsters: TMonsterArray): integer;
var
DeckMobCount: integer = 0; // Kol-vo mobov v pule
implementation
uses
uMainForm, uStreet;
constructor TMonster.Create;
begin
end;
function TMonster.Move(const MobMoveWhite: array of integer; const MobMoveBlack: array of integer): integer;
var
i, j: integer;
lok_id: Integer;
begin
Result := 0;
lok_id := fLocationId;
//case fMovBorder of
//1: begin // Black (normal)
if MobMoveWhite[fDimention - 1] = 1 then // if white mob move in mythos card
begin
for i := 1 to 36 do
if aMonsterMoves[i, 1] = lok_id then
begin
Arkham_Streets[ton(fLocationId)].TakeAwayMonster(fLocationId, Self);
Arkham_Streets[ton(aMonsterMoves[i, 2])].AddMonster(aMonsterMoves[i, 2], Self);
Result := aMonsterMoves[i, 2];
break;
end;
end;
if MobMoveBlack[fDimention - 1] = 1 then // if black mob move in mythos card
begin
for i := 1 to 36 do
if aMonsterMoves[i, 1] = lok_id then
begin
Arkham_Streets[ton(fLocationId)].TakeAwayMonster(fLocationId, Self);
Arkham_Streets[ton(aMonsterMoves[i, 3])].AddMonster(aMonsterMoves[i, 3], Self);
Result := aMonsterMoves[i, 3];
break;
end;
end;
// end;
//2: ; // Stationary (Yellow Border)
//3: ; // Fast (Red Border)
//4: ; // Unique (Green Border)
//5: ; // Flying (Blue Border)
//end;
end;
function LoadMonsterCards(var monsters: TMonsterArray; file_path: string): integer;
var
F: TextFile;
SR: TSearchRec; // поисковая переменная
FindRes: Integer; // переменная для записи результата поиска
s: string;
i, a, amt, j: integer;
begin
// задание условий поиска и начало поиска
FindRes := FindFirst(file_path+'\CardsData\Monsters\' + '*.txt', faAnyFile, SR);
i := 0;
a := 0;
while FindRes = 0 do // пока мы находим файлы (каталоги), то выполнять цикл
begin
AssignFile (F, file_path+'\CardsData\Monsters\' + SR.Name);
Reset(F);
amt := StrToInt(Copy(SR.Name, 4, 1));
for j := 0 to amt - 1 do
begin
i := i + 1;
SetLength(Monsters, i);
Monsters[i-1] := TMonster.Create;
with Monsters[i-1] do
begin
Id := StrToInt(Copy(SR.Name, 1, 4));
//monData: string;
Name := GetMonsterNameByID(Id);
readln(F, s);
Awareness := StrToInt(s);
readln(F, s);
MovBorder := StrToInt(s);
readln(F, s);
Dimention := StrToInt(s);
readln(F, s);
HorrorRate := StrToInt(s);
readln(F, s);
HorrorDmg := StrToInt(s);
readln(F, s);
Toughness := StrToInt(s);
readln(F, s);
CmbtRate := StrToInt(s);
readln(F, s);
CmbtDmg := StrToInt(s);
readln(F, s);
Ambush := StrToBool(s);
readln(F, s);
Endless := StrToBool(s);
readln(F, s);
Physical := StrToInt(s);
readln(F, s);
Magical := StrToInt(s);
readln(F, s);
Magical := StrToInt(s);
readln(F, s);
Nightmarish:= StrToInt(s);
readln(F, s);
Overwhelming:= StrToInt(s);
//spec: string[6];
end;
Reset(F);
end;
CloseFile(F);
//Cards^.Cards.Type := CT_UNIQUE_ITEM;
FindRes := FindNext(SR); // продолжение поиска по заданным условиям
//Form1.ComboBox2.Items.Add(IntToStr(Cards^[i].Card_ID));
end;
FindClose(SR); // закрываем поиск
LoadMonsterCards := i;
DeckMobCount := i;
end;
// Return mob ID
function DrawMonsterCard(monsters: TMonsterArray): TMonster;
var
i: integer;
dmonster: TMOnster;
begin
//Assert(monCount > 1);
dmonster := nil;
if DeckMobCount < 1 then
begin
MainForm.lstLog.Items.Add('DrawMonsterCard: нету монстров!');
Result := nil;
Exit;
end;
//ShuffleMonsterDeck(monsters);
for i := 0 to uMainForm.Monsters_Count - 1 do
begin
if monsters[i].fLocationId = 0 then
begin
dmonster := monsters[i];
Result := dmonster;
Exit;
end;
end;
ShowMessage('Ошибочка! Схватил не того монстра!');
Result := dmonster;
end;
// TODO: Access violation
procedure ShuffleMonsterDeck(var monsters_deck: TMonsterArray);
var
i, r: integer;
temp: TMonster;
begin
if DeckMobCount < 2 then exit;
randomize;
for i := 0 to DeckMobCount - 1 do
begin
temp := monsters_deck[i];
r := random(DeckMobCount);
monsters_deck[i] := monsters_deck[r];
monsters_deck[r] := temp;
end;
end;
//
function GetMonsterNameByID(id: integer): string;
var
i: integer;
begin
for i := 1 to MONSTER_MAX do
if StrToInt(MonsterNames[i, 1]) = id then
begin
GetMonsterNameByID := MonsterNames[i, 2];
break;
end;
end;
function GetMonsterByID(const monsters: TMonsterArray; id: integer): TMonster;
var
i: integer;
begin
for i := 0 to MONSTER_MAX-1 do
begin
if Monsters[i].fId = id then
begin
GetMonsterByID := Monsters[i];
//Monsters[i] := nil;
break;
end;
end;
end;
function GetMonsterCount(const monsters: TMonsterArray): integer;
var
i, c: integer;
begin
c := 0;
i := 0;
while monsters[i].fId <> 0 do
begin
c := c + 1;
i := i + 1;
end;
GetMonsterCount := c;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 26 O(2^N) Recursive Method
}
program
CubicGraph;
const
MaxN = 20;
var
N : Integer;
S : string [MaxN];
I, J : Integer;
F : Text;
procedure Cube (K : Integer; Rev : Byte);
begin
if K = 0 then
begin
Writeln(F, S);
Exit;
end;
Inc(S[0]);
S[Ord(S[0])] := Chr(Ord('0') + Rev ); Cube(K - 1, 0);
S[Ord(S[0])] := Chr(Ord('0') + 1 - Rev); Cube(K - 1, 1);
Dec(S[0]);
end;
begin
Readln(N);
Assign(F, 'output.txt');
ReWrite(F);
Cube(N, 0);
Close(F);
end.
|
{$R-}
{$Q-}
unit ncEncCast128;
// To disable as much of RTTI as possible (Delphi 2009/2010),
// Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ENDIF}
interface
uses
System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers;
type
TncEnc_cast128 = class(TncEnc_blockcipher64)
protected
KeyData: array [0 .. 31] of DWord;
Rounds: longword;
procedure InitKey(const Key; Size: longword); override;
public
class function GetAlgorithm: string; override;
class function GetMaxKeySize: integer; override;
class function SelfTest: boolean; override;
procedure Burn; override;
procedure EncryptECB(const InData; var OutData); override;
procedure DecryptECB(const InData; var OutData); override;
end;
{ ****************************************************************************** }
{ ****************************************************************************** }
implementation
uses ncEncryption;
const
cast_sbox1: array [0 .. 255] of DWord = ($30FB40D4, $9FA0FF0B, $6BECCD2F, $3F258C7A, $1E213F2F, $9C004DD3, $6003E540, $CF9FC949, $BFD4AF27, $88BBBDB5,
$E2034090, $98D09675, $6E63A0E0, $15C361D2, $C2E7661D, $22D4FF8E, $28683B6F, $C07FD059, $FF2379C8, $775F50E2, $43C340D3, $DF2F8656, $887CA41A, $A2D2BD2D,
$A1C9E0D6, $346C4819, $61B76D87, $22540F2F, $2ABE32E1, $AA54166B, $22568E3A, $A2D341D0, $66DB40C8, $A784392F, $004DFF2F, $2DB9D2DE, $97943FAC, $4A97C1D8,
$527644B7, $B5F437A7, $B82CBAEF, $D751D159, $6FF7F0ED, $5A097A1F, $827B68D0, $90ECF52E, $22B0C054, $BC8E5935, $4B6D2F7F, $50BB64A2, $D2664910, $BEE5812D,
$B7332290, $E93B159F, $B48EE411, $4BFF345D, $FD45C240, $AD31973F, $C4F6D02E, $55FC8165, $D5B1CAAD, $A1AC2DAE, $A2D4B76D, $C19B0C50, $882240F2, $0C6E4F38,
$A4E4BFD7, $4F5BA272, $564C1D2F, $C59C5319, $B949E354, $B04669FE, $B1B6AB8A, $C71358DD, $6385C545, $110F935D, $57538AD5, $6A390493, $E63D37E0, $2A54F6B3,
$3A787D5F, $6276A0B5, $19A6FCDF, $7A42206A, $29F9D4D5, $F61B1891, $BB72275E, $AA508167, $38901091, $C6B505EB, $84C7CB8C, $2AD75A0F, $874A1427, $A2D1936B,
$2AD286AF, $AA56D291, $D7894360, $425C750D, $93B39E26, $187184C9, $6C00B32D, $73E2BB14, $A0BEBC3C, $54623779, $64459EAB, $3F328B82, $7718CF82, $59A2CEA6,
$04EE002E, $89FE78E6, $3FAB0950, $325FF6C2, $81383F05, $6963C5C8, $76CB5AD6, $D49974C9, $CA180DCF, $380782D5, $C7FA5CF6, $8AC31511, $35E79E13, $47DA91D0,
$F40F9086, $A7E2419E, $31366241, $051EF495, $AA573B04, $4A805D8D, $548300D0, $00322A3C, $BF64CDDF, $BA57A68E, $75C6372B, $50AFD341, $A7C13275, $915A0BF5,
$6B54BFAB, $2B0B1426, $AB4CC9D7, $449CCD82, $F7FBF265, $AB85C5F3, $1B55DB94, $AAD4E324, $CFA4BD3F, $2DEAA3E2, $9E204D02, $C8BD25AC, $EADF55B3, $D5BD9E98,
$E31231B2, $2AD5AD6C, $954329DE, $ADBE4528, $D8710F69, $AA51C90F, $AA786BF6, $22513F1E, $AA51A79B, $2AD344CC, $7B5A41F0, $D37CFBAD, $1B069505, $41ECE491,
$B4C332E6, $032268D4, $C9600ACC, $CE387E6D, $BF6BB16C, $6A70FB78, $0D03D9C9, $D4DF39DE, $E01063DA, $4736F464, $5AD328D8, $B347CC96, $75BB0FC3, $98511BFB,
$4FFBCC35, $B58BCF6A, $E11F0ABC, $BFC5FE4A, $A70AEC10, $AC39570A, $3F04442F, $6188B153, $E0397A2E, $5727CB79, $9CEB418F, $1CACD68D, $2AD37C96, $0175CB9D,
$C69DFF09, $C75B65F0, $D9DB40D8, $EC0E7779, $4744EAD4, $B11C3274, $DD24CB9E, $7E1C54BD, $F01144F9, $D2240EB1, $9675B3FD, $A3AC3755, $D47C27AF, $51C85F4D,
$56907596, $A5BB15E6, $580304F0, $CA042CF1, $011A37EA, $8DBFAADB, $35BA3E4A, $3526FFA0, $C37B4D09, $BC306ED9, $98A52666, $5648F725, $FF5E569D, $0CED63D0,
$7C63B2CF, $700B45E1, $D5EA50F1, $85A92872, $AF1FBDA7, $D4234870, $A7870BF3, $2D3B4D79, $42E04198, $0CD0EDE7, $26470DB8, $F881814C, $474D6AD7, $7C0C5E5C,
$D1231959, $381B7298, $F5D2F4DB, $AB838653, $6E2F1E23, $83719C9E, $BD91E046, $9A56456E, $DC39200C, $20C8C571, $962BDA1C, $E1E696FF, $B141AB08, $7CCA89B9,
$1A69E783, $02CC4843, $A2F7C579, $429EF47D, $427B169C, $5AC9F049, $DD8F0F00, $5C8165BF);
cast_sbox2: array [0 .. 255] of DWord = ($1F201094, $EF0BA75B, $69E3CF7E, $393F4380, $FE61CF7A, $EEC5207A, $55889C94, $72FC0651, $ADA7EF79, $4E1D7235,
$D55A63CE, $DE0436BA, $99C430EF, $5F0C0794, $18DCDB7D, $A1D6EFF3, $A0B52F7B, $59E83605, $EE15B094, $E9FFD909, $DC440086, $EF944459, $BA83CCB3, $E0C3CDFB,
$D1DA4181, $3B092AB1, $F997F1C1, $A5E6CF7B, $01420DDB, $E4E7EF5B, $25A1FF41, $E180F806, $1FC41080, $179BEE7A, $D37AC6A9, $FE5830A4, $98DE8B7F, $77E83F4E,
$79929269, $24FA9F7B, $E113C85B, $ACC40083, $D7503525, $F7EA615F, $62143154, $0D554B63, $5D681121, $C866C359, $3D63CF73, $CEE234C0, $D4D87E87, $5C672B21,
$071F6181, $39F7627F, $361E3084, $E4EB573B, $602F64A4, $D63ACD9C, $1BBC4635, $9E81032D, $2701F50C, $99847AB4, $A0E3DF79, $BA6CF38C, $10843094, $2537A95E,
$F46F6FFE, $A1FF3B1F, $208CFB6A, $8F458C74, $D9E0A227, $4EC73A34, $FC884F69, $3E4DE8DF, $EF0E0088, $3559648D, $8A45388C, $1D804366, $721D9BFD, $A58684BB,
$E8256333, $844E8212, $128D8098, $FED33FB4, $CE280AE1, $27E19BA5, $D5A6C252, $E49754BD, $C5D655DD, $EB667064, $77840B4D, $A1B6A801, $84DB26A9, $E0B56714,
$21F043B7, $E5D05860, $54F03084, $066FF472, $A31AA153, $DADC4755, $B5625DBF, $68561BE6, $83CA6B94, $2D6ED23B, $ECCF01DB, $A6D3D0BA, $B6803D5C, $AF77A709,
$33B4A34C, $397BC8D6, $5EE22B95, $5F0E5304, $81ED6F61, $20E74364, $B45E1378, $DE18639B, $881CA122, $B96726D1, $8049A7E8, $22B7DA7B, $5E552D25, $5272D237,
$79D2951C, $C60D894C, $488CB402, $1BA4FE5B, $A4B09F6B, $1CA815CF, $A20C3005, $8871DF63, $B9DE2FCB, $0CC6C9E9, $0BEEFF53, $E3214517, $B4542835, $9F63293C,
$EE41E729, $6E1D2D7C, $50045286, $1E6685F3, $F33401C6, $30A22C95, $31A70850, $60930F13, $73F98417, $A1269859, $EC645C44, $52C877A9, $CDFF33A6, $A02B1741,
$7CBAD9A2, $2180036F, $50D99C08, $CB3F4861, $C26BD765, $64A3F6AB, $80342676, $25A75E7B, $E4E6D1FC, $20C710E6, $CDF0B680, $17844D3B, $31EEF84D, $7E0824E4,
$2CCB49EB, $846A3BAE, $8FF77888, $EE5D60F6, $7AF75673, $2FDD5CDB, $A11631C1, $30F66F43, $B3FAEC54, $157FD7FA, $EF8579CC, $D152DE58, $DB2FFD5E, $8F32CE19,
$306AF97A, $02F03EF8, $99319AD5, $C242FA0F, $A7E3EBB0, $C68E4906, $B8DA230C, $80823028, $DCDEF3C8, $D35FB171, $088A1BC8, $BEC0C560, $61A3C9E8, $BCA8F54D,
$C72FEFFA, $22822E99, $82C570B4, $D8D94E89, $8B1C34BC, $301E16E6, $273BE979, $B0FFEAA6, $61D9B8C6, $00B24869, $B7FFCE3F, $08DC283B, $43DAF65A, $F7E19798,
$7619B72F, $8F1C9BA4, $DC8637A0, $16A7D3B1, $9FC393B7, $A7136EEB, $C6BCC63E, $1A513742, $EF6828BC, $520365D6, $2D6A77AB, $3527ED4B, $821FD216, $095C6E2E,
$DB92F2FB, $5EEA29CB, $145892F5, $91584F7F, $5483697B, $2667A8CC, $85196048, $8C4BACEA, $833860D4, $0D23E0F9, $6C387E8A, $0AE6D249, $B284600C, $D835731D,
$DCB1C647, $AC4C56EA, $3EBD81B3, $230EABB0, $6438BC87, $F0B5B1FA, $8F5EA2B3, $FC184642, $0A036B7A, $4FB089BD, $649DA589, $A345415E, $5C038323, $3E5D3BB9,
$43D79572, $7E6DD07C, $06DFDF1E, $6C6CC4EF, $7160A539, $73BFBE70, $83877605, $4523ECF1);
cast_sbox3: array [0 .. 255] of DWord = ($8DEFC240, $25FA5D9F, $EB903DBF, $E810C907, $47607FFF, $369FE44B, $8C1FC644, $AECECA90, $BEB1F9BF, $EEFBCAEA,
$E8CF1950, $51DF07AE, $920E8806, $F0AD0548, $E13C8D83, $927010D5, $11107D9F, $07647DB9, $B2E3E4D4, $3D4F285E, $B9AFA820, $FADE82E0, $A067268B, $8272792E,
$553FB2C0, $489AE22B, $D4EF9794, $125E3FBC, $21FFFCEE, $825B1BFD, $9255C5ED, $1257A240, $4E1A8302, $BAE07FFF, $528246E7, $8E57140E, $3373F7BF, $8C9F8188,
$A6FC4EE8, $C982B5A5, $A8C01DB7, $579FC264, $67094F31, $F2BD3F5F, $40FFF7C1, $1FB78DFC, $8E6BD2C1, $437BE59B, $99B03DBF, $B5DBC64B, $638DC0E6, $55819D99,
$A197C81C, $4A012D6E, $C5884A28, $CCC36F71, $B843C213, $6C0743F1, $8309893C, $0FEDDD5F, $2F7FE850, $D7C07F7E, $02507FBF, $5AFB9A04, $A747D2D0, $1651192E,
$AF70BF3E, $58C31380, $5F98302E, $727CC3C4, $0A0FB402, $0F7FEF82, $8C96FDAD, $5D2C2AAE, $8EE99A49, $50DA88B8, $8427F4A0, $1EAC5790, $796FB449, $8252DC15,
$EFBD7D9B, $A672597D, $ADA840D8, $45F54504, $FA5D7403, $E83EC305, $4F91751A, $925669C2, $23EFE941, $A903F12E, $60270DF2, $0276E4B6, $94FD6574, $927985B2,
$8276DBCB, $02778176, $F8AF918D, $4E48F79E, $8F616DDF, $E29D840E, $842F7D83, $340CE5C8, $96BBB682, $93B4B148, $EF303CAB, $984FAF28, $779FAF9B, $92DC560D,
$224D1E20, $8437AA88, $7D29DC96, $2756D3DC, $8B907CEE, $B51FD240, $E7C07CE3, $E566B4A1, $C3E9615E, $3CF8209D, $6094D1E3, $CD9CA341, $5C76460E, $00EA983B,
$D4D67881, $FD47572C, $F76CEDD9, $BDA8229C, $127DADAA, $438A074E, $1F97C090, $081BDB8A, $93A07EBE, $B938CA15, $97B03CFF, $3DC2C0F8, $8D1AB2EC, $64380E51,
$68CC7BFB, $D90F2788, $12490181, $5DE5FFD4, $DD7EF86A, $76A2E214, $B9A40368, $925D958F, $4B39FFFA, $BA39AEE9, $A4FFD30B, $FAF7933B, $6D498623, $193CBCFA,
$27627545, $825CF47A, $61BD8BA0, $D11E42D1, $CEAD04F4, $127EA392, $10428DB7, $8272A972, $9270C4A8, $127DE50B, $285BA1C8, $3C62F44F, $35C0EAA5, $E805D231,
$428929FB, $B4FCDF82, $4FB66A53, $0E7DC15B, $1F081FAB, $108618AE, $FCFD086D, $F9FF2889, $694BCC11, $236A5CAE, $12DECA4D, $2C3F8CC5, $D2D02DFE, $F8EF5896,
$E4CF52DA, $95155B67, $494A488C, $B9B6A80C, $5C8F82BC, $89D36B45, $3A609437, $EC00C9A9, $44715253, $0A874B49, $D773BC40, $7C34671C, $02717EF6, $4FEB5536,
$A2D02FFF, $D2BF60C4, $D43F03C0, $50B4EF6D, $07478CD1, $006E1888, $A2E53F55, $B9E6D4BC, $A2048016, $97573833, $D7207D67, $DE0F8F3D, $72F87B33, $ABCC4F33,
$7688C55D, $7B00A6B0, $947B0001, $570075D2, $F9BB88F8, $8942019E, $4264A5FF, $856302E0, $72DBD92B, $EE971B69, $6EA22FDE, $5F08AE2B, $AF7A616D, $E5C98767,
$CF1FEBD2, $61EFC8C2, $F1AC2571, $CC8239C2, $67214CB8, $B1E583D1, $B7DC3E62, $7F10BDCE, $F90A5C38, $0FF0443D, $606E6DC6, $60543A49, $5727C148, $2BE98A1D,
$8AB41738, $20E1BE24, $AF96DA0F, $68458425, $99833BE5, $600D457D, $282F9350, $8334B362, $D91D1120, $2B6D8DA0, $642B1E31, $9C305A00, $52BCE688, $1B03588A,
$F7BAEFD5, $4142ED9C, $A4315C11, $83323EC5, $DFEF4636, $A133C501, $E9D3531C, $EE353783);
cast_sbox4: array [0 .. 255] of DWord = ($9DB30420, $1FB6E9DE, $A7BE7BEF, $D273A298, $4A4F7BDB, $64AD8C57, $85510443, $FA020ED1, $7E287AFF, $E60FB663,
$095F35A1, $79EBF120, $FD059D43, $6497B7B1, $F3641F63, $241E4ADF, $28147F5F, $4FA2B8CD, $C9430040, $0CC32220, $FDD30B30, $C0A5374F, $1D2D00D9, $24147B15,
$EE4D111A, $0FCA5167, $71FF904C, $2D195FFE, $1A05645F, $0C13FEFE, $081B08CA, $05170121, $80530100, $E83E5EFE, $AC9AF4F8, $7FE72701, $D2B8EE5F, $06DF4261,
$BB9E9B8A, $7293EA25, $CE84FFDF, $F5718801, $3DD64B04, $A26F263B, $7ED48400, $547EEBE6, $446D4CA0, $6CF3D6F5, $2649ABDF, $AEA0C7F5, $36338CC1, $503F7E93,
$D3772061, $11B638E1, $72500E03, $F80EB2BB, $ABE0502E, $EC8D77DE, $57971E81, $E14F6746, $C9335400, $6920318F, $081DBB99, $FFC304A5, $4D351805, $7F3D5CE3,
$A6C866C6, $5D5BCCA9, $DAEC6FEA, $9F926F91, $9F46222F, $3991467D, $A5BF6D8E, $1143C44F, $43958302, $D0214EEB, $022083B8, $3FB6180C, $18F8931E, $281658E6,
$26486E3E, $8BD78A70, $7477E4C1, $B506E07C, $F32D0A25, $79098B02, $E4EABB81, $28123B23, $69DEAD38, $1574CA16, $DF871B62, $211C40B7, $A51A9EF9, $0014377B,
$041E8AC8, $09114003, $BD59E4D2, $E3D156D5, $4FE876D5, $2F91A340, $557BE8DE, $00EAE4A7, $0CE5C2EC, $4DB4BBA6, $E756BDFF, $DD3369AC, $EC17B035, $06572327,
$99AFC8B0, $56C8C391, $6B65811C, $5E146119, $6E85CB75, $BE07C002, $C2325577, $893FF4EC, $5BBFC92D, $D0EC3B25, $B7801AB7, $8D6D3B24, $20C763EF, $C366A5FC,
$9C382880, $0ACE3205, $AAC9548A, $ECA1D7C7, $041AFA32, $1D16625A, $6701902C, $9B757A54, $31D477F7, $9126B031, $36CC6FDB, $C70B8B46, $D9E66A48, $56E55A79,
$026A4CEB, $52437EFF, $2F8F76B4, $0DF980A5, $8674CDE3, $EDDA04EB, $17A9BE04, $2C18F4DF, $B7747F9D, $AB2AF7B4, $EFC34D20, $2E096B7C, $1741A254, $E5B6A035,
$213D42F6, $2C1C7C26, $61C2F50F, $6552DAF9, $D2C231F8, $25130F69, $D8167FA2, $0418F2C8, $001A96A6, $0D1526AB, $63315C21, $5E0A72EC, $49BAFEFD, $187908D9,
$8D0DBD86, $311170A7, $3E9B640C, $CC3E10D7, $D5CAD3B6, $0CAEC388, $F73001E1, $6C728AFF, $71EAE2A1, $1F9AF36E, $CFCBD12F, $C1DE8417, $AC07BE6B, $CB44A1D8,
$8B9B0F56, $013988C3, $B1C52FCA, $B4BE31CD, $D8782806, $12A3A4E2, $6F7DE532, $58FD7EB6, $D01EE900, $24ADFFC2, $F4990FC5, $9711AAC5, $001D7B95, $82E5E7D2,
$109873F6, $00613096, $C32D9521, $ADA121FF, $29908415, $7FBB977F, $AF9EB3DB, $29C9ED2A, $5CE2A465, $A730F32C, $D0AA3FE8, $8A5CC091, $D49E2CE7, $0CE454A9,
$D60ACD86, $015F1919, $77079103, $DEA03AF6, $78A8565E, $DEE356DF, $21F05CBE, $8B75E387, $B3C50651, $B8A5C3EF, $D8EEB6D2, $E523BE77, $C2154529, $2F69EFDF,
$AFE67AFB, $F470C4B2, $F3E0EB5B, $D6CC9876, $39E4460C, $1FDA8538, $1987832F, $CA007367, $A99144F8, $296B299E, $492FC295, $9266BEAB, $B5676E69, $9BD3DDDA,
$DF7E052F, $DB25701C, $1B5E51EE, $F65324E6, $6AFCE36C, $0316CC04, $8644213E, $B7DC59D0, $7965291F, $CCD6FD43, $41823979, $932BCDF6, $B657C34D, $4EDFD282,
$7AE5290C, $3CB9536B, $851E20FE, $9833557E, $13ECF0B0, $D3FFB372, $3F85C5C1, $0AEF7ED2);
cast_sbox5: array [0 .. 255] of DWord = ($7EC90C04, $2C6E74B9, $9B0E66DF, $A6337911, $B86A7FFF, $1DD358F5, $44DD9D44, $1731167F, $08FBF1FA, $E7F511CC,
$D2051B00, $735ABA00, $2AB722D8, $386381CB, $ACF6243A, $69BEFD7A, $E6A2E77F, $F0C720CD, $C4494816, $CCF5C180, $38851640, $15B0A848, $E68B18CB, $4CAADEFF,
$5F480A01, $0412B2AA, $259814FC, $41D0EFE2, $4E40B48D, $248EB6FB, $8DBA1CFE, $41A99B02, $1A550A04, $BA8F65CB, $7251F4E7, $95A51725, $C106ECD7, $97A5980A,
$C539B9AA, $4D79FE6A, $F2F3F763, $68AF8040, $ED0C9E56, $11B4958B, $E1EB5A88, $8709E6B0, $D7E07156, $4E29FEA7, $6366E52D, $02D1C000, $C4AC8E05, $9377F571,
$0C05372A, $578535F2, $2261BE02, $D642A0C9, $DF13A280, $74B55BD2, $682199C0, $D421E5EC, $53FB3CE8, $C8ADEDB3, $28A87FC9, $3D959981, $5C1FF900, $FE38D399,
$0C4EFF0B, $062407EA, $AA2F4FB1, $4FB96976, $90C79505, $B0A8A774, $EF55A1FF, $E59CA2C2, $A6B62D27, $E66A4263, $DF65001F, $0EC50966, $DFDD55BC, $29DE0655,
$911E739A, $17AF8975, $32C7911C, $89F89468, $0D01E980, $524755F4, $03B63CC9, $0CC844B2, $BCF3F0AA, $87AC36E9, $E53A7426, $01B3D82B, $1A9E7449, $64EE2D7E,
$CDDBB1DA, $01C94910, $B868BF80, $0D26F3FD, $9342EDE7, $04A5C284, $636737B6, $50F5B616, $F24766E3, $8ECA36C1, $136E05DB, $FEF18391, $FB887A37, $D6E7F7D4,
$C7FB7DC9, $3063FCDF, $B6F589DE, $EC2941DA, $26E46695, $B7566419, $F654EFC5, $D08D58B7, $48925401, $C1BACB7F, $E5FF550F, $B6083049, $5BB5D0E8, $87D72E5A,
$AB6A6EE1, $223A66CE, $C62BF3CD, $9E0885F9, $68CB3E47, $086C010F, $A21DE820, $D18B69DE, $F3F65777, $FA02C3F6, $407EDAC3, $CBB3D550, $1793084D, $B0D70EBA,
$0AB378D5, $D951FB0C, $DED7DA56, $4124BBE4, $94CA0B56, $0F5755D1, $E0E1E56E, $6184B5BE, $580A249F, $94F74BC0, $E327888E, $9F7B5561, $C3DC0280, $05687715,
$646C6BD7, $44904DB3, $66B4F0A3, $C0F1648A, $697ED5AF, $49E92FF6, $309E374F, $2CB6356A, $85808573, $4991F840, $76F0AE02, $083BE84D, $28421C9A, $44489406,
$736E4CB8, $C1092910, $8BC95FC6, $7D869CF4, $134F616F, $2E77118D, $B31B2BE1, $AA90B472, $3CA5D717, $7D161BBA, $9CAD9010, $AF462BA2, $9FE459D2, $45D34559,
$D9F2DA13, $DBC65487, $F3E4F94E, $176D486F, $097C13EA, $631DA5C7, $445F7382, $175683F4, $CDC66A97, $70BE0288, $B3CDCF72, $6E5DD2F3, $20936079, $459B80A5,
$BE60E2DB, $A9C23101, $EBA5315C, $224E42F2, $1C5C1572, $F6721B2C, $1AD2FFF3, $8C25404E, $324ED72F, $4067B7FD, $0523138E, $5CA3BC78, $DC0FD66E, $75922283,
$784D6B17, $58EBB16E, $44094F85, $3F481D87, $FCFEAE7B, $77B5FF76, $8C2302BF, $AAF47556, $5F46B02A, $2B092801, $3D38F5F7, $0CA81F36, $52AF4A8A, $66D5E7C0,
$DF3B0874, $95055110, $1B5AD7A8, $F61ED5AD, $6CF6E479, $20758184, $D0CEFA65, $88F7BE58, $4A046826, $0FF6F8F3, $A09C7F70, $5346ABA0, $5CE96C28, $E176EDA3,
$6BAC307F, $376829D2, $85360FA9, $17E3FE2A, $24B79767, $F5A96B20, $D6CD2595, $68FF1EBF, $7555442C, $F19F06BE, $F9E0659A, $EEB9491D, $34010718, $BB30CAB8,
$E822FE15, $88570983, $750E6249, $DA627E55, $5E76FFA8, $B1534546, $6D47DE08, $EFE9E7D4);
cast_sbox6: array [0 .. 255] of DWord = ($F6FA8F9D, $2CAC6CE1, $4CA34867, $E2337F7C, $95DB08E7, $016843B4, $ECED5CBC, $325553AC, $BF9F0960, $DFA1E2ED,
$83F0579D, $63ED86B9, $1AB6A6B8, $DE5EBE39, $F38FF732, $8989B138, $33F14961, $C01937BD, $F506C6DA, $E4625E7E, $A308EA99, $4E23E33C, $79CBD7CC, $48A14367,
$A3149619, $FEC94BD5, $A114174A, $EAA01866, $A084DB2D, $09A8486F, $A888614A, $2900AF98, $01665991, $E1992863, $C8F30C60, $2E78EF3C, $D0D51932, $CF0FEC14,
$F7CA07D2, $D0A82072, $FD41197E, $9305A6B0, $E86BE3DA, $74BED3CD, $372DA53C, $4C7F4448, $DAB5D440, $6DBA0EC3, $083919A7, $9FBAEED9, $49DBCFB0, $4E670C53,
$5C3D9C01, $64BDB941, $2C0E636A, $BA7DD9CD, $EA6F7388, $E70BC762, $35F29ADB, $5C4CDD8D, $F0D48D8C, $B88153E2, $08A19866, $1AE2EAC8, $284CAF89, $AA928223,
$9334BE53, $3B3A21BF, $16434BE3, $9AEA3906, $EFE8C36E, $F890CDD9, $80226DAE, $C340A4A3, $DF7E9C09, $A694A807, $5B7C5ECC, $221DB3A6, $9A69A02F, $68818A54,
$CEB2296F, $53C0843A, $FE893655, $25BFE68A, $B4628ABC, $CF222EBF, $25AC6F48, $A9A99387, $53BDDB65, $E76FFBE7, $E967FD78, $0BA93563, $8E342BC1, $E8A11BE9,
$4980740D, $C8087DFC, $8DE4BF99, $A11101A0, $7FD37975, $DA5A26C0, $E81F994F, $9528CD89, $FD339FED, $B87834BF, $5F04456D, $22258698, $C9C4C83B, $2DC156BE,
$4F628DAA, $57F55EC5, $E2220ABE, $D2916EBF, $4EC75B95, $24F2C3C0, $42D15D99, $CD0D7FA0, $7B6E27FF, $A8DC8AF0, $7345C106, $F41E232F, $35162386, $E6EA8926,
$3333B094, $157EC6F2, $372B74AF, $692573E4, $E9A9D848, $F3160289, $3A62EF1D, $A787E238, $F3A5F676, $74364853, $20951063, $4576698D, $B6FAD407, $592AF950,
$36F73523, $4CFB6E87, $7DA4CEC0, $6C152DAA, $CB0396A8, $C50DFE5D, $FCD707AB, $0921C42F, $89DFF0BB, $5FE2BE78, $448F4F33, $754613C9, $2B05D08D, $48B9D585,
$DC049441, $C8098F9B, $7DEDE786, $C39A3373, $42410005, $6A091751, $0EF3C8A6, $890072D6, $28207682, $A9A9F7BE, $BF32679D, $D45B5B75, $B353FD00, $CBB0E358,
$830F220A, $1F8FB214, $D372CF08, $CC3C4A13, $8CF63166, $061C87BE, $88C98F88, $6062E397, $47CF8E7A, $B6C85283, $3CC2ACFB, $3FC06976, $4E8F0252, $64D8314D,
$DA3870E3, $1E665459, $C10908F0, $513021A5, $6C5B68B7, $822F8AA0, $3007CD3E, $74719EEF, $DC872681, $073340D4, $7E432FD9, $0C5EC241, $8809286C, $F592D891,
$08A930F6, $957EF305, $B7FBFFBD, $C266E96F, $6FE4AC98, $B173ECC0, $BC60B42A, $953498DA, $FBA1AE12, $2D4BD736, $0F25FAAB, $A4F3FCEB, $E2969123, $257F0C3D,
$9348AF49, $361400BC, $E8816F4A, $3814F200, $A3F94043, $9C7A54C2, $BC704F57, $DA41E7F9, $C25AD33A, $54F4A084, $B17F5505, $59357CBE, $EDBD15C8, $7F97C5AB,
$BA5AC7B5, $B6F6DEAF, $3A479C3A, $5302DA25, $653D7E6A, $54268D49, $51A477EA, $5017D55B, $D7D25D88, $44136C76, $0404A8C8, $B8E5A121, $B81A928A, $60ED5869,
$97C55B96, $EAEC991B, $29935913, $01FDB7F1, $088E8DFA, $9AB6F6F5, $3B4CBF9F, $4A5DE3AB, $E6051D35, $A0E1D855, $D36B4CF1, $F544EDEB, $B0E93524, $BEBB8FBD,
$A2D762CF, $49C92F54, $38B5F331, $7128A454, $48392905, $A65B1DB8, $851C97BD, $D675CF2F);
cast_sbox7: array [0 .. 255] of DWord = ($85E04019, $332BF567, $662DBFFF, $CFC65693, $2A8D7F6F, $AB9BC912, $DE6008A1, $2028DA1F, $0227BCE7, $4D642916,
$18FAC300, $50F18B82, $2CB2CB11, $B232E75C, $4B3695F2, $B28707DE, $A05FBCF6, $CD4181E9, $E150210C, $E24EF1BD, $B168C381, $FDE4E789, $5C79B0D8, $1E8BFD43,
$4D495001, $38BE4341, $913CEE1D, $92A79C3F, $089766BE, $BAEEADF4, $1286BECF, $B6EACB19, $2660C200, $7565BDE4, $64241F7A, $8248DCA9, $C3B3AD66, $28136086,
$0BD8DFA8, $356D1CF2, $107789BE, $B3B2E9CE, $0502AA8F, $0BC0351E, $166BF52A, $EB12FF82, $E3486911, $D34D7516, $4E7B3AFF, $5F43671B, $9CF6E037, $4981AC83,
$334266CE, $8C9341B7, $D0D854C0, $CB3A6C88, $47BC2829, $4725BA37, $A66AD22B, $7AD61F1E, $0C5CBAFA, $4437F107, $B6E79962, $42D2D816, $0A961288, $E1A5C06E,
$13749E67, $72FC081A, $B1D139F7, $F9583745, $CF19DF58, $BEC3F756, $C06EBA30, $07211B24, $45C28829, $C95E317F, $BC8EC511, $38BC46E9, $C6E6FA14, $BAE8584A,
$AD4EBC46, $468F508B, $7829435F, $F124183B, $821DBA9F, $AFF60FF4, $EA2C4E6D, $16E39264, $92544A8B, $009B4FC3, $ABA68CED, $9AC96F78, $06A5B79A, $B2856E6E,
$1AEC3CA9, $BE838688, $0E0804E9, $55F1BE56, $E7E5363B, $B3A1F25D, $F7DEBB85, $61FE033C, $16746233, $3C034C28, $DA6D0C74, $79AAC56C, $3CE4E1AD, $51F0C802,
$98F8F35A, $1626A49F, $EED82B29, $1D382FE3, $0C4FB99A, $BB325778, $3EC6D97B, $6E77A6A9, $CB658B5C, $D45230C7, $2BD1408B, $60C03EB7, $B9068D78, $A33754F4,
$F430C87D, $C8A71302, $B96D8C32, $EBD4E7BE, $BE8B9D2D, $7979FB06, $E7225308, $8B75CF77, $11EF8DA4, $E083C858, $8D6B786F, $5A6317A6, $FA5CF7A0, $5DDA0033,
$F28EBFB0, $F5B9C310, $A0EAC280, $08B9767A, $A3D9D2B0, $79D34217, $021A718D, $9AC6336A, $2711FD60, $438050E3, $069908A8, $3D7FEDC4, $826D2BEF, $4EEB8476,
$488DCF25, $36C9D566, $28E74E41, $C2610ACA, $3D49A9CF, $BAE3B9DF, $B65F8DE6, $92AEAF64, $3AC7D5E6, $9EA80509, $F22B017D, $A4173F70, $DD1E16C3, $15E0D7F9,
$50B1B887, $2B9F4FD5, $625ABA82, $6A017962, $2EC01B9C, $15488AA9, $D716E740, $40055A2C, $93D29A22, $E32DBF9A, $058745B9, $3453DC1E, $D699296E, $496CFF6F,
$1C9F4986, $DFE2ED07, $B87242D1, $19DE7EAE, $053E561A, $15AD6F8C, $66626C1C, $7154C24C, $EA082B2A, $93EB2939, $17DCB0F0, $58D4F2AE, $9EA294FB, $52CF564C,
$9883FE66, $2EC40581, $763953C3, $01D6692E, $D3A0C108, $A1E7160E, $E4F2DFA6, $693ED285, $74904698, $4C2B0EDD, $4F757656, $5D393378, $A132234F, $3D321C5D,
$C3F5E194, $4B269301, $C79F022F, $3C997E7E, $5E4F9504, $3FFAFBBD, $76F7AD0E, $296693F4, $3D1FCE6F, $C61E45BE, $D3B5AB34, $F72BF9B7, $1B0434C0, $4E72B567,
$5592A33D, $B5229301, $CFD2A87F, $60AEB767, $1814386B, $30BCC33D, $38A0C07D, $FD1606F2, $C363519B, $589DD390, $5479F8E6, $1CB8D647, $97FD61A9, $EA7759F4,
$2D57539D, $569A58CF, $E84E63AD, $462E1B78, $6580F87E, $F3817914, $91DA55F4, $40A230F3, $D1988F35, $B6E318D2, $3FFA50BC, $3D40F021, $C3C0BDAE, $4958C24C,
$518F36B2, $84B1D370, $0FEDCE83, $878DDADA, $F2A279C7, $94E01BE8, $90716F4B, $954B8AA3);
cast_sbox8: array [0 .. 255] of DWord = ($E216300D, $BBDDFFFC, $A7EBDABD, $35648095, $7789F8B7, $E6C1121B, $0E241600, $052CE8B5, $11A9CFB0, $E5952F11,
$ECE7990A, $9386D174, $2A42931C, $76E38111, $B12DEF3A, $37DDDDFC, $DE9ADEB1, $0A0CC32C, $BE197029, $84A00940, $BB243A0F, $B4D137CF, $B44E79F0, $049EEDFD,
$0B15A15D, $480D3168, $8BBBDE5A, $669DED42, $C7ECE831, $3F8F95E7, $72DF191B, $7580330D, $94074251, $5C7DCDFA, $ABBE6D63, $AA402164, $B301D40A, $02E7D1CA,
$53571DAE, $7A3182A2, $12A8DDEC, $FDAA335D, $176F43E8, $71FB46D4, $38129022, $CE949AD4, $B84769AD, $965BD862, $82F3D055, $66FB9767, $15B80B4E, $1D5B47A0,
$4CFDE06F, $C28EC4B8, $57E8726E, $647A78FC, $99865D44, $608BD593, $6C200E03, $39DC5FF6, $5D0B00A3, $AE63AFF2, $7E8BD632, $70108C0C, $BBD35049, $2998DF04,
$980CF42A, $9B6DF491, $9E7EDD53, $06918548, $58CB7E07, $3B74EF2E, $522FFFB1, $D24708CC, $1C7E27CD, $A4EB215B, $3CF1D2E2, $19B47A38, $424F7618, $35856039,
$9D17DEE7, $27EB35E6, $C9AFF67B, $36BAF5B8, $09C467CD, $C18910B1, $E11DBF7B, $06CD1AF8, $7170C608, $2D5E3354, $D4DE495A, $64C6D006, $BCC0C62C, $3DD00DB3,
$708F8F34, $77D51B42, $264F620F, $24B8D2BF, $15C1B79E, $46A52564, $F8D7E54E, $3E378160, $7895CDA5, $859C15A5, $E6459788, $C37BC75F, $DB07BA0C, $0676A3AB,
$7F229B1E, $31842E7B, $24259FD7, $F8BEF472, $835FFCB8, $6DF4C1F2, $96F5B195, $FD0AF0FC, $B0FE134C, $E2506D3D, $4F9B12EA, $F215F225, $A223736F, $9FB4C428,
$25D04979, $34C713F8, $C4618187, $EA7A6E98, $7CD16EFC, $1436876C, $F1544107, $BEDEEE14, $56E9AF27, $A04AA441, $3CF7C899, $92ECBAE6, $DD67016D, $151682EB,
$A842EEDF, $FDBA60B4, $F1907B75, $20E3030F, $24D8C29E, $E139673B, $EFA63FB8, $71873054, $B6F2CF3B, $9F326442, $CB15A4CC, $B01A4504, $F1E47D8D, $844A1BE5,
$BAE7DFDC, $42CBDA70, $CD7DAE0A, $57E85B7A, $D53F5AF6, $20CF4D8C, $CEA4D428, $79D130A4, $3486EBFB, $33D3CDDC, $77853B53, $37EFFCB5, $C5068778, $E580B3E6,
$4E68B8F4, $C5C8B37E, $0D809EA2, $398FEB7C, $132A4F94, $43B7950E, $2FEE7D1C, $223613BD, $DD06CAA2, $37DF932B, $C4248289, $ACF3EBC3, $5715F6B7, $EF3478DD,
$F267616F, $C148CBE4, $9052815E, $5E410FAB, $B48A2465, $2EDA7FA4, $E87B40E4, $E98EA084, $5889E9E1, $EFD390FC, $DD07D35B, $DB485694, $38D7E5B2, $57720101,
$730EDEBC, $5B643113, $94917E4F, $503C2FBA, $646F1282, $7523D24A, $E0779695, $F9C17A8F, $7A5B2121, $D187B896, $29263A4D, $BA510CDF, $81F47C9F, $AD1163ED,
$EA7B5965, $1A00726E, $11403092, $00DA6D77, $4A0CDD61, $AD1F4603, $605BDFB0, $9EEDC364, $22EBE6A8, $CEE7D28A, $A0E736A0, $5564A6B9, $10853209, $C7EB8F37,
$2DE705CA, $8951570F, $DF09822B, $BD691A6C, $AA12E4F2, $87451C0F, $E0F6A27A, $3ADA4819, $4CF1764F, $0D771C2B, $67CDB156, $350D8384, $5938FA0F, $42399EF3,
$36997B07, $0E84093D, $4AA93E61, $8360D87B, $1FA98B0C, $1149382C, $E97625A5, $0614D1B7, $0E25244B, $0C768347, $589E8D82, $0D2059D1, $A466BB1E, $F8DA0A82,
$04F19130, $BA6E4EC0, $99265164, $1EE7230D, $50B2AD80, $EAEE6801, $8DB2A283, $EA8BF59E);
function LRot32(a, n: DWord): DWord;
begin
Result := (a shl n) or (a shr (32 - n));
end;
class function TncEnc_cast128.GetMaxKeySize: integer;
begin
Result := 128;
end;
class function TncEnc_cast128.GetAlgorithm: string;
begin
Result := 'Cast128';
end;
class function TncEnc_cast128.SelfTest: boolean;
const
Key: array [0 .. 15] of byte = ($01, $23, $45, $67, $12, $34, $56, $78, $23, $45, $67, $89, $34, $56, $78, $9A);
InBlock: array [0 .. 7] of byte = ($01, $23, $45, $67, $89, $AB, $CD, $EF);
Out128: array [0 .. 7] of byte = ($23, $8B, $4F, $E5, $84, $7E, $44, $B2);
Out80: array [0 .. 7] of byte = ($EB, $6A, $71, $1A, $2C, $02, $27, $1B);
Out40: array [0 .. 7] of byte = ($7A, $C8, $16, $D1, $6E, $9B, $30, $2E);
var
Block: array [0 .. 7] of byte;
Cipher: TncEnc_cast128;
begin
Cipher := TncEnc_cast128.Create(nil);
Cipher.Init(Key, 128, nil);
Cipher.EncryptECB(InBlock, Block);
Result := boolean(CompareMem(@Block, @Out128, 8));
Cipher.DecryptECB(Block, Block);
Result := Result and boolean(CompareMem(@Block, @InBlock, 8));
Cipher.Burn;
Cipher.Init(Key, 80, nil);
Cipher.EncryptECB(InBlock, Block);
Result := Result and boolean(CompareMem(@Block, @Out80, 8));
Cipher.DecryptECB(Block, Block);
Result := Result and boolean(CompareMem(@Block, @InBlock, 8));
Cipher.Burn;
Cipher.Init(Key, 40, nil);
Cipher.EncryptECB(InBlock, Block);
Result := Result and boolean(CompareMem(@Block, @Out40, 8));
Cipher.DecryptECB(Block, Block);
Result := Result and boolean(CompareMem(@Block, @InBlock, 8));
Cipher.Burn;
Cipher.Free;
end;
procedure TncEnc_cast128.InitKey(const Key; Size: longword);
var
x, t, z: array [0 .. 3] of DWord;
i: longword;
begin
Size := Size div 8;
if Size <= 10 then
Rounds := 12
else
Rounds := 16;
FillChar(x, Sizeof(x), 0);
Move(Key, x, Size);
x[0] := (x[0] shr 24) or ((x[0] shr 8) and $FF00) or ((x[0] shl 8) and $FF0000) or (x[0] shl 24);
x[1] := (x[1] shr 24) or ((x[1] shr 8) and $FF00) or ((x[1] shl 8) and $FF0000) or (x[1] shl 24);
x[2] := (x[2] shr 24) or ((x[2] shr 8) and $FF00) or ((x[2] shl 8) and $FF0000) or (x[2] shl 24);
x[3] := (x[3] shr 24) or ((x[3] shr 8) and $FF00) or ((x[3] shl 8) and $FF0000) or (x[3] shl 24);
i := 0;
while i < 32 do
begin
case (i and 4) of
0:
begin
z[0] := x[0] xor cast_sbox5[(x[3] shr 16) and $FF] xor cast_sbox6[x[3] and $FF] xor cast_sbox7[x[3] shr 24] xor cast_sbox8[(x[3] shr 8) and $FF]
xor cast_sbox7[x[2] shr 24];
t[0] := z[0];
z[1] := x[2] xor cast_sbox5[z[0] shr 24] xor cast_sbox6[(z[0] shr 8) and $FF] xor cast_sbox7[(z[0] shr 16) and $FF] xor cast_sbox8[z[0] and $FF]
xor cast_sbox8[(x[2] shr 8) and $FF];
t[1] := z[1];
z[2] := x[3] xor cast_sbox5[z[1] and $FF] xor cast_sbox6[(z[1] shr 8) and $FF] xor cast_sbox7[(z[1] shr 16) and $FF] xor cast_sbox8[z[1] shr 24]
xor cast_sbox5[(x[2] shr 16) and $FF];
t[2] := z[2];
z[3] := x[1] xor cast_sbox5[(z[2] shr 8) and $FF] xor cast_sbox6[(z[2] shr 16) and $FF] xor cast_sbox7[z[2] and $FF] xor cast_sbox8[z[2] shr 24]
xor cast_sbox6[x[2] and $FF];
t[3] := z[3];
end;
4:
begin
x[0] := z[2] xor cast_sbox5[(z[1] shr 16) and $FF] xor cast_sbox6[z[1] and $FF] xor cast_sbox7[z[1] shr 24] xor cast_sbox8[(z[1] shr 8) and $FF]
xor cast_sbox7[z[0] shr 24];
t[0] := x[0];
x[1] := z[0] xor cast_sbox5[x[0] shr 24] xor cast_sbox6[(x[0] shr 8) and $FF] xor cast_sbox7[(x[0] shr 16) and $FF] xor cast_sbox8[x[0] and $FF]
xor cast_sbox8[(z[0] shr 8) and $FF];
t[1] := x[1];
x[2] := z[1] xor cast_sbox5[x[1] and $FF] xor cast_sbox6[(x[1] shr 8) and $FF] xor cast_sbox7[(x[1] shr 16) and $FF] xor cast_sbox8[x[1] shr 24]
xor cast_sbox5[(z[0] shr 16) and $FF];
t[2] := x[2];
x[3] := z[3] xor cast_sbox5[(x[2] shr 8) and $FF] xor cast_sbox6[(x[2] shr 16) and $FF] xor cast_sbox7[x[2] and $FF] xor cast_sbox8[x[2] shr 24]
xor cast_sbox6[z[0] and $FF];
t[3] := x[3];
end;
end;
case (i and 12) of
0, 12:
begin
KeyData[i + 0] := cast_sbox5[t[2] shr 24] xor cast_sbox6[(t[2] shr 16) and $FF] xor cast_sbox7[t[1] and $FF] xor cast_sbox8[(t[1] shr 8) and $FF];
KeyData[i + 1] := cast_sbox5[(t[2] shr 8) and $FF] xor cast_sbox6[t[2] and $FF] xor cast_sbox7[(t[1] shr 16) and $FF] xor cast_sbox8[t[1] shr 24];
KeyData[i + 2] := cast_sbox5[t[3] shr 24] xor cast_sbox6[(t[3] shr 16) and $FF] xor cast_sbox7[t[0] and $FF] xor cast_sbox8[(t[0] shr 8) and $FF];
KeyData[i + 3] := cast_sbox5[(t[3] shr 8) and $FF] xor cast_sbox6[t[3] and $FF] xor cast_sbox7[(t[0] shr 16) and $FF] xor cast_sbox8[t[0] shr 24];
end;
4, 8:
begin
KeyData[i + 0] := cast_sbox5[t[0] and $FF] xor cast_sbox6[(t[0] shr 8) and $FF] xor cast_sbox7[t[3] shr 24] xor cast_sbox8[(t[3] shr 16) and $FF];
KeyData[i + 1] := cast_sbox5[(t[0] shr 16) and $FF] xor cast_sbox6[t[0] shr 24] xor cast_sbox7[(t[3] shr 8) and $FF] xor cast_sbox8[t[3] and $FF];
KeyData[i + 2] := cast_sbox5[t[1] and $FF] xor cast_sbox6[(t[1] shr 8) and $FF] xor cast_sbox7[t[2] shr 24] xor cast_sbox8[(t[2] shr 16) and $FF];
KeyData[i + 3] := cast_sbox5[(t[1] shr 16) and $FF] xor cast_sbox6[t[1] shr 24] xor cast_sbox7[(t[2] shr 8) and $FF] xor cast_sbox8[t[2] and $FF];
end;
end;
case (i and 12) of
0:
begin
KeyData[i + 0] := KeyData[i + 0] xor cast_sbox5[(z[0] shr 8) and $FF];
KeyData[i + 1] := KeyData[i + 1] xor cast_sbox6[(z[1] shr 8) and $FF];
KeyData[i + 2] := KeyData[i + 2] xor cast_sbox7[(z[2] shr 16) and $FF];
KeyData[i + 3] := KeyData[i + 3] xor cast_sbox8[z[3] shr 24];
end;
4:
begin
KeyData[i + 0] := KeyData[i + 0] xor cast_sbox5[x[2] shr 24];
KeyData[i + 1] := KeyData[i + 1] xor cast_sbox6[(x[3] shr 16) and $FF];
KeyData[i + 2] := KeyData[i + 2] xor cast_sbox7[x[0] and $FF];
KeyData[i + 3] := KeyData[i + 3] xor cast_sbox8[x[1] and $FF];
end;
8:
begin
KeyData[i + 0] := KeyData[i + 0] xor cast_sbox5[(z[2] shr 16) and $FF];
KeyData[i + 1] := KeyData[i + 1] xor cast_sbox6[z[3] shr 24];
KeyData[i + 2] := KeyData[i + 2] xor cast_sbox7[(z[0] shr 8) and $FF];
KeyData[i + 3] := KeyData[i + 3] xor cast_sbox8[(z[1] shr 8) and $FF];
end;
12:
begin
KeyData[i + 0] := KeyData[i + 0] xor cast_sbox5[x[0] and $FF];
KeyData[i + 1] := KeyData[i + 1] xor cast_sbox6[x[1] and $FF];
KeyData[i + 2] := KeyData[i + 2] xor cast_sbox7[x[2] shr 24];
KeyData[i + 3] := KeyData[i + 3] xor cast_sbox8[(x[3] shr 16) and $FF];
end;
end;
if (i >= 16) then
begin
KeyData[i + 0] := KeyData[i + 0] and 31;
KeyData[i + 1] := KeyData[i + 1] and 31;
KeyData[i + 2] := KeyData[i + 2] and 31;
KeyData[i + 3] := KeyData[i + 3] and 31;
end;
Inc(i, 4);
end;
end;
procedure TncEnc_cast128.Burn;
begin
FillChar(KeyData, Sizeof(KeyData), $FF);
Rounds := 0;
inherited Burn;
end;
procedure TncEnc_cast128.EncryptECB(const InData; var OutData);
var
t, l, r: DWord;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
l := Pdword(@InData)^;
r := Pdword(longword(@InData) + 4)^;
l := (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r := (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
t := LRot32(KeyData[0] + r, KeyData[0 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[1] xor l, KeyData[1 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[2] - r, KeyData[2 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[3] + l, KeyData[3 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[4] xor r, KeyData[4 + 16]);
l := l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[5] - l, KeyData[5 + 16]);
r := r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[6] + r, KeyData[6 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[7] xor l, KeyData[7 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[8] - r, KeyData[8 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[9] + l, KeyData[9 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[10] xor r, KeyData[10 + 16]);
l := l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[11] - l, KeyData[11 + 16]);
r := r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
if Rounds > 12 then
begin
t := LRot32(KeyData[12] + r, KeyData[12 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[13] xor l, KeyData[13 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[14] - r, KeyData[14 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[15] + l, KeyData[15 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
end;
l := (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r := (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
Pdword(@OutData)^ := r;
Pdword(longword(@OutData) + 4)^ := l;
end;
procedure TncEnc_cast128.DecryptECB(const InData; var OutData);
var
t, l, r: DWord;
begin
if not fInitialized then
raise EncEnc_blockcipher.Create('Cipher not initialized');
r := Pdword(@InData)^;
l := Pdword(longword(@InData) + 4)^;
l := (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r := (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
if Rounds > 12 then
begin
t := LRot32(KeyData[15] + l, KeyData[15 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[14] - r, KeyData[14 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[13] xor l, KeyData[13 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[12] + r, KeyData[12 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
end;
t := LRot32(KeyData[11] - l, KeyData[11 + 16]);
r := r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[10] xor r, KeyData[10 + 16]);
l := l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[9] + l, KeyData[9 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[8] - r, KeyData[8 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[7] xor l, KeyData[7 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[6] + r, KeyData[6 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[5] - l, KeyData[5 + 16]);
r := r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[4] xor r, KeyData[4 + 16]);
l := l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[3] + l, KeyData[3 + 16]);
r := r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t := LRot32(KeyData[2] - r, KeyData[2 + 16]);
l := l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t := LRot32(KeyData[1] xor l, KeyData[1 + 16]);
r := r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) + cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t := LRot32(KeyData[0] + r, KeyData[0 + 16]);
l := l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) - cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
l := (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r := (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
Pdword(@OutData)^ := l;
Pdword(longword(@OutData) + 4)^ := r;
end;
end.
|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Escape.Index;
interface
uses
Deltics.Unicode.Types;
type
UnicodeIndex = class (UnicodeEscapeBase)
class function EscapedLength(const aChar: WideChar): Integer; override;
class function EscapedLength(const aCodepoint: Codepoint): Integer; override;
class procedure EscapeA(const aChar: WideChar; const aBuffer: PAnsiChar); override;
class procedure EscapeA(const aCodepoint: Codepoint; const aBuffer: PAnsiChar); override;
class procedure EscapeW(const aChar: WideChar; const aBuffer: PWideChar); override;
class procedure EscapeW(const aCodepoint: Codepoint; const aBuffer: PWideChar); override;
end;
implementation
uses
Deltics.Unicode.Utils;
{ UnicodeIndex }
class function UnicodeIndex.EscapedLength(const aChar: WideChar): Integer;
begin
result := 6;
end;
class function UnicodeIndex.EscapedLength(const aCodepoint: Codepoint): Integer;
{
We do NOT raise an EInvalidCodepoint exception for codepoints outside the valid
range since this escape is used by other escapes to report such invalid codepoints.
i.e. although such codepoints are invalid, we can still escape that invalid codepoint
using the normal codepoint index escape which is a naive hex representation of
the codepoint (essentially UTF-32).
This is not possible in other escapes. e.g. in a Json escape, any codepoint
above $10000 must be escaped as a surrogate pair, but there is no way to encode
codepoints above $10ffff as surrogates.
}
begin
case aCodepoint of
$00000000..$0000ffff : result := 6;
$00010000..$000fffff : result := 7;
$00100000..$00ffffff : result := 8;
$01000000..$0fffffff : result := 9;
else // $10000000..$ffffffff
result := 10;
end;
end;
class procedure UnicodeIndex.EscapeA(const aChar: WideChar; const aBuffer: PAnsiChar);
begin
SetBuffer(aBuffer, 'U+' + AnsiHex(Word(aChar), 4, TRUE));
end;
class procedure UnicodeIndex.EscapeA(const aCodepoint: Codepoint; const aBuffer: PAnsiChar);
begin
SetBuffer(aBuffer, 'U+' + AnsiHex(aCodepoint, EscapedLength(aCodepoint) - 2, TRUE));
end;
class procedure UnicodeIndex.EscapeW(const aChar: WideChar; const aBuffer: PWideChar);
begin
SetBuffer(aBuffer, 'U+' + WideHex(Word(aChar), 4, TRUE));
end;
class procedure UnicodeIndex.EscapeW(const aCodepoint: Codepoint; const aBuffer: PWideChar);
begin
SetBuffer(aBuffer, 'U+' + WideHex(aCodepoint, EscapedLength(aCodepoint) - 2, TRUE));
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Коллекция событий (календарь)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.StockCalendar;
{$I Compiler.inc}
interface
uses Classes, Windows, SysUtils, Controls, Contnrs,Collections.Map,
StockChart.Definitions,
FC.Definitions;
type
TStockCalendarItem = class;
TStockCalendar = class(TInterfacedObject,IStockCalendarWriteable, IStockCalendar)
private
FItems: TList;
FEventHandlers: TInterfaceList;
FLastFoundDate: TDateTime;
FLastFoundIndex: integer;
protected
procedure Delete(index: integer);
procedure RaiseChangeEvent;
function GetItemImpl(index: integer):TStockCalendarItem; inline;
procedure DeleteInternal(index: integer);
procedure ClearInternal;
public
//from IStockCalendar
function Count: integer; inline;
function GetItem(index: integer):ISCCalendarItem;
//найти первый элемент в коллекции, который случился на указанную дату
//или первый случившийся позже, если точно на указанную дату ничего нет
function FindFirstItemGE(const aDateTime: TDateTime): integer;
//end of IStockCalendar
//IStockCalendarWriteable
procedure Add(const aID: integer;
const aDateTime: TDateTime;
const aCountry: string;
const aClass: integer;
const aIndicator: string;
const aPriority: string;
const aPeriod: string;
const aPreviousValue: string;
const aForecastValue: string;
const aFactValue: string;
const aPFChangeType: TSCCalendarChangeType;
const aFFChangeType: TSCCalendarChangeType;
const aSource: string;
const aNotes: string
);
procedure AddCopy(const aItem: IStockCalendarItem);
procedure Clear;
procedure AddEventHandler(const aHandler:ISCCalendarEventHandler);
procedure RemoveEventHandler(const aHandler:ISCCalendarEventHandler);
//end of IStockCalendarWriteable
constructor Create; overload;
constructor Create(aQuery: IStockDataCalendarQuery); overload;
procedure Load(aQuery: IStockDataCalendarQuery);
destructor Destroy; override;
end;
TStockCalendarItem=class (TInterfacedObject,ISCCalendarItem)
public
DateTime: TDateTime;
Country: string;
Class_: integer;
Indicator: string;
Priority: string;
Period: string;
PreviousValue: string;
ForecastValue: string;
FactValue: string;
PFChangeType: TSCCalendarChangeType;
FFChangeType: TSCCalendarChangeType;
Source: string;
Notes: string;
ID: integer;
//from ISCCalendarItem
function GetID: integer;
function GetKey: string;
function GetDateTime: TDateTime;
function GetCountry: string;
function GetClass: integer;
function GetIndicator: string;
function GetPriority: string;
function GetPeriod: string;
function GetPreviousValue: string;
function GetForecastValue: string;
function GetFactValue: string;
//в какую сторону сменился показатель, если сравнивать Previous и Fact
function GetPFChangeType: TSCCalendarChangeType;
//в какую сторону сменился показатель, если сравнивать Forecast и Fact
function GetFFChangeType: TSCCalendarChangeType;
//Откуда было взято
function GetSource: string;
function GetNotes: string;
end;
implementation
uses SystemService,DateUtils, Application.Definitions;
function TStockCalendarItem.GetClass: integer;
begin
result:=Class_;
end;
function TStockCalendarItem.GetCountry: string;
begin
result:=Country;
end;
function TStockCalendarItem.GetDateTime: TDateTime;
begin
result:=DateTime;
end;
function TStockCalendarItem.GetFactValue: string;
begin
result:=FactValue;
end;
function TStockCalendarItem.GetForecastValue: string;
begin
result:=ForecastValue;
end;
function TStockCalendarItem.GetID: integer;
begin
result:=ID;
end;
function TStockCalendarItem.GetIndicator: string;
begin
result:=Indicator;
end;
function TStockCalendarItem.GetKey: string;
begin
result:=DateTimeToStr(GetDateTime)+'|'+GetCountry+'|'+GetIndicator+'|'+GetPeriod;
end;
function TStockCalendarItem.GetNotes: string;
begin
result:=Notes;
end;
function TStockCalendarItem.GetPeriod: string;
begin
result:=Period;
end;
function TStockCalendarItem.GetPreviousValue: string;
begin
result:=PreviousValue;
end;
function TStockCalendarItem.GetPriority: string;
begin
result:=Priority;
end;
function TStockCalendarItem.GetSource: string;
begin
result:=Source;
end;
function TStockCalendarItem.GetPFChangeType: TSCCalendarChangeType;
begin
result:=PFChangeType;
end;
function TStockCalendarItem.GetFFChangeType: TSCCalendarChangeType;
begin
result:=FFChangeType;
end;
{ TStockCalendar }
constructor TStockCalendar.Create;
begin
FItems:=TList.Create;
FEventHandlers:=TInterfaceList.Create;
end;
procedure TStockCalendar.Delete(index: integer);
begin
RaiseChangeEvent;
end;
procedure TStockCalendar.DeleteInternal(index: integer);
begin
IInterface(GetItemImpl(index))._Release;
FItems.Delete(index);
end;
destructor TStockCalendar.Destroy;
begin
Clear;
FreeAndNil(FItems);
FreeAndNil(FEventHandlers);
inherited;
end;
function TStockCalendar.FindFirstItemGE(const aDateTime: TDateTime): integer;
var
i,b,e: integer;
begin
if (FLastFoundDate>0) and (FLastFoundIndex>=0) then
begin
i:=CompareDateTime(aDateTime,FLastFoundDate);
if i=0 then
begin
result:=FLastFoundIndex;
exit;
end
else if i>0 then
begin
b:=FLastFoundIndex;
e:=Count;
end
else begin
b:=0;
e:=FLastFoundIndex+1;
end;
end
else begin
b:=0;
e:=Count;
end;
//Ищем методом половинного деления
i:=-1;
while (e-b>1) do
begin
i:=(b+e) div 2;
if CompareDateTime(GetItemImpl(i).DateTime,aDateTime)>0 then
b:=i
else if CompareDateTime(GetItemImpl(i).DateTime,aDateTime)<0 then
e:=i
else
break;
end;
//Если поиск зашел слишков влево, двигаем вправо
while (i>=0) and (CompareDateTime(GetItemImpl(i).DateTime,aDateTime)<0) do
begin
inc(i);
//Больше двигать некуда
if (i>=Count) then
begin
i:=-1;
break;
end;
end;
//Если поиск зашел слишком вправо, двигаем влево
while (i>=1) and (CompareDateTime(GetItemImpl(i-1).DateTime,aDateTime)>=0) do
dec(i);
result:=i;
if result>=0 then //Запоминаем значение только в случае удачного поиска
begin
FLastFoundDate:=aDateTime;
FLastFoundIndex:=result;
end;
end;
function TStockCalendar.GetItem(index: integer): ISCCalendarItem;
begin
result:=TStockCalendarItem(FItems[index]);
end;
function TStockCalendar.GetItemImpl(index: integer): TStockCalendarItem;
begin
result:=TStockCalendarItem(FItems[index]);
end;
procedure TStockCalendar.Add(
const aID: integer;
const aDateTime: TDateTime;
const aCountry: string;
const aClass: integer;
const aIndicator: string;
const aPriority: string;
const aPeriod: string;
const aPreviousValue: string;
const aForecastValue: string;
const aFactValue: string;
const aPFChangeType: TSCCalendarChangeType;
const aFFChangeType: TSCCalendarChangeType;
const aSource: string;
const aNotes: string);
var
aData:TStockCalendarItem;
begin
aData:=TStockCalendarItem.Create;
IInterface(aData)._AddRef;
aData.ID:=aID;
aData.DateTime:=aDateTime;
aData.Country:=aCountry;
aData.Class_:=aClass;
aData.Indicator:=aIndicator;
aData.Priority:=aPriority;
aData.Period:=aPeriod;
aData.PreviousValue:=aPreviousValue;
aData.ForecastValue:=aForecastValue;
aData.FactValue:=aFactValue;
aData.PFChangeType:=aPFChangeType;
aData.FFChangeType:=aFFChangeType;
aData.Source:=aSource;
aData.Notes:=aNotes;
FItems.Add(aData);
FLastFoundDate:=-1;
FLastFoundIndex:=-1;
end;
procedure TStockCalendar.AddCopy(const aItem: IStockCalendarItem);
begin
Add(aItem.GetID,aItem.GetDateTime,aItem.GetCountry,aItem.GetClass,aItem.GetIndicator,
aItem.GetPriority,aItem.GetPeriod,aItem.GetPreviousValue,aItem.GetForecastValue,aItem.GetFactValue,aItem.GetPFChangeType,
aItem.GetFFChangeType,aItem.GetSource, aItem.GetNotes);
end;
procedure TStockCalendar.AddEventHandler(
const aHandler: ISCCalendarEventHandler);
begin
FEventHandlers.Add(aHandler)
end;
procedure TStockCalendar.Clear;
begin
ClearInternal;
FLastFoundDate:=-1;
FLastFoundIndex:=-1;
RaiseChangeEvent;
end;
procedure TStockCalendar.ClearInternal;
begin
while Count>0 do
DeleteInternal(Count-1);
end;
function TStockCalendar.Count: integer;
begin
result:=FItems.Count;
end;
constructor TStockCalendar.Create(aQuery: IStockDataCalendarQuery);
begin
Create;
Load(aQuery);
end;
procedure TStockCalendar.Load(aQuery: IStockDataCalendarQuery);
begin
ClearInternal;
while not aQuery.Eof do
begin
Add(aQuery.GetID,
aQuery.GetDateTime,
aQuery.GetCountry,
aQuery.GetClass,
aQuery.GetIndicator,
aQuery.GetPriority,
aQuery.GetPeriod,
aQuery.GetPreviousValue,
aQuery.GetForecastValue,
aQuery.GetFactValue,
aQuery.GetPFChangeType,
aQuery.GetFFChangeType,
aQuery.GetSource,
aQuery.GetNotes);
aQuery.Next;
end;
RaiseChangeEvent;
end;
procedure TStockCalendar.RaiseChangeEvent;
var
i: integer;
begin
for I := 0 to FEventHandlers.Count-1 do
(FEventHandlers[i] as ISCCalendarEventHandler).OnChange;
end;
procedure TStockCalendar.RemoveEventHandler(
const aHandler: ISCCalendarEventHandler);
begin
FEventHandlers.Remove(aHandler);
end;
end.
|
unit Finance.Stock;
interface
uses
Finance.interfaces,
System.JSON;
type
TFinanceStock = class(TInterfacedObject, iFinanceStock)
private
FParent : iFinanceStocks;
FCode : string;
FName : string;
FLocation : string;
FPoints : string;
FVariation : string;
public
constructor Create (Parent : iFinanceStocks);
destructor Destroy; override;
function Code : string; overload;
function Name : string; overload;
function Location : string; overload;
function Points : string; overload;
function Variation : string; overload;
function Code (value : string) : iFinanceStock; overload;
function Name (value : string) : iFinanceStock; overload;
function Location ( value : string ) : iFinanceStock; overload;
function Points ( value : string ) : iFinanceStock; overload;
function Variation (value : string) : iFinanceStock; overload;
function &End : iFinanceStocks;
function SetJSON( value : TJSONPair) : iFinanceStock;
end;
implementation
uses
Injection;
{ TFinanceStock }
function TFinanceStock.Code: string;
begin
Result := FCode;
end;
function TFinanceStock.Code(value: string): iFinanceStock;
begin
Result := Self;
FCode := value;
end;
constructor TFinanceStock.Create(Parent: iFinanceStocks);
begin
TInjection.Weak(@FParent, Parent);
end;
destructor TFinanceStock.Destroy;
begin
inherited;
end;
function TFinanceStock.&End: iFinanceStocks;
begin
Result := FParent;
end;
function TFinanceStock.Location(value: string): iFinanceStock;
begin
Result := Self;
FLocation := value;
end;
function TFinanceStock.Location: string;
begin
Result := FLocation;
end;
function TFinanceStock.Name: string;
begin
Result := FName;
end;
function TFinanceStock.Name(value: string): iFinanceStock;
begin
Result := Self;
FName := value;
end;
function TFinanceStock.Points(value: string): iFinanceStock;
begin
Result := Self;
FPoints := value;
end;
function TFinanceStock.Points: string;
begin
Result := FPoints;
end;
function TFinanceStock.SetJSON(value: TJSONPair): iFinanceStock;
var
JSONStock : TJSONObject;
begin
Result := Self;
FCode := value.JsonString.Value;
JSONStock := value.JsonValue as TJSONObject;
JSONStock.tryGetValue<string>('name', FName);
JSONStock.tryGetValue<string>('location', FLocation);
JSONStock.tryGetValue<string>('points', FPoints);
JSONStock.tryGetValue<string>('variation', FVariation);
end;
function TFinanceStock.Variation(value: string): iFinanceStock;
begin
Result := Self;
FVariation := value;
end;
function TFinanceStock.Variation: string;
begin
Result := FVariation;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Attachment }
{ }
{ Copyright (c) 2001 Inprise Corporation }
{ }
{*******************************************************}
unit SOAPAttach;
interface
uses
SysUtils, Types, Classes, InvokeRegistry,
{XSBuiltIns,} HTTPApp, SOAPAttachIntf, WSDLIntf;
const
EOL = #13#10; { Linux vs. Windows is not relevant }
BlockReadSize = 10240; { Buffer side reading stream blocks }
type
TSOAPAttachmentData = class(TSOAPAttachment)
private
FID: string;
public
{ Id used to identify Attachment: Content-Id or Content-Location }
property ID: string read FID write FID;
procedure SetSourceStream(const Value: TStream; const Ownership: TStreamOwnership = soOwned); override;
{ allow Filename to be set without clearing out SourceStream }
procedure SetCacheFile(const Value: string);
end;
{ treats a TWebRequest as a TStream }
TWebRequestStream = class(TStream)
private
FWebRequest: TWebRequest;
FPosition: Int64;
FSize: Int64;
FContentSize: Integer;
FSavedChars: string;
FContentType: string;
FMaxLine: Integer;
public
constructor Create(ARequest: TWebRequest); reintroduce;
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function ReadLn: String;
function Seek(Offset: Longint; Origin: Word): Longint; overload; override;
function Write(const Buffer; Count: Longint): Longint; override;
property MaxLine: Integer read FMaxLine write FMaxLine;
end;
{ Utility functions }
function GetTempHandle(var ATempFileName: string): THandle;
function GetTempDir: string;
function GetMimeBoundaryFromType(const ContentType: string): string;
function GetBorlandMimeContentType: string;
function GetMimeAttachmentHandler(const ContentType: String): IMimeAttachmentHandler; overload;
function GetMimeAttachmentHandler(const BindingType: TWebServiceBindingType): IMimeAttachmentHandler; overload;
implementation
uses Math, SOAPConst, {$IFDEF LINUX}Libc{$ENDIF}{$IFDEF MSWINDOWS}Windows{$ENDIF};
{ Utility functions }
function GetTempDir: string;
begin;
{$IFDEF LINUX}
Result := GetEnv('TMPDIR');
if Result = '' then
Result := '/tmp/'
else if Result[Length(Result)] <> PathDelim then
Result := Result + PathDelim;
{$ENDIF}
{$IFDEF MSWINDOWS}
SetLength(Result, 255);
SetLength(Result, GetTempPath(255, (PChar(Result))));
{$ENDIF}
end;
function GetTempHandle(var ATempFileName: string): THandle;
{$IFDEF MSWINDOWS}
var
Index: Integer;
AFileName: string;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
Index := 0;
AFileName := ATempFileName + IntToStr(Index);
while FileExists(AFileName) do
begin
Inc(Index);
AFileName := ATempFileName + IntToStr(Index);
end;
ATempFileName := AFileName;
Result := FileCreate(AFileName);
{$ENDIF}
{$IFDEF LINUX}
UniqueString(ATempFileName);
Result := mkstemp(Pointer(ATempFileName));
{$ENDIF}
if Integer(Result) < 1 then
raise Exception.Create(STempFileAccessError);
end;
function GetBorlandMimeContentType: string;
begin
Result := Format(ContentHeaderMime, [SBorlandMimeBoundary]) +
Format(SStart, [SBorlandSoapStart]);
end;
function GetMimeBoundaryFromType(const ContentType: string): string;
begin
{ As per rfc2112 - http://www.faqs.org/rfcs/rfc2112.html -
we expect a content-type 'Multipart/Related' }
if Pos(SMultipartRelated, LowerCase(ContentType)) = 1 then { do not localize }
begin
Result := Copy(ContentType, Pos(SBoundary, ContentType) + Length(SBoundary), MaxInt);
if Pos(';', Result) > 1 then
Result := Copy(Result, 1, Pos(';', Result) -1);
end else
Result := '';
end;
{ TSOAPAttachmentData }
procedure TSOAPAttachmentData.SetSourceStream(const Value: TStream; const Ownership: TStreamOwnership = soOwned);
begin
InternalSetSourceStream(Value, Ownership);
end;
procedure TSOAPAttachmentData.SetCacheFile(const Value: string);
begin
SetSourceFile('');
InternalSetCacheFile(Value);
CacheFilePersist := True;
end;
{ TWebRequestStream }
constructor TWebRequestStream.Create(ARequest: TWebRequest);
begin
inherited Create;
FWebRequest := ARequest;
FSize := FWebRequest.ContentLength;
FPosition := 0;
FContentSize := Length(FWebRequest.Content);
FContentType := FWebRequest.ContentType;
FSavedChars := '';
FMaxLine := BlockReadSize;
end;
destructor TWebRequestStream.Destroy;
begin
inherited;
end;
{ assumes user knows headers are to follow, followed by blank line }
function TWebRequestStream.ReadLn: string;
var
ReadCount, CRPos: Integer;
SplitLF: string;
begin
SetLength(Result, MaxLine);
ReadCount := Read(Result[1], MaxLine);
SetLength(Result, ReadCount);
CrPos := Pos(EOL, Result);
if CrPos > 0 then
begin
Inc(CrPos);
FSavedChars := Copy(Result, CrPos + 1, Length(Result) - CrPos) + FSavedChars;
SetLength(Result, CrPos);
end else
begin
{ Check for split EOL }
if (Length(Result) > 0 ) and (Result[Length(Result)] = #13) then
begin
SetLength(SplitLF, 1);
Read(SplitLF[1], 1 );
if SplitLF[1] = #10 then
begin
{ cut off #13 from result }
SetLength(Result, MaxLine -1);
FSavedChars := FSavedChars + EOL;
end;
end;
end;
end;
function TWebRequestStream.Read(var Buffer; Count: Longint): Longint;
var
BytesToRead, BytesRead, SaveStart: LongInt;
P: PChar;
procedure LoadSavedChars(SaveStart: Integer);
var
Buffer : string;
begin
if FPosition < FContentSize then
begin
{ read first from FWebRequest.Content buffer }
BytesToRead := Min(Count, FContentSize - FPosition);
SetLength(Buffer, BytesToRead);
Move(FWebRequest.Content[FPosition + 1], Buffer[1], BytesToRead);
FSavedChars := FSavedChars + Buffer;
Inc(FPosition, BytesToRead);
Inc(SaveStart, BytesToRead);
end;
if SaveStart < Count then
begin
{ if still missing bytes then use TWebRequest.ReadClient }
while (SaveStart < Count) and (FPosition < FSize) do
begin
BytesToRead := Min(Count - SaveStart, FSize - FPosition);
SetLength(Buffer, BytesToRead);
BytesRead := FWebRequest.ReadClient(Buffer[1], BytesToRead);
if BytesRead < 1 then
break;
SetLength(Buffer, BytesRead);
FSavedChars := FSavedChars + Buffer;
Inc(FPosition, BytesRead);
Inc(SaveStart, BytesRead);
end;
end;
end;
begin
if Assigned(FWebRequest) then
begin
SaveStart := Length(FSavedChars);
if SaveStart < Count then
LoadSavedChars(SaveStart);
P := @Buffer;
Result := 0;
{ retrieve from Saved Buffer }
BytesToRead := Min(Count, Length(FSavedChars));
Move(FSavedChars[1], P[Result], BytesToRead);
Inc(Result, BytesToRead);
if BytesToRead >= Length(FSavedChars) then
FSavedChars := ''
else
FSavedChars := Copy(FSavedChars, BytesToRead + 1, MaxInt);
end else
Result := 0;
end;
function TWebRequestStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset + Length(FSavedChars);
soFromEnd: FPosition := FSize + Length(FSavedChars);
soFromCurrent: Inc(FPosition, Offset);
end;
Result := FPosition - Length(FSavedChars);
end;
function TWebRequestStream.Write(const Buffer; Count: Longint): Longint;
begin
raise Exception.Create(SMethodNotSupported);
end;
{ TAggregatedStream }
type
{ treats a collection of Streams as a single stream.
all streams in the FStreams TList are freed when object is destroyed! }
TAggregatedStream = class(TStream)
private
FCurrentStream: Integer;
FStreams: TList;
FOwners: array of TStreamOwnerShip;
FSize: Int64;
FPosition: Int64;
protected
procedure SetStreamToPosition;
public
{ from TAggregatedStream }
procedure AddStream(AStream: TStream; Ownership: TStreamOwnerShip); overload;
procedure AddStream(AValue: string); overload;
procedure ClearStream(FreeStreams: Boolean);
{ from TStream }
constructor Create;
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; overload; override;
function Write(const Buffer; Count: Longint): Longint; override;
property Position: Int64 read FPosition;
property Size: Int64 read FSize;
end;
constructor TAggregatedStream.Create;
begin
FStreams := TList.Create;
FCurrentStream := -1;
FSize := 0;
FPosition := 0;
end;
destructor TAggregatedStream.Destroy;
begin
ClearStream(True);
FreeAndNil(FStreams);
inherited;
end;
function TAggregatedStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset;
soFromCurrent: Inc(FPosition, Offset);
soFromEnd: FPosition := FSize + Offset;
end;
Result := FPosition;
end;
procedure TAggregatedStream.SetStreamToPosition;
var
FPos, FPositionInStream: LongInt;
begin
if FPosition = FSize then
begin
FCurrentStream := FStreams.Count -1;
FPositionInStream := TStream(FStreams[FCurrentStream]).Size;
FPos := FPosition;
end else
begin
FPos := 0;
FPositionInStream := 0;
FCurrentStream := 0;
end;
while FPos < FPosition do
begin
if (FPosition - FPos) > TStream(FStreams[FCurrentStream]).Size then
begin
Inc(FPos, TStream(FStreams[FCurrentStream]).Size);
if FCurrentStream < FStreams.Count -1 then
Inc(FCurrentStream)
else
break;
end else
begin
FPositionInStream := FPosition - FPos;
FPos := FPosition;
end;
end;
TStream(FStreams[FCurrentStream]).Seek(FPositionInStream, 0);
end;
function TAggregatedStream.Read(var Buffer; Count: Longint): Longint;
var
P: PChar;
BytesRead, ToRead: LongInt;
begin
Result := 0;
if FStreams.Count = 0 then
raise Exception.Create(SEmptyStream);
SetStreamToPosition;
if FPosition = FSize then exit;
P := @Buffer;
Result := 0;
while (Result < Count) and (FCurrentStream < FStreams.Count) do
begin
ToRead := Min(TStream(FStreams[FCurrentStream]).Size -
TStream(FStreams[FCurrentStream]).Position, Count - Result);
BytesRead := TStream(FStreams[FCurrentStream]).Read(P[Result], ToRead);
Inc(FPosition, BytesRead);
Inc(Result, BytesRead);
if Result < Count then
begin
if TStream(FStreams[FCurrentStream]).Position < TStream(FStreams[FCurrentStream]).Size then
continue;
if FCurrentStream < FStreams.Count -1 then
begin
Inc(FCurrentStream);
TStream(FStreams[FCurrentStream]).Seek(0, 0);
end else
begin
FPosition := FSize;
break;
end;
end;
end;
end;
function TAggregatedStream.Write(const Buffer; Count: Longint): Longint;
begin
raise Exception.Create(SMethodNotSupported);
end;
procedure TAggregatedStream.AddStream(AStream: TStream; OwnerShip: TStreamOwnership);
begin
AStream.Seek(0, 0);
FStreams.Add(AStream);
SetLength(FOwners, FStreams.Count);
FOwners[FStreams.Count - 1] := Ownership;
Inc(FSize, AStream.Size);
FPosition := 0;
FCurrentStream := 0;
end;
procedure TAggregatedStream.AddStream(AValue: string);
var
AStream: TMemoryStream;
begin
AStream := TMemoryStream.Create;
AStream.Write(AValue[1], Length(AValue));
AddStream(AStream, soOwned);
end;
procedure TAggregatedStream.ClearStream(FreeStreams: Boolean);
var
I: Integer;
begin
if FreeStreams then
for I := 0 to FStreams.Count -1 do
begin
if FOwners[I] = soOwned then
TStream(FStreams[I]).Free;
end;
SetLength(FOwners, 0);
FStreams.Clear;
FSize := 0;
FPosition := 0;
end;
type
{ TMimeStream }
TMimeAttachmentHandler = class(TAggregatedStream)
private
FAttachmentsStream: TAggregatedStream;
FLastMimeBoundary: string;
FMimeBoundary: string;
FSoapEnvelope: TStream;
FSoapHeaders: TStrings;
FOnSendAttachment: TOnSendAttachmentEvent;
FOnGetAttachment: TOnGetAttachmentEvent;
FContentType: string;
protected
{ create Attachments portion of Stream }
procedure CreateAttachmentStream(Attachments: TSoapDataList);
procedure DoOnSendAttachment(AttachmentStream: TStream; Attachment: TSOAPAttachment); virtual;
procedure DoOnGetAttachment(AttachmentStream: TStream; Attachment: TSOAPAttachment); virtual;
public
constructor Create;
destructor Destroy; override;
{ break up MultiPart form (as stream) into Soap Envelope
and Attachments }
procedure ProcessMultiPartForm(
const ASourceStream, ADestStream: TStream;
AMimeBoundary: string; SoapHeaders: TStrings;
Attachments: TSoapDataList; TempDir: string);
{ Add a new Soap Header }
procedure AddSoapHeader(Value: string);
procedure CreateMimeStream(Envelope: TStream; Attachments: TSoapDataList);
{ combine MimeBoundary, Soap Headers and Envelope, and Attachments into single Stream }
procedure FinalizeStream;
{ access Soap Envelope portion of stream }
property SoapEnvelope: TStream read FSoapEnvelope;
property ContentType: string read FContentType write FContentType;
property MimeBoundary: string read FMimeBoundary write FMimeBoundary;
{ access SOAP Headers portion of stream }
property SoapHeaders: TStrings read FSoapHeaders;
property OnSendAttachment: TOnSendAttachmentEvent read FOnSendAttachment write FOnSendAttachment;
property OnGetAttachment: TOnGetAttachmentEvent read FOnGetAttachment write FOnGetAttachment;
end;
constructor TMimeAttachmentHandler.Create;
begin
inherited;
FSOAPHeaders := TStringList.Create;
FAttachmentsStream := TAggregatedStream.Create;
end;
destructor TMimeAttachmentHandler.Destroy;
begin
FSOAPHeaders.Free;
FSoapEnvelope.Free;
FAttachmentsStream.Free;
inherited;
end;
procedure TMimeAttachmentHandler.FinalizeStream;
const
MimeStart = '--'; { do not localize }
var
Boundary : string;
I: Integer;
begin
if FAttachmentsStream.Size = 0 then
begin
AddStream(FSoapEnvelope, soReference);
FSoapHeaders.Clear;
end else
begin
Boundary := MimeStart + FMimeBoundary;
{ add starting MimeBoundary }
AddStream(EOL + Boundary + EOL);
{ add Soap Headers }
AddSoapHeader(Format(SContentId + ': <%s>', [SBorlandSoapStart])); { do not localize }
AddSoapHeader(Format(SContentLocation + ': %s', [SBorlandSoapStart])); { do not localize }
AddSoapHeader(Format(SContentLength + ': %d', [FSoapEnvelope.Size])); { do not localize }
// AddSoapHeader('Content-Transfer-Encoding: 8bit');
for I := 0 to FSoapHeaders.Count -1 do
AddStream(FSoapHeaders[I] + EOL);
{ add Soap Envelope with Mime boundary }
AddStream(EOL);
AddStream(FSoapEnvelope, soReference);
AddStream(EOL);
AddStream(FAttachmentsStream, soReference);
end;
end;
type
TMimeStreamHolder = class(TObject)
private
FSourceStream: TStream;
FHeaders: TStrings;
public
constructor Create;
destructor Destroy; override;
property Headers: TStrings read FHeaders;
property SourceStream: TStream read FSourceStream write FSourceStream;
end;
constructor TMimeStreamHolder.Create;
begin
inherited;
FHeaders := TStringList.Create;
end;
destructor TMimeStreamHolder.Destroy;
begin
FHeaders.Free;
inherited;
end;
procedure TMimeAttachmentHandler.ProcessMultiPartForm(
const ASourceStream, ADestStream: TStream;
AMimeBoundary: string; SoapHeaders: TStrings;
Attachments: TSoapDataList;
TempDir: string);
const
{$IFDEF MSWINDOWS}
BorlandTempFile = 'BorlandSoapAttachment';
{$ENDIF}
{$IFDEF LINUX}
BorlandTempFile = 'BorlandSoapAttachmentXXXXXX';
{$ENDIF}
var
Target: THandleStream;
HaveEnvelope, Done: Boolean;
Attachment: TSOAPAttachmentData;
MimeStream: TMimeStreamHolder;
AttachFileName, TempFileName: string;
TargetHandle: Integer;
function ReadLine(const SourceStream: TStream; BlockSize: Integer = 10240): String;
var
StreamPos, Size: Integer;
begin
if SourceStream is TWebRequestStream then
begin
Result := (MimeStream.SourceStream as TWebRequestStream).readln;
end else
begin
SetLength(Result, BlockSize);
StreamPos := SourceStream.Position;
SourceStream.Read(Result[1], BlockSize);
Size := Pos(EOL, Result);
if Size > 0 then
begin
Inc(Size);
SetLength(Result, Size);
SourceStream.Position := StreamPos + Size;
end;
end;
end;
function SameMimeBoundary(SFound, SMime: string): Boolean;
begin
Result := SameText(SFound, SMime) or
SameText(SFound, '--' + SMime + EOL) or
SameText(SFound, '--' + SMime + '--') or
SameText(SFound, '--' + SMime + '--' + EOL) or
SameText(SFound, SMime + EOL);
end;
procedure ReadContent(ADestStream: TStream);
var
SLine: string;
begin
SLine := ReadLine(MimeStream.SourceStream);
while (MimeStream.SourceStream.Position <= MimeStream.SourceStream.Size) and
(not SameMimeBoundary(SLine, MimeBoundary)) do
begin
ADestStream.Write(SLine[1], Length(SLine));
SLine := ReadLine(MimeStream.SourceStream);
if Length(SLine) = 0 then
Raise Exception.Create(SMimeReadError);
end;
FLastMimeBoundary := sLine;
end;
procedure ReadBody(ADestStream: TStream; var AMsgEnd: Boolean);
var
Size: Integer;
begin
if MimeStream.SourceStream.Position < MimeStream.SourceStream.Size then
begin
if MimeStream.Headers.Count = 0 then
exit;
if MimeStream.Headers.Values[SContentLength] = '' then
begin
ReadContent(ADestStream);
end else
begin
Size := StrToInt(MimeStream.Headers.Values[SContentLength]);
if (MimeStream.SourceStream.Size - MimeStream.SourceStream.Position) < Size then
raise Exception.Create(SInvalidContentLength);
if Size > 0 then
ADestStream.CopyFrom(MimeStream.SourceStream, Size);
end;
end;
if MimeStream.SourceStream.Position >= MimeStream.SourceStream.Size then
AMsgEnd := True;
end;
procedure GetHeaders;
var
AHeaders: TStringList;
Line: string;
begin
AHeaders := TStringList.Create;
try
Line := 'l';
while (Line <> '') and (Line <> EOL) do
begin
Line := ReadLine(MimeStream.SourceStream, 1024);
if (Line = '') or (Line = EOL) then
begin
MimeStream.Headers.Clear;
MimeStream.Headers.AddStrings(AHeaders);
break;
end else
begin
Line := StringReplace(Line, EOL, '', []);
AHeaders.Add(StringReplace(Line, ': ', '=', []));
end;
end;
finally
AHeaders.Free;
end;
end;
procedure SkipMimeBoundary;
var
MimeStr: string;
begin
if (FLastMimeBoundary = '') or (not SameMimeBoundary(FLastMimeBoundary, MimeBoundary)) then
begin
while ((MimeStr = '') or (MimeStr = eol)) and (MimeStream.SourceStream.Position < MimeStream.SourceStream.Size) do
begin
MimeStr := ReadLine(MimeStream.SourceStream);
end;
end;
Done := MimeStream.SourceStream.Position >= MimeStream.SourceStream.Size;
end;
begin
if TempDir = '' then
TempDir := GetTempDir;
TempFileName := TempDir + BorlandTempFile;
{ The MimeBoundary may come from a parameter }
if Pos('multipart/related', LowerCase(AMimeBoundary)) = 1 then { do not localize }
{ received ContentType, not MimeBoundary }
FMimeBoundary := GetMimeBoundaryFromType(AMimeBoundary)
else
FMimeBoundary := AMimeBoundary;
if FMimeBoundary = '' then
exit;
ASourceStream.Seek(0, 0);
MimeStream := TMimeStreamHolder.Create;
try
MimeStream.SourceStream := ASourceStream;
SkipMimeBoundary;
Done := False;
HaveEnvelope := False;
while not Done do
begin
GetHeaders;
if MimeStream.Headers.Count = 0 then
break;
if not HaveEnvelope then
begin
HaveEnvelope := True;
if MimeStream.Headers.Count > 0 then
begin
if Assigned(SoapHeaders) then
SoapHeaders.AddStrings(MimeStream.Headers);
end;
ADestStream.Position := 0;
ReadBody(ADestStream, Done);
SkipMimeBoundary;
end else
begin
Attachment := TSOAPAttachmentData.Create;
AttachFileName := TempFileName;
TargetHandle := GetTempHandle(AttachFileName);
if TargetHandle = -1 then
RaiseLastOSError;
try
Target := THandleStream.Create(TargetHandle);
try
Attachment.ID := MimeStream.Headers.Values[SContentID];
if Attachment.ID = '' then { if not ContentID, ID is location }
Attachment.ID := MimeStream.Headers.Values[SContentLocation];
Attachment.Headers.AddStrings(MimeStream.Headers);
ReadBody(Target, Done);
Attachment.SetCacheFile(AttachFileName);
DoOnGetAttachment(Target, Attachment);
FreeAndNil(Target);
Attachment.DataContext := Nil;
Attachment.ContentType := MimeStream.Headers.Values[SContentType];
Attachment.Encoding := MimeStream.Headers.Values[SCharacterEncoding];
Attachments.Add(Attachment);
SkipMimeBoundary;
finally
if Assigned(Target) then
FreeAndNil(Target);
end;
finally
FileClose(TargetHandle);
end;
end;
end;
finally
MimeStream.SourceStream := Nil;
MimeStream.Free;
end;
end;
procedure TMimeAttachmentHandler.DoOnSendAttachment(AttachmentStream: TStream;
Attachment: TSOAPAttachment);
begin
if Assigned(FOnSendAttachment) then
FOnSendAttachment(AttachmentStream, Attachment);
end;
procedure TMimeAttachmentHandler.DoOnGetAttachment(AttachmentStream: TStream;
Attachment: TSOAPAttachment);
begin
if Assigned(FOnGetAttachment) then
FOnGetAttachment(AttachmentStream, Attachment);
end;
procedure TMimeAttachmentHandler.AddSoapHeader(Value: string);
begin
FSoapHeaders.Add(Value);
end;
procedure TMimeAttachmentHandler.CreateMimeStream(Envelope: TStream; Attachments: TSoapDataList);
begin
{ Free any current Envelope stream }
{ And copy one passed in }
FSoapEnvelope.Free;
FSoapEnvelope := TMemoryStream.Create;
FSoapEnvelope.CopyFrom(Envelope, 0);
CreateAttachmentStream(Attachments);
FMimeBoundary := SBorlandMimeBoundary;
end;
{ store Attachments as AggregatedStream member FAttachmentsStream }
procedure TMimeAttachmentHandler.CreateAttachmentStream(Attachments: TSoapDataList);
const
MimeStart = '--';
var
Header: string;
I, J: Integer;
Stream: TStream;
Boundary : string;
Attachment: TSOAPAttachmentData;
Owner: TStreamOwnership;
begin
FMimeBoundary := SBorlandMimeBoundary;
Boundary := MimeStart + FMimeBoundary;
if FAttachmentsStream.Size > 0 then
FAttachmentsStream.ClearStream(True);
if Attachments.Count = 0 then
begin
FAttachmentsStream.AddStream(EOL + Boundary + '--'); { do not localize }
exit;
end;
for I := 0 to Attachments.Count -1 do
begin
Attachment := TSOAPAttachmentData(Attachments[I]);
Header := EOL + Boundary + EOL;
Owner := soOwned;
if Attachment.CacheFile <> '' then
Stream := TFileStream.Create(Attachment.CacheFile, fmOpenRead)
else if Assigned(Attachment.SourceStream) then
begin
Stream := Attachment.SourceStream;
Owner := Attachment.Ownership;
end else
begin
Stream := TMemoryStream.Create;
Stream.Write(Attachment.SourceString[1], Length(Attachment.SourceString));
end;
DoOnSendAttachment(Stream, Attachment);
for J := 0 to Attachment.Headers.Count -1 do
Header := Header + Attachment.Headers.Strings[J]+ EOL;
Header := Header + Format('Content-Length: %d' + EOL, [Stream.Size]); { do not localize }
if Attachment.ContentType <> '' then
Header := Header + Format(ContentTypeTemplate, [Attachment.ContentType]) + EOL { do not localize }
else
Header := Header + Format(ContentTypeTemplate, [ContentTypeApplicationBinary]) + EOL; { do not localize }
if Attachment.Encoding <> '' then
Header := Header + Format(SCharacterEncodingFormat, [Attachment.Encoding]) + EOL;
FAttachmentsStream.AddStream(Header + EOL);
FAttachmentsStream.AddStream(Stream, Owner); // TAggregateStreams takes care of freeing
{ if ownership is soOwned, Stream will be freed by TAggregatedStream }
Attachment.Ownership := soReference;
if I = Attachments.Count -1 then // unless Owner is soReference
FAttachmentsStream.AddStream(EOL + Boundary + '--') { do not localize }
else
FAttachmentsStream.AddStream(EOL);
end;
end;
type
TMimeAttachHandlerImpl = class(TInterfacedObject, IMimeAttachmentHandler)
private
FMimeAttachmentHandler: TMimeAttachmentHandler;
public
constructor Create;
destructor Destroy; override;
{ IMimeAttachmentHandler }
procedure ProcessMultiPartForm(
const ASourceStream, ADestStream: TStream;
AMimeBoundary: string; SoapHeaders: TStrings;
Attachments: TSoapDataList; TempDir: string);
{ Add a new Soap Header }
procedure AddSoapHeader(Value: string);
procedure CreateMimeStream(Envelope: TStream; Attachments: TSoapDataList(*; WebNode: IWebNode*));
{ combine MimeBoundary, Soap Headers and Envelope, and Attachments into single Stream }
procedure FinalizeStream;
function GetMIMEStream(Release: Boolean = False): TStream;
function GetMIMEBoundary: string;
procedure SetMIMEBoundary(const MimeBndry: string);
function GetOnSendAttachmentEvent: TOnSendAttachmentEvent;
procedure SetOnSendAttachmentEvent(OnSendAttachment: TOnSendAttachmentEvent);
function GetOnGetAttachmentEvent: TOnGetAttachmentEvent;
procedure SetOnGetAttachmentEvent(OnGetAttachment: TOnGetAttachmentEvent);
end;
function GetMimeAttachmentHandler(const ContentType: String): IMimeAttachmentHandler;
begin
Result := TMimeAttachHandlerImpl.Create;
end;
function GetMimeAttachmentHandler(const BindingType: TWebServiceBindingType): IMimeAttachmentHandler;
begin
Result := TMimeAttachHandlerImpl.Create;
end;
{ TMimeAttachHandlerImpl }
constructor TMimeAttachHandlerImpl.Create;
begin
FMimeAttachmentHandler := TMimeAttachmentHandler.Create;
inherited;
end;
destructor TMimeAttachHandlerImpl.Destroy;
begin
inherited;
FMimeAttachmentHandler.Free;
end;
procedure TMimeAttachHandlerImpl.AddSoapHeader(Value: string);
begin
FMimeAttachmentHandler.AddSoapHeader(Value);
end;
procedure TMimeAttachHandlerImpl.CreateMimeStream(Envelope: TStream;
Attachments: TSoapDataList);
begin
FMimeAttachmentHandler.CreateMimeStream(Envelope, Attachments);
end;
procedure TMimeAttachHandlerImpl.FinalizeStream;
begin
FMimeAttachmentHandler.FinalizeStream;
end;
function TMimeAttachHandlerImpl.GetMIMEStream(Release: Boolean): TStream;
begin
Result := FMimeAttachmentHandler;
if Release then
FMimeAttachmentHandler := Nil;
end;
procedure TMimeAttachHandlerImpl.ProcessMultiPartForm(const ASourceStream,
ADestStream: TStream; AMimeBoundary: string; SoapHeaders: TStrings;
Attachments: TSoapDataList; TempDir: string);
begin
FMimeAttachmentHandler.ProcessMultiPartForm(ASourceStream, ADestStream, AMimeBoundary,
SoapHeaders, Attachments, TempDir);
end;
function TMimeAttachHandlerImpl.GetOnGetAttachmentEvent: TOnGetAttachmentEvent;
begin
Result := FMimeAttachmentHandler.OnGetAttachment;
end;
function TMimeAttachHandlerImpl.GetOnSendAttachmentEvent: TOnSendAttachmentEvent;
begin
Result := FMimeAttachmentHandler.OnSendAttachment;
end;
procedure TMimeAttachHandlerImpl.SetOnGetAttachmentEvent(
OnGetAttachment: TOnGetAttachmentEvent);
begin
FMimeAttachmentHandler.OnGetAttachment := OnGetAttachment;
end;
procedure TMimeAttachHandlerImpl.SetOnSendAttachmentEvent(
OnSendAttachment: TOnSendAttachmentEvent);
begin
FMimeAttachmentHandler.OnSendAttachment := OnSendAttachment;
end;
function TMimeAttachHandlerImpl.GetMIMEBoundary: String;
begin
Result := FMimeAttachmentHandler.FMimeBoundary;
end;
procedure TMimeAttachHandlerImpl.SetMIMEBoundary(const MimeBndry: String);
begin
FMimeAttachmentHandler.FMimeBoundary := MimeBndry;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit mxpbar;
{ the progress dialog with a cancel button }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls;
type
EUserCanceled = class(Exception);
TProgressDialog = class(TForm)
ProgressBar: TProgressBar;
CancelButton: TButton;
StatusText: TStaticText;
procedure CancelButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FCanceled: Boolean;
FInterval: Integer;
FCount: Integer;
FRealMax: Integer;
FBuilding: Boolean;
BuildDone: Boolean;
FExceptMessage: string;
FOnPerformBuild: TNotifyEvent;
function GetMax: Integer;
procedure SetMax(Value: Integer);
procedure SetInterval(Value: Integer);
procedure StartBuild(var Message); message WM_USER;
public
function StepProgress: Boolean;
procedure ShowStatus(Msg: string);
function UpdateProgress: Integer;
procedure Reset;
property Max: Integer read GetMax write SetMax;
property Canceled: Boolean read FCanceled write FCanceled;
property Interval: Integer read FInterval write SetInterval;
property OnPerformBuild: TNotifyEvent read FOnPerformBuild write FOnPerformBuild;
property ExceptMessage: string read FExceptMessage write FExceptMessage;
end;
var
ProgressDlg: TProgressDialog = nil;
implementation
{$R *.DFM}
procedure TProgressDialog.StartBuild(var Message);
begin
try
FBuilding := True;
if Assigned(FOnPerformBuild) then
begin
try
FOnPerformBuild(Self);
except
FExceptMessage := Exception(ExceptObject).Message;
ModalResult := mrAbort;
end;
ModalResult := mrCancel;
end;
finally
Self.Visible := False;
BuildDone := True;
FBuilding := False;
Canceled := True;
end;
end;
function TProgressDialog.UpdateProgress: Integer;
begin
StepProgress;
Application.ProcessMessages;
if Canceled then
Result := -1
else
Result := 0;
end;
function TProgressDialog.GetMax: Integer;
begin
Result := FRealMax;
end;
procedure TProgressDialog.SetMax(Value: Integer);
begin
if (Value <> FRealMax) then
begin
FRealMax := Value;
ProgressBar.Max := Value;
ProgressBar.Position := 1;
if (Value > 10000) then
Interval := Integer(Trunc(Value * 0.05))
else if (Value > 100) then
Interval := Integer(Trunc(Value * 0.10))
else
Interval := 1;
end;
end;
function TProgressDialog.StepProgress: Boolean;
begin
Result := False;
if (FCount = FInterval) and (ProgressBar.Max > 0) then
begin
if not Visible then Visible := True;
ProgressBar.StepIt;
FCount := 0;
Result := True;
end;
Inc(FCount);
end;
procedure TProgressDialog.ShowStatus(Msg: string);
begin
if (StatusText.Visible = False) then
StatusText.Visible := True;
StatusText.Caption := msg;
end;
procedure TProgressDialog.CancelButtonClick(Sender: TObject);
begin
Canceled := True;
if BuildDone and (CancelButton.ModalResult <> mrOK) then
ModalResult := mrCancel;
end;
procedure TProgressDialog.SetInterval(Value: Integer);
begin
if (Value <> FInterval) then
begin
{ set the new max based on the interval }
FInterval := Value;
FCount := 1;
ProgressBar.Step := Value;
end;
end;
procedure TProgressDialog.Reset;
begin
ProgressBar.Position := 1;
end;
procedure TProgressDialog.FormActivate(Sender: TObject);
begin
if not FBuilding then
PostMessage(Handle, WM_USER, 0, 0);
end;
procedure TProgressDialog.FormCreate(Sender: TObject);
begin
SetBounds((Screen.Width - Width) div 2,
(GetSystemMetrics(SM_CYSCREEN) - Height) div 3,
Width, Height);
end;
end.
|
unit GrievanceComplaintSubreasonDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, Wwkeycb, Grids, Wwdbigrd,
Wwdbgrid, ComCtrls, wwriched, wwrichedspell;
type
TGrievanceComplaintSubreasonDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
Label1: TLabel;
Label2: TLabel;
GrievanceComplaintSubReasonCodeTable: TTable;
GrievanceComplaintSubreasonDataSource: TDataSource;
GrievanceDenialReasonGrid: TwwDBGrid;
GrievanceCodeIncrementalSearch: TwwIncrementalSearch;
Label3: TLabel;
ReasonRichEdit: TwwDBRichEditMSWord;
procedure OKButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Category,
GrievanceComplaintSubreasonCode : String;
end;
var
GrievanceComplaintSubreasonDialog: TGrievanceComplaintSubreasonDialog;
implementation
{$R *.DFM}
uses WinUtils, Utilitys;
{===============================================================}
Procedure TGrievanceComplaintSubreasonDialog.FormShow(Sender: TObject);
begin
try
GrievanceComplaintSubReasonCodeTable.Open;
except
MessageDlg('Error opening grievance complaint subreason reason code table.',
mtError, [mbOK], 0);
end;
SetRangeOld(GrievanceComplaintSubreasonCodeTable, ['Category', 'Code'],
[Category, ConstStr(' ', 10)],
[Category, ConstStr('Z', 10)]);
end; {FormShow}
{===============================================================}
Procedure TGrievanceComplaintSubreasonDialog.OKButtonClick(Sender: TObject);
begin
GrievanceComplaintSubreasonCode := GrievanceComplaintSubReasonCodeTable.FieldByName('Code').Text;
ModalResult := mrOK;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 43 O(FE) Ford-Folkerson Algorithm
}
program
MaximumFlow;
const
MaxN = 100;
MaxE = 10000;
var
N, M, S, T : Integer;
G, H : array [1 .. MaxN, 1 .. MaxN] of Integer;
E : array [1 .. MaxE, 1 .. 2] of Byte;
Mark : array [1 .. MaxN] of Boolean;
I, J, K, L : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N, M, S, T);
for I := 1 to M do
begin
Readln(F, J, K, L);
G[J, K] := L; E[I, 1] := J; E[I, 2] := K;
end;
end;
function ADfs (V : Integer; var MinDelta : Integer) : Boolean;
var
I : Integer;
MinDelta2 : Integer;
begin
Mark[V] := True;
for I := 1 to N do
begin
MinDelta2 := MinDelta;
if G[V, I] - H[V, I] < MinDelta2 then
MinDelta2 := G[V, I] - H[V, I];
if (H[V, I] < G[V, I]) and ((I = T) or (not Mark[I] and ADfs(I, MinDelta2))) then
begin
Inc(H[V, I], MinDelta2);
Dec(H[I, V], MinDelta2);
ADfs := True;
MinDelta := MinDelta2;
Exit;
end;
end;
ADfs := False;
end;
procedure MaxFlow;
var
MD : Integer;
begin
repeat
FillChar(Mark, SizeOf(Mark), 0);
until not ADfs(S, MD);
end;
procedure WriteOutput;
var
W : Longint;
begin
Assign(F, 'output.txt');
ReWrite(F);
W := 0;
for I := 1 to N do
Inc(W, H[S, I]);
Writeln(F, W);
for I := 1 to M do
Writeln(F, H[E[I, 1], E[I, 2]]);
Close(F);
end;
begin
ReadInput;
MaxFlow;
WriteOutput;
end.
|
PROGRAM SumOfDigits(INPUT, OUTPUT);
VAR
Digit, Sum: INTEGER;
PROCEDURE ReadDigit(VAR FromFile: TEXT; VAR Digit: INTEGER);
{Считывает текущий символ из файла, если он - цифра, возвращает его
преобразуя в значение типа INTEGER. Если считанный символ не цифра
возвращает -1}
VAR
Ch: CHAR;
BEGIN
Digit := -1;
IF NOT EOLN(FromFile)
THEN
BEGIN
READ(FromFile, Ch);
IF Ch = '0' THEN Digit := 0 ELSE
IF Ch = '1' THEN Digit := 1 ELSE
IF Ch = '2' THEN Digit := 2 ELSE
IF Ch = '3' THEN Digit := 3 ELSE
IF Ch = '4' THEN Digit := 4 ELSE
IF Ch = '5' THEN Digit := 5 ELSE
IF Ch = '6' THEN Digit := 6 ELSE
IF Ch = '7' THEN Digit := 7 ELSE
IF Ch = '8' THEN Digit := 8 ELSE
IF Ch = '9' THEN Digit := 9
END
END;
BEGIN
Sum := 0;
Digit := 0;
ReadDigit(INPUT, Digit);
WHILE (Digit <> -1)
DO
BEGIN
Sum := Sum + Digit;
ReadDigit(INPUT, Digit)
END;
WRITELN('Сумма цифр текста до первого нецифрового символа: ', Sum)
END.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXCDSReaders;
interface
uses
System.Classes, System.SysUtils, Datasnap.DBClient, Data.DB,
Data.DBXCommon, Data.DBXPlatform, Data.DBXCommonTable, Data.DBXDBReaders;
type
TDBXClientDataSetTable = class;
/// <summary>This class is not used directly by applications.</summary>
TDBXCDSOriginalRow = class(TDBXDBTable)
private
FAtEnd: Boolean;
FClonedTable: TDBXClientDataSetTable;
[Weak]FClientTable: TDBXClientDataSetTable;
protected
function GetWritableValue(const Ordinal: TInt32): TDBXWritableValue; override;
public
constructor Create(ClientTable: TDBXClientDataSetTable);
function GetOrdinal(const ColumnName: string): Integer; override;
function First: Boolean; override;
function Next: Boolean; override;
function InBounds: Boolean; override;
function GetColumns: TDBXValueTypeArray; override;
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXClientDataSetTable = class(TDBXDataSetTable)
private
FOriginal: TDBXCDSOriginalRow;
[Weak]FClientDataset: TClientDataSet;
protected
constructor Create(const CollectionName: string;
TableColumns: TDBXValueTypeArray; Table: TClientDataSet;
OwnsTable: Boolean = true); overload;
procedure SkipOriginalRow; override;
function GetDeletedRows: TDBXTable; override;
function GetInsertedRows: TDBXTable; override;
function GetUpdatedRows: TDBXTable; override;
function GetOriginalRow: TDBXTableRow; override;
public
constructor Create; overload;
constructor Create(ClientDataSet: TClientDataSet; OwnsTable: Boolean); overload;
destructor Destroy; override;
procedure AcceptChanges; override;
procedure Clear; override;
function CreateTableView(const OrderByColumnName: string): TDBXTable; override;
function FindStringKey(const Ordinal: Integer; const Value: string): Boolean; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
end;
/// <summary>TDBXReader implementation for the TClientDataSet
/// object.</summary>
TDBXClientDataSetReader = class(TDBXDataSetReader)
public
/// <summary>
/// Creates a <c>TDBXReader</c> for a <c>TDataSet</c> instance. If
/// <c>InstanceOwner</c> is true, the <c>TDataSet</c> instance will be
/// freed when this <c>TDBXDataSetReader</c> instance is freed.
/// </summary>
constructor Create(Params: TDataset; InstanceOwner: Boolean = true); override;
/// <summary>
/// Copies the contents of <c>Reader</c> into the <c>TDataSet</c>
/// instance.
/// </summary>
/// <returns>
/// The same <c>DataSet</c> instance that was passed into this method.
/// </returns>
class procedure CopyReaderToClientDataSet(Reader: TDBXReader;
Dataset: TClientDataSet); static;
class function ToClientDataSet(AOwner: TComponent; Reader: TDBXReader;
AOwnsInstance: Boolean): TClientDataSet; static;
end;
implementation
uses
Data.DBXCommonResStrs;
{ TDBXClientDataSetReader }
constructor TDBXClientDataSetReader.Create(Params: TDataset;
InstanceOwner: Boolean);
begin
if Params is TClientDataSet then
inherited Create(TDBXClientDataSetTable.Create(
Params.Name, nil, TClientDataSet(Params), InstanceOwner))
else
inherited Create(Params, InstanceOwner);
end;
class function TDBXClientDataSetReader.ToClientDataSet(AOwner: TComponent; Reader: TDBXReader; AOwnsInstance: Boolean): TClientDataSet;
begin
Result := TClientDataSet.Create(AOwner);
CopyReaderToClientDataSet(Reader, Result);
if AOwnsInstance then
Reader.Free;
end;
class procedure TDBXClientDataSetReader.CopyReaderToClientDataSet(
Reader: TDBXReader; DataSet: TClientDataSet);
var
Ordinal: Integer;
Table: TDBXTable;
ValueTypes: TDBXValueTypeArray;
ColumnCount: Integer;
begin
ColumnCount := Reader.ColumnCount;
SetLength(ValueTypes, Reader.ColumnCount);
for Ordinal := 0 to ColumnCount - 1 do
begin
ValueTypes[Ordinal] := Reader.ValueType[Ordinal].WritableClone;
end;
Table := TDBXClientDataSetTable.Create('', nil, DataSet, False);
Table.Columns := ValueTypes;
try
while Reader.Next do
begin
Table.Insert;
for Ordinal := 0 to ColumnCount - 1 do
Table.Value[Ordinal].SetValue(Reader.Value[Ordinal]);
Table.Post;
end;
finally
Table.Free;
end;
end;
{ TDBXCDSOriginalRow }
constructor TDBXCDSOriginalRow.Create(ClientTable: TDBXClientDataSetTable);
var
ClientDataSet: TClientDataSet;
begin
ClientDataSet := TClientDataSet.Create(nil);
ClientDataSet.CloneCursor(ClientTable.FClientDataSet, True);
ClientDataSet.StatusFilter := [usModified];
FClonedTable := TDBXClientDataSetTable.Create(ClientTable.CollectionName, ClientTable.CopyColumns, ClientDataSet);
FClientTable := ClientTable;
inherited Create(nil, TDBXDataSetRow.Create(ClientDataSet));
end;
function TDBXCDSOriginalRow.First: Boolean;
begin
FAtEnd := false;
Result := true;
end;
function TDBXCDSOriginalRow.GetColumns: TDBXValueTypeArray;
begin
Result := FClientTable.GetColumns;
end;
function TDBXCDSOriginalRow.GetOrdinal(const ColumnName: string): Integer;
begin
Result := FClientTable.GetOrdinal(ColumnName);
end;
function TDBXCDSOriginalRow.GetWritableValue(
const Ordinal: TInt32): TDBXWritableValue;
var
TargetRecNo: Integer;
begin
if FClientTable.Table.UpdateStatus in [usDeleted, usUnmodified] then
Result := FClientTable.GetWritableValue(Ordinal)
else if FClientTable.Table.UpdateStatus = usModified then
begin
if usModified in FClientTable.FClientDataset.StatusFilter then
TargetRecNo := FClientTable.Table.RecNo - 1
else
TargetRecNo := (FClientTable.Table.RecNo * 2) - 1;
if FClonedTable.Table.RecNo <> TargetRecNo then
begin
FClonedTable.Table.MoveBy(TargetRecNo - FClonedTable.Table.RecNo);
FClonedTable.RowNavigated;
end;
Result := FClonedTable.GetWritableValue(Ordinal);
end
else
Result := nil;
end;
function TDBXCDSOriginalRow.InBounds: Boolean;
begin
Result := not FAtEnd;
end;
function TDBXCDSOriginalRow.Next: Boolean;
begin
if FAtEnd then
Result := false
else
begin
FAtEnd := true;
Result := true;
end;
end;
{ TDBXClientDataSetTable }
constructor TDBXClientDataSetTable.Create;
begin
Create('', nil, TClientDataSet.Create(nil), true);
end;
constructor TDBXClientDataSetTable.Create(ClientDataSet: TClientDataSet;
OwnsTable: Boolean);
begin
Create('', nil, ClientDataSet, OwnsTable);
end;
procedure TDBXClientDataSetTable.AcceptChanges;
begin
FailIfRowIsNew();
FClientDataSet.MergeChangeLog;
end;
procedure TDBXClientDataSetTable.Clear;
begin
if (FClientDataSet.State in dsEditModes) then
FClientDataSet.Post;
if not (usModified in FClientDataSet.StatusFilter)
and not (usDeleted in FClientDataSet.StatusFilter)
and not (usInserted in FClientDataSet.StatusFilter) then
FClientDataSet.EmptyDataSet;
end;
function TDBXClientDataSetTable.CreateTableView(const OrderByColumnName: string): TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
if not OrderByColumnName.IsEmpty then
View.IndexFieldNames := OrderByColumnName;
Result := TDBXClientDataSetTable.Create(CollectionName, CopyColumns, View);
end;
destructor TDBXClientDataSetTable.Destroy;
begin
FreeAndNil(FOriginal);
inherited;
end;
function TDBXClientDataSetTable.FindStringKey(const Ordinal: Integer; const Value: string): Boolean;
var
ColumnName: string;
begin
ColumnName := FClientDataSet.FieldDefs[Ordinal].Name;
if FClientDataSet.IndexFieldNames <> ColumnName then
FClientDataSet.IndexFieldNames := ColumnName;
Result := FClientDataSet.FindKey([Value]);
end;
constructor TDBXClientDataSetTable.Create(const CollectionName: string;
TableColumns: TDBXValueTypeArray; Table: TClientDataSet; OwnsTable: Boolean);
begin
inherited Create(CollectionName, Table, OwnsTable, False);
Columns := TableColumns;
FClientDataset := Table;
end;
procedure TDBXClientDataSetTable.SkipOriginalRow;
begin
if (usModified in FClientDataSet.StatusFilter) and (FClientDataSet.UpdateStatus = usUnmodified) then
FClientDataSet.Next;
end;
procedure TDBXClientDataSetTable.SetColumns(const Columns: TDBXValueTypeArray);
var
Ordinal: Integer;
begin
FreeValueTypes;
ValueTypes := Columns;
if FClientDataSet <> nil then
begin
FClientDataSet.Close;
for Ordinal := Low(Columns) to High(Columns) do
begin
if Ordinal >= FClientDataSet.FieldDefs.Count then
CopyValueTypeProperties(FClientDataSet.FieldDefs.AddFieldDef, Columns[Ordinal], Ordinal)
else if not (FClientDataSet.FieldDefs[Ordinal].Name = Columns[Ordinal].Name) then
raise TDBXError.Create(SMustKeepOriginalColumnOrder);
end;
FClientDataSet.CreateDataSet;
end;
CreateValues;
end;
function TDBXClientDataSetTable.GetDeletedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
View.StatusFilter := [usDeleted];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(CollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetInsertedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
View.StatusFilter := [usInserted];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(CollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetUpdatedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet, False, False);
View.StatusFilter := [usModified];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(CollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetOriginalRow: TDBXTableRow;
begin
if FOriginal = nil then
FOriginal := TDBXCDSOriginalRow.Create(self);
if FClientDataSet.UpdateStatus = usInserted then
Result := nil
else
Result := FOriginal;
end;
end.
|
unit MediaStorage.Transport;
interface
uses SysUtils,Classes, Windows;
//{$DEFINE STATIC_LINK_FILEAGENT}
type
IRecordObjectReader = interface
['{26EFF231-E972-4197-95A9-F88191C2A421}']
function GetStream: TStream;
function GetWholeFile: string;
//Подготовка к загрузке сначала файла
procedure PrepareFromBegin;
//Подготовка к загрузке с конца файла
procedure PrepareFromEnd;
end;
IRecordObjectWriter = interface
['{39EFFB2A-856A-4D2A-8D66-349C4DD4B21B}']
//Записывает данные и сразу же закрывает сессию. Можно вызывать только 1 раз
procedure WriteAndCommit(const aData; aSize: integer); overload;
//Записывает данные из указанного файла в себя и сразу же закрывает сессию. Можно вызывать только 1 раз
procedure WriteAndCommit(const aFileName: string); overload;
end;
IRecordObjectTransport = interface
['{A47E3851-820A-4EF3-9E26-C715417E4FEE}']
function TypeCode: byte;
//Название транспорта
function Name: string;
//Доставляет файл и дает на него ссылку для чтения
function GetReader: IRecordObjectReader;
//Создает экземпляр писателя файла
function GetWriter: IRecordObjectWriter;
function FileExists: boolean;
function FileSize: int64;
function ConnectionString: string;
function NeedCopying: boolean;
//Указывает на то, что транспорту надо будет создать временную локальную копию файла
//function NeedFileLocalCopyCreation:boolean;
end;
IRecordObjectTransportFactory = interface
function CreateTransport(const aFileName: string):IRecordObjectTransport;
end;
TRecordObjectTransportBase = class (TInterfacedObject)
public
constructor Create;
destructor Destroy; override;
end;
TRecordObjectFileBase = class (TInterfacedObject)
end;
implementation
var
gTransportInstanceCount: integer;
{ TRecordObjectTransportBase }
constructor TRecordObjectTransportBase.Create;
begin
inc(gTransportInstanceCount);
end;
destructor TRecordObjectTransportBase.Destroy;
begin
inherited;
dec(gTransportInstanceCount);
end;
initialization
finalization
try
except
Assert(gTransportInstanceCount=0);
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: fRenameSetting
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2005 All Rights Reserved.
Author: Erwien Saputra
Purpose: UI to rename or copy a setting. This class has one entry point,
returns true if the user assigned new name and clicked OK.
History:
-----------------------------------------------------------------------------}
unit fRenameSetting;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons;
type
TfrmRenameSetting = class(TForm)
lblOldName: TLabeledEdit;
lblNewName: TLabeledEdit;
btnOK: TButton;
btnCancel: TButton;
procedure lblNewNameKeyPress(Sender: TObject; var Key: Char);
procedure lblNewNameChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
class function Execute (const OldName : string; var NewName : string;
const Rename : boolean = true) : boolean;
end;
var
frmRenameSetting: TfrmRenameSetting;
implementation
uses
dmGlyphs;
{$R *.dfm}
const
RENAME_CAPTION = 'Rename Setting';
COPY_CAPTION = 'Copy Setting';
{ TfrmRename }
//Entry point for this class. This class facilitates renaming an existing
//setting or copying a setting.
class function TfrmRenameSetting.Execute(const OldName: string;
var NewName: string; const Rename: boolean = true): boolean;
var
frm : TfrmRenameSetting;
begin
frm := TfrmRenameSetting.Create (nil);
try
if Rename = true then
frm.Caption := RENAME_CAPTION
else
frm.Caption := COPY_CAPTION;
frm.lblOldName.Text := OldName;
if (Trim (NewName) = EmptyStr) then
frm.lblNewName.Text := EmptyStr
else
frm.lblNewName.Text := NewName;
Result := (frm.ShowModal = mrOK) and
(frm.lblNewName.Text <> NewName);
if Result = true then
NewName := frm.lblNewName.Text;
finally
frm.Release;
end;
end;
procedure TfrmRenameSetting.lblNewNameChange(Sender: TObject);
begin
btnOK.Enabled := Trim (lblNewName.Text) <> EmptyStr;
end;
procedure TfrmRenameSetting.lblNewNameKeyPress(Sender: TObject; var Key: Char);
begin
if Key = '\' then
Key := #0;
end;
end.
|
unit Test_FIToolkit.ProjectGroupParser.Parser;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.ProjectGroupParser.Parser;
type
// Test methods for class TProjectGroupParser
TestTProjectGroupParser = class(TGenericTestCase)
strict private
FProjectGroupParser : TProjectGroupParser;
private
function FindProjectGroup : String;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestGetIncludedProjectsFiles;
procedure TestInvalidFile;
end;
implementation
uses
TestUtils,
System.SysUtils, System.Types, System.IOUtils,
FIToolkit.ProjectGroupParser.Exceptions;
{ TestTProjectGroupParser }
function TestTProjectGroupParser.FindProjectGroup : String;
begin
Result := TDirectory.GetFiles(GetProjectGroupDir, '*.groupproj', TSearchOption.soAllDirectories)[0];
end;
procedure TestTProjectGroupParser.SetUp;
begin
if GetCurrTestMethodAddr = @TestTProjectGroupParser.TestInvalidFile then
FProjectGroupParser := TProjectGroupParser.Create(String.Empty)
else
FProjectGroupParser := TProjectGroupParser.Create(FindProjectGroup);
end;
procedure TestTProjectGroupParser.TearDown;
begin
FreeAndNil(FProjectGroupParser);
end;
procedure TestTProjectGroupParser.TestGetIncludedProjectsFiles;
var
sRootDir, S : String;
ReturnValue : TArray<TFileName>;
begin
sRootDir := GetProjectGroupDir;
ReturnValue := FProjectGroupParser.GetIncludedProjectsFiles;
CheckTrue(Length(ReturnValue) > 0, 'CheckTrue::(Length(ReturnValue) > 0)');
for S in ReturnValue do
begin
CheckTrue(S.StartsWith(sRootDir, True), 'CheckTrue::ReturnValue[i].StartsWith(sRootDir)<%s>', [S]);
CheckTrue(TPath.GetExtension(S).Equals('.dpr') or TPath.GetExtension(S).Equals('.dpk'),
'CheckTrue::<"%s" in [".dpr", ".dpk"]>', [TPath.GetExtension(S)]);
CheckTrue(TFile.Exists(S), 'CheckTrue::TFile.Exists("%s")', [S]);
end;
end;
procedure TestTProjectGroupParser.TestInvalidFile;
begin
CheckException(
procedure
begin
FProjectGroupParser.GetIncludedProjectsFiles;
end,
EProjectGroupParseError,
'CheckException::EProjectGroupParseError'
);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTProjectGroupParser.Suite);
end.
|
unit Annotation.Action;
interface
uses
SuperObject, Vcl.Graphics, System.Types, Settings;
type
IAnnotationAction = interface
function ToJSON(): ISuperObject;
procedure AddToJSONArray(var JSON: ISuperObject; const ArrayName: string);
procedure RenderOnMask(var MaskBitmap: TBitmap);
procedure RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader);
function GetJOSNTypeName: string;
function HistoryCaption: string;
end;
TEmptyAction = class(TInterfacedObject, IAnnotationAction)
function ToJSON(): ISuperObject;
procedure AddToJSONArray(var JSON: ISuperObject; const ArrayName: string); virtual;
procedure RenderOnMask(var MaskBitmap: TBitmap); virtual;
procedure RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader); virtual;
function GetJOSNTypeName: string; virtual;
function HistoryCaption: string; virtual;
end;
TOriginalImageAction = class(TEmptyAction)
public
function HistoryCaption: string; override;
end;
TDotMarker = class(TInterfacedObject, IAnnotationAction)
private
FX: integer;
FY: integer;
public
constructor Create(const X, Y: integer); overload;
constructor Create(const APoint: TPoint); overload;
destructor Destroy; override;
property X: integer read FX;
property Y: integer read FY;
function ToJSON(): ISuperObject;
procedure AddToJSONArray(var JSON: ISuperObject; const ArrayName: string);
procedure RenderOnMask(var MaskBitmap: TBitmap);
procedure RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader);
function GetJOSNTypeName: string;
function HistoryCaption: string;
end;
TAnnotationClear = class(TEmptyAction, IAnnotationAction)
public
procedure AddToJSONArray(var JSON: ISuperObject; const ArrayName: string); override;
procedure RenderOnMask(var MaskBitmap: TBitmap); override;
procedure RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader); override;
function HistoryCaption: string; override;
end;
implementation
uses
SysUtils;
{ TDotMarker }
constructor TDotMarker.Create(const X, Y: integer);
begin
inherited Create;
FX:= X;
FY:= Y;
end;
procedure TDotMarker.AddToJSONArray(var JSON: ISuperObject; const ArrayName: string);
begin
JSON.A[ArrayName].Add(ToJSON);
end;
constructor TDotMarker.Create(const APoint: TPoint);
begin
Create(APoint.X, APoint.Y);
end;
destructor TDotMarker.Destroy;
begin
inherited;
end;
function TDotMarker.GetJOSNTypeName: string;
begin
Result:= 'dot_marker';
end;
function TDotMarker.HistoryCaption: string;
begin
Result:= 'Dot marker at [' + IntToStr(X) + ', ' + IntToStr(Y) + ']';
end;
procedure TDotMarker.RenderOnMask(var MaskBitmap: TBitmap);
begin
MaskBitmap.Canvas.Pixels[X, Y]:= clWhite;
end;
procedure TDotMarker.RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader);
var
PenWidth,
StrokeLength: integer;
begin
PenWidth:= Settings.GetDotMarkerStrokeWidth;
StrokeLength:= Settings.GetDotMarkerStrokeLength;
ViewBitmap.Canvas.Pen.Color:= Settings.GetDotMarkerColor;
ViewBitmap.Canvas.Pen.Width:= PenWidth;
ViewBitmap.Canvas.MoveTo(X, Y - StrokeLength);
ViewBitmap.Canvas.LineTo(X, Y + StrokeLength);
ViewBitmap.Canvas.MoveTo(X - StrokeLength, Y);
ViewBitmap.Canvas.LineTo(X + StrokeLength, Y);
end;
function TDotMarker.ToJSON(): ISuperObject;
begin
Result:= SO;
Result.S['type']:= GetJOSNTypeName;
Result.I['x']:= X;
Result.I['y']:= Y;
end;
{ TEmptyAction }
procedure TEmptyAction.AddToJSONArray(var JSON: ISuperObject; const ArrayName: string);
begin
//
end;
function TEmptyAction.GetJOSNTypeName: string;
begin
//
end;
function TEmptyAction.HistoryCaption: string;
begin
Result:= 'Empty action';
end;
procedure TEmptyAction.RenderOnMask(var MaskBitmap: TBitmap);
begin
//
end;
procedure TEmptyAction.RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader);
begin
//
end;
function TEmptyAction.ToJSON: ISuperObject;
begin
Result:= SO;
end;
{ TOriginalImageAction }
function TOriginalImageAction.HistoryCaption: string;
begin
Result:= 'Original image';
end;
{ TAnnotationClear }
procedure TAnnotationClear.AddToJSONArray(var JSON: ISuperObject;
const ArrayName: string);
begin
JSON.A[ArrayName].Clear(true);
end;
function TAnnotationClear.HistoryCaption: string;
begin
Result:= 'Clear';
end;
procedure TAnnotationClear.RenderOnMask(var MaskBitmap: TBitmap);
begin
MaskBitmap.Canvas.Brush.Color:= clBlack;
MaskBitmap.Canvas.FillRect(Rect(0, 0, MaskBitmap.Width, MaskBitmap.Height));
end;
procedure TAnnotationClear.RenderOnView(var ViewBitmap: TBitmap; const Settings: ISettingsReader);
begin
ViewBitmap.Canvas.Brush.Color:= clBlack;
ViewBitmap.Canvas.FillRect(Rect(0, 0, ViewBitmap.Width, ViewBitmap.Height));
end;
end.
|
unit PIA1070B_4_1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OnEditStdCtrl, OnEditCombo, ExtCtrls, OnShapeLabel, OnEditBaseCtrl,
OnEditBtnCtrl, OnTmaxCodeEdit, OnScheme, StdCtrls, OnFocusButton, Db,
Tmax_DataSetText;
type
TFM_SubForm4_1 = class(TForm)
FM_SubForm4_1: TOnSchemeForm;
TDml: TTMaxDataSet;
QR_du: TTMaxDataSet;
Panel1: TPanel;
OnShapeLabel1: TOnShapeLabel;
ED_Schgr: TTMaxCodePopupEdit;
OnShapeLabel2: TOnShapeLabel;
ED_Schnm: TOnEdit;
OnShapeLabel3: TOnShapeLabel;
OnShapeLabel4: TOnShapeLabel;
ED_SchCode: TTMaxCodePopupEdit;
OnShapeLabel5: TOnShapeLabel;
ED_SchFrYM: TOnMaskEdit;
OnShapeLabel6: TOnShapeLabel;
ED_Majorcode: TTMaxCodePopupEdit;
OnShapeLabel7: TOnShapeLabel;
BT_Add: TOnFocusButton;
BT_del: TOnFocusButton;
BT_save: TOnFocusButton;
BT_close: TOnFocusButton;
PA_Buttons: TPanel;
Label1: TLabel;
Image1: TImage;
BT_Exit: TOnFocusButton;
OnFocusButton1: TOnFocusButton;
BT_Find: TOnFocusButton;
Ed_Majornm: TOnEdit;
Ed_Schgrnm: TOnEdit;
ED_SchToYM: TOnMaskEdit;
Ed_Schkind: TTMaxCodePopupEdit;
Ed_Schkindnm: TOnEdit;
Ed_SchgrTime: TTMaxCodePopupEdit;
Ed_SchgrTimenm: TOnEdit;
Ed_SchRank: TOnEdit;
OnShapeLabel8: TOnShapeLabel;
Ed_Smajnm: TOnEdit;
OnShapeLabel9: TOnShapeLabel;
Ed_Stopic: TOnEdit;
procedure BT_closeClick(Sender: TObject);
procedure BT_saveClick(Sender: TObject);
procedure BT_AddClick(Sender: TObject);
procedure BT_delClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ED_SchgrChange(Sender: TObject);
private
{ Private declarations }
function BmodCheck : Boolean;
procedure PimPmasUpdate;
public
{ Public declarations }
function Csel_gfd(p_loc: Integer): String;
end;
var
FM_SubForm4_1: TFM_SubForm4_1;
v_add : string;
implementation
uses PIA1070B_1, PIA1070B_4;
{$R *.DFM}
procedure TFM_SubForm4_1.BT_closeClick(Sender: TObject);
begin
Close;
end;
// 저장 버튼 클릭시
procedure TFM_SubForm4_1.BT_saveClick(Sender: TObject);
var
Tem : String;
begin
PA_Buttons.Caption := ' ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
if BmodCheck = False then system.exit; //널값 체크
// 신규 데이터 추가시
if v_add = 'A' then
begin
// 기존 데이터 유무 체크
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
sql.Add(Format('select empno from pimscho '+
'where (empno = ''%s'') and (Schgr = ''%s'') and (SchRank = ''%s'')',
[FM_Main.ED_empno.Text,ED_Schgr.codeno,ED_SchRank.text ]));
Open;
if QR_du.RecordCount > 0 then
begin
Application.Messagebox('기존의 데이타가 존재합니다 !!','작업안내',mb_ok+ mb_IconStop);
system.Exit;
end;
end;
Tem := Format('insert into pimscho '+
' (EMPNO, KORNAME, SCHGR, SCHRANK, SCHCODE, SCHNM, '+
' MAJORCODE, SCHFRYM, SCHTOYM, SCHKIND, SCHGRTIME,'+
' SCHACKYN, SMAJNM, STOPIC, WRITETIME, WRITEEMP) '+
'values (''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', '+
' ''%s'', ''%s'', ''%s'', ''%s'', ''%s'' '+
' ''%s'', ''%s'', ''%s'', '+
' to_char(sysdate, ''YYYYMMDDHH24MISS''),''%s'') ',
[FM_Main.ED_empno.Text,FM_Main.ED_korname.valuecaption,ED_Schgr.codeno,
ED_SchRank.Text, Ed_Schcode.codeno, Ed_SchNm.Text,
ED_MajorCode.codeno, ED_schFrYm.Text, ED_schToYm.Text,
ED_SchKind.codeno, ED_Schgrtime.codeno, 'Y', FM_Main.FG_pempno]);
with TDml do
begin
Close;
Sql.Clear;
Sql.text := Tem;
ServiceName := 'PIB3012A_dml';
if not Execute then
begin
Application.Messagebox('저장에 실패했습니다.I','작업안내',mb_ok+ mb_IconStop);
end;
end;
PA_Buttons.Caption := ' ☞ 학력사항을 추가 -> 저장 하였습니다. !!. ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
end
else
begin
Tem := 'update pimscho '+
' set SCHGR ='''+ED_SchGr.codeno +''', '+
' SCHRANK ='''+ED_SchRank.Text +''', '+
' SCHCODE ='''+ED_SchCode.codeno +''', '+
' SCHNM ='''+ED_SchNm.Text +''', '+
' MAJORCODE='''+ED_MajorCode.codeno+''', '+
' SCHFRYM ='''+ED_SchFrYm.Text +''', '+
' SCHTOYM ='''+ED_SchToYm.Text +''', '+
' SCHKIND ='''+ED_SchKind.codeno +''', '+
' SCHGRTIME='''+ED_Schgrtime.codeno+''', '+
' SCHACKYN =''Y'', '+
' SMAJNM ='''+ED_SMajNm.Text +''', '+
' STOPIC ='''+ED_STopic.Text +''', '+
' writetime=to_char(sysdate, ''YYYYMMDDHH24MISS''), '+
' writeemp ='''+FM_Main.FG_pempno+''' '+
' where (empno ='''+FM_Main.ED_empno.Text+''') '+
' and (Schgr ='''+FM_SubForm3.QR_qry.FieldByName('Schgr').AsString+''') '+
' and (SchRank ='''+FM_SubForm3.QR_qry.FieldByName('SchRank').AsString+''')';
with TDml do
begin
Close;
Sql.Clear;
Sql.text := Tem;
ServiceName := 'PIB3012A_dml';
if not Execute then
begin
Application.Messagebox('저장에 실패했습니다.U','작업안내',mb_ok+ mb_IconStop);
end;
end;
PA_Buttons.Caption := ' ☞ 학력사항을 수정 -> 저장 하였습니다. !!. ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
end;
PimPmasUpdate;
v_add := '';
end;
function TFM_SubForm4_1.Csel_gfd(p_loc: Integer): String;
var
v_cnt, v_tmp: Integer;
v_data: String;
begin
Result := '';
v_data := QR_du.FieldByName('SEL_DATA').AsString;
v_cnt := 1;
while v_cnt < p_loc do
begin
v_tmp := Pos(';',v_data);
if not(v_tmp > 0) then Exit;
v_cnt := v_cnt + 1;
Delete(v_data, 1, v_tmp);
end;
v_tmp := Pos(';',v_data) - 1;
if v_tmp < 0 then v_tmp := Length(v_data);
Result := Copy(v_data,1,v_tmp);
end;
{인사마스터 부분 수정}
procedure TFM_SubForm4_1.PimPmasUpdate;
var
Stemp : array[1..14] of String;
i : integer;
begin
for i := 1 to 14 do Stemp[i] := '';
Try
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
Sql.Text := 'select schgr from pimscho '+
' where empno = '''+FM_Main.ED_empno.Text+''' '+
' and schgrtime = ''1'' '+
' order by schgr desc,schrank ';
Open;
Stemp[1] := Csel_gfd(1); {입사시학력}
end;
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
Sql.Text := 'select schgr||'';''||schcode||'';''||schnm||'';''|| '+
' majorcode||'';''||schtoym||'';''||schfrym '+
' from pimscho '+
' where (empno = '''+FM_Main.ED_empno.Text+''') '+
' order by schgr desc,schrank ';
Open;
First;
Stemp[2] := Csel_gfd(1); {최종학력}
Stemp[3] := Csel_gfd(2); {최종학교}
Stemp[4] := Csel_gfd(3); {최종학교명}
Stemp[5] := Csel_gfd(4); {전공}
Stemp[6] := Csel_gfd(5); {졸업}
Stemp[7] := Csel_gfd(6); {입학}
end;
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
Sql.Text := 'select schgr||'';''||smajnm||'';''||stopic from pimscho '+
' where empno = '''+FM_Main.ED_empno.Text+''' '+
' and substr(schgr,2,1) in (''9'', ''7'')) '+
' order by schgr desc, schrank ';
Open;
First;
if (Copy(Csel_gfd(1), 2, 1) = '7') then
Stemp[8] := copy(Csel_gfd(1), 1, 1) + '9'
else
Stemp[8] := Csel_gfd(1); {최종학위}
Stemp[9] := Csel_gfd(2); {세부전공}
Stemp[10] := Csel_gfd(3); {논문}
end;
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
Sql.Text := 'select schcode||'';''||majorcode||'';''||schtoym||'';''||schfrym '+
' from pimscho '+
' where (empno = '''+FM_Main.ED_empno.Text+''' and schgr = ''59'') '+
' order by schrank ';
Open;
First;
Stemp[11] := Csel_gfd(1);
Stemp[12] := Csel_gfd(2);
Stemp[13] := Csel_gfd(3);
Stemp[14] := Csel_gfd(4); {입학}
Close;
end;
{인사마스터에 데이타를 업데이트 한다..}
PA_Buttons.Caption := '인사 마스터를 수정하고 있는 중입니다..';
with TDml do
begin
Close;
Sql.Clear;
Sql.text :='update pimpmas '+
' set empschgr = '''+Stemp[1] +''', '+
' lschgr = '''+Stemp[2] +''', '+
' lschcode = '''+Stemp[3] +''', '+
' lschnm = '''+Stemp[4] +''', '+
' lmajorcode= '''+Stemp[5] +''', '+
' lschgrym = '''+Stemp[6] +''', '+
' lschfrym = '''+Stemp[7] +''', '+
' lschdeg = '''+Stemp[8] +''', '+
' lschmajnm = '''+Stemp[9] +''', '+
' lschtopic = '''+Stemp[10]+''', '+
' unicode = '''+Stemp[11]+''', '+
' unimajor = '''+Stemp[12]+''', '+
' unigrym = '''+Stemp[13]+''', '+
' unifrym = '''+Stemp[14]+''' '+
' where (empno = '''+FM_Main.ED_empno.Text+''') ';
ServiceName := 'PIB3012A_dml';
if not Execute then
begin
Application.Messagebox('인사마스터 저장에 실패했습니다.','작업안내',mb_ok+ mb_IconStop);
end;
end;
EXCEPT ON E : EDataBaseError DO
Application.Messagebox('인사마스터 저장에 실패했습니다.','작업안내',mb_ok+ mb_IconStop);
END;
end;
function TFM_SubForm4_1.BmodCheck : Boolean;
var
str : string;
begin
Result := True;
str := '';
if (trim(ED_Schgr.Text) = '') then
str := str+'학력구분 필드에러'+chr(13)+chr(10)+chr(13)+chr(10);;
if (trim(ED_SchRank.Text) = '') then
str := str+'동일학력순위 필드에러'+chr(13)+chr(10)+chr(13)+chr(10);
if str <> '' then begin
MessageBox(handle,pChar(str),'에 러',MB_OK or $0010);
Result := False;
end;
end;
//추가 버튼 클릭시
procedure TFM_SubForm4_1.BT_AddClick(Sender: TObject);
begin
PA_Buttons.Caption := ' ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
ED_Schgr.Text :='';
Ed_Schgrnm.Text :='';
Ed_SchRank.Text :='';
ED_SchCode.Text :='';
ED_Schnm.Text :='';
ED_Majorcode.Text :='';
Ed_Majornm.Text :='';
ED_SchFrYM.Text :='';
ED_SchToYM.Text :='';
Ed_Schkind.Text :='';
Ed_Schkindnm.Text :='';
Ed_SchgrTime.Text :='';
Ed_SchgrTimenm.Text :='';
Ed_Smajnm.Text :='';
Ed_Stopic.Text :='';
v_add:='A';
end;
//삭제 버튼 클릭시
procedure TFM_SubForm4_1.BT_delClick(Sender: TObject);
var
Tem : string;
begin
PA_Buttons.Caption := ' ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
// 기존 데이터 유무 체크
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
sql.Add(Format('select empno from pimscho '+
'where (empno = ''%s'') and (Schgr = ''%s'') and (SchRank = ''%s'')',
[FM_Main.ED_empno.Text,ED_Schgr.codeno,ED_SchRank.text ]));
Open;
if QR_du.RecordCount <= 0 then
begin
Application.Messagebox('데이타가 존재하지 않습니다. !!','작업안내',mb_ok+ mb_IconStop);
system.Exit;
end;
end;
if MessageBox(handle,'데이타를 삭제하시겠습니까 ?.','확 인',MB_YESNO or $0030) = ID_NO then begin
system.exit;
end;
Tem := Format('delete from pimscho '+
'where (empno = ''%s'') and (Schgr = ''%s'') and (SchRank = ''%s'')',
[FM_Main.ED_empno.Text,ED_Schgr.codeno,ED_SchRank.text ]);
with TDml do
begin
Close;
Sql.Clear;
Sql.text := Tem;
ServiceName := 'PIB3012A_dml';
if not Execute then
begin
Application.Messagebox('삭제에 실패했습니다.D','작업안내',mb_ok+ mb_IconStop);
end;
end;
ED_Schgr.Text :='';
Ed_Schgrnm.Text :='';
Ed_SchRank.Text :='';
ED_SchCode.Text :='';
ED_Schnm.Text :='';
ED_Majorcode.Text :='';
Ed_Majornm.Text :='';
ED_SchFrYM.Text :='';
ED_SchToYM.Text :='';
Ed_Schkind.Text :='';
Ed_Schkindnm.Text :='';
Ed_SchgrTime.Text :='';
Ed_SchgrTimenm.Text :='';
Ed_Smajnm.Text :='';
Ed_Stopic.Text :='';
PA_Buttons.Caption := ' ☞ 학력사항을 삭제 하였습니다. !!. ';
SendMessage(PA_Buttons.handle,WM_PAINT,0,0);
end;
procedure TFM_SubForm4_1.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Close;
end;
procedure TFM_SubForm4_1.ED_SchgrChange(Sender: TObject);
begin
Case TTMaxCodePopupEdit(Sender).Tag of
1: begin
if (Copy(Ed_Schgr.Text,1,1) = '6') or
(Copy(Ed_Schgr.Text,1,1) = '7') or
(Copy(Ed_Schgr.Text,2,1) = '' ) then
begin
Ed_Smajnm.Enabled := True;
Ed_Stopic.Enabled := True;
end
else
begin
Ed_Smajnm.Enabled := False;
Ed_Stopic.Enabled := False;
end;
Ed_Schgrnm.Text := TTMaxCodePopupEdit(Sender).Codename;
with QR_du do
begin
Close;
ServiceName := 'SHR0SSEL';
ClearFieldInfo;
AddField('SEL_DATA',ftString,5000);
Sql.Clear;
Sql.Text := 'select Count(schgr)+1 from pimscho '+
' where empno = '''+FM_Main.ED_empno.Text+''' '+
' and schgr = '''+Ed_Schgr.Text+''' ';
Open;
Ed_SchRank.Text := Csel_gfd(1); {동일학력순위}
end;
end;
2: Ed_Schnm.Text := TTMaxCodePopupEdit(Sender).Codename;
3: Ed_Majornm.Text := TTMaxCodePopupEdit(Sender).Codename;
4: Ed_SchKindnm.Text := TTMaxCodePopupEdit(Sender).Codename;
5: Ed_SchGrTimenm.Text := TTMaxCodePopupEdit(Sender).Codename;
end;
end;
end.
|
unit BodyVariationsQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TBodyVariationW = class(TDSWrap)
private
FIDBodyData: TFieldWrap;
FID: TFieldWrap;
FImage: TFieldWrap;
FLandPattern: TFieldWrap;
FOutlineDrawing: TFieldWrap;
FVariation: TFieldWrap;
protected
property IDBodyData: TFieldWrap read FIDBodyData;
property ID: TFieldWrap read FID;
property Image: TFieldWrap read FImage;
property LandPattern: TFieldWrap read FLandPattern;
property OutlineDrawing: TFieldWrap read FOutlineDrawing;
property Variation: TFieldWrap read FVariation;
public
constructor Create(AOwner: TComponent); override;
end;
TQueryBodyVariations = class(TQueryBase)
FDUpdateSQL: TFDUpdateSQL;
private
FW: TBodyVariationW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
procedure LocateOrAppend(AIDBodyData: Integer; const AOutlineDrawing,
ALandPattern, AVariation, AImage: string);
property W: TBodyVariationW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQueryBodyVariations.Create(AOwner: TComponent);
begin
inherited;
FW := TBodyVariationW.Create(FDQuery);
end;
procedure TQueryBodyVariations.LocateOrAppend(AIDBodyData: Integer; const
AOutlineDrawing, ALandPattern, AVariation, AImage: string);
var
AFieldNames: string;
begin
Assert(AIDBodyData > 0);
AFieldNames := Format('%s;%s', [W.IDBodyData.FieldName, W.Variation.FieldName]);
if not FDQuery.LocateEx(AFieldNames, VarArrayOf([AIDBodyData, AVariation]),
[lxoCaseInsensitive]) then
W.TryAppend
else
W.TryEdit;
W.IDBodyData.F.Value := AIDBodyData;
W.OutlineDrawing.F.Value := AOutlineDrawing;
W.LandPattern.F.Value := ALandPattern;
W.Variation.F.Value := AVariation;
W.Image.F.Value := AImage;
W.TryPost;
end;
constructor TBodyVariationW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FIDBodyData := TFieldWrap.Create(Self, 'IDBodyData');
FImage := TFieldWrap.Create(Self, 'Image');
FLandPattern := TFieldWrap.Create(Self, 'LandPattern');
FOutlineDrawing := TFieldWrap.Create(Self, 'OutlineDrawing');
FVariation := TFieldWrap.Create(Self, 'Variation');
end;
end.
|
unit Security.ChangePassword.Interfaces;
interface
Type
TChangePasswordNotifyEvent = procedure(const aID: Int64; const aNewPassword: string; var aError: string; var aChanged: boolean) of Object;
TResultNotifyEvent = procedure(const aResult: boolean = false) of Object;
Type
iPrivateChangePasswordEvents = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ Strict private declarations }
function getUsuario: string;
procedure setUsuario(const Value: string);
function getID: Int64;
procedure setID(const Value: Int64);
function getPassword: string;
procedure setPassword(const Value: string);
function getNewPassword: string;
procedure setOnChangePassword(const Value: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent);
function getOnChangePassword: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent;
procedure setOnResult(const Value: Security.ChangePassword.Interfaces.TResultNotifyEvent);
function getOnResult: Security.ChangePassword.Interfaces.TResultNotifyEvent;
end;
iChangePasswordViewEvents = interface(iPrivateChangePasswordEvents)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ Public declarations }
property OnChangePassword: TChangePasswordNotifyEvent read getOnChangePassword write setOnChangePassword;
property OnResult: TResultNotifyEvent read getOnResult write setOnResult;
end;
iPrivateChangePasswordViewProperties = interface
['{DCE42688-962D-4AA4-B719-7058C8714386}']
{ Private declarations }
function getComputerIP: string;
function getServerIP: string;
function getSigla: string;
function getUpdatedAt: string;
function getVersion: string;
procedure setComputerIP(const Value: string);
procedure setServerIP(const Value: string);
procedure setSigla(const Value: string);
procedure setUpdatedAt(const Value: string);
procedure setVersion(const Value: string);
end;
iChangePasswordViewProperties = interface(iPrivateChangePasswordViewProperties)
['{9047BD6E-6181-49F0-95CD-123155EC0EA9}']
{ Public declarations }
property ComputerIP: string read getComputerIP write setComputerIP;
property ServerIP: string read getServerIP write setServerIP;
property Sigla: string read getSigla write setSigla;
property Version: string read getVersion write setVersion;
property UpdatedAt: string read getUpdatedAt write setUpdatedAt;
end;
iChangePasswordView = interface
['{87FEC43E-4C47-47D7-92F6-E0B6A532E49D}']
// function Properties: iChangePasswordViewProperties;
function Events: iChangePasswordViewEvents;
end;
implementation
end.
|
unit LoanTypeList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton,
Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel,
Vcl.ExtCtrls, RzPanel, Vcl.DBCtrls, RzDBEdit, RzDBCmbo;
type
TfrmLoanTypeList = class(TfrmBaseGridDetail)
edTypeName: TRzDBEdit;
RzDBMemo1: TRzDBMemo;
dbluAccountType: TRzDBLookupComboBox;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
protected
function EntryIsValid: boolean; override;
function NewIsAllowed: boolean; override;
function EditIsAllowed: boolean; override;
procedure SearchList; override;
procedure BindToObject; override;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
LoansAuxData, IFinanceDialogs;
procedure TfrmLoanTypeList.SearchList;
begin
grList.DataSource.DataSet.Locate('loan_type_name',edSearchKey.Text,
[loPartialKey,loCaseInsensitive]);
end;
procedure TfrmLoanTypeList.BindToObject;
begin
inherited;
end;
function TfrmLoanTypeList.EditIsAllowed: boolean;
begin
Result := true;
end;
function TfrmLoanTypeList.EntryIsValid: boolean;
var
error: string;
begin
if Trim(edTypeName.Text) = '' then error := 'Please enter a name.'
else if Trim(dbluAccountType.Text) = '' then error := 'Please select an account.';
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
procedure TfrmLoanTypeList.FormClose(Sender: TObject; var Action: TCloseAction);
begin
dmLoansAux.Free;
inherited;
end;
procedure TfrmLoanTypeList.FormCreate(Sender: TObject);
begin
dmLoansAux := TdmLoansAux.Create(self);
inherited;
end;
function TfrmLoanTypeList.NewIsAllowed: boolean;
begin
Result := true;
end;
end.
|
unit caMutex;
{$INCLUDE ca.inc}
interface
uses
// Standard delphi units
Windows,
SysUtils,
Classes,
// ca units
caClasses,
caUtils;
type
TcaMutexActivation = (maOpen, maCreate);
TcaMutexState = (msClosed, msOpenNew, msOpenExisting);
TcaWaitResult = (wrAbandoned, wrSignaledObject, wrTimedOut, wrFailed);
//```````````````````````````````````````````````````````````````````````````
// IcaMutex
//```````````````````````````````````````````````````````````````````````````
IcaMutex = interface
['{D59BF1B3-772E-4EC2-A7EE-D1FDDCD7F3F3}']
// Property methods
function GetHandle: THandle;
function GetIsOpen: Boolean;
function GetName: string;
function GetState: TcaMutexState;
// Interface methods
function Wait(ATimeOut: DWORD = 0): TcaWaitResult;
procedure Activate(AActivationType: TcaMutexActivation);
procedure Open;
procedure Close;
// Interface properties
property Handle: THandle read GetHandle;
property IsOpen: Boolean read GetIsOpen;
property Name: string read GetName;
property State: TcaMutexState read GetState;
end;
//```````````````````````````````````````````````````````````````````````````
// TcaMutex
//```````````````````````````````````````````````````````````````````````````
TcaMutex = class(TInterfacedObject)
private
// Property fields
FHandle: THandle;
FName: string;
FState: TcaMutexState;
// Property methods
function GetHandle: THandle;
function GetIsOpen: Boolean;
function GetName: string;
function GetState: TcaMutexState;
public
// Create/Destroy
constructor Create(const AName: string = '');
destructor Destroy; override;
// Interface methods
function Wait(ATimeOut: DWORD = INFINITE): TcaWaitResult;
procedure Open;
procedure Close;
// Interface properties
property Handle: THandle read GetHandle;
property IsOpen: Boolean read GetIsOpen;
property Name: string read GetName;
property State: TcaMutexState read GetState;
end;
implementation
//```````````````````````````````````````````````````````````````````````````
// TcaMutex
//```````````````````````````````````````````````````````````````````````````
// Create/Destroy
constructor TcaMutex.Create(const AName: string);
begin
inherited Create;
FName := AName;
end;
destructor TcaMutex.Destroy;
begin
if GetIsOpen then Close;
inherited;
end;
// Interface methods
function TcaMutex.Wait(ATimeOut: DWORD = INFINITE): TcaWaitResult;
var
WaitResult: DWORD;
begin
WaitResult := WaitForSingleObject(FHandle, ATimeOut);
case WaitResult of
WAIT_OBJECT_0: Result := wrSignaledObject;
WAIT_ABANDONED: Result := wrAbandoned;
WAIT_TIMEOUT: Result := wrTimedOut;
WAIT_FAILED: Result := wrFailed;
else
Result := wrFailed;
end;
end;
procedure TcaMutex.Close;
begin
ReleaseMutex(FHandle);
CloseHandle(FHandle);
FHandle := 0;
FState := msClosed;
end;
procedure TcaMutex.Open;
var
Err: DWORD;
begin
if FState = msClosed then
begin
FHandle := CreateMutex(nil, False, PChar(FName));
Err := GetLastError;
if Err = ERROR_ALREADY_EXISTS then
begin
FHandle := OpenMutex(MUTEX_ALL_ACCESS, True, PChar(FName));
FState := msOpenExisting;
end
else
begin
if Err = ERROR_SUCCESS then
FState := msOpenNew
else
FState := msClosed;
end;
end;
end;
// Property methods
function TcaMutex.GetHandle: THandle;
begin
Result := FHandle;
end;
function TcaMutex.GetName: string;
begin
Result := FName;
end;
function TcaMutex.GetIsOpen: Boolean;
begin
Result := FState <> msClosed;
end;
function TcaMutex.GetState: TcaMutexState;
begin
Result := FState;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Win.BluetoothWinRT;
interface
uses
System.SysUtils, System.Bluetooth;
{$SCOPEDENUMS ON}
type
TPlatformWinRTBluetoothLEManager = class(TBluetoothLEManager)
public
class function GetBluetoothManager: TBluetoothLEManager; override;
end;
implementation
uses
Winapi.Windows, System.Types, System.Generics.Collections, System.SyncObjs, System.StrUtils, System.Classes,
WinApi.Bluetooth, WinApi.BluetoothLE, System.Win.Winrt, Winapi.winrt, Winapi.Foundation, Winapi.Foundation.Types,
Winapi.Foundation.Collections, Winapi.Devices.Enumeration, Winapi.Devices, Winapi.Devices.Bluetooth,
Winapi.Devices.Bluetooth.Advertisement, Winapi.CommonTypes, Winapi.Storage.Streams, System.NetConsts, System.RTLConsts;
const
SBluetoothMACAddressFormat = '%0.2X:%0.2X:%0.2X:%0.2X:%0.2X:%0.2X'; // Do not translate
type
TAsyncOperation<T: IInterface> = class
private type
TCancelProcedure = reference to procedure;
TThreadTimer = class(TThread)
private
FTimeout: Cardinal;
FEvent: TEvent;
FOnTimer: TCancelProcedure;
procedure Cancel;
public
constructor Create(const ACancelProc: TCancelProcedure; Timeout: Cardinal); overload;
destructor Destroy; override;
procedure Execute; override;
end;
class function Wait(const AAsyncOp: T; var AsyncOpResult: T; ATimeout: Cardinal = INFINITE): AsyncStatus;
end;
TWinRTBluetoothLEManager = class(TPlatformWinRTBluetoothLEManager)
private
FLEAdapter: TBluetoothLEAdapter;
protected
function GetRadioAdapter: Boolean;
function GetConnectionState: TBluetoothConnectionState; override;
function DoGetAdapter: TBluetoothLEAdapter; override;
// LE Fucntionality
function DoGetGattServer: TBluetoothGattServer; override;
function DoGetSupportsGattClient: Boolean; override;
function DoGetSupportsGattServer: Boolean; override;
function DoEnableBluetooth: Boolean; override;
public
destructor Destroy; override;
end;
TWinRTBluetoothLEAdapter = class;
TBLEAdvertisementReceivedEventHandler = class(TInspectableObject,
TypedEventHandler_2__IBluetoothLEAdvertisementWatcher__IBluetoothLEAdvertisementReceivedEventArgs_Delegate_Base,
TypedEventHandler_2__IBluetoothLEAdvertisementWatcher__IBluetoothLEAdvertisementReceivedEventArgs)
private
[Weak] FAdapter: TWinRTBluetoothLEAdapter;
procedure Invoke(sender: IBluetoothLEAdvertisementWatcher; args: IBluetoothLEAdvertisementReceivedEventArgs); safecall;
public
constructor Create(const AAdapter: TWinRTBluetoothLEAdapter);
end;
TWinRTBluetoothLEAdapter = class(TBluetoothLEAdapter)
private type
TStopDiscoveryProc = procedure of object;
TDiscoverThreadTimer = class(TThread)
private
[Weak] FAdapter: TBluetoothLEAdapter;
FTimeout: Cardinal;
FOnTimer: TStopDiscoveryProc;
FEvent: TEvent;
procedure Cancel;
public
constructor Create(const AnAdapter: TBluetoothLEAdapter; const AStopDiscoveryProc: TStopDiscoveryProc; Timeout: Cardinal); overload;
destructor Destroy; override;
procedure Execute; override;
end;
private
FAdvertisementWatcher: IBluetoothLEAdvertisementWatcher;
FBLEAdvertisementReceivedDelegate: TypedEventHandler_2__IBluetoothLEAdvertisementWatcher__IBluetoothLEAdvertisementReceivedEventArgs;
FBLEAdvertisementReceivedDelegateERT: EventRegistrationToken;
FScannedLEDevices: TBluetoothLEDeviceDictionary;
FTimerThread: TDiscoverThreadTimer;
FBluetoothLEScanFilterList: TBluetoothLEScanFilterList;
procedure GetBLEPairedDevices;
protected
FRadioInfo: TBluetoothRadioInfo;
function GetAdapterName: string; override;
procedure SetAdapterName(const Value: string); override;
function GetAddress: System.Bluetooth.TBluetoothMacAddress; override;
function DoStartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList = nil;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil): Boolean; override;
function DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; override;
procedure DoCancelDiscovery; override;
procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); override;
function GetScanMode: TBluetoothScanMode; override;
function GetState: TBluetoothAdapterState; override;
procedure BLEAdvertisementReceived(const AAdvertisement: IBluetoothLEAdvertisement;
const AdvertisementType: BluetoothLEAdvertisementType; AAddress: UInt64; ARSSI: SmallInt; const ATimestamp: DateTime);
procedure StopDiscovery;
procedure DoDeviceDiscovered(const ADevice: System.Bluetooth.TBluetoothLEDevice; ANewDevice: Boolean;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList); override;
public
constructor Create(const AManager: TBluetoothLEManager; const ARadioInfo: TBluetoothRadioInfo);
destructor Destroy; override;
end;
TWinRTBluetoothLEAdvertiseData = class(TBluetoothLEAdvertiseData)
private
FDevice: System.Bluetooth.TBluetoothLEDevice;
protected
function DoAddServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; override;
procedure DoRemoveServiceUUID(const AServiceUUID: TBluetoothUUID); override;
procedure DoClearServiceUUIDs; override;
function DoAddServiceData(const AServiceUUID: TBluetoothUUID; const AData: TBytes): Boolean; override;
procedure DoRemoveServiceData(const AServiceUUID: TBluetoothUUID); override;
procedure DoClearServiceData; override;
function ContainsServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; override;
function GetServiceUUIDs: TArray<TBluetoothUUID>; override;
function GetServiceData: TArray<TServiceDataRawData>; override;
function GetDataForService(const AServiceUUID: TBluetoothUUID): TBytes; override;
procedure SetLocalName(const ALocalName: string); override;
function GetLocalName: string; override;
procedure SetTxPowerLevel(ATxPowerLevel: Integer); override;
function GetTxPowerLevel: Integer; override;
procedure SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes); override;
function GetManufacturerSpecificData: TBytes; override;
public
constructor Create(const ADevice: System.Bluetooth.TBluetoothLEDevice);
end;
TWinRTBluetoothLEDevice = class;
TConnectionStatusChangeEventHandler = class(TInspectableObject,
TypedEventHandler_2__IBluetoothLEDevice__IInspectable_Delegate_Base,
TypedEventHandler_2__IBluetoothLEDevice__IInspectable)
private
[Weak] FDevice: TWinRTBluetoothLEDevice;
procedure Invoke(sender: IBluetoothLEDevice; args: IInspectable); safecall;
public
constructor Create(const ADevice: TWinRTBluetoothLEDevice);
end;
TWinRTBluetoothLEDevice = class(System.Bluetooth.TBluetoothLEDevice)
private
FClosed: Boolean;
FLEAdapter: TWinRTBluetoothLEAdapter;
FConnectionStatusChangeDelegate: TypedEventHandler_2__IBluetoothLEDevice__IInspectable;
procedure CheckInitialized;
procedure CheckNotClosed;
protected
FId: HSTRING;
FAddress: UInt64;
FBluetoothLEDevice: IBluetoothLEDevice;
FDeviceName: string;
FReliableWriteTransaction: GenericAttributeProfile_IGattReliableWriteTransaction;
function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; override;
function GetAddress: TBluetoothMacAddress; override;
function GetDeviceName: string; override;
function GetBluetoothType: TBluetoothType; override;
function GetIdentifier: string; override;
function GetIsConnected: Boolean; override;
procedure DoAbortReliableWrite; override;
function DoBeginReliableWrite: Boolean; override;
function DoExecuteReliableWrite: Boolean; override;
function DoDiscoverServices: Boolean; override;
function DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
function DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
function DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoReadRemoteRSSI: Boolean; override;
function DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; override;
procedure ConnectionStatusChanged;
function DoDisconnect: Boolean; override;
function DoConnect: Boolean; override;
procedure CloseServices;
procedure SetScanned(AScanned: Boolean);
function GetScanned: Boolean;
public
class function AddressFromId(const AId: HSTRING): Int64;
property Scanned: Boolean read GetScanned write SetScanned;
constructor Create(const AId: HSTRING; const ALEAdapter: TWinRTBluetoothLEAdapter; AutoConnect: Boolean); overload;
constructor Create(const AAddress: UInt64; const ALEAdapter: TWinRTBluetoothLEAdapter; AutoConnect: Boolean); overload;
destructor Destroy; override;
end;
TWinRTBluetoothGattServer = class(TBluetoothGattServer)
private
FAdvertismentPublisher: IBluetoothLEAdvertisementPublisher;
protected
{ Service Management }
function DoCreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override;
function DoCreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID;
AType: TBluetoothServiceType): TBluetoothGattService; override;
{ Characteristic Management }
function DoCreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID;
const AProps: TBluetoothPropertyFlags; const ADescription: string = ''): TBluetoothGattCharacteristic; override;
{ Descriptor Management }
function DoCreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; override;
function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; override;
{ Add the previously created Services and characteristics... }
function DoAddService(const AService: TBluetoothGattService): Boolean; override;
function DoAddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
function DoGetServices: TBluetoothGattServiceList; override;
procedure DoClose; override;
procedure DoClearServices; override;
procedure DoCharacteristicReadRequest(const ADevice: System.Bluetooth.TBluetoothLEDevice; ARequestId: Integer; AnOffset: Integer;
const AGattCharacteristic: TBluetoothGattCharacteristic); override;
procedure DoCharacteristicWriteRequest(const ADevice: System.Bluetooth.TBluetoothLEDevice; ARequestId: Integer;
const AGattCharacteristic: TBluetoothGattCharacteristic; APreparedWrite: Boolean; AResponseNeeded: Boolean;
AnOffset: Integer; const AValue: TBytes); override;
procedure DoUpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); override;
procedure DoServiceAdded(AStatus: TBluetoothGattStatus; const AService: TBluetoothGattService); override;
/// <summary> Advertises peripheral manager data </summary>
procedure DoStartAdvertising; override;
/// <summary> Stops advertising peripheral manager data </summary>
procedure DoStopAdvertising; override;
/// <summary> A Boolean value indicating whether the peripheral is currently advertising data </summary>
function DoIsAdvertising: Boolean; override;
public
constructor Create(const AManager: TBluetoothLEManager);
destructor Destroy; override;
end;
TWinRTBluetoothGattService = class(TBluetoothGattService)
private
FUUID: TGUID;
protected
[Weak] FDevice: TWinRTBluetoothLEDevice;
FGattService: GenericAttributeProfile_IGattDeviceService;
FType: TBluetoothServiceType;
function GetServiceUUID: TBluetoothUUID; override;
function GetServiceType: TBluetoothServiceType; override;
function DoGetCharacteristics: TBluetoothGattCharacteristicList; override;
function DoGetIncludedServices: TBluetoothGattServiceList; override;
function DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags;
const ADescription: string): TBluetoothGattCharacteristic; override;
function DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; override;
// Add the previously created Services and characteristics...
function DoAddIncludedService(const AService: TBluetoothGattService): Boolean; override;
function DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; override;
procedure CheckNotClosed;
procedure Close;
public
constructor Create(const ADevice: TWinRTBluetoothLEDevice; const AGattService: GenericAttributeProfile_IGattDeviceService;
AType: TBluetoothServiceType);
destructor Destroy; override;
end;
TWinRTBluetoothGattCharacteristic = class;
TGattValueChangedEventHandler = class(TInspectableObject,
TypedEventHandler_2__GenericAttributeProfile_IGattCharacteristic__GenericAttributeProfile_IGattValueChangedEventArgs_Delegate_Base,
TypedEventHandler_2__GenericAttributeProfile_IGattCharacteristic__GenericAttributeProfile_IGattValueChangedEventArgs)
private
[Weak] FGattCharacteristic: TWinRTBluetoothGattCharacteristic;
procedure Invoke(sender: GenericAttributeProfile_IGattCharacteristic; args: GenericAttributeProfile_IGattValueChangedEventArgs); safecall;
public
constructor Create(const AGattCharacteristic: TWinRTBluetoothGattCharacteristic);
end;
TWinRTBluetoothGattCharacteristic = class(TBluetoothGattCharacteristic)
private
FValue: TBytes;
FGattValueChanged: TypedEventHandler_2__GenericAttributeProfile_IGattCharacteristic__GenericAttributeProfile_IGattValueChangedEventArgs;
FGattValueChangedERT: EventRegistrationToken;
function UpdateValueFromDevice: TBluetoothGattStatus;
function SetValueToDevice: TBluetoothGattStatus;
protected
[Weak] FBluetoothGattService: TWinRTBluetoothGattService;
FGattCharacteristic: GenericAttributeProfile_IGattCharacteristic;
FValueChangeEventHandle: TBluetoothGattEventHandle;
function GetUUID: TBluetoothUUID; override;
function GetProperties: TBluetoothPropertyFlags; override;
function DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; override;
function DoGetDescriptors: TBluetoothGattDescriptorList; override;
function DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; override;
function DoGetValue: TBytes; override;
procedure DoSetValue(const AValue: TBytes); override;
procedure GattValueChangedEvent(const Args: GenericAttributeProfile_IGattValueChangedEventArgs);
function SetClientCharacteristicConfigurationDescriptor(
const ADescriptorValue: GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue): Boolean;
public
constructor Create(const AService: TWinRTBluetoothGattService; const AGattCharacteristic: GenericAttributeProfile_IGattCharacteristic);
destructor Destroy; override;
end;
TWinRTBluetoothGattDescriptor = class(TBluetoothGattDescriptor)
private
FValue: TBytes;
function UpdateValueFromDevice: TBluetoothGattStatus;
function SetValueToDevice: TBluetoothGattStatus;
protected
FGattDescriptor: GenericAttributeProfile_IGattDescriptor;
// Characteristic Extended Properties
function DoGetReliableWrite: Boolean; override;
function DoGetWritableAuxiliaries: Boolean; override;
// Characteristic User Description
function DoGetUserDescription: string; override;
procedure DoSetUserDescription(const Value: string); override;
// Client Characteristic Configuration
procedure DoSetNotification(const Value: Boolean); override;
function DoGetNotification: Boolean; override;
procedure DoSetIndication(const Value: Boolean); override;
function DoGetIndication: Boolean; override;
// Server Characteristic Configuration
function DoGetBroadcasts: Boolean; override;
procedure DoSetBroadcasts(const Value: Boolean); override;
//Characteristic Presentation Format
function DoGetFormat: TBluetoothGattFormatType; override;
function DoGetExponent: ShortInt; override;
function DoGetFormatUnit: TBluetoothUUID; override;
function DoGetValue: TBytes; override;
procedure DoSetValue(const AValue: TBytes); override;
function GetUUID: TBluetoothUUID; override;
public
constructor Create(const ACharacteristic: TWinRTBluetoothGattCharacteristic;
const AGattDescriptor: GenericAttributeProfile_IGattDescriptor);
end;
{Helper Functions}
function TBthLeUuidToUUID(const Uuid: TBthLeUuid): TBluetoothUUID; inline;
var
TempGuuid: TBluetoothUUID;
begin
if Uuid.IsShortUuid then
begin
TempGuuid := BTH_LE_ATT_BLUETOOTH_BASE_GUID;
Inc(TempGuuid.D1, Uuid.ShortUuid);
Result := TempGuuid;
end
else
Result := Uuid.LongUuid;
end;
function BLEUuidToString(Uuid: TBthLeUuid): string; inline;
begin
Result := TBthLeUuidToUUID(Uuid).ToString;
end;
function CheckOSVersionForGattClient: Boolean;
begin
Result := TOSVersion.Check(10);
end;
function CheckOSVersionForGattServer: Boolean;
begin
Result := TOSVersion.Check(10);
end;
function BthAddressToString(const AnAddress: TBluetoothAddress): string; inline;
begin
Result := Format(SBluetoothMACAddressFormat, [AnAddress.rgBytes[5], AnAddress.rgBytes[4],
AnAddress.rgBytes[3], AnAddress.rgBytes[2], AnAddress.rgBytes[1], AnAddress.rgBytes[0]]);
end;
function BytesFromIBuffer(const ABuffer: IBuffer): TBytes;
var
LReader: IDataReader;
LLength: Cardinal;
begin
LReader := TDataReader.Statics.FromBuffer(ABuffer);
LLength := LReader.UnconsumedBufferLength;
SetLength(Result, LLength);
if LLength > 0 then
LReader.ReadBytes(LLength, @Result[0]);
end;
function BytesToIBuffer(const ABytes: TBytes; AOffset: Integer = 0): IBuffer;
var
LWriter: IDataWriter;
LNumBytes: Integer;
begin
LWriter := TDataWriter.Create;
LNumBytes := Length(ABytes) - AOffset;
if LNumBytes > 0 then
LWriter.WriteBytes(LNumBytes, @ABytes[AOffset]);
Result := LWriter.DetachBuffer;
end;
{ TPlatformBluetoothLEManager }
class function TPlatformWinRTBluetoothLEManager.GetBluetoothManager: TBluetoothLEManager;
begin
Result := TWinRTBluetoothLEManager.Create;
end;
{ TWinBluetoothLEManager }
function TWinRTBluetoothLEManager.DoGetGattServer: TBluetoothGattServer;
begin
Result := TWinRTBluetoothGattServer.Create(Self);
end;
function TWinRTBluetoothLEManager.DoGetAdapter: TBluetoothLEAdapter;
begin
if not GetRadioAdapter then
FLEAdapter := nil;
Result := FLEAdapter;
end;
function TWinRTBluetoothLEManager.DoGetSupportsGattClient: Boolean;
begin
Result := CheckOSVersionForGattClient;
end;
function TWinRTBluetoothLEManager.DoGetSupportsGattServer: Boolean;
begin
Result := CheckOSVersionForGattServer;
end;
function TWinRTBluetoothLEManager.GetConnectionState: TBluetoothConnectionState;
begin
if GetRadioAdapter then
Result := TBluetoothConnectionState.Connected
else
Result := TBluetoothConnectionState.Disconnected;
end;
function TWinRTBluetoothLEManager.GetRadioAdapter: Boolean;
var
btfrp: TBlueToothFindRadioParams;
hRadio: THandle;
hFind: HBLUETOOTH_RADIO_FIND;
LRadioInfo: TBluetoothRadioInfo;
begin
FillChar(btfrp, SizeOf(btfrp), 0);
btfrp.dwSize := SizeOf(btfrp);
hFind := BluetoothFindFirstRadio(btfrp, hRadio);
if hFind <> 0 then
begin
Result := True;
if FLEAdapter = nil then
begin
LRadioInfo.dwSize := SizeOf(TBluetoothRadioInfo);
BluetoothGetRadioInfo(hRadio, LRadioInfo);
FLEAdapter := TWinRTBluetoothLEAdapter.Create(Self, LRadioInfo);
end;
BluetoothFindRadioClose(hFind);
end
else
Result := False;
end;
destructor TWinRTBluetoothLEManager.Destroy;
begin
if FLEAdapter <> nil then
begin
TWinRTBluetoothLEAdapter(FLEAdapter).StopDiscovery;
FLEAdapter.Free;
end;
inherited;
end;
function TWinRTBluetoothLEManager.DoEnableBluetooth: Boolean;
begin
Result := False;
end;
{ TWinRTBluetoothLEAdapter.TThreadTimer }
procedure TWinRTBluetoothLEAdapter.TDiscoverThreadTimer.Cancel;
begin
Terminate;
FEvent.SetEvent;
FOnTimer := nil;
end;
constructor TWinRTBluetoothLEAdapter.TDiscoverThreadTimer.Create(const AnAdapter: TBluetoothLEAdapter;
const AStopDiscoveryProc: TStopDiscoveryProc; Timeout: Cardinal);
begin
inherited Create(True);
FAdapter := AnAdapter;
FOnTimer := AStopDiscoveryProc;
FTimeout := Timeout;
FEvent := TEvent.Create;
end;
destructor TWinRTBluetoothLEAdapter.TDiscoverThreadTimer.Destroy;
begin
Cancel;
inherited;
FEvent.Free;
end;
procedure TWinRTBluetoothLEAdapter.TDiscoverThreadTimer.Execute;
begin
inherited;
FEvent.WaitFor(FTimeout);
if (not Terminated) and Assigned(FOnTimer) then
begin
try
FOnTimer;
except
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
end;
end;
end;
{ TWinBluetoothLEAdapter }
procedure TWinRTBluetoothLEAdapter.BLEAdvertisementReceived(const AAdvertisement: IBluetoothLEAdvertisement;
const AdvertisementType: BluetoothLEAdvertisementType; AAddress: UInt64; ARSSI: SmallInt;
const ATimestamp: DateTime);
var
LId: string;
LDevice: System.Bluetooth.TBluetoothLEDevice;
I: Integer;
LSection: IBluetoothLEAdvertisementDataSection;
LDataBytes: TBytes;
LNew: Boolean;
begin
LId := Format('%.12x', [AAddress]);
LNew := False;
LDevice := TWinRTBluetoothLEManager.GetDeviceInList(LId, FManager.AllDiscoveredDevices);
if LDevice = nil then
begin
LNew := True;
LDevice := TWinRTBluetoothLEDevice.Create(AAddress, Self, True);
end;
if AAdvertisement.DataSections.Size > 0 then
for I := 0 to AAdvertisement.DataSections.Size - 1 do
begin
LSection := AAdvertisement.DataSections.GetAt(I);
LDataBytes := BytesFromIBuffer(LSection.Data);
if LDevice.AdvertisedData = nil then
TWinRTBluetoothLEDevice(LDevice).FAdvertisedData := TScanResponse.Create;
LDevice.AdvertisedData.AddOrSetValue(TScanResponseKey(LSection.DataType), LDataBytes);
if AAdvertisement.LocalName <> 0 then
begin
TWinRTBluetoothLEDevice(LDevice).FDeviceName := AAdvertisement.LocalName.ToString;
TWinRTBluetoothLEAdvertiseData(LDevice.ScannedAdvertiseData).FLocalName := AAdvertisement.LocalName.ToString;
end;
end;
if AAdvertisement.ServiceUuids.Size > 0 then
for I := 0 to AAdvertisement.ServiceUuids.Size - 1 do
if not TWinRTBluetoothLEAdvertiseData(LDevice.ScannedAdvertiseData).FServiceUUIDs.Contains(AAdvertisement.ServiceUuids.GetAt(I)) then
TWinRTBluetoothLEAdvertiseData(LDevice.ScannedAdvertiseData).FServiceUUIDs.Add(AAdvertisement.ServiceUuids.GetAt(I));
DoDeviceDiscovered(LDevice, LNew, nil);
end;
constructor TWinRTBluetoothLEAdapter.Create(const AManager: TBluetoothLEManager; const ARadioInfo: TBluetoothRadioInfo);
begin
inherited Create(AManager);
FScannedLEDevices := TBluetoothLEDeviceDictionary.Create;
FRadioInfo := ARadioInfo;
FBLEAdvertisementReceivedDelegate := TBLEAdvertisementReceivedEventHandler.Create(Self);
FAdvertisementWatcher := TBluetoothLEAdvertisementWatcher.Create;
FBLEAdvertisementReceivedDelegateERT := FAdvertisementWatcher.add_Received(FBLEAdvertisementReceivedDelegate);
FAdvertisementWatcher.ScanningMode := BluetoothLEScanningMode.Active;
end;
destructor TWinRTBluetoothLEAdapter.Destroy;
begin
StopDiscovery;
if FBLEAdvertisementReceivedDelegateERT.Value <> 0 then
FAdvertisementWatcher.remove_Received(FBLEAdvertisementReceivedDelegateERT);
FBLEAdvertisementReceivedDelegate := nil;
FBluetoothLEScanFilterList.Free;
FScannedLEDevices.Free;
inherited;
end;
procedure TWinRTBluetoothLEAdapter.GetBLEPairedDevices;
var
LDeviceInformationCollectionAsyncOp: IAsyncOperation_1__IVectorView_1__IDeviceInformation;
LBLEDevicesFound: IVectorView_1__IDeviceInformation;
LWinBluetoothLEDevice: TWinRTBluetoothLEDevice;
I: Integer;
begin
for I := 0 to FManager.AllDiscoveredDevices.Count - 1 do
TWinRTBluetoothLEDevice(FManager.AllDiscoveredDevices[I]).FPaired := False;
if TAsyncOperation<IAsyncOperation_1__IVectorView_1__IDeviceInformation>.Wait(
TDeviceInformation.Statics.FindAllAsync(TBluetoothLEDevice.Statics.GetDeviceSelector),
LDeviceInformationCollectionAsyncOp) = AsyncStatus.Completed then
begin
LBLEDevicesFound := LDeviceInformationCollectionAsyncOp.GetResults;
if LBLEDevicesFound.Size > 0 then
for I := 0 to LBLEDevicesFound.Size - 1 do
begin
LWinBluetoothLEDevice := TWinRTBluetoothLEDevice(TWinRTBluetoothLEManager.GetDeviceInList
(Format('%.12x', [TWinRTBluetoothLEDevice.AddressFromId(LBLEDevicesFound.GetAt(I).Id)]), FManager.AllDiscoveredDevices));
if LWinBluetoothLEDevice = nil then
begin
LWinBluetoothLEDevice := TWinRTBluetoothLEDevice.Create(LBLEDevicesFound.GetAt(I).Id, Self, False);
LWinBluetoothLEDevice := TWinRTBluetoothLEDevice(TWinRTBluetoothLEManager.AddDeviceToList
(System.Bluetooth.TBluetoothLEDevice(LWinBluetoothLEDevice), FManager.AllDiscoveredDevices));
end;
LWinBluetoothLEDevice.FPaired := True;
end;
end;
end;
function TWinRTBluetoothLEAdapter.DoStartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean;
var
I: Integer;
begin
GetBLEPairedDevices;
FScannedLEDevices.Clear;
FBluetoothLEScanFilterList := ABluetoothLEScanFilterList;
FAdvertisementWatcher.AdvertisementFilter.Advertisement.ServiceUuids.Clear;
if AFilterUUIDList <> nil then
for I := 0 to AFilterUUIDList.Count - 1 do
FAdvertisementWatcher.AdvertisementFilter.Advertisement.ServiceUuids.Append(AFilterUUIDList[I]);
FAdvertisementWatcher.Start;
FTimerThread := TDiscoverThreadTimer.Create(Self, DoCancelDiscovery, Timeout);
FTimerThread.Start;
Result := True;
end;
function TWinRTBluetoothLEAdapter.DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList;
Refresh: Boolean): Boolean;
begin
FScannedLEDevices.Clear;
FBluetoothLEScanFilterList := ABluetoothLEScanFilterList;
FAdvertisementWatcher.Start;
Result := True;
end;
function TWinRTBluetoothLEAdapter.GetAdapterName: string;
begin
Result := FRadioInfo.szName;
end;
function TWinRTBluetoothLEAdapter.GetAddress: System.Bluetooth.TBluetoothMacAddress;
var
LAddress: TBluetoothAddress;
begin
Result := '00:00:00:00:00:00'; // Do not translate
LAddress := FRadioInfo.address;
if LAddress.ullLong <> BLUETOOTH_NULL_ADDRESS.ullLong then
Result := BthAddressToString(LAddress);
end;
function TWinRTBluetoothLEAdapter.GetScanMode: TBluetoothScanMode;
begin
Result := Default(TBluetoothScanMode);
end;
function TWinRTBluetoothLEAdapter.GetState: TBluetoothAdapterState;
begin
Result := Default(TBluetoothAdapterState);
end;
procedure TWinRTBluetoothLEAdapter.SetAdapterName(const Value: string);
begin
raise EBluetoothAdapterException.Create(SBluetoothNotImplemented);
end;
procedure TWinRTBluetoothLEAdapter.StopDiscovery;
begin
if FAdvertisementWatcher.Status = BluetoothLEAdvertisementWatcherStatus.Started then
begin
FAdvertisementWatcher.Stop;
if FTimerThread <> nil then
begin
FTimerThread.Free;
FTimerThread := nil;
end;
end;
end;
procedure TWinRTBluetoothLEAdapter.DoCancelDiscovery;
begin
StopDiscovery;
DoDiscoveryEnd(Self, nil);
end;
procedure TWinRTBluetoothLEAdapter.DoDeviceDiscovered(
const ADevice: System.Bluetooth.TBluetoothLEDevice; ANewDevice: Boolean;
const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList);
var
LDiscovered: Boolean;
begin
LDiscovered := True;
if (not ADevice.Scanned) then
begin
if (FBluetoothLEScanFilterList <> nil) then
LDiscovered := DoDeviceOvercomesFilters(ADevice, FBluetoothLEScanFilterList);
if ANewDevice then
TWinRTBluetoothLEManager.AddDeviceToList(ADevice, FManager.AllDiscoveredDevices);
if LDiscovered then
begin
//if TWinRTBluetoothLEDevice(ADevice).Paired then // Need to be thought
TWinRTBluetoothLEManager.AddDeviceToList(ADevice, FManager.LastDiscoveredDevices);
TWinRTBluetoothLEDevice(ADevice).Scanned := True;
end;
end;
if LDiscovered then
DoDiscoverDevice(Self, ADevice, ADevice.LastRSSI, ADevice.AdvertisedData);
end;
procedure TWinRTBluetoothLEAdapter.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList);
begin
inherited DoDiscoveryEnd(Sender, nil);
end;
{ TWinBluetoothGattClient }
procedure TWinRTBluetoothLEDevice.CheckNotClosed;
begin
if FClosed then
raise EBluetoothServiceException.Create(SBluetoothLEDeviceDisconnectedExplicity);
end;
procedure TWinRTBluetoothLEDevice.CloseServices;
var
LService: TBluetoothGattService;
begin
for LService in FServices do
(LService as TWinRTBluetoothGattService).Close;
end;
procedure TWinRTBluetoothLEDevice.ConnectionStatusChanged;
var
LConnected: Boolean;
begin
LConnected := GetIsConnected;
if LConnected and Assigned(OnConnect) then
OnConnect(Self)
else
if (not LConnected) and Assigned(OnDisconnect) then
OnDisconnect(Self);
end;
constructor TWinRTBluetoothLEDevice.Create(const AAddress: UInt64; const ALEAdapter: TWinRTBluetoothLEAdapter;
AutoConnect: Boolean);
begin
inherited Create(AutoConnect);
FAddress := AAddress;
FLEAdapter := ALEAdapter;
end;
constructor TWinRTBluetoothLEDevice.Create(const AId: HSTRING; const ALEAdapter: TWinRTBluetoothLEAdapter;
AutoConnect: Boolean);
begin
inherited Create(AutoConnect);
FId := AId;
FAddress := AddressFromId(AId);
FLEAdapter := ALEAdapter;
end;
destructor TWinRTBluetoothLEDevice.Destroy;
begin
FReliableWriteTransaction := nil;
DoDisconnect;
inherited;
end;
procedure TWinRTBluetoothLEDevice.DoAbortReliableWrite;
begin
FReliableWriteTransaction := nil;
end;
function TWinRTBluetoothLEDevice.DoBeginReliableWrite: Boolean;
begin
FReliableWriteTransaction := TGenericAttributeProfile_GattReliableWriteTransaction.Create;
Result := True;
end;
function TWinRTBluetoothLEDevice.DoDiscoverServices: Boolean;
var
I: Integer;
LGattService: GenericAttributeProfile_IGattDeviceService;
begin
Result := True;
FServices.Clear;
CheckInitialized;
if FBluetoothLEDevice.GattServices.Size > 0 then
for I := 0 to FBluetoothLEDevice.GattServices.Size - 1 do
begin
LGattService := FBluetoothLEDevice.GattServices.GetAt(I);
FServices.Add(TWinRTBluetoothGattService.Create(Self, LGattService, TBluetoothServiceType.Primary));
end;
DoOnServicesDiscovered(Self, FServices);
end;
function TWinRTBluetoothLEDevice.DoExecuteReliableWrite: Boolean;
var
LWriteValueAsync: IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus;
begin
CheckNotClosed;
if FReliableWriteTransaction <> nil then
begin
if TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus>.Wait(
FReliableWriteTransaction.CommitAsync, LWriteValueAsync) = AsyncStatus.Completed then
Result := LWriteValueAsync.GetResults = GenericAttributeProfile_GattCommunicationStatus.Success
else
Result := False;
FReliableWriteTransaction := nil;
end
else
Result := False;
end;
function TWinRTBluetoothLEDevice.DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
CheckNotClosed;
TThread.CreateAnonymousThread(procedure
begin
DoOnCharacteristicRead(ACharacteristic, TWinRTBluetoothGattCharacteristic(ACharacteristic).UpdateValueFromDevice);
end).Start;
Result := True;
end;
function TWinRTBluetoothLEDevice.DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
CheckNotClosed;
TThread.CreateAnonymousThread(procedure
begin
DoOnDescriptorRead(ADescriptor, TWinRTBluetoothGattDescriptor(ADescriptor).UpdateValueFromDevice);
end).Start;
Result := True;
end;
function TWinRTBluetoothLEDevice.DoReadRemoteRSSI: Boolean;
begin
{ Not supported on windows }
Result := False;
end;
function TWinRTBluetoothLEDevice.DoConnect: Boolean;
begin
{ Not supported on windows }
Result := False;
end;
function TWinRTBluetoothLEDevice.DoCreateAdvertiseData: TBluetoothLEAdvertiseData;
begin
Result := TWinRTBluetoothLEAdvertiseData.Create(Self);
end;
function TWinRTBluetoothLEDevice.DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic;
Enable: Boolean): Boolean;
var
LDescriptorValue: GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue;
begin
CheckNotClosed;
if TBluetoothProperty.Notify in ACharacteristic.Properties then
LDescriptorValue := GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue.Notify
else
if TBluetoothProperty.Indicate in ACharacteristic.Properties then
LDescriptorValue := GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue.Indicate
else
Exit(False);
if not Enable then
LDescriptorValue := GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue.None;
Result := TWinRTBluetoothGattCharacteristic(ACharacteristic).SetClientCharacteristicConfigurationDescriptor(LDescriptorValue);
end;
function TWinRTBluetoothLEDevice.DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
CheckNotClosed;
TThread.CreateAnonymousThread(procedure
begin
DoOnCharacteristicWrite(ACharacteristic, TWinRTBluetoothGattCharacteristic(ACharacteristic).SetValueToDevice);
end).Start;
Result := True;
end;
function TWinRTBluetoothLEDevice.DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
CheckNotClosed;
TThread.CreateAnonymousThread(procedure
begin
DoOnDescriptorWrite(ADescriptor, TWinRTBluetoothGattDescriptor(ADescriptor).SetValueToDevice);
end).Start;
Result := True;
end;
function TWinRTBluetoothLEDevice.GetAddress: TBluetoothMacAddress;
begin
Result := Format('%.12x', [FAddress]).ToUpper;
Result.Insert(2,':');
Result.Insert(5,':');
Result.Insert(8,':');
Result.Insert(11,':');
Result.Insert(14,':');
end;
function TWinRTBluetoothLEDevice.GetBluetoothType: TBluetoothType;
begin
Result := TBluetoothType.LE;
end;
function TWinRTBluetoothLEDevice.GetDeviceName: string;
begin
Result := FDeviceName;
end;
function TWinRTBluetoothLEDevice.GetIdentifier: string;
begin
Result := Format('%.12x', [FAddress]);
end;
function TWinRTBluetoothLEDevice.GetIsConnected: Boolean;
begin
if FBluetoothLEDevice <> nil then
Result := FBluetoothLEDevice.ConnectionStatus = BluetoothConnectionStatus.Connected
else
Result := False;
end;
function TWinRTBluetoothLEDevice.GetScanned: Boolean;
begin
Result := FScanned;
end;
procedure TWinRTBluetoothLEDevice.SetScanned(AScanned: Boolean);
begin
FScanned := AScanned;
end;
class function TWinRTBluetoothLEDevice.AddressFromId(const AId: HSTRING): Int64;
var
LTemp: string;
LDevPos: Integer;
begin
LTemp := AId.ToString;
LDevPos := LTemp.ToUpper.IndexOf('#DEV_'); // Do not translate
if LDevPos <> -1 then
LTemp := LTemp.Substring(LDevPos + 5, 12)
else
LTemp := ReplaceStr(RightStr(LTemp, 17), ':', '');
Result := StrToInt64('$' + LTemp);
end;
procedure TWinRTBluetoothLEDevice.CheckInitialized;
var
LBLEDeviceAsyncOp: IAsyncOperation_1__IBluetoothLEDevice;
begin
if (FBluetoothLEDevice = nil) or FClosed then
begin
if FId = 0 then
raise EBluetoothDeviceException.Create(SBluetoothLEDeviceNotPaired);
if TAsyncOperation<IAsyncOperation_1__IBluetoothLEDevice>.Wait(
TBluetoothLEDevice.Statics.FromIdAsync(FId), LBLEDeviceAsyncOp) = AsyncStatus.Completed then
begin
FBluetoothLEDevice := LBLEDeviceAsyncOp.GetResults;
FClosed := False;
if DeviceName = '' then
FDeviceName := FBluetoothLEDevice.Name.ToString;
FConnectionStatusChangeDelegate := TConnectionStatusChangeEventHandler.Create(Self);
FBluetoothLEDevice.add_ConnectionStatusChanged(FConnectionStatusChangeDelegate);
end;
end;
end;
function TWinRTBluetoothLEDevice.DoDisconnect: Boolean;
var
LBLEClosable: IClosable;
begin
if (not FClosed) and (FBluetoothLEDevice <> nil) and (FBluetoothLEDevice.QueryInterface(IClosable, LBLEClosable) = 0) then
begin
CloseServices;
LBLEClosable.Close;
FClosed := True;
Result := True;
end
else
Result := False;
end;
{ TWinBluetoothGattCharacteristic }
constructor TWinRTBluetoothGattCharacteristic.Create(const AService: TWinRTBluetoothGattService;
const AGattCharacteristic: GenericAttributeProfile_IGattCharacteristic);
begin
inherited Create(AService);
FBluetoothGattService := AService;
FGattCharacteristic := AGattCharacteristic;
if (TBluetoothProperty.Notify in Properties) or (TBluetoothProperty.Indicate in Properties) then
FGattValueChanged := TGattValueChangedEventHandler.Create(Self);
end;
destructor TWinRTBluetoothGattCharacteristic.Destroy;
begin
if FGattValueChangedERT.Value <> 0 then
FGattCharacteristic.remove_ValueChanged(FGattValueChangedERT);
inherited;
end;
function TWinRTBluetoothGattCharacteristic.DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean;
begin
Result := False;
end;
function TWinRTBluetoothGattCharacteristic.DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor;
begin
raise EBluetoothLECharacteristicException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattCharacteristic.DoGetDescriptors: TBluetoothGattDescriptorList;
var
LGattDescriptors: IVectorView_1__GenericAttributeProfile_IGattDescriptor;
I: Integer;
begin
FDescriptors.Clear;
LGattDescriptors := (FGattCharacteristic as GenericAttributeProfile_IGattCharacteristic2).GetAllDescriptors;
if LGattDescriptors.Size > 0 then
for I := 0 to LGattDescriptors.Size - 1 do
FDescriptors.Add(TWinRTBluetoothGattDescriptor.Create(Self, LGattDescriptors.GetAt(I)));
Result := FDescriptors;
end;
function TWinRTBluetoothGattCharacteristic.DoGetValue: TBytes;
begin
Result := FValue;
end;
procedure TWinRTBluetoothGattCharacteristic.DoSetValue(const AValue: TBytes);
begin
FValue := AValue;
end;
procedure TWinRTBluetoothGattCharacteristic.GattValueChangedEvent(const Args: GenericAttributeProfile_IGattValueChangedEventArgs);
begin
FValue := BytesFromIBuffer(Args.CharacteristicValue);
TWinRTBluetoothGattService(FService).FDevice.DoOnCharacteristicRead(Self, TBluetoothGattStatus.Success);
end;
function TWinRTBluetoothGattCharacteristic.GetProperties: TBluetoothPropertyFlags;
function HasProperty(const Props: GenericAttributeProfile_GattCharacteristicProperties;
const AProperty: GenericAttributeProfile_GattCharacteristicProperties): Boolean;
begin
Result := (Ord(Props) and Ord(AProperty) = Ord(AProperty));
end;
var
LProps: GenericAttributeProfile_GattCharacteristicProperties;
begin
Result := [];
LProps := FGattCharacteristic.CharacteristicProperties;
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.Broadcast) then
Include(Result, TBluetoothProperty.Broadcast);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.Read) then
Include(Result, TBluetoothProperty.Read);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.Write) then
Include(Result, TBluetoothProperty.Write);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.WriteWithoutResponse) then
Include(Result, TBluetoothProperty.WriteNoResponse);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.AuthenticatedSignedWrites) then
Include(Result, TBluetoothProperty.SignedWrite);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.Notify) then
Include(Result, TBluetoothProperty.Notify);
if HasProperty(LProps, GenericAttributeProfile_GattCharacteristicProperties.Indicate) then
Include(Result, TBluetoothProperty.Indicate);
end;
function TWinRTBluetoothGattCharacteristic.GetUUID: TBluetoothUUID;
begin
Result := FGattCharacteristic.Uuid;
end;
function TWinRTBluetoothGattCharacteristic.SetClientCharacteristicConfigurationDescriptor(
const ADescriptorValue: GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue): Boolean;
var
LWriteDescValueAsync: IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus;
begin
Result := False;
if ADescriptorValue = GenericAttributeProfile_GattClientCharacteristicConfigurationDescriptorValue.None then
begin
if FGattValueChangedERT.Value <> 0 then
begin
FGattCharacteristic.remove_ValueChanged(FGattValueChangedERT);
FGattValueChangedERT.Value := 0;
end;
end
else
if (TBluetoothProperty.Notify in Properties) or (TBluetoothProperty.Indicate in Properties) then
begin
if FGattValueChangedERT.Value <> 0 then
FGattCharacteristic.remove_ValueChanged(FGattValueChangedERT);
FGattValueChangedERT := FGattCharacteristic.add_ValueChanged(FGattValueChanged);
end;
if TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus>.Wait(
FGattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(ADescriptorValue),
LWriteDescValueAsync) = AsyncStatus.Completed then
Result := LWriteDescValueAsync.GetResults = GenericAttributeProfile_GattCommunicationStatus.Success;
end;
function TWinRTBluetoothGattCharacteristic.SetValueToDevice: TBluetoothGattStatus;
var
LWriteValueAsync: IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus;
LWriteOption: GenericAttributeProfile_GattWriteOption;
begin
Result := TBluetoothGattStatus.Failure;
if FBluetoothGattService.FDevice.FReliableWriteTransaction <> nil then
begin
FBluetoothGattService.FDevice.FReliableWriteTransaction.WriteValue(FGattCharacteristic, BytesToIBuffer(FValue));
Result := TBluetoothGattStatus.Success;
end
else
begin
if TBluetoothProperty.WriteNoResponse in Properties then
LWriteOption := GenericAttributeProfile_GattWriteOption.WriteWithoutResponse
else
LWriteOption := GenericAttributeProfile_GattWriteOption.WriteWithResponse;
if TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus>.Wait(
FGattCharacteristic.WriteValueAsync(BytesToIBuffer(FValue), LWriteOption),
LWriteValueAsync) = AsyncStatus.Completed then
if LWriteValueAsync.GetResults = GenericAttributeProfile_GattCommunicationStatus.Success then
Result := TBluetoothGattStatus.Success;
end;
end;
function TWinRTBluetoothGattCharacteristic.UpdateValueFromDevice: TBluetoothGattStatus;
var
LGattReadValueAsyncOp: IAsyncOperation_1__GenericAttributeProfile_IGattReadResult;
LReadResult: GenericAttributeProfile_IGattReadResult;
begin
Result := TBluetoothGattStatus.Failure;
if TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_IGattReadResult>.Wait(
FGattCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached),
LGattReadValueAsyncOp) = AsyncStatus.Completed then
begin
LReadResult := LGattReadValueAsyncOp.GetResults;
if LReadResult.Status = GenericAttributeProfile_GattCommunicationStatus.Success then
begin
FValue := BytesFromIBuffer(LReadResult.Value);
Result := TBluetoothGattStatus.Success;
end;
end;
end;
{ TWinBluetoothGattService }
procedure TWinRTBluetoothGattService.CheckNotClosed;
begin
if FDevice.FClosed then
raise EBluetoothServiceException.Create(SBluetoothLEDeviceDisconnectedExplicity);
end;
procedure TWinRTBluetoothGattService.Close;
var
LGattServiceClosable: IClosable;
begin
if (FGattService <> nil) and (FGattService.QueryInterface(IClosable, LGattServiceClosable) = 0) then
begin
LGattServiceClosable.Close;
FGattService := nil;
end;
end;
constructor TWinRTBluetoothGattService.Create(const ADevice: TWinRTBluetoothLEDevice;
const AGattService: GenericAttributeProfile_IGattDeviceService; AType: TBluetoothServiceType);
begin
inherited Create(TGUID.Empty, AType);
FDevice := ADevice;
FGattService := AGattService;
FUUID := FGattService.Uuid;
FType := AType;
end;
destructor TWinRTBluetoothGattService.Destroy;
begin
Close;
inherited;
end;
function TWinRTBluetoothGattService.DoGetCharacteristics: TBluetoothGattCharacteristicList;
var
I: Integer;
LGattCharacteristics: IVectorView_1__GenericAttributeProfile_IGattCharacteristic;
begin
CheckNotClosed;
FCharacteristics.Clear;
LGattCharacteristics := (FGattService as GenericAttributeProfile_IGattDeviceService2).GetAllCharacteristics;
if LGattCharacteristics.Size > 0 then
for I := 0 to LGattCharacteristics.Size - 1 do
FCharacteristics.Add(TWinRTBluetoothGattCharacteristic.Create(Self, LGattCharacteristics.GetAt(I)));
Result := FCharacteristics;
end;
function TWinRTBluetoothGattService.DoGetIncludedServices: TBluetoothGattServiceList;
var
I: Integer;
LGattServices: IVectorView_1__GenericAttributeProfile_IGattDeviceService;
begin
CheckNotClosed;
FIncludedServices.Clear;
LGattServices := (FGattService as GenericAttributeProfile_IGattDeviceService2).GetAllIncludedServices;
if LGattServices.Size > 0 then
for I := 0 to LGattServices.Size - 1 do
FIncludedServices.Add(TWinRTBluetoothGattService.Create(FDevice, LGattServices.GetAt(I), TBluetoothServiceType.Primary));
Result := FIncludedServices;
end;
function TWinRTBluetoothGattService.DoAddIncludedService(const AService: TBluetoothGattService): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
function TWinRTBluetoothGattService.DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
function TWinRTBluetoothGattService.DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags;
const ADescription: string): TBluetoothGattCharacteristic;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattService.DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattService.GetServiceType: TBluetoothServiceType;
begin
Result := FType;
end;
function TWinRTBluetoothGattService.GetServiceUUID: TBluetoothUUID;
begin
Result := FUUID;
end;
{ TWinBluetoothGattDescriptor }
constructor TWinRTBluetoothGattDescriptor.Create(const ACharacteristic: TWinRTBluetoothGattCharacteristic;
const AGattDescriptor: GenericAttributeProfile_IGattDescriptor);
begin
inherited Create(ACharacteristic);
FGattDescriptor := AGattDescriptor;
end;
function TWinRTBluetoothGattDescriptor.DoGetBroadcasts: Boolean;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.ServerCharacteristicConfiguration then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := TBluetoothProperty.Broadcast in FCharacteristic.Properties;
end;
function TWinRTBluetoothGattDescriptor.DoGetExponent: ShortInt;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicPresentationFormat then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := ShortInt(Value[1]);
end;
function TWinRTBluetoothGattDescriptor.DoGetFormat: TBluetoothGattFormatType;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicPresentationFormat then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := TBluetoothGattFormatType(Value[0]);
end;
function TWinRTBluetoothGattDescriptor.DoGetFormatUnit: TBluetoothUUID;
var
LValue: Word;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicPresentationFormat then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
if Length(FValue) < 4 then
LValue := 0
else
LValue := FValue[2] or (FValue[3] shl 8);
Result := System.Bluetooth.TBluetoothUUIDHelper.GetBluetoothUUID(LValue);
end;
function TWinRTBluetoothGattDescriptor.DoGetIndication: Boolean;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.ClientCharacteristicConfiguration then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := TBluetoothProperty.Indicate in FCharacteristic.Properties;
end;
function TWinRTBluetoothGattDescriptor.DoGetNotification: Boolean;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.ClientCharacteristicConfiguration then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := TBluetoothProperty.Notify in FCharacteristic.Properties;
end;
function TWinRTBluetoothGattDescriptor.DoGetReliableWrite: Boolean;
const
LProp = GenericAttributeProfile_GattCharacteristicProperties.ReliableWrites;
var
LProps: GenericAttributeProfile_GattCharacteristicProperties;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicExtendedProperties then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
LProps := TWinRTBluetoothGattCharacteristic(FCharacteristic).FGattCharacteristic.CharacteristicProperties;
Result := Ord(LProps) and Ord(LProp) = Ord(LProp);
end;
function TWinRTBluetoothGattDescriptor.DoGetUserDescription: string;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicUserDescription then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
Result := TEncoding.Unicode.GetString(FValue);
end;
function TWinRTBluetoothGattDescriptor.DoGetValue: TBytes;
begin
Result := FValue;
end;
function TWinRTBluetoothGattDescriptor.DoGetWritableAuxiliaries: Boolean;
const
LProp = GenericAttributeProfile_GattCharacteristicProperties.ReliableWrites;
var
LProps: GenericAttributeProfile_GattCharacteristicProperties;
begin
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicExtendedProperties then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
LProps := TWinRTBluetoothGattCharacteristic(FCharacteristic).FGattCharacteristic.CharacteristicProperties;
Result := Ord(LProps) and Ord(LProp) = Ord(LProp);
end;
procedure TWinRTBluetoothGattDescriptor.DoSetBroadcasts(const Value: Boolean);
var
B: TBytes;
begin
if not (TBluetoothProperty.Broadcast in FCharacteristic.Properties) then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
if Value then
B := [$01, $00]
else
B := [$00, $00];
SetValue(B);
end;
procedure TWinRTBluetoothGattDescriptor.DoSetIndication(const Value: Boolean);
var
B: TBytes;
begin
inherited;
if not (TBluetoothProperty.Indicate in FCharacteristic.Properties) then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
if Value then
B := [$02, $00]
else
B := [$00, $00];
SetValue(B);
end;
procedure TWinRTBluetoothGattDescriptor.DoSetNotification(const Value: Boolean);
var
B: TBytes;
begin
inherited;
if not (TBluetoothProperty.Notify in FCharacteristic.Properties) then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
if Value then
B := [$01, $00]
else
B := [$00, $00];
SetValue(B);
end;
procedure TWinRTBluetoothGattDescriptor.DoSetUserDescription(const Value: string);
begin
inherited;
if UUID <> TGenericAttributeProfile_GattDescriptorUuids.Statics.CharacteristicUserDescription then
raise EBluetoothLEDescriptorException.Create(SBluetoothDescriptorTypeError);
DoSetValue(TEncoding.Unicode.GetBytes(Value));
end;
procedure TWinRTBluetoothGattDescriptor.DoSetValue(const AValue: TBytes);
begin
FValue := AValue;
end;
function TWinRTBluetoothGattDescriptor.GetUUID: TBluetoothUUID;
begin
Result := FGattDescriptor.Uuid;
end;
function TWinRTBluetoothGattDescriptor.SetValueToDevice: TBluetoothGattStatus;
var
LWriteValueAsync: IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus;
begin
Result := TBluetoothGattStatus.Failure;
if (TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_GattCommunicationStatus>.Wait(
FGattDescriptor.WriteValueAsync(BytesToIBuffer(FValue)), LWriteValueAsync) = AsyncStatus.Completed) and
(LWriteValueAsync.GetResults = GenericAttributeProfile_GattCommunicationStatus.Success) then
Result := TBluetoothGattStatus.Success;
end;
function TWinRTBluetoothGattDescriptor.UpdateValueFromDevice: TBluetoothGattStatus;
var
LGattReadValueAsyncOp: IAsyncOperation_1__GenericAttributeProfile_IGattReadResult;
LReadResult: GenericAttributeProfile_IGattReadResult;
begin
Result := TBluetoothGattStatus.Success;
if TAsyncOperation<IAsyncOperation_1__GenericAttributeProfile_IGattReadResult>.Wait(
FGattDescriptor.ReadValueAsync(BluetoothCacheMode.Uncached),
LGattReadValueAsyncOp) = AsyncStatus.Completed then
begin
LReadResult := LGattReadValueAsyncOp.GetResults;
if LReadResult.Status = GenericAttributeProfile_GattCommunicationStatus.Success then
FValue := BytesFromIBuffer(LReadResult.Value)
else
Result := TBluetoothGattStatus.Failure;
end;
end;
{ TConnectionStatusChangeEventHandler }
constructor TConnectionStatusChangeEventHandler.Create(const ADevice: TWinRTBluetoothLEDevice);
begin
inherited Create;
FDevice := ADevice;
end;
procedure TConnectionStatusChangeEventHandler.Invoke(sender: IBluetoothLEDevice; args: IInspectable);
begin
FDevice.ConnectionStatusChanged;
end;
{ TGattValueChangedEventHandler }
constructor TGattValueChangedEventHandler.Create(const AGattCharacteristic: TWinRTBluetoothGattCharacteristic);
begin
inherited Create;
FGattCharacteristic := AGattCharacteristic;
end;
procedure TGattValueChangedEventHandler.Invoke(sender: GenericAttributeProfile_IGattCharacteristic;
args: GenericAttributeProfile_IGattValueChangedEventArgs);
begin
FGattCharacteristic.GattValueChangedEvent(args);
end;
{ TAsyncOperation }
class function TAsyncOperation<T>.Wait(const AAsyncOp: T; var AsyncOpResult: T; ATimeout: Cardinal): AsyncStatus;
var
LAsyncInfo: IAsyncInfo;
LTimer: TThreadTimer;
begin
if AAsyncOp.QueryInterface(IAsyncInfo, LAsyncInfo) <> 0 then
raise Exception.Create(SNoAsyncInfo);
LTimer := TThreadTimer.Create(
procedure
begin
LAsyncInfo.Cancel;
end,
ATimeout);
LTimer.Start;
while LAsyncInfo.Status = AsyncStatus.Started do
TThread.Yield;
LTimer.Free;
AsyncOpResult := AAsyncOp;
Result := LAsyncInfo.Status;
end;
{ TAsyncOperation.TThreadTimer }
procedure TAsyncOperation<T>.TThreadTimer.Cancel;
begin
Terminate;
FEvent.SetEvent;
FOnTimer := nil;
end;
constructor TAsyncOperation<T>.TThreadTimer.Create(const ACancelProc: TCancelProcedure; Timeout: Cardinal);
begin
inherited Create(True);
FOnTimer := ACancelProc;
FTimeout := Timeout;
FEvent := TEvent.Create;
end;
destructor TAsyncOperation<T>.TThreadTimer.Destroy;
begin
Cancel;
FEvent.Free;
inherited;
end;
procedure TAsyncOperation<T>.TThreadTimer.Execute;
begin
inherited;
FEvent.WaitFor(FTimeout);
if not Terminated and Assigned(FOnTimer) then
FOnTimer;
end;
{ TBLEAdvertisementReceivedEventHandler }
constructor TBLEAdvertisementReceivedEventHandler.Create(const AAdapter: TWinRTBluetoothLEAdapter);
begin
inherited Create;
FAdapter := AAdapter;
end;
procedure TBLEAdvertisementReceivedEventHandler.Invoke(sender: IBluetoothLEAdvertisementWatcher;
args: IBluetoothLEAdvertisementReceivedEventArgs);
begin
FAdapter.BLEAdvertisementReceived(args.Advertisement, args.AdvertisementType, args.BluetoothAddress,
args.RawSignalStrengthInDBm, args.Timestamp);
end;
{ TWinRTBluetoothLEAdvertiseData }
function TWinRTBluetoothLEAdvertiseData.ContainsServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean;
begin
Result := FServiceUUIDs.Contains(AServiceUUID);
end;
constructor TWinRTBluetoothLEAdvertiseData.Create(const ADevice: System.Bluetooth.TBluetoothLEDevice);
begin
inherited Create;
FDevice := ADevice;
end;
function TWinRTBluetoothLEAdvertiseData.DoAddServiceData(const AServiceUUID: TBluetoothUUID;
const AData: TBytes): Boolean;
begin
// Not supported in Windows
Result := False;
end;
function TWinRTBluetoothLEAdvertiseData.DoAddServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean;
begin
// Not supported in Windows
Result := False;
end;
procedure TWinRTBluetoothLEAdvertiseData.DoClearServiceData;
begin
inherited;
// Not supported in Windows
end;
procedure TWinRTBluetoothLEAdvertiseData.DoClearServiceUUIDs;
begin
inherited;
// Not supported in Windows
end;
procedure TWinRTBluetoothLEAdvertiseData.DoRemoveServiceData(const AServiceUUID: TBluetoothUUID);
begin
inherited;
// Not supported in Windows
end;
procedure TWinRTBluetoothLEAdvertiseData.DoRemoveServiceUUID(const AServiceUUID: TBluetoothUUID);
begin
inherited;
// Not supported in Windows
end;
function TWinRTBluetoothLEAdvertiseData.GetDataForService(const AServiceUUID: TBluetoothUUID): TBytes;
begin
if Length(GetServiceData) > 0 then
FServiceData.TryGetValue(AServiceUUID, Result)
else
Result := nil;
end;
function TWinRTBluetoothLEAdvertiseData.GetLocalName: string;
begin
Result := FLocalName;
end;
function TWinRTBluetoothLEAdvertiseData.GetManufacturerSpecificData: TBytes;
begin
if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then
if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.ManufacturerSpecificData) then
FManufacturerSpecificData := FDevice.AdvertisedData.Items[TScanResponseKey.ManufacturerSpecificData];
Result := FManufacturerSpecificData;
end;
function TWinRTBluetoothLEAdvertiseData.GetServiceData: TArray<TServiceDataRawData>;
var
LData: TBytes;
LServiceTBytes: TBytes;
LServiceUUID: TGUID;
LSize: Integer;
LServiceData: TPair<TBluetoothUUID,TBytes>;
begin
if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then
if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.ServiceData) then
begin
LData := FDevice.AdvertisedData.Items[TScanResponseKey.ServiceData];
LServiceUUID := System.Bluetooth.TBluetoothUUIDHelper.GetBluetoothUUID(PWord(@LData[0])^);
LSize := Length(LData) - 2;
SetLength(LServiceTBytes, LSize);
Move(LData[2], LServiceTBytes[0], LSize);
FServiceData.AddOrSetValue(LServiceUUID, LServiceTBytes);
end;
// Prepared to be an array, but it will just own one element for now.
SetLength(Result, FServiceData.count);
LSize := 0;
for LServiceData in FServiceData do
begin
Result[LSize].create(LServiceData);;
Inc(LSize);
end;
end;
function TWinRTBluetoothLEAdvertiseData.GetServiceUUIDs: TArray<TBluetoothUUID>;
begin
Result := FServiceUUIDs.ToArray;
end;
function TWinRTBluetoothLEAdvertiseData.GetTxPowerLevel: Integer;
begin
if (FDevice <> nil) and (FDevice.AdvertisedData <> nil) then
if FDevice.AdvertisedData.ContainsKey(TScanResponseKey.TxPowerLevel) then
FTxPowerLevel := ShortInt(FDevice.AdvertisedData.Items[TScanResponseKey.TxPowerLevel]);
Result := FTxPowerLevel;
end;
procedure TWinRTBluetoothLEAdvertiseData.SetLocalName(const ALocalName: string);
begin
inherited;
// Not supported in Windows
end;
procedure TWinRTBluetoothLEAdvertiseData.SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes);
begin
inherited;
FManufacturerSpecificData := AManufacturerSpecificData;
end;
procedure TWinRTBluetoothLEAdvertiseData.SetTxPowerLevel(ATxPowerLevel: Integer);
begin
inherited;
// Not supported in Windows
end;
{ TWinRTBluetoothGattServer }
constructor TWinRTBluetoothGattServer.Create(const AManager: TBluetoothLEManager);
begin
inherited;
FAdvertismentPublisher := TBluetoothLEAdvertisementPublisher.Create;
end;
destructor TWinRTBluetoothGattServer.Destroy;
begin
if IsAdvertising then
StopAdvertising;
inherited;
end;
function TWinRTBluetoothGattServer.DoAddCharacteristic(const AService: TBluetoothGattService;
const ACharacteristic: TBluetoothGattCharacteristic): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
function TWinRTBluetoothGattServer.DoAddService(const AService: TBluetoothGattService): Boolean;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := False;
end;
procedure TWinRTBluetoothGattServer.DoClearServices;
begin
inherited;
// Not implemented
end;
procedure TWinRTBluetoothGattServer.DoClose;
begin
inherited;
// Not implemented
end;
function TWinRTBluetoothGattServer.DoCreateAdvertiseData: TBluetoothLEAdvertiseData;
begin
Result := TWinRTBluetoothLEAdvertiseData.Create(nil);
end;
function TWinRTBluetoothGattServer.DoCreateCharacteristic(const AService: TBluetoothGattService;
const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags;
const ADescription: string): TBluetoothGattCharacteristic;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattServer.DoCreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic;
const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattServer.DoCreateIncludedService(const AService: TBluetoothGattService;
const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattServer.DoCreateService(const AnUUID: TBluetoothUUID;
AType: TBluetoothServiceType): TBluetoothGattService;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattServer.DoGetServices: TBluetoothGattServiceList;
begin
raise EBluetoothServiceException.Create(SBluetoothNotImplemented);
Result := nil;
end;
function TWinRTBluetoothGattServer.DoIsAdvertising: Boolean;
begin
Result := FAdvertismentPublisher.Status = BluetoothLEAdvertisementPublisherStatus.Started
end;
procedure TWinRTBluetoothGattServer.DoCharacteristicReadRequest(const ADevice: System.Bluetooth.TBluetoothLEDevice; ARequestId: Integer;
AnOffset: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic);
begin
// Not implemented
end;
procedure TWinRTBluetoothGattServer.DoCharacteristicWriteRequest(const ADevice: System.Bluetooth.TBluetoothLEDevice; ARequestId: Integer;
const AGattCharacteristic: TBluetoothGattCharacteristic; APreparedWrite: Boolean; AResponseNeeded: Boolean;
AnOffset: Integer; const AValue: TBytes);
begin
// Not implemented
end;
procedure TWinRTBluetoothGattServer.DoUpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic);
begin
// Not implemented
end;
procedure TWinRTBluetoothGattServer.DoServiceAdded(AStatus: TBluetoothGattStatus; const AService: TBluetoothGattService);
begin
// Not implemented
end;
procedure TWinRTBluetoothGattServer.DoStartAdvertising;
var
LManufacturerData: IBluetoothLEManufacturerData;
LRawManufacturerData: TBytes;
LCompanyID: Word;
begin
inherited;
if IsAdvertising then
StopAdvertising;
LRawManufacturerData := AdvertiseData.ManufacturerSpecificData;
FAdvertismentPublisher.Advertisement.ManufacturerData.Clear;
if Length(LRawManufacturerData) >= 2 then
begin
LManufacturerData := TBluetoothLEManufacturerData.Create;
Move(LRawManufacturerData[0], LCompanyId, SizeOf(Word));
LManufacturerData.CompanyId := LCompanyID;
if Length(LRawManufacturerData) >= 3 then
LManufacturerData.Data := BytesToIBuffer(LRawManufacturerData, 2);
FAdvertismentPublisher.Advertisement.ManufacturerData.Append(LManufacturerData);
FAdvertismentPublisher.Start;
end
else
raise EBluetoothLEAdvertiseDataException.Create(SBluetoothLEAdvertisementEmpty);
end;
procedure TWinRTBluetoothGattServer.DoStopAdvertising;
begin
if IsAdvertising then
FAdvertismentPublisher.Stop;
end;
end.
|
unit Initializer.SSDLabelListRefresh;
interface
uses
Classes, Forms, SysUtils, Generics.Collections, Windows, ShellAPI,
Global.LanguageString, OS.EnvironmentVariable, Form.Alert,
Device.PhysicalDrive, Getter.PhysicalDrive.ListChange, Component.SSDLabel,
Component.SSDLabel.List;
type
TSSDLabelListRefresher = class
private
SSDLabel: TSSDLabelList;
ChangesList: TChangesList;
procedure AddByAddedList;
procedure AddDevice(const Entry: IPhysicalDrive);
procedure AlertAndExecuteNewDiagnosisInstance;
procedure DeleteAndAddDevicesByResultList;
procedure DeleteByDeletedList;
procedure DeleteDevice(const Path: String);
procedure FreeChangesList;
function ChangeExists: Boolean;
function IsNoSupportedDriveExists: Boolean;
procedure RefreshMainFormAndSetNewSelection;
procedure SetChangesList;
procedure SetFirstDeviceAsSelected;
procedure SetFirstDeviceAsSelectedIfNoDeviceSelected;
public
procedure RefreshDrives(const SSDLabelToRefresh: TSSDLabelList);
end;
implementation
uses Form.Main;
type
THackMainform = TForm;
procedure TSSDLabelListRefresher.AlertAndExecuteNewDiagnosisInstance;
begin
AlertCreate(fMain, AlrtNoSupport[CurrLang]);
ShellExecute(0, 'open',
PChar(EnvironmentVariable.AppPath + 'SSDTools.exe'),
PChar('/diag'), nil, SW_SHOW);
end;
procedure TSSDLabelListRefresher.FreeChangesList;
begin
FreeAndNil(ChangesList.Added);
FreeAndNil(ChangesList.Deleted);
end;
procedure TSSDLabelListRefresher.SetChangesList;
var
ListChangeGetter: TListChangeGetter;
begin
ListChangeGetter := TListChangeGetter.Create;
ListChangeGetter.IsOnlyGetSupportedDrives := true;
ChangesList :=
ListChangeGetter.RefreshListWithResultFrom(fMain.IdentifiedDriveList);
FreeAndNil(ListChangeGetter);
end;
function TSSDLabelListRefresher.IsNoSupportedDriveExists: Boolean;
begin
result := fMain.IdentifiedDriveList.Count = 0;
end;
procedure TSSDLabelListRefresher.DeleteAndAddDevicesByResultList;
begin
DeleteByDeletedList;
AddByAddedList;
end;
procedure TSSDLabelListRefresher.DeleteByDeletedList;
var
CurrentEntry: String;
begin
for CurrentEntry in ChangesList.Deleted do
DeleteDevice(CurrentEntry);
end;
procedure TSSDLabelListRefresher.AddByAddedList;
var
CurrentEntry: IPhysicalDrive;
begin
for CurrentEntry in ChangesList.Added do
AddDevice(CurrentEntry);
end;
procedure TSSDLabelListRefresher.DeleteDevice(const Path: String);
begin
if not SSDLabel.IsExistsByPath(Path) then
exit;
SSDLabel.Delete(SSDLabel.IndexOfByPath(Path));
end;
procedure TSSDLabelListRefresher.AddDevice(const Entry: IPhysicalDrive);
begin
SSDLabel.Add(TSSDLabel.Create(Entry));
end;
function TSSDLabelListRefresher.ChangeExists: Boolean;
begin
result :=
(ChangesList.Added.Count > 0) or
(ChangesList.Deleted.Count > 0);
end;
procedure TSSDLabelListRefresher.SetFirstDeviceAsSelected;
begin
SSDLabel[0].OnClick(SSDLabel[0]);
end;
procedure TSSDLabelListRefresher.SetFirstDeviceAsSelectedIfNoDeviceSelected;
begin
if ChangeExists then
SetFirstDeviceAsSelected;
end;
procedure TSSDLabelListRefresher.RefreshMainFormAndSetNewSelection;
begin
DeleteAndAddDevicesByResultList;
SetFirstDeviceAsSelectedIfNoDeviceSelected;
end;
procedure TSSDLabelListRefresher.RefreshDrives(
const SSDLabelToRefresh: TSSDLabelList);
begin
SSDLabel := SSDLabelToRefresh;
SetChangesList;
if IsNoSupportedDriveExists then
AlertAndExecuteNewDiagnosisInstance
else
RefreshMainFormAndSetNewSelection;
FreeChangesList;
end;
end.
|
unit SingleFPBenchmark2Unit;
interface
uses Windows, BenchmarkClassUnit, Classes, Math;
type
TSingleFPThreads2 = class(TFastcodeMMBenchmark)
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses SysUtils;
type
TSingleFPThread2 = class(TThread)
FBenchmark: TFastcodeMMBenchmark;
procedure Execute; override;
end;
TRegtangularComplexS = packed record
RealPart, ImaginaryPart : Single;
end;
//Loading some Single values
procedure TestFunction(var Res : TRegtangularComplexS; const X, Y : TRegtangularComplexS);
begin
Res.RealPart := X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart
+ X.RealPart + Y.RealPart;
Res.ImaginaryPart := X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart
+ X.ImaginaryPart + Y.ImaginaryPart;
end;
procedure TSingleFPThread2.Execute;
var
I1, I2, I5: Integer;
Src1Array1 : array of TRegtangularComplexS;
Src2Array1 : array of TRegtangularComplexS;
ResultArray1 : array of TRegtangularComplexS;
BenchArraySize, PrevArraySize : Integer;
const
MINBENCHARRAYSIZE : Integer = 1000;
MAXBENCHARRAYSIZE : Integer = 100000;
ARRAYSIZEINCREMENT = 1000;
NOOFRUNS : Integer = 20;
begin
PrevArraySize := 0;
BenchArraySize := MINBENCHARRAYSIZE;
while BenchArraySize < MAXBENCHARRAYSIZE do
begin
SetLength(Src1Array1, BenchArraySize);
SetLength(Src2Array1, BenchArraySize);
SetLength(ResultArray1, BenchArraySize);
FBenchmark.UpdateUsageStatistics;
//Fill source arrays
for I1 := PrevArraySize to BenchArraySize-1 do
begin
Src1Array1[I1].RealPart := 1;
Src1Array1[I1].ImaginaryPart := 1;
Src2Array1[I1].RealPart := 1;
Src2Array1[I1].ImaginaryPart := 1;
end;
//This is the real botleneck and the performance we want to measure
for I2 := 0 to NOOFRUNS do
begin
for I5 := 0 to BenchArraySize-1 do
begin
TestFunction(ResultArray1[I5], Src1Array1[I5], Src2Array1[I5]);
end;
end;
PrevArraySize := BenchArraySize;
inc(BenchArraySize, ARRAYSIZEINCREMENT);
end;
end;
class function TSingleFPThreads2.GetBenchmarkDescription: string;
begin
Result := 'A benchmark that tests access to Single FP variables '
+ 'in a dynamic array. '
+ 'Reveals set associativity related issues.'
+ 'Benchmark submitted by Dennis Kjaer Christensen.';
end;
class function TSingleFPThreads2.GetBenchmarkName: string;
begin
Result := 'Single Variables Access 3 arrays at a time';
end;
class function TSingleFPThreads2.GetCategory: TBenchmarkCategory;
begin
Result := bmMemoryAccessSpeed;
end;
class function TSingleFPThreads2.GetSpeedWeight: Double;
begin
Result := 0.9;
end;
procedure TSingleFPThreads2.RunBenchmark;
var
SingleFPThread : TSingleFPThread2;
begin
inherited;
SingleFPThread := TSingleFPThread2.Create(True);
SingleFPThread.FreeOnTerminate := False;
SingleFPThread.FBenchmark := Self;
SingleFPThread.Resume;
SingleFPThread.WaitFor;
SingleFPThread.Free;
end;
end. |
program SplitEnv;
uses
SysUtils;
const
MAX_SIZE = 1024;
END_OF_STRING = CHR(0);
type
String1024 = array [1..MAX_SIZE] of Char; (* Terminated by chr 0 in FreePascal *)
StringArray = array [1..MAX_SIZE] of String1024; (* Terminated by an empty string *)
var
path : String1024;
i : Integer;
function split(toSplit:String1024; splittor:Char; var parts:StringArray) : Integer;
(* Find character "c" in string "s" and return the index of "c". *)
function find(s:String1024; c:Char; startIndex:Integer) : Integer;
var
i:Integer;
found:Boolean;
foundAtIndex:Integer;
begin
i := startIndex;
found := false;
foundAtIndex := -1;
while (s[i] <> END_OF_STRING) and (not found) do begin
if s[i] = c then begin
found := true;
foundAtIndex = i;
end
end;
find := foundAtIndex;
end; (* find *)
var
partCount:Integer;
i:Integer;
begin
i := 0;
partCount := 0;
split := 0;
i := find(toSplit, splittor, 1);
while i > 0 do begin
end;
end; (* split *)
(* Main program below *)
begin
path := GetEnvironmentVariable('PATH');
writeln(path);
for i := 1 to MAX_SIZE do begin
writeln(path[i], ' = ', ord(path[i]));
end;
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.10
* @Brief:
* @References: Introduction to Algorithms, Second Edition
*}
unit org.algorithms.tree;
interface
uses
WinApi.Windows,
org.algorithms
{$IfDef TEST_ALGORITHMS}
, Vcl.Graphics;
{$Else}
;
{$ENDIF}
type
TRBColor = (rbRed, rbBlack);
TAVLFactor = -2..2;
TTreeType = (tBinary, tRedBlack, tTreap, tAVL);
PNodeParameter = ^TNodeParameter;
TNodeParameter = record
case TTreeType of
tRedBlack: (Color: TRBColor);
tTreap: (Priority: Integer);
tAVL: (Factor: TAVLFactor);
end;
TNode<TKey, TValue> = class
private
FKey: TKey;
FValue: TValue;
FParent: TNode<TKey, TValue>;
FLeft: TNode<TKey, TValue>;
FRight: TNode<TKey, TValue>;
FSentinel: Boolean;
FParameter: PNodeParameter;
FKeyNotify: TValueNotify<TKey>;
FValueNotify: TValueNotify<TValue>;
public
{$IfDef TEST_ALGORITHMS}
Index: Integer;
Layer: Integer;
X: Double;
Y: Double;
{$ENDIF}
public
constructor Create(AKey: TKey; AValue: TValue);
destructor Destroy; override;
property Key: TKey read FKey;
property Value: TValue read FValue;
property OnKeyNotify: TValueNotify<TKey> read FKeyNotify write FKeyNotify;
property OnValueNotify: TValueNotify<TValue> read FValueNotify write FValueNotify;
end;
//遍历树时用于指定对结点的操作,如打印、删除等
TNodeMethod<TKey, TValue> = procedure (Node: TNode<TKey, TValue>) of object;
TBinaryTree<TKey, TValue> = class
private
FRoot: TNode<TKey, TValue>;
FCount: Integer;
FHeight: Integer;
//
FKeyCompare: TValueCompare<TKey>;
FKeyNotify: TValueNotify<TKey>;
FValueNotify: TValueNotify<TValue>;
// 动态获取树高
function GetHeight: Integer;
// 释放结点
procedure FreeNode(Node: TNode<TKey, TValue>);
//{$IfDef TEST_ALGORITHMS}
public
//{$Endif}
// 判读结点是否为岗哨
class function IsSentinel(Node: TNode<TKey, TValue>): Boolean;
// 查找某子树中最小的Key对应的结点
function Minimum(SubRoot: TNode<TKey, TValue>): TNode<TKey, TValue>;
// 查找某子树中最大的Key对应的结点
function Maximum(SubRoot: TNode<TKey, TValue>): TNode<TKey, TValue>;
// 查找某结点的后序
function Successor(Node: TNode<TKey, TValue>): TNode<TKey, TValue>;
// 查找某结点的前序
function Predecessor(Node: TNode<TKey, TValue>): TNode<TKey, TValue>;
// 获取某子树的树高
function GetSubHeight(SubRoot: TNode<TKey, TValue>): Integer;
// 中序遍历某子树
// @Root 子树
// @Routine 处理例程
procedure InOrder(SubRoot: TNode<TKey, TValue>; Routine: TNodeMethod<TKey, TValue>);
// 后序遍历某子树
procedure PostOrder(SubRoot: TNode<TKey, TValue>; Routine: TNodeMethod<TKey, TValue>);
// 前序遍历某子树
procedure PreOrder(SubRoot: TNode<TKey, TValue>; Routine: TNodeMethod<TKey, TValue>);
protected
// 拼接
procedure Transplant(u, v: TNode<TKey, TValue>);
// 左旋
procedure LeftRotate(Node: TNode<TKey, TValue>);
// 右旋
procedure RightRotate(Node: TNode<TKey, TValue>);
public
destructor Destroy(); override;
// 查找在某子树中指定Key对应的结点
function Search(SubRoot: TNode<TKey, TValue>; const AKey: TKey): TNode<TKey, TValue>; overload;
function Search(const AKey: TKey): TNode<TKey, TValue>; overload;
// 向树中插入结点
procedure Insert(AKey: TKey; AValue: TValue); overload;
procedure Insert(Node: TNode<TKey, TValue>); overload; virtual;
// 从树中删除结点
procedure Delete(Node: TNode<TKey, TValue>); virtual;
//
property Root: TNode<TKey, TValue> read FRoot;
property Count: Integer read FCount;
property Height: Integer read GetHeight;
property OnKeyCompare: TValueCompare<TKey> read FKeyCompare Write FKeyCompare;
property OnKeyNotify: TValueNotify<TKey> read FKeyNotify write FKeyNotify;
property OnValueNotify: TValueNotify<TValue> read FValueNotify write FValueNotify;
{$IfDef TEST_ALGORITHMS}
procedure RefreshCoordinate(Node: TNode<TKey, TValue>);
{$ENDIF}
end;
TRBTree<TKey, TValue> = class(TBinaryTree<TKey, TValue>)
private
FSentinel: TNode<TKey, TValue>;
procedure InsertFixup(Node: TNode<TKey, TValue>);
procedure DeleteFixup(Node: TNode<TKey, TValue>);
public
constructor Create;
destructor Destroy; override;
procedure Insert(Node: TNode<TKey, TValue>); override;
procedure Delete(Node: TNode<TKey, TValue>); override;
end;
TTreapTree<TKey, TValue> = class(TBinaryTree<TKey, TValue>)
private
FSentinel: TNode<TKey, TValue>;
public
constructor Create;
destructor Destroy; override;
procedure Insert(Node: TNode<TKey, TValue>); override;
procedure Delete(Node: TNode<TKey, TValue>); override;
end;
TAVLTree<TKey, TValue> = class(TBinaryTree<TKey, TValue>)
private
procedure InsertBalance(Node: TNode<TKey, TValue>);
procedure DeleteBalance(Node: TNode<TKey, TValue>);
public
procedure Insert(Node: TNode<TKey, TValue>); override;
procedure Delete(Node: TNode<TKey, TValue>); override;
end;
{$IfDef TEST_ALGORITHMS}
function GetX(TreeHeight, Layer, Index: Integer): Double;
procedure DrawTree(Root: TNode<Integer, Integer>; Canvas: TCanvas;
Left, Top: Integer; XStep, YStep: Double; TreeType: TTreeType = tBinary);
{$ENDIF}
const
TREE_TYPE_DESC: array [TTreeType] of string = (
'二叉树',
'红黑树',
'随机树',
'平衡树'
);
implementation
{$IfDef TEST_ALGORITHMS}
uses
System.SysUtils,
System.Math;
{$ENDIF}
{ TBinaryTree<TKey, TValue> }
procedure TBinaryTree<TKey, TValue>.Delete(Node: TNode<TKey, TValue>);
var
Y: TNode<TKey, TValue>;
begin
if IsSentinel(Node.FLeft) then
Transplant(Node, Node.FRight)
else if IsSentinel(Node.FRight) then
Transplant(Node, Node.FLeft)
else begin
Y := Minimum(Node.FRight);
if Y.FParent <> Node then begin
Transplant(Y, Y.FRight);
Y.FRight := Node.FRight;
Y.FRight.FParent := Y;
end;
Transplant(Node, Y);
Y.FLeft := Node.FLeft;
Y.FLeft.FParent := Y;
end;
FHeight := -1; // 树高需重新计算
Dec(FCount);
end;
destructor TBinaryTree<TKey, TValue>.Destroy;
begin
PostOrder(FRoot, FreeNode);
inherited;
end;
procedure TBinaryTree<TKey, TValue>.FreeNode(
Node: TNode<TKey, TValue>);
begin
if Assigned(FKeyNotify) then
FKeyNotify(Node.Key, atDelete);
if Assigned(FValueNotify) then
FValueNotify(Node.Value, atDelete);
Node.Free();
end;
function TBinaryTree<TKey, TValue>.GetSubHeight(
SubRoot: TNode<TKey, TValue>): Integer;
var
LeftHeight, RightHeight: Integer;
begin
if IsSentinel(SubRoot) then
Result := 0
else begin
LeftHeight := 0;
if not IsSentinel(SubRoot.FLeft) then
LeftHeight := GetSubHeight(SubRoot.FLeft);
RightHeight := 0;
if not IsSentinel(SubRoot.FRight) then
RightHeight := GetSubHeight(SubRoot.FRight);
if LeftHeight > RightHeight then
Result := LeftHeight + 1
else
Result := RightHeight + 1;
end;
end;
function TBinaryTree<TKey, TValue>.GetHeight: Integer;
begin
if FHeight = -1 then
FHeight := GetSubHeight(FRoot);
Result := FHeight;
end;
procedure TBinaryTree<TKey, TValue>.InOrder(
SubRoot: TNode<TKey, TValue>;
Routine: TNodeMethod<TKey, TValue>);
begin
if not IsSentinel(SubRoot) then begin
if not IsSentinel(SubRoot.FLeft) then
InOrder(SubRoot.FLeft, Routine);
Routine(SubRoot);
if not IsSentinel(SubRoot.FRight) then
InOrder(SubRoot.FRight, Routine);
end;
end;
procedure TBinaryTree<TKey, TValue>.Insert(AKey: TKey; AValue: TValue);
var
Node: TNode<TKey, TValue>;
begin
Node := TNode<TKey,TValue>.Create(AKey, AValue);
Insert(Node);
end;
procedure TBinaryTree<TKey, TValue>.Insert(Node: TNode<TKey, TValue>);
var
Parent: TNode<TKey, TValue>;
Tmp: TNode<TKey, TValue>;
begin
Node.OnKeyNotify := FKeyNotify;
Node.OnValueNotify := FValueNotify;
Parent := FRoot;
Tmp := FRoot;
while not IsSentinel(Tmp) do begin
Parent := Tmp;
if FKeyCompare(Node.FKey, Tmp.FKey) < 0 then
Tmp := Tmp.FLeft
else
Tmp := Tmp.FRight;
end;
Node.FParent := Parent;
if IsSentinel(Parent) then
FRoot := Node
else if FKeyCompare(Node.FKey, Parent.FKey) < 0 then
Parent.FLeft := Node
else
Parent.FRight := Node;
FHeight := -1; // 需重新计算树高
Inc(FCount);
end;
class function TBinaryTree<TKey, TValue>.IsSentinel(
Node: TNode<TKey, TValue>): Boolean;
begin
Result := False;
if (Node = nil) or Node.FSentinel then
Result := True;
end;
procedure TBinaryTree<TKey, TValue>.LeftRotate(Node: TNode<TKey, TValue>);
var
Y: TNode<TKey, TValue>;
begin
Y := Node.FRight;
Node.FRight := Y.FLeft;
if not IsSentinel(Y.FLeft) then
Y.FLeft.FParent := Node;
Y.FParent := Node.FParent;
if IsSentinel(Node.FParent) then
FRoot := Y
else if Node = Node.FParent.FLeft then
Node.FParent.FLeft := Y
else
Node.FParent.FRight := Y;
Y.FLeft := Node;
Node.FParent := Y;
end;
function TBinaryTree<TKey, TValue>.Maximum(
SubRoot: TNode<TKey, TValue>): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
if not IsSentinel(SubRoot) then begin
Tmp := SubRoot;
while not IsSentinel(Tmp.FRight) do begin
Tmp := Tmp.FRight
end;
Result := Tmp;
end;
end;
function TBinaryTree<TKey, TValue>.Minimum(
SubRoot: TNode<TKey, TValue>): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
if not IsSentinel(SubRoot) then begin
Tmp := SubRoot;
while not IsSentinel(Tmp.FLeft) do begin
Tmp := Tmp.FLeft
end;
Result := Tmp;
end;
end;
procedure TBinaryTree<TKey, TValue>.PostOrder(
SubRoot: TNode<TKey, TValue>;
Routine: TNodeMethod<TKey, TValue>);
begin
if not IsSentinel(SubRoot) then begin
if not IsSentinel(SubRoot.FLeft) then
PostOrder(SubRoot.FLeft, Routine);
if not IsSentinel(SubRoot.FRight) then
PostOrder(SubRoot.FRight, Routine);
Routine(SubRoot);
end;
end;
function TBinaryTree<TKey, TValue>.Predecessor(
Node: TNode<TKey, TValue>): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
if not IsSentinel(Node.FLeft) then
Result := Maximum(Node.FLeft)
else begin
Tmp := Node;
while not IsSentinel(Tmp.FParent) and (Tmp = Tmp.FParent.FLeft) do
Tmp := Tmp.FParent;
if not IsSentinel(Tmp.FParent) then
Result := Tmp.FParent;
end;
end;
procedure TBinaryTree<TKey, TValue>.PreOrder(
SubRoot: TNode<TKey, TValue>;
Routine: TNodeMethod<TKey, TValue>);
begin
if not IsSentinel(SubRoot) then begin
Routine(SubRoot);
if not IsSentinel(SubRoot.FLeft) then
PreOrder(SubRoot.FLeft, Routine);
if not IsSentinel(SubRoot.FRight) then
PreOrder(SubRoot.FRight, Routine);
end;
end;
{$IfDef TEST_ALGORITHMS}
function GetX(TreeHeight, Layer, Index: Integer): Double;
begin
if Layer = TreeHeight - 1 then
Result := Index
else
Result := (GetX(TreeHeight, Layer + 1, 2 * Index) + GetX(TreeHeight, Layer + 1, 2 * Index + 1)) / 2;
end;
{$Endif}
{$IfDef TEST_ALGORITHMS}
procedure TBinaryTree<TKey, TValue>.RefreshCoordinate(
Node: TNode<TKey, TValue>);
begin
if not IsSentinel(Node) then begin
if IsSentinel(Node.FParent) then begin
Node.Layer := 0;
Node.Index := 0;
end
else begin
Node.Layer := Node.FParent.Layer + 1;
if Node = Node.FParent.FLeft then
Node.Index := 2 * Node.FParent.Index
else
Node.Index := 2 * Node.FParent.Index + 1;
end;
RefreshCoordinate(Node.FLeft);
RefreshCoordinate(Node.FRight);
Node.Y := Node.Layer;
if IsSentinel(Node.FLeft) and IsSentinel(Node.FRight) then begin
if Node.Layer = Height - 1 then begin
Node.X := Node.Index;
end
else begin
Node.X := GetX(Height, Node.Layer + 1, 2 * Node.Index) + GetX(Height, Node.Layer + 1, 2 * Node.Index + 1);
Node.X := Node.X / 2;
end;
end
else if IsSentinel(Node.FLeft) then begin
Node.X := GetX(Height, Node.Layer + 1, 2 * Node.Index) + Node.FRight.X;
Node.X := Node.X / 2;
end
else if IsSentinel(Node.FRight) then begin
Node.X := Node.FLeft.X + GetX(Height, Node.Layer + 1, 2 * Node.Index + 1);
Node.X := Node.X / 2;
end
else begin
Node.X := (Node.FLeft.X + Node.FRight.X) / 2;
end;
end;
end;
{$Endif}
procedure TBinaryTree<TKey, TValue>.RightRotate(
Node: TNode<TKey, TValue>);
var
X: TNode<TKey, TValue>;
begin
X := Node.FLeft;
Node.FLeft := X.FRight;
if not IsSentinel(X.FRight) then
X.FRight.FParent := Node;
X.FParent := Node.FParent;
if IsSentinel(Node.FParent) then
FRoot := X
else if Node = Node.FParent.FLeft then
Node.FParent.FLeft := X
else
Node.FParent.FRight := X;
X.FRight := Node;
Node.FParent := X;
end;
function TBinaryTree<TKey, TValue>.Search(SubRoot: TNode<TKey, TValue>;
const AKey: TKey): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
Tmp := SubRoot;
while not IsSentinel(Tmp) and (FKeyCompare(AKey, Tmp.FKey) <> 0) do begin
if FKeyCompare(AKey, Tmp.FKey) < 0 then
Tmp := Tmp.FLeft
else
Tmp := Tmp.FRight;
end;
if not IsSentinel(Tmp) then
Result := Tmp;
end;
function TBinaryTree<TKey, TValue>.Search(const AKey: TKey): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
Tmp := FRoot;
while not IsSentinel(Tmp) and (FKeyCompare(AKey, Tmp.FKey) <> 0) do begin
if FKeyCompare(AKey, Tmp.FKey) < 0 then
Tmp := Tmp.FLeft
else
Tmp := Tmp.FRight;
end;
if not IsSentinel(Tmp) then
Result := Tmp;
end;
function TBinaryTree<TKey, TValue>.Successor(
Node: TNode<TKey, TValue>): TNode<TKey, TValue>;
var
Tmp: TNode<TKey, TValue>;
begin
Result := nil;
if not IsSentinel(Node.FRight) then
Result := Minimum(Node.FRight)
else begin
Tmp := Node;
while not IsSentinel(Tmp.FParent) and (Tmp = Tmp.FParent.FRight) do
Tmp := Tmp.FParent;
if not IsSentinel(Tmp.FParent) then
Result := Tmp.FParent;
end;
end;
procedure TBinaryTree<TKey, TValue>.Transplant(u, v: TNode<TKey, TValue>);
begin
if IsSentinel(u.FParent) then
FRoot := v
else if u = u.FParent.FLeft then
u.FParent.FLeft := v
else
u.FParent.FRight := v;
if v <> nil then
v.FParent := u.FParent;
end;
{$IfDef TEST_ALGORITHMS}
procedure DrawTree(Root: TNode<Integer, Integer>; Canvas: TCanvas;
Left, Top: Integer; XStep, YStep: Double; TreeType: TTreeType);
var
X0, Y0, X1, Y1, X2, Y2, X, Y: Integer;
Text: string;
TextWidth, TextHeight: Integer;
TextOffsetX, TextOffSetY: Integer;
begin
if not TBinaryTree<Integer, Integer>.IsSentinel(Root) then begin
X := Floor(Root.X * XStep) + Left;
Y := Floor(Root.Y * YStep) + Top;
// 绘制父结点
if not TBinaryTree<Integer, Integer>.IsSentinel(Root.FParent) then begin
X0 := Floor(Root.FParent.X * XStep) + Left;
Y0 := Floor(Root.FParent.Y * YStep) + Top;
Canvas.MoveTo(X0, Y0);
Canvas.LineTo(X, Y);
Text := Format('%d', [Root.FParent.FKey]);
TextHeight := Canvas.TextHeight(Text);
TextWidth := Canvas.TextWidth(Text);
TextOffsetX := TextWidth div 2;
TextOffSetY := TextHeight div 2;
if TextWidth < TextHeight then
TextWidth := TextHeight;
X1 := X0 - TextWidth;
X2 := X0 + TextWidth;
Y1 := Y0 - TextHeight;
Y2 := Y0 + TextHeight;
if TreeType = tRedBlack then begin
if Root.FParent.FParameter^.Color = rbRed then
Canvas.Brush.Color := clRed
else
Canvas.Brush.Color := clGray;
end;
Canvas.Ellipse(X1, Y1, X2, Y2);
Canvas.TextOut(X0 - TextOffsetX, Y0 - TextOffSetY, Text);
end;
// 绘制左子树
DrawTree(Root.FLeft, Canvas, Left, Top, XStep, YStep, TreeType);
// 绘制右子树
DrawTree(Root.FRight, Canvas, Left, Top, XStep, YStep, TreeType);
if TBinaryTree<Integer, Integer>.IsSentinel(Root.FLeft) and
TBinaryTree<Integer, Integer>.IsSentinel(Root.FRight) then begin
Text := Format('%d', [Root.FKey]);
TextHeight := Canvas.TextHeight(Text);
TextWidth := Canvas.TextWidth(Text);
TextOffsetX := TextWidth div 2;
TextOffSetY := TextHeight div 2;
if TextWidth < TextHeight then
TextWidth := TextHeight;
X1 := X - TextWidth;
X2 := X + TextWidth;
Y1 := Y - TextHeight;
Y2 := Y + TextHeight;
if TreeType = tRedBlack then begin
if Root.FParameter^.Color = rbRed then
Canvas.Brush.Color := clRed
else
Canvas.Brush.Color := clGray;
end;
Canvas.Ellipse(X1, Y1, X2, Y2);
Canvas.TextOut(X - TextOffsetX, Y - TextOffSetY, Text);
end;
end;
end;
{$Endif}
{ TNode<TKey, TValue> }
constructor TNode<TKey, TValue>.Create(AKey: TKey; AValue: TValue);
begin
FKey := AKey;
FValue := AValue;
FParent := nil;
FLeft := nil;
FRight := nil;
FSentinel := False;
New(FParameter);
end;
destructor TNode<TKey, TValue>.Destroy;
begin
if Assigned(FKeyNotify) then
FKeyNotify(Fkey, atDelete);
if Assigned(FValueNotify) then
FValueNotify(FValue, atDelete);
Dispose(FParameter);
inherited;
end;
{ TRBTree<TKey, TValue> }
constructor TRBTree<TKey, TValue>.Create;
begin
inherited Create;
FSentinel := TNode<TKey, TValue>.Create(Default(TKey), Default(TValue));
FSentinel.FSentinel := True;
FSentinel.FParameter^.Color := rbBlack;
FRoot := FSentinel;
end;
procedure TRBTree<TKey, TValue>.Delete(Node: TNode<TKey, TValue>);
var
X, Y, Z: TNode<TKey, TValue>;
YOriginalColor: TRBColor;
begin
Z := Node;
Y := Z;
YOriginalColor := Y.FParameter^.Color;
if IsSentinel(Z.FLeft) then begin
X := Z.FRight;
Transplant(Z, Z.FRight);
end
else if IsSentinel(Z.FRight) then begin
X := Z.FLeft;
Transplant(Z, Z.FLeft);
end
else begin
Y := Minimum(Z.FRight);
YOriginalColor := Y.FParameter^.Color;
X := Y.FRight;
if Y.FParent = Z then
X.FParent := Y
else begin
Transplant(Y, Y.FRight);
Y.FRight := Z.FRight;
Y.FRight.FParent := Y;
end;
Transplant(Z, Y);
Y.FLeft := Z.FLeft;
Y.FLeft.FParent := Y;
Y.FParameter^.Color := Z.FParameter^.Color;
end;
if YOriginalColor = rbBlack then
DeleteFixup(X);
FHeight := -1;
Dec(FCount);
end;
procedure TRBTree<TKey, TValue>.DeleteFixup(Node: TNode<TKey, TValue>);
var
Y: TNode<TKey, TValue>;
begin
while (Node <> FRoot) and (Node.FParameter^.Color = rbBlack) do begin
if Node = Node.FParent.FLeft then begin
Y := Node.FParent.FRight;
if Y.FParameter^.Color = rbRed then begin
Y.FParameter^.Color := rbBlack;
Node.FParent.FParameter^.Color := rbRed;
LeftRotate(Node.FParent);
Y := Node.FParent.FRight;
end;
if (Y.FLeft.FParameter^.Color = rbBlack) and (Y.FRight.FParameter^.Color = rbBlack) then begin
Y.FParameter^.Color := rbRed;
Node := Node.FParent;
end
else begin
if Y.FRight.FParameter^.Color = rbBlack then begin
Y.FLeft.FParameter^.Color := rbBlack;
Y.FParameter^.Color := rbRed;
RightRotate(Y);
Y := Node.FParent.FRight;
end;
Y.FParameter^.Color := Node.FParent.FParameter.Color;
Node.FParent.FParameter^.Color := rbBlack;
Y.FRight.FParameter^.Color := rbBlack;
LeftRotate(Node.FParent);
Node := FRoot;
end;
end
else begin
Y := Node.FParent.FLeft;
if Y.FParameter^.Color = rbRed then begin
Y.FParameter^.Color := rbBlack;
Node.FParent.FParameter^.Color := rbRed;
RightRotate(Node.FParent);
Y := Node.FParent.FLeft;
end;
if (Y.FLeft.FParameter^.Color = rbBlack) and (Y.FRight.FParameter^.Color = rbBlack) then begin
Y.FParameter^.Color := rbRed;
Node := Node.FParent;
end
else begin
if Y.FLeft.FParameter^.Color = rbBlack then begin
Y.FRight.FParameter^.Color := rbBlack;
Y.FParameter^.Color := rbRed;
LeftRotate(Y);
Y := Node.FParent.FLeft;
end;
Y.FParameter^.Color := Node.FParent.FParameter^.Color;
Node.FParent.FParameter^.Color := rbBlack;
Y.FLeft.FParameter^.Color := rbBlack;
RightRotate(Node.FParent);
Node := FRoot;
end;
end;
end;
Node.FParameter^.Color := rbBlack;
end;
destructor TRBTree<TKey, TValue>.Destroy;
begin
inherited;
FSentinel.Free();
end;
procedure TRBTree<TKey, TValue>.Insert(Node: TNode<TKey, TValue>);
var
Z, Tmp: TNode<TKey, TValue>;
begin
inherited;
Z := Node;
Z.FLeft := FSentinel;
Z.FRight := FSentinel;
Z.FParameter^.Color := rbRed;
Tmp := Z;
InsertFixup(Tmp);
end;
procedure TRBTree<TKey, TValue>.InsertFixup(Node: TNode<TKey, TValue>);
var
Y: TNode<TKey, TValue>;
begin
while Node.FParent.FParameter^.Color = rbRed do begin
if Node.FParent = Node.FParent.FParent.FLeft then begin
Y := Node.FParent.FParent.FRight;
if Y.FParameter^.Color = rbRed then begin
Node.FParent.FParameter^.Color := rbBlack;
Y.FParameter^.Color := rbBlack;
Node.FParent.FParent.FParameter^.Color := rbRed;
Node := Node.FParent.FParent;
end
else begin
if Node = Node.FParent.FRight then begin
Node := Node.FParent;
LeftRotate(Node);
end;
Node.FParent.FParameter^.Color := rbBlack;
Node.FParent.FParent.FParameter^.Color := rbRed;
RightRotate(Node.FParent.FParent);
end;
end
else begin
Y := Node.FParent.FParent.FLeft;
if Y.FParameter^.Color = rbRed then begin
Node.FParent.FParameter^.Color := rbBlack;
Y.FParameter^.Color := rbBlack;
Node.FParent.FParent.FParameter^.Color := rbRed;
Node := Node.FParent.FParent;
end
else begin
if Node = Node.FParent.FLeft then begin
Node := Node.FParent;
RightRotate(Node);
end;
Node.FParent.FParameter^.Color := rbBlack;
Node.FParent.FParent.FParameter^.Color := rbRed;
LeftRotate(Node.FParent.FParent);
end;
end;
end;
FRoot.FParameter^.Color := rbBlack;
end;
{ TTreapTree<TKey, TValue> }
constructor TTreapTree<TKey, TValue>.Create;
begin
inherited Create;
FSentinel := TNode<TKey, TValue>.Create(Default(TKey), Default(TValue));
FSentinel.FSentinel := True;
FSentinel.FParameter^.Priority := 0;
FRoot := FSentinel;
end;
procedure TTreapTree<TKey, TValue>.Delete(Node: TNode<TKey, TValue>);
var
Z: TNode<TKey, TValue>;
begin
Z := Node;
while not IsSentinel(Z.FLeft) or not IsSentinel(Z.FRight) do begin
if Z.FLeft.FParameter^.Priority > Z.FRight.FParameter^.Priority then
RightRotate(Z)
else
LeftRotate(Z);
end;
Transplant(Z, FSentinel);
FHeight := -1;
Dec(FCount);
end;
destructor TTreapTree<TKey, TValue>.Destroy;
begin
inherited;
FSentinel.Free();
end;
procedure TTreapTree<TKey, TValue>.Insert(Node: TNode<TKey, TValue>);
var
Z: TNode<TKey, TValue>;
begin
inherited;
Z := Node;
Z.FLeft := FSentinel;
Z.FRight := FSentinel;
Z.FParameter^.Priority := Random(1000);
while (Z <> FRoot) and (Z.FParameter^.Priority > Z.FParent.FParameter^.Priority) do begin
if Z = Z.FParent.FLeft then
RightRotate(Z.FParent)
else
LeftRotate(Z.FParent);
end;
end;
{ TAVLTree<TKey, TValue> }
procedure TAVLTree<TKey, TValue>.Delete(Node: TNode<TKey, TValue>);
var
X, Y, Z: TNode<TKey, TValue>;
begin
Z := Node;
if IsSentinel(Z.FLeft) and IsSentinel(Z.FRight) then begin
if Z = FRoot then
//do nothing
else if Z = Z.FParent.FLeft then
Dec(Z.FParent.FParameter^.Factor)
else
Inc(Z.FParent.FParameter^.Factor);
X := Z.FParent;
Transplant(Z, nil);
end
else if IsSentinel(Z.FLeft) then begin
Y := Z.FRight;
Transplant(Z, Y);
X := Y;
end
else if IsSentinel(Z.FRight) then begin
Y := Z.FLeft;
Transplant(Z, Y);
X := Y;
end
else begin
Y := Minimum(Z.FRight);
if Y.FParent <> Z then begin
Transplant(Y, Y.FRight);
Y.FRight := Z.FRight;
Y.FRight.FParent := Y;
Y.FParameter^.Factor := Z.FParameter^.Factor;
X := Y.FParent;
Dec(X.FParameter^.Factor);
end
else begin
Y.FParameter^.Factor := Z.FParameter^.Factor + 1;
X := Y;
end;
Transplant(Z, Y);
Y.FLeft := Z.FLeft;
Y.FLeft.FParent := Y;
end;
while not IsSentinel(X) do begin
if X.FParameter^.Factor = 0 then begin
if not IsSentinel(X.FParent) then begin
if X = X.FParent.FLeft then
Dec(X.FParent.FParameter^.Factor)
else
Inc(X.FParent.FParameter^.Factor);
X := X.FParent;
end else
Break;
end
else if (X.FParameter^.Factor = 1) or (X.FParameter^.Factor = -1) then begin
Break
end
else begin
DeleteBalance(X);
X := X.FParent;
end;
end;
FHeight := -1;
Dec(FCount);
end;
procedure TAVLTree<TKey, TValue>.DeleteBalance(Node: TNode<TKey, TValue>);
var
NodeFactor, NodeLeftFactor, NodeRightFactor: TAVLFactor;
begin
NodeFactor := 0;
if Node.FParameter^.Factor = 2 then begin
NodeLeftFactor := 0;
if Node.FLeft.FParameter^.Factor = -1 then begin
if Node.FLeft.FRight.FParameter^.Factor = 1 then begin
Node.FLeft.FParameter^.Factor := 0;
NodeFactor := -1;
end
else if node.FLeft.FRight.FParameter^.Factor = -1 then begin
Node.FLeft.FParameter^.Factor := 1
end else
Node.FLeft.FParameter^.Factor := 0;
LeftRotate(Node.FLeft);
end
else if Node.FLeft.FParameter^.Factor = 0 then begin
NodeFactor := 1;
NodeLeftFactor := -1;
end;
Node.FParameter^.Factor := NodeFactor;
Node.FLeft.FParameter^.Factor := NodeLeftFactor;
RightRotate(Node);
end
else begin
NodeRightFactor := 0;
if Node.FRight.FParameter^.Factor = 1 then begin
if Node.FRight.FLeft.FParameter^.Factor = -1 then begin
Node.FRight.FParameter^.Factor := 0;
NodeFactor := 1;
end
else if Node.FRight.FLeft.FParameter^.Factor = 1 then begin
Node.FRight.FParameter^.Factor := -1
end else
Node.FRight.FParameter^.Factor := 0;
RightRotate(Node.FRight)
end
else if Node.FRight.FParameter^.Factor = 0 then begin
NodeFactor := -1;
NodeRightFactor := 1;
end;
Node.FParameter^.Factor := NodeFactor;
Node.FRight.FParameter^.Factor := NodeRightFactor;
LeftRotate(Node);
end;
end;
procedure TAVLTree<TKey, TValue>.Insert(Node: TNode<TKey, TValue>);
var
Tmp, Parent: TNode<TKey, TValue>;
begin
inherited;
Node.FParameter^.Factor := 0; // 初始平衡因子
Tmp := Node;
Parent := Tmp.FParent;
while not IsSentinel(Parent) do begin
if Tmp = Parent.FLeft then
Inc(Parent.FParameter^.Factor)
else
Dec(Parent.FParameter^.Factor);
if Parent.FParameter^.Factor = 0 then begin
Break;
end
else if (Parent.FParameter^.Factor = -1) or (Parent.FParameter^.Factor = 1) then begin
Tmp := Parent;
Parent := Tmp.FParent;
end
else begin
InsertBalance(Parent);
Break;
end;
end;
end;
procedure TAVLTree<TKey, TValue>.InsertBalance(Node: TNode<TKey, TValue>);
var
NodeFactor: TAVLFactor;
begin
NodeFactor := 0;
if Node.FParameter^.Factor = 2 then begin
if Node.FLeft.FParameter^.Factor = -1 then begin
if Node.FLeft.FRight.FParameter^.Factor = 1 then begin
Node.FLeft.FParameter^.Factor := 0;
NodeFactor := -1;
end
else if Node.FLeft.FRight.FParameter^.Factor = -1 then begin
Node.FLeft.FParameter^.Factor := 1
end else
Node.FLeft.FParameter^.Factor := 0;
LeftRotate(Node.FLeft);
end;
Node.FParameter^.Factor := NodeFactor;
Node.FLeft.FParameter^.Factor := 0;
RightRotate(Node);
end
else begin
if Node.FRight.FParameter^.Factor = 1 then begin
if Node.FRight.FLeft.FParameter^.Factor = -1 then begin
Node.FRight.FParameter^.Factor := 0;
NodeFactor := 1;
end
else if Node.FRight.FLeft.FParameter^.Factor = 1 then begin
Node.FRight.FParameter^.Factor := -1
end else
Node.FRight.FParameter^.Factor := 0;
RightRotate(Node.FRight);
end;
Node.FParameter^.Factor := NodeFactor;
Node.FRight.FParameter^.Factor := 0;
LeftRotate(Node);
end;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
unit RN_DetourStatus;
interface
type TdtStatus = Cardinal;
// High level status.
const DT_FAILURE: Cardinal = Cardinal(1) shl 31; // Operation failed.
const DT_SUCCESS: Cardinal = Cardinal(1) shl 30; // Operation succeed.
const DT_IN_PROGRESS: Cardinal = Cardinal(1) shl 29; // Operation still in progress.
// Detail information for status.
const DT_STATUS_DETAIL_MASK: Cardinal = $0ffffff;
const DT_WRONG_MAGIC: Cardinal = 1 shl 0; // Input data is not recognized.
const DT_WRONG_VERSION: Cardinal = 1 shl 1; // Input data is in wrong version.
const DT_OUT_OF_MEMORY: Cardinal = 1 shl 2; // Operation ran out of memory.
const DT_INVALID_PARAM: Cardinal = 1 shl 3; // An input parameter was invalid.
const DT_BUFFER_TOO_SMALL: Cardinal = 1 shl 4; // Result buffer for the query was too small to store all results.
const DT_OUT_OF_NODES: Cardinal = 1 shl 5; // Query ran out of nodes during search.
const DT_PARTIAL_RESULT: Cardinal = 1 shl 6; // Query did not reach the end location, returning best guess.
function dtStatusSucceed(status: TdtStatus): Boolean;
function dtStatusFailed(status: TdtStatus): Boolean;
function dtStatusInProgress(status: TdtStatus): Boolean;
function dtStatusDetail(status: TdtStatus; detail: Cardinal): Boolean;
implementation
// Returns true of status is success.
function dtStatusSucceed(status: TdtStatus): Boolean;
begin
Result := (status and DT_SUCCESS) <> 0;
end;
// Returns true of status is failure.
function dtStatusFailed(status: TdtStatus): Boolean;
begin
Result := (status and DT_FAILURE) <> 0;
end;
// Returns true of status is in progress.
function dtStatusInProgress(status: TdtStatus): Boolean;
begin
Result := (status and DT_IN_PROGRESS) <> 0;
end;
// Returns true if specific detail is set.
function dtStatusDetail(status: TdtStatus; detail: Cardinal): Boolean;
begin
Result := (status and detail) <> 0;
end;
end.
|
unit LuaStringGrid;
interface
Uses Classes, Types, Controls, Contnrs, LuaPas, LuaControl, Forms, Grids, StdCtrls, TypInfo, LuaCanvas,
Graphics; ///QVCL
function CreateStringGrid(L: Plua_State): Integer; cdecl;
type
PLuaStringGridCellAttr = ^TLuaStringGridCellAttr;
TLuaStringGridCellAttr = record
Color: TColor;
IsSetColor: Boolean;
end;
TLuaStringGrid = class(TStringGrid)
LuaCtl: TLuaControl;
LuaCanvas: TLuaCanvas;
protected
function GetCellAttr(ACol, ARow: Integer): PLuaStringGridCellAttr;
procedure DoPrepareCanvas(aCol,aRow:Integer; aState: TGridDrawState); override;
public
destructor Destroy; override;
procedure SetCellColor(ACol, ARow: Integer; const AValue: TColor);
end;
// ***********************************************
implementation
Uses LuaStrings, LuaProperties, Lua, Dialogs;
function Clear(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,cf,r :Integer;
begin
CheckArg(L, 1);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := lStringGrid.ColCount;
cf := lStringGrid.FixedCols;
r := lStringGrid.FixedRows;
lStringGrid.Clear;
lStringGrid.RowCount := r;
lStringGrid.FixedRows := r;
lStringGrid.ColCount := c;
lStringGrid.FixedCols := cf;
Result := 0;
end;
function DrawCell(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r:Integer;
rect:TRect;
aState:TGridDrawState;
begin
CheckArg(L, 5);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
r := trunc(lua_tonumber(L,3));
rect := LuaGetRect(L,4);
aState := TGridDrawState(GetEnumValue(TypeInfo(TGridDrawState),lua_tostring(L,5)));
lStringGrid.defaultdrawcell(c,r,rect,aState);
Result := 0;
end;
function CellsGet(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r :Integer;
begin
CheckArg(L, 3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
r := trunc(lua_tonumber(L,3));
lua_pushstring(L,pchar(lStringGrid.Cells[c,r]));
Result := 1;
end;
function CellsSet(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r :Integer;
begin
CheckArg(L, 4);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
r := trunc(lua_tonumber(L,3));
lStringGrid.Cells[c,r] := AnsiToUtf8(lua_tostring(L,4));
Result := 0;
end;
function SetCellColor(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r :Integer;
begin
CheckArg(L, 4, 'SetCellColor');
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
r := trunc(lua_tonumber(L,3));
lStringGrid.SetCellColor(c,r,TColor(lua_tointeger(L,4)));
Result := 0;
end;
function ColsGet(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
i,n :Integer;
begin
CheckArg(L, 2);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
n := trunc(lua_tonumber(L,2));
lua_newtable(L);
for i:= 0 to lStringGrid.Cols[n].Count-1 do begin
lua_pushnumber(L,i);
lua_pushstring(L,pchar(lStringGrid.Cols[n][i]));
lua_rawset(L,-3);
end;
Result := 1;
end;
function RowsGet(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
i,n :Integer;
begin
CheckArg(L, 2);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
n := trunc(lua_tonumber(L,2));
lua_newtable(L);
for i:= 0 to lStringGrid.Rows[n].Count-1 do begin
lua_pushnumber(L,i+1); // lua_table
lua_pushstring(L,pchar(lStringGrid.Rows[n][i]));
lua_rawset(L,-3);
end;
Result := 1;
end;
function CellRectGet(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r :Integer;
Rect : TRect;
begin
CheckArg(L, 3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
r := trunc(lua_tonumber(L,3));
Rect := lStringGrid.CellRect(c,r);
lua_newtable(L);
lua_pushliteral(L,'Left');
lua_pushnumber(L,Rect.Left);
lua_rawset(L,-3);
lua_pushliteral(L,'Top');
lua_pushnumber(L,Rect.Top);
lua_rawset(L,-3);
lua_pushliteral(L,'Right');
lua_pushnumber(L,Rect.Right);
lua_rawset(L,-3);
lua_pushliteral(L,'Bottom');
lua_pushnumber(L,Rect.Bottom);
lua_rawset(L,-3);
// lua_pushnumber(L,4);
// lua_pushliteral(L,'n');
// lua_rawset(L,-3);
Result := 1;
end;
function GetSelectedCell(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
c,r :Integer;
Rect : TRect;
begin
CheckArg(L, 1);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := lStringGrid.Selection.TopLeft.x;
r := lStringGrid.Selection.TopLeft.y;
Rect := lStringGrid.CellRect(c,r);
lua_pushnumber(L,c);
lua_pushnumber(L,r);
Result := 2;
end;
function GetMouseToCell(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
X,Y,c,r :Integer;
begin
CheckArg(L, 3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
X := trunc(lua_tonumber(L,2));
Y := trunc(lua_tonumber(L,3));
lStringGrid.MouseToCell(X, Y, c, r);
lua_pushnumber(L,c);
lua_pushnumber(L,r);
Result := 2;
end;
function SetColWidth(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
n,i,w :Integer;
begin
n := lua_gettop(L);
if (n=2) and lua_istable(L,2) then begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lua_pushnil(L);
i := 0;
while (lua_next(L, n) <> 0) do begin
lStringGrid.ColWidths[i] := trunc(lua_tonumber(L,-1));
lua_pop(L, 1);
inc(i);
end;
end
else begin
CheckArg(L, 3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
i := trunc(lua_tonumber(L,2));
w := trunc(lua_tonumber(L,3));
if i=0 then
lStringGrid.DefaultColWidth := w
else
lStringGrid.ColWidths[i] := w;
end;
Result := 0;
end;
function SetRowHeight(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
i,h :Integer;
begin
CheckArg(L, 3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
i := trunc(lua_tonumber(L,2));
h := trunc(lua_tonumber(L,3));
if i=0 then
lStringGrid.DefaultRowHeight := h
else
lStringGrid.RowHeights[i] := h;
Result := 0;
end;
function SetRowData(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
i,r :Integer;
begin
CheckArg(L, 3);
// lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
r := trunc(lua_tonumber(L,2));
if lua_istable(L,3) then begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lua_pushnil(L);
i := 0;
while (lua_next(L, 3) <> 0) do begin
lStringGrid.Cells[i,r] := AnsiToUtf8(lua_tostring(L,-1));
lua_pop(L, 1);
inc(i);
end;
end;
Result := 0;
end;
function SetColData(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
i,c :Integer;
begin
CheckArg(L, 3);
// lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
c := trunc(lua_tonumber(L,2));
if lua_istable(L,3) then begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lua_pushnil(L);
i := 0;
while (lua_next(L, 3) <> 0) do begin
lStringGrid.Cells[c,i] := AnsiToUtf8(lua_tostring(L,-1));
lua_pop(L, 1);
inc(i);
end;
end;
Result := 0;
end;
procedure StringGridColumsToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L,Index,Sender);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function LoadColParamsFromTable(L:Plua_State; LGridCol:TGridColumn):Boolean;
var
n:Integer;
PInfo: PPropInfo;
begin
Result := False;
if lua_istable(L,-1) then begin
n := lua_gettop(L);
result := true;
lua_pushnil(L);
while (lua_next(L, n) <> 0) do begin
if lua_istable(L,-1) and (TObject(GetInt64Prop(LGridCol,lua_tostring(L, -2)))<>nil) then begin
SetPropertiesFromLuaTable(L,TObject(GetInt64Prop(LGridCol,lua_tostring(L, -2))),-1);
end
else begin
PInfo := GetPropInfo(LGridCol.ClassInfo,lua_tostring(L, -2));
if PInfo<>nil then
SetProperty(L, -1, TComponent(LGridCol), PInfo);
// Todo error
end;
lua_pop(L, 1);
end;
end;
end;
function SetColParams(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
LGridCol: TGridColumn;
n,i :Integer;
begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
n := lua_gettop(L);
if ((n=3) and (lua_isnumber(L,2))) then begin
if lua_istable(L,-1) then begin
LGridCol := lStringGrid.Columns[trunc(lua_tonumber(L,2))];
LoadColParamsFromTable(L,LGridCol);
inc(i);
end;
end else begin
lua_pushnil(L);
i:=0;
while (lua_next(L, n) <> 0) do begin // menuitems
if lua_istable(L,-1) then begin
LGridCol := lStringGrid.Columns.Add;
LoadColParamsFromTable(L,LGridCol);
inc(i);
end;
lua_pop(L, 1);
end;
end;
Result := 0;
end;
function GetColumns(L: Plua_State): Integer; cdecl;
var lStringGrid:TLuaStringGrid;
begin
CheckArg(L, 1);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
StringGridColumsToTable(L,-1, TStringGrid(lStringGrid.Columns));
Result := 1;
end;
function AddCol(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
LGridCol: TGridColumn;
n,i :Integer;
begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
n := lua_gettop(L);
LGridCol := lStringGrid.Columns.Add;
SetPropertiesFromLuaTable(L,LGridCol,-1);
if ((n=3) and (lua_isnumber(L,2))) then begin
LGridCol.Index:= trunc(lua_tonumber(L,2));
end;
Result := 0;
end;
function AddRow(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
n,i,r,c:Integer;
begin
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
n := lua_gettop(L);
lStringGrid.RowCount:=lStringGrid.RowCount+1;
// insert?
if (lua_isnumber(L,2)) then begin
i:= trunc(lua_tonumber(L,2));
for r := lStringGrid.RowCount-1 downto i do
lStringGrid.Rows[r] := lStringGrid.Rows[r-1];
for c:= lStringGrid.FixedCols to lStringGrid.ColCount-1 do
lStringGrid.Cells[c,i] := '';
lua_pushnumber(L, i);
end else
lua_pushnumber(L, lStringGrid.RowCount-1);
Result := 1;
end;
function DeleteColRow(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
begin
CheckArg(L,3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lStringGrid.DeleteColRow(lua_toboolean(L,2),trunc(lua_tonumber(L,3)));
Result := 0;
end;
function SortColRow(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
begin
CheckArg(L,3);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lStringGrid.SortColRow(lua_toboolean(L,2),trunc(lua_tonumber(L,3)));
Result := 0;
end;
function GridSaveToFile(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
fn:String;
begin
CheckArg(L,2);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lStringGrid.SaveOptions:= [soDesign, soAttributes, soContent];
lStringGrid.SaveToFile(lua_tostring(L,2));
Result := 0;
end;
function GridLoadFromFile(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
fn:String;
begin
CheckArg(L,2);
lStringGrid := TLuaStringGrid(GetLuaObject(L, 1));
lStringGrid.LoadFromFile(lua_tostring(L,2));
lStringGrid.Refresh;
Result := 0;
end;
function GridGetCanvas(L: Plua_State): Integer; cdecl;
var lC:TLuaStringGrid;
begin
lC := TLuaStringGrid(GetLuaObject(L, 1));
lC.LuaCanvas.ToTable(L, -1, lC.Canvas);
result := 1;
end;
destructor TLuaStringGrid.Destroy;
begin
if (LuaCanvas<>nil) then LuaCanvas.Free;
inherited Destroy;
end;
procedure TLuaStringGrid.DoPrepareCanvas(aCol,aRow:Integer; aState: TGridDrawState);
var
CellAttr:PLuaStringGridCellAttr;
begin
CellAttr := GetCellAttr(ACol, ARow);
if CellAttr.IsSetColor then
Canvas.Brush.Color := CellAttr.Color;
inherited;
end;
function TLuaStringGrid.GetCellAttr(ACol, ARow: Integer): PLuaStringGridCellAttr;
procedure CrealCellAttr(attr: PLuaStringGridCellAttr);
begin
attr.Color := Self.Color;
attr.IsSetColor := False;
end;
var
C: PCellProps;
begin
C:= FGrid.Celda[aCol,aRow];
if C<>nil then begin
if C^.Attr=nil then begin
C^.Attr:=new(PLuaStringGridCellAttr);
CrealCellAttr(C^.Attr);
end;
end else begin
New(C);
C^.Attr:=new(PLuaStringGridCellAttr);
CrealCellAttr(C^.Attr);
C^.Data:=nil;
C^.Text:=nil;
FGrid.Celda[aCol,aRow]:=C;
end;
Result := C^.Attr;
end;
procedure TLuaStringGrid.SetCellColor(ACol, ARow: Integer; const AValue: TColor);
var
CellAttr:PLuaStringGridCellAttr;
begin
CellAttr := GetCellAttr(ACol, ARow);
if CellAttr.Color <> AValue then begin
CellAttr.Color := AValue;
CellAttr.IsSetColor := True;
InvalidateCell(ACol, ARow);
Modified := True;
end;
end;
procedure ToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetTableFunction(L, Index, 'Clear', @Clear);
LuaSetTableFunction(L, Index, 'GetCell', @CellsGet);
LuaSetTableFunction(L, Index, 'SetCell', @CellsSet);
LuaSetTableFunction(L, Index, 'SetCellColor', @SetCellColor);
LuaSetTableFunction(L, Index, 'DrawCell', @DrawCell);
LuaSetTableFunction(L, Index, 'ColToTable', @ColsGet);
LuaSetTableFunction(L, Index, 'LoadColFromTable', @SetColData);
LuaSetTableFunction(L, Index, 'RowToTable', @RowsGet);
LuaSetTableFunction(L, Index, 'LoadRowFromTable', @SetRowData);
LuaSetTableFunction(L, Index, 'CellRect', @CellRectGet);
LuaSetTableFunction(L, Index, 'MouseToCell', @GetMouseToCell);
LuaSetTableFunction(L, Index, 'SelectedCell', @GetSelectedCell);
LuaSetTableFunction(L, Index, 'SetRowHeight', @SetRowHeight);
LuaSetTableFunction(L, Index, 'SetColWidth', @SetColWidth);
LuaSetTableFunction(L, Index, 'SetColParams', @SetColParams);
LuaSetTableFunction(L, Index, 'GetColumns', @GetColumns);
LuaSetTableFunction(L, Index, 'AddCol', @AddCol);
LuaSetTableFunction(L, Index, 'AddRow', @AddRow);
LuaSetTableFunction(L, Index, 'DeleteColRow', @DeleteColRow);
LuaSetTableFunction(L, Index, 'SortColRow', @SortColRow);
LuaSetTableFunction(L, Index, 'SaveToFile',@GridSaveToFile);
LuaSetTableFunction(L, Index, 'LoadFromFile',@GridLoadFromFile);
if (Sender.InheritsFrom(TCustomControl) or Sender.InheritsFrom(TGraphicControl)) then
LuaSetTableFunction(L, Index, 'GetCanvas', GridGetCanvas);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function CreateStringGrid(L: Plua_State): Integer; cdecl;
var
lStringGrid:TLuaStringGrid;
Parent:TComponent;
Name:String;
begin
GetControlParents(L,Parent,Name);
lStringGrid := TLuaStringGrid.Create(Parent);
lStringGrid.Parent := TWinControl(Parent);
lStringGrid.LuaCtl := TLuaControl.Create(lStringGrid,L,@ToTable);
if (lua_gettop(L)>0) and (GetLuaObject(L, -1) = nil) then
SetPropertiesFromLuaTable(L, TObject(lStringGrid),-1)
else
lStringGrid.Name := Name;
if (lStringGrid.InheritsFrom(TCustomControl) or lStringGrid.InheritsFrom(TGraphicControl)) then
lStringGrid.LuaCanvas := TLuaCanvas.Create;
ToTable(L, -1, lStringGrid);
Result := 1;
end;
end.
|
unit k03_kel3_utils;
{Berisi fungsi-fungsi perantara yang vital untuk membantu unit-unit lain}
{REFERENSI : https://stackoverflow.com/questions/27708404/crt-library-changes-console-encoding-pascal (clearscreen in windows)
https://stackoverflow.com/questions/6320003/how-do-i-check-whether-a-string-exists-in-an-array
http://computer-programming-forum.com/29-pascal/f1ca9109e91492c4.htm (Pascal, Password mask)}
interface
uses
ucsvwrapper,
uuser, crt;
const
delimiter = ',';
{PUBLIC FUNCTIONS, PROCEDURE}
function StrToInt(rawString : string): integer;
function IntToStr(rawInt : integer): string;
function IntToHex(n: Cardinal): string;
procedure clrscr_();
procedure printFeatures(pactiveUser : psingleuser);
function queryValid(q : string): boolean;
function readpass(ptr : psingleuser): string;
implementation
{FUNGSI dan PROSEDUR}
function StrToInt(rawString : string): integer;
{DESKRIPSI : Mengubah string menjadi integer}
{PARAMETER : string berisi angka}
{RETURN : integer yang merepresentasikan string tersebut}
{KAMUS LOKAL}
var
i : integer;
done : boolean;
{ALGORITMA}
begin
{cari bilangan tak nol pertama dalam string tsb}
i := 1;
while (rawString[i] = '0') do begin
i += 1;
end;
{skema pencarian dengan boolean}
done := false;
StrToInt := 0;
while (not done) and (i <= length(rawString)) do begin
if (rawString[i] <> '.') then begin
StrToInt := StrToInt * 10 + (ord(rawString[i]) - ord('0'));
end else begin {kalau string memuat titik, berhenti (karena hanya ingin integer nya saja)}
done := true;
end;
i += 1;
end;
end;
function IntToStr(rawInt : integer): string;
{DESKRIPSI : Mengubah integer menjadi string}
{PARAMETER : integer yang ingin diubah menjadi string}
{RETURN : string yang merepresentasikan integer tersebut}
{KAMUS LOKAL}
var
isNeg : boolean;
{ALGORITMA}
begin
{kasus integer negatif}
if (rawInt < 0) then begin
rawInt *= -1;
isNeg := true;
end else begin
isNeg := false;
end;
IntToStr := '';
while (rawInt <> 0) do begin
{ambil digit terakhir (mod 10), ubah jadi char bersesuaian}
IntToStr := chr((rawInt mod 10) + ord('0')) + IntToStr;
rawInt := rawInt div 10;
end;
{beri tanda negatif jika integer negatif}
if (isNeg) then begin
IntToStr := '-' + IntToStr;
end;
end;
function IntToHex(n: Cardinal): string;
{DESKRIPSI : Mengubah 32-bit unsigned integer (Cardinal) menjadi string hexadecimalnya}
{PARAMETER : integer yang ingin diubah menjadi string hexadecimal}
{RETURN : string yang merepresentasikan nilai hexadecimal integer tersebut}
{KAMUS LOKAL}
var
tmp : integer;
{ALGORITMA}
begin
IntToHex := '';
{skema yang sama seperti StrToInt}
while (n <> 0) do begin
tmp := n mod 16;
{bagi 2 kasus, kurang dari 10 dan di atas 10}
if (tmp < 10) then begin
{ubah jadi char yang bersesuaian}
IntToHex := chr(tmp + ord('0')) + IntToHex;
end else begin
tmp -= 10;
{10 -> 'a', 11 -> 'b', 12 -> 'c', 13 -> 'd', 14 -> 'e', 15 -> 'f'}
IntToHex := chr(tmp + ord('a')) + IntToHex;
end;
n := n div 16;
end;
end;
procedure clrscr_();
{DESKRIPSI : Menghapus layar cmd}
{I.S. : sembarang}
{F.S. : layar cmd kosong}
{Proses : menggunakan clrscr dan assign ulang input output}
{ALGORITMA}
begin
clrscr;
{IFDEF WINDOWS}
assign(input, ''); reset(input);
assign(output, ''); rewrite(output);
{ENDIF}
end;
procedure printFeatures(pactiveUser : psingleuser);
{DESKRIPSI : Menampilkan fitur-fitur pada layar}
{I.S. : Sembarang}
{F.S. : Fitur-fitur tertulis di layar}
{Proses : Menulis fitur-fitur di layar}
{ALGORITMA}
begin
writeln('Selamat datang di Perpustakaan Tengah Gurun, ', unwraptext(pactiveUser^.username), '!' );
{Prompt pada Admin}
if (pactiveUser^.isAdmin) then begin
writeln('$ register : Regitrasi Akun' );
writeln('$ logout : Logout' );
writeln('$ cari : Pencarian Buku berdasar Kategori' );
writeln('$ caritahunterbit : Pencarian Buku berdasar Tahun Terbit' );
writeln('$ pinjam_buku : Pemimjaman Buku' );
writeln('$ kembalikan_buku : Pengembalian Buku' );
writeln('$ lapor_hilang : Melaporkan Buku Hilang' );
writeln('$ lihat_laporan : Melihat Laporan Buku yang Hilang' );
writeln('$ tambah_buku : Menambahkan Buku Baru ke Sistem' );
writeln('$ tambah_jumlah_buku : Melakukan Penambahan Jumlah Buku ke Sistem' );
writeln('$ riwayat : Melihat Riwayat Peminjaman' );
writeln('$ statistik : Melihat Statistik' );
writeln('$ load : Load File' );
writeln('$ save : Save File' );
writeln('$ cari_anggota : Pencarian Anggota' );
writeln('$ exit : Exit' );
{Prompt pada pengguna yang sudah login}
end else if (pactiveUser^.username <> wraptext('Anonymous')) then begin
writeln('$ logout : Logout' );
writeln('$ cari : Pencarian Buku berdasar Kategori' );
writeln('$ caritahunterbit : Pencarian Buku berdasar Tahun Terbit' );
writeln('$ pinjam_buku : Pemimjaman Buku' );
writeln('$ kembalikan_buku : Pengembalian Buku' );
writeln('$ lapor_hilang : Melaporkan Buku Hilang' );
writeln('$ load : Load File' );
writeln('$ save : Save File' );
writeln('$ exit : Exit' );
{Prompt pada penggunayang belum login}
end else begin
writeln('$ login : Login' );
writeln('$ cari : Pencarian Buku berdasar Kategori' );
writeln('$ caritahunterbit : Pencarian Buku berdasar Tahun Terbit' );
writeln('$ lapor_hilang : Melaporkan Buku Hilang' );
writeln('$ exit : Exit' );
end;
end;
function queryValid(q : string): boolean;
{DESKRIPSI : mengecek apakah query yang dimasukkan user valid/tidak}
{PARAMETER : query input user }
{RETURN : boolean apakah query valid }
{KAMUS LOKAL}
const
NUMQUERIES = 17;
QUERIES : array [1..NUMQUERIES] of string =
('register', 'login', 'cari', 'caritahunterbit', 'pinjam_buku', 'kembalikan_buku',
'lapor_hilang', 'lihat_laporan', 'tambah_buku', 'tambah_jumlah_buku', 'riwayat',
'statistik', 'load', 'save', 'cari_anggota', 'exit', 'logout');
var
str : string;
i : integer;
{ALGORITMA}
begin
queryValid := false;
for i := 1 to NUMQUERIES do begin
str := QUERIES[i];
if (q = str) then begin
queryValid := true;
end;
end;
end;
function readpass(ptr : psingleuser): string;
{DESKRIPSI : membuat agar password tidak terlihat di layar}
{PARAMETER : pointer user untuk menentukan apakah sedang login/register }
{RETURN : string password}
{KAMUS LOKAL}
var
ch: char;
i : integer;
{ALGORITMA}
begin
readpass := '';
ch := readkey;
while (ch <> #13) do begin
if (ch = #8) then begin
if (length(readpass) <> 0) then begin
clrscr_();
delete(readpass, length(readpass), 1);
if (ptr^.fullname = wraptext('Anonymous')) then begin
writeln('$ login');
writeln('Masukkan username: ', unwraptext(ptr^.username));
write('Masukkan password: ');
end else begin
writeln('$ register');
writeln('Masukkan nama pengunjung: ', unwraptext(ptr^.fullname));
writeln('Masukkan alamat pengunjung: ', unwraptext(ptr^.address));
writeln('Masukkan username pengunjung: ', unwraptext(ptr^.username));
write('Masukkan password pengunjung: ');
end;
for i := 1 to length(readpass) do begin
write('*');
end;
end;
end else begin
write('*');
readpass += ch;
end;
ch := readkey;
end;
writeln();
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Internal.ICU;
{$HPPEMIT NOUSINGNAMESPACE}
interface
uses
System.SysUtils;
(*$HPPEMIT 'namespace System'*)
(*$HPPEMIT '{'*)
(*$HPPEMIT '#if !defined(__ANDROID__)'*)
(*$HPPEMIT ' // System::_PPAnsiChar leaks via the PMarshaledAString alias'*)
(*$HPPEMIT ' typedef char** _PPAnsiChar;'*)
(*$HPPEMIT '#endif'*)
(*$HPPEMIT '}'*)
{*********************************************************}
{ Delphi ICU port. }
{ Documentation: http://www.icu-project.org/apiref/icu4c/ }
{*********************************************************}
{ Basic definitions for ICU }
{ http://www.icu-project.org/apiref/icu4c/utypes_8h.html }
type
UErrorCode = (
U_USING_FALLBACK_WARNING = -128, U_ERROR_WARNING_START = -128, U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126, U_STATE_OLD_WARNING = -125, U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123, U_AMBIGUOUS_ALIAS_WARNING = -122, U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120, U_ERROR_WARNING_LIMIT, U_ZERO_ERROR = 0, U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2, U_INVALID_FORMAT_ERROR = 3, U_FILE_ACCESS_ERROR = 4, U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6, U_MEMORY_ALLOCATION_ERROR = 7, U_INDEX_OUTOFBOUNDS_ERROR = 8, U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10, U_TRUNCATED_CHAR_FOUND = 11, U_ILLEGAL_CHAR_FOUND = 12, U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14, U_BUFFER_OVERFLOW_ERROR = 15, U_UNSUPPORTED_ERROR = 16, U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18, U_UNSUPPORTED_ESCAPE_SEQUENCE = 19, U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21, U_PRIMARY_TOO_LONG_ERROR = 22, U_STATE_TOO_OLD_ERROR = 23, U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25, U_INVARIANT_CONVERSION_ERROR = 26, U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28, U_USELESS_COLLATOR_ERROR = 29, U_NO_WRITE_PERMISSION = 30, U_STANDARD_ERROR_LIMIT,
U_BAD_VARIABLE_DEFINITION = $10000, U_PARSE_ERROR_START = $10000, U_MALFORMED_RULE, U_MALFORMED_SET,
U_MALFORMED_SYMBOL_REFERENCE, U_MALFORMED_UNICODE_ESCAPE, U_MALFORMED_VARIABLE_DEFINITION,
U_MALFORMED_VARIABLE_REFERENCE, U_MISMATCHED_SEGMENT_DELIMITERS, U_MISPLACED_ANCHOR_START,
U_MISPLACED_CURSOR_OFFSET, U_MISPLACED_QUANTIFIER, U_MISSING_OPERATOR, U_MISSING_SEGMENT_CLOSE,
U_MULTIPLE_ANTE_CONTEXTS, U_MULTIPLE_CURSORS, U_MULTIPLE_POST_CONTEXTS, U_TRAILING_BACKSLASH,
U_UNDEFINED_SEGMENT_REFERENCE, U_UNDEFINED_VARIABLE, U_UNQUOTED_SPECIAL, U_UNTERMINATED_QUOTE, U_RULE_MASK_ERROR,
U_MISPLACED_COMPOUND_FILTER, U_MULTIPLE_COMPOUND_FILTERS, U_INVALID_RBT_SYNTAX, U_INVALID_PROPERTY_PATTERN,
U_MALFORMED_PRAGMA, U_UNCLOSED_SEGMENT, U_ILLEGAL_CHAR_IN_SEGMENT, U_VARIABLE_RANGE_EXHAUSTED,
U_VARIABLE_RANGE_OVERLAP, U_ILLEGAL_CHARACTER, U_INTERNAL_TRANSLITERATOR_ERROR, U_INVALID_ID, U_INVALID_FUNCTION,
U_PARSE_ERROR_LIMIT, U_UNEXPECTED_TOKEN = $10100, U_FMT_PARSE_ERROR_START = $10100, U_MULTIPLE_DECIMAL_SEPARATORS,
U_MULTIPLE_DECIMAL_SEPERATORS = U_MULTIPLE_DECIMAL_SEPARATORS, U_MULTIPLE_EXPONENTIAL_SYMBOLS,
U_MALFORMED_EXPONENTIAL_PATTERN, U_MULTIPLE_PERCENT_SYMBOLS, U_MULTIPLE_PERMILL_SYMBOLS, U_MULTIPLE_PAD_SPECIFIERS,
U_PATTERN_SYNTAX_ERROR, U_ILLEGAL_PAD_POSITION, U_UNMATCHED_BRACES, U_UNSUPPORTED_PROPERTY, U_UNSUPPORTED_ATTRIBUTE,
U_ARGUMENT_TYPE_MISMATCH, U_DUPLICATE_KEYWORD, U_UNDEFINED_KEYWORD, U_DEFAULT_KEYWORD_MISSING,
U_DECIMAL_NUMBER_SYNTAX_ERROR, U_FORMAT_INEXACT_ERROR, U_FMT_PARSE_ERROR_LIMIT, U_BRK_INTERNAL_ERROR = $10200,
U_BRK_ERROR_START = $10200, U_BRK_HEX_DIGITS_EXPECTED, U_BRK_SEMICOLON_EXPECTED, U_BRK_RULE_SYNTAX,
U_BRK_UNCLOSED_SET, U_BRK_ASSIGN_ERROR, U_BRK_VARIABLE_REDFINITION, U_BRK_MISMATCHED_PAREN,
U_BRK_NEW_LINE_IN_QUOTED_STRING, U_BRK_UNDEFINED_VARIABLE, U_BRK_INIT_ERROR, U_BRK_RULE_EMPTY_SET,
U_BRK_UNRECOGNIZED_OPTION, U_BRK_MALFORMED_RULE_TAG, U_BRK_ERROR_LIMIT, U_REGEX_INTERNAL_ERROR = $10300,
U_REGEX_ERROR_START = $10300, U_REGEX_RULE_SYNTAX, U_REGEX_INVALID_STATE, U_REGEX_BAD_ESCAPE_SEQUENCE,
U_REGEX_PROPERTY_SYNTAX, U_REGEX_UNIMPLEMENTED, U_REGEX_MISMATCHED_PAREN, U_REGEX_NUMBER_TOO_BIG,
U_REGEX_BAD_INTERVAL, U_REGEX_MAX_LT_MIN, U_REGEX_INVALID_BACK_REF, U_REGEX_INVALID_FLAG, U_REGEX_LOOK_BEHIND_LIMIT,
U_REGEX_SET_CONTAINS_STRING, U_REGEX_OCTAL_TOO_BIG, U_REGEX_MISSING_CLOSE_BRACKET, U_REGEX_INVALID_RANGE,
U_REGEX_STACK_OVERFLOW, U_REGEX_TIME_OUT, U_REGEX_STOPPED_BY_CALLER, U_REGEX_ERROR_LIMIT,
U_IDNA_PROHIBITED_ERROR = $10400, U_IDNA_ERROR_START = $10400, U_IDNA_UNASSIGNED_ERROR, U_IDNA_CHECK_BIDI_ERROR,
U_IDNA_STD3_ASCII_RULES_ERROR, U_IDNA_ACE_PREFIX_ERROR, U_IDNA_VERIFICATION_ERROR, U_IDNA_LABEL_TOO_LONG_ERROR,
U_IDNA_ZERO_LENGTH_LABEL_ERROR, U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR, U_IDNA_ERROR_LIMIT,
U_STRINGPREP_PROHIBITED_ERROR = U_IDNA_PROHIBITED_ERROR, U_STRINGPREP_UNASSIGNED_ERROR = U_IDNA_UNASSIGNED_ERROR,
U_STRINGPREP_CHECK_BIDI_ERROR = U_IDNA_CHECK_BIDI_ERROR, U_PLUGIN_ERROR_START = $10500, U_PLUGIN_TOO_HIGH = $10500,
U_PLUGIN_DIDNT_SET_LEVEL, U_PLUGIN_ERROR_LIMIT, U_ERROR_LIMIT = U_PLUGIN_ERROR_LIMIT
);
type
UBool = ShortInt;
UDate = Double;
UChar = Char;
PUChar = PChar;
PPUChar = ^PChar;
UChar32 = Int32;
PUErrorCode = ^UErrorCode;
TByteArray = array of Byte;
UInt16 = Word;
PInt32 = ^Int32;
{ ICU ucnv.h File Reference }
{ http://icu-project.org/apiref/icu4c/ucnv_8h.html }
const
// Maximum length of a converter name including the terminating NULL.
UCNV_MAX_CONVERTER_NAME_LENGTH = 60;
// Maximum length of a converter name including path and terminating NULL.
UCNV_MAX_FULL_FILE_NAME_LENGTH = (600+UCNV_MAX_CONVERTER_NAME_LENGTH);
// Shift in for EBDCDIC_STATEFUL and iso2022 states.
UCNV_SI = $0F;
// Shift out for EBDCDIC_STATEFUL and iso2022 states.
UCNV_SO = $0E;
// Character that separates converter names from options and options from each other.
UCNV_OPTION_SEP_CHAR: char = ',';
// String version of UCNV_OPTION_SEP_CHAR.
UCNV_OPTION_SEP_STRING: string = ',';
// Character that separates a converter option from its value.
UCNV_VALUE_SEP_CHAR: char = '=';
// String version of UCNV_VALUE_SEP_CHAR.
UCNV_VALUE_SEP_STRING: string = '=';
// Converter option for specifying a locale.
UCNV_LOCALE_OPTION_STRING = ',locale=';
// Converter option for specifying a version selector (0..9) for some converters.
UCNV_VERSION_OPTION_STRING = ',version=';
// Converter option for EBCDIC SBCS or mixed-SBCS/DBCS (stateful) codepages.
UCNV_SWAP_LFNL_OPTION_STRING = ',swaplfnl';
// Definition of a buffer size that is designed to be large enough for converters to be cloned with ucnv_safeClone().
U_CNV_SAFECLONE_BUFFERSIZE = 1024;
//Calculates the size of a buffer for conversion from Unicode to a charset.
//UCNV_GET_MAX_BYTES_FOR_STRING(length, maxCharSize) (((int32_t)(length)+10)*(int32_t)(maxCharSize))
const
UCNV_PRV_ESCAPE_ICU = 0;
UCNV_PRV_ESCAPE_C = Ord('C');
UCNV_PRV_ESCAPE_XML_DEC = Ord('D');
UCNV_PRV_ESCAPE_XML_HEX = Ord('X');
UCNV_PRV_ESCAPE_JAVA = Ord('J');
UCNV_PRV_ESCAPE_UNICODE = Ord('U');
UCNV_PRV_ESCAPE_CSS2 = Ord('S');
UCNV_PRV_STOP_ON_ILLEGAL = Ord('i');
type
PUSet = ^USet;
USet = record end;
// Enum for specifying basic types of converters.
UConverterType = (
UCNV_UNSUPPORTED_CONVERTER = -1, UCNV_SBCS = 0, UCNV_DBCS = 1, UCNV_MBCS = 2, UCNV_LATIN_1 = 3, UCNV_UTF8 = 4,
UCNV_UTF16_BigEndian = 5, UCNV_UTF16_LittleEndian = 6, UCNV_UTF32_BigEndian = 7, UCNV_UTF32_LittleEndian = 8,
UCNV_EBCDIC_STATEFUL = 9, UCNV_ISO_2022 = 10, UCNV_LMBCS_1 = 11, UCNV_LMBCS_2, UCNV_LMBCS_3, UCNV_LMBCS_4,
UCNV_LMBCS_5, UCNV_LMBCS_6, UCNV_LMBCS_8, UCNV_LMBCS_11, UCNV_LMBCS_16, UCNV_LMBCS_17, UCNV_LMBCS_18, UCNV_LMBCS_19,
UCNV_LMBCS_LAST = UCNV_LMBCS_19, UCNV_HZ, UCNV_SCSU, UCNV_ISCII, UCNV_US_ASCII, UCNV_UTF7, UCNV_BOCU1, UCNV_UTF16,
UCNV_UTF32, UCNV_CESU8, UCNV_IMAP_MAILBOX, UCNV_COMPOUND_TEXT, UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES
);
// Enum for specifying which platform a converter ID refers to.
UConverterPlatform = (UCNV_UNKNOWN = -1, UCNV_IBM = 0);
// Selectors for Unicode sets that can be returned by ucnv_getUnicodeSet().
UConverterUnicodeSet = (UCNV_ROUNDTRIP_SET, UCNV_ROUNDTRIP_AND_FALLBACK_SET, UCNV_SET_COUNT);
// Selectors for Unicode sets that can be returned by ucnv_getUnicodeSet().
UConverterCallbackReason = (
UCNV_CB_UNASSIGNED = 0, // The code point is unassigned. The error code U_INVALID_CHAR_FOUND will be set.
UCNV_CB_ILLEGAL = 1, // The code point is illegal. The error code U_ILLEGAL_CHAR_FOUND will be set.
UCNV_CB_IRREGULAR = 2, // The codepoint is not a regular sequence in the encoding. The error code U_INVALID_CHAR_FOUND will be set.
UCNV_CB_RESET = 3, // The callback is called with this reason when a 'reset' has occured. Callback should reset all state.
UCNV_CB_CLOSE = 4, // Called when the converter is closed. The callback should release any allocated memory.
UCNV_CB_CLONE = 5 // Called when ucnv_safeClone() is called on the converter. the pointer available as the
// 'context' is an alias to the original converters' context pointer. If the context must be owned
// by the new converter, the callback must clone the data and call ucnv_setFromUCallback
// (or setToUCallback) with the correct pointer.
);
PUConverter = ^UConverter;
UConverter = record end;
PUConverterToUnicodeArgs = ^UConverterToUnicodeArgs;
UConverterToUnicodeArgs = record // http://icu-project.org/apiref/icu4c/structUConverterToUnicodeArgs.html
size: UInt16; // The size of this struct
flush: UBool; // The internal state of converter will be reset and data flushed if set to TRUE.
converter: PUConverter; // Pointer to the converter that is opened and to which this struct is passed as an argument.
source: MarshaledAString; // Pointer to the source source buffer.
sourceLimit: MarshaledAString; // Pointer to the limit (end + 1) of source buffer.
target: PUChar; // Pointer to the target buffer.
targetLimit: PUChar; // Pointer to the limit (end + 1) of target buffer.
offsets: PInt32; // Pointer to the buffer that recieves the offsets.
end;
PUConverterFromUnicodeArgs = ^UConverterFromUnicodeArgs;
UConverterFromUnicodeArgs = record // http://icu-project.org/apiref/icu4c/structUConverterToUnicodeArgs.html
size: UInt16; // The size of this struct
flush: UBool; // The internal state of converter will be reset and data flushed if set to TRUE.
converter: PUConverter; // Pointer to the converter that is opened and to which this struct is passed as an argument.
source: MarshaledAString; // Pointer to the source source buffer.
sourceLimit: MarshaledAString; // Pointer to the limit (end + 1) of source buffer.
target: PUChar; // Pointer to the target buffer.
targetLimit: PUChar; // Pointer to the limit (end + 1) of target buffer.
offsets: PInt32; // Pointer to the buffer that recieves the offsets.
end;
//typedef void(* UConverterToUCallback )(const void *context, UConverterToUnicodeArgs *args, const char *codeUnits, int32_t length, UConverterCallbackReason reason, UErrorCode *pErrorCode)
// Function pointer for error callback in the codepage to unicode direction.
UConverterToUCallback = procedure(const context: Pointer; args: PUConverterToUnicodeArgs;
const codeUnits: MarshaledAString; aLength: Int32; reason: UConverterCallbackReason;
var ErrorCode: UErrorCode); cdecl;
//typedef void(* UConverterFromUCallback )(const void *context, UConverterFromUnicodeArgs *args, const UChar *codeUnits, int32_t length, UChar32 codePoint, UConverterCallbackReason reason, UErrorCode *pErrorCode)
// Function pointer for error callback in the unicode to codepage direction.
UConverterFromUCallBack = procedure(const context: Pointer; args: PUConverterFromUnicodeArgs;
const codeUnits: PUChar; aLength: Int32; codePoint: UChar32; reason: UConverterCallbackReason;
var ErrorCode: UErrorCode); cdecl;
{ ICU ucol.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucol_8h.html }
const
USCRIPT_UNKNOWN = 103; // From "uscript.h"
type
UCollationResult = (UCOL_LESS = -1, UCOL_EQUAL = 0, UCOL_GREATER = 1);
PUCollator = ^UCollator;
UCollator = record end;
// Enum containing attribute values for controling collation behavior.
UColAttributeValue = (
UCOL_DEFAULT = -1, UCOL_PRIMARY = 0, UCOL_SECONDARY = 1, UCOL_TERTIARY = 2, UCOL_DEFAULT_STRENGTH = UCOL_TERTIARY,
UCOL_CE_STRENGTH_LIMIT, UCOL_QUATERNARY = 3, UCOL_IDENTICAL = 15, UCOL_STRENGTH_LIMIT, UCOL_OFF = 16, UCOL_ON = 17,
UCOL_SHIFTED = 20, UCOL_NON_IGNORABLE = 21, UCOL_LOWER_FIRST = 24, UCOL_UPPER_FIRST = 25, UCOL_ATTRIBUTE_VALUE_COUNT
);
UCollationStrength = UColAttributeValue;
// Enum containing the codes for reordering segments of the collation table that are not script codes.
UColReorderCode = (
UCOL_REORDER_CODE_DEFAULT = -1, UCOL_REORDER_CODE_NONE = USCRIPT_UNKNOWN,
UCOL_REORDER_CODE_OTHERS = USCRIPT_UNKNOWN, UCOL_REORDER_CODE_SPACE = $1000,
UCOL_REORDER_CODE_FIRST = UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION = $1001,
UCOL_REORDER_CODE_SYMBOL = $1002, UCOL_REORDER_CODE_CURRENCY = $1003, UCOL_REORDER_CODE_DIGIT = $1004,
UCOL_REORDER_CODE_LIMIT = $1005
);
// Attributes that collation service understands.
UColAttribute = (
UCOL_FRENCH_COLLATION, UCOL_ALTERNATE_HANDLING, UCOL_CASE_FIRST, UCOL_CASE_LEVEL, UCOL_NORMALIZATION_MODE,
UCOL_DECOMPOSITION_MODE = UCOL_NORMALIZATION_MODE, UCOL_STRENGTH, UCOL_HIRAGANA_QUATERNARY_MODE = UCOL_STRENGTH + 1,
UCOL_NUMERIC_COLLATION = UCOL_STRENGTH + 2, UCOL_ATTRIBUTE_COUNT
);
//Options for retrieving the rule string.
UColRuleOption = (UCOL_TAILORING_ONLY, UCOL_FULL_RULES);
// enum that is taken by ucol_getBound API See below for explanation do not change
// the values assigned to the members of this enum.
UColBoundMode = (UCOL_BOUND_LOWER = 0, UCOL_BOUND_UPPER = 1, UCOL_BOUND_UPPER_LONG = 2, UCOL_BOUND_VALUE_COUNT);
{ ICU uloc.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/uloc_8h.html }
// Constants for *_getLocale() Allow user to select whether she wants information on requested, valid or actual locale.
ULocDataLocaleType = (
ULOC_ACTUAL_LOCALE = 0, ULOC_VALID_LOCALE = 1, ULOC_REQUESTED_LOCALE = 2, ULOC_DATA_LOCALE_TYPE_LIMIT = 3
);
// enums for the 'outResult' parameter return value
UAcceptResult = (ULOC_ACCEPT_FAILED = 0, ULOC_ACCEPT_VALID = 1, ULOC_ACCEPT_FALLBACK = 2);
const
// Useful constant for the maximum size of the language part of a locale ID.
ULOC_LANG_CAPACITY = 12;
// Useful constant for the maximum size of the country part of a locale ID (including the terminating NULL).
ULOC_COUNTRY_CAPACITY = 4;
// Useful constant for the maximum size of the whole locale ID (including the terminating NULL and all keywords).
ULOC_FULLNAME_CAPACITY = 157;
// Useful constant for the maximum size of the script part of a locale ID (including the terminating NULL).
ULOC_SCRIPT_CAPACITY = 6;
// Useful constant for the maximum size of keywords in a locale.
ULOC_KEYWORDS_CAPACITY = 50;
// Useful constant for the maximum total size of keywords and their values in a locale.
ULOC_KEYWORD_AND_VALUES_CAPACITY = 100;
// Invariant character separating keywords from the locale string.
ULOC_KEYWORD_SEPARATOR = '@';
// Unicode code point for '@' separating keywords from the locale string.
ULOC_KEYWORD_SEPARATOR_UNICODE = $40;
// Invariant character for assigning value to a keyword.
ULOC_KEYWORD_ASSIGN = '=';
// Unicode code point for '=' for assigning value to a keyword.
ULOC_KEYWORD_ASSIGN_UNICODE = $3D;
// Invariant character separating keywords.
ULOC_KEYWORD_ITEM_SEPARATOR = ';';
// Unicode code point for ';' separating keywords.
ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE = $3B;
{ ICU uloc.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/uloc_8h.html }
type
// A locale data object.
PULocaleData = ^ULocaleData;
ULocaleData = record end;
// The possible types of exemplar character sets.
ULocaleDataExemplarSetType = (
ULOCDATA_ES_STANDARD = 0, ULOCDATA_ES_AUXILIARY = 1, ULOCDATA_ES_INDEX = 2, ULOCDATA_ES_PUNCTUATION = 3,
ULOCDATA_ES_COUNT = 4
);
// The possible types of delimiters.
ULocaleDataDelimiterType = (
ULOCDATA_QUOTATION_START = 0, ULOCDATA_QUOTATION_END = 1, ULOCDATA_ALT_QUOTATION_START = 2,
ULOCDATA_ALT_QUOTATION_END = 3, ULOCDATA_DELIMITER_COUNT = 4
);
// Enumeration for representing the measurement systems.
UMeasurementSystem = (UMS_SI, UMS_US, UMS_LIMIT);
type
PUFieldPosition = ^UFieldPosition;
UFieldPosition = record
field: Int32;
beginIndex: Int32;
endIndex: Int32;
end;
const
U_PARSE_CONTEXT_LEN = 16;
type
PUParseError = ^UParseError;
UParseError = record
line: Int32; // The line on which the error occured.
offset: Int32; // The character offset to the error.
preContext : array [0..U_PARSE_CONTEXT_LEN-1] of UChar; // Textual context before the error.
postContext: array [0..U_PARSE_CONTEXT_LEN-1] of UChar; // The error itself and/or textual context after the error.
end;
{ unum.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/unum_8h.html }
// A number formatter. Dummy structure.
PUNumberFormat = ^UNumberFormat;
UNumberFormat = record end;
// The possible number format styles.
UNumberFormatStyle = (
UNUM_PATTERN_DECIMAL = 0, UNUM_DECIMAL = 1, UNUM_CURRENCY, UNUM_PERCENT, UNUM_SCIENTIFIC, UNUM_SPELLOUT,
UNUM_ORDINAL, UNUM_DURATION, UNUM_NUMBERING_SYSTEM, UNUM_PATTERN_RULEBASED, UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL,
UNUM_FORMAT_STYLE_COUNT, UNUM_DEFAULT = UNUM_DECIMAL, UNUM_IGNORE = UNUM_PATTERN_DECIMAL
);
// The possible number format rounding modes.
UNumberFormatRoundingMode = (
UNUM_ROUND_CEILING, UNUM_ROUND_FLOOR, UNUM_ROUND_DOWN, UNUM_ROUND_UP, UNUM_ROUND_HALFEVEN,
UNUM_FOUND_HALFEVEN = UNUM_ROUND_HALFEVEN, UNUM_ROUND_HALFDOWN, UNUM_ROUND_HALFUP, UNUM_ROUND_UNNECESSARY
);
// The possible number format pad positions. More...
UNumberFormatPadPosition = (
UNUM_PAD_BEFORE_PREFIX, UNUM_PAD_AFTER_PREFIX, UNUM_PAD_BEFORE_SUFFIX, UNUM_PAD_AFTER_SUFFIX
);
// Constants for specifying short or long format. More...
UNumberCompactStyle = ( UNUM_SHORT, UNUM_LONG );
// Constants for specifying currency spacing. More...
UCurrencySpacing = (
UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH, UNUM_CURRENCY_INSERT, UNUM_CURRENCY_SPACING_COUNT
);
// FieldPosition and UFieldPosition selectors for format fields defined by NumberFormat and UNumberFormat. More...
UNumberFormatFields = (
UNUM_INTEGER_FIELD, UNUM_FRACTION_FIELD, UNUM_DECIMAL_SEPARATOR_FIELD, UNUM_EXPONENT_SYMBOL_FIELD,
UNUM_EXPONENT_SIGN_FIELD, UNUM_EXPONENT_FIELD, UNUM_GROUPING_SEPARATOR_FIELD, UNUM_CURRENCY_FIELD,
UNUM_PERCENT_FIELD, UNUM_PERMILL_FIELD, UNUM_SIGN_FIELD, UNUM_FIELD_COUNT
);
// The possible UNumberFormat numeric attributes. More...
UNumberFormatAttribute = (
UNUM_PARSE_INT_ONLY, UNUM_GROUPING_USED, UNUM_DECIMAL_ALWAYS_SHOWN, UNUM_MAX_INTEGER_DIGITS,
UNUM_MIN_INTEGER_DIGITS, UNUM_INTEGER_DIGITS, UNUM_MAX_FRACTION_DIGITS, UNUM_MIN_FRACTION_DIGITS,
UNUM_FRACTION_DIGITS, UNUM_MULTIPLIER, UNUM_GROUPING_SIZE, UNUM_ROUNDING_MODE, UNUM_ROUNDING_INCREMENT,
UNUM_FORMAT_WIDTH, UNUM_PADDING_POSITION, UNUM_SECONDARY_GROUPING_SIZE, UNUM_SIGNIFICANT_DIGITS_USED,
UNUM_MIN_SIGNIFICANT_DIGITS, UNUM_MAX_SIGNIFICANT_DIGITS, UNUM_LENIENT_PARSE, UNUM_SCALE = UNUM_LENIENT_PARSE + 2,
UNUM_NUMERIC_ATTRIBUTE_COUNT, UNUM_MAX_NONBOOLEAN_ATTRIBUTE = $0FFF,
UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS = $1000, UNUM_PARSE_NO_EXPONENT, UNUM_LIMIT_BOOLEAN_ATTRIBUTE
);
// The possible UNumberFormat text attributes. More...
UNumberFormatTextAttribute = (
UNUM_POSITIVE_PREFIX, UNUM_POSITIVE_SUFFIX, UNUM_NEGATIVE_PREFIX, UNUM_NEGATIVE_SUFFIX,
UNUM_PADDING_CHARACTER, UNUM_CURRENCY_CODE, UNUM_DEFAULT_RULESET, UNUM_PUBLIC_RULESETS
);
// Constants for specifying a number format symbol. More...
UNumberFormatSymbol = (
UNUM_DECIMAL_SEPARATOR_SYMBOL = 0, UNUM_GROUPING_SEPARATOR_SYMBOL = 1, UNUM_PATTERN_SEPARATOR_SYMBOL = 2,
UNUM_PERCENT_SYMBOL = 3, UNUM_ZERO_DIGIT_SYMBOL = 4, UNUM_DIGIT_SYMBOL = 5, UNUM_MINUS_SIGN_SYMBOL = 6,
UNUM_PLUS_SIGN_SYMBOL = 7, UNUM_CURRENCY_SYMBOL = 8, UNUM_INTL_CURRENCY_SYMBOL = 9,
UNUM_MONETARY_SEPARATOR_SYMBOL = 10, UNUM_EXPONENTIAL_SYMBOL = 11, UNUM_PERMILL_SYMBOL = 12,
UNUM_PAD_ESCAPE_SYMBOL = 13, UNUM_INFINITY_SYMBOL = 14, UNUM_NAN_SYMBOL = 15, UNUM_SIGNIFICANT_DIGIT_SYMBOL = 16,
UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL = 17, UNUM_ONE_DIGIT_SYMBOL = 18, UNUM_TWO_DIGIT_SYMBOL = 19,
UNUM_THREE_DIGIT_SYMBOL = 20, UNUM_FOUR_DIGIT_SYMBOL = 21, UNUM_FIVE_DIGIT_SYMBOL = 22, UNUM_SIX_DIGIT_SYMBOL = 23,
UNUM_SEVEN_DIGIT_SYMBOL = 24, UNUM_EIGHT_DIGIT_SYMBOL = 25, UNUM_NINE_DIGIT_SYMBOL = 26, UNUM_FORMAT_SYMBOL_COUNT = 27
);
{ C API: DateFormat. Types and Enumerations}
{ http://www.icu-project.org/apiref/icu4c/udat_8h.html }
PUDateFormat = ^UDateFormat;
UDateFormat = record end;
//The possible date/time format styles.
UDateFormatStyle = (
UDAT_FULL, UDAT_LONG, UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT = UDAT_MEDIUM, UDAT_RELATIVE = 128,
UDAT_FULL_RELATIVE = UDAT_FULL + UDAT_RELATIVE, UDAT_LONG_RELATIVE = UDAT_LONG + UDAT_RELATIVE,
UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM + UDAT_RELATIVE, UDAT_SHORT_RELATIVE = UDAT_SHORT + UDAT_RELATIVE,
UDAT_NONE = -1, UDAT_PATTERN = -2, UDAT_IGNORE = UDAT_PATTERN
);
// FieldPosition and UFieldPosition selectors for format fields defined by DateFormat and UDateFormat.
UDateFormatField = (
UDAT_ERA_FIELD = 0, UDAT_YEAR_FIELD = 1, UDAT_MONTH_FIELD = 2, UDAT_DATE_FIELD = 3, UDAT_HOUR_OF_DAY1_FIELD = 4,
UDAT_HOUR_OF_DAY0_FIELD = 5, UDAT_MINUTE_FIELD = 6, UDAT_SECOND_FIELD = 7, UDAT_FRACTIONAL_SECOND_FIELD = 8,
UDAT_DAY_OF_WEEK_FIELD = 9, UDAT_DAY_OF_YEAR_FIELD = 10, UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11,
UDAT_WEEK_OF_YEAR_FIELD = 12, UDAT_WEEK_OF_MONTH_FIELD = 13, UDAT_AM_PM_FIELD = 14, UDAT_HOUR1_FIELD = 15,
UDAT_HOUR0_FIELD = 16, UDAT_TIMEZONE_FIELD = 17, UDAT_YEAR_WOY_FIELD = 18, UDAT_DOW_LOCAL_FIELD = 19,
UDAT_EXTENDED_YEAR_FIELD = 20, UDAT_JULIAN_DAY_FIELD = 21, UDAT_MILLISECONDS_IN_DAY_FIELD = 22,
UDAT_TIMEZONE_RFC_FIELD = 23, UDAT_TIMEZONE_GENERIC_FIELD = 24, UDAT_STANDALONE_DAY_FIELD = 25,
UDAT_STANDALONE_MONTH_FIELD = 26, UDAT_QUARTER_FIELD = 27, UDAT_STANDALONE_QUARTER_FIELD = 28,
UDAT_TIMEZONE_SPECIAL_FIELD = 29, UDAT_YEAR_NAME_FIELD = 30, UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD = 31,
UDAT_TIMEZONE_ISO_FIELD = 32, UDAT_TIMEZONE_ISO_LOCAL_FIELD = 33, UDAT_FIELD_COUNT = 34
);
// The possible types of date format symbols.
UDateFormatSymbolType = (
UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, UDAT_LOCALIZED_CHARS,
UDAT_ERA_NAMES, UDAT_NARROW_MONTHS, UDAT_NARROW_WEEKDAYS, UDAT_STANDALONE_MONTHS, UDAT_STANDALONE_SHORT_MONTHS,
UDAT_STANDALONE_NARROW_MONTHS, UDAT_STANDALONE_WEEKDAYS, UDAT_STANDALONE_SHORT_WEEKDAYS,
UDAT_STANDALONE_NARROW_WEEKDAYS, UDAT_QUARTERS, UDAT_SHORT_QUARTERS, UDAT_STANDALONE_QUARTERS,
UDAT_STANDALONE_SHORT_QUARTERS, UDAT_SHORTER_WEEKDAYS, UDAT_STANDALONE_SHORTER_WEEKDAYS
);
{ ucal.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucal_8h.html }
// A calendar. Dummy record.
PUCalendar = ^UCalendar;
UCalendar = record end;
// Possible types of UCalendars.
UCalendarType = (UCAL_TRADITIONAL, UCAL_DEFAULT = UCAL_TRADITIONAL, UCAL_GREGORIAN);
// Possible fields in a UCalendar.
UCalendarDateFields = (
UCAL_ERA, UCAL_YEAR, UCAL_MONTH, UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR,
UCAL_DAY_OF_WEEK, UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET, UCAL_YEAR_WOY, UCAL_DOW_LOCAL, UCAL_EXTENDED_YEAR,
UCAL_JULIAN_DAY, UCAL_MILLISECONDS_IN_DAY, UCAL_IS_LEAP_MONTH, UCAL_FIELD_COUNT, UCAL_DAY_OF_MONTH = UCAL_DATE
);
// Useful constant for days of week.
UCalendarDaysOfWeek = (
UCAL_SUNDAY = 1, UCAL_MONDAY, UCAL_TUESDAY, UCAL_WEDNESDAY, UCAL_THURSDAY, UCAL_FRIDAY, UCAL_SATURDAY
);
// Possible months in a UCalendar.
UCalendarMonths = (
UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY, UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER,
UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER
);
// Possible AM/PM values in a UCalendar.
UCalendarAMPMs = (UCAL_AM, UCAL_PM);
// System time zone type constants used by filtering zones in ucal_openTimeZoneIDEnumeration.
USystemTimeZoneType = (UCAL_ZONE_TYPE_ANY, UCAL_ZONE_TYPE_CANONICAL, UCAL_ZONE_TYPE_CANONICAL_LOCATION);
// Possible formats for a UCalendar's display name.
UCalendarDisplayNameType = (UCAL_STANDARD, UCAL_SHORT_STANDARD, UCAL_DST, UCAL_SHORT_DST);
// Types of UCalendar attributes.
UCalendarAttribute = (
UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK, UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME, UCAL_SKIPPED_WALL_TIME
);
// Options for handling ambiguous wall time at time zone offset transitions.
UCalendarWallTimeOption = (UCAL_WALLTIME_LAST, UCAL_WALLTIME_FIRST, UCAL_WALLTIME_NEXT_VALID);
// Possible limit values for a UCalendar.
UCalendarLimitType = (
UCAL_MINIMUM, UCAL_MAXIMUM, UCAL_GREATEST_MINIMUM, UCAL_LEAST_MAXIMUM, UCAL_ACTUAL_MINIMUM, UCAL_ACTUAL_MAXIMUM
);
// Time zone transition types for ucal_getTimeZoneTransitionDate.
UCalendarWeekdayType = (UCAL_WEEKDAY, UCAL_WEEKEND, UCAL_WEEKEND_ONSET, UCAL_WEEKEND_CEASE);
// Weekday types, as returned by ucal_getDayOfWeekType().
UTimeZoneTransitionType = (
UCAL_TZ_TRANSITION_NEXT, UCAL_TZ_TRANSITION_NEXT_INCLUSIVE,
UCAL_TZ_TRANSITION_PREVIOUS, UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE
);
{ C API: String Enumeration. Definition in file uenum.h. }
{ http://www.icu-project.org/apiref/icu4c/uenum_8h.html }
// structure representing an enumeration object instance
PUEnumeration = ^UEnumeration;
UEnumeration = record end;
var
{ Basic definitions for ICU }
//const char * u_getDataDirectory (void)
// u_getDataDirectory: function: MarshaledAString; cdecl;
{ http://www.icu-project.org/apiref/icu4c/utypes_8h.html }
// Return a string for a UErrorCode value.
u_errorName: function(code: UErrorCode): MarshaledAString; cdecl;
{ ICU ustring.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ustring_8h.html }
//int32_t u_strlen (const UChar *s)
// Determine the length of an array of UChar.
//int32_t u_countChar32 (const UChar *s, int32_t length)
// Count Unicode code points in the length UChar code units of the string.
//UBool u_strHasMoreChar32Than (const UChar *s, int32_t length, int32_t number)
// Check if the string contains more Unicode code points than a certain number.
//UChar * u_strcat (UChar *dst, const UChar *src)
// Concatenate two ustrings.
//UChar * u_strncat (UChar *dst, const UChar *src, int32_t n)
// Concatenate two ustrings.
//UChar * u_strstr (const UChar *s, const UChar *substring)
// Find the first occurrence of a substring in a string.
//UChar * u_strFindFirst (const UChar *s, int32_t length, const UChar *substring, int32_t subLength)
// Find the first occurrence of a substring in a string.
//UChar * u_strchr (const UChar *s, UChar c)
// Find the first occurrence of a BMP code point in a string.
//UChar * u_strchr32 (const UChar *s, UChar32 c)
// Find the first occurrence of a code point in a string.
//UChar * u_strrstr (const UChar *s, const UChar *substring)
// Find the last occurrence of a substring in a string.
//UChar * u_strFindLast (const UChar *s, int32_t length, const UChar *substring, int32_t subLength)
// Find the last occurrence of a substring in a string.
//UChar * u_strrchr (const UChar *s, UChar c)
// Find the last occurrence of a BMP code point in a string.
//UChar * u_strrchr32 (const UChar *s, UChar32 c)
// Find the last occurrence of a code point in a string.
//UChar * u_strpbrk (const UChar *string, const UChar *matchSet)
// Locates the first occurrence in the string string of any of the characters in the string matchSet.
//int32_t u_strcspn (const UChar *string, const UChar *matchSet)
// Returns the number of consecutive characters in string, beginning with the first, that do not occur somewhere in matchSet.
//int32_t u_strspn (const UChar *string, const UChar *matchSet)
// Returns the number of consecutive characters in string, beginning with the first, that occur somewhere in matchSet.
//UChar * u_strtok_r (UChar *src, const UChar *delim, UChar **saveState)
// The string tokenizer API allows an application to break a string into tokens.
// Compare two Unicode strings for bitwise equality (code unit order).
u_strcmp: function(const s1: PUChar; const s2: PUChar): Int32; cdecl;
// Compare two Unicode strings for CodePoint Order equality (code point order).
// u_strcmpCodePointOrder: function(const s1: PUChar; const s2: PUChar): Int32; cdecl;
//int32_t u_strCompare (const UChar *s1, int32_t length1, const UChar *s2, int32_t length2, UBool codePointOrder)
// Compare two Unicode strings (binary order).
//int32_t u_strCompareIter (UCharIterator *iter1, UCharIterator *iter2, UBool codePointOrder)
// Compare two Unicode strings (binary order) as presented by UCharIterator objects.
// Compare two strings case-insensitively using full case folding.
// u_strCaseCompare: function(const s1:PUChar; length1: Int32; const s2:PUChar; length2: Int32; options: UInt32;
// var ErrorCode: UErrorCode): Int32; cdecl;
// Compare two Unicode strings for bitwise equality (code unit order).
// u_strncmp: function(const s1: PUChar; const s2: PUChar; n: Int32): Int32; cdecl;
//int32_t u_strncmpCodePointOrder (const UChar *s1, const UChar *s2, int32_t n)
// Compare two Unicode strings in code point order.
// u_strncmpCodePointOrder: function(const s1: PUChar; const s2: PUChar; n: Int32): Int32; cdecl;
// Compare two strings case-insensitively using full case folding.
// u_strcasecmp: function(const s1:PUChar; const s2:PUChar; options: Int32): Int32; cdecl;
// Compare two strings case-insensitively using full case folding.
// u_strncasecmp: function(const s1:PUChar; const s2:PUChar; aLength, options: Int32): Int32; cdecl;
// Compare two strings case-insensitively using full case folding.
// u_memcasecmp: function(const s1:PUChar; const s2:PUChar; aLength, options: Int32): Int32; cdecl;
// Copy a ustring.
// u_strcpy: function(dst:PUChar; const src: PUChar): PUChar; cdecl;
// Copy a ustring.
// u_strncpy: function(dst:PUChar; const src: PUChar; n: Int32): PUChar; cdecl;
// Copy a byte string encoded in the default codepage to a ustring.
// u_uastrcpy: function(dst:PUChar; const src: MarshaledAString): PUChar; cdecl;
// Copy a byte string encoded in the default codepage to a ustring.
// u_uastrncpy: function(dst:PUChar; const src: MarshaledAString; n: Int32): PUChar; cdecl;
// Copy ustring to a byte string encoded in the default codepage.
// u_austrcpy: function(dst:MarshaledAString; const src: PUChar): MarshaledAString; cdecl;
// Copy ustring to a byte string encoded in the default codepage.
// u_austrncpy: function(dst:MarshaledAString; const src: PUChar; n: Int32): MarshaledAString; cdecl;
//UChar * u_memcpy (UChar *dest, const UChar *src, int32_t count)
// Synonym for memcpy(), but with UChars only.
//UChar * u_memmove (UChar *dest, const UChar *src, int32_t count)
// Synonym for memmove(), but with UChars only.
//UChar * u_memset (UChar *dest, UChar c, int32_t count)
// Initialize count characters of dest to c.
//int32_t u_memcmp (const UChar *buf1, const UChar *buf2, int32_t count)
// Compare the first count UChars of each buffer.
//int32_t u_memcmpCodePointOrder (const UChar *s1, const UChar *s2, int32_t count)
// Compare two Unicode strings in code point order.
//UChar * u_memchr (const UChar *s, UChar c, int32_t count)
// Find the first occurrence of a BMP code point in a string.
//UChar * u_memchr32 (const UChar *s, UChar32 c, int32_t count)
// Find the first occurrence of a code point in a string.
//UChar * u_memrchr (const UChar *s, UChar c, int32_t count)
// Find the last occurrence of a BMP code point in a string.
//UChar * u_memrchr32 (const UChar *s, UChar32 c, int32_t count)
// Find the last occurrence of a code point in a string.
//int32_t u_unescape (const char *src, UChar *dest, int32_t destCapacity)
// Unescape a string of characters and write the resulting Unicode characters to the destination buffer.
//UChar32 u_unescapeAt (UNESCAPE_CHAR_AT charAt, int32_t *offset, int32_t length, void *context)
// Unescape a single sequence.
// Uppercase the characters in a string.
u_strToUpper: function(dest: PUChar; destCapaciy: Int32; const src: PUChar;
srcLength: Int32; const locale: MarshaledAString; var ErrorCode:UErrorCode): Int32; cdecl;
// Lowercase the characters in a string.
u_strToLower: function(dest: PUChar; destCapaciy: Int32; const src: PUChar;
srcLength: Int32; const locale: MarshaledAString; var ErrorCode:UErrorCode): Int32; cdecl;
//int32_t u_strToTitle (UChar *dest, int32_t destCapacity, const UChar *src, int32_t srcLength, UBreakIterator *titleIter, const char *locale, UErrorCode *pErrorCode)
// Titlecase a string.
//int32_t u_strFoldCase (UChar *dest, int32_t destCapacity, const UChar *src, int32_t srcLength, uint32_t options, UErrorCode *pErrorCode)
// Case-folds the characters in a string.
//wchar_t * u_strToWCS (wchar_t *dest, int32_t destCapacity, int32_t *pDestLength, const UChar *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a UTF-16 string to a wchar_t string.
//UChar * u_strFromWCS (UChar *dest, int32_t destCapacity, int32_t *pDestLength, const wchar_t *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a wchar_t string to UTF-16.
// Convert a UTF-16 string to UTF-8.
// u_strToUTF8: function(dest: MarshaledAString; destCapacity: Int32; var DestLength: Int32;
// const src: PUChar; srcLength: Int32; var ErrorCode: UErrorCode): MarshaledAString; cdecl;
//Convert a UTF-8 string to UTF-16.
// u_strFromUTF8: function(dest: PUChar; destCapacity: Int32; var DestLength: Int32;
// const src: MarshaledAString; srcLength: Int32; var ErrorCode: UErrorCode): PUChar; cdecl;
//char * u_strToUTF8WithSub (char *dest, int32_t destCapacity, int32_t *pDestLength, const UChar *src, int32_t srcLength, UChar32 subchar, int32_t *pNumSubstitutions, UErrorCode *pErrorCode)
// Convert a UTF-16 string to UTF-8.
//Convert a UTF-8 string to UTF-16 with Sub.
// u_strFromUTF8WithSub: function(dest: PUChar; destCapacity: Int32; var DestLength: Int32;
// const src: MarshaledAString; srcLength: Int32; subchar: UChar32; var NumSubstitutions: Int32;
// var ErrorCode: UErrorCode): PUChar; cdecl;
//UChar * u_strFromUTF8Lenient (UChar *dest, int32_t destCapacity, int32_t *pDestLength, const char *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a UTF-8 string to UTF-16.
//UChar32 * u_strToUTF32 (UChar32 *dest, int32_t destCapacity, int32_t *pDestLength, const UChar *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a UTF-16 string to UTF-32.
//UChar * u_strFromUTF32 (UChar *dest, int32_t destCapacity, int32_t *pDestLength, const UChar32 *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a UTF-32 string to UTF-16.
//UChar32 * u_strToUTF32WithSub (UChar32 *dest, int32_t destCapacity, int32_t *pDestLength, const UChar *src, int32_t srcLength, UChar32 subchar, int32_t *pNumSubstitutions, UErrorCode *pErrorCode)
// Convert a UTF-16 string to UTF-32.
//UChar * u_strFromUTF32WithSub (UChar *dest, int32_t destCapacity, int32_t *pDestLength, const UChar32 *src, int32_t srcLength, UChar32 subchar, int32_t *pNumSubstitutions, UErrorCode *pErrorCode)
// Convert a UTF-32 string to UTF-16.
//char * u_strToJavaModifiedUTF8 (char *dest, int32_t destCapacity, int32_t *pDestLength, const UChar *src, int32_t srcLength, UErrorCode *pErrorCode)
// Convert a 16-bit Unicode string to Java Modified UTF-8.
//UChar * u_strFromJavaModifiedUTF8WithSub (UChar *dest, int32_t destCapacity, int32_t *pDestLength, const char *src, int32_t srcLength, UChar32 subchar, int32_t *pNumSubstitutions, UErrorCode *pErrorCode)
// Convert a Java Modified UTF-8 string to a 16-bit Unicode string.
{ ICU ucnv.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucnv_8h.html }
// Do a fuzzy compare of two converter/alias names.
// int ucnv_compareNames (const char *name1, const char *name2)
// ucnv_compareNames: function(const name1, name2: MarshaledAString): Integer; cdecl;
// Creates a UConverter object with the name of a coded character set specified as a C string.
ucnv_open: function(converterName: MarshaledAString; var err: UErrorCode): PUConverter; cdecl;
// Creates a Unicode converter with the names specified as unicode string.
// ucnv_openU: function(name: MarshaledAString; var err: UErrorCode): PUConverter; cdecl;
// Creates a UConverter object from a CCSID number and platform pair.
// ucnv_openCCSID: function(codePage: Int32; aPlatform: UConverterPlatform; var err: UErrorCode): PUConverter; cdecl;
// UConverter * ucnv_openPackage (const char *packageName, const char *converterName, UErrorCode *err)
// Creates a UConverter object specified from a packageName and a converterName.
// ucnv_openPackage: function(const packageName, converterName: MarshaledAString; var err: UErrorCode): PUConverter; cdecl;
//UConverter * ucnv_safeClone (const UConverter *cnv, void *stackBuffer, int32_t *pBufferSize, UErrorCode *status)
// Thread safe converter cloning operation.
// ucnv_safeClone: function(const cnv: PUConverter; stackBuffer: Pointer; pBufferSize: PInt32;
// var status: UErrorCode): PUConverter; cdecl;
// Deletes the unicode converter and releases resources associated with just this instance.
ucnv_close: procedure(converter: PUConverter); cdecl;
//void ucnv_getSubstChars (const UConverter *converter, char *subChars, int8_t *len, UErrorCode *err)
// Fills in the output parameter, subChars, with the substitution characters as multiple bytes.
// Sets the substitution chars when converting from unicode to a codepage.
// ucnv_setSubstChars: procedure(converter: PUConverter; subChars: MarshaledAString;
// len: word; var err: UErrorCode); cdecl;
//Fills in the output parameter, errBytes, with the error characters from the last failing conversion.
// ucnv_getInvalidChars: function(cnv: PUConverter; errBytes: MarshaledAString;
// var len: ShortInt; var ErrorCode: UErrorCode): Int32; cdecl;
//Fills in the output parameter, errChars, with the error characters from the last failing conversion.
// ucnv_getInvalidUChars: function(cnv: PUConverter; errUChars: PUChar; var len: ShortInt;
// var ErrorCode: UErrorCode): Int32; cdecl;
//Resets the state of a converter to the default state.
// ucnv_reset: procedure(converter: PUConverter); cdecl;
//void ucnv_resetToUnicode (UConverter *converter)
// Resets the to-Unicode part of a converter state to the default state.
//void ucnv_resetFromUnicode (UConverter *converter)
// Resets the from-Unicode part of a converter state to the default state.
// Returns the maximum number of bytes that are output per UChar in conversion
// from Unicode using this converter.
ucnv_getMaxCharSize: function (const converter: PUConverter): Int8; cdecl;
// Returns the minimum byte length for characters in this codepage.
// ucnv_getMinCharSize: function (const converter: PUConverter): Int8; cdecl;
// Returns the display name of the converter passed in based on the Locale passed in.
ucnv_getDisplayName: function (const converter: PUConverter; displayLocale: MarshaledAString;
displayName: PUChar;displayNameCapacity: Int32; var err: UErrorCode ): Int32; cdecl;
// Gets the internal, canonical name of the converter (zero-terminated).
ucnv_getName: function (const converter:PUConverter; var err: UErrorCode ): MarshaledAString; cdecl;
// Gets a codepage number associated with the converter.
// ucnv_getCCSID: function (const converter: PUConverter; var err: UErrorCode ): Int32; cdecl;
//UConverterPlatform ucnv_getPlatform (const UConverter *converter, UErrorCode *err)
// Gets a codepage platform associated with the converter.
//UConverterType ucnv_getType (const UConverter *converter)
// Gets the type of the converter e.g.
//void ucnv_getStarters (const UConverter *converter, UBool starters[256], UErrorCode *err)
// Gets the "starter" (lead) bytes for converters of type MBCS.
//void ucnv_getUnicodeSet (const UConverter *cnv, USet *setFillIn, UConverterUnicodeSet whichSet, UErrorCode *pErrorCode)
// Returns the set of Unicode code points that can be converted by an ICU converter.
//void ucnv_getToUCallBack (const UConverter *converter, UConverterToUCallback *action, const void **context)
// Gets the current calback function used by the converter when an illegal or invalid codepage sequence is found.
//void ucnv_getFromUCallBack (const UConverter *converter, UConverterFromUCallback *action, const void **context)
// Gets the current callback function used by the converter when illegal or invalid Unicode sequence is found.
//Changes the callback function used by the converter when an illegal or invalid sequence is found.
// ucnv_setToUCallBack: procedure(cnv: PUConverter; newAction: UConverterFromUCallback; newContext: Pointer;
// oldAction: UConverterFromUCallback; oldContext: PPointer; var ErrorCode: UErrorCode); cdecl;
//Changes the current callback function used by the converter when an illegal or invalid sequence is found.
// ucnv_setFromUCallBack: procedure(cnv: PUConverter; newAction: UConverterFromUCallback; newContext: Pointer;
// oldAction: UConverterFromUCallback; oldContext: PPointer; var ErrorCode: UErrorCode); cdecl;
//void ucnv_fromUnicode (UConverter *converter, char **target, const char *targetLimit, const UChar **source, const UChar *sourceLimit, int32_t *offsets, UBool flush, UErrorCode *err)
// Converts an array of unicode characters to an array of codepage characters.
// Converts a buffer of codepage bytes into an array of unicode UChars characters.
// ucnv_toUnicode: procedure(Converter: PUConverter; var Target: PUChar; TargetLimit: PUChar;
// var Source: MarshaledAString; sourceLimit: MarshaledAString; var offsets: Int32;
// flush: UBool; var err: UErrorcode); cdecl;
//Convert the Unicode string into a codepage string using an existing UConverter.
// ucnv_fromUChars: function(cnv: PUConverter; dest: MarshaledAString; destCapacity: Int32;
// const src: PUChar; srcLength: Int32; var ErrorCode: UErrorCode): Int32; cdecl;
//Convert the codepage string into a Unicode string using an existing UConverter.
// ucnv_toUChars: function(cnv: PUConverter; dest: PUChar; destCapacity: Int32; const src: MarshaledAString;
// srcLength: Int32; var ErrorCode: UErrorCode): Int32; cdecl;
//UChar32 ucnv_getNextUChar (UConverter *converter, const char **source, const char *sourceLimit, UErrorCode *err)
// Convert a codepage buffer into Unicode one character at a time.
//void ucnv_convertEx (UConverter *targetCnv, UConverter *sourceCnv, char **target, const char *targetLimit, const char **source, const char *sourceLimit, UChar *pivotStart, UChar **pivotSource, UChar **pivotTarget, const UChar *pivotLimit, UBool reset, UBool flush, UErrorCode *pErrorCode)
// Convert from one external charset to another using two existing UConverters.
//int32_t ucnv_convert (const char *toConverterName, const char *fromConverterName, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode)
// Convert from one external charset to another.
//int32_t ucnv_toAlgorithmic (UConverterType algorithmicType, UConverter *cnv, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode)
// Convert from one external charset to another.
//int32_t ucnv_fromAlgorithmic (UConverter *cnv, UConverterType algorithmicType, char *target, int32_t targetCapacity, const char *source, int32_t sourceLength, UErrorCode *pErrorCode)
// Convert from one external charset to another.
//int32_t ucnv_flushCache (void)
// Frees up memory occupied by unused, cached converter shared data.
// Returns the number of available converters, as per the alias file.
// ucnv_countAvailable: function: Int32; cdecl;
// Gets the canonical converter name of the specified converter from a list
// of all available converters contaied in the alias file.
// All converters in this list can be opened.
// ucnv_getAvailableName: function(index: Int32): MarshaledAString; cdecl;
//UEnumeration * ucnv_openAllNames (UErrorCode *pErrorCode)
// Returns a UEnumeration to enumerate all of the canonical converter names, as per the alias file, regardless of the ability to open each converter.
//uint16_t ucnv_countAliases (const char *alias, UErrorCode *pErrorCode)
// Gives the number of aliases for a given converter or alias name.
// ucnv_countAliases: function(const alias: MarshaledAString; var ErrorCode: UErrorCode): UInt16; cdecl;
//const char * ucnv_getAlias (const char *alias, uint16_t n, UErrorCode *pErrorCode)
// Gives the name of the alias at given index of alias list.
// ucnv_getAlias: function(const alias: MarshaledAString; n: UInt16; var ErrorCode: UErrorCode): MarshaledAString; cdecl;
//void ucnv_getAliases (const char *alias, const char **aliases, UErrorCode *pErrorCode)
// Fill-up the list of alias names for the given alias.
// ucnv_getAliases: procedure(const alias: MarshaledAString; const aliases: PMarshaledAString; var ErrorCode: UErrorCode); cdecl;
//UEnumeration * ucnv_openStandardNames (const char *convName, const char *standard, UErrorCode *pErrorCode)
// Return a new UEnumeration object for enumerating all the alias names for a given converter that are recognized by a standard.
//uint16_t ucnv_countStandards (void)
// Gives the number of standards associated to converter names.
//const char * ucnv_getStandard (uint16_t n, UErrorCode *pErrorCode)
// Gives the name of the standard at given index of standard list.
// Returns a standard name for a given converter name.
ucnv_getStandardName: function (name: MarshaledAString; standard: MarshaledAString;
var err: UErrorCode ): MarshaledAString; cdecl;
//const char * ucnv_getCanonicalName (const char *alias, const char *standard, UErrorCode *pErrorCode)
// This function will return the internal canonical converter name of the tagged alias.
//const char * ucnv_getDefaultName (void)
// Returns the current default converter name.
//void ucnv_setDefaultName (const char *name)
// This function is not thread safe.
//void ucnv_fixFileSeparator (const UConverter *cnv, UChar *source, int32_t sourceLen)
// Fixes the backslash character mismapping.
//UBool ucnv_isAmbiguous (const UConverter *cnv)
// Determines if the converter contains ambiguous mappings of the same character or not.
//void ucnv_setFallback (UConverter *cnv, UBool usesFallback)
// Sets the converter to use fallback mappings or not.
//UBool ucnv_usesFallback (const UConverter *cnv)
// Determines if the converter uses fallback mappings or not.
//const char * ucnv_detectUnicodeSignature (const char *source, int32_t sourceLength, int32_t *signatureLength, UErrorCode *pErrorCode)
// Detects Unicode signature byte sequences at the start of the byte stream and returns the charset name of the indicated Unicode charset.
//int32_t ucnv_fromUCountPending (const UConverter *cnv, UErrorCode *status)
// Returns the number of UChars held in the converter's internal state because more input is needed for completing the conversion.
//int32_t ucnv_toUCountPending (const UConverter *cnv, UErrorCode *status)
// Returns the number of chars held in the converter's internal state because more input is needed for completing the conversion.
//UBool ucnv_isFixedWidth (UConverter *cnv, UErrorCode *status)
// Returns whether or not the charset of the converter has a fixed number of bytes per charset character.
//Fills in the output parameter, errBytes, with the error characters from the last failing conversion.
// ucnv_cbToUWriteUChars: procedure(args: PUConverterToUnicodeArgs; const source: PUChar;
// length: Int32; offsetIndex: Int32; var ErrorCode: UErrorCode); cdecl;
{ ICU uchar.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/uchar_8h.html }
// UBool u_hasBinaryProperty (UChar32 c, UProperty which)
// Check a binary Unicode property for a code point.
//UBool u_isUAlphabetic (UChar32 c)
// Check if a code point has the Alphabetic Unicode property.
//UBool u_isULowercase (UChar32 c)
// Check if a code point has the Lowercase Unicode property.
//UBool u_isUUppercase (UChar32 c)
// Check if a code point has the Uppercase Unicode property.
//UBool u_isUWhiteSpace (UChar32 c)
// Check if a code point has the White_Space Unicode property.
//int32_t u_getIntPropertyValue (UChar32 c, UProperty which)
// Get the property value for an enumerated or integer Unicode property for a code point.
//int32_t u_getIntPropertyMinValue (UProperty which)
// Get the minimum value for an enumerated/integer/binary Unicode property.
//int32_t u_getIntPropertyMaxValue (UProperty which)
// Get the maximum value for an enumerated/integer/binary Unicode property.
//double u_getNumericValue (UChar32 c)
// Get the numeric value for a Unicode code point as defined in the Unicode Character Database.
//UBool u_islower (UChar32 c)
// Determines whether the specified code point has the general category "Ll" (lowercase letter).
//UBool u_isupper (UChar32 c)
// Determines whether the specified code point has the general category "Lu" (uppercase letter).
//UBool u_istitle (UChar32 c)
// Determines whether the specified code point is a titlecase letter.
//UBool u_isdigit (UChar32 c)
// Determines whether the specified code point is a digit character according to Java.
//UBool u_isalpha (UChar32 c)
// Determines whether the specified code point is a letter character.
//UBool u_isalnum (UChar32 c)
// Determines whether the specified code point is an alphanumeric character (letter or digit) according to Java.
//UBool u_isxdigit (UChar32 c)
// Determines whether the specified code point is a hexadecimal digit.
//UBool u_ispunct (UChar32 c)
// Determines whether the specified code point is a punctuation character.
//UBool u_isgraph (UChar32 c)
// Determines whether the specified code point is a "graphic" character (printable, excluding spaces).
//UBool u_isblank (UChar32 c)
// Determines whether the specified code point is a "blank" or "horizontal space", a character that visibly separates words on a line.
//UBool u_isdefined (UChar32 c)
// Determines whether the specified code point is "defined", which usually means that it is assigned a character.
//UBool u_isspace (UChar32 c)
// Determines if the specified character is a space character or not.
//UBool u_isJavaSpaceChar (UChar32 c)
// Determine if the specified code point is a space character according to Java.
//UBool u_isWhitespace (UChar32 c)
// Determines if the specified code point is a whitespace character according to Java/ICU.
//UBool u_iscntrl (UChar32 c)
// Determines whether the specified code point is a control character (as defined by this function).
//UBool u_isISOControl (UChar32 c)
// Determines whether the specified code point is an ISO control code.
//UBool u_isprint (UChar32 c)
// Determines whether the specified code point is a printable character.
//UBool u_isbase (UChar32 c)
// Determines whether the specified code point is a base character.
//UCharDirection u_charDirection (UChar32 c)
// Returns the bidirectional category value for the code point, which is used in the Unicode bidirectional algorithm (UAX #9 http://www.unicode.org/reports/tr9/).
//UBool u_isMirrored (UChar32 c)
// Determines whether the code point has the Bidi_Mirrored property.
//UChar32 u_charMirror (UChar32 c)
// Maps the specified character to a "mirror-image" character.
//UChar32 u_getBidiPairedBracket (UChar32 c)
// Maps the specified character to its paired bracket character.
//int8_t u_charType (UChar32 c)
// Returns the general category value for the code point.
//void u_enumCharTypes (UCharEnumTypeRange *enumRange, const void *context)
// Enumerate efficiently all code points with their Unicode general categories.
//uint8_t u_getCombiningClass (UChar32 c)
// Returns the combining class of the code point as specified in UnicodeData.txt.
//int32_t u_charDigitValue (UChar32 c)
// Returns the decimal digit value of a decimal digit character.
//UBlockCode ublock_getCode (UChar32 c)
// Returns the Unicode allocation block that contains the character.
//int32_t u_charName (UChar32 code, UCharNameChoice nameChoice, char *buffer, int32_t bufferLength, UErrorCode *pErrorCode)
// Retrieve the name of a Unicode character.
//int32_t u_getISOComment (UChar32 c, char *dest, int32_t destCapacity, UErrorCode *pErrorCode)
// Returns an empty string.
//UChar32 u_charFromName (UCharNameChoice nameChoice, const char *name, UErrorCode *pErrorCode)
// Find a Unicode character by its name and return its code point value.
//void u_enumCharNames (UChar32 start, UChar32 limit, UEnumCharNamesFn *fn, void *context, UCharNameChoice nameChoice, UErrorCode *pErrorCode)
// Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name.
//const char * u_getPropertyName (UProperty property, UPropertyNameChoice nameChoice)
// Return the Unicode name for a given property, as given in the Unicode database file PropertyAliases.txt.
//UProperty u_getPropertyEnum (const char *alias)
// Return the UProperty enum for a given property name, as specified in the Unicode database file PropertyAliases.txt.
//const char * u_getPropertyValueName (UProperty property, int32_t value, UPropertyNameChoice nameChoice)
// Return the Unicode name for a given property value, as given in the Unicode database file PropertyValueAliases.txt.
//int32_t u_getPropertyValueEnum (UProperty property, const char *alias)
// Return the property value integer for a given value name, as specified in the Unicode database file PropertyValueAliases.txt.
//UBool u_isIDStart (UChar32 c)
// Determines if the specified character is permissible as the first character in an identifier according to Unicode (The Unicode Standard, Version 3.0, chapter 5.16 Identifiers).
//UBool u_isIDPart (UChar32 c)
// Determines if the specified character is permissible in an identifier according to Java.
//UBool u_isIDIgnorable (UChar32 c)
// Determines if the specified character should be regarded as an ignorable character in an identifier, according to Java.
//UBool u_isJavaIDStart (UChar32 c)
// Determines if the specified character is permissible as the first character in a Java identifier.
//UBool u_isJavaIDPart (UChar32 c)
// Determines if the specified character is permissible in a Java identifier.
// The given character is mapped to its lowercase equivalent according to UnicodeData.txt;
// if the character has no lowercase equivalent, the character itself is returned.
u_tolower: function(c: UChar32): UChar32; cdecl;
// The given character is mapped to its uppercase equivalent according to UnicodeData.txt;
// if the character has no uppercase equivalent, the character itself is returned.
u_toupper: function(c: UChar32): UChar32; cdecl;
//UChar32 u_totitle (UChar32 c)
// The given character is mapped to its titlecase equivalent according to UnicodeData.txt; if none is defined, the character itself is returned.
//UChar32 u_foldCase (UChar32 c, uint32_t options)
// The given character is mapped to its case folding equivalent according to UnicodeData.txt and CaseFolding.txt; if the character has no case folding equivalent, the character itself is returned.
//int32_t u_digit (UChar32 ch, int8_t radix)
// Returns the decimal digit value of the code point in the specified radix.
//UChar32 u_forDigit (int32_t digit, int8_t radix)
// Determines the character representation for a specific digit in the specified radix.
//void u_charAge (UChar32 c, UVersionInfo versionArray)
// Get the "age" of the code point.
//void u_getUnicodeVersion (UVersionInfo versionArray)
// Gets the Unicode version information.
//int32_t u_getFC_NFKC_Closure (UChar32 c, UChar *dest, int32_t destCapacity, UErrorCode *pErrorCode)
// Get the FC_NFKC_Closure property string for a character.
{ ICU uloc.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/uloc_8h.html }
// Gets ICU's default locale.
// uloc_getDefault: function: MarshaledAString; cdecl;
// Sets ICU's default locale.
// uloc_setDefault: procedure(const localeID: MarshaledAString; var status: UErrorCode); cdecl;
// Gets the language code for the specified locale.
// uloc_getLanguage: function(const localeID: MarshaledAString; language: MarshaledAString;
// languageCapacity: Int32; var errCode: UErrorCode): Int32; cdecl;
// Gets the script code for the specified locale.
// uloc_getScript: function(const localeID: MarshaledAString; script: MarshaledAString;
// scriptCapacity: Int32; var err: UErrorCode): Int32; cdecl;
// Gets the country code for the specified locale.
// uloc_getCountry: function(const localeID: MarshaledAString; country: MarshaledAString;
// countryCapacity: Int32; var err: UErrorCode): Int32; cdecl;
// Gets the variant code for the specified locale.
// uloc_getVariant: function(const localeID: MarshaledAString; variant: MarshaledAString;
// variantCapacity: Int32; var err: UErrorCode): Int32; cdecl;
// Gets the full name for the specified locale.
// uloc_getName: function(const localeID: MarshaledAString; name: MarshaledAString;
// nameCapacity: Int32; var err: UErrorCode): Int32; cdecl;
// Gets the full name for the specified locale.
uloc_canonicalize: function(const localeID: MarshaledAString; name: MarshaledAString;
nameCapacity: Int32; var err: UErrorCode): Int32; cdecl;
// Gets the ISO language code for the specified locale.
// uloc_getISO3Language: function(const localeID: MarshaledAString): MarshaledAString; cdecl;
// Gets the ISO country code for the specified locale.
// uloc_getISO3Country: function(const localeID: MarshaledAString): MarshaledAString; cdecl;
//uint32_t uloc_getLCID (const char *localeID)
// Gets the Win32 LCID value for the specified locale.
// uloc_getLCID: function(const localeID: MarshaledAString): UInt32; cdecl;
//int32_t uloc_getDisplayLanguage (const char *locale, const char *displayLocale, UChar *language, int32_t languageCapacity, UErrorCode *status)
// Gets the language name suitable for display for the specified locale.
//int32_t uloc_getDisplayScript (const char *locale, const char *displayLocale, UChar *script, int32_t scriptCapacity, UErrorCode *status)
// Gets the script name suitable for display for the specified locale.
//int32_t uloc_getDisplayCountry (const char *locale, const char *displayLocale, UChar *country, int32_t countryCapacity, UErrorCode *status)
// Gets the country name suitable for display for the specified locale.
//int32_t uloc_getDisplayVariant (const char *locale, const char *displayLocale, UChar *variant, int32_t variantCapacity, UErrorCode *status)
// Gets the variant name suitable for display for the specified locale.
//int32_t uloc_getDisplayKeyword (const char *keyword, const char *displayLocale, UChar *dest, int32_t destCapacity, UErrorCode *status)
// Gets the keyword name suitable for display for the specified locale.
//int32_t uloc_getDisplayKeywordValue (const char *locale, const char *keyword, const char *displayLocale, UChar *dest, int32_t destCapacity, UErrorCode *status)
// Gets the value of the keyword suitable for display for the specified locale.
//int32_t uloc_getDisplayName (const char *localeID, const char *inLocaleID, UChar *result, int32_t maxResultSize, UErrorCode *err)
// Gets the full name suitable for display for the specified locale.
// Gets the specified locale from a list of all available locales.
uloc_getAvailable: function(n: Int32): MarshaledAString; cdecl;
// Gets the size of the all available locale list.
uloc_countAvailable: function: Int32; cdecl;
//const char *const * uloc_getISOLanguages (void)
// Gets a list of all available 2-letter language codes defined in ISO 639, plus additional 3-letter codes determined to be useful for locale generation as defined by Unicode CLDR.
//const char *const * uloc_getISOCountries (void)
// Gets a list of all available 2-letter country codes defined in ISO 639.
//int32_t uloc_getParent (const char *localeID, char *parent, int32_t parentCapacity, UErrorCode *err)
// Truncate the locale ID string to get the parent locale ID.
//int32_t uloc_getBaseName (const char *localeID, char *name, int32_t nameCapacity, UErrorCode *err)
// Gets the full name for the specified locale.
uloc_getBaseName: function(const localeID: MarshaledAString; name: MarshaledAString;
nameCapacity: Int32; var err: UErrorCode): Int32; cdecl;
//UEnumeration * uloc_openKeywords (const char *localeID, UErrorCode *status)
// Gets an enumeration of keywords for the specified locale.
//int32_t uloc_getKeywordValue (const char *localeID, const char *keywordName, char *buffer, int32_t bufferCapacity, UErrorCode *status)
// Get the value for a keyword.
//int32_t uloc_setKeywordValue (const char *keywordName, const char *keywordValue, char *buffer, int32_t bufferCapacity, UErrorCode *status)
// Set the value of the specified keyword.
//ULayoutType uloc_getCharacterOrientation (const char *localeId, UErrorCode *status)
// Get the layout character orientation for the specified locale.
//ULayoutType uloc_getLineOrientation (const char *localeId, UErrorCode *status)
// Get the layout line orientation for the specified locale.
//int32_t uloc_acceptLanguageFromHTTP (char *result, int32_t resultAvailable, UAcceptResult *outResult, const char *httpAcceptLanguage, UEnumeration *availableLocales, UErrorCode *status)
// Based on a HTTP header from a web browser and a list of available locales, determine an acceptable locale for the user.
//int32_t uloc_acceptLanguage (char *result, int32_t resultAvailable, UAcceptResult *outResult,
// const char **acceptList, int32_t acceptListCount, UEnumeration *availableLocales, UErrorCode *status)
// Based on a list of available locales, determine an acceptable locale for the user.
// uloc_acceptLanguage: function(aResult: MarshaledAString; resultAvailable: Int32; var outResult: UAcceptResult;
// const acceptList: PMarshaledAString; acceptListCount: Int32; availableLocals: PUEnumeration;
// var status: UErrorCode): Int32; cdecl;
//int32_t uloc_getLocaleForLCID (uint32_t hostID, char *locale, int32_t localeCapacity, UErrorCode *status)
// Gets the ICU locale ID for the specified Win32 LCID value.
//int32_t uloc_addLikelySubtags (const char *localeID, char *maximizedLocaleID, int32_t maximizedLocaleIDCapacity, UErrorCode *err)
// Add the likely subtags for a provided locale ID, per the algorithm described in the following CLDR technical report:
//int32_t uloc_minimizeSubtags (const char *localeID, char *minimizedLocaleID, int32_t minimizedLocaleIDCapacity, UErrorCode *err)
// Minimize the subtags for a provided locale ID, per the algorithm described in the following CLDR technical report:
//int32_t uloc_forLanguageTag (const char *langtag, char *localeID, int32_t localeIDCapacity, int32_t *parsedLength, UErrorCode *err)
// Returns a locale ID for the specified BCP47 language tag string.
//int32_t uloc_toLanguageTag (const char *localeID, char *langtag, int32_t langtagCapacity, UBool strict, UErrorCode *err)
// Returns a well-formed language tag for this locale ID.
uloc_toLanguageTag: function(const localeID: MarshaledAString; langtag: MarshaledAString;
langtagCapacity: Int32; strictCheck: UBool; var err: UErrorCode): Int32; cdecl;
{ ICU ulocdata.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ulocdata_8h.html }
//ULocaleData * ulocdata_open (const char *localeID, UErrorCode *status)
// Opens a locale data object for the given locale.
//void ulocdata_close (ULocaleData *uld)
// Closes a locale data object.
//void ulocdata_setNoSubstitute (ULocaleData *uld, UBool setting)
// Sets the "no Substitute" attribute of the locale data object.
//UBool ulocdata_getNoSubstitute (ULocaleData *uld)
// Retrieves the current "no Substitute" value of the locale data object.
//USet * ulocdata_getExemplarSet (ULocaleData *uld, USet *fillIn, uint32_t options, ULocaleDataExemplarSetType extype, UErrorCode *status)
// Returns the set of exemplar characters for a locale.
//int32_t ulocdata_getDelimiter (ULocaleData *uld, ULocaleDataDelimiterType type, UChar *result, int32_t resultLength, UErrorCode *status)
// Returns one of the delimiter strings associated with a locale.
//UMeasurementSystem ulocdata_getMeasurementSystem (const char *localeID, UErrorCode *status)
// Returns the measurement system used in the locale specified by the localeID.
//void ulocdata_getPaperSize (const char *localeID, int32_t *height, int32_t *width, UErrorCode *status)
// Returns the element gives the normal business letter size, and customary units.
//void ulocdata_getCLDRVersion (UVersionInfo versionArray, UErrorCode *status)
// Return the current CLDR version used by the library.
//int32_t ulocdata_getLocaleDisplayPattern (ULocaleData *uld, UChar *pattern, int32_t patternCapacity, UErrorCode *status)
// Returns locale display pattern associated with a locale.
//int32_t ulocdata_getLocaleSeparator (ULocaleData *uld, UChar *separator, int32_t separatorCapacity, UErrorCode *status)
// Returns locale separator associated with a locale.
{ ICU ucol.h File Reference}
{ http://www.icu-project.org/apiref/icu4c/ucol_8h.html }
// Open a UCollator for comparing strings.
ucol_open: function(const loc: MarshaledAString; var status: UErrorCode): PUCollator; cdecl;
//UCollator * ucol_openRules (const UChar *rules, int32_t rulesLength, UColAttributeValue normalizationMode, UCollationStrength strength, UParseError *parseError, UErrorCode *status)
// Produce an UCollator instance according to the rules supplied.
//UCollator * ucol_openFromShortString (const char *definition, UBool forceDefaults, UParseError *parseError, UErrorCode *status)
// Open a collator defined by a short form string.
//int32_t ucol_getContractions (const UCollator *coll, USet *conts, UErrorCode *status)
// Get a set containing the contractions defined by the collator.
//void ucol_getContractionsAndExpansions (const UCollator *coll, USet *contractions, USet *expansions, UBool addPrefixes, UErrorCode *status)
// Get a set containing the expansions defined by the collator.
// Close a UCollator.
ucol_close: procedure(coll: PUCollator); cdecl;
// Compare two strings.
ucol_strcoll: function(const coll: PUCollator; const source: PUChar; sourceLength: Int32;
const target: PUChar; targetLength: Int32): UCollationResult; cdecl;
// Compare two strings in UTF-8.
// ucol_strcollUTF8: function(const coll: PUCollator; const source: PUChar; sourceLength: Int32;
// const target: PUChar; targetLength: Int32; var status: UErrorCode): UCollationResult; cdecl;
//UBool ucol_greater (const UCollator *coll, const UChar *source, int32_t sourceLength, const UChar *target, int32_t targetLength)
// Determine if one string is greater than another.
//UBool ucol_greaterOrEqual (const UCollator *coll, const UChar *source, int32_t sourceLength, const UChar *target, int32_t targetLength)
// Determine if one string is greater than or equal to another.
//UBool ucol_equal (const UCollator *coll, const UChar *source, int32_t sourceLength, const UChar *target, int32_t targetLength)
// Compare two strings for equality.
//UCollationResult ucol_strcollIter (const UCollator *coll, UCharIterator *sIter, UCharIterator *tIter, UErrorCode *status)
// Compare two UTF-8 encoded trings.
// Get the collation strength used in a UCollator.
// ucol_getStrength: function(const coll: PUCollator): UCollationStrength; cdecl;
// Set the collation strength used in a UCollator.
// ucol_setStrength: procedure(const coll: PUCollator; strength: UCollationStrength); cdecl;
//int32_t ucol_getReorderCodes (const UCollator *coll, int32_t *dest, int32_t destCapacity, UErrorCode *pErrorCode)
// Retrieves the reordering codes for this collator.
// ucol_getReorderCodes: function(const coll: PUCollator; dest: PInt32; destCapacity: Int32;
// var ErrorCode: UErrorCode): Int32; cdecl;
//void ucol_setReorderCodes (UCollator *coll, const int32_t *reorderCodes, int32_t reorderCodesLength, UErrorCode *pErrorCode)
// Sets the reordering codes for this collator.
// ucol_setReorderCodes: procedure(const coll: PUCollator; const reorderCodes: PInt32;
// reorderCodesLength: Int32; var ErrorCode: UErrorCode); cdecl;
//int32_t ucol_getEquivalentReorderCodes (int32_t reorderCode, int32_t *dest, int32_t destCapacity, UErrorCode *pErrorCode)
// Retrieves the reorder codes that are grouped with the given reorder code.
// ucol_getEquivalentReorderCodes: function(reorderCode: Int32; const dest: PInt32;
// destCapacity: Int32; var ErrorCode: UErrorCode): Int32; cdecl;
//int32_t ucol_getDisplayName (const char *objLoc, const char *dispLoc, UChar *result, int32_t resultLength, UErrorCode *status)
// Get the display name for a UCollator.
// ucol_getDisplayName: function(const objLoc, dispLoc: MarshaledAString; aResult:PUChar; resultLength: Int32; var status: UErrorCode): Int32; cdecl;
// Get a locale for which collation rules are available.
// ucol_getAvailable: function(localeIndex: Int32): MarshaledAString; cdecl;
// Determine how many locales have collation rules available.
// ucol_countAvailable: function: Int32; cdecl;
//UEnumeration * ucol_openAvailableLocales (UErrorCode *status)
// Create a string enumerator of all locales for which a valid collator may be opened.
//UEnumeration * ucol_getKeywords (UErrorCode *status)
// Create a string enumerator of all possible keywords that are relevant to collation.
//UEnumeration * ucol_getKeywordValues (const char *keyword, UErrorCode *status)
// Given a keyword, create a string enumeration of all values for that keyword that are currently in use.
//UEnumeration * ucol_getKeywordValuesForLocale (const char *key, const char *locale, UBool commonlyUsed, UErrorCode *status)
// Given a key and a locale, returns an array of string values in a preferred order that would make a difference.
//int32_t ucol_getFunctionalEquivalent (char *result, int32_t resultCapacity, const char *keyword, const char *locale, UBool *isAvailable, UErrorCode *status)
// Return the functionally equivalent locale for the given requested locale, with respect to given keyword, for the collation service.
//const UChar * ucol_getRules (const UCollator *coll, int32_t *length)
// Get the collation tailoring rules from a UCollator.
// ucol_getRules: function(const coll: PUCollator; var length: Int32): PUChar; cdecl;
//int32_t ucol_getShortDefinitionString (const UCollator *coll, const char *locale, char *buffer, int32_t capacity, UErrorCode *status)
// Get the short definition string for a collator.
//int32_t ucol_normalizeShortDefinitionString (const char *source, char *destination, int32_t capacity, UParseError *parseError, UErrorCode *status)
// Verifies and normalizes short definition string.
//int32_t ucol_getSortKey (const UCollator *coll, const UChar *source, int32_t sourceLength, uint8_t *result, int32_t resultLength)
// Get a sort key for a string from a UCollator.
//int32_t ucol_nextSortKeyPart (const UCollator *coll, UCharIterator *iter, uint32_t state[2], uint8_t *dest, int32_t count, UErrorCode *status)
// Gets the next count bytes of a sort key.
//int32_t ucol_getBound (const uint8_t *source, int32_t sourceLength, UColBoundMode boundType, uint32_t noOfLevels, uint8_t *result, int32_t resultLength, UErrorCode *status)
// Produce a bound for a given sortkey and a number of levels.
//void ucol_getVersion (const UCollator *coll, UVersionInfo info)
// Gets the version information for a Collator.
//void ucol_getUCAVersion (const UCollator *coll, UVersionInfo info)
// Gets the UCA version information for a Collator.
//int32_t ucol_mergeSortkeys (const uint8_t *src1, int32_t src1Length, const uint8_t *src2, int32_t src2Length, uint8_t *dest, int32_t destCapacity)
// Merges two sort keys.
// Universal attribute setter.
ucol_setAttribute: procedure(const coll: PUCollator; attr: UColAttribute;
value: UColAttributeValue; var status: UErrorCode); cdecl;
// Universal attribute getter.
// ucol_getAttribute: function(const coll: PUCollator; attr: UColAttribute;
// var status: UErrorCode): UColAttributeValue; cdecl;
//uint32_t ucol_setVariableTop (UCollator *coll, const UChar *varTop, int32_t len, UErrorCode *status)
// Variable top is a two byte primary value which causes all the codepoints with primary values that are less or equal than the variable top to be shifted when alternate handling is set to UCOL_SHIFTED.
//uint32_t ucol_getVariableTop (const UCollator *coll, UErrorCode *status)
// Gets the variable top value of a Collator.
//void ucol_restoreVariableTop (UCollator *coll, const uint32_t varTop, UErrorCode *status)
// Sets the variable top to a collation element value supplied.
// Thread safe cloning operation.
// ucol_safeClone: function(const coll: PUCollator; stackBuffer: Pointer;
// pBufferSize: PInt32; var status: UErrorCode): PUCollator; cdecl;
//int32_t ucol_getRulesEx (const UCollator *coll, UColRuleOption delta, UChar *buffer, int32_t bufferLen)
// Returns current rules.
// gets the locale name of the collator.
// ucol_getLocale: function(const coll: PUCollator; aType: ULocDataLocaleType;
// var status: UErrorCode): MarshaledAString; cdecl;
// gets the locale name of the collator.
// ucol_getLocaleByType: function(const coll: PUCollator; aType: ULocDataLocaleType;
// var status: UErrorCode): MarshaledAString; cdecl;
//USet * ucol_getTailoredSet (const UCollator *coll, UErrorCode *status)
// Get an Unicode set that contains all the characters and sequences tailored in this collator.
//UColAttributeValue ucol_getAttributeOrDefault (const UCollator *coll, UColAttribute attr, UErrorCode *status)
// Universal attribute getter that returns UCOL_DEFAULT if the value is default.
//UBool ucol_equals (const UCollator *source, const UCollator *target)
// Check whether two collators are equal.
//int32_t ucol_getUnsafeSet (const UCollator *coll, USet *unsafe, UErrorCode *status)
// Calculates the set of unsafe code points, given a collator.
//void ucol_forgetUCA (void)
// Reset UCA's static pointers.
//void ucol_prepareShortStringOpen (const char *definition, UBool forceDefaults, UParseError *parseError, UErrorCode *status)
// Touches all resources needed for instantiating a collator from a short string definition, thus filling up the cache.
//Creates a binary image of a collator.
// ucol_cloneBinary: function(const coll: PUCollator; buffer: PByte; capacity: Int32;
// var status: UErrorCode): Int32; cdecl;
// Opens a collator from a collator binary image created using ucol_cloneBinary.
// ucol_openBinary: function(const bin: PByte; length: UInt32; const base: PUCollator;
// var status: UErrorCode): PUCollator; cdecl;
{ C API: String Enumeration. Definition in file uenum.h. }
{ http://www.icu-project.org/apiref/icu4c/uenum_8h.html }
// Disposes of resources in use by the iterator.
// uenum_close: procedure(en: PUEnumeration); cdecl;
// Returns the number of elements that the iterator traverses.
// uenum_count: function(en: PUEnumeration; var status: UErrorCode): Int32; cdecl;
// Returns the next element in the iterator's list.
// uenum_unext: function(en: PUEnumeration; var resultLength: Int32; var status: UErrorCode): PUChar; cdecl;
// Returns the next element in the iterator's list.
// uenum_next: function(en: PUEnumeration; var resultLength: Int32; var status: UErrorCode): MarshaledAString; cdecl;
// Resets the iterator to the current list of service IDs.
// uenum_reset: procedure(en: PUEnumeration; var status: UErrorCode); cdecl;
// Given an array of const UChar* strings, return a UEnumeration.
// uenum_openUCharStringsEnumeration: function(const strings: PPUChar; count: Int32; var ec: UErrorCode):PUEnumeration; cdecl;
// Given an array of const char* strings (invariant chars only), return a UEnumeration.
// uenum_openCharStringsEnumeration: function(const strings: PMarshaledAString; count: Int32; var ec: UErrorCode): PUEnumeration; cdecl;
{ C API: DateFormat. }
{ http://www.icu-project.org/apiref/icu4c/udat_8h.html }
// Maps from a UDateFormatField to the corresponding UCalendarDateFields.
// udat_toCalendarDateField: function(field: UDateFormatField): UCalendarDateFields; cdecl;
// Open a new UDateFormat for formatting and parsing dates and times.
udat_open: function(timeStyle: UDateFormatStyle; dateStyle: UDateFormatStyle;
const locale: MarshaledAString; const tzID: PUChar; tzIDLenght: Int32;
const pattern: PUChar; patternLenght: Int32; var status: UErrorCode): PUDateFormat; cdecl;
// Close a UDateFormat.
udat_close: procedure(format: PUDateFormat); cdecl;
// Open a copy of a UDateFormat.
// udat_clone: function(const fmt: PUDateFormat; var status: UErrorCode): PUDateFormat; cdecl;
// Format a date using an UDateFormat.
// udat_format: function(const format: PUDateFormat; dateToFormat: UDate;
// aResult: PUChar; aResultLength: Int32; position: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Parse a string into an date/time using a UDateFormat.
// udat_parse: function(const format: PUDateFormat; const text: PUChar; textLength: Int32;
// var parsePos: Int32; var status: UErrorCode): UDate; cdecl;
// Parse a string into an date/time using a UDateFormat.
// udat_parseCalendar:procedure(const format: PUDateFormat; calendar: PUCalendar;
// const text: PUChar; textLength: Int32; var parsePos: Int32; var status: UErrorCode); cdecl;
// Determine if an UDateFormat will perform lenient parsing.
// udat_isLenient: function(const fmt: PUDateFormat): UBool; cdecl;
// Specify whether an UDateFormat will perform lenient parsing.
// udat_setLenient: procedure(fmt: PUDateFormat; isLenient: UBool); cdecl;
// Get the UCalendar associated with an UDateFormat.
// udat_getCalendar: function(const fmt: PUDateFormat): PUCalendar; cdecl;
//void udat_setCalendar (UDateFormat *fmt, const UCalendar *calendarToSet)
// Set the UCalendar associated with an UDateFormat.
// udat_setCalendar: procedure(fmt: PUDateFormat; const calendarToSet: PUCalendar); cdecl;
// Get the UNumberFormat associated with an UDateFormat.
// udat_getNumberFormat: function(const fmt: PUDateFormat): PUNumberFormat; cdecl;
// Set the UNumberFormat associated with an UDateFormat.
// udat_setNumberFormat: procedure(fmt: PUDateFormat; const numberFormatToSet: PUNumberFormat); cdecl;
// Get a locale for which date/time formatting patterns are available.
// udat_getAvailable: function(localeIndex: Int32): MarshaledAString; cdecl;
// Determine how many locales have date/time formatting patterns available.
// udat_countAvailable: function: Int32; cdecl;
// Get the year relative to which all 2-digit years are interpreted.
// udat_get2DigitYearStart: function(const fmt: PUDateFormat; var status: UErrorCode): UDate; cdecl;
// Set the year relative to which all 2-digit years will be interpreted.
// udat_set2DigitYearStart: procedure(fmt: PUDateFormat; d: UDate; var status: UErrorCode); cdecl;
// Extract the pattern from a UDateFormat.
// udat_toPattern: function(const fmt: PUDateFormat; localized: UBool; aResult: PUChar;
// aResultLength: Int32; var status: UErrorCode): Int32; cdecl;
// Set the pattern used by an UDateFormat.
// udat_applyPattern: procedure (const format: PUDateFormat; localized: UBool;
// pattern: PUChar; patternLength: Int32); cdecl;
// Get the symbols associated with an UDateFormat.
udat_getSymbols: function(const fmt: PUDateFormat; aType: UDateFormatSymbolType;
symbolIndex: Int32; aResult: PUChar; aResultLen: Int32; var status: UErrorCode): Int32; cdecl;
// Count the number of particular symbols for an UDateFormat.
udat_countSymbols: function(const fmt: PUDateFormat; aType: UDateFormatSymbolType): Int32;
//void udat_setSymbols (UDateFormat *format, UDateFormatSymbolType type, int32_t symbolIndex, UChar *value, int32_t valueLength, UErrorCode *status)
// Set the symbols associated with an UDateFormat.
//const char * udat_getLocaleByType (const UDateFormat *fmt, ULocDataLocaleType type, UErrorCode *status)
// Get the locale for this date format object.
//void udat_setContext (UDateFormat *fmt, UDisplayContext value, UErrorCode *status)
// Set a particular UDisplayContext value in the formatter, such as UDISPCTX_CAPITALIZATION_FOR_STANDALONE.
//UDisplayContext udat_getContext (UDateFormat *fmt, UDisplayContextType type, UErrorCode *status)
// Get the formatter's UDisplayContext value for the specified UDisplayContextType, such as UDISPCTX_TYPE_CAPITALIZATION.
// Extract the date pattern from a UDateFormat set for relative date formatting.
udat_toPatternRelativeDate: function(const fmt: PUDateFormat; aResult: PUChar;
aResultLen: Int32; var status: UErrorCode): Int32; cdecl;
// Extract the time pattern from a UDateFormat set for relative date formatting.
udat_toPatternRelativeTime: function(const fmt: PUDateFormat; aResult: PUChar;
aResultLen: Int32; var status: UErrorCode): Int32; cdecl;
//void udat_applyPatternRelative (UDateFormat *format, const UChar *datePattern, int32_t datePatternLength, const UChar *timePattern, int32_t timePatternLength, UErrorCode *status)
// Set the date & time patterns used by a UDateFormat set for relative date formatting.
//void udat_registerOpener (UDateFormatOpener opener, UErrorCode *status)
// Register a provider factory.
//UDateFormatOpener udat_unregisterOpener (UDateFormatOpener opener, UErrorCode *status)
// Un-Register a provider factory.
{ C API: NumberFormat. }
{ http://www.icu-project.org/apiref/icu4c/unum_8h.html }
// Create and return a new UNumberFormat for formatting and parsing numbers.
unum_open: function(style: UNumberFormatStyle; const pattern: PUChar; patternLength: Int32;
const locale: MarshaledAString; parseErr: PUParseError; var status: UErrorCode): PUNumberFormat; cdecl;
// Close a UNumberFormat.
unum_close: procedure(fmt: PUNumberFormat); cdecl;
// Open a copy of a UNumberFormat.
// unum_clone: function(const fmt: PUNumberFormat; var status: UErrorCode): PUNumberFormat; cdecl;
// Format an integer using a UNumberFormat.
// unum_format: function(const fmt: PUNumberFormat; number: Int32; aResult: PUChar; aResultLength: Int32;
// pos: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Format an int64 using a UNumberFormat.
// unum_formatInt64: function(const fmt: PUNumberFormat; number: Int64; aResult: PUChar; aResultLength: Int32;
// pos: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Format a double using a UNumberFormat.
// unum_formatDouble: function(const fmt: PUNumberFormat; number: Double; aResult: PUChar; aResultLength: Int32;
// pos: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Format a decimal number using a UNumberFormat.
// unum_formatDecimal: function(const fmt: PUNumberFormat; const number: MarshaledAString; numberLength: Int32;
// aResult: PUChar; aResultLength: Int32; pos: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Format a double currency amount using a UNumberFormat.
// unum_formatDoubleCurrency: function(const fmt: PUNumberFormat; number: Double; currency: PUChar;
// aResult: PUChar; aResultLength: Int32; pos: PUFieldPosition; var status: UErrorCode): Int32; cdecl;
// Parse a string into an integer using a UNumberFormat.
// unum_parse: function(const fmt: PUNumberFormat; const text: PUChar; textLength: Int32;
// parsePos: PInt32; var status: UErrorCode): Int32; cdecl;
// Parse a string into an int64 using a UNumberFormat.
// unum_parseInt64: function(const fmt: PUNumberFormat; const text: PUChar; textLength: Int32;
// parsePos: PInt32; var status: UErrorCode): Int64; cdecl;
// Parse a string into a double using a UNumberFormat.
// unum_parseDouble: function(const fmt: PUNumberFormat; const text: PUChar; textLength: Int32;
// parsePos: PInt32; var status: UErrorCode): Double; cdecl;
// Parse a number from a string into an unformatted numeric string using a UNumberFormat.
// unum_parseDecimal: function(const fmt: PUNumberFormat; const text: PUChar; textLength: Int32;
// parsePos: PInt32; outBuf: PUChar; outBufLength: Int32; var status: UErrorCode): Int32; cdecl;
// Parse a string into a double and a currency using a UNumberFormat.
// unum_parseDoubleCurrency: function(const fmt: PUNumberFormat; const text: PUChar; textLength: Int32;
// parsePos: PInt32; currency: PUChar; var status: UErrorCode): Double; cdecl;
// Set the pattern used by a UNumberFormat.
// unum_applyPattern: procedure(format: PUNumberFormat; localized: UBool; const pattern: PUChar;
// patternLength: Int32; parseError: PUParseError; var status: UErrorCode); cdecl;
// Get a locale for which decimal formatting patterns are available.
// unum_getAvailable: function(localeIndex: Int32): MarshaledAString; cdecl;
// Determine how many locales have decimal formatting patterns available.
// unum_countAvailable: function: Int32; cdecl;
// Get a numeric attribute associated with a UNumberFormat.
unum_getAttribute: function(const fmt: PUNumberFormat; attr: UNumberFormatAttribute): Int32; cdecl;
//void unum_setAttribute (UNumberFormat *fmt, UNumberFormatAttribute attr, int32_t newValue)
// Set a numeric attribute associated with a UNumberFormat.
// unum_setAttribute: procedure(const fmt: PUNumberFormat; attr: UNumberFormatAttribute; newValue: Int32); cdecl;
//double unum_getDoubleAttribute (const UNumberFormat *fmt, UNumberFormatAttribute attr)
// Get a numeric attribute associated with a UNumberFormat.
// unum_getDoubleAttribute: function(const fmt: PUNumberFormat; attr: UNumberFormatAttribute): Double; cdecl;
//void unum_setDoubleAttribute (UNumberFormat *fmt, UNumberFormatAttribute attr, double newValue)
// Set a numeric attribute associated with a UNumberFormat.
// unum_setDoubleAttribute: procedure(const fmt: PUNumberFormat; attr: UNumberFormatAttribute; newValue: Double); cdecl;
// Get a text attribute associated with a UNumberFormat.
unum_getTextAttribute: function(const fmt: PUNumberFormat; tag: UNumberFormatTextAttribute;
aResult: PUChar; aResultLength: Int32; var status: UErrorCode): Int32; cdecl;
//void unum_setTextAttribute (UNumberFormat *fmt, UNumberFormatTextAttribute tag, const UChar *newValue, int32_t newValueLength, UErrorCode *status)
// Set a text attribute associated with a UNumberFormat.
// unum_setTextAttribute: procedure(const fmt: PUNumberFormat; tag: UNumberFormatTextAttribute;
// const newValue: PUChar; newValueLength: Int32; var status: UErrorCode); cdecl;
//int32_t unum_toPattern (const UNumberFormat *fmt, UBool isPatternLocalized, UChar *result, int32_t resultLength, UErrorCode *status)
// Extract the pattern from a UNumberFormat.
// unum_toPattern: function(const fmt: PUNumberFormat; isPatternLocalized: UBool;
// aResult: PUChar; aResultLength: Int32; var status: UErrorCode): Int32; cdecl;
//int32_t unum_getSymbol (const UNumberFormat *fmt, UNumberFormatSymbol symbol, UChar *buffer, int32_t size, UErrorCode *status)
// Get a symbol associated with a UNumberFormat.
unum_getSymbol: function(const fmt: PUNumberFormat; symbol: UNumberFormatSymbol;
buffer: PUChar; bufferLength: Int32; var status: UErrorCode): Int32; cdecl;
//void unum_setSymbol (UNumberFormat *fmt, UNumberFormatSymbol symbol, const UChar *value, int32_t length, UErrorCode *status)
// Set a symbol associated with a UNumberFormat.
// unum_setSymbol: procedure(const fmt: PUNumberFormat; symbol: UNumberFormatSymbol;
// const value: PUChar; length: Int32; var status: UErrorCode); cdecl;
//const char * unum_getLocaleByType (const UNumberFormat *fmt, ULocDataLocaleType type, UErrorCode *status)
// Get the locale for this number format object.
// unum_getLocaleByType: function(const fmt: PUNumberFormat; aType: ULocDataLocaleType;
// var status: UErrorCode): MarshaledAString; cdecl;
{ ucal.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucal_8h.html }
// Create an enumeration over system time zone IDs with the given filter conditions.
// ucal_openTimeZoneIDEnumeration: function(zoneType: USystemTimeZoneType; const region: MarshaledAString;
// const rawOffset: PInt32; var ec: UErrorCode): PUEnumeration; cdecl;
// Create an enumeration over all time zones.
// ucal_openTimeZones: function(var ec: UErrorCode): PUEnumeration; cdecl;
// Create an enumeration over all time zones associated with the given country.
// ucal_openCountryTimeZones: function(const country: MarshaledAString; var ec: UErrorCode): PUEnumeration; cdecl;
// Return the default time zone.
// ucal_getDefaultTimeZone: function(aResult: PUChar; aResultCapacity: Int32; var ec: UErrorCode): Int32; cdecl;
// Set the default time zone.
// ucal_setDefaultTimeZone: procedure(const zoneID: PUChar; var ec: UErrorCode); cdecl;
// Return the amount of time in milliseconds that the clock is advanced during
// daylight savings time for the given time zone, or zero if the time zone does not observe daylight savings time.
// ucal_getDSTSavings: function(const zoneID: PUChar; var ec: UErrorCode): Int32; cdecl;
// Get the current date and time.
ucal_getNow: function: UDate; cdecl;
// Open a UCalendar.
ucal_open: function(const zoneID: PUChar; len: Int32; const locale: MarshaledAString;
aType: UCalendarType; var status: UErrorCode): PUCalendar; cdecl;
// Close a UCalendar.
ucal_close: procedure(car: PUCalendar); cdecl;
// Open a copy of a UCalendar.
// ucal_clone: function(car: PUCalendar; var status: UErrorCode): PUCalendar; cdecl;
// Set the TimeZone used by a UCalendar.
// ucal_setTimeZone: procedure(cal: PUCalendar; const zoneID: PUChar; len: Int32; var status: UErrorCode); cdecl;
// Get the ID of the UCalendar's time zone.
// ucal_getTimeZoneID: function(const cal: PUCalendar; aResult: PUChar; aResultLength: Int32;
// var status: UErrorCode): Int32; cdecl;
// Get the display name for a UCalendar's TimeZone.
// ucal_getTimeZoneDisplayName: function(const cal: PUCalendar; aType: UCalendarDisplayNameType;
// const locale: MarshaledAString; aResult: PUChar; aResultLength: Int32; var status: UErrorCode): Int32; cdecl;
// Determine if a UCalendar is currently in daylight savings time.
// ucal_inDaylightTime: function(cal: PUCalendar; var status: UErrorCode): UBool; cdecl;
// Sets the GregorianCalendar change date.
// ucal_setGregorianChange: procedure(cal: PUCalendar; aDate: UDate; var status: UErrorCode); cdecl;
// Gets the Gregorian Calendar change date.
// ucal_getGregorianChange: function(cal: PUCalendar; var status: UErrorCode): UBool; cdecl;
// Get a numeric attribute associated with a UCalendar.
// ucal_getAttribute: function(cal: PUCalendar; attr: UCalendarAttribute): Int32; cdecl;
// Set a numeric attribute associated with a UCalendar.
// ucal_setAttribute: procedure(cal: PUCalendar; attr: UCalendarAttribute; newValue: Int32); cdecl;
// Get a locale for which calendars are available.
// ucal_getAvailable: function(localeIndex: Int32): MarshaledAString; cdecl;
// Determine how many locales have calendars available.
// ucal_countAvailable: function: Int32; cdecl;
// Get a UCalendar's current time in millis.
ucal_getMillis: function(const cal: PUCalendar; var status: UErrorCode): UDate; cdecl;
// Set a UCalendar's current time in millis.
ucal_setMillis: function(cal: PUCalendar; dateTime: UDate; var status: UErrorCode): UDate; cdecl;
// Set a UCalendar's current date.
// ucal_setDate: procedure(cal: PUCalendar; year, month, date: Int32; var status: UErrorCode); cdecl;
// Set a UCalendar's current date.
ucal_setDateTime: procedure(cal: PUCalendar; year, month, date, hour, minute, second: Int32;
var status: UErrorCode); cdecl;
//UBool ucal_equivalentTo (const UCalendar *cal1, const UCalendar *cal2)
// Returns TRUE if two UCalendars are equivalent.
//void ucal_add (UCalendar *cal, UCalendarDateFields field, int32_t amount, UErrorCode *status)
// Add a specified signed amount to a particular field in a UCalendar.
//void ucal_roll (UCalendar *cal, UCalendarDateFields field, int32_t amount, UErrorCode *status)
// Add a specified signed amount to a particular field in a UCalendar.
//int32_t ucal_get (const UCalendar *cal, UCalendarDateFields field, UErrorCode *status)
// Get the current value of a field from a UCalendar.
ucal_get: function(const cal: PUCalendar; field: UCalendarDateFields; var status: UErrorCode): Int32; cdecl;
//void ucal_set (UCalendar *cal, UCalendarDateFields field, int32_t value)
// Set the value of a field in a UCalendar.
// ucal_set: procedure(cal: PUCalendar; field: UCalendarDateFields; value: Int32); cdecl;
//UBool ucal_isSet (const UCalendar *cal, UCalendarDateFields field)
// Determine if a field in a UCalendar is set.
// ucal_isSet: function(cal: PUCalendar; field: UCalendarDateFields): Boolean; cdecl;
//void ucal_clearField (UCalendar *cal, UCalendarDateFields field)
// Clear a field in a UCalendar.
// ucal_clearField: procedure(cal: PUCalendar; field: UCalendarDateFields); cdecl;
//void ucal_clear (UCalendar *calendar)
// Clear all fields in a UCalendar.
// ucal_clear: procedure(cal: PUCalendar); cdecl;
//int32_t ucal_getLimit (const UCalendar *cal, UCalendarDateFields field, UCalendarLimitType type, UErrorCode *status)
// Determine a limit for a field in a UCalendar.
// ucal_getLimit: function(const cal: PUCalendar; field: UCalendarDateFields; aType: UCalendarLimitType;
// var status: UErrorCode): Int32; cdecl;
//const char * ucal_getLocaleByType (const UCalendar *cal, ULocDataLocaleType type, UErrorCode *status)
// Get the locale for this calendar object.
// ucal_getLocaleByType: function(const cal: PUCalendar; aType: ULocDataLocaleType; var status: UErrorCode): Int32; cdecl;
//const char * ucal_getTZDataVersion (UErrorCode *status)
// Returns the timezone data version currently used by ICU.
// ucal_getTZDataVersion: function(var status: UErrorCode): MarshaledAString; cdecl;
//int32_t ucal_getCanonicalTimeZoneID (const UChar *id, int32_t len, UChar *result, int32_t resultCapacity, UBool *isSystemID, UErrorCode *status)
// Returns the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID.
// ucal_getCanonicalTimeZoneID: function(const id: PUChar; len: Int32; result: PUChar;
// resultCapacity: Int32; var isSystemID: UBool; var status: UErrorCode): Int32; cdecl;
//const char * ucal_getType (const UCalendar *cal, UErrorCode *status)
// Get the resource keyword value string designating the calendar type for the UCalendar.
//UEnumeration * ucal_getKeywordValuesForLocale (const char *key, const char *locale, UBool commonlyUsed, UErrorCode *status)
// Given a key and a locale, returns an array of string values in a preferred order that would make a difference.
//UCalendarWeekdayType ucal_getDayOfWeekType (const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode *status)
// Returns whether the given day of the week is a weekday, a weekend day, or a day
// that transitions from one to the other, in this calendar system.
//int32_t ucal_getWeekendTransition (const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode *status)
// Returns the time during the day at which the weekend begins or ends in this calendar system.
//UBool ucal_isWeekend (const UCalendar *cal, UDate date, UErrorCode *status)
// Returns TRUE if the given UDate is in the weekend in this calendar system.
//int32_t ucal_getFieldDifference (UCalendar *cal, UDate target, UCalendarDateFields field, UErrorCode *status)
// Return the difference between the target time and the time this calendar object is currently set to.
// ucal_getFieldDifference: function(cal: PUCalendar; target: UDate; field: UCalendarDateFields;
// var status: UErrorCode): Int32; cdecl;
//UBool ucal_getTimeZoneTransitionDate (const UCalendar *cal, UTimeZoneTransitionType type, UDate *transition, UErrorCode *status)
// Get the UDate for the next/previous time zone transition relative to the calendar's
// current date, in the time zone to which the calendar is currently set.
// ucal_getTimeZoneTransitionDate: function(const cal: PUCalendar; aType: UTimeZoneTransitionType; var transition: UDate;
// var status: UErrorCode): UBool; cdecl;
// This procedure needs to be called upon thread destruction if the user code
// is not using a TThread descendant to do the thread management.
// This frees the collator cache.
procedure ClearCollatorCache;
function GetCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
procedure InitHIC;
implementation
uses
System.SysConst,
Posix.String_,
Posix.Dlfcn;
type
TCacheCollator = record
const
MaxCollatorCacheSize: Integer = 10;
private
type
TCollatorItem = record
LocaleStr: MarshaledAString;
UsageCounter: UInt32;
Options: TCompareOptions;
Collator: PUCollator;
constructor Create(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions);
procedure Destroy;
end;
function AddCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
function FindCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
function GetUnusedIndex: Integer;
procedure AdjustUsageStatistics;
class procedure MapOptionsToCollator(AOptions: TCompareOptions; const collator: PUCollator); static; inline;
var
LangCollators: array of TCollatorItem;
public
function GetCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
procedure Destroy;
end;
// The collators cannot be shared between threads, therefore we duplicate the cache for every thread.
threadvar
CollatorCache: TCacheCollator;
function GetCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
begin
Result := CollatorCache.GetCollator(ALocaleStr, AOptions);
end;
function InitICU: Boolean;
begin
InitHIC;
Result := False;
end;
function GetFncAddress(Handle: NativeUInt; FunctionName: string): Pointer;
var
Ptr: TPtrWrapper;
begin
Ptr := TMarshal.AllocStringAsUtf8(FunctionName + System.LibICUSuffix);
Result := dlsym(Handle, Ptr.ToPointer);
TMarshal.FreeMem(Ptr);
end;
function InitHICUUC: Boolean;
begin
// @u_getDataDirectory := GetFncAddress(System.HICUUC, 'u_getDataDirectory');
@u_errorName := GetFncAddress(System.HICUUC, 'u_errorName');
{ ICU ucnv.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucnv_8h.html }
// @ucnv_compareNames := GetFncAddress(System.HICUUC, 'ucnv_compareNames');
@ucnv_open := GetFncAddress(System.HICUUC,'ucnv_open');
// @ucnv_openU := GetFncAddress(System.HICUUC,'ucnv_openU');
// @ucnv_openCCSID := GetFncAddress(System.HICUUC,'ucnv_openCCSID');
// @ucnv_openPackage := GetFncAddress(System.HICUUC, 'ucnv_openPackage');
// @ucnv_safeClone := GetFncAddress(System.HICUUC, 'ucnv_safeClone');
@ucnv_close := GetFncAddress(System.HICUUC,'ucnv_close');
// @ucnv_setSubstChars := GetFncAddress(System.HICUUC, 'ucnv_setSubstChars');
// @ucnv_getInvalidChars := GetFncAddress(System.HICUUC, 'ucnv_getInvalidChars');
// @ucnv_getInvalidUChars := GetFncAddress(System.HICUUC, 'ucnv_getInvalidUChars');
// @ucnv_reset := GetFncAddress(System.HICUUC, 'ucnv_reset');
@ucnv_getMaxCharSize := GetFncAddress(System.HICUUC, 'ucnv_getMaxCharSize');
// @ucnv_getMinCharSize := GetFncAddress(System.HICUUC, 'ucnv_getMinCharSize');
@ucnv_getDisplayName := GetFncAddress(System.HICUUC, 'ucnv_getDisplayName');
@ucnv_getName := GetFncAddress(System.HICUUC, 'ucnv_getName');
@ucnv_getStandardName := GetFncAddress(System.HICUUC, 'ucnv_getStandardName');
// @ucnv_getCCSID := GetFncAddress(System.HICUUC, 'ucnv_getCCSID');
// @ucnv_setToUCallBack := GetFncAddress(System.HICUUC, 'ucnv_setToUCallBack');
// @ucnv_setFromUCallBack := GetFncAddress(System.HICUUC, 'ucnv_setFromUCallBack');
// @ucnv_toUnicode := GetFncAddress(System.HICUUC, 'ucnv_toUnicode');
// @ucnv_fromUChars := GetFncAddress(System.HICUUC, 'ucnv_fromUChars');
// @ucnv_toUChars := GetFncAddress(System.HICUUC, 'ucnv_toUChars');
// @ucnv_countAvailable := GetFncAddress(System.HICUUC, 'ucnv_countAvailable');
// @ucnv_getAvailableName := GetFncAddress(System.HICUUC, 'ucnv_getAvailableName');
// @ucnv_countAliases := GetFncAddress(System.HICUUC, 'ucnv_countAliases');
// @ucnv_getAlias := GetFncAddress(System.HICUUC, 'ucnv_getAlias');
// @ucnv_getAliases := GetFncAddress(System.HICUUC, 'ucnv_getAliases');
// @ucnv_cbToUWriteUChars := GetFncAddress(System.HICUUC, 'ucnv_cbToUWriteUChars');
{ ICU ustring.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ustring_8h.html }
@u_strcmp := GetFncAddress(System.HICUUC, 'u_strcmp');
// @u_strcmpCodePointOrder := GetFncAddress(System.HICUUC, 'u_strcmpCodePointOrder');
// @u_strCaseCompare := GetFncAddress(System.HICUUC, 'u_strCaseCompare');
// @u_strncmp := GetFncAddress(System.HICUUC, 'u_strncmp');
// @u_strncmpCodePointOrder := GetFncAddress(System.HICUUC, 'u_strncmpCodePointOrder');
// @u_strcasecmp := GetFncAddress(System.HICUUC, 'u_strcasecmp');
// @u_strncasecmp := GetFncAddress(System.HICUUC, 'u_strncasecmp');
// @u_memcasecmp := GetFncAddress(System.HICUUC, 'u_memcasecmp');
// @u_strcpy := GetFncAddress(System.HICUUC, 'u_strcpy');
// @u_strncpy := GetFncAddress(System.HICUUC, 'u_strncpy');
// @u_uastrcpy := GetFncAddress(System.HICUUC, 'u_uastrcpy');
// @u_uastrncpy := GetFncAddress(System.HICUUC, 'u_uastrncpy');
// @u_austrcpy := GetFncAddress(System.HICUUC, 'u_austrcpy');
// @u_austrncpy := GetFncAddress(System.HICUUC, 'u_austrncpy');
@u_strToLower := GetFncAddress(System.HICUUC, 'u_strToLower');
@u_strToUpper := GetFncAddress(System.HICUUC, 'u_strToUpper');
// @u_strToUTF8 := GetFncAddress(System.HICUUC, 'u_strToUTF8');
// @u_strFromUTF8 := GetFncAddress(System.HICUUC, 'u_strFromUTF8');
// @u_strFromUTF8WithSub := GetFncAddress(System.HICUUC, 'u_strFromUTF8WithSub');
{ ICU uchar.h File Reference }
{ http://icu-project.org/apiref/icu4c/uchar_8h.html }
@u_tolower := GetFncAddress(System.HICUUC, 'u_tolower');
@u_toupper := GetFncAddress(System.HICUUC, 'u_toupper');
{ ICU uloc.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/uloc_8h.html }
// @uloc_getDefault := GetFncAddress(System.HICUUC, 'uloc_getDefault');
// @uloc_setDefault := GetFncAddress(System.HICUUC, 'uloc_setDefault');
// @uloc_getLanguage := GetFncAddress(System.HICUUC, 'uloc_getLanguage');
// @uloc_getScript := GetFncAddress(System.HICUUC, 'uloc_getScript');
// @uloc_getCountry := GetFncAddress(System.HICUUC, 'uloc_getCountry');
// @uloc_getVariant := GetFncAddress(System.HICUUC, 'uloc_getVariant');
// @uloc_getName := GetFncAddress(System.HICUUC, 'uloc_getName');
@uloc_canonicalize := GetFncAddress(System.HICUUC, 'uloc_canonicalize');
// @uloc_getISO3Language := GetFncAddress(System.HICUUC, 'uloc_getISO3Language');
// @uloc_getISO3Country := GetFncAddress(System.HICUUC, 'uloc_getISO3Country');
// @uloc_getLCID := GetFncAddress(System.HICUUC, 'uloc_getLCID');
@uloc_getAvailable := GetFncAddress(System.HICUUC, 'uloc_getAvailable');
@uloc_countAvailable := GetFncAddress(System.HICUUC, 'uloc_countAvailable');
@uloc_getBaseName := GetFncAddress(System.HICUUC, 'uloc_getBaseName');
// @uloc_acceptLanguage := GetFncAddress(System.HICUUC, 'uloc_acceptLanguage');
@uloc_toLanguageTag := GetFncAddress(System.HICUUC, 'uloc_toLanguageTag');
{ ICU ulocdata.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ulocdata_8h.html }
{ C API: String Enumeration. Definition in file uenum.h. }
{ http://www.icu-project.org/apiref/icu4c/uenum_8h.html }
// @uenum_close := GetFncAddress(System.HICUUC, 'uenum_close');
// @uenum_count := GetFncAddress(System.HICUUC, 'uenum_count');
// @uenum_unext := GetFncAddress(System.HICUUC, 'uenum_unext');
// @uenum_next := GetFncAddress(System.HICUUC, 'uenum_next');
// @uenum_reset := GetFncAddress(System.HICUUC, 'uenum_reset');
// @uenum_openUCharStringsEnumeration := GetFncAddress(System.HICUUC, 'uenum_openUCharStringsEnumeration');
// @uenum_openCharStringsEnumeration := GetFncAddress(System.HICUUC, 'uenum_openCharStringsEnumeration');
Result := True;
end;
function InitHICUI18N: Boolean;
begin
// Collation related functions...
@ucol_open := GetFncAddress(System.HICUI18N, 'ucol_open');
@ucol_close := GetFncAddress(System.HICUI18N, 'ucol_close');
@ucol_strcoll := GetFncAddress(System.HICUI18N, 'ucol_strcoll');
// @ucol_strcollUTF8 := GetFncAddress(System.HICUI18N, 'ucol_strcollUTF8');
// @ucol_getStrength := GetFncAddress(System.HICUI18N, 'ucol_getStrength');
// @ucol_setStrength := GetFncAddress(System.HICUI18N, 'ucol_setStrength');
// @ucol_getReorderCodes := GetFncAddress(System.HICUI18N, 'ucol_getReorderCodes');
// @ucol_setReorderCodes := GetFncAddress(System.HICUI18N, 'ucol_setReorderCodes');
// @ucol_getEquivalentReorderCodes := GetFncAddress(System.HICUI18N, 'ucol_getEquivalentReorderCodes');
// @ucol_getDisplayName := GetFncAddress(System.HICUI18N, 'ucol_getDisplayName');
// @ucol_getAvailable := GetFncAddress(System.HICUI18N, 'ucol_getAvailable');
// @ucol_countAvailable := GetFncAddress(System.HICUI18N, 'ucol_countAvailable');
// @ucol_getRules := GetFncAddress(System.HICUI18N, 'ucol_getRules');
@ucol_setAttribute := GetFncAddress(System.HICUI18N, 'ucol_setAttribute');
// @ucol_getAttribute := GetFncAddress(System.HICUI18N, 'ucol_getAttribute');
// @ucol_safeClone := GetFncAddress(System.HICUI18N, 'ucol_safeClone');
// @ucol_getLocale := GetFncAddress(System.HICUI18N, 'ucol_getLocale');
// @ucol_getLocaleByType := GetFncAddress(System.HICUI18N, 'ucol_getLocaleByType');
// @ucol_cloneBinary := GetFncAddress(System.HICUI18N, 'ucol_cloneBinary');
// @ucol_openBinary := GetFncAddress(System.HICUI18N, 'ucol_openBinary');
// Date Format functions...
// @udat_toCalendarDateField := GetFncAddress(System.HICUI18N, 'udat_toCalendarDateField');
@udat_open := GetFncAddress(System.HICUI18N, 'udat_open');
@udat_close := GetFncAddress(System.HICUI18N, 'udat_close');
// @udat_clone := GetFncAddress(System.HICUI18N, 'udat_clone');
// @udat_format := GetFncAddress(System.HICUI18N, 'udat_format');
// @udat_parse := GetFncAddress(System.HICUI18N, 'udat_parse');
// @udat_parseCalendar := GetFncAddress(System.HICUI18N, 'udat_parseCalendar');
// @udat_isLenient := GetFncAddress(System.HICUI18N, 'udat_isLenient');
// @udat_setLenient := GetFncAddress(System.HICUI18N, 'udat_setLenient');
// @udat_getCalendar := GetFncAddress(System.HICUI18N, 'udat_getCalendar');
// @udat_setCalendar := GetFncAddress(System.HICUI18N, 'udat_setCalendar');
// @udat_getNumberFormat := GetFncAddress(System.HICUI18N, 'udat_getNumberFormat');
// @udat_setNumberFormat := GetFncAddress(System.HICUI18N, 'udat_setNumberFormat');
// @udat_getAvailable := GetFncAddress(System.HICUI18N, 'udat_getAvailable');
// @udat_countAvailable := GetFncAddress(System.HICUI18N, 'udat_countAvailable');
// @udat_get2DigitYearStart := GetFncAddress(System.HICUI18N, 'udat_get2DigitYearStart');
// @udat_set2DigitYearStart := GetFncAddress(System.HICUI18N, 'udat_set2DigitYearStart');
// @udat_toPattern := GetFncAddress(System.HICUI18N, 'udat_toPattern');
// @udat_applyPattern := GetFncAddress(System.HICUI18N, 'udat_applyPattern');
@udat_getSymbols := GetFncAddress(System.HICUI18N, 'udat_getSymbols');
@udat_countSymbols := GetFncAddress(System.HICUI18N, 'udat_countSymbols');
@udat_toPatternRelativeDate := GetFncAddress(System.HICUI18N, 'udat_toPatternRelativeDate');
@udat_toPatternRelativeTime := GetFncAddress(System.HICUI18N, 'udat_toPatternRelativeTime');
{ C API: NumberFormat. }
{ http://www.icu-project.org/apiref/icu4c/unum_8h.html }
// Number Format functions...
@unum_open := GetFncAddress(System.HICUI18N, 'unum_open');
@unum_close := GetFncAddress(System.HICUI18N, 'unum_close');
// @unum_clone := GetFncAddress(System.HICUI18N, 'unum_clone');
// @unum_format := GetFncAddress(System.HICUI18N, 'unum_format');
// @unum_formatInt64 := GetFncAddress(System.HICUI18N, 'unum_formatInt64');
// @unum_formatDouble := GetFncAddress(System.HICUI18N, 'unum_formatDouble');
// @unum_formatDecimal := GetFncAddress(System.HICUI18N, 'unum_formatDecimal');
// @unum_formatDoubleCurrency := GetFncAddress(System.HICUI18N, 'unum_formatDoubleCurrency');
// @unum_parse := GetFncAddress(System.HICUI18N, 'unum_parse');
// @unum_parseInt64 := GetFncAddress(System.HICUI18N, 'unum_parseInt64');
// @unum_parseDouble := GetFncAddress(System.HICUI18N, 'unum_parseDouble');
// @unum_parseDecimal := GetFncAddress(System.HICUI18N, 'unum_parseDecimal');
// @unum_parseDoubleCurrency := GetFncAddress(System.HICUI18N, 'unum_parseDoubleCurrency');
// @unum_applyPattern := GetFncAddress(System.HICUI18N, 'unum_applyPattern');
// @unum_getAvailable := GetFncAddress(System.HICUI18N, 'unum_getAvailable');
// @unum_countAvailable := GetFncAddress(System.HICUI18N, 'unum_countAvailable');
@unum_getAttribute := GetFncAddress(System.HICUI18N, 'unum_getAttribute');
// @unum_setAttribute := GetFncAddress(System.HICUI18N, 'unum_setAttribute');
// @unum_getDoubleAttribute := GetFncAddress(System.HICUI18N, 'unum_getDoubleAttribute');
// @unum_setDoubleAttribute := GetFncAddress(System.HICUI18N, 'unum_setDoubleAttribute');
@unum_getTextAttribute := GetFncAddress(System.HICUI18N, 'unum_getTextAttribute');
// @unum_setTextAttribute := GetFncAddress(System.HICUI18N, 'unum_setTextAttribute');
// @unum_toPattern := GetFncAddress(System.HICUI18N, 'unum_toPattern');
@unum_getSymbol := GetFncAddress(System.HICUI18N, 'unum_getSymbol');
// @unum_setSymbol := GetFncAddress(System.HICUI18N, 'unum_setSymbol');
// @unum_getLocaleByType := GetFncAddress(System.HICUI18N, 'unum_getLocaleByType');
{ ucal.h File Reference }
{ http://www.icu-project.org/apiref/icu4c/ucal_8h.html }
// @ucal_openTimeZoneIDEnumeration := GetFncAddress(System.HICUI18N, 'ucal_openTimeZoneIDEnumeration');
// @ucal_openTimeZones := GetFncAddress(System.HICUI18N, 'ucal_openTimeZones');
// @ucal_openCountryTimeZones := GetFncAddress(System.HICUI18N, 'ucal_openCountryTimeZones');
// @ucal_getDefaultTimeZone := GetFncAddress(System.HICUI18N, 'ucal_getDefaultTimeZone');
// @ucal_setDefaultTimeZone := GetFncAddress(System.HICUI18N, 'ucal_setDefaultTimeZone');
// @ucal_getDSTSavings := GetFncAddress(System.HICUI18N, 'ucal_getDSTSavings');
@ucal_getNow := GetFncAddress(System.HICUI18N, 'ucal_getNow');
@ucal_open := GetFncAddress(System.HICUI18N, 'ucal_open');
@ucal_close := GetFncAddress(System.HICUI18N, 'ucal_close');
// @ucal_clone := GetFncAddress(System.HICUI18N, 'ucal_clone');
// @ucal_setTimeZone := GetFncAddress(System.HICUI18N, 'ucal_setTimeZone');
// @ucal_getTimeZoneID := GetFncAddress(System.HICUI18N, 'ucal_getTimeZoneID');
// @ucal_getTimeZoneDisplayName := GetFncAddress(System.HICUI18N, 'ucal_getTimeZoneDisplayName');
// @ucal_inDaylightTime := GetFncAddress(System.HICUI18N, 'ucal_inDaylightTime');
// @ucal_setGregorianChange := GetFncAddress(System.HICUI18N, 'ucal_setGregorianChange');
// @ucal_getGregorianChange := GetFncAddress(System.HICUI18N, 'ucal_getGregorianChange');
// @ucal_getAttribute := GetFncAddress(System.HICUI18N, 'ucal_getAttribute');
// @ucal_setAttribute := GetFncAddress(System.HICUI18N, 'ucal_setAttribute');
// @ucal_getAvailable := GetFncAddress(System.HICUI18N, 'ucal_getAvailable');
// @ucal_countAvailable := GetFncAddress(System.HICUI18N, 'ucal_countAvailable');
@ucal_getMillis := GetFncAddress(System.HICUI18N, 'ucal_getMillis');
@ucal_setMillis := GetFncAddress(System.HICUI18N, 'ucal_setMillis');
// @ucal_setDate := GetFncAddress(System.HICUI18N, 'ucal_setDate');
@ucal_setDateTime := GetFncAddress(System.HICUI18N, 'ucal_setDateTime');
@ucal_get := GetFncAddress(System.HICUI18N, 'ucal_get');
// @ucal_set := GetFncAddress(System.HICUI18N, 'ucal_set');
// @ucal_isSet := GetFncAddress(System.HICUI18N, 'ucal_isSet');
// @ucal_clearField := GetFncAddress(System.HICUI18N, 'ucal_clearField');
// @ucal_clear := GetFncAddress(System.HICUI18N, 'ucal_clear');
// @ucal_getLimit := GetFncAddress(System.HICUI18N, 'ucal_getLimit');
// @ucal_getLocaleByType := GetFncAddress(System.HICUI18N, 'ucal_getLocaleByType');
// @ucal_getTZDataVersion := GetFncAddress(System.HICUI18N, 'ucal_getTZDataVersion');
// @ucal_getCanonicalTimeZoneID := GetFncAddress(System.HICUI18N, 'ucal_getCanonicalTimeZoneID');
// @ucal_getFieldDifference := GetFncAddress(System.HICUI18N, 'ucal_getFieldDifference');
// @ucal_getTimeZoneTransitionDate := GetFncAddress(System.HICUI18N, 'ucal_getTimeZoneTransitionDate');
Result := True;
end;
procedure InitHIC;
begin
if System.HICUUC <> 0 then
InitHICUUC;
if System.HICUI18N <> 0 then
InitHICUI18N;
end;
procedure ClearCollatorCache;
begin
CollatorCache.Destroy;
end;
{ TCacheCollator }
procedure TCacheCollator.TCollatorItem.Destroy;
begin
System.FreeMem(LocaleStr);
if IsICUAvailable then
ucol_close(Collator);
end;
procedure TCacheCollator.Destroy;
var
I: Integer;
begin
for I := Low(LangCollators) to High(LangCollators) do
LangCollators[I].Destroy;
Finalize(LangCollators);
end;
constructor TCacheCollator.TCollatorItem.Create(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions);
var
ErrorCode: UErrorCode;
LLength: Integer;
begin
UsageCounter := 0;
LLength := Length(ALocaleStr) + 1;
LocaleStr := System.AllocMem(LLength);
System.Move(ALocaleStr^, LocaleStr^, LLength);
Options := AOptions;
ErrorCode := U_ZERO_ERROR;
Collator := ucol_open(ALocaleStr, ErrorCode);
if ErrorCode > U_ZERO_ERROR then
raise Exception.CreateFmt(SICUError, [Int32(ErrorCode), UTF8ToString(u_errorName(ErrorCode))]);
MapOptionsToCollator(AOptions, Collator);
end;
function TCacheCollator.GetUnusedIndex: Integer;
var
I: Integer;
MinValue: UInt32;
MinIndex: Integer;
begin
MinIndex := 0;
MinValue := MAXINT;
Result := -1;
for I := Low(LangCollators) to High(LangCollators) do
begin
// If there is one unused collator, first use this.
if LangCollators[I].UsageCounter = 0 then
begin
Result := I;
break;
end;
if LangCollators[I].UsageCounter < MinValue then
begin
MinValue := LangCollators[I].UsageCounter;
MinIndex := I;
end;
end;
if Result = -1 then
begin
// If all the collators were used, reset the usage statistics, and choose the least used.
Result := MinIndex;
for I := Low(LangCollators) to High(LangCollators) do
LangCollators[I].UsageCounter := 0;
end;
end;
function TCacheCollator.AddCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
var
I: Integer;
LLength: Integer;
begin
LLength := Length(LangCollators);
// If the collator is not found we add the collator or clean an old one.
if LLength < MaxCollatorCacheSize then
begin
SetLength(LangCollators, LLength + 1);
I := High(LangCollators);
end
else begin
I := GetUnusedIndex;
LangCollators[I].Destroy;
end;
LangCollators[I] := TCollatorItem.Create(ALocaleStr, AOptions);
Result := LangCollators[I].Collator;
end;
procedure TCacheCollator.AdjustUsageStatistics;
var
I: Integer;
begin
// Change in the same proportion all counters. Divide by 65536
for I := Low(LangCollators) to High(LangCollators) do
LangCollators[I].UsageCounter := LangCollators[I].UsageCounter shr 16;
end;
function TCacheCollator.FindCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
var
I: Integer;
begin
Result := nil;
for I := Low(LangCollators) to High(LangCollators) do
begin
if (LangCollators[I].Options = AOptions) and (strcmp(LangCollators[I].LocaleStr, ALocaleStr) = 0) then
begin
// If we get past the signed MAXINT value then we need to adjust the counters
// This likely will happen on servers that do a lot of string comparisions.
if LangCollators[I].UsageCounter > UInt32(MAXINT) then
AdjustUsageStatistics;
// Increment the use counter and return the Collator.
Inc(LangCollators[I].UsageCounter);
Result := LangCollators[I].Collator;
break;
end;
end;
end;
function TCacheCollator.GetCollator(const ALocaleStr: MarshaledAString; AOptions: TCompareOptions): PUCollator;
begin
Result := FindCollator(ALocaleStr, AOptions);
if Result = nil then
Result := AddCollator(ALocaleStr, AOptions);
end;
class procedure TCacheCollator.MapOptionsToCollator(AOptions: TCompareOptions; const collator: PUCollator);
begin
string.InternalMapOptionsToFlags(AOptions, Collator);
end;
initialization
InitICU;
finalization
ClearCollatorCache;
end.
|
unit SuperSocketUtils;
interface
uses
DebugTools, DynamicQueue,
SysUtils, Classes, WinSock2;
const
/// Packet size limitation including header.
PACKET_SIZE = 1024 * 32;
/// Concurrent connection limitation
CONNECTION_POOL_SIZE = 4096;
/// Buffer size of TPacketReader
PACKETREADER_PAGE_SIZE = PACKET_SIZE * 16;
MAX_IDLE_MS = 20000;
ERROR_CONNECT = -1;
type
{*
메모리를 사용후 해제하지 않고 큐에 넣어서 재사용한다.
PACKET_SIZE의 같은 크기의 메모리를 재사용하기 위해 사용.
}
TMemoryRecylce = class
strict private
FQueue : TDynamicQueue;
public
constructor Create;
destructor Destroy; override;
function Get:pointer;
procedure Release(AData:pointer);
end;
PPacket = ^TPacket;
{*
[Packet] = [PacketSize:word] [PacketType: byte] [Data]
}
TPacket = packed record
strict private
function GetData: pointer;
function GetDataSize: word;
procedure SetDataSize(const Value: word);
function GetText: string;
public
PacketSize : word;
PacketType : byte;
DataStart : byte;
class function GetPacket(APacketType:byte; AData:pointer; ASize:integer):PPacket; overload; static;
class function GetPacket(APacketType:byte; const AText:string):PPacket; overload; static;
procedure Clear;
procedure Clone(APacket:PPacket); overload;
function Clone:PPacket; overload;
public
property Data : pointer read GetData;
/// Size of [Data]
property DataSize : word read GetDataSize write SetDataSize;
/// Convert [Data] to string
property Text : string read GetText;
end;
TPacketReader = class
strict private
FBuffer : pointer;
FBufferSize : integer;
FOffset : integer;
FCapacity : integer;
FOffsetPtr : PByte;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Write(AData:pointer; ASize:integer);
function Read:PPacket;
function canRead:boolean;
function canReadSize:boolean;
{*
Check where packet is broken.
If it is, VerifyPacket will clear all packet inside.
}
function VerifyPacket:boolean;
public
property BufferSize : integer read FBufferSize;
end;
IMemoryPoolObserver = interface
['{8E41C992-E8F5-480E-94F1-D30E738506DB}']
procedure MemoryRefresh;
end;
IMemoryPoolControl = interface
['{B763D3F8-CABD-4CBA-82A4-A7B5804232AB}']
procedure AddObserver(AObserver:IMemoryPoolObserver);
function GetPacketClone(APacket:PPacket):PPacket;
end;
var
WSAData : TWSAData;
NilPacket : TPacket;
function GetIP(const AHost:AnsiString):AnsiString;
procedure SetSocketDelayOption(ASocket:integer; ADelay:boolean);
procedure SetSocketLingerOption(ASocket,ALinger:integer);
implementation
function GetIP(const AHost:AnsiString):AnsiString;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
i: Integer;
begin
Result := '';
phe := GetHostByName(PAnsiChar(AHost));
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
i := 0;
while pPtr^[i] <> nil do begin
Result := inet_ntoa(pptr^[i]^);
Inc(i);
end;
end;
procedure SetSocketDelayOption(ASocket:integer; ADelay:boolean);
var
iValue : integer;
begin
if ADelay then iValue := 0
else iValue := 1;
setsockopt( ASocket, IPPROTO_TCP, TCP_NODELAY, @iValue, SizeOf(iValue) );
end;
procedure SetSocketLingerOption(ASocket,ALinger:integer);
type
TLinger = packed record
OnOff : integer;
Linger : integer;
end;
var
Linger : TLinger;
begin
Linger.OnOff := 1;
Linger.Linger := ALinger;
setsockopt( ASocket, SOL_SOCKET, SO_LINGER, @Linger, SizeOf(Linger) );
end;
{ TMemoryRecylce }
constructor TMemoryRecylce.Create;
begin
FQueue := TDynamicQueue.Create(false);
end;
destructor TMemoryRecylce.Destroy;
begin
FreeAndNil(FQueue);
inherited;
end;
function TMemoryRecylce.Get: pointer;
const
// 돌려 받은 메모리를 바로 다시 할당하지 않도록 버퍼 공간을 둔다.
// 혹시라도 아주 짧은 순간에 돌려받은 메모리가 다른 프로세스에서 사용되거나 영향 줄까봐 노파심에
// 메모리를 조금 더 사용할 뿐 부정적 영향은 없을 거 같아서 추가된 코드 무시해도 된다.
SPARE_SPACE = 1024;
begin
if (FQueue.Count < SPARE_SPACE) or (not FQueue.Pop(Result)) then GetMem(Result, PACKET_SIZE);
end;
procedure TMemoryRecylce.Release(AData: pointer);
begin
FQueue.Push(AData);
end;
{ TPacket }
procedure TPacket.Clear;
begin
PacketSize := 0;
PacketType := 0;
end;
function TPacket.Clone: PPacket;
begin
GetMem(Result, PacketSize);
Move(Self, Result^, PacketSize);
end;
procedure TPacket.Clone(APacket: PPacket);
begin
Move(Self, APacket^, PacketSize);
end;
function TPacket.GetData: pointer;
begin
Result := @DataStart;
end;
class function TPacket.GetPacket(APacketType: byte; const AText: string): PPacket;
var
utf8 : UTF8String;
begin
if AText = '' then begin
Result := TPacket.GetPacket(APacketType, nil, 0);
Exit;
end;
utf8 := AText;
Result := TPacket.GetPacket(APacketType, @utf8[1], Length(utf8));
end;
class function TPacket.GetPacket(APacketType:byte; AData:pointer; ASize:integer): PPacket;
begin
GetMem(Result, ASize + SizeOf(Word) + SizeOf(Byte));
Result^.PacketType := APacketType;
Result^.DataSize := ASize;
if ASize > 0 then Move(AData^, Result^.Data^, ASize);
end;
function TPacket.GetText: string;
var
utf8 : UTF8String;
begin
SetLength(utf8, GetDataSize);
Move(DataStart, utf8[1], GetDataSize);
Result := utf8;
end;
function TPacket.GetDataSize: word;
begin
Result := PacketSize - SizeOf(Word) - SizeOf(Byte);
end;
procedure TPacket.SetDataSize(const Value: word);
begin
PacketSize := Value + SizeOf(Word) + SizeOf(Byte);
end;
{ TPacketReader }
function TPacketReader.canRead: boolean;
var
PacketPtr : PPacket;
begin
if FOffsetPtr = nil then begin
Result := false;
Exit;
end;
PacketPtr := Pointer(FOffsetPtr);
Result := (FBufferSize > 0) and (FBufferSize >= PacketPtr^.PacketSize);
end;
function TPacketReader.canReadSize: boolean;
var
PacketPtr : PPacket;
begin
if FOffsetPtr = nil then begin
Result := false;
Exit;
end;
PacketPtr := Pointer(FOffsetPtr);
Result := FBufferSize >= SizeOf(Word);
end;
procedure TPacketReader.Clear;
begin
FBufferSize := 0;
FOffset := 0;
FCapacity := 0;
if FBuffer <> nil then FreeMem(FBuffer);
FBuffer := nil;
FOffsetPtr := nil;
end;
constructor TPacketReader.Create;
begin
inherited;
FBuffer := nil;
FBufferSize := 0;
FOffset := 0;
FCapacity := 0;
FOffsetPtr := nil;
end;
destructor TPacketReader.Destroy;
begin
Clear;
inherited;
end;
function TPacketReader.Read: PPacket;
begin
Result := nil;
if not canRead then Exit;
Result := Pointer(FOffsetPtr);
FBufferSize := FBufferSize - Result^.PacketSize;
FOffset := FOffset + Result^.PacketSize;
FOffsetPtr := FOffsetPtr + Result^.PacketSize;
end;
function TPacketReader.VerifyPacket:boolean;
var
PacketPtr : PPacket;
begin
Result := true;
if not canReadSize then Exit;
PacketPtr := Pointer(FOffsetPtr);
Result := PacketPtr^.PacketSize <= PACKET_SIZE;
{$IFDEF DEBUG}
if Result = false then begin
Trace( Format('TPacketReader.VerifyPacket - Size: %d', [PacketPtr^.PacketSize]) );
end;
{$ENDIF}
end;
procedure TPacketReader.Write(AData: pointer; ASize: integer);
var
iNewSize : integer;
pNewData : pointer;
pTempIndex : pbyte;
pOldData : pointer;
begin
if ASize <= 0 then Exit;
iNewSize := FBufferSize + ASize;
if (iNewSize + FOffset) > FCapacity then begin
FCapacity := ((iNewSize div PACKETREADER_PAGE_SIZE) + 1) * PACKETREADER_PAGE_SIZE;
GetMem(pNewData, FCapacity);
pTempIndex := pNewData;
if FBufferSize > 0 then begin
Move(FOffsetPtr^, pTempIndex^, FBufferSize);
pTempIndex := pTempIndex + FBufferSize;
end;
Move(AData^, pTempIndex^, ASize);
FOffset := 0;
pOldData := FBuffer;
FBuffer := pNewData;
if pOldData <> nil then FreeMem(pOldData);
FOffsetPtr := FBuffer;
end else begin
pTempIndex := FOffsetPtr + FBufferSize;
Move(AData^, pTempIndex^, ASize);
end;
FBufferSize := iNewSize;
end;
initialization
NilPacket.PacketSize := 3;
NilPacket.PacketType := 255;
if WSAStartup(WINSOCK_VERSION, WSAData) <> 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
finalization
WSACleanup;
end.
|
unit MediaStream.Filer.Wave;
interface
uses SysUtils,Classes, Windows, SyncObjs, MediaStream.Filer, MediaProcessing.Definitions,MediaStream.Writer.Wave;
type
TStreamFilerWave = class (TStreamFiler)
private
FWriter: TMediaStreamWriter_Wave;
protected
procedure DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Close; override;
class function DefaultExt: string; override;
end;
implementation
{ TStreamFilerWave }
procedure TStreamFilerWave.Close;
begin
FWriter.Close;
inherited;
end;
constructor TStreamFilerWave.Create;
begin
inherited;
FWriter:=TMediaStreamWriter_Wave.Create;
end;
class function TStreamFilerWave.DefaultExt: string;
begin
result:='.wav';
end;
destructor TStreamFilerWave.Destroy;
begin
inherited;
FreeAndNil(FWriter);
end;
procedure TStreamFilerWave.DoWriteData(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
begin
if (aFormat.biMediaType=mtAudio) and (aFormat.biStreamType=stPCM) then
begin
if not FWriter.Opened then
FWriter.Open(self.FStream,aFormat.AudioChannels,aFormat.AudioSamplesPerSec,aFormat.AudioBitsPerSample);
FWriter.WritePcmData(aData,aDataSize);
end;
end;
end.
|
PROGRAM FBS;
PROCEDURE BruteSearch(s, p : STRING;
VAR pos : INTEGER);
VAR
sLen, pLen, i, j : INTEGER;
wrongChar : BOOLEAN;
BEGIN
sLen := Length(s); pLen := Length(p);
i := 1; j := 1;
wrongChar := false;
REPEAT
IF s[i] = p[j] THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
IF ((wrongChar) OR (j = 1)) THEN BEGIN
i := i - j + 2;
j := 1;
END ELSE BEGIN
wrongChar := true;
Inc(i);
Inc(j);
END; (* IF *)
END;
UNTIL (i > sLen) OR (j > pLen);
IF j > pLen THEN
pos := i - pLen
ELSE
pos := 0;
END; (* BruteSearch *)
VAR i : INTEGER;
BEGIN (* FBS *)
BruteSearch('AABC', 'ABC', i);
WriteLn(i);
BruteSearch('ABXZ', 'ABC', i);
WriteLn(i);
BruteSearch('XYAXC', 'ABC', i);
WriteLn(i);
BruteSearch('BBC', 'ABC', i);
WriteLn(i);
END. (* FBS *) |
{
Этот файл является частью библиотеки CryptEngine\CryptoChat
Copyright (c) 2015-2015 by Anton Rodin
Работа с базой данных
Назначение таблиц:
- USERS - Список пользователей системы
- FRIENDS - Список друзей пользователя
- MESSAGES - Список сообщений
- TRANSPORT - Настройки транспорта
**********************************************************************}
unit Databases;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, sqlite3conn, FileUtil, Dialogs, md5,
SQLite3, SQLite3Wrap, LazUTF8;
const
INVALID_VALUE = -1;
CONNECTIONTYPE_EMAIL = 0;
type
TMsgDirection = (mdIncomingMsg = 1 {Входящее}, mdoutgoingMsg = 2{Исходящее});
TMsgType = (mtAddFriend{добавление в друзья}, mtExchangeKey{обмен ключами},
mtMessage {сообщение});
{ TCustomDataBase }
TCustomDataBase = class(TObject)
private
// Для основной работы
CriticalSection: TRTLCriticalSection;
SqliteDatabase: TSQLite3Database;
{: Обновление структур основных таблиц в базе данных}
procedure UpdateGeneralTableStructure;
public
constructor Create; virtual;
destructor Destroy; override;
{: Создание новой базы данных}
function CreateDataBase(FileName: string): boolean;
{: Открытие БД SQLite}
function OpenDataBase(DBPath: string): boolean;
{: Выполнить произвольный запрос}
function ExecSQL(SQLText: string): boolean;
public
{: Добавление нового пользователя}
function AddUser(const NickName, Password, Email: string; const AvatarFileName: string = ''): boolean;
{: Удаление пользователя}
function RemoveUser(UserID: integer): boolean;
{: Установить NickName пользователю}
function SetUserNickName(UserID: integer; const NickName: string): boolean;
{: Установить Email пользователю}
function SetUserEMail(UserID: integer; const EMail: string): boolean;
{: Установить аватарку пользователю из файла}
function SetUserAvatar(UserID: integer; const AvatarFileName: string = ''): boolean;
{: Получить NickName пользователя}
function GetUserNickName(UserID: integer): string;
{: Получить Email пользователя}
function GetUserEMail(UserID: integer): string;
{: Получить PasswordHash пользователя}
function GetUserPasswordHash(UserID: integer): string;
{: Сохранить аватарку пользоватля в поток}
function SaveUserAvatarToStream(UserID: integer; Stream: TStream): boolean;
{: Получить информацию о пользователе}
function GetUserInfo(UserID: integer; out NickName, PasswordHash, Email: string): boolean;
{: Получить количество пользователей в БД}
function GetUsersCount: integer;
{: Узнать наличие пользователя в БД}
function UserExist(AnyStrData: string): integer;
public
{: Добавить способ передачи данных}
function AddTransport(UserID, TypeConnection, PortIncoming, PortOutgoing: integer;
HostIncoming, HostOutgoing, User, Password: string): boolean;
{: Удаление транспорта}
function RemoveTransport(UserID: integer): boolean;
{: Получить тип сетевого соединения}
function GetTransportType(UserID: integer): integer;
{: Получить порт входящих сообщений}
function GetTransportPortIn(UserID: integer): integer;
{: Получить порт исходящих сообщений}
function GetTransportPortOut(UserID: integer): integer;
{: Получить хост входящих}
function GetTransportHostIn(UserID: integer): string;
{: Получить хост исходящих}
function GetTransportHostOut(UserID: integer): string;
{: Получить имя пользователя\логин для авторизации на хосте}
function GetTransportUserName(UserID: integer): string;
{: Получить пароль для авторизации на хосте}
function GetTransportPassword(UserID: integer): string;
public
{: Добавить нового друга}
function AddFriend(UserID: integer; const NickName, Email: string; const AvatarFileName: string = ''): boolean;
{: Удалить друга}
function RemoveFriend(UserID, FriendID: integer): boolean;
{: Установить новое имя пользователю}
function SetFriendNickName(UserID, FriendID: integer; NickName: string): boolean;
{: Присвоить новую почту пользователю}
function SetFriendEmail(UserID, FriendID: integer; EMail: string): boolean;
{: Получить имя пользователя}
function GetFriendNickName(UserID, FriendID: integer): string;
{: Получить email пользователя}
function GetFriendEmail(UserID, FriendID: integer): string;
{: Получить количество друзей пользователя}
function GetFriendsCount(UserID: integer): integer;
{: Сохранить аватарку друга в поток}
function SaveFriendAvatarToStream(UserID, FriendID: integer; Stream: TStream): boolean;
public
{: Добавление нового сообщения}
function AddMessage(UserID, FriendID: integer; Direction: TMsgDirection; TypeMsg: TMsgType;
MessageStream, OpenKey, PrivateKey, BlowFishKey: TStream): boolean;
{: Удаление сообщения}
function RemoveMessage(UserID, FriendID, ID: integer): boolean;
{: Получить направление сообщения}
function GetMessageDirection(UserID, FriendID, ID: integer): TMsgDirection;
{: Получить тип сообщения}
function GetMessageType(UserID, FriendID, ID: integer): TMsgType;
{: Получить закодированные данные сообщения}
function GetMessage(UserID, FriendID, ID: integer; Stream: TStream): boolean;
{: Получить дату сообщения}
function GetMessageDate(UserID, FriendID, ID: integer): TDateTime;
{: Получить открытый ключ}
function GetMessageOpenKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
{: Получить закрытый ключ}
function GetMessagePrivateKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
{: Получить blowfish ключ}
function GetMessageBlowFishKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
{: Получить количество сообщений}
function GetMessagesCount(UserID, FriendID: integer): integer;
end;
type
{ TDataBase }
TDataBase = class(TCustomDataBase)
private
fCurrentUserID: integer;
fFileName: string;
public
constructor Create; override;
destructor Destroy; override;
public
{: Вход в систему}
function Login(EMail, Password: string): boolean;
public
property CurrentUserID: integer read fCurrentUserID;
property FileName: string read fFileName write fFileName;
end;
var
DataBase: TDataBase;
implementation
{ TDataBase }
constructor TDataBase.Create;
begin
inherited Create;
fFileName := ExtractFilePath(ParamStrUTF8(0)) + 'DATA' + PathDelim + 'DataBase.SQLite3';
end;
destructor TDataBase.Destroy;
begin
inherited Destroy;
end;
function TDataBase.Login(EMail, Password: string): boolean;
// Вход в систему
var
UserID: integer;
begin
Result := False;
UserID := UserExist(EMail);
if UserID <> INVALID_VALUE then
begin
if MD5Print(MD5String(Password)) = GetUserPasswordHash(UserID) then
Result := True;
end;
fCurrentUserID := UserID;
end;
{ TCustomDataBase }
procedure TCustomDataBase.UpdateGeneralTableStructure;
// Обновление структур основных таблиц в базе данных
begin
// Таблица с описанием пользователей программы
ExecSQL('CREATE TABLE IF NOT EXISTS USERS (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, NickName TEXT, Email TEXT, ' +
'PasswordHash TEXT, AVATAR BLOB)');
// Таблица с описанием друзей
ExecSQL('CREATE TABLE IF NOT EXISTS FRIENDS (USERID INTEGER REFERENCES ID(USERS), ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ' +
'NickName TEXT, Email TEXT, AVATAR BLOB)');
// Таблица с сообщениями
///////////////////////////////////////
// 1. Пользователь
// 2. Друг
// 3. Направление сообщения (входящее, исходящее)
// 4. Тип (обмен ключами, сообщение, добавление в друзья)
// 5. Сообщение в зашифрованном виде
// 6. Дата сообщения
// 7. Открытый ключ RSA
// 8. Закрытый ключ RSA
// 9. Ключ BlowFish
///////////////////////////////////////
ExecSQL('CREATE TABLE IF NOT EXISTS MESSAGES (USERID INTEGER REFERENCES ID(USERS), FRIENDID INTEGER REFERENCES ID(Friends), ' +
'ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, DIRECTION INTEGER, TYPE INTEGER, ENCMESSAGE BLOB, DATE DATETIME, ' +
'OPENKEY BLOB, PRIVATEKEY BLOB, BLOWFISHKEY BLOB)');
ExecSQL('CREATE TABLE IF NOT EXISTS TRANSPORTS (USERID INTEGER REFERENCES ID(USERS), TYPE INTEGER, PORTIN INTEGER, ' +
'PORTOUT INTEGER, HOSTIN TEXT, HOSTOUT TEXT, USERNAME TEXT, PASSWORD TEXT)');
end;
constructor TCustomDataBase.Create;
begin
inherited Create;
end;
destructor TCustomDataBase.Destroy;
begin
if Assigned(SqliteDatabase) then
FreeAndNil(SqliteDatabase);
inherited Destroy;
end;
function TCustomDataBase.CreateDataBase(FileName: string): boolean;
// Создание новой базы данных
begin
Result := True;
try
if Assigned(SqliteDatabase) then
FreeAndNil(SqliteDatabase);
SqliteDatabase := TSQLite3Database.Create;
SqliteDatabase.Open(WideString(FileName));
UpdateGeneralTableStructure;
Result := FileExists(FileName);
except
Result := False;
end;
end;
function TCustomDataBase.OpenDataBase(DBPath: string): boolean;
// Открытие БД SQLite
begin
try
Result := CreateDataBase(DBPath);
if Result then
UpdateGeneralTableStructure;
except
Result := False;
end;
end;
function TCustomDataBase.ExecSQL(SQLText: string): boolean;
// Выполнить произвольный запрос
begin
EnterCriticalsection(CriticalSection);
try
try
Result := True;
SqliteDatabase.Execute(WideString(SQLText));
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.AddUser(const NickName, Password, Email: string; const AvatarFileName: string): boolean;
// Создание нового пользователя
var
Stmt: TSQLite3Statement;
Stream: TMemoryStream;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
if AvatarFileName <> '' then
begin
Stmt := SqliteDatabase.Prepare('INSERT INTO USERS (NickName, Email, PasswordHash, AVATAR) VALUES (?, ?, ?, ?)');
Stream := TMemoryStream.Create;
Stream.LoadFromFile(AvatarFileName);
Stmt.BindText(1, WideString(NickName));
Stmt.BindText(2, WideString(EMail));
Stmt.BindText(3, WideString(MD5Print(MD5String(Password))));
Stmt.BindBlob(4, Stream.Memory, Stream.Size);
Stream.Free;
Stmt.Step;
Stmt.Free;
end
else
begin
SqliteDatabase.Execute(
WideString(Format('INSERT INTO USERS (NickName, Email, PasswordHash) VALUES (''%s'', ''%s'', ''%s'');',
[NickName, Email, MD5Print(MD5String(Password))])));
end;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.RemoveUser(UserID: integer): boolean;
// Удаление пользователя
begin
Result := ExecSQL(Format('DELETE FROM USERS WHERE ID = %d', [UserID]));
end;
function TCustomDataBase.SetUserNickName(UserID: integer; const NickName: string): boolean;
// Установить NickName пользователю
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare('UPDATE USERS SET NickName = ? WHERE ID = ?');
Stmt.BindText(1, WideString(NickName));
Stmt.BindInt(2, UserID);
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.SetUserEMail(UserID: integer; const EMail: string): boolean;
// Установить Email пользователю
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare('UPDATE USERS SET EMail = ? WHERE ID = ?');
Stmt.BindText(1, WideString(EMail));
Stmt.BindInt(2, UserID);
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.SetUserAvatar(UserID: integer; const AvatarFileName: string): boolean;
// Установка новой аватарки пользователю
var
Stmt: TSQLite3Statement;
Stream: TMemoryStream;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare('UPDATE USERS SET AVATAR = ? WHERE ID = ?');
Stream := TMemoryStream.Create;
Stream.LoadFromFile(AvatarFileName);
Stmt.BindBlob(1, Stream.Memory, Stream.Size);
Stmt.BindInt(2, UserID);
Stream.Free;
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetUserNickName(UserID: integer): string;
// Получить NickName пользователя
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT NickName FROM USERS WHERE ID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetUserEMail(UserID: integer): string;
// Получить Email пользователя
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT Email FROM USERS WHERE ID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetUserPasswordHash(UserID: integer): string;
// Получить PasswordHash пользователя
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT PasswordHash FROM USERS WHERE ID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.SaveUserAvatarToStream(UserID: integer; Stream: TStream): boolean;
// Сохранение пользовательской аватарки в файл
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT AVATAR FROM USERS WHERE ID = ' + WideString(IntToStr(UserID)));
try
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetUserInfo(UserID: integer; out NickName, PasswordHash, Email: string): boolean;
// Получить информацию о пользователе
var
Stmt: TSQLite3Statement;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
try
Stmt := SqliteDatabase.Prepare('SELECT NickName, EMail, PasswordHash FROM USERS WHERE ID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
NickName := string(Stmt.ColumnText(0));
Email := string(Stmt.ColumnText(1));
PasswordHash := string(Stmt.ColumnText(2));
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetUsersCount: integer;
// Получить количество пользователей
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT COUNT(ID) FROM USERS');
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.UserExist(AnyStrData: string): integer;
// Узнать наличие пользователя в БД
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT ID, NickName FROM USERS');
while Stmt.Step = SQLITE_ROW do
if Stmt.ColumnText(1) = WideString(AnyStrData) then
Exit(Stmt.ColumnInt(0));
Stmt := SqliteDatabase.Prepare('SELECT ID, Email FROM USERS');
while Stmt.Step = SQLITE_ROW do
if Stmt.ColumnText(1) = WideString(AnyStrData) then
Exit(Stmt.ColumnInt(0));
Stmt := SqliteDatabase.Prepare('SELECT ID, PasswordHash FROM USERS');
while Stmt.Step = SQLITE_ROW do
if Stmt.ColumnText(1) = WideString(AnyStrData) then
Exit(Stmt.ColumnInt(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.AddTransport(UserID, TypeConnection, PortIncoming, PortOutgoing: integer;
HostIncoming, HostOutgoing, User, Password: string): boolean;
// Добавление настроек соединения
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare(
'INSERT INTO TRANSPORTS (USERID, TYPE, PORTIN, PORTOUT, HOSTIN, HOSTOUT, USERNAME, PASSWORD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
Stmt.BindInt(1, UserID);
Stmt.BindInt(2, TypeConnection);
Stmt.BindInt(3, PortIncoming);
Stmt.BindInt(4, PortOutgoing);
Stmt.BindText(5, WideString(HostIncoming));
Stmt.BindText(6, WideString(HostOutgoing));
Stmt.BindText(7, WideString(User));
Stmt.BindText(8, WideString(Password));
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.RemoveTransport(UserID: integer): boolean;
// Удаление транспорта
begin
Result := ExecSQL(Format('DELETE FROM TRANSPORTS WHERE USERID = %d', [UserID]));
end;
function TCustomDataBase.GetTransportType(UserID: integer): integer;
// Получить тип сетевого соединения
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT TYPE FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportPortIn(UserID: integer): integer;
// Получить порт входящих сообщений
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT PORTIN FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportPortOut(UserID: integer): integer;
// Получить порт исходящих сообщений
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT PORTOUT FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportHostIn(UserID: integer): string;
// Получить хост входящих
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT HOSTIN FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportHostOut(UserID: integer): string;
// Получить хост исходящих
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT HOSTOUT FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportUserName(UserID: integer): string;
// Получить имя пользователя\логин для авторизации на хосте
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT USERNAME FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetTransportPassword(UserID: integer): string;
// Получить пароль для авторизации на хосте
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT PASSWORD FROM TRANSPORTS WHERE USERID = ' + WideString(IntToStr(UserID)));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.AddFriend(UserID: integer; const NickName, Email: string; const AvatarFileName: string): boolean;
// Добавить нового друга
var
Stmt: TSQLite3Statement;
Stream: TMemoryStream;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
if AvatarFileName <> '' then
begin
Stmt := SqliteDatabase.Prepare('INSERT INTO FRIENDS (UserID, NickName, Email, AVATAR) VALUES (?, ?, ?, ?)');
Stream := TMemoryStream.Create;
Stream.LoadFromFile(AvatarFileName);
Stmt.BindInt(1, UserID);
Stmt.BindText(2, WideString(NickName));
Stmt.BindText(3, WideString(EMail));
Stmt.BindBlob(4, Stream.Memory, Stream.Size);
Stream.Free;
Stmt.Step;
Stmt.Free;
end
else
begin
SqliteDatabase.Execute(
WideString(Format('INSERT INTO FRIENDS (UserID, NickName, Email) VALUES (''%d'', ''%s'', ''%s'');', [UserID, NickName, Email])));
end;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.RemoveFriend(UserID, FriendID: integer): boolean;
// Удалить друга
begin
Result := ExecSQL(Format('DELETE FROM FRIENDS WHERE USERID = %d AND ID = %d', [UserID, FriendID]));
end;
function TCustomDataBase.SetFriendNickName(UserID, FriendID: integer; NickName: string): boolean;
// Установить новое имя пользователю
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare('UPDATE FRIENDS SET NickName = ? WHERE USERID = ? AND ID = ?');
Stmt.BindText(1, WideString(NickName));
Stmt.BindInt(2, UserID);
Stmt.BindInt(3, FriendID);
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.SetFriendEmail(UserID, FriendID: integer; EMail: string): boolean;
// Присвоить новую почту пользователю
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare('UPDATE FRIENDS SET EMail = ? WHERE USERID = ? AND ID = ?');
Stmt.BindText(1, WideString(EMail));
Stmt.BindInt(2, UserID);
Stmt.BindInt(3, FriendID);
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetFriendNickName(UserID, FriendID: integer): string;
// Получить имя пользователя
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT NickName FROM FRIENDS WHERE USERID = %d AND ID = %d', [UserID, FriendID])));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetFriendEmail(UserID, FriendID: integer): string;
// Получить email пользователя
var
Stmt: TSQLite3Statement;
begin
Result := '';
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT EMail FROM FRIENDS WHERE USERID = %d AND ID = %d', [UserID, FriendID])));
Stmt.Step;
Result := string(Stmt.ColumnText(0));
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetFriendsCount(UserID: integer): integer;
// Получить количество друзей
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString('SELECT COUNT(ID) FROM FRIENDS WHERE USERID = ' + IntToStr(UserID)));
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.SaveFriendAvatarToStream(UserID, FriendID: integer; Stream: TStream): boolean;
// Сохранить аватарку друга в поток
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT AVATAR FROM FRIENDS WHERE USERID = ? AND ID = ?');
try
Stmt.BindInt(1, UserID);
Stmt.BindInt(2, FriendID);
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.AddMessage(UserID, FriendID: integer; Direction: TMsgDirection; TypeMsg: TMsgType;
MessageStream, OpenKey, PrivateKey, BlowFishKey: TStream): boolean;
// Добавление нового сообщения
var
Stmt: TSQLite3Statement;
begin
EnterCriticalsection(CriticalSection);
try
Result := True;
try
Stmt := SqliteDatabase.Prepare(
'INSERT INTO MESSAGES (UserID, FriendID, Direction, Type, EncMessage, Date, OpenKey, PrivateKey, BlowFishKey) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
Stmt.BindInt(1, UserID);
Stmt.BindInt(2, FriendID);
case Direction of
mdIncomingMsg: Stmt.BindInt(3, 1);
mdoutgoingMsg: Stmt.BindInt(3, 2);
end;
case TypeMsg of
mtAddFriend: Stmt.BindInt(4, 1);
mtExchangeKey: Stmt.BindInt(4, 2);
mtMessage: Stmt.BindInt(4, 3);
end;
Stmt.BindBlob(5, MessageStream, MessageStream.Size);
Stmt.BindDouble(6, Now);
Stmt.BindBlob(7, OpenKey, OpenKey.Size);
Stmt.BindBlob(8, PrivateKey, PrivateKey.Size);
Stmt.BindBlob(9, BlowFishKey, BlowFishKey.Size);
Stmt.Step;
Stmt.Free;
except
Result := False;
end;
finally
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.RemoveMessage(UserID, FriendID, ID: integer): boolean;
// Удаление сообщения
begin
Result := ExecSQL(Format('DELETE FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d', [UserID, FriendID, ID]));
end;
function TCustomDataBase.GetMessageDirection(UserID, FriendID, ID: integer): TMsgDirection;
// Получить направление сообщения
var
Stmt: TSQLite3Statement;
begin
Result := mdoutgoingMsg;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT Direction FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
Stmt.Step;
if Stmt.ColumnInt(0) = 1 then
Result := mdIncomingMsg;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessageType(UserID, FriendID, ID: integer): TMsgType;
// Получить тип сообщения
var
Stmt: TSQLite3Statement;
begin
Result := mtMessage;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT TYPE FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
Stmt.Step;
case Stmt.ColumnInt(0) of
1: Result := mtAddFriend;
2: Result := mtExchangeKey;
else
Result := mtMessage;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessage(UserID, FriendID, ID: integer; Stream: TStream): boolean;
// Получение сообщения
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT ENCMESSAGE FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
try
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessageDate(UserID, FriendID, ID: integer): TDateTime;
// Получить закодированные данные сообщения
var
Stmt: TSQLite3Statement;
begin
Result := 0;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT Date FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
Stmt.Step;
Result := Stmt.ColumnDouble(0);
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessageOpenKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
// Получить открытый ключ
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT OPENKEY FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
try
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessagePrivateKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
// Получить закрытый ключ
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT PrivateKey FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
try
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessageBlowFishKey(UserID, FriendID, ID: integer; Stream: TStream): boolean;
// Получить blowfish ключ
var
Stmt: TSQLite3Statement;
MemoryStream: TMemoryStream;
Size: integer;
begin
Result := True;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare(WideString(Format('SELECT BLOWFISHKEY FROM MESSAGES WHERE USERID = %d AND FRIENDID = %d AND ID = %d',
[UserID, FriendID, ID])));
try
Stmt.Step;
Size := Stmt.ColumnBytes(0);
MemoryStream := TMemoryStream.Create;
MemoryStream.SetSize(Size);
MemoryStream.Write(Stmt.ColumnBlob(0)^, Size);
MemoryStream.Position := 0;
MemoryStream.SaveToStream(Stream);
MemoryStream.Free;
except
Result := False;
end;
finally
Stmt.Free;
LeaveCriticalsection(CriticalSection);
end;
end;
function TCustomDataBase.GetMessagesCount(UserID, FriendID: integer): integer;
// Получаем количество сообщений
var
Stmt: TSQLite3Statement;
begin
Result := INVALID_VALUE;
EnterCriticalsection(CriticalSection);
try
Stmt := SqliteDatabase.Prepare('SELECT COUNT(ID) FROM MESSAGES WHERE USERID = ? AND FRIENDID = ?');
Stmt.BindInt(1, UserID);
Stmt.BindInt(2, FriendID);
Stmt.Step;
Result := Stmt.ColumnInt(0);
finally
LeaveCriticalsection(CriticalSection);
end;
end;
initialization
{$IFDEF WINDOWS}// Windows
SQLiteLibraryName := 'sqlite3.dll';
{$ENDIF}
DataBase := TDataBase.Create;
finalization
if Assigned(DataBase) then
DataBase.Free;
end.
|
unit ReportQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap, BaseEventsQuery;
type
TReportW = class(TDSWrap)
private
FИзображение: TFieldWrap;
FОписание: TFieldWrap;
FСпецификация: TFieldWrap;
FСхема: TFieldWrap;
FЧертёж: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property Изображение: TFieldWrap read FИзображение;
property Описание: TFieldWrap read FОписание;
property Спецификация: TFieldWrap read FСпецификация;
property Схема: TFieldWrap read FСхема;
property Чертёж: TFieldWrap read FЧертёж;
end;
TQueryReports = class(TQueryBaseEvents)
private
FW: TReportW;
procedure DoBeforeOpen(Sender: TObject);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property W: TReportW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses NotifyEvents, DefaultParameters;
constructor TQueryReports.Create(AOwner: TComponent);
begin
inherited;
TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList);
end;
function TQueryReports.CreateDSWrap: TDSWrap;
begin
Result := TReportW.Create(FDQuery);
end;
procedure TQueryReports.DoBeforeOpen(Sender: TObject);
begin
// Заполняем код параметра "Производитель"
FDQuery.ParamByName('ProducerParamSubParamID').AsInteger :=
TDefaultParameters.ProducerParamSubParamID;
FDQuery.ParamByName('PackagePinsParamSubParamID').AsInteger :=
TDefaultParameters.PackagePinsParamSubParamID;
FDQuery.ParamByName('DatasheetParamSubParamID').AsInteger :=
TDefaultParameters.DatasheetParamSubParamID;
FDQuery.ParamByName('DiagramParamSubParamID').AsInteger :=
TDefaultParameters.DiagramParamSubParamID;
FDQuery.ParamByName('DrawingParamSubParamID').AsInteger :=
TDefaultParameters.DrawingParamSubParamID;
FDQuery.ParamByName('ImageParamSubParamID').AsInteger :=
TDefaultParameters.ImageParamSubParamID;
end;
constructor TReportW.Create(AOwner: TComponent);
begin
inherited;
FИзображение := TFieldWrap.Create(Self, 'Изображение');
FОписание := TFieldWrap.Create(Self, 'Описание');
FСпецификация := TFieldWrap.Create(Self, 'Спецификация');
FСхема := TFieldWrap.Create(Self, 'Схема');
FЧертёж := TFieldWrap.Create(Self, 'Чертёж');
end;
end.
|
unit Main;
interface
uses
// Delphi/Windows
Windows, Menus, Forms, Classes, Controls, SysUtils,
// (J)VCL
JvMenus, JvComponentBase, JvTrayIcon, JvAppInst,
// SysTool
Global
;
type
TFormMain = class(TForm)
JvTrayIcon: TJvTrayIcon;
JvPopupMenuTray: TJvPopupMenu;
TrayMenuItemStayOnTop: TMenuItem;
TrayMenuItemFileUtilities: TMenuItem;
TrayMenuItemBitPattern: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
TrayMenuItemQuit: TMenuItem;
N3: TMenuItem;
TrayMenuItemSessionID: TMenuItem;
TrayMenuItemStyle: TMenuItem;
TrayMenuItemStyleBtnLowered: TMenuItem;
TrayMenuItemStyleBtnRaised: TMenuItem;
TrayMenuItemStyleItemPainter: TMenuItem;
TrayMenuItemStyleOffice: TMenuItem;
TrayMenuItemStyleOwnerDraw: TMenuItem;
TrayMenuItemStyleStandard: TMenuItem;
TrayMenuItemStyleXP: TMenuItem;
TrayMenuItemHide: TMenuItem;
TrayMenuItemConvert: TMenuItem;
N4: TMenuItem;
TrayMenuItemConvertLocalToUNC: TMenuItem;
TrayMenuItemConvertUNCToLocal: TMenuItem;
JvAppInstances: TJvAppInstances;
procedure FormCreate(Sender: TObject); // module routine
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); // module routine
procedure TrayMenuItemStayOnTopClick(Sender: TObject);
procedure TrayMenuItemQuitClick(Sender: TObject);
procedure TrayMenuItemBitPatternClick(Sender: TObject);
procedure TrayMenuItemFileUtilitiesClick(Sender: TObject);
procedure FormDblClick(Sender: TObject);
procedure JvTrayIconDblClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure TrayMenuItemStyleClick(Sender: TObject);
procedure TrayMenuItemHideClick(Sender: TObject);
procedure TrayMenuItemConvertLocalToUNCClick(Sender: TObject);
procedure TrayMenuItemConvertUNCToLocalClick(Sender: TObject);
private
// none
public
ActiveModule: TSysToolModule;
procedure SetFormStayOnTop(StayOnTop: Boolean); // module routine
end;
var
FormMain: TFormMain;
implementation
uses
// Delphi/Windows
StrUtils, ClipBrd,
// SysTool
BitPattern, FileAnalysis
;
{$R *.dfm}
procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Global.SetRegistryKeyValue(REGKEY_COMMON_STAY_ON_TOP, TrayMenuItemStayOnTop.Checked);
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
StayOnTop : Variant;
ProcessID : DWORD;
CursorPos : TPoint;
begin
ProcessID := GetCurrentProcessID;
TrayMenuItemStayOnTop.Checked := FALSE;
if Global.GetRegistryKeyValue(REGKEY_COMMON_STAY_ON_TOP, StayOnTop) then
begin
TrayMenuItemStayOnTop.Checked := StayOnTop;
Self.SetFormStayOnTop(StayOnTop);
end;
TrayMenuItemSessionID.Caption :=
Format('%s (PID %d)', [Global.GetSessionKey(svHost), ProcessID]);
if not GetCommandLineSwitch(clsStartupSilent) and JvTrayIcon.AcceptBalloons then
begin
JvTrayIcon.BalloonHint(
{ Title = } Format('%s', [Global.GetApplicationNameVersionString()]),
{ Message = } Format('Host %s, PID %d', [Global.GetSessionKey(svHost), ProcessID]),
{ Style = } btNone // btNone btError btInfo btWarning
{ Delay = 5000, }
{ Cancel = FALSE }
);
end;
ActiveModule := stmNone;
if not GetCommandLineSwitch(clsStartupNoMenu) and
not GetCommandLineSwitch(clsStartupSilent) then
begin
CursorPos := Mouse.CursorPos;
JvPopupMenuTray.Popup(CursorPos.X, CursorPos.Y);
end;
end;
procedure TFormMain.FormDblClick(Sender: TObject);
begin
//
end;
procedure TFormMain.JvTrayIconDblClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
// if JvTrayIcon.AcceptBalloons then
// begin
//
// JvTrayIcon.BalloonHint(
// 'SHARK ATTACK',
// '______\o/_____/|______',
// { Style = } btWarning // btNone btError btInfo btWarning
// { Delay = 5000, }
// { Cancel = FALSE }
// );
//
// end;
case ActiveModule of
stmNone:
begin
JvPopupMenuTray.Popup(X, Y);
end;
stmBitPattern:
begin
TrayMenuItemBitPatternClick(Sender);
end;
stmFileAnalysis:
begin
TrayMenuItemFileUtilitiesClick(Sender);
end;
end;
end;
procedure TFormMain.TrayMenuItemBitPatternClick(Sender: TObject);
begin
ActiveModule := stmBitPattern;
FormBitPattern.Show;
if FormBitPattern.WindowState = wsMinimized then
begin
ShowWindow(FormBitPattern.Handle, SW_RESTORE);
end;
end;
procedure TFormMain.TrayMenuItemFileUtilitiesClick(Sender: TObject);
begin
ActiveModule := stmFileAnalysis;
FormFileAnalysis.Show;
if FormFileAnalysis.WindowState = wsMinimized then
begin
ShowWindow(FormFileAnalysis.Handle, SW_RESTORE);
end;
end;
procedure TFormMain.TrayMenuItemConvertLocalToUNCClick(Sender: TObject);
var
PreviousActiveModule: TSysToolModule;
LocalPath: String;
UNCPath: String;
BalloonTitle: String;
BalloonMessage: String;
BalloonType: TBalloonType;
begin
// there's no form associated with this module, so save the previous and restore it
// once we've performed our duties
PreviousActiveModule := ActiveModule;
ActiveModule := stmConvertPathLocalUNC;
LocalPath := ClipBoard.AsText;
UNCPath := GetUNCPath(LocalPath);
if JvTrayIcon.AcceptBalloons then
begin
if Length(Trim(UNCPath)) > 0 then
begin
ClipBoard.AsText := UNCPath;
BalloonTitle := Format('Copied UNC path to clipboard', []);
BalloonMessage := Format('%s', [UNCPath]);
BalloonType := btInfo;
end
else
begin
BalloonTitle := Format('Clipboard contains invalid local path', []);
BalloonMessage := Format('%s', [LocalPath]);
BalloonType := btError;
end;
JvTrayIcon.BalloonHint(
{ Title = } BalloonTitle,
{ Message = } BalloonMessage,
{ Style = } BalloonType // btNone btError btInfo btWarning
{ Delay = 5000, }
{ Cancel = FALSE }
);
end
else
begin
// notify user without balloons somehow?
end;
ActiveModule := PreviousActiveModule;
end;
procedure TFormMain.TrayMenuItemConvertUNCToLocalClick(Sender: TObject);
var
PreviousActiveModule: TSysToolModule;
UNCPath: String;
LocalPath: String;
BalloonTitle: String;
BalloonMessage: String;
BalloonType: TBalloonType;
begin
// there's no form associated with this module, so save the previous and restore it
// once we've performed our duties
PreviousActiveModule := ActiveModule;
ActiveModule := stmConvertPathUNCLocal;
UNCPath := ClipBoard.AsText;
LocalPath := GetLocalPath(UNCPath);
if JvTrayIcon.AcceptBalloons then
begin
if Length(Trim(LocalPath)) > 0 then
begin
ClipBoard.AsText := LocalPath;
BalloonTitle := Format('Copied local path to clipboard', []);
BalloonMessage := Format('%s', [LocalPath]);
BalloonType := btInfo;
end
else
begin
BalloonTitle := Format('Clipboard contains invalid UNC path', []);
BalloonMessage := Format('%s', [UNCPath]);
BalloonType := btError;
end;
JvTrayIcon.BalloonHint(
{ Title = } BalloonTitle,
{ Message = } BalloonMessage,
{ Style = } BalloonType // btNone btError btInfo btWarning
{ Delay = 5000, }
{ Cancel = FALSE }
);
end
else
begin
// notify user without balloons somehow?
end;
ActiveModule := PreviousActiveModule;
end;
procedure TFormMain.TrayMenuItemHideClick(Sender: TObject);
begin
if FormBitPattern <> nil then
FormBitPattern.Close;
if FormFileAnalysis <> nil then
FormFileAnalysis.Close;
end;
procedure TFormMain.TrayMenuItemQuitClick(Sender: TObject);
begin
Self.Close;
end;
procedure TFormMain.TrayMenuItemStayOnTopClick(Sender: TObject);
begin
Self.SetFormStayOnTop(TrayMenuItemStayOnTop.Checked);
Global.SetRegistryKeyValue(REGKEY_COMMON_STAY_ON_TOP, TrayMenuItemStayOnTop.Checked);
end;
procedure TFormMain.TrayMenuItemStyleClick(Sender: TObject);
begin
if Sender is TMenuItem then
begin
TrayMenuItemStyleBtnLowered.Checked := FALSE;
TrayMenuItemStyleBtnRaised.Checked := FALSE;
TrayMenuItemStyleItemPainter.Checked := FALSE;
TrayMenuItemStyleOffice.Checked := FALSE;
TrayMenuItemStyleOwnerDraw.Checked := FALSE;
TrayMenuItemStyleStandard.Checked := FALSE;
TrayMenuItemStyleXP.Checked := FALSE;
(Sender as TMenuItem).Checked := TRUE;
case (Sender as TMenuItem).Tag of
0: JvPopupMenuTray.Style := msBtnLowered;
1: JvPopupMenuTray.Style := msBtnRaised;
2: JvPopupMenuTray.Style := msItemPainter;
3: JvPopupMenuTray.Style := msOffice;
4: JvPopupMenuTray.Style := msOwnerDraw;
5: JvPopupMenuTray.Style := msStandard;
6: JvPopupMenuTray.Style := msXP;
else JvPopupMenuTray.Style := msStandard;
end;
JvPopupMenuTray.Rebuild;
end;
end;
procedure TFormMain.SetFormStayOnTop(StayOnTop: Boolean);
begin
if FormBitPattern <> nil then
FormBitPattern.SetFormStayOnTop(StayOnTop);
if FormFileAnalysis <> nil then
FormFileAnalysis.SetFormStayOnTop(StayOnTop);
end;
end.
|
unit Plugin_events;
interface
uses CoolQSDK,iconv;
Function code_eventStartup:longint;
Function code_eventExit:longint;
Function code_eventEnable:longint;
Function code_eventDisable:longint;
Function code_eventPrivateMsg(subType,MsgID:longint;fromQQ:int64;const msg:ansistring;font:longint):longint;
Function code_eventGroupMsg(subType,MsgID:longint;fromgroup,fromQQ:int64;const fromAnonymous,msg:ansistring;font:longint):longint;
Function code_eventDiscussMsg(subType,MsgID:longint;fromDiscuss,fromQQ:int64;msg:ansistring;font:longint):longint;
Function code_eventGroupUpload(subType,sendTime:longint;fromGroup,fromQQ:int64;Pfileinfo:ansistring):longint;
Function code_eventSystem_GroupAdmin(subType,sendTime:longint;fromGroup,beingOperateQQ:int64):longint;
Function code_eventSystem_GroupMemberDecrease(subType,sendTime:longint;fromGroup,fromQQ,beingOperateQQ:int64):longint;
Function code_eventSystem_GroupMemberIncrease(subType,sendTime:longint;fromGroup,fromQQ,beingOperateQQ:int64):longint;
Function code_eventFriend_Add(subType,sendTime:longint;fromQQ:int64):longint;
Function code_eventRequest_AddFriend(subType,sendTime:longint;fromQQ:int64;const msg:ansistring;responseFlag:Pchar):longint;
Function code_eventRequest_AddGroup(subType,sendTime:longint;fromGroup,fromQQ:int64;msg:ansistring;responseFlag:Pchar):longint;
implementation
uses
inifiles;
Var
Config : TIniFile;
PluginEnabled : boolean;
Function isEnabledInGroup(groupID:int64):boolean;
Var
i,flag:int64;
Begin
i:=random(100000000);
flag := Config.ReadInt64('group',NumtoChar(groupID),i);
if flag<>i then begin
exit(flag<>0);
end
else
begin
exit(Config.ReadInt64('general','globalstatus',0)<>0)
end;
End;
function CanDelete(groupID,ActiveQQ,TargetQQ:int64):boolean;
Var
TActiveQQ,TTargetQQ:CQ_Type_GroupMember;
Begin
if Config.ReadInt64('general','checkpermission',1)=0 then exit(true);
if (CQ_i_getGroupMemberInfo(groupID,ActiveQQ,TActiveQQ,true)=0) and
(CQ_i_getGroupMemberInfo(groupID,TargetQQ,TTargetQQ,true)=0) and
(TActiveQQ.Permission > TTargetQQ.Permission) then exit(true) else exit(false);
End;
function hasConfigPerm(groupID,ActiveQQ:int64):boolean;
Var
TActiveQQ:CQ_Type_GroupMember;
Begin
if (CQ_i_getGroupMemberInfo(groupID,ActiveQQ,TActiveQQ,true)=0) and
(TActiveQQ.Permission >= 2) then exit(true) else exit(false);
End;
{
* Type=1001 酷Q启动
* 无论本应用是否被启用,本函数都会在酷Q启动后执行一次,请在这里执行应用初始化代码。
* 如非必要,不建议在这里加载窗口。(可以添加菜单,让用户手动打开窗口)
}
Function code_eventStartup:longint;
Begin
{$IFDEF FPC}
exit(0);
{$ELSE}
result:=0;
{$ENDIF}
End;
{
* Type=1002 酷Q退出
* 无论本应用是否被启用,本函数都会在酷Q退出前执行一次,请在这里执行插件关闭代码。
* 本函数调用完毕后,酷Q将很快关闭,请不要再通过线程等方式执行其他代码。
}
Function code_eventExit:longint;
Begin
if PluginEnabled then Config.Destroy;
PluginEnabled:= false;
{$IFDEF FPC}
exit(0);
{$ELSE}
result:=0;
{$ENDIF}
End;
{
* Type=1003 应用已被启用
* 当应用被启用后,将收到此事件。
* 如果酷Q载入时应用已被启用,则在_eventStartup(Type=1001,酷Q启动)被调用后,本函数也将被调用一次。
* 如非必要,不建议在这里加载窗口。(可以添加菜单,让用户手动打开窗口)
}
Function code_eventEnable:longint;
Var
i:longint;
Begin
PluginEnabled:=true;
Config := TIniFile.Create(CQ_i_getAppDirectory+'config.ini',false);
Config.CacheUpdates:= true;
i:=random(100000000);
if Config.ReadInt64('general','globalstatus',i)=i then Config.WriteInt64('general','globalstatus',1);
i:=random(100000000);
if Config.ReadInt64('general','checkpermission',i)=i then Config.WriteInt64('general','checkpermission',1);
{$IFDEF FPC}
exit(0)
{$ELSE}
result:=0;
{$ENDIF}
End;
{
* Type=1004 应用将被停用
* 当应用被停用前,将收到此事件。
* 如果酷Q载入时应用已被停用,则本函数*不会*被调用。
* 无论本应用是否被启用,酷Q关闭前本函数都*不会*被调用。
}
Function code_eventDisable:longint;
Begin
if PluginEnabled then Begin
Config.Destroy;
Config:=nil;
End;
PluginEnabled:= false;
{$IFDEF FPC}
exit(0);
{$ELSE}
result:=0;
{$ENDIF}
End;
{
* Type=21 私聊消息
* subType 子类型,11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组
}
Function code_eventPrivateMsg(
subType,MsgID :longint;
fromQQ :int64;
const msg :ansistring;
font :longint):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
//如果要回复消息,请调用酷Q方法发送,并且这里 exit(EVENT_BLOCK) - 截断本条消息,不再继续处理 注意:应用优先级设置为"最高"(10000)时,不得使用本返回值
//如果不回复消息,交由之后的应用/过滤器处理,这里 exit(return EVENT_IGNORE) - 忽略本条消息
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
End;
{
* Type=2 群消息
}
Function code_eventGroupMsg(
subType,MsgID :longint;
fromgroup,fromQQ :int64;
const fromAnonymous,msg :ansistring;
font :longint):longint;
//Var
//AnonymousMes : CQ_Type_GroupAnonymous;
Begin
{if (fromQQ=80000000) and (fromAnonymous<>'') then begin
CQ_Tools_TextToAnonymous(fromAnonymous,AnonymousMes);
//将匿名用户信息存到 AnonymousMes
end;}
//if msg='签到' then CQ_i_sendGroupMsg(fromgroup,CQCode_Group_At(fromQQ)+' : 签到并没有成功[CQ:image,file=funnyface.png]');
if (msg=ansistring('收到福袋,请使用新版手机QQ查看')) and (isEnabledInGroup(fromgroup)) and (CanDelete(fromGroup,CQ_i_getLoginQQ,fromQQ))
then CQ_i_deleteMsg(MsgID);
if ((upcase(msg)=ansistring('FUKUBUKURO-ON')) or (msg=ansistring('撤回福袋')) or (msg=ansistring('福袋撤回'))) and hasConfigPerm(fromGroup,fromQQ) then begin
if isEnabledInGroup(fromgroup) then exit(EVENT_IGNORE);
Config.WriteInt64('group',NumtoChar(fromGroup),1);
CQ_i_sendGroupMsg(fromGroup,CQCode_Group_At(fromQQ)+': AntiFukubukuro Now Enabled!');
end;
if ((upcase(msg)=ansistring('FUKUBUKURO-OFF')) or (msg=ansistring('放行福袋')) or (msg=ansistring('福袋放行'))) and hasConfigPerm(fromGroup,fromQQ) then begin
if not isEnabledInGroup(fromgroup) then exit(EVENT_IGNORE);
Config.WriteInt64('group',NumtoChar(fromGroup),0);
CQ_i_sendGroupMsg(fromGroup,CQCode_Group_At(fromQQ)+': AntiFukubukuro Now Disenabled!');
end;
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=4 讨论组消息
}
Function code_eventDiscussMsg(
subType,MsgID :longint;
fromDiscuss,fromQQ :int64;
msg :ansistring;
font :longint):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
*Type=11 群文件上传事件
}
Function code_eventGroupUpload(
subType,sendTime :longint;
fromGroup,fromQQ :int64;
Pfileinfo :ansistring):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=101 群事件-管理员变动
* subType 子类型,1/被取消管理员 2/被设置管理员
}
Function code_eventSystem_GroupAdmin(
subType,sendTime :longint;
fromGroup,
beingOperateQQ :int64):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=102 群事件-群成员减少
* subType 子类型,1/群员离开 2/群员被踢 3/自己(即登录号)被踢
* fromQQ 操作者QQ(仅subType为2、3时存在)
* beingOperateQQ 被操作QQ
}
Function code_eventSystem_GroupMemberDecrease(
subType,sendTime :longint;
fromGroup,fromQQ,
beingOperateQQ :int64):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=103 群事件-群成员增加
* subType 子类型,1/管理员已同意 2/管理员邀请
* fromQQ 操作者QQ(即管理员QQ)
* beingOperateQQ 被操作QQ(即加群的QQ)
}
Function code_eventSystem_GroupMemberIncrease(
subType,sendTime :longint;
fromGroup,fromQQ,
beingOperateQQ :int64):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=201 好友事件-好友已添加
}
Function code_eventFriend_Add(
subType,sendTime :longint;
fromQQ :int64):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=301 请求-好友添加
* msg 附言
* responseFlag
反馈标识(处理请求用)
这个我就不帮你转换成string了,反正你拿来也没什么用
}
Function code_eventRequest_AddFriend(
subType,sendTime :longint;
fromQQ :int64;
const msg :ansistring;
responseFlag :Pchar):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
{
* Type=302 请求-群添加
* subType 子类型,1/他人申请入群 2/自己(即登录号)受邀入群
* msg 附言
* responseFlag
反馈标识(处理请求用)
这个我也不帮你转换了
}
Function code_eventRequest_AddGroup(
subType,sendTime :longint;
fromGroup,fromQQ :int64;
msg :ansistring;
responseFlag :Pchar):longint;
Begin
{$IFDEF FPC}
exit(EVENT_IGNORE);
{$ELSE}
result:=EVENT_IGNORE;
{$ENDIF}
//关于返回值说明, 见“code_eventPrivateMsg”函数
End;
initialization
Randomize;
PluginEnabled:=false;
Config:=nil;
end. |
unit ObservableImplTests;
interface
uses Classes, TestFramework, Rx, Generics.Collections, SysUtils;
type
TSmartVariableTests = class(TTestCase)
strict private
FLog: TList<string>;
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Sane;
procedure Clear;
procedure Visibility;
procedure GarbageCollection;
end;
TSubscriptionTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure OnSubscribe;
procedure SubscriptionLeave;
procedure OnCompleted;
procedure OnError;
procedure Catch;
procedure CatchEmpty;
procedure StreamSequence;
procedure Unsubscribe;
end;
TMergeTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure PassingOnNext;
procedure PassingOnError;
end;
TMemoryLeaksTests = class(TTestCase)
strict private
FStream: TList<string>;
FFreesLog: TList<string>;
procedure OnItemFree;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure EmptySubscribers;
procedure MapCase1;
procedure MapCase2;
procedure Zip1;
procedure Zip2;
end;
TOperationsTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure FilterTest1;
procedure FilterTest2;
procedure FilterTest3;
procedure FilterStatic;
procedure MapTest1;
procedure MapTest2;
procedure MapStatic;
procedure Merge1;
procedure Merge2;
procedure Merge3;
procedure MergeDuplex;
procedure Defer;
procedure Zip1;
procedure Zip2;
procedure ZipCompleted1;
procedure ZipCompleted2;
procedure ZipCompletedMultiThreaded;
procedure ZipError1;
procedure ZipNFibersInSingleThread;
procedure CombineLatest1;
procedure WithLatestFrom1;
procedure AMB1;
procedure Take;
procedure Skip;
procedure Delay;
procedure FlatMapSane1;
procedure FlatMapSane2;
procedure FlatMapStatic;
procedure FlatMapOnSubscribe;
end;
TAdvancedOpsTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Scan;
procedure ScanObjects;
procedure Reduce;
procedure ResuceZero;
procedure CollectWithList;
procedure CollectWithDict;
end;
TConstructorTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure Just;
procedure Range;
procedure Interval;
end;
TSchedulersTests = class(TTestCase)
strict private
FStream: TList<string>;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ContractLockIssue;
procedure MainThreadScheduler1;
procedure MainThreadScheduler2;
procedure SeparateThreadScheduler;
procedure NewThreadScheduler;
procedure ThreadPoolScheduler;
end;
implementation
uses SyncObjs, Rx.Fibers, BaseTests;
procedure Setup(L: TList<string>; const Collection: array of string);
var
S: string;
begin
L.Clear;
for S in Collection do
L.Add(S);
end;
{ TSubscriptionTests }
procedure TSubscriptionTests.Catch;
var
O: TObservable<string>;
OnNext: TOnNext<string>;
OnError: TOnError;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnError := procedure(Throwable: IThrowable)
begin
FStream.Add(Format('error:%s(%s)', [Throwable.GetClass.ClassName, Throwable.GetMessage]));
end;
O.Subscribe(OnNext, OnError);
try
O.OnNext('1');
O.OnNext('2');
O.OnNext('3');
raise ETestError.Create('test');
O.OnNext('4');
except
O.Catch;
end;
Check(IsEqual(FStream, ['1', '2', '3', 'error:ETestError(test)']));
end;
procedure TSubscriptionTests.CatchEmpty;
var
O: TObservable<string>;
OnError: TOnError;
begin
OnError := procedure(Throwable: IThrowable)
begin
FStream.Add(Format('error:%s(%s)', [Throwable.GetClass.ClassName, Throwable.GetMessage]));
end;
O.Subscribe(OnError);
O.OnNext('1');
O.OnNext('2');
O.Catch;
CheckEquals(0, FStream.Count);
end;
procedure TSubscriptionTests.OnCompleted;
var
O: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
S.OnNext('3');
S.OnCompleted;
S.OnNext('4');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<string>.Create(OnSubscribe);
O.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['1', '2', '3', 'completed']));
end;
procedure TSubscriptionTests.OnError;
var
O: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
OnError: TOnError;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
S.OnNext('3');
S.OnError(nil);
S.OnNext('4');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnError := procedure(Throwable: IThrowable)
begin
FStream.Add('error');
end;
O := TObservable<string>.Create(OnSubscribe);
O.Subscribe(OnNext, OnError);
Check(IsEqual(FStream, ['1', '2', '3', 'error']));
end;
procedure TSubscriptionTests.OnSubscribe;
var
O: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
S.OnNext('3');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
O := TObservable<string>.Create(OnSubscribe);
O.Subscribe(OnNext);
Check(IsEqual(FStream, ['1', '2', '3']));
end;
procedure TSubscriptionTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TSubscriptionTests.StreamSequence;
var
O: TObservable<string>;
OnNextA: TOnNext<string>;
OnNextB: TOnNext<string>;
begin
OnNextA := procedure(const Data: string)
begin
FStream.Add('A' + Data);
end;
OnNextB := procedure(const Data: string)
begin
FStream.Add('B' + Data);
end;
O.Subscribe(OnNextA);
O.OnNext('1');
O.Subscribe(OnNextB);
O.OnNext('2');
O.OnNext('3');
O.OnCompleted;
O.OnNext('4');
Check(IsEqual(FStream, ['A1', 'A2', 'B2', 'A3', 'B3']));
end;
procedure TSubscriptionTests.SubscriptionLeave;
var
O: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
S.OnNext('3');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
O := TObservable<string>.Create(OnSubscribe);
O.Subscribe(OnNext);
O.OnNext('4');
O.OnCompleted;
O.OnNext('5');
Check(IsEqual(FStream, ['1', '2', '3', '4']));
end;
procedure TSubscriptionTests.TearDown;
begin
inherited;
FStream.Free;
end;
procedure TSubscriptionTests.Unsubscribe;
var
O: TObservable<string>;
OnNext: TOnNext<string>;
Subscription: ISubscription;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
Subscription := O.Subscribe(OnNext);
O.OnNext('1');
O.OnNext('2');
Subscription.Unsubscribe;
O.OnNext('3');
Check(IsEqual(FStream, ['1', '2']));
end;
{ TOperationsTests }
procedure TOperationsTests.AMB1;
var
A: TObservable<string>;
B: TObservable<Integer>;
AMB: TObservable<TZip<string, Integer>>;
OnSubscribeA: TOnSubscribe<string>;
OnSubscribeB: TOnSubscribe<Integer>;
OnNextAMB: TOnNext<TZip<string, Integer>>;
OnCompleted: TOnCompleted;
begin
// A is more FAST than B
// emulate faster-lower through call context yielding (fibers api)
OnSubscribeA := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
O.OnNext('C');
O.OnNext('D');
O.OnNext('E');
O.OnNext('F');
O.OnNext('G');
O.OnNext('H');
O.OnNext('I');
O.OnCompleted;
end;
OnSubscribeB := procedure(O: IObserver<Integer>)
begin
Yield;
O.OnNext(1);
Yield;
O.OnNext(2);
Yield;
O.OnNext(3);
end;
OnNextAMB := procedure(const Data: TZip<string, Integer>)
begin
FStream.Add(Format('%s:%d', [Data.A, Data.B]));
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
A := TObservable<string>.Create(OnSubscribeA);
B := TObservable<Integer>.Create(OnSubscribeB);
AMB := A.AMB<Integer>(B);
AMB.Subscribe(OnNextAMB, OnCompleted);
Check(IsEqual(FStream, ['A:1', 'C:2', 'E:3', 'completed']));
end;
procedure TOperationsTests.CombineLatest1;
var
L: TObservable<string>;
R: TObservable<Integer>;
Comb: TObservable<TZip<string, Integer>>;
OnNext: TOnNext<TZip<string, Integer>>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: TZip<string, Integer>)
begin
FStream.Add(Format('%s%d', [Data.A, Data.B]))
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
Comb := L.CombineLatest<Integer>(R);
Comb.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, []));
L.OnNext('A');
L.OnNext('B');
Check(IsEqual(FStream, []));
R.OnNext(1);
Check(IsEqual(FStream, ['B1']));
R.OnNext(2);
Check(IsEqual(FStream, ['B1', 'B2']));
R.OnNext(3);
R.OnNext(4);
Check(IsEqual(FStream, ['B1', 'B2', 'B3', 'B4']));
L.OnNext('C');
Check(IsEqual(FStream, ['B1', 'B2', 'B3', 'B4', 'C4']));
R.OnCompleted;
Check(IsEqual(FStream, ['B1', 'B2', 'B3', 'B4', 'C4', 'completed']));
L.OnNext('D');
Check(IsEqual(FStream, ['B1', 'B2', 'B3', 'B4', 'C4', 'completed']));
end;
procedure TOperationsTests.Defer;
var
Routine: TDefer<string>;
O: TObservable<string>;
Switch: Boolean;
OnNext: TOnNext<string>;
OnError: TOnError;
OnCompleted: TOnCompleted;
OnSubscribe1, OnSubscribe2: TOnSubscribe<string>;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnError := procedure(Throwable: IThrowable)
begin
FStream.Add('error');
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
OnSubscribe1 := procedure(O: IObserver<string>)
begin
O.OnNext('A1');
O.OnNext('A2');
O.OnCompleted;
end;
OnSubscribe2 := procedure(O: IObserver<string>)
begin
O.OnNext('B1');
O.OnNext('B2');
O.OnError(nil);
end;
Routine := function: IObservable<string>
var
O: TObservable<string>;
begin
if Switch then
O := TObservable<string>.Create(OnSubscribe1)
else
O := TObservable<string>.Create(OnSubscribe2);
Result := O;
end;
O := TObservable<string>.Defer(Routine);
// case 1
try
Switch := True;
O.Subscribe(OnNext, OnError, OnCompleted);
Check(IsEqual(FStream, ['A1', 'A2', 'completed']));
FStream.Clear;
// case 2
Switch := False;
O.Subscribe(OnNext, OnError, OnCompleted);
Check(IsEqual(FStream, ['B1', 'B2', 'error']));
finally
OnSubscribe1 := nil;
OnSubscribe2 := nil;
end
end;
procedure TOperationsTests.Delay;
var
O: TObservable<string>;
E: TEvent;
OnSubscribe: TOnSubscribe<string>;
OnCompleted: TOnCompleted;
OnNext: TOnNext<string>;
Stamps: array of TDateTime;
S: string;
I, Val: Integer;
begin
OnSubscribe := procedure(O: IObserver<string>)
begin
O.OnNext('0');
O.OnNext('1');
O.OnNext('2');
O.OnCompleted;
end;
OnNext := procedure(const Data: string)
var
S: string;
begin
S := TimeToStr(Now*1000);
FStream.Add(Format('%s_%s', [Data, S]));
end;
OnCompleted := procedure
begin
E.SetEvent;
end;
E := TEvent.Create;
try
O := TObservable<string>.Create(OnSubscribe);
O.Delay(100, TimeUnit.MILLISECONDS).Subscribe(OnNext, OnCompleted);
Check(E.WaitFor(500) = wrSignaled);
CheckEquals(3, FStream.Count);
SetLength(Stamps, FStream.Count);
for I := 0 to FStream.Count-1 do begin
Val := StrToInt(Copy(FStream[I], 1, 1));
CheckEquals(I, Val);
S := Copy(FStream[I], 3, Length(FStream[I])-2);
Stamps[I] := StrToTime(S);
end;
for I := 0 to FStream.Count-2 do begin
Check(Stamps[I+1] > Stamps[I]);
end;
finally
E.Free
end
end;
function FilterRoutine(const Data: string): Boolean;
begin
Result := Data[1] = '*'
end;
procedure TOperationsTests.FilterStatic;
var
O, FilterObs: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('*2');
S.OnNext('3');
S.OnNext('*4');
S.OnCompleted;
S.OnNext('*5');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
O := TObservable<string>.Create(OnSubscribe);
FilterObs := O.Filter(FilterRoutine);
FilterObs.Subscribe(OnNext);
Check(IsEqual(FStream, ['*2', '*4']));
end;
procedure TOperationsTests.FilterTest1;
var
O, FilterObs: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
Routine: TFilter<string>;
OnNext: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('*2');
S.OnNext('3');
S.OnNext('*4');
S.OnCompleted;
S.OnNext('*5');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
Routine := function(const Data: string): Boolean
begin
Result := Data[1] = '*'
end;
O := TObservable<string>.Create(OnSubscribe);
FilterObs := O.Filter(Routine);
FilterObs.Subscribe(OnNext);
Check(IsEqual(FStream, ['*2', '*4']));
end;
procedure TOperationsTests.FilterTest2;
var
O, FilterObs: TObservable<string>;
Routine: TFilter<string>;
OnNext: TOnNext<string>;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
Routine := function(const Data: string): Boolean
begin
Result := Data[1] = '*'
end;
FilterObs := O.Filter(Routine);
FilterObs.Subscribe(OnNext);
O.OnNext('1');
O.OnNext('*2');
O.OnNext('3');
O.OnNext('*4');
O.OnCompleted;
O.OnNext('*5');
Check(IsEqual(FStream, ['*2', '*4']));
end;
procedure TOperationsTests.FilterTest3;
var
O, FilterObs: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
Routine: TFilter<string>;
OnNextA, OnNextB: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('*2');
S.OnNext('3');
S.OnNext('*4');
S.OnCompleted;
S.OnNext('*5');
end;
OnNextA := procedure(const Data: string)
begin
FStream.Add('A' + Data);
end;
OnNextB := procedure(const Data: string)
begin
FStream.Add('B' + Data);
end;
Routine := function(const Data: string): Boolean
begin
Result := Data[1] = '*'
end;
O := TObservable<string>.Create(OnSubscribe);
FilterObs := O.Filter(Routine);
FilterObs.Subscribe(OnNextA);
FilterObs.Subscribe(OnNextB);
Check(IsEqual(FStream, ['A*2', 'A*4', 'B*2', 'B*4']));
end;
procedure TOperationsTests.FlatMapOnSubscribe;
var
O: TObservable<Integer>;
Flat: TObservable<string>;
Routine: TFlatMap<Integer, string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
OnSubscribe: TOnSubscribe<Integer>;
begin
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(20);
end;
O := TObservable<Integer>.Create(OnSubscribe);
Routine := function(const Data: Integer): IObservable<string>
var
O: TObservable<string>;
begin
O := TObservable<string>.Just([
IntToStr(Data),
IntToStr(Data+1),
IntToStr(Data+2)
]);
Result := O;
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
Flat := O.FlatMap<string>(Routine);
Flat.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['1', '2', '3', '10', '11', '12']));
end;
procedure TOperationsTests.FlatMapSane1;
var
O: TObservable<Integer>;
Flat: TObservable<string>;
Routine: TFlatMap<Integer, string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
Routine := function(const Data: Integer): IObservable<string>
var
O: TObservable<string>;
begin
O := TObservable<string>.Just([
IntToStr(Data),
IntToStr(Data+1),
IntToStr(Data+2)
]);
Result := O;
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
Flat := O.FlatMap<string>(Routine);
Flat.Subscribe(OnNext, OnCompleted);
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(11);
Check(IsEqual(FStream, ['1', '2', '3', '10', '11', '12', 'completed']));
end;
procedure TOperationsTests.FlatMapSane2;
var
O: TObservable<Integer>;
Flat: TObservable<string>;
Routine: TFlatMap<Integer, string>;
OnNext: TOnNext<string>;
OnError: TOnError;
begin
Routine := function(const Data: Integer): IObservable<string>
var
O: TObservable<string>;
begin
O := TObservable<string>.Just([
IntToStr(Data),
IntToStr(Data+1),
IntToStr(Data+2)
]);
Result := O;
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnError := procedure(E: IThrowable)
begin
FStream.Add('error');
end;
Flat := O.FlatMap<string>(Routine);
Flat.Subscribe(OnNext, OnError);
O.OnNext(1);
O.OnNext(10);
O.OnError(nil);
O.OnNext(20);
Check(IsEqual(FStream, ['1', '2', '3', '10', '11', '12', 'error']));
end;
function FlatMapRoutine(const Data: Integer): IObservable<string>;
var
O: TObservable<string>;
begin
O := TObservable<string>.Just([
IntToStr(Data),
IntToStr(Data+1),
IntToStr(Data+2)
]);
Result := O;
end;
procedure TOperationsTests.FlatMapStatic;
var
O: TObservable<Integer>;
Flat: TObservable<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
Flat := O.FlatMap<string>(FlatMapRoutine);
Flat.Subscribe(OnNext, OnCompleted);
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(11);
Check(IsEqual(FStream, ['1', '2', '3', '10', '11', '12', 'completed']));
end;
function MapRoutine(const Data: string): Integer;
begin
Result := StrToIntDef(Data, -1)
end;
procedure TOperationsTests.MapStatic;
var
O: TObservable<string>;
MapObs: TObservable<Integer>;
OnNext: TOnNext<Integer>;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(IntToStr(Data));
end;
MapObs := O.Map<Integer>(MapRoutine);
MapObs.Subscribe(OnNext);
O.OnNext('1');
O.OnNext('2');
O.OnNext('-');
O.OnNext('4');
O.OnCompleted;
O.OnNext('5');
Check(IsEqual(FStream, ['1', '2', '-1', '4']));
end;
procedure TOperationsTests.MapTest1;
var
O: TObservable<string>;
MapObs: TObservable<Integer>;
Routine: TMap<string, Integer>;
OnNext: TOnNext<Integer>;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add(IntToStr(Data));
end;
Routine := function(const Data: string): Integer
begin
Result := StrToIntDef(Data, -1)
end;
MapObs := O.Map<Integer>(Routine);
MapObs.Subscribe(OnNext);
O.OnNext('1');
O.OnNext('2');
O.OnNext('-');
O.OnNext('4');
O.OnCompleted;
O.OnNext('5');
Check(IsEqual(FStream, ['1', '2', '-1', '4']));
end;
procedure TOperationsTests.MapTest2;
var
O: TObservable<string>;
MapObs: TObservable<Integer>;
Routine: TMap<string, Integer>;
OnNextA, OnNextB: TOnNext<Integer>;
OnSubscribe: TOnSubscribe<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
S.OnNext('_');
S.OnNext('4');
S.OnCompleted;
S.OnNext('5');
end;
OnNextA := procedure(const Data: Integer)
begin
FStream.Add('A' + IntToStr(Data));
end;
OnNextB := procedure(const Data: Integer)
begin
FStream.Add('B' + IntToStr(Data));
end;
Routine := function(const Data: string): Integer
begin
Result := StrToIntDef(Data, -1)
end;
O := TObservable<string>.Create(OnSubscribe);
MapObs := O.Map<Integer>(Routine);
MapObs.Subscribe(OnNextA);
MapObs.Subscribe(OnNextB);
Check(IsEqual(FStream, ['A1', 'A2', 'A-1', 'A4', 'B1', 'B2', 'B-1', 'B4']));
end;
procedure TOperationsTests.Merge1;
var
O, O1, O2: TObservable<string>;
OnSubscribe1, OnSubscribe2: TOnSubscribe<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
OnSubscribe1 := procedure(S: IObserver<string>)
begin
S.OnNext('A1');
S.OnNext('A2');
end;
OnSubscribe2 := procedure(S: IObserver<string>)
begin
S.OnNext('B1');
S.OnNext('B2');
S.OnCompleted;
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O1 := TObservable<string>.Create(OnSubscribe1);
O2 := TObservable<string>.Create(OnSubscribe2);
O := TObservable<string>.Merge(O1, O2);
O.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['A1', 'A2', 'B1', 'B2', 'completed']));
end;
procedure TOperationsTests.Merge2;
var
O, O1, O2: TObservable<string>;
OnSubscribe1, OnSubscribe2: TOnSubscribe<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
OnSubscribe1 := procedure(S: IObserver<string>)
begin
S.OnNext('A1');
S.OnNext('A2');
S.OnCompleted;
S.OnNext('A3');
end;
OnSubscribe2 := procedure(S: IObserver<string>)
begin
S.OnNext('B1');
S.OnNext('B2');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<string>.Merge(O1, O2);
O.Subscribe(OnNext, OnCompleted);
O1.OnNext('A1');
O2.OnNext('B1');
O1.OnNext('A2');
O2.OnNext('B2');
O1.OnCompleted;
O2.OnNext('B3');
Check(IsEqual(FStream, ['A1', 'B1', 'A2', 'B2', 'completed']));
end;
procedure TOperationsTests.Merge3;
var
O, O1, O2, O3: TObservable<string>;
OnSubscribe1, OnSubscribe2: TOnSubscribe<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
begin
OnSubscribe1 := procedure(S: IObserver<string>)
begin
S.OnNext('A1');
S.OnNext('A2');
S.OnCompleted;
S.OnNext('A3');
S.OnCompleted;
end;
OnSubscribe2 := procedure(S: IObserver<string>)
begin
S.OnNext('B1');
S.OnNext('B2');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<string>.Merge(O1, O2, O3);
O.Subscribe(OnNext, OnCompleted);
O1.OnNext('A1');
O2.OnNext('B1');
O1.OnNext('A2');
O2.OnNext('B2');
O3.OnNext('C1');
O1.OnCompleted;
O2.OnNext('B3');
Check(IsEqual(FStream, ['A1', 'B1', 'A2', 'B2', 'C1', 'completed']));
end;
procedure TOperationsTests.MergeDuplex;
var
O, O1: TObservable<string>;
OnSubscribe: TOnSubscribe<string>;
OnNext: TOnNext<string>;
begin
OnSubscribe := procedure(S: IObserver<string>)
begin
S.OnNext('1');
S.OnNext('2');
end;
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
O1 := TObservable<string>.Create(OnSubscribe);
O := TObservable<string>.Merge(O1, O1);
O.Subscribe(OnNext);
Check(IsEqual(FStream, ['1', '2']));
end;
procedure TOperationsTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TOperationsTests.Skip;
var
O: TObservable<Integer>;
OnSubscribe: TOnSubscribe<Integer>;
OnNext: TOnNext<Integer>;
begin
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
end;
OnNext := procedure(const Data: Integer)
begin
FStream.Add(IntToStr(Data));
end;
O := TObservable<Integer>.Create(OnSubscribe);
O.Skip(3).Subscribe(OnNext);
Check(IsEqual(FStream, ['4', '5']));
end;
procedure TOperationsTests.Take;
var
O: TObservable<Integer>;
OnSubscribe: TOnSubscribe<Integer>;
OnNext: TOnNext<Integer>;
begin
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
end;
OnNext := procedure(const Data: Integer)
begin
FStream.Add(IntToStr(Data));
end;
O := TObservable<Integer>.Create(OnSubscribe);
O.Take(3).Subscribe(OnNext);
Check(IsEqual(FStream, ['1', '2', '3']));
end;
procedure TOperationsTests.TearDown;
begin
inherited;
FStream.Free;
end;
procedure TOperationsTests.WithLatestFrom1;
var
L: TObservable<string>;
R: TObservable<Integer>;
WL: TObservable<TZip<string, Integer>>;
OnNext: TOnNext<TZip<string, Integer>>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: TZip<string, Integer>)
begin
FStream.Add(Format('%s%d', [Data.A, Data.B]))
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
WL := L.WithLatestFrom<Integer>(R);
WL.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, []));
L.OnNext('A');
L.OnNext('B');
Check(IsEqual(FStream, []));
R.OnNext(1);
Check(IsEqual(FStream, ['B1']));
R.OnNext(2);
Check(IsEqual(FStream, ['B1']));
R.OnNext(3);
R.OnNext(4);
Check(IsEqual(FStream, ['B1']));
L.OnNext('C');
Check(IsEqual(FStream, ['B1', 'C4']));
R.OnCompleted;
Check(IsEqual(FStream, ['B1', 'C4', 'completed']));
L.OnNext('D');
Check(IsEqual(FStream, ['B1', 'C4', 'completed']));
end;
procedure TOperationsTests.Zip1;
var
L: TObservable<string>;
R: TObservable<Integer>;
Zip: TObservable<TZip<string, Integer>>;
OnNext: TOnNext<TZip<string, Integer>>;
OnCompleted: TOnCompleted;
begin
OnNext := procedure(const Data: TZip<string, Integer>)
begin
FStream.Add(Format('%s%d', [Data.A, Data.B]))
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
Zip := L.Zip<Integer>(R);
Zip.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, []));
L.OnNext('A');
L.OnNext('B');
Check(IsEqual(FStream, []));
R.OnNext(1);
Check(IsEqual(FStream, ['A1']));
R.OnNext(2);
Check(IsEqual(FStream, ['A1', 'B2']));
R.OnNext(3);
R.OnNext(4);
Check(IsEqual(FStream, ['A1', 'B2']));
L.OnNext('C');
Check(IsEqual(FStream, ['A1', 'B2', 'C3']));
R.OnCompleted;
Check(IsEqual(FStream, ['A1', 'B2', 'C3']));
L.OnNext('D');
Check(IsEqual(FStream, ['A1', 'B2', 'C3', 'D4', 'completed']));
end;
procedure TOperationsTests.Zip2;
var
L: TObservable<string>;
R: TObservable<Integer>;
Zip: TObservable<TZip<string, Integer>>;
OnNext: TOnNext<TZip<string, Integer>>;
OnCompleted: TOnCompleted;
OnSubscribeLeft: TOnSubscribe<string>;
OnSubscribeRight: TOnSubscribe<Integer>;
begin
OnNext := procedure(const Data: TZip<string, Integer>)
begin
FStream.Add(Format('%s%d', [Data.A, Data.B]))
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
OnSubscribeLeft := procedure(Observer: IObserver<string>)
begin
Observer.OnNext('A');
Observer.OnNext('B');
end;
OnSubscribeRight := procedure(Observer: IObserver<Integer>)
begin
Observer.OnNext(1);
Observer.OnNext(2);
Observer.OnNext(3);
end;
L := TObservable<string>.Create(OnSubscribeLeft);
R := TObservable<Integer>.Create(OnSubscribeRight);
Zip := L.Zip<Integer>(R);
Zip.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['A1', 'B2']));
L.OnNext('C');
L.OnCompleted;
Check(IsEqual(FStream, ['A1', 'B2', 'C3', 'completed']));
end;
procedure TOperationsTests.ZipCompleted1;
var
Left: TObservable<Integer>;
Right: TObservable<string>;
OnNext: TOnNext<TZip<Integer, string>>;
OnCompleted: TOnCompleted;
OnSubscribe1: TOnSubscribe<Integer>;
OnSubscribe2: TOnSubscribe<string>;
begin
OnNext := procedure(const Data: TZip<Integer, string>)
begin
FStream.Add(Format('%d:%s', [Data.A, Data.B]));
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
OnSubscribe1 := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
O.OnNext(6);
end;
OnSubscribe2 := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
O.OnCompleted;
end;
Left := TObservable<Integer>.Create(OnSubscribe1);
Right := TObservable<string>.Create(OnSubscribe2);
Observable.Zip<Integer, string>(Left, Right).Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['1:A', '2:B', 'completed']));
end;
procedure TOperationsTests.ZipCompleted2;
var
Left: TObservable<Integer>;
Right: TObservable<string>;
OnNext: TOnNext<TZip<Integer, string>>;
OnCompleted: TOnCompleted;
OnSubscribe1: TOnSubscribe<Integer>;
OnSubscribe2: TOnSubscribe<string>;
begin
OnNext := procedure(const Data: TZip<Integer, string>)
begin
FStream.Add(Format('%d:%s', [Data.A, Data.B]));
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
OnSubscribe1 := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
O.OnNext(6);
end;
OnSubscribe2 := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
O.OnCompleted;
end;
Left := TObservable<Integer>.Create(OnSubscribe1);
Observable.Zip<Integer, string>(Left, Right).Subscribe(OnNext, OnCompleted);
Right.OnNext('A');
Right.OnNext('B');
Right.OnCompleted;
Check(IsEqual(FStream, ['1:A', '2:B', 'completed']));
end;
procedure TOperationsTests.ZipCompletedMultiThreaded;
var
Timer: TObservable<LongWord>;
Values: TObservable<string>;
OnNext: TOnNext<TZip<LongWord, string>>;
OnCompleted: TOnCompleted;
OnSubscribeValues: TOnSubscribe<string>;
Zip: TObservable<TZip<LongWord, string>>;
Completed: TEvent;
begin
Completed := TEvent.Create(nil, True, False, '');
try
OnNext := procedure(const Data: TZip<LongWord, string>)
begin
FStream.Add(Format('%d:%s', [Data.A, Data.B]));
end;
OnCompleted := procedure
begin
FStream.Add('completed');
Completed.SetEvent;
end;
OnSubscribeValues := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
O.OnCompleted;
end;
Timer := Observable.Interval(100, TimeUnit.MILLISECONDS);
Values := TObservable<string>.Create(OnSubscribeValues);
Zip := Observable.Zip<LongWord, string>(Timer, Values);
Zip.Subscribe(OnNext, OnCompleted);
Check(Completed.WaitFor(1000) = wrSignaled, 'OnCompleted timeout');
Check(IsEqual(FStream, ['0:A', '1:B', 'completed']));
finally
Completed.Free;
end
end;
procedure TOperationsTests.ZipError1;
var
Left: TObservable<Integer>;
Right: TObservable<string>;
OnNext: TOnNext<TZip<Integer, string>>;
OnError: TOnError;
OnSubscribe1: TOnSubscribe<Integer>;
OnSubscribe2: TOnSubscribe<string>;
begin
OnNext := procedure(const Data: TZip<Integer, string>)
begin
FStream.Add(Format('%d:%s', [Data.A, Data.B]));
end;
OnError := procedure(E: IThrowable)
begin
FStream.Add(Format('error: %s', [E.GetMessage]));
end;
OnSubscribe1 := procedure(O: IObserver<Integer>)
begin
O.OnNext(1);
O.OnNext(2);
O.OnNext(3);
O.OnNext(4);
O.OnNext(5);
O.OnNext(6);
end;
OnSubscribe2 := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
raise ETestError.Create('test');
O.OnNext('C');
end;
Left := TObservable<Integer>.Create(OnSubscribe1);
Right := TObservable<string>.Create(OnSubscribe2);
Observable.Zip<Integer, string>(Left, Right).Subscribe(OnNext, OnError);
Check(IsEqual(FStream, ['1:A', '2:B', 'error: test']));
end;
procedure TOperationsTests.ZipNFibersInSingleThread;
var
Timer: TObservable<LongWord>;
Values: TObservable<string>;
OnNext: TOnNext<TZip<LongWord, string>>;
OnCompleted: TOnCompleted;
OnSubscribeValues: TOnSubscribe<string>;
Zip: TObservable<TZip<LongWord, string>>;
Completed: TEvent;
ThreadId: LongWord;
I: Integer;
begin
ThreadId := 0;
Completed := TEvent.Create(nil, True, False, '');
try
OnNext := procedure(const Data: TZip<LongWord, string>)
begin
ThreadId := TThread.CurrentThread.ThreadID;
FStream.Add(Format('%d', [ThreadId]));
end;
OnCompleted := procedure
begin
Completed.SetEvent;
end;
OnSubscribeValues := procedure(O: IObserver<string>)
begin
O.OnNext('A');
O.OnNext('B');
O.OnCompleted;
end;
Timer := Observable.Interval(100, TimeUnit.MILLISECONDS);
Values := TObservable<string>.Create(OnSubscribeValues);
Zip := Observable.Zip<LongWord, string>(Timer, Values);
Zip.Subscribe(OnNext, OnCompleted);
Check(Completed.WaitFor(1000) = wrSignaled, 'OnCompleted timeout');
CheckNotEquals(ThreadId, MainThreadID);
for I := 0 to FStream.Count-1 do
CheckEquals(IntToStr(ThreadId), FStream[I])
finally
Completed.Free;
end
end;
{ TSmartVariableTests }
procedure TSmartVariableTests.Clear;
var
A: TLoggingObj;
Variable: TSmartVariable<TLoggingObj>;
Logger: TThreadProcedure;
begin
Logger := procedure
begin
FLog.Add('*');
end;
A := TLoggingObj.Create(Logger);
Variable := A;
Variable.Clear;
CheckEquals(1, FLog.Count);
end;
procedure TSmartVariableTests.GarbageCollection;
var
O: TObservable<TLoggingObj>;
Logger: TThreadProcedure;
OnNext: TOnNext<TLoggingObj>;
begin
Logger := procedure
begin
FLog.Add('*');
end;
OnNext := procedure(const Data: TLoggingObj)
begin
FStream.Add(Format('%p', [Pointer(Data)]))
end;
O.Subscribe(OnNext);
O.OnNext(TLoggingObj.Create(Logger));
O.OnNext(TLoggingObj.Create(Logger));
O.OnNext(TLoggingObj.Create(Logger));
Logger := nil;
CheckEquals(3, FStream.Count);
CheckEquals(3, FLog.Count);
end;
procedure TSmartVariableTests.Sane;
var
A1, A2: TLoggingObj;
Variable: TSmartVariable<TLoggingObj>;
Logger: TThreadProcedure;
begin
Logger := procedure
begin
FLog.Add('*');
end;
A1 := TLoggingObj.Create(Logger);
A2 := TLoggingObj.Create(Logger);
Variable := A1;
CheckTrue(A1 = Variable.Get);
CheckFalse(A2 = Variable.Get);
CheckEquals(0, FLog.Count);
Variable := A2;
CheckEquals(1, FLog.Count);
end;
procedure TSmartVariableTests.SetUp;
begin
inherited;
FLog := TList<string>.Create;
FStream := TList<string>.Create;
end;
procedure TSmartVariableTests.TearDown;
begin
inherited;
FLog.Free;
FStream.Free;
end;
procedure TSmartVariableTests.Visibility;
var
InternalCall: TThreadProcedure;
Logger: TThreadProcedure;
begin
Logger := procedure
begin
FLog.Add('*');
end;
InternalCall := procedure
var
A: TSmartVariable<TLoggingObj>;
begin
A := TLoggingObj.Create(Logger);
end;
InternalCall();
Logger := nil; // чистим транзитивные замыкания
CheckEquals(1, FLog.Count);
end;
{ TMemoryLeaksTests }
procedure TMemoryLeaksTests.EmptySubscribers;
var
O: TObservable<TLoggingObj>;
begin
O.OnNext(TLoggingObj.Create(OnItemFree));
CheckEquals(1, FFreesLog.Count);
end;
procedure TMemoryLeaksTests.MapCase1;
var
O: TObservable<TLoggingObj>;
OnNext: TOnNext<TLoggingObjDescendant>;
Mapper: TMap<TLoggingObj, TLoggingObjDescendant>;
begin
OnNext := procedure (const Data: TLoggingObjDescendant)
begin
FStream.Add('*');
end;
Mapper := function(const Data: TLoggingObj): TLoggingObjDescendant
begin
Result := TLoggingObjDescendant.Create(OnItemFree);
end;
O.Map<TLoggingObjDescendant>(Mapper);
O.OnNext(TLoggingObj.Create(OnItemFree));
CheckEquals(2, FFreesLog.Count);
FFreesLog.Clear;
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
O.OnNext(TLoggingObj.Create(OnItemFree));
CheckEquals(3, FStream.Count);
CheckEquals(2 + 3, FFreesLog.Count);
end;
procedure TMemoryLeaksTests.MapCase2;
var
O: TObservable<TLoggingObj>;
OnNext: TOnNext<TLoggingObjDescendant>;
Mapper: TMap<TLoggingObj, TLoggingObjDescendant>;
procedure SubscribeOutOfScope;
begin
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
O.Map<TLoggingObjDescendant>(Mapper).Subscribe(OnNext);
end;
begin
OnNext := procedure (const Data: TLoggingObjDescendant)
begin
FStream.Add('*');
end;
Mapper := function(const Data: TLoggingObj): TLoggingObjDescendant
begin
Result := TLoggingObjDescendant.Create(OnItemFree);
end;
SubscribeOutOfScope;
O.OnNext(TLoggingObj.Create(OnItemFree));
CheckEquals(3, FStream.Count);
CheckEquals(2 + 2, FFreesLog.Count);
end;
procedure TMemoryLeaksTests.OnItemFree;
begin
FFreesLog.Add('destroy')
end;
procedure TMemoryLeaksTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
FFreesLog := TList<string>.Create;
end;
procedure TMemoryLeaksTests.TearDown;
begin
inherited;
FStream.Free;
FFreesLog.Free;
end;
procedure TMemoryLeaksTests.Zip1;
var
A: TObservable<TLoggingObj>;
B: TObservable<TLoggingObjDescendant>;
Z: TObservable<TZip<TLoggingObj, TLoggingObjDescendant>>;
OnNext: TOnNext<TZip<TLoggingObj, TLoggingObjDescendant>>;
begin
OnNext := procedure (const Data: TZip<TLoggingObj, TLoggingObjDescendant>)
begin
FStream.Add('*');
end;
Z := A.Zip<TLoggingObjDescendant>(B);
A.OnNext(TLoggingObj.Create(OnItemFree));
B.OnNext(TLoggingObjDescendant.Create(OnItemFree));
CheckEquals(2, FFreesLog.Count);
FFreesLog.Clear;
Z.Subscribe(OnNext);
Z.Subscribe(OnNext);
Z.Subscribe(OnNext);
A.OnNext(TLoggingObj.Create(OnItemFree));
B.OnNext(TLoggingObjDescendant.Create(OnItemFree));
CheckEquals(3, FStream.Count);
CheckEquals(2, FFreesLog.Count);
end;
procedure TMemoryLeaksTests.Zip2;
var
A: TObservable<TLoggingObj>;
B: TObservable<TLoggingObjDescendant>;
Z: TObservable<TZip<TLoggingObj, TLoggingObjDescendant>>;
OnNext: TOnNext<TZip<TLoggingObj, TLoggingObjDescendant>>;
procedure SubscribeOutOfScope;
begin
Z.Subscribe(OnNext);
Z.Subscribe(OnNext);
Z.Subscribe(OnNext);
end;
begin
OnNext := procedure (const Data: TZip<TLoggingObj, TLoggingObjDescendant>)
begin
FStream.Add('*');
end;
Z := A.Zip<TLoggingObjDescendant>(B);
SubscribeOutOfScope;
A.OnNext(TLoggingObj.Create(OnItemFree));
B.OnNext(TLoggingObjDescendant.Create(OnItemFree));
CheckEquals(3, FStream.Count);
CheckEquals(2, FFreesLog.Count);
end;
{ TConstructorTests }
procedure TConstructorTests.Interval;
var
O: TObservable<LongWord>;
OnNext: TOnNext<LongWord>;
Sub: ISubscription;
begin
OnNext := procedure(const Data: LongWord)
begin
FStream.Add(IntToStr(Data));
end;
O := Rx.Observable.Interval(1);
Sub := O.Subscribe(OnNext);
Sleep(3500);
Check(IsEqual(FStream, ['0', '1', '2']));
end;
procedure TConstructorTests.Just;
var
O: TObservable<string>;
OnNext: TOnNext<string>;
OnCompleted: TOnCompleted;
A: array of TSmartVariable<string>;
begin
OnNext := procedure(const Data: string)
begin
FStream.Add(Data);
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<string>.Just(['1', '2', '3']);
O.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['1', '2', '3', 'completed']));
FStream.Clear;
SetLength(A, 3);
A[0] := '10';
A[1] := '11';
A[2] := '12' ;
O := TObservable<string>.Just(A);
O.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['10', '11', '12', 'completed']));
end;
procedure TConstructorTests.Range;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
begin
O := Rx.Observable.Range(1, 10, 2);
OnNext := procedure(const Data: Integer)
begin
FStream.Add(IntToStr(Data))
end;
OnCompleted := procedure
begin
FStream.Add('Completed');
end;
O.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, ['1', '3', '5', '7', '9', 'Completed']));
end;
procedure TConstructorTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TConstructorTests.TearDown;
begin
inherited;
FStream.Free;
end;
{ TSchedulersTests }
procedure TSchedulersTests.ContractLockIssue;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
OnSubscribe: TOnSubscribe<Integer>;
ThreadID: LongWord;
Event: TEvent;
begin
OnNext := procedure(const Data: Integer)
begin
ThreadID := TThread.CurrentThread.ThreadID;
end;
OnCompleted := procedure
begin
Event.SetEvent;
end;
OnSubscribe := procedure(O: IObserver<Integer>)
var
Th: TThread;
begin
Th := TThread.CreateAnonymousThread(procedure
begin
O.OnNext(1);
O.OnCompleted;
end);
Th.Start;
Sleep(1000);
end;
Event := TEvent.Create(nil, False, False, '');
ThreadID := 0;
try
O := TObservable<Integer>.Create(OnSubscribe);
O := O.ScheduleOn(StdSchedulers.CreateMainThreadScheduler);
O.Subscribe(OnNext, OnCompleted);
Check(Event.WaitFor(5000) = wrSignaled, 'event wait timeout');
Check(ThreadID <> TThread.CurrentThread.ThreadID);
finally
Event.Free
end
end;
procedure TSchedulersTests.MainThreadScheduler1;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
OnSubscribe: TOnSubscribe<Integer>;
ThreadID: LongWord;
Expected: string;
begin
OnSubscribe := procedure(O: IObserver<Integer>)
var
Th: TThread;
begin
Th := TThread.CreateAnonymousThread(procedure
begin
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(20);
end);
ThreadID := Th.ThreadID;
Th.Start;
Sleep(1000);
end;
O := TObservable<Integer>.Create(OnSubscribe);
OnNext := procedure(const Data: Integer)
begin
FStream.Add('next:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
OnCompleted := procedure
begin
FStream.Add('completed:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
O.Subscribe(OnNext, OnCompleted);
Expected := 'next:' + IntToStr(ThreadID);
Check(IsEqual(FStream, [Expected, Expected, 'completed:' + IntToStr(ThreadID)]));
FStream.Clear;
O := O.ScheduleOn(StdSchedulers.CreateMainThreadScheduler);
O.Subscribe(OnNext, OnCompleted);
Expected := 'next:' + IntToStr(MainThreadID);
{CheckSynchronize(100);
CheckSynchronize(100);
CheckSynchronize(100);
CheckSynchronize(100);}
Check(IsEqual(FStream, [Expected, Expected, 'completed:' + IntToStr(MainThreadID)]));
end;
procedure TSchedulersTests.MainThreadScheduler2;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
ThreadID: LongWord;
Expected: string;
Th: TThread;
begin
OnNext := procedure(const Data: Integer)
begin
FStream.Add('next:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
OnCompleted := procedure
begin
FStream.Add('completed:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
O.Subscribe(OnNext, OnCompleted);
Th := TThread.CreateAnonymousThread(
procedure
begin
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(20);
end);
ThreadID := Th.ThreadID;
Th.Start;
Sleep(1000);
Expected := 'next:' + IntToStr(ThreadID);
Check(IsEqual(FStream, [Expected, Expected, 'completed:' + IntToStr(ThreadID)]));
FStream.Clear;
O.ScheduleOn(StdSchedulers.CreateMainThreadScheduler);
O.Subscribe(OnNext, OnCompleted);
Expected := 'next:' + IntToStr(MainThreadID);
Th := TThread.CreateAnonymousThread(
procedure
begin
O.OnNext(1);
O.OnNext(10);
O.OnCompleted;
O.OnNext(20);
end);
Th.Start;
Sleep(1000);
CheckSynchronize(100);
CheckSynchronize(100);
CheckSynchronize(100);
CheckSynchronize(100);
Check(IsEqual(FStream, [Expected, Expected, 'completed:' + IntToStr(MainThreadID)]));
end;
procedure TSchedulersTests.NewThreadScheduler;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
Th: TThread;
ThreadID: LongWord;
CompletedOK: Boolean;
I: Integer;
begin
ThreadID := 0;
CompletedOK := False;
OnNext := procedure(const Data: Integer)
begin
if ThreadID = 0 then
ThreadID := TThread.CurrentThread.ThreadID;
FStream.Add(IntToStr(TThread.CurrentThread.ThreadID));
end;
OnCompleted := procedure
begin
FStream.Add(IntToStr(TThread.CurrentThread.ThreadID));
CompletedOK := True;
end;
O.ScheduleOn(StdSchedulers.CreateNewThreadScheduler);
O.Subscribe(OnNext, OnCompleted);
Th := TThread.CreateAnonymousThread(
procedure
begin
O.OnNext(1);
O.OnNext(2);
O.OnCompleted;
O.OnNext(3);
end);
Th.Start;
Sleep(5000);
CheckTrue(CompletedOK);
CheckNotEquals(MainThreadID, ThreadID);
CheckEquals(3, FStream.Count);
for I := 0 to FStream.Count-1 do
CheckEquals(I, FStream.IndexOf(FStream[I]))
end;
procedure TSchedulersTests.SeparateThreadScheduler;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
ThreadID: LongWord;
Expected: string;
Th: TThread;
begin
ThreadID := 0;
OnNext := procedure(const Data: Integer)
begin
if ThreadID = 0 then
ThreadID := TThread.CurrentThread.ThreadID;
FStream.Add('next:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
OnCompleted := procedure
begin
FStream.Add('completed:'+IntToStr(TThread.CurrentThread.ThreadID));
end;
O.ScheduleOn(StdSchedulers.CreateSeparateThreadScheduler);
O.Subscribe(OnNext, OnCompleted);
O.OnNext(1);
O.OnNext(2);
O.OnCompleted;
O.OnNext(3);
Sleep(5000);
CheckFalse(ThreadID = MainThreadID, 'thread problem');
Expected := 'next:' + IntToStr(ThreadID);
Check(IsEqual(FStream, [Expected, Expected, 'completed:' + IntToStr(ThreadID)]));
end;
procedure TSchedulersTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TSchedulersTests.TearDown;
begin
inherited;
FStream.Free;
end;
procedure TSchedulersTests.ThreadPoolScheduler;
var
O: TObservable<Integer>;
OnNext: TOnNext<Integer>;
OnCompleted: TOnCompleted;
Th: TThread;
ThreadID: LongWord;
CompletedOK: Boolean;
I: Integer;
begin
ThreadID := 0;
CompletedOK := False;
OnNext := procedure(const Data: Integer)
begin
if ThreadID = 0 then
ThreadID := TThread.CurrentThread.ThreadID;
FStream.Add(IntToStr(TThread.CurrentThread.ThreadID));
Sleep(1000)
end;
OnCompleted := procedure
begin
FStream.Add(IntToStr(TThread.CurrentThread.ThreadID));
CompletedOK := True;
end;
O.ScheduleOn(StdSchedulers.CreateThreadPoolScheduler(5));
O.Subscribe(OnNext, OnCompleted);
Th := TThread.CreateAnonymousThread(
procedure
begin
O.OnNext(1);
O.OnNext(2);
O.OnCompleted;
O.OnNext(3);
end);
Th.Start;
Sleep(5000);
CheckTrue(CompletedOK);
CheckNotEquals(MainThreadID, ThreadID);
CheckEquals(3, FStream.Count);
for I := 0 to FStream.Count-1 do
CheckEquals(I, FStream.IndexOf(FStream[I]))
end;
{ TAdvancedOpsTests }
procedure TAdvancedOpsTests.ScanObjects;
var
O, Progress: TObservable<TInteger>;
OnSubscribe: TOnSubscribe<TInteger>;
OnNext: TOnNext<TInteger>;
Scan: TScanRoutine<TInteger, TInteger>;
begin
Scan := procedure(var Progress: TInteger; const Cur: TInteger)
begin
Progress.Value := Progress.Value + Cur.Value;
end;
OnSubscribe := procedure(O: IObserver<TInteger>)
begin
O.OnNext(TInteger.Create(10));
O.OnNext(TInteger.Create(30));
O.OnNext(TInteger.Create(10));
end;
OnNext := procedure(const Progress: TInteger)
begin
FStream.Add(IntToStr(Progress.Value));
end;
O := TObservable<TInteger>.Create(OnSubscribe);
Progress := O.Scan(TInteger.Create(0), Scan);
Progress.Subscribe(OnNext);
Check(IsEqual(FStream, ['10', '40', '50']));
end;
procedure TAdvancedOpsTests.CollectWithDict;
var
O: TObservable<TInteger>;
CollectO: TObservable<TDictionary<Integer, TInteger>>;
OnSubscribe: TOnSubscribe<TInteger>;
OnNext: TOnNext<TDictionary<Integer, TInteger>>;
Collect: TCollectAction2<Integer, TInteger, TInteger>;
OnCompleted: TOnCompleted;
begin
Collect := procedure(const Dict: TDictionary<Integer, TInteger>; const Value: TInteger)
var
Key: Integer;
begin
Key := Value.Value;
if Dict.ContainsKey(Key) then
Dict[Key].Value := Dict[Key].Value + 1
else
Dict.Add(Key, TInteger.Create(1));
end;
OnSubscribe := procedure(O: IObserver<TInteger>)
begin
O.OnNext(TInteger.Create(1));
O.OnNext(TInteger.Create(2));
O.OnNext(TInteger.Create(2));
O.OnNext(TInteger.Create(3));
O.OnNext(TInteger.Create(1));
O.OnNext(TInteger.Create(1));
end;
OnNext := procedure(const Dict: TDictionary<Integer, TInteger>)
var
KV: TPair<Integer, TInteger>;
begin
for KV in Dict do begin
FStream.Add(Format('%d:%d', [KV.Key, KV.Value.Value]))
end;
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<TInteger>.Create(OnSubscribe);
CollectO := O.Collect<Integer, TInteger>(Collect);
CollectO.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, []));
O.OnCompleted;
Check(IsEqual(FStream, ['3:1', '2:2', '1:3', 'completed']));
end;
procedure TAdvancedOpsTests.CollectWithList;
var
O: TObservable<TInteger>;
CollectO: TObservable<TList<TInteger>>;
OnSubscribe: TOnSubscribe<TInteger>;
OnNext: TOnNext<TList<TInteger>>;
Collect: TCollectAction1<TInteger, TInteger>;
OnCompleted: TOnCompleted;
begin
Collect := procedure(const List: TList<TInteger>; const Value: TInteger)
var
Found: Boolean;
I: Integer;
begin
Found := False;
for I := 0 to List.Count-1 do
if List[I].Value = Value.Value then begin
Found := True;
Break
end;
if not Found then
List.Add(Value)
end;
OnSubscribe := procedure(O: IObserver<TInteger>)
begin
O.OnNext(TInteger.Create(30));
O.OnNext(TInteger.Create(10));
O.OnNext(TInteger.Create(50));
O.OnNext(TInteger.Create(10));
end;
OnNext := procedure(const Collection: TList<TInteger>)
var
I: Integer;
Item: TInteger;
begin
for I := 0 to Collection.Count-1 do begin
Item := Collection[I];
FStream.Add(IntToStr(Item.Value));
end;
end;
OnCompleted := procedure
begin
FStream.Add('completed');
end;
O := TObservable<TInteger>.Create(OnSubscribe);
CollectO := O.Collect<TInteger>([TInteger.Create(10)], Collect);
CollectO.Subscribe(OnNext, OnCompleted);
Check(IsEqual(FStream, []));
O.OnCompleted;
Check(IsEqual(FStream, ['10', '30', '50', 'completed']));
end;
procedure TAdvancedOpsTests.Reduce;
var
O, Progress: TObservable<Integer>;
OnSubscribe: TOnSubscribe<Integer>;
OnNext: TOnNext<Integer>;
Reduce: TReduceRoutine<Integer, Integer>;
begin
Reduce := function(const Accum: Integer; const Item: Integer): Integer
begin
Result := Accum + Item
end;
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(10);
O.OnNext(30);
O.OnNext(10);
end;
OnNext := procedure(const Progress: Integer)
begin
FStream.Add(IntToStr(Progress));
end;
O := TObservable<Integer>.Create(OnSubscribe);
Progress := O.Reduce(Reduce);
Progress.Subscribe(OnNext);
Check(IsEqual(FStream, []));
O.OnCompleted;
Check(IsEqual(FStream, ['50']));
end;
procedure TAdvancedOpsTests.ResuceZero;
var
O, Progress: TObservable<Integer>;
OnSubscribe: TOnSubscribe<Integer>;
OnNext: TOnNext<Integer>;
Reduce: TReduceRoutine<Integer, Integer>;
begin
Reduce := function(const Accum: Integer; const Item: Integer): Integer
begin
Result := Accum + Item
end;
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnCompleted;
O.OnNext(10)
end;
OnNext := procedure(const Progress: Integer)
begin
FStream.Add(IntToStr(Progress));
end;
O := TObservable<Integer>.Create(OnSubscribe);
Progress := O.Reduce(Reduce);
Check(IsEqual(FStream, []));
end;
procedure TAdvancedOpsTests.Scan;
var
O, Progress: TObservable<Integer>;
OnSubscribe: TOnSubscribe<Integer>;
OnNext: TOnNext<Integer>;
Scan: TScanRoutine<Integer, Integer>;
begin
Scan := procedure(var Progress: Integer; const Cur: Integer)
begin
Progress := Progress + Cur;
end;
OnSubscribe := procedure(O: IObserver<Integer>)
begin
O.OnNext(10);
O.OnNext(30);
O.OnNext(10);
end;
OnNext := procedure(const Progress: Integer)
begin
FStream.Add(IntToStr(Progress));
end;
O := TObservable<Integer>.Create(OnSubscribe);
Progress := O.Scan(0, Scan);
Progress.Subscribe(OnNext);
Check(IsEqual(FStream, ['10', '40', '50']));
end;
procedure TAdvancedOpsTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TAdvancedOpsTests.TearDown;
begin
inherited;
FStream.Free;
end;
{ TMergeTests }
procedure TMergeTests.PassingOnError;
var
Source, Dest1, Dest2: TObservable<string>;
Map: TMap<string, string>;
OnError1, OnError2: TOnError;
begin
Map := function(const Data: string): string
begin
Result := Data
end;
OnError1 := procedure(E: IThrowable)
begin
FStream.Add('error:1')
end;
OnError2 := procedure(E: IThrowable)
begin
FStream.Add('error:2')
end;
Source.SetName('Source');
Dest1 := Source.Map<string>(Map);
Dest1.SetName('Dest1');
Dest1.Subscribe(nil, OnError1);
Dest2 := Source.Map<string>(Map);
Dest2.Subscribe(nil, OnError2);
Source.OnError(nil);
Check(IsEqual(FStream, ['error:1', 'error:2']));
end;
procedure TMergeTests.PassingOnNext;
var
Source, Dest1, Dest2: TObservable<string>;
Map: TMap<string, string>;
OnNext1, OnNext2: TOnNext<string>;
begin
Map := function(const Data: string): string
begin
Result := Data
end;
OnNext1 := procedure(const Data: string)
begin
FStream.Add(Data + ':1')
end;
OnNext2 := procedure(const Data: string)
begin
FStream.Add(Data + ':2')
end;
Dest1 := Source.Map<string>(Map);
Dest1.Subscribe(OnNext1);
Dest2 := Source.Map<string>(Map);
Dest2.Subscribe(OnNext2);
Source.OnNext('A');
Source.OnNext('B');
Source.OnNext('C');
Check(IsEqual(FStream, ['A:1', 'A:2', 'B:1', 'B:2', 'C:1', 'C:2']));
end;
procedure TMergeTests.SetUp;
begin
inherited;
FStream := TList<string>.Create;
end;
procedure TMergeTests.TearDown;
begin
inherited;
FStream.Free;
end;
initialization
RegisterTests('Observable', [
TSmartVariableTests.Suite,
TSubscriptionTests.Suite,
TMergeTests.Suite,
TOperationsTests.Suite,
TAdvancedOpsTests.Suite,
TMemoryLeaksTests.Suite,
TConstructorTests.Suite,
TSchedulersTests.Suite
]);
end.
|
unit Model.Interfaces;
interface
uses
FMX.Graphics, System.Generics.Collections, Model.PhoneNumber;
type
IPizza = interface
['{17F036A2-FE50-4834-887B-4358B068EA05}']
function GetID: Integer;
function GetName: String;
function GetPhoto: TBitMap;
function GetPrice: Currency;
procedure SetID(const Value: Integer);
procedure SetName(const Value: String);
procedure SetPhoto(const Value: TBitMap);
procedure SetPrice(const Value: Currency);
// Properties
property ID:Integer read GetID write SetID;
property Name:String read GetName write SetName;
property Price:Currency read GetPrice write SetPrice;
property Photo:TBitMap read GetPhoto write SetPhoto;
end;
implementation
end.
|
unit Unit_Barras;
interface
uses
SysUtils, Classes;
type
TBarras = Class
Private
ListaBarras: TStringList; // Objeto que ha de guardar la lista de las barras
IntCuentaBarras: Integer; // Indicador de número de barras creadas
IntPosicionClick: Integer; // 1 - Se toma la barra de lado izaquierdo, 2 del centro y 3 del lado derecho
IntLastNumBarra: Integer; // Número de barra clicada
BolLastBarra: Boolean; // ¿Se tecleó una barra?
function ProcGetX(Index: Integer): Integer;
function ProcGetY(Index: Integer): Integer;
function ProcGetWidth(Index: Integer): Integer;
function ProcGetHeight(Index: Integer): Integer;
function ProcGetTipo(Index: Integer): String;
function ProcGetNumero(Index: Integer): String;
function ProcGetInicio(Index: Integer): TDateTime;
function ProcGetTermino(Index: Integer): TDateTime;
function ProcExisteBarra(X,Y,Cual: Integer): Integer;
procedure SetPosicionClick(Value: Integer);
function ProcFechaHora(X: Integer; Inicio,Termino,Periodo,Ancho: Real; sbPosition: Integer): TDateTime;
Public
constructor create;
destructor Destroy;
procedure CrearBarra(IntBarraX, IntBarraY, IntBarraWidth, IntBarraHeight: Integer; StrBarraNumeroActividad: String; StrBarraTipoA: String; DateBarraInicio, DateBarraTermino: TDateTime);
procedure QuitaReferenciaBarra;
procedure Limpiar;
property CuentaBarras: Integer Read IntCuentaBarras;
property X[Index: Integer]: Integer Read ProcGetX;
property Y[Index: Integer]: Integer Read ProcGetY;
property Width[Index: Integer]: Integer Read ProcGetWidth;
property Height[Index: Integer]: Integer Read ProcGetHeight;
property Tipo[Index: Integer]: String Read ProcGetTipo;
property NumeroActividad[Index: Integer]: String Read ProcGetNumero;
property Inicio[Index: Integer]: TDateTime Read ProcGetInicio;
property Termino[Index: Integer]: TDateTime Read ProcGetTermino;
property ExisteBarra[X,Y,Cual: Integer]: Integer Read ProcExisteBarra;
property PosicionClick: Integer Read IntPosicionClick Write SetPosicionClick;
property LastNumBarra: Integer Read IntLastNumBarra;
property LastBarra: Boolean Read BolLastBarra;
property FechaHora[X: Integer; Inicio,Termino,Periodo,Ancho: Real; sbPosition: Integer]: TDateTime Read ProcFechaHora;
End;
implementation
Function Entry(Cadena: String; Indice: Integer): String;
var
subcad: String;
Continua: Boolean;
cta, Buscar: Integer;
Begin
cta := 0;
subcad := '';
Continua := True;
Buscar := 0;
while (cta < Length(Cadena)) And (Continua) do
begin
inc(cta);
if Cadena[cta] = ':' then
begin
Inc(Buscar);
Continua := Buscar <> Indice;
if Continua then
subcad := ''; // Preparar el inicio de una nueva cadena a buscar
end
else
Begin
subcad := subcad + cadena[cta];
End;
end;
Entry := SubCad;
End;
function TBarras.ProcFechaHora(X: Integer; Inicio,Termino,Periodo,Ancho: Real; sbPosition: Integer): TDateTime;
var
mFecha: TDateTime;
iInicia: Integer;
begin
mFecha := Inicio;
iInicia := -1;
while (mFecha <= Termino) and (iInicia <= X) do
Begin
iInicia := Trunc((((mFecha - Inicio) / Periodo) * (Periodo * Ancho)) - (sbPosition * Ancho));
if iInicia <= X then mFecha := mFecha + 1;
End;
mFecha := mFecha - 1; // Ajustar también porque siempre sale un dia despues
ProcFechaHora := mFecha;
end;
Procedure TBarras.SetPosicionClick(Value: Integer);
Begin
IntPosicionClick := Value;
End;
procedure TBarras.QuitaReferenciaBarra;
Begin
IntLastNumBarra := 0;
BolLastBarra := False;
IntPosicionClick := 0;
End;
function TBarras.ProcExisteBarra(X,Y,Cual: Integer): Integer;
var
cta: Integer;
LastBarra: Boolean;
begin
// Identificar en que barra se ha hecho el click
LastBarra := False;
cta := 0;
while (Not LastBarra) and (cta < IntCuentaBarras) do
Begin
LastBarra := (X >= ProcGetX(cta)) And (X <= ProcGetWidth(Cta)) And (Y >= ProcGetY(cta)) And (Y <= ProcGetHeight(cta)) And (ProcGetTipo(cta) = 'Actividad');
Inc(cta);
End;
if LastBarra then
Begin
Dec(Cta);
IntLastNumBarra := Cta; // Indicador de la última barra seleccionada
IntPosicionClick := 2; // Por default al centro...
if (X < ProcGetX(cta) + 4) then IntPosicionClick := 1;
if (X > ProcGetWidth(cta) - 4) then IntPosicionClick := 3;
End
else
cta := 0;
BolLastBarra := LastBarra;
ProcExisteBarra := Cta;
end;
function TBarras.ProcGetX(Index: Integer): Integer;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetX := StrToInt(Entry(Cadena,1)); // Localizar coordenada X
End;
function TBarras.ProcGetY(Index: Integer): Integer;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetY := StrToInt(Entry(Cadena,2)); // Localizar coordenada Y
End;
function TBarras.ProcGetWidth(Index: Integer): Integer;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetWidth := StrToInt(Entry(Cadena,3)); // Localizar el ancho de la barra
End;
function TBarras.ProcGetHeight(Index: Integer): Integer;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetHeight := StrToInt(Entry(Cadena,4)); // Localizar la altura de la barra
End;
function TBarras.ProcGetNumero(Index: Integer): String;
Var
Cadena: String;
begin
Cadena := ListaBarras[Index] + ':';
ProcGetNumero := Entry(Cadena,5); // Localizar el numero de actividad
end;
function TBarras.ProcGetTipo(Index: Integer): String;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetTipo := Entry(Cadena,6); // Localizar el tipo de la actividad
End;
function TBarras.ProcGetInicio(Index: Integer): TDateTime;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetInicio := StrToInt(Entry(Cadena,7)); // Localizar la fecha de inicio de la barra
End;
function TBarras.ProcGetTermino(Index: Integer): TDateTime;
Var
Cadena: String;
Begin
Cadena := ListaBarras[Index] + ':';
ProcGetTermino := StrToInt(Entry(Cadena,8)); // Localizar la fecha de termino de la barra
End;
constructor TBarras.Create;
Begin
ListaBarras := TStringList.Create;
IntCuentaBarras := 0; // Indicador de número de barras creadas
IntPosicionClick := 0; // Ninguna barra seleccionada
IntLastNumBarra := 0; // Número de barra clicada
BolLastBarra := False; // ¿Se tecleó una barra?
End;
destructor TBarras.Destroy;
Begin
IntCuentaBarras := 0;
Freeandnil(ListaBarras);
End;
procedure TBarras.CrearBarra(IntBarraX, IntBarraY, IntBarraWidth, IntBarraHeight: Integer; StrBarraNumeroActividad: String; StrBarraTipoA: String; DateBarraInicio, DateBarraTermino: TDateTime);
Begin
// Agregar la información necesaria para la barra
ListaBarras.add(IntToStr(IntBarraX) + ':' + IntToStr(IntBarraY) + ':' + IntToStr(IntBarraWidth) + ':' + IntToStr(IntBarraHeight) + ':' + StrBarraNumeroActividad + ':' + StrBarraTipoA + ':' + FloatToStr(DateBarraInicio) + ':' + FloatToStr(DateBarraTermino));
Inc(IntCuentaBarras);
End;
procedure TBarras.Limpiar;
Var
Cta: Integer;
begin
// Limpiar todas las barras existentes
Cta := 0;
while Cta < IntCuentaBarras do
Begin
ListaBarras.Delete(0);
Inc(Cta);
End;
IntCuentaBarras := 0;
BolLastBarra := False;
end;
end.
|
unit UFuncaoCalculadora;
interface
type
TFuncaoCalculadora = class
private
public
class function soma(valor1, valor2: Double): Double;
class function subtrair(valor1, valor2: Double): Double;
class function dividir(valor1, valor2:Double): Double;
class function multiplicar(valor1, valor2: Double): Double;
end;
implementation
{ TFuncaoCalculadora }
class function TFuncaoCalculadora.dividir(valor1, valor2: Double): Double;
begin
Result := (valor1 / valor2);
end;
class function TFuncaoCalculadora.multiplicar(valor1, valor2: Double): Double;
begin
Result := (valor1 * valor2);
end;
class function TFuncaoCalculadora.soma(valor1, valor2: Double): Double;
begin
Result := (valor1 + valor2);
end;
class function TFuncaoCalculadora.subtrair(valor1, valor2: Double): Double;
begin
Result := (valor1 - valor2);
end;
end.
|
unit MyData;
{
MyData: thin LibMySQL wrapper to connect to a MySQL/MariaDB server.
https://github.com/stijnsanders/DataLank
ATTENTION:
Include following files in the folder that contains the executable,
or in a folder included in the default DLL search path.
They are provided with the Windows MySQL/MariaDB server install.
libmysql.dll
}
interface
//debugging: prevent step-into from debugging TQueryResult calls:
{$D-}
{$L-}
uses SysUtils, LibMy;
type
TMySQLConnection=class(TObject)
private
FDB:PMYSQL;
procedure Exec(const SQL:UTF8String);
public
constructor Create(const Host, User, Pwd, SelectDB: UTF8String;
Port: integer); overload;
constructor Create(const Parameters: UTF8String); overload;
destructor Destroy; override;
procedure BeginTrans;
procedure CommitTrans;
procedure RollbackTrans;
function Execute(const SQL: WideString;
const Values: array of Variant): integer;
function Insert(const TableName: WideString;
const Values: array of Variant;
const PKFieldName:string=''): integer;
procedure Update(const TableName: WideString;
const Values:array of Variant);
property Handle:PMYSQL read FDB;
end;
TMySQLStatement=class(TObject)
private
FFirstRead,FFieldNamesListed:boolean;
FFieldNames:array of string;
function FieldIdx(const Idx:Variant):integer;
function GetValue(const Idx:Variant):Variant;
function IsEof:boolean;
function GetCount:integer;
protected
FDB:PMYSQL;
FResultSet:PMYSQL_RES;
FResultRow:MYSQL_ROW;
public
constructor Create(Connection: TMySQLConnection; const SQL: WideString;
const Values: array of Variant);
destructor Destroy; override;
procedure Reset;
procedure NextResults;
function Read:boolean;
property Fields[const Idx:Variant]:Variant read GetValue; default;
property EOF: boolean read IsEof;
property Count: integer read GetCount;
function GetInt(const Idx:Variant):integer;
function GetStr(const Idx:Variant):WideString;
function GetDate(const Idx:Variant):TDateTime;
function IsNull(const Idx:Variant):boolean;
end;
EMyDataError=class(Exception);
EQueryResultError=class(Exception);
implementation
uses Variants, VarConv;
{$IF not Declared(UTF8ToWideString)}
function UTF8ToWideString(const s: UTF8String): WideString;
begin
Result:=UTF8Decode(s);
end;
{$IFEND}
{ TMySQLConnection }
constructor TMySQLConnection.Create(const Host, User, Pwd, SelectDB: UTF8String;
Port: integer);
begin
inherited Create;
FDB:=mysql_init(nil);
if mysql_real_connect(FDB,PAnsiChar(Host),
PAnsiChar(User),PAnsiChar(Pwd),PAnsiChar(SelectDB),Port,nil,0)=nil then
raise EMyDataError.Create(mysql_error(FDB));
end;
constructor TMySQLConnection.Create(const Parameters: UTF8String);
var
i,j,k,l:integer;
s,t, Host, User, Pwd, SelectDB: UTF8String;
Port: integer;
begin
inherited Create;
//defaults
Host:='';
User:='';
Pwd:='';
SelectDB:='';
Port:=MYSQL_PORT;
//parse
i:=1;
l:=Length(Parameters);
while (i<=l) do
begin
j:=i;
while (j<=l) and (Parameters[j]<>'=') do inc(j);
k:=j+1;
while (k<=l) and (Parameters[k]>' ') do inc(k);
s:=LowerCase(Copy(Parameters,i,j-i));
inc(j);
t:=Copy(Parameters,j,k-j);
i:=k+1;
if s='host' then Host:=t
else if s='user' then User:=t
else if s='password' then Pwd:=t
else if s='post' then Port:=StrToInt(t)
else if s='db' then SelectDB:=t
else raise EMyDataError.Create('Unknown connection parameter "'+s+'"');
end;
//connect
FDB:=mysql_init(nil);
if mysql_real_connect(FDB,PAnsiChar(Host),
PAnsiChar(User),PAnsiChar(Pwd),PAnsiChar(SelectDB),Port,nil,0)=nil then
raise EMyDataError.Create(mysql_error(FDB));
end;
destructor TMySQLConnection.Destroy;
begin
if FDB<>nil then
try
mysql_close(FDB);
finally
FDB:=nil;
end;
inherited;
end;
procedure TMySQLConnection.Exec(const SQL: UTF8String);
var
r:PMYSQL_RES;
begin
if mysql_real_query(FDB,PAnsiChar(SQL),Length(SQL))<>0 then
raise EMyDataError.Create(mysql_error(FDB));
r:=mysql_store_result(FDB);
if r<>nil then
begin
mysql_free_result(r);//raise unexpected result set?µ
raise EQueryResultError.Create('Exec: unexpected result set');
end;
end;
procedure TMySQLConnection.BeginTrans;
begin
//mysql_?
Exec('begin');
//TODO: support savepoints
end;
procedure TMySQLConnection.CommitTrans;
begin
//mysql_commit(FDB);?
Exec('commit');
end;
procedure TMySQLConnection.RollbackTrans;
begin
//mysql_rollback(FDB);
Exec('rollback');
end;
function VarToSQL(const Value:Variant):UTF8String;
begin
case VarType(Value) of
varNull,varEmpty:
Result:='NULL';
varSmallint,varInteger,varSingle,varDouble,varCurrency,14,
varShortInt,varByte,varWord,varLongWord,varInt64:
Result:=UTF8Encode(VarToWideStr(Value));
varDate:
Result:=AnsiString(FormatDateTime('"{ts ''"yyyy-mm-dd hh:nn:ss.zzz"''}"',
VarToDateTime(Value)));
varString,varOleStr:
Result:=''''+UTF8Encode(StringReplace(
VarToStr(Value),'''','\''',[rfReplaceAll]))+'''';//TODO: mysql_real_escape_string
varBoolean:
if Value then Result:='1' else Result:='0';
else raise EMyDataError.Create('Unsupported parameter value type');
end;
end;
function ParamBind(SQL:UTF8String;const Values:array of Variant):UTF8String;
var
i,j,k,l,n:integer;
begin
//TODO: mysql_stmt_prepare
Result:='';//TODO: TStringStream
i:=1;
l:=Length(SQL);
k:=0;
n:=Length(Values);
while i<=l do
begin
j:=i;
while (j<=l) and (SQL[j]<>'?') do inc(j);
Result:=Result+Copy(SQL,i,j-i);
i:=j;
if j<=l then
begin
if k>=n then raise EMyDataError.Create('Insufficient parameter values');
Result:=Result+VarToSQL(Values[k]);
inc(k);
inc(i);
end;
end;
if k<n then raise EMyDataError.Create('Superfluous parameter values');
end;
function TMySQLConnection.Execute(const SQL: WideString;
const Values: array of Variant): integer;
var
r:PMYSQL_RES;
s:UTF8String;
begin
s:=ParamBind(UTF8ToWideString(SQL),Values);
if mysql_real_query(FDB,PAnsiChar(s),Length(s))<>0 then
raise EMyDataError.Create(mysql_error(FDB));
r:=mysql_store_result(FDB);//TODO: switch? mysql_use_result
if r<>nil then
begin
mysql_free_result(r);
raise EQueryResultError.Create('Execute: unexpected result set');
end;
Result:=mysql_affected_rows(FDB);
end;
function TMySQLConnection.Insert(const TableName: WideString;
const Values: array of Variant; const PKFieldName:string=''): integer;
var
i,l:integer;
sql1,sql2:UTF8String;
r:PMYSQL_RES;
begin
l:=Length(Values);
if (l and 1)<>0 then
raise EQueryResultError.Create('Insert('''+string(TableName)+
''') requires an even number of values');
sql1:='';
sql2:='';
i:=1;
while i<l do
begin
if not VarIsNull(Values[i]) then
begin
sql1:=sql1+','+UTF8Encode(VarToWideStr(Values[i-1]));
sql2:=sql2+','+VarToSQL(Values[i]);
end;
inc(i,2);
end;
sql1[1]:='(';
sql2[1]:='(';
sql1:='insert into '+TableName+' '+sql1+') values '+sql2+')';
if mysql_real_query(FDB,PAnsiChar(sql1),Length(sql1))<>0 then
raise EMyDataError.Create(mysql_error(FDB));
r:=mysql_store_result(FDB);//TODO: switch? mysql_use_result
if r<>nil then
begin
mysql_free_result(r);
raise EQueryResultError.Create('Insert: unexpected result set');
end;
if PKFieldName='' then Result:=-1 else Result:=mysql_insert_id(FDB);
end;
procedure TMySQLConnection.Update(const TableName: WideString;
const Values: array of Variant);
var
i,l:integer;
sql:UTF8String;
r:PMYSQL_RES;
begin
l:=Length(Values);
if (l and 1)<>0 then
raise EQueryResultError.Create('Update('''+string(TableName)+
''') requires an even number of values');
sql:='';
i:=3;
while i<l do
begin
if not VarIsNull(Values[i]) then
sql:=sql+','+UTF8Encode(VarToWideStr(Values[i-1]))+
'='+VarToSQL(Values[i]);
inc(i,2);
end;
sql[1]:=' ';
sql:='update '+TableName+' set'+sql+
' where '+Values[0]+'='+VarToSQL(Values[1]);
if mysql_real_query(FDB,PAnsiChar(sql),Length(sql))<>0 then
raise EMyDataError.Create(mysql_error(FDB));
r:=mysql_store_result(FDB);//TODO: switch? mysql_use_result
if r<>nil then
begin
mysql_free_result(r);
raise EQueryResultError.Create('Update: unexpected result set');
end;
end;
{ TMySQLStatement }
constructor TMySQLStatement.Create(Connection: TMySQLConnection;
const SQL: WideString; const Values: array of Variant);
var
s:UTF8String;
begin
inherited Create;
FDB:=Connection.FDB;
s:=ParamBind(SQL,Values);
if mysql_real_query(FDB,PAnsiChar(s),Length(s))<>0 then
raise EMyDataError.Create(mysql_error(FDB));
//TODO: switch? mysql_use_result
FResultSet:=mysql_store_result(FDB);
if FResultSet=nil then
raise EQueryResultError.Create('Query did not return a result set');
FResultRow:=mysql_fetch_row(FResultSet);
FFirstRead:=true;
FFieldNamesListed:=false;
end;
destructor TMySQLStatement.Destroy;
begin
mysql_free_result(FResultSet);
inherited;
end;
function TMySQLStatement.Read: boolean;
begin
if (FResultSet=nil) or (FResultRow=nil) then Result:=false else
begin
if FFirstRead then FFirstRead:=false else
FResultRow:=mysql_fetch_row(FResultSet);
Result:=FResultRow<>nil;
end;
end;
procedure TMySQLStatement.Reset;
begin
FFirstRead:=true;
mysql_row_seek(FResultSet,nil);
end;
function TMySQLStatement.FieldIdx(const Idx: Variant): integer;
var
i:integer;
f:PMYSQL_FIELD;
s:string;
begin
Result:=-1;//default
if FResultRow=nil then
raise EQueryResultError.Create('Reading past EOF');
if VarIsNumeric(Idx) then Result:=Idx else
begin
s:=VarToStr(Idx);
if FFieldNamesListed then
begin
i:=0;
while (i<FResultSet.field_count) and (CompareText(s,FFieldNames[i])<>0) do
inc(i);
Result:=i;
end
else
begin
SetLength(FFieldNames,FResultSet.field_count);
FFieldNamesListed:=true;
i:=0;
f:=mysql_fetch_field(FResultSet);
while f<>nil do
begin
FFieldNames[i]:=f.name;//org_name?
if (Result=-1) and (CompareText(s,FFieldNames[i])=0) then
Result:=i;
inc(i);
f:=mysql_fetch_field(FResultSet);
end;
end;
end;
if (Result<0) or (Result>=FResultSet.field_count) then
raise EQueryResultError.Create('GetInt: Field not found: '+VarToStr(Idx));
end;
function TMySQLStatement.GetInt(const Idx: Variant): integer;
var
p:PAnsiChar;
begin
p:=FResultRow[FieldIdx(Idx)];
if p=nil then Result:=0 else Result:=StrToInt(p);
end;
function TMySQLStatement.GetStr(const Idx: Variant): WideString;
begin
Result:=UTF8ToWideString(FResultRow[FieldIdx(Idx)]);
end;
function TMySQLStatement.GetDate(const Idx: Variant): TDateTime;
var
i,l,f:integer;
dy,dm,dd,th,tm,ts,tz:word;
s:UTF8String;
function Next:word;
begin
Result:=0;
while (i<=l) and (s[i] in ['0'..'9']) do
begin
Result:=Result*10+(byte(s[i]) and $F);
inc(i);
end;
end;
begin
s:=FResultRow[FieldIdx(Idx)];
if s='' then
Result:=0 //now?
else
begin
i:=1;
l:=Length(s);
dy:=Next;
inc(i);//'-'
dm:=Next;
inc(i);//'-'
dd:=Next;
inc(i);//' '
th:=Next;
inc(i);//':'
tm:=Next;
inc(i);//':'
ts:=Next;
inc(i);//'.'
tz:=0;//Next;//more precision than milliseconds here, encode floating:
f:=24*60*60;
Result:=0.0;
while (i<=l) and (s[i] in ['0'..'9']) do
begin
f:=f*10;
Result:=Result+(byte(s[i]) and $F)/f;
inc(i);
end;
//assert i>l
Result:=EncodeDate(dy,dm,dd)+EncodeTime(th,tm,ts,tz)+Result;
end;
end;
function TMySQLStatement.GetValue(const Idx: Variant): Variant;
var
i:integer;
p:PAnsiChar;
begin
i:=FieldIdx(Idx);
p:=FResultRow[i];
if p=nil then Result:=Null else
begin
VarClear(Result);
case mysql_fetch_field_direct(FResultSet,i).type_ of
MYSQL_TYPE_TINY:
begin
TVarData(Result).VType:=varByte;
TVarData(Result).VByte:=StrToInt(p);
end;
MYSQL_TYPE_SHORT:
begin
TVarData(Result).VType:=varShortInt;
TVarData(Result).VShortInt:=StrToInt(p);
end;
MYSQL_TYPE_LONG,MYSQL_TYPE_INT24:
begin
TVarData(Result).VType:=varInteger;
TVarData(Result).VInteger:=StrToInt(p);
end;
MYSQL_TYPE_FLOAT,
MYSQL_TYPE_DOUBLE,
MYSQL_TYPE_DECIMAL,
MYSQL_TYPE_NEWDECIMAL:
begin
TVarData(Result).VType:=varDouble;
TVarData(Result).VDouble:=StrToFloat(p);
end;
MYSQL_TYPE_NULL:
Result:=Null;
MYSQL_TYPE_TIMESTAMP,//?
MYSQL_TYPE_DATE,
MYSQL_TYPE_TIME,
MYSQL_TYPE_DATETIME,
MYSQL_TYPE_YEAR,
MYSQL_TYPE_NEWDATE:
Result:=GetDate(Idx);//?
MYSQL_TYPE_LONGLONG:
begin
TVarData(Result).VType:=varInt64;
TVarData(Result).VInt64:=StrToInt64(p);
end;
MYSQL_TYPE_VARCHAR,
MYSQL_TYPE_VAR_STRING,
MYSQL_TYPE_STRING:
Result:=UTF8ToWideString(p);
MYSQL_TYPE_BIT:
if p='0' then Result:=false else Result:=true;
//MYSQL_TYPE_ENUM=247,
//MYSQL_TYPE_SET=248,
//MYSQL_TYPE_TINY_BLOB=249,
//MYSQL_TYPE_MEDIUM_BLOB=250,
//MYSQL_TYPE_LONG_BLOB=251,
//MYSQL_TYPE_BLOB=252,
//MYSQL_TYPE_GEOMETRY=255
else
//raise?
Result:=UTF8ToWideString(p);
end;
end;
end;
function TMySQLStatement.IsNull(const Idx: Variant): boolean;
begin
Result:=FResultRow[FieldIdx(Idx)]=nil;
end;
function TMySQLStatement.IsEof: boolean;
begin
Result:=(FResultSet=nil) or (FResultRow=nil);
end;
function TMySQLStatement.GetCount: integer;
begin
if FResultSet=nil then Result:=-1 else Result:=FResultSet.row_count;
end;
procedure TMySQLStatement.NextResults;
begin
//xxxxxxxx
end;
initialization
//something fixed invalid, see function RefCursor
mysql_library_init(0,nil,nil);
finalization
mysql_library_end;
end.
|
unit ProgressBarImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls;
type
TProgressBarX = class(TActiveXControl, IProgressBarX)
private
{ Private declarations }
FDelphiControl: TProgressBar;
FEvents: IProgressBarXEvents;
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Max: Integer; safecall;
function Get_Min: Integer; safecall;
function Get_Orientation: TxProgressBarOrientation; safecall;
function Get_Position: Integer; safecall;
function Get_Smooth: WordBool; safecall;
function Get_Step: Integer; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Max(Value: Integer); safecall;
procedure Set_Min(Value: Integer); safecall;
procedure Set_Orientation(Value: TxProgressBarOrientation); safecall;
procedure Set_Position(Value: Integer); safecall;
procedure Set_Smooth(Value: WordBool); safecall;
procedure Set_Step(Value: Integer); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure StepBy(Delta: Integer); safecall;
procedure StepIt; safecall;
end;
implementation
uses ComObj, About23;
{ TProgressBarX }
procedure TProgressBarX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_ProgressBarXPage); }
end;
procedure TProgressBarX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IProgressBarXEvents;
end;
procedure TProgressBarX.InitializeControl;
begin
FDelphiControl := Control as TProgressBar;
end;
function TProgressBarX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TProgressBarX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TProgressBarX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TProgressBarX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TProgressBarX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TProgressBarX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TProgressBarX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TProgressBarX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TProgressBarX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TProgressBarX.Get_Max: Integer;
begin
Result := FDelphiControl.Max;
end;
function TProgressBarX.Get_Min: Integer;
begin
Result := FDelphiControl.Min;
end;
function TProgressBarX.Get_Orientation: TxProgressBarOrientation;
begin
Result := Ord(FDelphiControl.Orientation);
end;
function TProgressBarX.Get_Position: Integer;
begin
Result := FDelphiControl.Position;
end;
function TProgressBarX.Get_Smooth: WordBool;
begin
Result := FDelphiControl.Smooth;
end;
function TProgressBarX.Get_Step: Integer;
begin
Result := FDelphiControl.Step;
end;
function TProgressBarX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TProgressBarX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TProgressBarX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TProgressBarX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TProgressBarX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TProgressBarX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TProgressBarX.AboutBox;
begin
ShowProgressBarXAbout;
end;
procedure TProgressBarX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TProgressBarX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TProgressBarX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TProgressBarX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TProgressBarX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TProgressBarX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TProgressBarX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TProgressBarX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TProgressBarX.Set_Max(Value: Integer);
begin
FDelphiControl.Max := Value;
end;
procedure TProgressBarX.Set_Min(Value: Integer);
begin
FDelphiControl.Min := Value;
end;
procedure TProgressBarX.Set_Orientation(Value: TxProgressBarOrientation);
begin
FDelphiControl.Orientation := TProgressBarOrientation(Value);
end;
procedure TProgressBarX.Set_Position(Value: Integer);
begin
FDelphiControl.Position := Value;
end;
procedure TProgressBarX.Set_Smooth(Value: WordBool);
begin
FDelphiControl.Smooth := Value;
end;
procedure TProgressBarX.Set_Step(Value: Integer);
begin
FDelphiControl.Step := Value;
end;
procedure TProgressBarX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TProgressBarX.StepBy(Delta: Integer);
begin
FDelphiControl.StepBy(Delta);
end;
procedure TProgressBarX.StepIt;
begin
FDelphiControl.StepIt;
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TProgressBarX,
TProgressBar,
Class_ProgressBarX,
23,
'{695CDB8A-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
{********************************************}
{ TeeChart Extended Series Editors }
{ Copyright (c) 1996-2004 by David Berneda }
{********************************************}
unit TeeEditPro;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
{$IFDEF CLX}
QControls, QGraphics, Types,
{$ELSE}
Controls, Graphics,
{$ENDIF}
Classes, Chart, TeEngine;
type
// Custom Graphic class to support loading *.tee files into TImage
// components, etc.
TChartImage = class(TGraphic) { 5.03 }
private
FChart : TChart;
FCustom : Boolean;
function GetChart: TChart;
procedure SetChart(const Value: TChart);
protected
function GetEmpty: Boolean; override;
function GetHeight: Integer; override;
{$IFNDEF CLX}
function GetPalette: HPALETTE; override;
{$ENDIF}
function GetWidth: Integer; override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
procedure ReadData(Stream: TStream); override;
procedure SetHeight(Value: Integer); override;
procedure SetTransparent(Value: Boolean); override;
procedure SetWidth(Value: Integer); override;
procedure WriteData(Stream: TStream); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Clear;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToFile(const Filename: String); override;
procedure SaveToStream(Stream: TStream); override;
{$IFNDEF CLX}
procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE); override;
procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE); override;
{$ENDIF}
procedure Assign(Source: TPersistent); override;
published
property Chart:TChart read GetChart write SetChart;
end;
{ Show the user the dialog associated to the Series }
Procedure EditOneSeries(AOwner:TControl; ASeries:TChartSeries);
{ Show the user a "Save to..." dialog to save it to disk. }
Function SaveChartDialog(AChart:TCustomChart):String;
implementation
{ This unit should be "used" by your applications if showing the
Chart Editor with "Extended" Series and Functions. }
uses SysUtils,
{$IFDEF CLX}
QForms, QDialogs,
{$ELSE}
Forms, Dialogs,
{$ENDIF}
{$IFDEF CLR}
Variants,
{$ENDIF}
EditChar, TeePenDlg, TeeEdiSeri, TeExport, TeeExport, TeeStore, TeeConst,
TeeProCo,
StatChar, TeeCandlEdi, TeeVolEd, TeeSurfEdit, TeePolarEditor,
TeeErrBarEd, CurvFitt, TeeContourEdit,
TeeBezie, TeePo3DEdit, TeeProcs,
TeeCount, TeeCumu, TeeDonutEdit, TeeCursorEdit, TeeTriSurfEdit,
MyPoint, Bar3D, BigCandl, ImaPoint, ImageBar, TeeImaEd, TeeRose,
TeeBoxPlot, TeeHistoEdit, TeeTools, TeeColorLineEditor, TeeColorBandEdit,
TeeAxisArrowEdit, TeeDrawLineEditor, TeeImageToolEdit, TeeAnnToolEdit,
TeeBarJoinEditor, TeeLinePointEditor, TeeRotateToolEditor,
TeeHighLowEdit, TeeClockEditor, TeeBoxPlotEditor, TeeWindRoseEditor,
TeeColorGridEditor, TeeWaterFallEdit, TeeSmith, TeePyramid, TeePyramidEdit,
TeeNearestToolEditor, TeeSmithEdit, TeeCalendarEditor, TeePageNumTool,
TeeMapSeries, TeeMapSeriesEdit,
TeeMarksTipToolEdit, TeeDragMarksEdit, TeeDragPoint,
TeeFunnel, TeeFunnelEditor, TeeADXFuncEditor, TeeMovAveFuncEdit,
TeeSpline, TeeSmoothFuncEdit, TeeTransposeTool,
TeeCompressOHLC, TeeMACDFuncEdit, TeeBollingerEditor,
TeeRMSFuncEdit, TeeExpAveFuncEdit, TeeGanttTool, TeeGridBandToolEdit,
TeeCLVFunction, TeeOBVFunction, TeeCCIFunction, TeePVOFunction,
TeePointFigure, TeeGaugeEditor, TeeTowerEdit,
TeeVectorEdit, TeeSeriesAnimEdit,
TeePieTool, TeeSeriesBandTool, TeeExtraLegendTool, TeeSelectorTool,
TeeLighting, TeeLegendScrollBar, TeeSurfaceTool
;
{$IFDEF CLR}
{$R 'TCandleSeries.bmp'}
{$R 'TContourSeries.bmp'}
{$R 'TErrorBarSeries.bmp'}
{$R 'TPolarSeries.bmp'}
{$R 'TVolumeSeries.bmp'}
{$R 'TPoint3DSeries.bmp'}
{$R 'TRadarSeries.bmp'}
{$R 'TErrorSeries.bmp'}
{$R 'TBezierSeries.bmp'}
{$R 'TClockSeries.bmp'}
{$R 'TWindRoseSeries.bmp'}
{$R 'TDonutSeries.bmp'}
{$R 'THistogramSeries.bmp'}
{$R 'TColorGridSeries.bmp'}
{$R 'THighLowSeries.bmp'}
{$R 'THorizBoxSeries.bmp'}
{$R 'TSurfaceSeries.bmp'}
{$R 'TTriSurfaceSeries.bmp'}
{$R 'TBoxSeries.bmp'}
{$R 'TWaterFallSeries.bmp'}
{$R 'TPyramidSeries.bmp'}
{$R 'TSmithSeries.bmp'}
{$R 'TImagePointSeries.bmp'}
{$R 'TDeltaPointSeries.bmp'}
{$R 'TMapSeries.bmp'}
{$R 'TCalendarSeries.bmp'}
{$R 'TVector3DSeries.bmp'}
{$R 'TTowerSeries.bmp'}
{$R 'TGaugeSeries.bmp'}
{$R 'TPointFigureSeries.bmp'}
{$ELSE}
{$R TeeProBm.res}
{$ENDIF}
{$IFNDEF CLR}
type
TTeeExportFormatAccess=class(TTeeExportFormat);
{$ENDIF}
{ This method shows the "Save As..." dialog to save a Chart into a
native *.tee file or a picture file, depending if exporting formats
are registered (units like TeeBMP used in the application)
}
Function SaveChartDialog(AChart:TCustomChart):String;
var tmpDialog : TSaveDialog;
tmp : TStringList;
t : Integer;
begin
result:='';
tmpDialog:=TSaveDialog.Create(nil);
With tmpDialog do
try
Filter:=TeeMsg_TeeFiles+' (*.'+TeeMsg_TeeExtension+')';
{$IFNDEF CLX}
Filter:=Filter+'|*.'+TeeMsg_TeeExtension;
Options:=[ofHideReadOnly,ofOverwritePrompt];
{$ENDIF}
tmp:=TStringList.Create;
try
TeeFillPictureDialog(tmpDialog,AChart,tmp);
DefaultExt:=TeeMsg_TeeExtension;
if Execute then
begin
if FilterIndex=1 then // native save to *.tee file
SaveChartToFile(AChart,FileName)
else
{ search the selected exporting picture format and save to file }
for t:=0 to tmp.Count-1 do
with {$IFDEF CLR}TTeeExportFormat{$ELSE}TTeeExportFormatAccess{$ENDIF}(tmp.Objects[t]) do
if WantsFilterIndex(tmpDialog.FilterIndex) then // 6.01
begin
SaveToFile(FileName); // 5.02
break;
end;
result:=FileName;
end;
finally
tmp.Free;
end;
finally
Free;
end;
end;
{ This method shows the Series editor dialog as a stand-alone window,
just to edit one series. }
Procedure EditOneSeries(AOwner:TControl; ASeries:TChartSeries);
begin
with TeeCreateForm(SeriesEditorForm(ASeries),AOwner) do
try
BorderIcons:=[biSystemMenu];
Scaled:=False;
Caption:=Format(TeeMsg_Editing,[ASeries.Name]);
Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(ASeries);
{$IFNDEF CLX}
Height:=Height+GetSystemMetrics(SM_CYDLGFRAME)+GetSystemMetrics(SM_CYCAPTION);
{$ENDIF}
ShowModal;
finally
Free;
end;
end;
{ TChartImage }
procedure TChartImage.Assign(Source: TPersistent);
begin
if Assigned(Source) then
if (Source is TChartImage) then
begin
if Assigned(TChartImage(Source).FChart) then
Chart.Assign(TChartImage(Source).FChart)
end
else
inherited;
end;
procedure TChartImage.Clear;
begin
if FCustom then FChart.Free;
end;
constructor TChartImage.Create;
begin
inherited;
FCustom:=True;
end;
destructor TChartImage.Destroy;
begin
if FCustom then FChart.Free;
inherited;
end;
procedure TChartImage.Draw(ACanvas: TCanvas; const Rect: TRect);
begin
Chart.Draw(ACanvas,Rect);
end;
function TChartImage.GetChart: TChart;
begin
if not Assigned(FChart) then
begin
FChart:=TChart.Create(nil);
FCustom:=True;
end;
result:=FChart
end;
function TChartImage.GetEmpty: Boolean;
begin
result:=not Assigned(FChart);
end;
function TChartImage.GetHeight: Integer;
begin
result:=Chart.Height;
end;
{$IFNDEF CLX}
function TChartImage.GetPalette: HPALETTE;
begin
result:=0;
end;
{$ENDIF}
function TChartImage.GetWidth: Integer;
begin
result:=Chart.Width;
end;
{$IFNDEF CLX}
procedure TChartImage.LoadFromClipboardFormat(AFormat: Word;
AData: THandle; APalette: HPALETTE);
begin
end;
procedure TChartImage.SaveToClipboardFormat(var AFormat: Word;
var AData: THandle; var APalette: HPALETTE);
begin
end;
{$ENDIF}
procedure TChartImage.LoadFromStream(Stream: TStream);
begin
ReadData(Stream);
end;
procedure TChartImage.ReadData(Stream: TStream);
{$IFDEF CLR}
var tmp : TCustomChart;
{$ENDIF}
begin
Chart;
{$IFDEF CLR}
//TODO: How to cast to "var TCustomChart"...
tmp:=FChart;
LoadChartFromStream(tmp,Stream);
{$ELSE}
LoadChartFromStream(TCustomChart(FChart),Stream);
{$ENDIF}
end;
procedure TChartImage.SaveToFile(const Filename: String);
begin
SaveChartToFile(Chart,FileName);
end;
procedure TChartImage.SaveToStream(Stream: TStream);
begin
WriteData(Stream);
end;
procedure TChartImage.SetChart(const Value: TChart);
begin
FChart:=Value;
FCustom:=False;
Changed(Self);
end;
procedure TChartImage.SetHeight(Value: Integer);
begin
Chart.Height:=Value;
end;
procedure TChartImage.SetTransparent(Value: Boolean);
begin
Chart.Color:=clNone;
end;
procedure TChartImage.SetWidth(Value: Integer);
begin
Chart.Width:=Value;
end;
procedure TChartImage.WriteData(Stream: TStream);
begin
SaveChartToStream(Chart,Stream);
end;
{$IFNDEF TEEOCX}
initialization
TPicture.RegisterFileFormat(TeeMsg_TeeExtension,'TeeChart',TChartImage);
finalization
TPicture.UnRegisterGraphicClass(TChartImage);
{$ENDIF}
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TChart Geographic Maps }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Chart.Geo;
{.$DEFINE FMX}
interface
uses
{$IFDEF FMX}
FMXBI.Chart.Plugin, FMXTee.Series.World,
{$ELSE}
VCLBI.Chart.Plugin, VCLTee.TeeWorldSeries,
{$ENDIF}
BI.DataItem;
type
TGeoContext=record
public
Map : TWorldMap;
ByCode,
IsMulti : Boolean;
end;
TGeoChart=record
private
class function AreEntities(const Text:TDataItem; out AContext:TGeoContext):Boolean; static;
public
class function CanReuse(const AChart:TBITChart;
const AContext:TGeoContext):Boolean; static;
class procedure Fill(const AChart:TBITChart;
const AValues,AText:TDataItem;
const AContext:TGeoContext); static;
class function Guess(const X,Text:TDataItem;
out AContext:TGeoContext):Boolean; static;
end;
implementation
|
unit adot.Win.HookFormMethods;
interface
uses
adot.Win.HookClassMethods,
Vcl.Forms,
System.Classes,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils;
type
{
High level API to catch TForm.DnCreate/TForm.DoShow/TFrame.Create.
1. It is NOT thread-safe.
2. It is safe to use it from threads different from main one, but all
calls must be serialized (because of 1.). Indeed it is NOT tested yet.
3. It is safe to register same handler for different events if they are
compatible (like TNotifyFormOnCreate and TNotifyFormOnShow).
4. It is not neccessary to unhook if handler is valid all the time.
5. It is safe to unhook handler several times (returns True only first time).
6. It is safe to use it from Initialization section of the unit.
7. Compatible with Windows x32 and x64 platforms.
8. Use it only if it is really neccessary (if there is no standard way).
}
TNotifyFormOnCreate = reference to procedure(AForm: TCustomForm; ABeforeOriginal: Boolean);
TNotifyFormOnShow = reference to procedure(AForm: TCustomForm; ABeforeOriginal: Boolean);
TNotifyFrameCreate = reference to procedure(AFrame: TCustomFrame; ABeforeOriginal: Boolean);
function RegHookFormOnCreate(AHandler: TNotifyFormOnCreate):Int64;
function RegHookFormOnShow(AHandler: TNotifyFormOnShow):Int64;
function RegHookFrameCreate(AHandler: TNotifyFrameCreate):Int64;
function UnregHook(const AHookId: int64):Boolean;
{
Unregister all handlers and disable hooks. By default it is called
automatically from Finalization section, but this behaviour can be disabled
(for example if you need to use it in finalization section of other unit).
}
procedure FinalizeHooks;
procedure DisableAutoFinalization;
implementation
type
THookedForm = class(TCustomForm)
procedure HookedDoCreate;
procedure HookedDoShow;
end;
THookedFrame = class(TCustomFrame)
constructor Create(AOwner: TComponent); override;
end;
var
AutoFinalizationDisabled: Boolean;
Initialized: Boolean;
IdCounter: int64;
FormDoCreate: TPatchRecord;
FormDoShow: TPatchRecord;
FrameCreate: TPatchRecord;
HooksFormOnCreate: TDictionary<int64, TNotifyFormOnCreate>;
HooksFormOnShow: TDictionary<int64, TNotifyFormOnShow>;
HooksFrameCreate: TDictionary<int64, TNotifyFrameCreate>;
procedure PatchCreate;
begin
FormDoCreate.InstallHook(@THookedForm.DoCreate, @THookedForm.HookedDoCreate);
FormDoShow.InstallHook(@THookedForm.DoShow, @THookedForm.HookedDoShow);
FrameCreate.InstallHook(@TCustomFrame.Create, @THookedFrame.Create);
end;
procedure InitHook;
begin
if Initialized then
Exit;
Initialized := True;
HooksFormOnCreate := TDictionary<int64, TNotifyFormOnCreate>.Create;
HooksFormOnShow := TDictionary<int64, TNotifyFormOnShow>.Create;
HooksFrameCreate := TDictionary<int64, TNotifyFrameCreate>.Create;
PatchCreate;
end;
procedure FinalizeHooks;
begin
if not Initialized then
Exit;
Initialized := False;
FormDoCreate.DisableHook;
FormDoShow.DisableHook;
FrameCreate.DisableHook;
FreeAndNil(HooksFormOnCreate);
FreeAndNil(HooksFormOnShow);
FreeAndNil(HooksFrameCreate);
end;
procedure DisableAutoFinalization;
begin
AutoFinalizationDisabled := True;
end;
function RegHookFormOnCreate(AHandler: TNotifyFormOnCreate):Int64;
begin
InitHook;
inc(IdCounter);
Result := IdCounter;
HooksFormOnCreate.Add(Result, AHandler);
end;
function RegHookFormOnShow(AHandler: TNotifyFormOnShow):Int64;
begin
InitHook;
inc(IdCounter);
Result := IdCounter;
HooksFormOnShow.Add(Result, AHandler);
end;
function RegHookFrameCreate(AHandler: TNotifyFrameCreate):Int64;
begin
InitHook;
inc(IdCounter);
Result := IdCounter;
HooksFrameCreate.Add(Result, AHandler);
end;
function UnregHook(const AHookId: int64):Boolean;
begin
Result := False;
if not Initialized then
Exit;
if HooksFormOnCreate.ContainsKey(AHookId) then
begin
Result := True;
HooksFormOnCreate.Remove(AHookId);
end;
if HooksFormOnShow.ContainsKey(AHookId) then
begin
Result := True;
HooksFormOnShow.Remove(AHookId);
end;
if HooksFrameCreate.ContainsKey(AHookId) then
begin
Result := True;
HooksFrameCreate.Remove(AHookId);
end;
end;
{ THookedForm }
procedure THookedForm.HookedDoCreate;
var
h: TNotifyFormOnCreate;
begin
for h in HooksFormOnCreate.Values do
h(Self, True);
FormDoCreate.DisableHook;
try
DoCreate;
finally
FormDoCreate.EnableHook;
end;
for h in HooksFormOnCreate.Values do
h(Self, False);
end;
procedure THookedForm.HookedDoShow;
var
h: TNotifyFormOnShow;
begin
for h in HooksFormOnShow.Values do
h(Self, True);
FormDoShow.DisableHook;
try
DoShow;
finally
FormDoShow.EnableHook;
end;
for h in HooksFormOnShow.Values do
h(Self, False);
end;
{ THookedFrame }
constructor THookedFrame.Create(AOwner: TComponent);
var
h: TNotifyFrameCreate;
begin
for h in HooksFrameCreate.Values do
h(Self, True);
FrameCreate.DisableHook;
try
inherited Create(AOwner);
finally
FrameCreate.EnableHook;
end;
for h in HooksFrameCreate.Values do
h(Self, False);
end;
initialization
// we initialize hooks on first request
finalization
if not AutoFinalizationDisabled then
FinalizeHooks;
end.
|
UNIT myColors;
INTERFACE
USES math,myGenerics;
TYPE
T_colorChannel =(cc_red, cc_green, cc_blue, cc_alpha);
RGB_CHANNELS =cc_red..cc_blue;
T_rgbColor =array[RGB_CHANNELS ] of byte;
T_rgbaColor =array[T_colorChannel] of byte;
T_rgbFloatColor =array[RGB_CHANNELS ] of single;
T_rgbaFloatColor =array[T_colorChannel] of single;
T_hsvChannel =(hc_hue,hc_saturation,hc_value,hc_alpha);
HSV_CHANNELS =hc_hue..hc_value;
T_hsvColor =array[HSV_CHANNELS] of single;
T_hsvaColor =array[T_hsvChannel] of single;
CONST
SUBJECTIVE_GREY_RED_WEIGHT =0.2126;
SUBJECTIVE_GREY_GREEN_WEIGHT=0.7152;
SUBJECTIVE_GREY_BLUE_WEIGHT =0.0722;
NO_COLOR:T_rgbaFloatColor=(0,0,0,0);
RED :T_rgbFloatColor=(1,0,0);
GREEN :T_rgbFloatColor=(0,1,0);
BLUE :T_rgbFloatColor=(0,0,1);
CYAN :T_rgbFloatColor=(0,1,1);
YELLOW :T_rgbFloatColor=(1,1,0);
MAGENTA:T_rgbFloatColor=(1,0,1);
WHITE :T_rgbFloatColor=(1,1,1);
BLACK :T_rgbFloatColor=(0,0,0);
GREY :T_rgbFloatColor=(0.5,0.5,0.5);
FUNCTION rgbColor (CONST r,g,b :single):T_rgbFloatColor;
FUNCTION rgbaColor(CONST r,g,b,a:single):T_rgbaFloatColor;
FUNCTION hsvColor (CONST h,s,v :single):T_hsvColor;
FUNCTION hsvaColor(CONST h,s,v,a:single):T_hsvaColor;
OPERATOR :=(CONST x:T_rgbColor ):T_rgbaColor;
OPERATOR :=(CONST x:T_rgbFloatColor ):T_rgbaFloatColor;
OPERATOR :=(CONST x:T_rgbColor ):T_rgbFloatColor;
OPERATOR :=(CONST x:T_rgbaColor ):T_rgbaFloatColor;
FUNCTION projectedColor(CONST x:T_rgbFloatColor):T_rgbFloatColor;
OPERATOR :=( x:T_rgbFloatColor ):T_rgbColor;
OPERATOR :=(CONST x:T_rgbaFloatColor):T_rgbaColor;
OPERATOR :=(CONST x:T_hsvColor ):T_hsvaColor;
OPERATOR :=(CONST x:T_rgbFloatColor ):T_hsvColor;
OPERATOR :=(CONST x:T_rgbaFloatColor):T_hsvaColor;
OPERATOR :=( x:T_hsvColor ):T_rgbFloatColor;
OPERATOR :=(CONST x:T_hsvaColor ):T_rgbaFloatColor;
OPERATOR =(CONST x,y:T_rgbFloatColor ):boolean;
OPERATOR =(CONST x,y:T_rgbaFloatColor):boolean;
OPERATOR =(CONST x,y:T_hsvColor ):boolean;
OPERATOR =(CONST x,y:T_hsvaColor ):boolean;
OPERATOR +(CONST x,y:T_rgbFloatColor ):T_rgbFloatColor; inline;
OPERATOR +(CONST x,y:T_rgbaFloatColor):T_rgbaFloatColor;
OPERATOR -(CONST x,y:T_rgbFloatColor ):T_rgbFloatColor;
OPERATOR -(CONST x,y:T_rgbaFloatColor):T_rgbaFloatColor;
OPERATOR *(CONST x:T_rgbFloatColor ; CONST y:double):T_rgbFloatColor; inline;
OPERATOR *(CONST x:T_rgbaFloatColor; CONST y:double):T_rgbaFloatColor;
OPERATOR *(CONST x,y:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION blend(CONST below:T_rgbFloatColor; CONST atop:T_rgbaFloatColor):T_rgbFloatColor;
FUNCTION blend(CONST below,atop:T_rgbaFloatColor):T_rgbaFloatColor;
FUNCTION getOverbright(VAR x:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION tint (CONST c:T_hsvColor; CONST h:single):T_hsvColor; inline;
FUNCTION subjectiveGrey(CONST c:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION greyLevel (CONST c:T_rgbFloatColor):single; inline;
FUNCTION sepia (CONST c:T_rgbFloatColor):T_rgbFloatColor; inline;
FUNCTION gamma (CONST c:T_rgbFloatColor; CONST gR,gG,gB:single):T_rgbFloatColor;
FUNCTION gammaHSV (CONST c:T_hsvColor; CONST gH,gS,gV:single):T_hsvColor;
FUNCTION invert (CONST c:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION absCol (CONST c:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION calcErr (CONST c00,c01,c02,c10,c11,c12,c20,c21,c22:T_rgbFloatColor):double; inline;
FUNCTION colDiff (CONST x,y:T_rgbFloatColor):double;
FUNCTION subjectiveColDiff(CONST x,y:T_rgbFloatColor):double; inline;
FUNCTION innerProduct (CONST x,y:T_rgbFloatColor):double;
FUNCTION rgbMax (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline;
FUNCTION rgbMin (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline;
FUNCTION rgbDiv (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline;
FUNCTION rgbScreen(CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline;
FUNCTION hasNanOrInfiniteComponent(CONST c:T_rgbFloatColor):boolean;
FUNCTION simpleIlluminatedColor(CONST baseColor:T_rgbFloatColor; CONST nx,ny,nz:double):T_rgbFloatColor;
PROCEDURE averageIllumination(CONST borderAccrossFraction,borderUpFraction:double; OUT baseFraction,whiteFraction:double);
CONST HISTOGRAM_ADDITIONAL_SPREAD=128;
TYPE
T_histogram=object
private
isIncremental:boolean;
globalMin,globalMax:single;
bins:array [-HISTOGRAM_ADDITIONAL_SPREAD..255+HISTOGRAM_ADDITIONAL_SPREAD] of single;
PROCEDURE switch;
PROCEDURE incBin(CONST index:longint; CONST increment:single);
public
CONSTRUCTOR create;
CONSTRUCTOR createSmoothingKernel(CONST sigma:single);
DESTRUCTOR destroy;
PROCEDURE clear;
PROCEDURE putSample(CONST value:single; CONST weight:single=1);
PROCEDURE putSampleSmooth(CONST value:single; CONST weight:single=1);
PROCEDURE smoothen(CONST sigma:single);
PROCEDURE smoothen(CONST kernel:T_histogram);
FUNCTION percentile(CONST percent:single):single;
PROCEDURE getNormalizationParams(OUT offset,stretch:single);
FUNCTION median:single;
FUNCTION mightHaveOutOfBoundsValues:boolean;
FUNCTION mode:single;
PROCEDURE merge(CONST other:T_histogram; CONST weight:single);
FUNCTION lookup(CONST value:T_rgbFloatColor):T_rgbFloatColor;
FUNCTION lookup(CONST value:single):single;
FUNCTION sampleCount:longint;
end;
T_compoundHistogram=object
R,G,B:T_histogram;
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE putSample(CONST value:T_rgbFloatColor; CONST weight:single=1);
PROCEDURE putSampleSmooth(CONST value:T_rgbFloatColor; CONST weight:single=1);
PROCEDURE smoothen(CONST sigma:single);
PROCEDURE smoothen(CONST kernel:T_histogram);
FUNCTION subjectiveGreyHistogram:T_histogram;
FUNCTION sumHistorgram:T_histogram;
FUNCTION mightHaveOutOfBoundsValues:boolean;
PROCEDURE clear;
end;
T_colorList=array of T_rgbFloatColor;
T_intMapOfInt=specialize G_longintKeyMap<longint>;
T_colorTree=object
private
hist:T_intMapOfInt;
table:T_colorList;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE addSample(CONST c:T_rgbColor);
PROCEDURE finishSampling(CONST colors:longint);
PROPERTY colorTable:T_colorList read table;
FUNCTION getQuantizedColorIndex(CONST c:T_rgbFloatColor):longint;
FUNCTION getQuantizedColor(CONST c:T_rgbFloatColor):T_rgbFloatColor;
end;
IMPLEMENTATION
CONST by255=1/255;
FUNCTION rgbColor(CONST r,g,b:single):T_rgbFloatColor;
begin
result[cc_red ]:=r;
result[cc_green]:=g;
result[cc_blue ]:=b;
end;
FUNCTION rgbaColor(CONST r,g,b,a:single):T_rgbaFloatColor;
begin
result[cc_red ]:=r;
result[cc_green]:=g;
result[cc_blue ]:=b;
result[cc_alpha]:=a;
end;
FUNCTION hsvColor (CONST h,s,v :single):T_hsvColor;
begin
result[hc_hue ]:=h;
result[hc_saturation]:=s;
result[hc_value ]:=v;
end;
FUNCTION hsvaColor(CONST h,s,v,a:single):T_hsvaColor;
begin
result[hc_hue ]:=h;
result[hc_saturation]:=s;
result[hc_value ]:=v;
result[hc_alpha ]:=a;
end;
OPERATOR:=(CONST x: T_rgbColor ): T_rgbaColor; VAR c:T_colorChannel; begin initialize(result); for c in RGB_CHANNELS do result[c]:=x[c]; result[cc_alpha]:=255; end;
OPERATOR:=(CONST x: T_rgbFloatColor): T_rgbaFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in RGB_CHANNELS do result[c]:=x[c]; result[cc_alpha]:=1; end;
OPERATOR:=(CONST x: T_rgbColor ): T_rgbFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in RGB_CHANNELS do result[c]:=x[c]*by255; end;
OPERATOR:=(CONST x: T_rgbaColor ): T_rgbaFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in T_colorChannel do result[c]:=x[c]*by255; end;
FUNCTION projectedColor(CONST x:T_rgbFloatColor):T_rgbFloatColor;
VAR k1,k2,k3,j:T_colorChannel;
aid:single;
begin
result:=x;
for j in RGB_CHANNELS do if isNan(result[j]) or isInfinite(result[j]) then result[j]:=random;
if (result[cc_red ]<0) or (result[cc_red ]>1) or
(result[cc_green]<0) or (result[cc_green]>1) or
(result[cc_blue ]<0) or (result[cc_blue ]>1) then begin
k1:=cc_red; k2:=cc_green; k3:=cc_blue;
if result[k2]<result[k1] then begin j:=k2; k2:=k1; k1:=j; end;
if result[k3]<result[k1] then begin j:=k3; k3:=k1; k1:=j; end;
if result[k3]<result[k2] then begin j:=k3; k3:=k2; k2:=j; end;
//now we have result[k1]<=result[k2]<=result[k3]
if result[k1]<0 then begin //if darkest channel is underbright...
//distribute brightness:----//
aid:=0.5*(result[k1]); //
result[k1]:=0; //
result[k2]:=result[k2]+aid; //
result[k3]:=result[k3]+aid; //
//------:distribute brightness
if result[k2]<0 then begin //if originally second darkest channel is underbright...
result[k3]:=max(0,result[k3]+result[k2]);
result[k2]:=0;
end;
end; //if brightest channel is overbright...
if result[k3]>1 then begin //if brightest channel is overbright...
//distribute brightness:----//
aid:=0.5*(result[k3]-1); //
result[k3]:=1; //
result[k2]:=result[k2]+aid; //
result[k1]:=result[k1]+aid; //
//------:distribute brightness
if result[k2]>1 then begin //if originally second brightest channel is overbright...
result[k1]:=min(1,result[k1]+result[k2]-1);
result[k2]:=1;
end;
end; //if brightest channel is overbright...
//now we have 0<=result[i]<=1 for all channels i
for j in RGB_CHANNELS do if result[j]<0 then result[j]:=0;
end;
end;
OPERATOR:=(x: T_rgbFloatColor): T_rgbColor;
VAR c:T_colorChannel;
begin
initialize(result);
x:=projectedColor(x);
for c in RGB_CHANNELS do result[c]:=round(255*x[c]);
end;
OPERATOR:=(CONST x: T_rgbaFloatColor): T_rgbaColor;
VAR c:T_colorChannel;
begin
initialize(result);
for c in T_colorChannel do
if isNan(x[c]) or (x[c]<0) then result[c]:=0
else if x[c]>1 then result[c]:=255
else result[c]:=round(x[c]*255);
end;
OPERATOR :=(CONST x:T_hsvColor ):T_hsvaColor;
VAR c:T_hsvChannel;
begin
initialize(result);
for c in HSV_CHANNELS do result[c]:=x[c]; result[hc_alpha]:=1;
end;
OPERATOR :=(CONST x:T_rgbFloatColor ):T_hsvColor;
VAR brightChannel:T_colorChannel;
begin
initialize(result);
if x[cc_red]>x[cc_green] then begin result[hc_value]:=x[cc_red]; brightChannel:=cc_red ; end
else begin result[hc_value]:=x[cc_green]; brightChannel:=cc_green; end;
if x[cc_blue]>result[hc_value] then begin result[hc_value]:=x[cc_blue]; brightChannel:=cc_blue ; end;
//result[hc_value] now holds the brightest component of x
if x[cc_red]<x[cc_green] then result[hc_saturation]:=x[cc_red]
else result[hc_saturation]:=x[cc_green];
if x[cc_blue]<result[hc_saturation] then result[hc_saturation]:=x[cc_blue];
if result[hc_saturation]=result[hc_value] then brightChannel:=cc_alpha;
//result[hc_saturation] now holds the darkest component of x
case brightChannel of
cc_red : result[hc_hue]:=( (x[cc_green]-x[cc_blue ])/(result[hc_value]-result[hc_saturation]))/6;
cc_green: result[hc_hue]:=(2+(x[cc_blue ]-x[cc_red ])/(result[hc_value]-result[hc_saturation]))/6;
cc_blue : result[hc_hue]:=(4+(x[cc_red ]-x[cc_green])/(result[hc_value]-result[hc_saturation]))/6;
cc_alpha: result[hc_hue]:=0;
end;
if brightChannel=cc_alpha then result[hc_saturation]:=0
else result[hc_saturation]:=(result[hc_value]-result[hc_saturation])/result[hc_value];
while result[hc_hue]<0 do result[hc_hue]:=result[hc_hue]+1;
while result[hc_hue]>1 do result[hc_hue]:=result[hc_hue]-1;
end;
OPERATOR :=(CONST x:T_rgbaFloatColor):T_hsvaColor;
VAR tmp:T_rgbFloatColor;
c:T_colorChannel;
begin
initialize(tmp);
for c in RGB_CHANNELS do tmp[c]:=x[c];
result:=T_hsvColor(tmp);
result[hc_alpha]:=x[cc_alpha];
end;
OPERATOR :=( x:T_hsvColor ):T_rgbFloatColor;
VAR hi:byte;
p,q,t:single;
begin
initialize(result);
if isInfinite(x[hc_hue]) or isNan(x[hc_hue]) then exit(rgbColor(random,random,random));
if x[hc_hue]>1 then x[hc_hue]:=frac(x[hc_hue])
else if x[hc_hue]<0 then x[hc_hue]:=1+frac(x[hc_hue]);
while x[hc_hue]<0 do x[hc_hue]:=x[hc_hue]+1;
while x[hc_hue]>1 do x[hc_hue]:=x[hc_hue]-1;
hi:=trunc(x[hc_hue]*6); x[hc_hue]:=x[hc_hue]*6-hi;
p:=x[hc_value]*(1-x[hc_saturation] );
q:=x[hc_value]*(1-x[hc_saturation]* x[hc_hue] );
t:=x[hc_value]*(1-x[hc_saturation]*(1-x[hc_hue]));
case hi of
1 : result:=rgbColor(q,x[hc_value],p);
2 : result:=rgbColor(p,x[hc_value],t);
3 : result:=rgbColor(p,q,x[hc_value]);
4 : result:=rgbColor(t,p,x[hc_value]);
5 : result:=rgbColor(x[hc_value],p,q);
else result:=rgbColor(x[hc_value],t,p);
end;
end;
OPERATOR :=(CONST x:T_hsvaColor ):T_rgbaFloatColor;
VAR tmp:T_hsvColor;
c:T_hsvChannel;
begin
initialize(tmp);
for c in HSV_CHANNELS do tmp[c]:=x[c];
result:=T_rgbFloatColor(tmp);
result[cc_alpha]:=x[hc_alpha];
end;
OPERATOR =(CONST x,y:T_rgbFloatColor ):boolean; VAR c:T_colorChannel; begin for c in RGB_CHANNELS do if x[c]<>y[c] then exit(false); result:=true; end;
OPERATOR =(CONST x,y:T_rgbaFloatColor):boolean; VAR c:T_colorChannel; begin for c in T_colorChannel do if x[c]<>y[c] then exit(false); result:=true; end;
OPERATOR =(CONST x,y:T_hsvColor ):boolean; VAR c:T_hsvChannel; begin for c in HSV_CHANNELS do if x[c]<>y[c] then exit(false); result:=true; end;
OPERATOR =(CONST x,y:T_hsvaColor ):boolean; VAR c:T_hsvChannel; begin for c in T_hsvChannel do if x[c]<>y[c] then exit(false); result:=true; end;
OPERATOR+(CONST x, y: T_rgbFloatColor ): T_rgbFloatColor;
begin
result[cc_red ]:=x[cc_red ]+y[cc_red ];
result[cc_green]:=x[cc_green]+y[cc_green];
result[cc_blue ]:=x[cc_blue ]+y[cc_blue ];
end;
OPERATOR+(CONST x, y: T_rgbaFloatColor): T_rgbaFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in T_colorChannel do result[c]:=x[c]+y[c]; end;
OPERATOR-(CONST x, y: T_rgbFloatColor ): T_rgbFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in RGB_CHANNELS do result[c]:=x[c]-y[c]; end;
OPERATOR-(CONST x, y: T_rgbaFloatColor): T_rgbaFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in T_colorChannel do result[c]:=x[c]-y[c]; end;
OPERATOR *(CONST x: T_rgbFloatColor; CONST y: double): T_rgbFloatColor;
begin
result[cc_red ]:=x[cc_red ]*y;
result[cc_green]:=x[cc_green]*y;
result[cc_blue ]:=x[cc_blue ]*y;
end;
OPERATOR *(CONST x: T_rgbaFloatColor; CONST y: double): T_rgbaFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in T_colorChannel do result[c]:=x[c]*y; end;
OPERATOR *(CONST x,y:T_rgbFloatColor ): T_rgbFloatColor; VAR c:T_colorChannel; begin initialize(result); for c in RGB_CHANNELS do result[c]:=x[c]*y[c]; end;
FUNCTION blend(CONST below: T_rgbFloatColor; CONST atop: T_rgbaFloatColor): T_rgbFloatColor;
VAR BF:single;
c:T_colorChannel;
begin
initialize(result);
BF:=1-atop[cc_alpha];
for c in RGB_CHANNELS do result[c]:=atop[c]*atop[cc_alpha]+below[c]*BF;
end;
FUNCTION blend(CONST below, atop: T_rgbaFloatColor): T_rgbaFloatColor;
VAR af,BF:single;
c:T_colorChannel;
begin
initialize(result);
af:= atop [cc_alpha];
BF:=(1-af)*below[cc_alpha];
result[cc_alpha]:=af+BF;
af:=af/result[cc_alpha];
BF:=BF/result[cc_alpha];
for c in RGB_CHANNELS do result[c]:=atop[c]*af+below[c]*BF;
end;
FUNCTION getOverbright(VAR x:T_rgbFloatColor):T_rgbFloatColor;
VAR b:single;
begin
initialize(result);
if x[cc_red]>x[cc_green] then b:=x[cc_red] //find brightest channel
else b:=x[cc_green];
if x[cc_blue]>b then b:=x[cc_blue];
if b<1.002 then result:=BLACK else begin //if brightest channel is darker than 1, there is no overbrightness
result:=x*(1-1/b); //else result is
x :=x-result;
end;
if x[cc_red ]<0 then x[cc_red ]:=0;
if x[cc_green]<0 then x[cc_green]:=0;
if x[cc_blue ]<0 then x[cc_blue ]:=0;
end;
FUNCTION tint(CONST c:T_hsvColor; CONST h:single):T_hsvColor;
begin
result:=c;
result[hc_hue]:=h;
end;
FUNCTION subjectiveGrey(CONST c:T_rgbFloatColor):T_rgbFloatColor; inline;
begin
result:=WHITE*greyLevel(c);
end;
FUNCTION greyLevel(CONST c:T_rgbFloatColor):single;
begin
result:=SUBJECTIVE_GREY_RED_WEIGHT *c[cc_red]+
SUBJECTIVE_GREY_GREEN_WEIGHT*c[cc_green]+
SUBJECTIVE_GREY_BLUE_WEIGHT *c[cc_blue];
end;
{local} FUNCTION safeGamma(CONST x,gamma:single):single; inline;
begin
if x> 1E-4 then result:= exp(ln( x)*gamma)
else if x<-1E-4 then result:=-exp(ln(-x)*gamma)
else result:=x;
end;
FUNCTION sepia(CONST c:T_rgbFloatColor):T_rgbFloatColor; inline;
begin
result[cc_red ]:=safeGamma(c[cc_red],0.5);
result[cc_green]:=c[cc_green];
result[cc_blue ]:=sqr(c[cc_blue]);
end;
FUNCTION gamma(CONST c:T_rgbFloatColor; CONST gR,gG,gB:single):T_rgbFloatColor; inline;
begin
result[cc_red ]:=safeGamma(c[cc_red ],gR);
result[cc_green]:=safeGamma(c[cc_green],gG);
result[cc_blue ]:=safeGamma(c[cc_blue ],gB);
end;
FUNCTION gammaHSV(CONST c:T_hsvColor; CONST gH,gS,gV:single):T_hsvColor; inline;
begin
result[hc_hue ]:=safeGamma(c[hc_hue ],gH);
result[hc_saturation]:=safeGamma(c[hc_saturation],gS);
result[hc_value ]:=safeGamma(c[hc_value ],gV);
end;
FUNCTION invert(CONST c:T_rgbFloatColor):T_rgbFloatColor;
begin
result:=WHITE-c;
end;
FUNCTION absCol(CONST c:T_rgbFloatColor):T_rgbFloatColor;
VAR i:T_colorChannel;
begin
initialize(result);
for i in RGB_CHANNELS do if c[i]<0 then result[i]:=-c[i] else result[i]:=c[i];
end;
FUNCTION calcErr(CONST c00,c01,c02,c10,c11,c12,c20,c21,c22:T_rgbFloatColor):double; inline;
VAR a0,a1,b0,b1:T_rgbFloatColor;
begin
a0:=c11-(c01+c21)*0.5;
a1:=c11-(c10+c12)*0.5;
b0:=c11-(c00+c22)*0.5;
b1:=c11-(c20+c02)*0.5;
result:=(a0[cc_red]*a0[cc_red]+a0[cc_green]*a0[cc_green]+a0[cc_blue]*a0[cc_blue]+
a1[cc_red]*a1[cc_red]+a1[cc_green]*a1[cc_green]+a1[cc_blue]*a1[cc_blue])*3+
(b0[cc_red]*b0[cc_red]+b0[cc_green]*b0[cc_green]+b0[cc_blue]*b0[cc_blue]+
b1[cc_red]*b1[cc_red]+b1[cc_green]*b1[cc_green]+b1[cc_blue]*b1[cc_blue])*1.5;
end;
FUNCTION colDiff(CONST x,y:T_rgbFloatColor):double;
begin
result:=(sqr(x[cc_red ]-y[cc_red ])+
sqr(x[cc_green]-y[cc_green])+
sqr(x[cc_blue ]-y[cc_blue ]));
end;
FUNCTION subjectiveColDiff(CONST x,y:T_rgbFloatColor):double; inline;
VAR dr,dg,db:double;
begin
dr:=x[cc_red] -y[cc_red];
dg:=x[cc_green]-y[cc_green];
db:=x[cc_blue] -y[cc_blue];
result:=sqr(dr*0.49 +dg*0.31 +db*0.2 )+
sqr(dr*0.17697+dg*0.8124+db*0.01063)+
sqr( dg*0.01 +db*0.99 );
end;
FUNCTION innerProduct (CONST x,y:T_rgbFloatColor):double;
VAR i:T_colorChannel;
begin
result:=0;
for i in RGB_CHANNELS do result+=x[i]*y[i];
end;
FUNCTION rgbMax (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline; VAR i:T_colorChannel; begin initialize(result); for i in RGB_CHANNELS do if a[i]>b[i] then result[i]:=a[i] else result[i]:=b[i]; end;
FUNCTION rgbMin (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline; VAR i:T_colorChannel; begin initialize(result); for i in RGB_CHANNELS do if a[i]<b[i] then result[i]:=a[i] else result[i]:=b[i]; end;
FUNCTION rgbDiv (CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline; VAR i:T_colorChannel; begin initialize(result); for i in RGB_CHANNELS do result[i]:=a[i]/b[i]; end;
FUNCTION rgbScreen(CONST a,b:T_rgbFloatColor):T_rgbFloatColor; inline; VAR i:T_colorChannel; begin initialize(result); for i in RGB_CHANNELS do result[i]:=1-(1-a[i])*(1-b[i]); end;
FUNCTION hasNanOrInfiniteComponent(CONST c:T_rgbFloatColor):boolean;
VAR i:T_colorChannel;
begin
for i in RGB_CHANNELS do if isNan(c[i]) or isInfinite(c[i]) then exit(true);
result:=false;
end;
FUNCTION simpleIlluminatedColor(CONST baseColor:T_rgbFloatColor; CONST nx,ny,nz:double):T_rgbFloatColor;
CONST lx=-1/4;
ly=-1/2;
lz= 1;
whiteFactor=6.866060555964674;
VAR illumination:double;
begin
illumination:=nx*lx+ny*ly+nz*lz;
if illumination<0 then result:=BLACK
else if illumination<1 then result:=baseColor*illumination
else if illumination<1.14564392373896 then begin
illumination:=whiteFactor*(illumination-1);
result:=baseColor*(1-illumination)+WHITE*illumination;
end else result:=BLACK;
end;
PROCEDURE averageIllumination(CONST borderAccrossFraction,borderUpFraction:double; OUT baseFraction,whiteFraction:double);
CONST lx=-1/4;
ly=-1/2;
lz= 1;
whiteFactor=6.866060555964674;
VAR illumination:double;
alpha:double;
k:longint;
begin
baseFraction:=0;
whiteFraction:=0;
for k:=0 to 999 do begin
alpha:=k*2*pi/1000;
illumination:=borderAccrossFraction*(cos(alpha)*lx+sin(alpha)*ly)+borderUpFraction*lz;
if illumination<0 then begin end
else if illumination<1 then baseFraction+=illumination*1E-3
else if illumination<1.14564392373896 then begin
illumination:=whiteFactor*(illumination-1);
baseFraction+=(1-illumination)*1E-3;
whiteFraction+=illumination *1E-3;
end;
end;
end;
PROCEDURE T_histogram.switch;
VAR i:longint;
begin
if isIncremental then begin
for i:=high(bins) downto low(bins)+1 do bins[i]:=bins[i]-bins[i-1];
end else begin
for i:=low(bins)+1 to high(bins) do bins[i]:=bins[i]+bins[i-1];
end;
isIncremental:=not(isIncremental);
end;
CONSTRUCTOR T_histogram.create;
begin
clear;
end;
CONSTRUCTOR T_histogram.createSmoothingKernel(CONST sigma: single);
VAR i:longint;
s:double;
begin
clear;
if sigma<1E-3 then s:=1E3 else s:=1/sigma;
for i:=-HISTOGRAM_ADDITIONAL_SPREAD to HISTOGRAM_ADDITIONAL_SPREAD do bins[i]:=exp(-sqr(i*s));
end;
DESTRUCTOR T_histogram.destroy;
begin end;//Pro forma destructor
PROCEDURE T_histogram.clear;
VAR i:longint;
begin
isIncremental:=false;
globalMax:=-infinity;
globalMin:= infinity;
for i:=low(bins) to high(bins) do bins[i]:=0;
end;
PROCEDURE T_histogram.incBin(CONST index: longint; CONST increment: single);
VAR i:longint;
begin
if index<low (bins) then i:=low(bins)
else if index>high(bins) then i:=high(bins)
else i:=index;
bins[i]:=bins[i]+increment;
end;
PROCEDURE T_histogram.putSample(CONST value: single; CONST weight: single);
begin
if isIncremental then switch;
if isNan(value) or isInfinite(value) then exit;
globalMax:=max(globalMax,value);
globalMin:=min(globalMin,value);
incBin(round(max(min(value,8E6),-8E6)*255),weight);
end;
PROCEDURE T_histogram.putSampleSmooth(CONST value: single; CONST weight: single);
VAR i:longint;
begin
if isIncremental then switch;
if isNan(value) or isInfinite(value) then exit;
if value<-1 then i:=-255
else if value> 2 then i:=510
else i:=round(value*255);
incBin(i-1,weight*0.25);
incBin(i ,weight*0.5 );
incBin(i+1,weight*0.25);
end;
PROCEDURE T_histogram.smoothen(CONST sigma: single);
VAR kernel:T_histogram;
begin
if isIncremental then switch;
kernel.createSmoothingKernel(sigma);
smoothen(kernel);
kernel.destroy;
end;
PROCEDURE T_histogram.smoothen(CONST kernel: T_histogram);
VAR temp:T_histogram;
i,j:longint;
sum1,sum2:double;
begin
if isIncremental then switch;
temp.create;
for i:=low(bins) to high(bins)-1 do begin
sum1:=0;
sum2:=0;
for j:=-HISTOGRAM_ADDITIONAL_SPREAD to HISTOGRAM_ADDITIONAL_SPREAD do if (i+j>=low(bins)) and (i+j<high(bins)) then begin
sum1:=sum1+kernel.bins[abs(j)]*bins[i+j];
sum2:=sum2+kernel.bins[abs(j)];
end;
temp.bins[i]:=sum1/sum2;
end;
for i:=low(bins) to high(bins)-1 do bins[i]:=temp.bins[i];
temp.destroy;
end;
FUNCTION T_histogram.percentile(CONST percent: single): single;
VAR absVal:single;
i:longint;
begin
if not(isIncremental) then switch;
absVal:=percent/100*bins[high(bins)];
if bins[low(bins)]>absVal then exit(low(bins)/255);
for i:=low(bins)+1 to high(bins) do if (bins[i-1]<=absVal) and (bins[i]>absVal) then exit((i+(absVal-bins[i-1])/(bins[i]-bins[i-1]))/255);
result:=high(bins)/255;
end;
PROCEDURE T_histogram.getNormalizationParams(OUT offset, stretch: single);
VAR absVal0,absVal1:single;
bin0:longint=low(bins);
bin1:longint=low(bins);
i:longint;
begin
if not(isIncremental) then switch;
absVal0:=0.001*bins[high(bins)];
absVal1:=0.999*bins[high(bins)];
for i:=low(bins)+1 to high(bins) do begin
if (bins[i-1]<=absVal0) and (bins[i]>absVal0) then bin0:=i;
if (bins[i-1]<=absVal1) and (bins[i]>absVal1) then bin1:=i;
end;
if bin0<=low (bins) then offset :=globalMin
else if bin0>=high(bins) then offset :=globalMax
else offset :=(bin0+(absVal0-bins[bin0-1])/(bins[bin0]-bins[bin0-1]))/255;
if bin1<=low (bins) then stretch:=globalMin
else if bin1>=high(bins) then stretch:=globalMax
else stretch:=(bin1+(absVal1-bins[bin1-1])/(bins[bin1]-bins[bin1-1]))/255;
if (stretch-offset)>1E-20
then stretch:=1/(stretch-offset)
else stretch:=1;
end;
FUNCTION T_histogram.median: single;
begin
result:=percentile(50);
end;
FUNCTION T_histogram.mightHaveOutOfBoundsValues: boolean;
begin
if (isIncremental) then switch;
result:=(bins[low(bins)]>0) or (bins[high(bins)]>0);
end;
FUNCTION T_histogram.mode: single;
VAR i:longint;
ir:longint=low(bins);
begin
if isIncremental then switch;
for i:=low(bins)+1 to high(bins) do if bins[i]>bins[ir] then ir:=i;
result:=ir/255;
end;
PROCEDURE T_histogram.merge(CONST other: T_histogram; CONST weight: single);
VAR i:longint;
begin
if isIncremental then switch;
if other.isIncremental then switch;
for i:=low(bins) to high(bins) do bins[i]:=bins[i]+other.bins[i]*weight;
end;
FUNCTION T_histogram.lookup(CONST value: T_rgbFloatColor): T_rgbFloatColor;
VAR i:longint;
c:T_colorChannel;
begin
initialize(result);
if not(isIncremental) then switch;
for c in RGB_CHANNELS do begin
i:=round(255*value[c]);
if i<low(bins) then i:=low(bins) else if i>high(bins) then i:=high(bins);
result[c]:=bins[i];
end;
result:=result*(1/bins[high(bins)]);
end;
FUNCTION T_histogram.lookup(CONST value: single): single;
VAR i:longint;
begin
if not(isIncremental) then switch;
i:=round(255*value);
if i<low(bins) then i:=low(bins) else if i>high(bins) then i:=high(bins);
result:=bins[i]*(1/bins[high(bins)]);
end;
FUNCTION T_histogram.sampleCount: longint;
begin
if not(isIncremental) then switch;
result:=round(bins[high(bins)]);
end;
CONSTRUCTOR T_compoundHistogram.create;
begin
r.create;
g.create;
b.create;
end;
DESTRUCTOR T_compoundHistogram.destroy;
begin
r.destroy;
g.destroy;
b.destroy;
end;
PROCEDURE T_compoundHistogram.putSample(CONST value: T_rgbFloatColor;
CONST weight: single);
begin
r.putSample(value[cc_red],weight);
g.putSample(value[cc_green],weight);
b.putSample(value[cc_blue],weight);
end;
PROCEDURE T_compoundHistogram.putSampleSmooth(CONST value: T_rgbFloatColor;
CONST weight: single);
begin
r.putSampleSmooth(value[cc_red],weight);
g.putSampleSmooth(value[cc_green],weight);
b.putSampleSmooth(value[cc_blue],weight);
end;
PROCEDURE T_compoundHistogram.smoothen(CONST sigma: single);
VAR kernel:T_histogram;
begin
kernel.createSmoothingKernel(sigma);
smoothen(kernel);
kernel.destroy;
end;
PROCEDURE T_compoundHistogram.smoothen(CONST kernel: T_histogram);
begin
r.smoothen(kernel);
g.smoothen(kernel);
b.smoothen(kernel);
end;
FUNCTION T_compoundHistogram.subjectiveGreyHistogram: T_histogram;
begin
result.create;
result.merge(r,SUBJECTIVE_GREY_RED_WEIGHT);
result.merge(g,SUBJECTIVE_GREY_GREEN_WEIGHT);
result.merge(b,SUBJECTIVE_GREY_BLUE_WEIGHT);
end;
FUNCTION T_compoundHistogram.sumHistorgram: T_histogram;
begin
result.create;
result.merge(r,1/3);
result.merge(g,1/3);
result.merge(b,1/3);
end;
FUNCTION T_compoundHistogram.mightHaveOutOfBoundsValues: boolean;
begin
result:=r.mightHaveOutOfBoundsValues or
g.mightHaveOutOfBoundsValues or
b.mightHaveOutOfBoundsValues;
end;
PROCEDURE T_compoundHistogram.clear;
begin
r.clear;
g.clear;
b.clear;
end;
CONSTRUCTOR T_colorTree.create;
begin
hist.create;
end;
DESTRUCTOR T_colorTree.destroy;
begin
hist.destroy;
setLength(table,0);
end;
PROCEDURE T_colorTree.addSample(CONST c: T_rgbColor);
VAR key:longint=0;
count:longint;
begin
move(c,key,3);
if hist.containsKey(key,count)
then inc(count)
else count:=1;
hist.put(key,count+1);
end;
PROCEDURE T_colorTree.finishSampling(CONST colors: longint);
TYPE T_countedSample=record
color:T_rgbFloatColor;
count:longint;
end;
FUNCTION colorFromIndex(CONST index:longint):T_rgbFloatColor;
VAR c24:T_rgbColor;
begin
initialize(c24);
move(index,c24,3);
result:=c24;
end;
FUNCTION fidelity(CONST entry:T_countedSample):double;
VAR i:longint;
dist:double;
begin
result:=1E50;
for i:=0 to length(table)-1 do begin
dist:=colDiff(entry.color,table[i]);
if dist<result then result:=dist;
end;
result:=result*entry.count;
end;
VAR i,k:longint;
digest:array of T_countedSample;
histEntry:T_intMapOfInt.KEY_VALUE_LIST;
best,
next:T_countedSample;
bestFid,
nextFid:double;
begin
histEntry:=hist.entrySet;
setLength(digest,0);
for i:=0 to length(histEntry)-1 do begin
if histEntry[i].value>=16 then begin
setLength(digest,length(digest)+1);
digest[length(digest)-1].color:=colorFromIndex(histEntry[i].key);
digest[length(digest)-1].count:=histEntry[i].value;
end;
end;
hist.destroy;
hist.create;
best:=digest[0];
for i:=1 to length(digest)-1 do begin
next:=digest[i];
if next.count>best.count then best:=next;
end;
setLength(table,1);
table[0]:=best.color;
for k:=1 to colors-1 do begin
best:=digest[0];
bestFid:=fidelity(best);
for i:=1 to length(digest)-1 do begin
next:=digest[i];
nextFid:=fidelity(next);
if nextFid>bestFid then begin
best :=next;
bestFid:=nextFid;
end;
end;
setLength(table,k+1);
table[k]:=best.color;
end;
end;
FUNCTION T_colorTree.getQuantizedColorIndex(CONST c: T_rgbFloatColor): longint;
VAR newDist,dist1:double;
i:longint;
begin
dist1:=colDiff(c,table[0]); result:=0;
for i:=1 to length(table)-1 do begin
newDist:=colDiff(c,table[i]);
if newDist<dist1 then begin dist1:=newDist; result:=i; end;
end;
end;
FUNCTION T_colorTree.getQuantizedColor(CONST c: T_rgbFloatColor): T_rgbFloatColor;
VAR newDist,dist1:double;
i:longint;
begin
dist1:=colDiff(c,table[0]); result:=table[0];
for i:=1 to length(table)-1 do begin
newDist:=colDiff(c,table[i]);
if newDist<dist1 then begin dist1:=newDist; result:=table[i]; end;
end;
end;
end.
|
unit CacheProp;
interface
uses
sysutils,
classes,
DB,
Variants,
TypInfo;
type
IntPtr = ^Longint;
CharPtr = ^Char;
FloatPtr = ^Extended;
VariantPtr = ^Variant;
StringPtr = ^String;
Int64Ptr = ^Int64;
PCachePropItem = ^TCachePropItem;
TCachePropItem = record
pcPropInfo : PPropInfo;
pcValor : Pointer;
end;
TCPWriter = class ( TWriter )
public
procedure WriteVariant(Value: Variant);
end;
TCPReader = class ( TReader )
public
function ReadVariant: Variant;
end;
TCacheProp = class
private
FObj: TObject;
FItens : TList;
FPropertiesAlteradas: String;
function NovoItem(PI: PPropInfo): PCachePropItem;
function GetItem(PI: PPropInfo): PCachePropItem;
procedure LePropItem(PI: PPropInfo);
procedure ReverteItem(Item: PCachePropItem);
procedure LePropField(PI: PPropInfo; F: TField);
procedure SalvaPropField(PI: PPropInfo; F: TField);
procedure GravaItemStream(W: TCPWriter; PI: PPropInfo; SoAlterados: Boolean);
procedure LeItemStream(R: TCPReader; PI: PPropInfo);
function AlterouItem(PI: PPropInfo): Boolean;
procedure AssignProp(PI: PPropInfo; ObjFonte: TObject);
public
constructor Create(aObj: TObject);
destructor Destroy; override;
procedure LeProps; // Salva valores das propriedades no cache
procedure Reverte; // Salva valores em cache para propriedades
procedure Limpa;
function AlterouPropItem(Item: PCachePropItem): Boolean;
function Alterou: Boolean;
procedure SalvaStream(S: TStream; SoAlterados: Boolean);
procedure SalvaWriter(W: TCPWriter; SoAlterados: Boolean);
procedure LeStream(S: TStream);
procedure LeReader(R: TCPReader; S: TStream);
procedure SalvaDataset(Tab: TDataset);
procedure LeDataset(Tab: TDataset);
procedure Assign(ObjFonte: TObject);
property PropertiesAlteradas: String
read FPropertiesAlteradas;
end;
const
TiposValidos : TTypeKinds =
[tkInteger, tkEnumeration, tkChar, tkFloat, tkString, tkLString, tkWString, tkVariant, tkInt64{$ifdef ver300}, tkUString{$endif}];
implementation
uses ncDebug;
{ TCacheProp }
procedure DisposePropItem(Item : PCachePropItem);
begin
with Item^ do
case pcPropInfo^.PropType^^.Kind of
tkInteger: Dispose(IntPtr(pcValor));
tkEnumeration : Dispose(IntPtr(pcValor));
tkChar: Dispose(CharPtr(pcValor));
tkFloat: Dispose(FloatPtr(pcValor));
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}: Dispose(StringPtr(pcValor));
tkVariant: Dispose(VariantPtr(pcValor));
tkInt64: Dispose(Int64Ptr(pcValor));
end;
Dispose(Item);
end;
constructor TCacheProp.Create(aObj: TObject);
begin
FObj := aObj;
FItens := TList.Create;
FPropertiesAlteradas := '';
end;
destructor TCacheProp.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TCacheProp.GetItem(PI: PPropInfo): PCachePropItem;
var I : Integer;
begin
for I := 0 to pred(FItens.Count) do begin
Result := FItens[I];
if Result^.pcPropInfo = PI then Exit;
end;
Result := nil;
end;
procedure SetStringValue(var S: String; V: String);
begin
S := V;
V := V + V;
end;
procedure TCacheProp.LePropItem(PI: PPropInfo);
var Item : PCachePropItem;
begin
with PI^, PropType^^ do
if (Kind in TiposValidos) and (GetProc <> nil) then
begin
Item := GetItem(PI);
if (Item=nil) then Item := NovoItem(PI);
if Item <> nil then with Item^ do
case Kind of
tkInteger : IntPtr(pcValor)^ := GetOrdProp(FObj, PI);
tkEnumeration : IntPtr(pcValor)^ := GetOrdProp(FObj, PI);
tkChar: CharPtr(pcValor)^ := Chr(GetOrdProp(FObj, PI));
tkFloat: FloatPtr(pcValor)^ := GetFloatProp(FObj, PI);
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}:
SetStringValue(StringPtr(pcValor)^, GetStrProp(FObj, PI));
tkVariant: VariantPtr(pcValor)^ := GetVariantProp(FObj, PI);
tkInt64: Int64Ptr(pcValor)^ := GetInt64Prop(FObj, PI);
end;
end;
end;
procedure TCacheProp.ReverteItem(Item: PCachePropItem);
begin
with Item^ do
case pcPropInfo^.PropType^^.Kind of
tkInteger: SetOrdProp(FObj, pcPropInfo, IntPtr(pcValor)^);
tkEnumeration: SetOrdProp(FObj, pcPropInfo, IntPtr(pcValor)^);
tkChar: SetOrdProp(FObj, pcPropInfo, Ord(CharPtr(pcValor)^));
tkFloat: SetFloatProp(FObj, pcPropInfo, FloatPtr(pcValor)^);
tkString, tkLString, tkWString{$ifdef ver3000}, tkUString{$endif}: SetStrProp(FObj, pcPropInfo, StringPtr(pcValor)^);
tkVariant: SetVariantProp(FObj, pcPropInfo, VariantPtr(pcValor)^);
tkInt64: SetInt64Prop(FObj, pcPropInfo, Int64Ptr(pcValor)^);
end;
end;
function TCacheProp.AlterouItem(PI: PPropInfo): Boolean;
var Item : PCachePropItem;
begin
Item := GetItem(PI);
Result := (Item=nil) or AlterouPropItem(Item);
end;
function TCacheProp.AlterouPropItem(Item: PCachePropItem): Boolean;
var I : Integer;
function CompIntProp: Boolean;
begin
Result := (IntPtr(Item^.pcValor)^ <> GetOrdProp(FObj, Item^.pcPropInfo));
Inc(I);
end;
function CompCharProp: Boolean;
begin
Result := (CharPtr(Item^.pcValor)^ <> Chr(GetOrdProp(FObj, Item^.pcPropInfo)));
Inc(I);
end;
function CompFloatProp: Boolean;
begin
Result := (FloatPtr(Item^.pcValor)^ <> GetFloatProp(FObj, Item^.pcPropInfo));
Inc(I);
end;
function CompInt64Prop: Boolean;
begin
Result := (Int64Ptr(Item^.pcValor)^ <> GetInt64Prop(FObj, Item^.pcPropInfo));
Inc(I);
end;
function CompStrProp: Boolean;
begin
Result := (StringPtr(Item^.pcValor)^ <> GetStrProp(FObj, Item^.pcPropInfo));
Inc(I);
end;
function CompVariantProp: Boolean;
begin
Result := (VariantPtr(Item^.pcValor)^ <> GetVariantProp(FObj, Item^.pcPropInfo));
Inc(I);
end;
begin
Result := True;
case Item^.pcPropInfo^.PropType^^.Kind of
tkEnumeration,
tkInteger: Result := CompIntProp;
tkChar: Result := CompCharProp;
tkFloat: Result := CompFloatProp;
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}: Result := CompStrProp;
tkVariant: Result := CompVariantProp;
tkInt64: Result := CompInt64Prop;
end;
end;
procedure TCacheProp.LeProps;
var
I, Count: Integer;
PropInfo: PPropInfo;
PropList: PPropList;
begin
if FObj.ClassInfo=nil then
// Para conter ClassInfo classe tem que ser compilada com $M+
Exit;
Count := GetTypeData(FObj.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropInfos(FObj.ClassInfo, PropList);
for I := 0 to Count - 1 do
begin
PropInfo := PropList^[I];
if PropInfo = nil then break;
if IsStoredProp(FObj, PropInfo) then
LePropItem(PropInfo);
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end;
function TCacheProp.NovoItem(PI: PPropInfo): PCachePropItem;
begin
New(Result);
Result^.pcPropInfo := PI;
FItens.Add(Result);
with Result^ do
case pcPropInfo^.PropType^^.Kind of
tkEnumeration,
tkInteger: New(IntPtr(pcValor));
tkChar: New(CharPtr(pcValor));
tkFloat: New(FloatPtr(pcValor));
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}: New(StringPtr(pcValor));
tkVariant: New(VariantPtr(pcValor));
tkInt64: New(Int64Ptr(pcValor));
end;
end;
function TCacheProp.Alterou: Boolean;
var I : Integer;
begin
Result := True;
for I := 0 to pred(FItens.Count) do
if AlterouPropItem(PCachePropItem(FItens[I])) then
Exit;
Result := False;
end;
procedure TCacheProp.Reverte;
var I : Integer;
begin
for I := 0 to pred(FItens.Count) do
ReverteItem(PCachePropItem(FItens[I]));
FPropertiesAlteradas := '';
end;
procedure TCacheProp.Limpa;
begin
while FItens.Count > 0 do begin
DisposePropItem(PCachePropItem(FItens[0]));
FItens.Delete(0);
end;
FPropertiesAlteradas := '';
end;
procedure TCacheProp.SalvaStream(S: TStream; SoAlterados: Boolean);
var W: TCPWriter;
begin
try
W := TCPWriter.Create(S, 4096);
try
SalvaWriter(W, SoAlterados);
finally
W.Free;
end;
except
on E: Exception do
raise Exception.Create('TCacheProp.SalvaStream - Exception: ' + E.Message);
end;
end;
procedure TCacheProp.SalvaWriter(W: TCPWriter; SoAlterados: Boolean);
var
I, Count: Integer;
PropInfo: PPropInfo;
PropList: PPropList;
S : String;
begin
if FObj.ClassInfo=nil then
// Para conter ClassInfo classe tem que ser compilada com $M+
Raise Exception.Create('TCacheProp.SalvaWriter - Exception: FObj.ClassInfo=nil');
S := '';
try
S := '1';
Count := GetTypeData(FObj.ClassInfo)^.PropCount;
S := '2';
if Count > 0 then
begin
S := '3';
W.WriteListBegin;
S := '4';
GetMem(PropList, Count * SizeOf(Pointer));
S := '5';
try
S := '6';
GetPropInfos(FObj.ClassInfo, PropList);
S := '7';
for I := 0 to Count - 1 do
begin
S := '8';
PropInfo := PropList^[I];
S := '9';
if PropInfo = nil then break;
S := PropInfo.Name;
if IsStoredProp(FObj, PropInfo) then
GravaItemStream(W, PropInfo, SoAlterados);
S := '11';
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
W.WriteListEnd;
end;
except
on E: Exception do
raise Exception.Create('TCacheProp.SalvaWriter - Exception ' + S + ': ' + E.Message);
end;
end;
procedure TCacheProp.GravaItemStream(W: TCPWriter; PI: PPropInfo; SoAlterados: Boolean);
var S: String;
begin
try
S := PI^.Name;
if SameText(S, 'RecRodape') then begin
S := '77zeber';
// DebugMsg('TCacheProp.GravaItemStream - PI^.Name: '+S);
end;
except
S := 'PI^.Name ##ERRO';
end;
try
if (PI^.PropType^^.Kind in TiposValidos) and
((not SoAlterados) or
AlterouItem(PI)) then
with W do begin
S := PI^.Name;
// DebugMsg('TCacheProp.GravaItemStream - PI^.Name: '+S);
WriteString(PI^.Name);
case PI^.PropType^^.Kind of
tkEnumeration,
tkInteger: WriteInteger(GetOrdProp(FObj, PI));
tkChar: WriteChar(Chr(GetOrdProp(FObj, PI)));
tkFloat: WriteFloat(GetFloatProp(FObj, PI));
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}: begin
S := GetStrProp(FObj, PI);
WriteString(S);
// DebugMsg('TCacheProp.GravaItemStream - StringValue: '+S);
end;
tkVariant: WriteVariant(GetVariantProp(FObj, PI));
tkInt64: WriteInteger(GetInt64Prop(FObj, PI));
end;
end;
except
on E: Exception do Raise
Exception.Create('Exception on GravaItemStream.'+S+' - Exception: ' + E.Message);
end;
end;
procedure TCacheProp.LeItemStream(R: TCPReader; PI: PPropInfo);
var
S, S2 : String;
I : Integer;
begin
S := PI^.Name;
if SameText(S, 'RecRodape') then begin
if S='sdfsfsf' then Exit;
S := 'kkkk';
end;
S2 := S;
with R do
case PI^.PropType^^.Kind of
tkEnumeration,
tkInteger: SetOrdProp(FObj, PI, ReadInteger);
tkChar: SetOrdProp(FObj, PI, Ord(ReadChar));
tkFloat: SetFloatProp(FObj, PI, ReadFloat);
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}: begin
S := ReadString;
SetStrProp(FObj, PI, S);
end;
tkVariant: SetVariantProp(FObj, PI, ReadVariant);
tkInt64: SetInt64Prop(FObj, PI, ReadInt64);
else
I := Integer(PI^.PropType^^.Kind);
if I = -11 then
S := '-11';
end;
{ Item := GetItem(PI);
if Item <> nil then
LePropItem(PI);}
end;
procedure TCacheProp.LeReader(R: TCPReader; S: TStream);
var
N : String;
PI : PPropInfo;
begin
R.ReadListBegin;
FPropertiesAlteradas := '';
while (not R.EndOfList) and (R.Position<(S.Size-1)) do begin
N := R.ReadString;
if FPropertiesAlteradas>'' then
FPropertiesAlteradas := FPropertiesAlteradas + ';';
FPropertiesAlteradas := FPropertiesAlteradas + N;
PI := GetPropInfo(FObj, N);
if PI <> nil then
LeItemStream(R, PI);
end;
R.ReadListEnd;
end;
procedure TCacheProp.LeStream(S: TStream);
var R : TCPReader;
begin
R := TCPReader.Create(S, 4096);
try
LeReader(R, S);
finally
R.Free;
end;
end;
procedure TCacheProp.LeDataset(Tab: TDataset);
var
P : PPropInfo;
I : Integer;
begin
with Tab do
for I := 0 to pred(FieldCount) do begin
P := GetPropInfo(FObj, Fields[I].FieldName);
if P <> nil then
LePropField(P, Fields[I]);
end;
end;
procedure TCacheProp.SalvaDataset(Tab: TDataset);
var
P : PPropInfo;
I : Integer;
begin
with Tab do
for I := 0 to pred(FieldCount) do begin
P := GetPropInfo(FObj, Fields[I].FieldName);
if P <> nil then
SalvaPropField(P, Fields[I]);
end;
end;
function StringToChar(S: String): Char;
begin
if S > '' then
Result := S[1]
else
Result := #0;
end;
procedure TCacheProp.LePropField(PI: PPropInfo; F: TField);
begin
case PI^.PropType^^.Kind of
tkEnumeration:
if F.DataType = ftBoolean then
SetOrdProp(FObj, PI, Integer(F.AsBoolean));
tkInteger: SetOrdProp(FObj, PI, F.AsInteger);
tkChar: SetOrdProp(FObj, PI, Ord(StringToChar(F.AsString)));
tkFloat: SetFloatProp(FObj, PI, F.AsFloat);
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}:
begin
if (F.DataType=ftGuid) and F.IsNull then
SetStrProp(FObj, PI, '') else
SetStrProp(FObj, PI, F.AsString);
end;
tkVariant: SetVariantProp(FObj, PI, F.Value);
tkInt64: SetInt64Prop(FObj, PI, F.AsInteger);
end;
{ Item := GetItem(PI);
if Item <> nil then
LePropItem(PI); }
end;
procedure TCacheProp.SalvaPropField(PI: PPropInfo; F: TField);
var
s2 : String;
S: Variant;
I: Integer;
I64 : Int64;
begin
if (F=nil) or (PI=nil) then Exit;
case PI^.PropType^^.Kind of
tkEnumeration :
if F.DataType = ftBoolean then
F.AsBoolean := Boolean(GetOrdProp(FObj, PI));
tkInteger: begin
I := GetOrdProp(FObj, PI);
if (I<0) and (F.DataType in [ftWord,{$ifdef ver300} ftLongWord, ftByte,{$endif} ftAutoInc]) then
I := 0;
F.AsInteger := I;
end;
tkChar: F.AsString := Chr(GetOrdProp(FObj, PI));
tkFloat: F.AsFloat := GetFloatProp(FObj, PI);
tkString, tkLString, tkWString{$ifdef ver300}, tkUString{$endif}:
begin
s2 := GetStrProp(FObj, PI);
if (F.DataType=ftGuid) and (s2='') then
F.Clear else
F.AsString := s2;
end;
tkVariant: F.Value := GetVariantProp(FObj, PI);
tkInt64: F.AsInteger := GetInt64Prop(FObj, PI);
end;
S := F.FieldName;
if S<>'dfkljhasdkfjh' then
S := F.Value;
if (S=Null) and (F.FieldName = '234098234') then
F.Value := 'teste';
end;
procedure TCacheProp.Assign(ObjFonte: TObject);
var
I, Count: Integer;
PropInfo: PPropInfo;
PropList: PPropList;
begin
if FObj.ClassInfo=nil then
// Para conter ClassInfo classe tem que ser compilada com $M+
Exit;
Count := GetTypeData(FObj.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropInfos(FObj.ClassInfo, PropList);
for I := 0 to Count - 1 do
begin
PropInfo := PropList^[I];
if PropInfo = nil then break;
if IsStoredProp(FObj, PropInfo) then
AssignProp(PropInfo, ObjFonte);
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
end;
procedure TCacheProp.AssignProp(PI: PPropInfo; ObjFonte: TObject);
begin
if PI=nil then Exit;
case PI^.PropType^^.Kind of
tkInteger,
tkEnumeration,
tkChar : SetOrdProp(FObj, PI, GetOrdProp(ObjFonte, PI));
tkFloat : SetFloatProp(FObj, PI, GetFloatProp(ObjFonte, PI));
tkString,
tkLString,
{$ifdef ver300}tkUString,{$endif}
tkWString : SetStrProp(FObj, PI, GetStrProp(ObjFonte, PI));
tkVariant : SetVariantProp(FObj, PI, GetVariantProp(ObjFonte, PI));
tkInt64 : SetInt64Prop(FObj, PI, GetInt64Prop(ObjFonte, PI));
end;
end;
{ TCPReader }
function TCPReader.ReadVariant: Variant;
const
ValTtoVarT: array[TValueType] of Integer = (varNull, varError, varByte,
varSmallInt, varInteger, varDouble, varString, varError, varBoolean,
varBoolean, varError, varError, varString, varEmpty, varError, varSingle,
varCurrency, varDate, varOleStr,
varInt64,
varError,
varDouble);
var
ValType: TValueType;
begin
ValType := NextValue;
case ValType of
vaNil, vaNull:
begin
if ReadValue = vaNil then
VarClear(Result)
else
Result := NULL;
end;
vaInt8: TVarData(Result).VByte := Byte(ReadInteger);
vaInt16: TVarData(Result).VSmallint := Smallint(ReadInteger);
vaInt32: TVarData(Result).VInteger := ReadInteger;
{$ifdef Ver150}
vaInt64: TVarData(Result).VInt64 := ReadInt64;
{$endif}
{$ifdef Ver140}
vaInt64: TVarData(Result).VInt64 := ReadInt64;
{$endif}
vaExtended: TVarData(Result).VDouble := ReadFloat;
{$ifdef Ver180}
vaDouble: TVarData(Result).VDouble := ReadFloat;
{$endif}
vaSingle: TVarData(Result).VSingle := ReadSingle;
vaCurrency: TVarData(Result).VCurrency := ReadCurrency;
vaDate: TVarData(Result).VDate := ReadDate;
vaString, vaLString: Result := ReadString;
vaWString: Result := ReadWideString;
vaFalse, vaTrue: TVarData(Result).VBoolean := (ReadValue = vaTrue);
end;
TVarData(Result).VType := ValTtoVarT[ValType];
end;
{ TCPWriter }
procedure TCPWriter.WriteVariant(Value: Variant);
var VType: Integer;
begin
if VarIsArray(Value) then Value := null;
VType := VarType(Value);
case (VType and varTypeMask) of
varEmpty: WriteValue(vaNil);
varNull: WriteValue(vaNull);
varOleStr: WriteWideString(Value);
varString: WriteString(Value);
varByte, varSmallInt, varInteger: WriteInteger(Value);
{$ifdef Ver150}
varInt64 : WriteInteger(TVarData(Value).VInt64);
{$endif}
varSingle: WriteSingle(Value);
varDouble: WriteFloat(Value);
varCurrency: WriteCurrency(Value);
varDate: WriteDate(Value);
varBoolean:
if Value then
WriteValue(vaTrue)
else
WriteValue(vaFalse);
else
WriteValue(vaNull);
end;
end;
end.
|
PROGRAM Encryption(INPUT, OUTPUT);
{Переводит символы из INPUT в код согласно Chiper
и печатает новые символы в OUTPUT}
CONST
Len = 20;
PermissibleValues = [' ', 'A'..'Z'];
ValidEncryption = [' ' .. 'Z'];
TYPE
Str = ARRAY [1 .. Len] OF ' ' .. 'Z';
Chiper = ARRAY [' ' .. 'Z'] OF CHAR;
VAR
Msg: Str;
Code: Chiper;
FCode: TEXT;
Error: BOOLEAN;
I: INTEGER;
PROCEDURE Initialize(VAR Code: Chiper; VAR FCode: TEXT; VAR Error: BOOLEAN);
VAR
AvailChForEncoding: SET OF CHAR;
Ch1, Ch2, Ch3: CHAR;
NumberString:INTEGER;
{Присвоить Code шифр замены}
BEGIN {Initialize}
RESET(FCode);
NumberString := 0;
AvailChForEncoding := [];
WHILE ((NOT EOF(FCode)) AND (NOT Error))
DO
BEGIN
NumberString := NumberString + 1;
IF NOT EOLN(FCode)
THEN
READ(FCode, Ch1);
IF NOT EOLN(FCode)
THEN
READ(FCode, Ch2);
IF NOT EOLN(FCode)
THEN
READ(FCode, Ch3)
ELSE
BEGIN
WRITELN('INCORRECT DATA TYPE. FORMAT SYMBOL = SYMBOL', NumberString, 'СТРОКА');
Error := TRUE
END;
IF ((Ch1 IN PermissibleValues ) AND (Ch2 = '=') AND NOT(Ch3 IN AvailChForEncoding) AND (Ch3 IN ValidEncryption))
THEN
BEGIN
Code[Ch1] := Ch3;
AvailChForEncoding := AvailChForEncoding + [Ch3]
END
ELSE
BEGIN
WRITELN('INCORRECT DATA TYPE. FORMAT SYMBOL = SYMBOL. You cannot repeat the cipher ', NumberString, ' СТРОКА');
ERROR := TRUE
END;
READLN(FCODE);
END
END; {Initialize}
PROCEDURE Encode(VAR Msg: Str; VAR I: INTEGER);
{Выводит символы из Code, соответствующие символам из Msg}
VAR
Index: 1 .. Len;
BEGIN {Encode}
FOR Index := 1 TO I
DO
IF Msg[Index] IN (PermissibleValues)
THEN
WRITE(Code[Msg[Index]])
ELSE
WRITE(Msg[Index]);
WRITELN
END; {Encode}
BEGIN {Encryption}
{Инициализировать Code}
ASSIGN(FCode, 'code.txt');
Error := FALSE;
Initialize(Code, FCode, Error);
{читать строку в Msg и распечатать ее}
IF NOT Error
THEN
BEGIN
WHILE NOT EOF
DO
BEGIN
I := 0;
WHILE NOT EOLN AND (I < Len)
DO
BEGIN
I := I + 1;
READ(Msg[I]);
END;
READLN;
Encode(Msg, I);
END
END
END. {Encryption}
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 77 Simulating
}
program
Eating;
const
MaxN = 100;
type
TMan = record
P : Integer;
S : Integer;
T : Longint;
D : Integer;
R : Integer;
G : Integer;
end;
TMans = array [0 .. MaxN] of TMan;
TTable = array [0 .. MaxN] of Byte;
TF = array [0 .. MaxN] of Extended;
var
M, N, K : Integer;
T : Longint;
Time, MinTime : Longint;
Mans : TMans;
Table, Dir, Map : TTable;
MinF : TF;
Ate : Integer;
I, J, P, Q : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N, M, T, K);
for I := 1 to M do
begin
Read(F, Mans[I].P);
Map[Mans[I].P] := I;
end;
Close(F);
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
for I :=1 to M do
Writeln(F, MinF[I] : 0 : 5, ' ');
Close(F);
end;
procedure Simulate;
begin
for J := 1 to K do
begin
for I := 1 to N do
Table[I] := 1;
for I := 1 to M do
with Mans[I] do
begin
S := 0;
T := 0;
R := 1;
end;
Ate := 0;
Time := 0;
MinTime := 0;
while Ate < M do
begin
for I := 1 to N do
if Table[I] = 1 then
if (Map[I] <> 0) and (Map[I mod N + 1] <> 0)
and (Mans[Map[I]].R = 1) and (Mans[Map[I]].T = Time)
and (Mans[Map[I mod N + 1]].R = 1)
and (Mans[Map[I mod N + 1]].T = Time) then
Dir[I] := Random(2) else Dir[I] := 2 else Dir[I] := 3;
for I := 1 to M do
if Mans[I].R = 1 then
Mans[I].D := Random(2);
for I := 1 to M do
if Mans[I].T = Time then
with Mans[I] do
case S of
0 : if (Table[(P + D + N - 2) mod N + 1] = 1) and
((Dir[(P + D + N - 2) mod N + 1] + D = 1)
or (Dir[(P + D + N - 2) mod N + 1] = 2)) then
begin
Table[(P + D + N - 2) mod N + 1] := 0;
S := 1;
T := Time + 1;
G := D;
end
else
T := Time + 1;
1 : begin
D := 1 - G;
if (Table[(P + D + N - 2) mod N + 1] = 1) and
(Dir[(P + D + N - 2) mod N + 1] + D = 1)
or (Dir[(P + D + N - 2) mod N + 1] = 2) then
begin
Table[(P + D + N - 2) mod N + 1] := 0;
S := 2;
T := Time + Eating.T - 1;
MinF[I] := (MinF[I] * (J - 1) + T + 1) / J;
Inc(Ate);
end
else
begin
S := 0;
T := Time + 2;
Table[(P + G + N - 2) mod N + 1] := 1;
R := 1;
end;
end;
2 : begin
S := 4;
T := MaxLongInt;
Table[P] := 1;
Table[(P + N - 2) mod N + 1] := 1;
end;
end;
MinTime := MaxLongInt;
for I := 1 to M do
if Mans[I].T < MinTime then MinTime := Mans[I].T;
Time := MinTime;
end;
end;
end;
begin
ReadInput;
Simulate;
WriteOutput;
end. |
unit u_xpl_console_app;
{$i xpl.inc}
interface
uses CustApp;
type // TxPLConsoleApp ========================================================
TxPLConsoleApp = class(TCustomApplication)
protected
procedure DoRun; override;
public
destructor Destroy; override;
procedure Run; reintroduce;
end;
implementation // =============================================================
uses Keyboard
, Classes
, SysUtils
, u_xpl_application
;
const K_STR_1 = 'Quitting the application...';
K_STR_2 = 'Press "q" to quit.';
// TxPLConsoleApp =============================================================
procedure TxPLConsoleApp.DoRun;
begin
inherited DoRun;
if (PollKeyEvent<>0) and (KeyEventToString(TranslateKeyEvent(GetKeyEvent)) = 'q') then begin
xPLApplication.Log(etInfo,K_STR_1);
terminate;
end;
CheckSynchronize(500);
end;
destructor TxPLConsoleApp.Destroy;
begin
DoneKeyboard;
inherited Destroy;
{if destroy hangs it comes from this fu**ing fptimer bug, get the good here
http://svn.freepascal.org/cgi-bin/viewvc.cgi/trunk/packages/fcl-base/src/fptimer.pp?revision=13012
et forcer son utilisation en ajoutant le chemin de recherche :
C:\pp\packages\fcl-base\src\ dans les paths du projet }
end;
procedure TxPLConsoleApp.Run;
begin
if HasOption('h') then begin
writeln ('Usage:');
writeln (chr(9),Exename, ' [flags] [options]');
writeln (chr(9),'where valid flags are:');
writeln (chr(9),' -h - show this help text');
writeln (chr(9),' -v - verbose mode');
writeln (chr(9),'and valid options are (default shown in brackets):');
writeln (chr(9),' -i if0 - the interface for xPL messages');
end else begin
InitKeyboard;
xPLApplication.Log(etInfo,K_STR_2);
inherited Run;
end;
end;
end.
|
unit Card;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, SolidInput;
type
TCard = class(TControl)
private
{ Private declarations }
protected
{ Protected declarations }
FPointerOnClose: TNotifyEvent;
FPointerOnOpen: TNotifyEvent;
FBackgroundCard: TRectangle;
FShadow: TShadowEffect;
function GetFTag: NativeInt;
procedure SetFTag(const Value: NativeInt);
function GetFCorners: TCorners;
procedure SetFCorners(const Value: TCorners);
function GetFOnClose: TNotifyEvent;
function GetFOnOpen: TNotifyEvent;
procedure SetFOnClose(const Value: TNotifyEvent);
procedure SetFOnOpen(const Value: TNotifyEvent);
function GetFCursor: TCursor;
function GetFElevation: Boolean;
function GetFElevationColor: TAlphaColor;
function GetFElevationDirection: Single;
function GetFElevationDistance: Single;
function GetFElevationOpacity: Single;
function GetFElevationSoftness: Single;
function GetFHitTest: Boolean;
procedure SetFCursor(const Value: TCursor);
procedure SetFElevation(const Value: Boolean);
procedure SetFElevationColor(const Value: TAlphaColor);
procedure SetFElevationDirection(const Value: Single);
procedure SetFElevationDistance(const Value: Single);
procedure SetFElevationOpacity(const Value: Single);
procedure SetFElevationSoftness(const Value: Single);
procedure SetFHitTest(const Value: Boolean);
function GetFBackgroudColor: TBrush;
procedure SetFBackgroudColor(const Value: TBrush);
function GetFCornerRound: Single;
procedure SetFCornerRound(const Value: Single);
function GetFOnClick: TNotifyEvent;
function GetFOnDblClick: TNotifyEvent;
function GetFOnKeyDown: TKeyEvent;
function GetFOnKeyUp: TKeyEvent;
function GetFOnMouseDown: TMouseEvent;
function GetFOnMouseEnter: TNotifyEvent;
function GetFOnMouseLeave: TNotifyEvent;
function GetFOnMouseMove: TMouseMoveEvent;
function GetFOnMouseUp: TMouseEvent;
function GetFOnMouseWheel: TMouseWheelEvent;
procedure SetFOnClick(const Value: TNotifyEvent);
procedure SetFOnDblClick(const Value: TNotifyEvent);
procedure SetFOnKeyDown(const Value: TKeyEvent);
procedure SetFOnKeyUp(const Value: TKeyEvent);
procedure SetFOnMouseDown(const Value: TMouseEvent);
procedure SetFOnMouseEnter(const Value: TNotifyEvent);
procedure SetFOnMouseLeave(const Value: TNotifyEvent);
procedure SetFOnMouseMove(const Value: TMouseMoveEvent);
procedure SetFOnMouseUp(const Value: TMouseEvent);
procedure SetFOnMouseWheel(const Value: TMouseWheelEvent);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open(Duration: Single = 0.2); virtual;
procedure Close(Duration: Single = 0.2); virtual;
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
{ Additional properties }
property Cursor: TCursor read GetFCursor write SetFCursor;
property HitTest: Boolean read GetFHitTest write SetFHitTest default True;
property Color: TBrush read GetFBackgroudColor write SetFBackgroudColor;
property Elevation: Boolean read GetFElevation write SetFElevation;
property ElevationDistance: Single read GetFElevationDistance write SetFElevationDistance;
property ElevationDirection: Single read GetFElevationDirection write SetFElevationDirection;
property ElevationOpacity: Single read GetFElevationOpacity write SetFElevationOpacity;
property ElevationSoftness: Single read GetFElevationSoftness write SetFElevationSoftness;
property ElevationColor: TAlphaColor read GetFElevationColor write SetFElevationColor;
property CornerRound: Single read GetFCornerRound write SetFCornerRound;
property Corners: TCorners read GetFCorners write SetFCorners;
property Tag: NativeInt read GetFTag write SetFTag;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick;
property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick;
property OnKeyDown: TKeyEvent read GetFOnKeyDown write SetFOnKeyDown;
property OnKeyUp: TKeyEvent read GetFOnKeyUp write SetFOnKeyUp;
property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown;
property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp;
property OnMouseWheel: TMouseWheelEvent read GetFOnMouseWheel write SetFOnMouseWheel;
property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove;
property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter;
property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave;
property OnClose: TNotifyEvent read GetFOnClose write SetFOnClose;
property OnOpen: TNotifyEvent read GetFOnOpen write SetFOnOpen;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TCard]);
end;
{ TCard }
procedure TCard.Open(Duration: Single = 0.2);
begin
Self.BringToFront;
Self.Visible := True;
Self.Opacity := 0;
Self.AnimateFloat('Opacity', 1, Duration, TAnimationType.InOut, TInterpolationType.Circular);
if Assigned(FPointerOnOpen) then
FPointerOnOpen(Self);
end;
procedure TCard.Close(Duration: Single = 0.2);
begin
Self.AnimateFloatWait('Opacity', 0, Duration, TAnimationType.InOut, TInterpolationType.Circular);
Self.Visible := False;
Self.Opacity := 1;
if Assigned(FPointerOnClose) then
FPointerOnClose(Self);
end;
constructor TCard.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 300;
Self.Height := 300;
{ BackgroudCard }
FBackgroundCard := TRectangle.Create(Self);
Self.AddObject(FBackgroundCard);
FBackgroundCard.Align := TAlignLayout.Contents;
FBackgroundCard.Stroke.Kind := TBrushKind.None;
FBackgroundCard.Fill.Kind := TBrushKind.Solid;
FBackgroundCard.Fill.Color := TAlphaColor($FFFFFFFF);
FBackgroundCard.SetSubComponent(True);
FBackgroundCard.Stored := False;
{ Shadow }
FShadow := TShadowEffect.Create(Self);
FBackgroundCard.AddObject(FShadow);
FShadow.Direction := 90;
FShadow.Distance := 7;
FShadow.Opacity := 0.2;
FShadow.Softness := 0.3;
FShadow.Enabled := True;
end;
destructor TCard.Destroy;
begin
if Assigned(FShadow) then
FShadow.Free;
if Assigned(FBackgroundCard) then
FBackgroundCard.Free;
inherited;
end;
function TCard.GetFBackgroudColor: TBrush;
begin
Result := FBackgroundCard.Fill;
end;
function TCard.GetFCornerRound: Single;
begin
Result := FBackgroundCard.XRadius;
end;
function TCard.GetFCorners: TCorners;
begin
Result := FBackgroundCard.Corners;
end;
function TCard.GetFCursor: TCursor;
begin
Result := FBackgroundCard.Cursor;
end;
function TCard.GetFElevation: Boolean;
begin
Result := FShadow.Enabled;
end;
function TCard.GetFElevationColor: TAlphaColor;
begin
Result := FShadow.ShadowColor;
end;
function TCard.GetFElevationDirection: Single;
begin
Result := FShadow.Direction;
end;
function TCard.GetFElevationDistance: Single;
begin
Result := FShadow.Distance;
end;
function TCard.GetFElevationOpacity: Single;
begin
Result := FShadow.Opacity;
end;
function TCard.GetFElevationSoftness: Single;
begin
Result := FShadow.Softness;
end;
function TCard.GetFHitTest: Boolean;
begin
Result := FBackgroundCard.HitTest;
end;
function TCard.GetFOnClick: TNotifyEvent;
begin
Result := FBackgroundCard.OnClick;
end;
function TCard.GetFOnClose: TNotifyEvent;
begin
Result := FPointerOnClose;
end;
function TCard.GetFOnDblClick: TNotifyEvent;
begin
Result := FBackgroundCard.OnDblClick;
end;
function TCard.GetFOnKeyDown: TKeyEvent;
begin
Result := FBackgroundCard.OnKeyDown;
end;
function TCard.GetFOnKeyUp: TKeyEvent;
begin
Result := FBackgroundCard.OnKeyUp;
end;
function TCard.GetFOnMouseDown: TMouseEvent;
begin
Result := FBackgroundCard.OnMouseDown;
end;
function TCard.GetFOnMouseEnter: TNotifyEvent;
begin
Result := FBackgroundCard.OnMouseEnter;
end;
function TCard.GetFOnMouseLeave: TNotifyEvent;
begin
Result := FBackgroundCard.OnMouseLeave;
end;
function TCard.GetFOnMouseMove: TMouseMoveEvent;
begin
Result := FBackgroundCard.OnMouseMove;
end;
function TCard.GetFOnMouseUp: TMouseEvent;
begin
Result := FBackgroundCard.OnMouseUp;
end;
function TCard.GetFOnMouseWheel: TMouseWheelEvent;
begin
Result := FBackgroundCard.OnMouseWheel;
end;
function TCard.GetFOnOpen: TNotifyEvent;
begin
Result := FPointerOnOpen;
end;
function TCard.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
procedure TCard.SetFBackgroudColor(const Value: TBrush);
begin
FBackgroundCard.Fill := Value;
end;
procedure TCard.SetFCornerRound(const Value: Single);
begin
FBackgroundCard.XRadius := Value;
FBackgroundCard.YRadius := Value;
end;
procedure TCard.SetFCorners(const Value: TCorners);
begin
FBackgroundCard.Corners := Value;
end;
procedure TCard.SetFCursor(const Value: TCursor);
begin
FBackgroundCard.Cursor := Value;
end;
procedure TCard.SetFElevation(const Value: Boolean);
begin
FShadow.Enabled := Value;
end;
procedure TCard.SetFElevationColor(const Value: TAlphaColor);
begin
FShadow.ShadowColor := Value;
end;
procedure TCard.SetFElevationDirection(const Value: Single);
begin
FShadow.Direction := Value;
end;
procedure TCard.SetFElevationDistance(const Value: Single);
begin
FShadow.Distance := Value;
end;
procedure TCard.SetFElevationOpacity(const Value: Single);
begin
FShadow.Opacity := Value;
end;
procedure TCard.SetFElevationSoftness(const Value: Single);
begin
FShadow.Softness := Value;
end;
procedure TCard.SetFHitTest(const Value: Boolean);
begin
FBackgroundCard.HitTest := Value;
end;
procedure TCard.SetFOnClick(const Value: TNotifyEvent);
begin
FBackgroundCard.OnClick := Value;
end;
procedure TCard.SetFOnClose(const Value: TNotifyEvent);
begin
FPointerOnClose := Value;
end;
procedure TCard.SetFOnDblClick(const Value: TNotifyEvent);
begin
FBackgroundCard.OnDblClick := Value;
end;
procedure TCard.SetFOnKeyDown(const Value: TKeyEvent);
begin
FBackgroundCard.OnKeyDown := Value;
end;
procedure TCard.SetFOnKeyUp(const Value: TKeyEvent);
begin
FBackgroundCard.OnKeyUp := Value;
end;
procedure TCard.SetFOnMouseDown(const Value: TMouseEvent);
begin
FBackgroundCard.OnMouseDown := Value;
end;
procedure TCard.SetFOnMouseEnter(const Value: TNotifyEvent);
begin
FBackgroundCard.OnMouseEnter := Value;
end;
procedure TCard.SetFOnMouseLeave(const Value: TNotifyEvent);
begin
FBackgroundCard.OnMouseLeave := Value;
end;
procedure TCard.SetFOnMouseMove(const Value: TMouseMoveEvent);
begin
FBackgroundCard.OnMouseMove := Value;
end;
procedure TCard.SetFOnMouseUp(const Value: TMouseEvent);
begin
FBackgroundCard.OnMouseUp := Value;
end;
procedure TCard.SetFOnMouseWheel(const Value: TMouseWheelEvent);
begin
FBackgroundCard.OnMouseWheel := Value;
end;
procedure TCard.SetFOnOpen(const Value: TNotifyEvent);
begin
FPointerOnOpen := Value;
end;
procedure TCard.SetFTag(const Value: NativeInt);
begin
FBackgroundCard.Tag := Value;
TControl(Self).Tag := Value;
end;
end.
|
unit const_sarray_1;
interface
implementation
const A: array [4] of Int32 = (1, 2, 3, 4);
var G1, G2: Int32;
procedure Test;
begin
G1 := A[0];
G2 := A[3];
end;
initialization
Test();
finalization
Assert(G1 = 1);
Assert(G2 = 4);
end.
|
unit cUserReg;
interface
uses System.Classes, Vcl.Controls, Vcl.ExtCtrls,Vcl.Dialogs,System.SysUtils,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error,
FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async,
FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cCrypto;
type
TUser = class
private
dbConnection:TFDConnection;
F_id : Integer;
F_username : String;
F_password : String;
function getPassword : String;
procedure setPassword(const Value : String);
public
constructor Create(aConnection : TFDConnection);
destructor Destroy; override;
function Insert : Boolean;
function Update : Boolean;
function Delete : Boolean;
function Select(id:Integer) : Boolean;
function ExistingUser(aUser:String):Boolean;
function ChangePassword: Boolean;
function Login(aUser:String; aPassword:String):Boolean;
published
property id : Integer read F_id write F_id;
property username : string read F_username write F_username;
property password : string read getPassword write setPassword;
end;
implementation
{$region 'Constructor and Destructor'}
constructor TUser.Create(aConnection : TFDConnection);
begin
dbConnection := TFDConnection.Create(nil);
end;
destructor TUser.Destroy;
begin
FreeAndNil(dbConnection);
inherited;
end;
{$endRegion}
{$region 'CRUD'}
function TUser.Delete: Boolean;
var Qry:TFDQuery;
begin
if MessageDlg('Delete the register: '+#13+#13+
'ID: '+IntToStr(F_id)+#13+
'Username: ' +F_username,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin
Result:=false;
abort;
end;
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM user '+
' WHERE id=:id ');
Qry.ParamByName('id').AsInteger :=F_id;
Try
dbConnection.StartTransaction;
Qry.ExecSQL;
dbConnection.Commit;
Except
dbConnection.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TUser.Update: Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE user '+
' SET name =:name '+
' ,password =:password '+
' WHERE id=:id ');
Qry.ParamByName('id').AsInteger :=Self.F_id;
Qry.ParamByName('name').AsString :=Self.F_username;
Qry.ParamByName('password').AsString :=Self.F_password;
Try
dbConnection.StartTransaction;
Qry.ExecSQL;
dbConnection.Commit;
Except
dbConnection.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TUser.Insert: Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO user (name, '+
' password )'+
' VALUES (:name, '+
' :password )' );
Qry.ParamByName('name').AsString :=Self.F_username;
Qry.ParamByName('password').AsString :=Self.F_password;
Try
dbConnection.StartTransaction;
Qry.ExecSQL;
dbConnection.Commit;
Except
dbConnection.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TUser.Select(id: Integer): Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT id,'+
' name, '+
' password '+
' FROM user '+
' WHERE id=:id');
Qry.ParamByName('id').AsInteger:=id;
Try
Qry.Open;
Self.F_id := Qry.FieldByName('id').AsInteger;
Self.F_username := Qry.FieldByName('name').AsString;
Self.F_password := Qry.FieldByName('password').AsString;;
Except
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TUser.ExistingUser(aUser:String):Boolean;
var Qry:TFDQuery;
begin
try
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT COUNT(id) AS Qt '+
' FROM user '+
' WHERE name =:name ');
Qry.ParamByName('name').AsString :=aUser;
Try
Qry.Open;
if Qry.FieldByName('Qt').AsInteger>0 then
result := true
else
result := false;
Except
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
{$region 'GET E SET'}
function TUser.getPassword: String;
begin
Result := Decrypt(Self.F_password);
end;
procedure TUser.setPassword(const Value: String);
begin
Self.F_password := Encrypt(Value);
end;
{$endregion}
{$region 'LOGIN'}
function TUser.Login(aUser:String; aPassword:String):Boolean;
var Qry:TFDQuery;
begin
try
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT id, '+
' name, '+
' password '+
' FROM user '+
' WHERE name=:name '+
' AND password=:password');
Qry.ParamByName('name').AsString :=aUser;
Qry.ParamByName('password').AsString:=Encrypt(aPassword);
Try
Qry.Open;
if Qry.FieldByName('id').AsInteger>0 then begin
result := true;
F_id:= Qry.FieldByName('usuarioId').AsInteger;
F_username := Qry.FieldByName('name').AsString;
F_password := Qry.FieldByName('password').AsString;
end
else
result := false;
Except
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
{$region 'CHANGE PASSWORD'}
function TUser.ChangePassword: Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:=dbConnection;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE user '+
' SET password =:password '+
' WHERE id=:id ');
Qry.ParamByName('id').AsInteger :=Self.F_id;
Qry.ParamByName('password').AsString :=Self.F_password;
Try
dbConnection.StartTransaction;
Qry.ExecSQL;
dbConnection.Commit;
Except
dbConnection.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
end.
|
unit MatchChecker;
interface
uses
MetroBase, MetroVisCom;
//----------------------------------------------------------------------------
// TMatchChecker is a class that determines if a map and a network match.
// Matching maps and networks contain exactly the same stations and lines.
//----------------------------------------------------------------------------
type
TMatchChecker = class(TObject)
private
FNetwork: TNetwork;
FMap: TMetroMap;
public
// construction/deconstruction ---------------------------------------------
constructor Create(AMap: TMetroMap; ANetwork: TNetwork);
// pre: True
// post: FMap = AMap and FNetwork = ANetwork
// derived queries ---------------------------------------------------------
function Compatible: Boolean;
// pre: True
// ret: (forall S: S in FNetwork.GetStationSet.Abstr:
// (exists T: T in FMap.AbstrStations: S.GetCode = T.GetCode))
// and
// (forall S: S in FMap.AbstrStations:
// (exists T: T in FNetwork.GetStationSet.Abstr:
// S.GetCode = T.GetCode))
// and
// (forall L: L in FNetwork.GetLineSet.Abstr:
// (exists M: M in FMap.AbstrLines: L.GetCode = M.GetCode))
// and
// (forall L: L in FMap.AbstrLines:
// (exists M: M in FNetwork.GetLineSet.Abstr:
// L.GetCode = M.GetCode))
// and
// (forall L, M: L in FNetwork.GetLineSet.Abstr and
// M in FMap.AbstrLines and L.GetCode = M.GetCode:
// (forall I: 0 <= I < |L.Abstr|:
// (exists J: 0 <= J < |M.Abstr| - I:
// L.Abstr[I].GetCode = M.Abstr[I + J].GetCode and
// (forall X: 0 <= X < J: M.Abstr[X] is TVisStationDummy))))
end;
implementation
{ TCompatibilityChecker }
function TMatchChecker.Compatible: Boolean;
var
I, J, K: Integer;
VStation: TStationR;
VLine: TLineR;
VVisStation: TVisStation;
VVisLine: TVisLine;
begin
Result := True;
// Check if all stations in the network exist on the map.
for I := 0 to FNetwork.GetStationSet.Count - 1 do begin
VStation := FNetwork.GetStationSet.GetStation(I);
if not(FMap.HasStation(VStation.GetCode)) then begin
Result := False
end
end;
// Check if all lines in the network exist on the map and
// check if all stations on the lines in the network exist
// on the corresponding line in the map in the same order.
for I := 0 to FNetwork.GetLineSet.Count - 1 do begin
VLine := FNetwork.GetLineSet.GetLine(I);
if not(FMap.HasLine(VLine.GetCode)) then begin
Result := False
end
else begin
VVisLine := FMap.GetLine(VLine.GetCode);
K := 0;
for J := 0 to VLine.Count - 1 do begin
while VVisLine.GetStation(K) is TVisStationDummy do begin
K := K + 1
end;
if VVisLine.GetStation(K).GetCode <> VLine.Stop(J).GetCode then begin
Result := False
end;
K := K + 1
end
end
end;
// Check if all stations on the map exist in the network.
for I := 0 to FMap.VisComCount - 1 do begin
if FMap.GetVisCom(I) is TVisStation then begin
VVisStation := TVisStation(FMap.GetVisCom(I));
if not(FNetwork.GetStationSet.HasCode(VVisStation.GetCode)) and
not(VVisStation is TVisStationDummy) then begin
Result := False
end
end
end;
// Check if all lines on the map exist in the network
for I := 0 to FMap.VisComCount - 1 do begin
if FMap.GetVisCom(I) is TVisLine then begin
VVisLine := TVisLine(FMap.GetVisCom(I));
if not(FNetwork.GetLineSet.HasCode(VVisLine.GetCode)) then begin
Result := False
end
end
end
end;
constructor TMatchChecker.Create(AMap: TMetroMap;
ANetwork: TNetwork);
begin
FMap := AMap;
FNetwork := ANetwork
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.EMSApi;
{$SCOPEDENUMS ON}
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections, System.JSON,
REST.Client, REST.Types, System.Net.URLClient;
type
EEMSClientAPIError = class;
EEMSClientHTTPError = class;
TEMSClientHTTPErrorClass = class of EEMSClientHTTPError;
/// <summary>
/// <para>
/// TEMSClientAPI implements REST requests to the EMS server
/// </para>
/// </summary>
TEMSClientAPI = class(TComponent)
public type
TConnectionInfo = record
public
ApiVersion: string;
ApplicationId: string;
AppSecret: string;
MasterSecret: string;
UserName: string;
Password: string;
ProxyPassword: string;
ProxyPort: Integer;
ProxyServer: string;
ProxyUsername: string;
BaseURL: string;
LoginResource: string;
OnValidateCertificate: TValidateCertificateEvent;
TenantId: string;
TenantSecret: string;
end;
THeaderNames = record
public const
ApiVersion = 'X-Embarcadero-Api-Version';
ApplicationId = 'X-Embarcadero-Application-Id';
SessionToken = 'X-Embarcadero-Session-Token';
MasterSecret = 'X-Embarcadero-Master-Secret';
AppSecret = 'X-Embarcadero-App-Secret';
TenantId = 'X-Embarcadero-Tenant-Id';
TenantSecret = 'X-Embarcadero-Tenant-Secret';
end;
TJSONNames = record
public const
UserName = 'username';
Password = 'password';
SessionToken = 'sessionToken';
Error = 'error';
Description = 'description';
UserID = '_id';
GroupName = 'groupname';
InstallationID = '_id';
MetaData = '_meta';
MetaCreated = 'created';
MetaUpdated = 'updated';
MetaCreator = 'creator';
PushWhere = 'where';
PushChannels = 'channels';
PushData = 'data';
PushBadge = 'badge';
FieldName = 'name';
FieldCustom = 'custom';
FieldFields = 'fields';
ModuleID = '_id';
ResourceModuleID = 'moduleid';
ModuleName = 'modulename';
Protocol = 'protocol';
ResourceName = 'resourcename';
ProtocolProps = 'protocolprops';
Resources = 'resources';
end;
TSegmentNames = record
public const
Users = 'users';
UsersFields = 'users/fields';
Groups = 'groups';
GroupsFields = 'groups/fields';
Installations = 'installations';
InstallationsChannels = 'installations/channels';
InstallationsFields = 'installations/fields';
Login = 'login';
Signup = 'signup';
Logout = 'logout';
Restore = '_restore';
Me = 'me';
Push = 'push';
Modules = 'edgemodules';
ModulesResources = 'edgemodules/resources';
ModulesFields = 'edgemodules/fields';
ResourcesFields = 'edgemodules/resources/fields';
Resources = 'resources';
end;
TQueryParamNames = record
public const
Order = 'order';
Where = 'where';
Limit = 'limit';
Skip = 'skip';
end;
TUpdatedAt = record
private
FUpdatedAt: TDateTime;
public
constructor Create(AUpdatedAt: TDateTime);
property UpdatedAt: TDateTime read FUpdatedAt;
end;
TUser = record
private
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FUserID: string;
FUserName: string;
FCreator: string;
public
constructor Create(const AUserName: string; const AUserID: string = '');
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property UserID: string read FUserID;
property UserName: string read FUserName;
property Creator: string read FCreator;
end;
TGroup = record
private
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FGroupName: string;
FCreator: string;
public
constructor Create(const AGroupName: string);
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property GroupName: string read FGroupName;
property Creator: string read FCreator;
end;
TLogin = record
private
FAuthToken: string;
FUser: TUser;
public
constructor Create(const AAuthToken: string; const AUser: TUser);
property AuthToken: string read FAuthToken;
property User: TUser read FUser;
end;
TInstallation = record
private
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FInstallationID: string;
FCreator: string;
public
constructor Create(const AInstallationID: string);
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property InstallationID: string read FInstallationID;
property Creator: string read FCreator;
end;
TModule = record
private
FModuleID: string;
FModuleName: string;
FProtocol: string;
FProtocolProps: string;
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FCreator: string;
public
constructor Create(const AModuleID, AName: string);
property ModuleID: string read FModuleID;
property ModuleName: string read FModuleName;
property Protocol: string read FProtocol;
property ProtocolProps: string read FProtocolProps;
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property Creator: string read FCreator;
end;
TModuleResource = record
private
FResourceName: string;
FModuleName: string;
FModuleID: string;
FCreatedAt: TDateTime;
FUpdatedAt: TDateTime;
FCreator: string;
public
constructor Create(const AName, AModuleID, AModuleName: string);
property ResourceName: string read FResourceName;
property ModuleName: string read FModuleName;
property ModuleID: string read FModuleID;
property CreatedAt: TDateTime read FCreatedAt;
property UpdatedAt: TDateTime read FUpdatedAt;
property Creator: string read FCreator;
end;
TResourcePair = TPair<string, TJSONObject>;
TResourceList = TArray<TResourcePair>;
TDeviceTypes = record
public
const IOS = 'ios';
const Android = 'android';
end;
TPushStatus = record
private
FAndroid: Integer;
FIOS: Integer;
public
constructor Create(AIOS, AAndroid: Integer);
property QueuedIOS: Integer read FIOS;
property QueuedAndroid: Integer read FAndroid;
end;
TCreatorNames = record
public
const Master = '00000000-0000-0000-0000-000000000001';
const Null = '00000000-0000-0000-0000-000000000000';
end;
TAuthentication = (Default, MasterSecret, AppSecret, Session, None);
TDefaultAuthentication = (AppSecret, MasterSecret, Session, None);
// TFindObjectProc = reference to procedure(const AID: TObjectID; const AObj: TJSONObject);
TAppHandshakeProc = reference to procedure(const AObj: TJSONObject);
TQueryUserNameProc = reference to procedure(const AUser: TUser;
const AObj: TJSONObject);
TLoginProc = reference to procedure(const ALogin: TLogin;
const AObj: TJSONObject);
TRetrieveUserProc = reference to procedure(const AUser: TUser;
const AObj: TJSONObject);
TRetrieveGroupProc = reference to procedure(const AGroup: TGroup;
const AObj: TJSONObject);
TRetrieveInstallationProc = reference to procedure(const AInstallation: TInstallation;
const AObj: TJSONObject);
TRetrieveModuleProc = reference to procedure(const AModule: TModule;
const AObj: TJSONObject);
TRetrieveModuleResourceProc = reference to procedure(const AResource: TModuleResource;
const AObj: TJSONObject);
TQueryModuleNameProc = reference to procedure(const AModule: TModule;
const AObj: TJSONObject);
public const
DateTimeIsUTC = True;
public
class var EmptyConnectionInfo: TConnectionInfo;
public const
cDefaultApiVersion = '2';
private
FRESTClient: TRESTClient;
FRequest: TRESTRequest;
FResponse: TRESTResponse;
FOwnsResponse: Boolean;
FConnectionInfo: TConnectionInfo;
FSessionAuthToken: string;
FAuthentication: TAuthentication;
FDefaultAuthentication: TDefaultAuthentication;
FInLogin: Boolean;
procedure SetConnectionInfo(const Value: TConnectionInfo);
function GetLoggedIn: Boolean;
protected
procedure AddAuthHeader(const ARequest: TCustomRESTRequest; const AKey,
AValue: string);
function MakeLoginResource(const ASegmentName: string): string; inline;
function MetaDataFromObject(const AJSONObject: TJSONObject; out ACreatedAt,
AUpdatedAt: TDateTime; out ACreator: string): Boolean;
function DeleteResource(const AResource, AID: string; const AAddParameters: TProc = nil): Boolean;
procedure PutResource(const AResource, AID: string;
const AJSON: TJSONObject; const AAddParameters: TProc = nil);
procedure AddResource(const AResource: string; const AJSON: TJSONObject; const AAddParameters: TProc = nil);
procedure QueryResource(const AResource: string;
const AQuery: array of string; const AJSONArray: TJSONArray;
AReset: Boolean; const AAddParameters: TProc = nil);
function RetrieveInstallation(const AInstallationID: string; out AFoundInstallation: TInstallation;
const AJSON: TJSONArray; AProc: TRetrieveInstallationProc;
AReset: Boolean): Boolean; overload;
procedure AddAppSecret(const ARequest: TCustomRESTRequest; const AKey: string);
/// <summary>Gets actual Authentication and adds it to the request. </summary>
procedure DoAddAuthParameters; overload;
/// <summary>Adds authentication parameters to the request. </summary>
/// <param name="AAuthentication">Authentication type: AppSecret, MasterSecret, Session, None</param>
procedure DoAddAuthParameters(AAuthentication: TAuthentication); overload;
/// <summary>Adds authentication parameters to the request. </summary>
/// <param name="ARequest">The Request</param>
/// <param name="AAuthentication">Authentication type: AppSecret, MasterSecret, Session, None</param>
procedure DoAddAuthParameters(const ARequest: TCustomRESTRequest; AAuthentication: TAuthentication); overload;
procedure AddMasterKey(const ARequest: TCustomRESTRequest; const AKey: string);
procedure AddSessionToken(const ARequest: TCustomRESTRequest; const ASessionToken: string);
procedure AddTenantId(const ARequest: TCustomRESTRequest; const AKey: string);
function GetActualAuthentication: TAuthentication;
function CreateHTTPException(const AResponse: TCustomRESTResponse;
const AClass: TEMSClientHTTPErrorClass): EEMSClientHTTPError; overload;
function CreateHTTPException(const AResponse: TCustomRESTResponse): EEMSClientHTTPError; overload;
procedure CheckForResponseError; overload;
procedure CheckForResponseError(AValidStatusCodes: array of Integer); overload;
function LoginFromObject(const AUserName: string;
const AJSONObject: TJSONObject): TLogin;
procedure LoginUser(const AUserName, APassword: string; out ALogin: TLogin;
const AJSON: TJSONArray; AProc: TLoginProc); overload;
function QueryUserName(const AUserName: string; out AUser: TUser;
const AJSON: TJSONArray; AProc: TQueryUserNameProc): Boolean; overload;
function UpdatedAtFromObject(const AJSONObject: TJSONObject): TUpdatedAt;
function UserFromObject(const AUserName: string;
const AJSONObject: TJSONObject): TUser; overload;
function RetrieveUser(const AObjectID: string; out AUser: TUser;
const AJSON: TJSONArray; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveGroup(const AGroupName: string; out AGroup: TGroup;
const AJSON: TJSONArray; AProc: TRetrieveGroupProc): Boolean; overload;
function RetrieveModule(const AModuleID: string; out AModule: TModule;
const AJSON: TJSONArray; AProc: TRetrieveModuleProc): Boolean; overload;
function RetrieveModuleResource(const AModuleID, AResourceName: string; out AResource: TModuleResource;
const AJSON: TJSONArray; AProc: TRetrieveModuleResourceProc): Boolean; overload;
function GroupFromObject(const AGroupName: string;
const AJSONObject: TJSONObject): TGroup; overload;
function GroupFromObject(const AJSONObject: TJSONObject): TGroup; overload;
function InstallationFromObject(const AInstallationID: string;
const AJSONObject: TJSONObject): TInstallation; overload;
function InstallationFromObject(const AJSONObject: TJSONObject): TInstallation; overload;
procedure ApplyConnectionInfo; overload;
property RestClient: TRESTClient read FRESTClient;
property Request: TRESTRequest read FRequest;
procedure PushBody(const AMessage: TJSONObject); overload;
procedure PushBody(const AMessage: TJSONObject; out AStatus: TPushStatus); overload;
function PushStatusFromObject(
const AJSONObject: TJSONObject): TPushStatus; overload;
function CreateInstallationObject(const ADeviceType: string; const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
function CreateInstallationObject(const ADeviceType: string; const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject; overload;
procedure RetrieveFields(const AResourceName: string;
const AFields: TJSONArray);
function ModuleFromObject(const AJSONObject: TJSONObject): TModule; overload;
function ModuleFromObject(const AModuleID: string; const AJSONObject: TJSONObject): TModule; overload;
function ResourceFromObject(const AJSONObject: TJSONObject): TModuleResource;
function QueryModuleName(const AModuleName: string; out AModule: TModule;
const AJSON: TJSONArray; AProc: TQueryModuleNameProc): Boolean; overload;
public
constructor Create; reintroduce; overload;
constructor Create(AOwner: TComponent;
const AResponse: TRESTResponse = nil); reintroduce; overload;
destructor Destroy; override;
procedure CheckForResponseError(const AResponse: TCustomRESTResponse; const AValidStatusCodes: array of Integer); overload;
procedure CheckForResponseError(const AResponse: TCustomRESTResponse); overload;
procedure ApplyConnectionInfo(const AClient: TCustomRESTClient); overload;
procedure AddAuthParameters(const ARequest: TCustomRESTRequest); overload;
// Utilities
function UserFromObject(const AJSONObject: TJSONObject): TUser; overload;
// Handshake
procedure AppHandshake(const AJSONArray: TJSONArray); overload;
procedure AppHandshake(const AProc: TAppHandshakeProc); overload;
// Users
function QueryUserName(const AUserName: string; AProc: TQueryUserNameProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TUser;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveUser(const AUser: TUser; AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveUser(const AUser: TUser; out AFoundUser: TUser;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveUser(const AObjectID: string; out AUser: TUser;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveUser(const AObjectID: string; AProc: TRetrieveUserProc): Boolean; overload;
procedure SignupUser(const AUserName, APassword: string;
const AUserFields: TJSONObject; out ALogin: TLogin);
procedure AddUser(const AUserName, APassword: string;
const AUserFields: TJSONObject; out AUser: TUser);
procedure LoginUser(const AUserName, APassword: string;
AProc: TLoginProc); overload;
procedure LoginUser(const AUserName, APassword: string; out ALogin: TLogin;
const AJSON: TJSONArray = nil); overload;
procedure LogoutUser;
function RetrieveCurrentUser(AProc: TRetrieveUserProc): Boolean; overload;
function RetrieveCurrentUser(out AUser: TUser;
const AJSON: TJSONArray = nil): Boolean; overload;
procedure UpdateUser(const AObjectID: string;
const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
procedure UpdateUser(const AUser: TUser; const AUserObject: TJSONObject;
out AUpdatedAt: TUpdatedAt); overload;
function DeleteUser(const AObjectID: string): Boolean; overload;
function DeleteUser(const AUser: TUser): Boolean; overload;
procedure QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray; out AUsers: TArray<TUser>); overload;
procedure RetrieveUsersFields(const AFields: TJSONArray);
function RetrieveUsersNames: TArray<string>;
// Groups
procedure QueryGroups(const AQuery: array of string;
const AJSONArray: TJSONArray); overload;
procedure QueryGroups(const AQuery: array of string;
const AJSONArray: TJSONArray; out AGroups: TArray<TGroup>); overload;
procedure CreateGroup(const AGroupName: string;
const AGroupFields: TJSONObject; out AGroup: TGroup);
procedure UpdateGroup(const AGroupName: string;
const AGroupObject: TJSONObject; out AUpdatedAt: TUpdatedAt); overload;
procedure UpdateGroup(const AGroup: TGroup; const AGroupObject: TJSONObject;
out AUpdatedAt: TUpdatedAt); overload;
function DeleteGroup(const AGroupName: string): Boolean; overload;
function DeleteGroup(const AGroup: TGroup): Boolean; overload;
function RetrieveGroup(const AGroupName: string; out AFoundGroup: TGroup;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveGroup(const AGroupName: string; AProc: TRetrieveGroupProc): Boolean; overload;
function RetrieveGroup(const AGroup: TGroup; out AFoundGroup: TGroup;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveGroup(const AGroup: TGroup; AProc: TRetrieveGroupProc): Boolean; overload;
procedure AddUsersToGroup(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedAt: TUpdatedAt);
function RemoveUsersFromGroup(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedAt: TUpdatedAt): Boolean;
procedure RetrieveGroupsFields(const AFields: TJSONArray);
function RetrieveGroupsNames: TArray<string>;
function RetrieveUserGroups(const AUserID: string): TArray<string>;
// Installations
function CreateAndroidInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
function CreateAndroidInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject; overload;
function CreateIOSInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject; overload;
function CreateIOSInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject; overload;
procedure UploadInstallation(const AJSON: TJSONObject; out ANewObject: TInstallation);
procedure UpdateInstallation(const AInstallationID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
function DeleteInstallation(const AInstallationID: string): Boolean; overload;
procedure QueryInstallations(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryInstallations(const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TInstallation>); overload;
function RetrieveInstallation(const AInstallationID: string; out AFoundInstallation: TInstallation;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveInstallation(const AInstallationID: string; AProc: TRetrieveInstallationProc): Boolean; overload;
function RetrieveInstallation(const AInstallation: TInstallation; out AFoundInstallation: TInstallation;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveInstallation(const AInstallation: TInstallation; AProc: TRetrieveInstallationProc): Boolean; overload;
function RetrieveInstallationsChannelNames: TArray<string>;
procedure RetrieveInstallationsFields(const AFields: TJSONArray);
// Push
procedure PushBroadcast(const AData: TJSONObject); overload;
procedure PushBroadcast(const AData: TJSONObject; out AStatus: TPushStatus); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject; out AStatus: TPushStatus); overload;
procedure PushToChannels(const AData: TJSONObject; const AChannels: array of string); overload;
procedure PushToChannels(const AData: TJSONObject; const AChannels: array of string; out AStatus: TPushStatus); overload;
procedure PushWhere(const AData: TJSONObject; const AWhere: TJSONObject); overload;
procedure PushWhere(const AData: TJSONObject; const AWhere: TJSONObject; out AStatus: TPushStatus); overload;
// Edgemodules
procedure RegisterModule(const AName, AProtocol, AProtocolProps: string; const ADetails: TJSONObject;
const AResources: TJSONArray; out AModule: TModule); overload;
procedure RegisterModule(const AModuleName, AProtocol, AProtocolProps: string; const ADetails: TJSONObject; const Resources: TResourceList; out AModule: TModule); overload;
function UnregisterModule(const AModuleID: string): Boolean;
procedure QueryModules(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryModules(const AQuery: array of string;
const AJSONArray: TJSONArray; out AModules: TArray<TModule>); overload;
procedure UpdateModule(const AModuleID, AModuleName, AProtocol, AProtocolProps: string; const AJSONObject: TJSONObject; const AResources: TJSONArray; out AUpdatedAt: TUpdatedAt); overload;
procedure UpdateModule(const AModuleID: string; const AJSONObject: TJSONObject; const AResources: TJSONArray; out AUpdatedAt: TUpdatedAt); overload;
function RetrieveModule(const AModuleID: string; out AFoundModule: TModule;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveModule(const AModuleID: string; AProc: TRetrieveModuleProc): Boolean; overload;
function RetrieveModule(const AModule: TModule; out AFoundModule: TModule;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveModule(const AModule: TModule; AProc: TRetrieveModuleProc): Boolean; overload;
procedure RetrieveModulesFields(const AFields: TJSONArray);
function QueryModuleName(const AModuleName: string; AProc: TQueryModuleNameProc): Boolean; overload;
function QueryModuleName(const AModuleName: string; out AModule: TModule;
const AJSON: TJSONArray = nil): Boolean; overload;
// Edgemodule Resources
function UnregisterModuleResource(const AModuleID, AName: string): Boolean;
procedure QueryModuleResources(const AModuleID: string; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryModuleResources(const AModuleID: string; const AQuery: array of string; const AJSONArray: TJSONArray;
out AResources: TArray<TModuleResource>); overload;
procedure UpdateModuleResource(const AModuleID, AResourceName: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
function RetrieveModuleResource(const AModuleID, AResourceName: string; out AFoundResource: TModuleResource;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveModuleResource(const AModuleID, AResourceName: string; AProc: TRetrieveModuleResourceProc): Boolean; overload;
function RetrieveModuleResource(const AResource: TModuleResource; out AFoundResource: TModuleResource;
const AJSON: TJSONArray = nil): Boolean; overload;
function RetrieveModuleResource(const AResource: TModuleResource; AProc: TRetrieveModuleResourceProc): Boolean; overload;
procedure RetrieveModuleResourcesFields(const AFields: TJSONArray);
procedure Login(const ASessionAuthToken: string); overload;
procedure Login(const ALogin: TLogin); overload;
procedure Logout;
property LoggedIn: Boolean read GetLoggedIn;
property Authentication: TAuthentication read FAuthentication
write FAuthentication;
property DefaultAuthentication: TDefaultAuthentication
read FDefaultAuthentication write FDefaultAuthentication;
property Response: TRESTResponse read FResponse;
property ConnectionInfo: TConnectionInfo read FConnectionInfo write SetConnectionInfo;
end;
EEMSClientAPIError = class(Exception);
EEMSClientHTTPError = class(EEMSClientAPIError)
public type
TCodes = record
const BadRequest = 400;
const NotFound = 404;
const Duplicate = 409; // Duplicate
const Unauthorized = 401; // Don't know who you are
const Forbidden = 403; // I know who you are but not allowed
end;
private
FError: string;
FDescription: string;
FCode: Integer;
public
constructor Create(ACode: Integer; const AError: string; const ADescription: string = ''); overload;
property Code: Integer read FCode;
property Error: string read FError;
property Description: string read FDescription;
end;
EEMSClientHTTPBadRequest = class(EEMSClientHTTPError);
EEMSClientHTTPNotFound = class(EEMSClientHTTPError);
EEMSClientHTTPDuplicate = class(EEMSClientHTTPError);
EEMSClientHTTPUnauthorized = class(EEMSClientHTTPError);
EEMSClientHTTPForbidden = class(EEMSClientHTTPError);
implementation
uses
{$IFDEF MACOS}
Macapi.CoreFoundation,
{$ENDIF}
System.Rtti, System.TypInfo,
REST.JSON.Types,
REST.Consts, REST.Backend.EMSConsts;
procedure CheckUserID(const AObjectID: string);
begin
if AObjectID = '' then
raise EEMSClientAPIError.Create(sUserIDRequired);
end;
procedure CheckGroupName(const AGroupName: string);
begin
if AGroupName = '' then
raise EEMSClientAPIError.Create(sGroupNameRequired);
end;
procedure CheckInstallationID(const AInstallationID: string);
begin
if AInstallationID = '' then
raise EEMSClientAPIError.Create(sInstallationIDRequired);
end;
procedure CheckAuthToken(const AAuthToken: string);
begin
if AAuthToken = '' then
raise EEMSClientAPIError.Create(sAuthTokenRequired);
end;
procedure CheckJSONObject(const AJSON: TJSONObject);
begin
if AJSON = nil then
raise EEMSClientAPIError.Create(sJSONObjectRequired);
end;
procedure CheckMasterSecret(const AMasterKey: string);
begin
if AMasterKey = '' then
raise EEMSClientAPIError.Create(sMasterSecretRequired);
end;
procedure CheckSessionID(const SessionID: string);
begin
if SessionID = '' then
raise EEMSClientAPIError.Create(sSessionIDRequired);
end;
procedure CheckModuleID(const AModuleID: string);
begin
if AModuleID = '' then
raise EEMSClientAPIError.Create(sModuleIDRequired);
end;
procedure CheckResourceName(const AName: string);
begin
if AName = '' then
raise EEMSClientAPIError.Create(sResourceNameRequired);
end;
{ TEMSClientAPI }
// GET /version
procedure TEMSClientAPI.AppHandshake(const AJSONArray: TJSONArray);
begin
AppHandshake(
procedure(const AJSON: TJSONObject)
begin
if Assigned(AJSONArray) then
AJSONArray.AddElement(AJSON.Clone as TJSONObject);
end);
end;
procedure TEMSClientAPI.AppHandshake(const AProc: TAppHandshakeProc);
begin
FRequest.ResetToDefaults;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := 'version';
DoAddAuthParameters;
FRequest.Execute;
CheckForResponseError;
if Assigned(AProc) then
AProc(FRequest.Response.JSONValue as TJSONObject);
end;
procedure TEMSClientAPI.ApplyConnectionInfo;
begin
ApplyConnectionInfo(FRESTClient);
end;
procedure TEMSClientAPI.ApplyConnectionInfo(const AClient: TCustomRESTClient);
begin
AClient.BaseURL := FConnectionInfo.BaseURL;
AClient.Params.AddHeader(THeaderNames.ApiVersion,
FConnectionInfo.ApiVersion);
AClient.Params.AddHeader(THeaderNames.ApplicationId,
FConnectionInfo.ApplicationId);
AClient.ProxyPort := FConnectionInfo.ProxyPort;
AClient.ProxyPassword := FConnectionInfo.ProxyPassword;
AClient.ProxyUsername := FConnectionInfo.ProxyUsername;
AClient.ProxyServer := FConnectionInfo.ProxyServer;
AClient.OnValidateCertificate := FConnectionInfo.OnValidateCertificate;
end;
procedure TEMSClientAPI.AddMasterKey(const ARequest: TCustomRESTRequest; const AKey: string);
begin
CheckMasterSecret(AKey);
AddAuthHeader(ARequest, THeaderNames.MasterSecret, AKey);
end;
procedure TEMSClientAPI.AddSessionToken(const ARequest: TCustomRESTRequest; const ASessionToken: string);
begin
CheckSessionID(ASessionToken);
AddAuthHeader(ARequest, THeaderNames.SessionToken, ASessionToken);
end;
procedure TEMSClientAPI.AddTenantId(const ARequest: TCustomRESTRequest;
const AKey: string);
begin
if not AKey.IsEmpty then
ARequest.AddParameter(THeaderNames.TenantId, AKey, pkHTTPHEADER)
end;
procedure TEMSClientApi.AddAuthHeader(const ARequest: TCustomRESTRequest; const AKey, AValue: string);
begin
if AValue <> '' then
ARequest.AddAuthParameter(AKey, AValue, TRESTRequestParameterKind.pkHTTPHEADER,
[poTransient])
end;
procedure TEMSClientAPI.AddAppSecret(const ARequest: TCustomRESTRequest; const AKey: string);
begin
AddAuthHeader(ARequest, THeaderNames.AppSecret, AKey);
end;
function TEMSClientAPI.GetActualAuthentication: TAuthentication;
var
LAuthentication: TAuthentication;
begin
LAuthentication := FAuthentication;
if LAuthentication = TAuthentication.Default then
case FDefaultAuthentication of
TDefaultAuthentication.MasterSecret:
LAuthentication := TAuthentication.MasterSecret;
TDefaultAuthentication.AppSecret:
LAuthentication := TAuthentication.AppSecret;
TEMSClientAPI.TDefaultAuthentication.Session:
LAuthentication := TAuthentication.Session;
TEMSClientAPI.TDefaultAuthentication.None:
LAuthentication := TAuthentication.None;
else
Assert(False);
end;
Result := LAuthentication;
end;
procedure TEMSClientAPI.DoAddAuthParameters;
begin
AddAuthParameters(FRequest);
end;
procedure TEMSClientAPI.AddAuthParameters(const ARequest: TCustomRESTRequest);
var
LAuthentication: TAuthentication;
begin
LAuthentication := GetActualAuthentication;
DoAddAuthParameters(ARequest, LAuthentication);
end;
procedure TEMSClientAPI.DoAddAuthParameters(AAuthentication: TAuthentication);
begin
DoAddAuthParameters(Request, AAuthentication);
end;
procedure TEMSClientAPI.DoAddAuthParameters(const ARequest: TCustomRESTRequest;
AAuthentication: TAuthentication);
begin
case AAuthentication of
TEMSClientAPI.TAuthentication.AppSecret:
AddAppSecret(ARequest, ConnectionInfo.AppSecret);
TEMSClientAPI.TAuthentication.MasterSecret:
AddMasterKey(ARequest, ConnectionInfo.MasterSecret);
TEMSClientAPI.TAuthentication.Session:
begin
if (FSessionAuthToken <> '') or not FInLogin then
AddSessionToken(ARequest, FSessionAuthToken);
if ConnectionInfo.AppSecret <> '' then
// Also add app secret
AddAppSecret(ARequest, ConnectionInfo.AppSecret);
end;
TEMSClientAPI.TAuthentication.None:
;
else
Assert(False);
end;
AddTenantId(ARequest, ConnectionInfo.TenantId);
AddAuthHeader(ARequest, THeaderNames.TenantSecret, ConnectionInfo.TenantSecret);
end;
procedure TEMSClientAPI.CreateGroup(const AGroupName: string;
const AGroupFields: TJSONObject; out AGroup: TGroup);
var
LJSON: TJSONObject;
LResponse: TJSONObject;
begin
if AGroupFields <> nil then
LJSON := AGroupFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.GroupName, AGroupName);
FRequest.AddBody(LJSON);
AddResource(TSegmentNames.Groups, LJSON);
finally
LJSON.Free;
end;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AGroup := GroupFromObject(AGroupName, LResponse);
end;
procedure TEMSClientAPI.CheckForResponseError;
begin
CheckForResponseError(FRequest.Response);
end;
constructor TEMSClientAPI.Create;
begin
Create(nil);
end;
function TEMSClientAPI.CreateHTTPException(const AResponse: TCustomRESTResponse): EEMSClientHTTPError;
begin
case AResponse.StatusCode of
EEMSClientHTTPError.TCodes.BadRequest:
Result := CreateHTTPException(AResponse, EEMSClientHTTPBadRequest);
EEMSClientHTTPError.TCodes.NotFound:
Result := CreateHTTPException(AResponse, EEMSClientHTTPNotFound);
EEMSClientHTTPError.TCodes.Duplicate:
Result := CreateHTTPException(AResponse, EEMSClientHTTPDuplicate);
EEMSClientHTTPError.TCodes.Unauthorized:
Result := CreateHTTPException(AResponse, EEMSClientHTTPUnauthorized);
EEMSClientHTTPError.TCodes.Forbidden:
Result := CreateHTTPException(AResponse, EEMSClientHTTPForbidden);
else
Result := CreateHTTPException(AResponse, EEMSClientHTTPError);
end;
end;
function TEMSClientAPI.CreateHTTPException(const AResponse: TCustomRESTResponse;
const AClass: TEMSClientHTTPErrorClass): EEMSClientHTTPError;
var
LError: string;
LDescription: string;
LJSONError: TJSONValue;
LJSONDescription: TJSONValue;
LCode: Integer;
begin
LCode := AResponse.StatusCode;
if AResponse.JSONValue <> nil then
begin
LJSONError := (AResponse.JSONValue as TJSONObject)
.GetValue(TJSONNames.Error);
if LJSONError <> nil then
LError := LJSONError.Value;
LJSONDescription := (AResponse.JSONValue as TJSONObject)
.GetValue(TJSONNames.Description);
if LJSONDescription <> nil then
LDescription := LJSONDescription.Value;
if (LJSONError <> nil) and (LJSONDescription <> nil) then
Result := AClass.Create(LCode, LError, LDescription)
else if LJSONDescription <> nil then
Result := AClass.Create(LCode, LDescription)
else if LJSONError <> nil then
Result := AClass.Create(LCode, LError)
else
Result := AClass.Create(LCode, AResponse.Content.Substring(0, 100));
end
else if AResponse.Status.ClientError then
Result := AClass.Create(AResponse.StatusCode, AResponse.StatusText)
else
Result := AClass.Create(LCode, AResponse.Content.Substring(0, 100));
end;
procedure TEMSClientAPI.CheckForResponseError(const AResponse: TCustomRESTResponse);
begin
if AResponse.StatusCode >= 300 then
raise CreateHTTPException(AResponse);
end;
procedure TEMSClientAPI.CheckForResponseError(const AResponse: TCustomRESTResponse;
const AValidStatusCodes: array of Integer);
var
LCode: Integer;
LResponseCode: Integer;
begin
LResponseCode := AResponse.StatusCode;
for LCode in AValidStatusCodes do
if LResponseCode = LCode then
Exit; // Code is valid, exit with no exception
CheckForResponseError(AResponse);
end;
procedure TEMSClientAPI.CheckForResponseError(AValidStatusCodes: array of Integer);
begin
CheckForResponseError(FRequest.Response, AValidStatusCodes);
end;
constructor TEMSClientAPI.Create(AOwner: TComponent;
const AResponse: TRESTResponse);
begin
inherited Create(AOwner);
FRESTClient := TRESTClient.Create(nil);
FRESTClient.SynchronizedEvents := False;
FRequest := TRESTRequest.Create(nil);
FRequest.SynchronizedEvents := False;
FRESTClient.RaiseExceptionOn500 := False;
FRequest.Client := FRESTClient;
FOwnsResponse := AResponse = nil;
if FOwnsResponse then
FResponse := TRESTResponse.Create(nil)
else
FResponse := AResponse;
FRequest.Response := FResponse;
ApplyConnectionInfo;
end;
destructor TEMSClientAPI.Destroy;
begin
FRESTClient.Free;
FRequest.Free;
if FOwnsResponse then
FResponse.Free;
inherited;
end;
function TEMSClientAPI.GetLoggedIn: Boolean;
begin
Result := FSessionAuthToken <> '';
end;
procedure TEMSClientAPI.Login(const ASessionAuthToken: string);
begin
CheckSessionID(ASessionAuthToken);
FSessionAuthToken := ASessionAuthToken;
FAuthentication := TAuthentication.Session;
end;
procedure TEMSClientAPI.Login(const ALogin: TLogin);
begin
Login(ALogin.AuthToken);
end;
function TEMSClientAPI.LoginFromObject(const AUserName: string;
const AJSONObject: TJSONObject): TLogin;
var
LUser: TUser;
LSessionToken: string;
begin
LUser := UserFromObject(AUserName, AJSONObject);
if not AJSONObject.TryGetValue<string>(TJSONNames.SessionToken, LSessionToken) then
raise EEMSClientAPIError.Create(sSessionTokenExpected);
Assert(LSessionToken <> '');
Result := TLogin.Create(LSessionToken, LUser);
end;
function TEMSClientAPI.UnregisterModule(const AModuleID: string): Boolean;
begin
Result := DeleteResource(TSegmentNames.Modules, AModuleID);
end;
function TEMSClientAPI.UnregisterModuleResource(const AModuleID, AName: string): Boolean;
begin
Result := DeleteResource(TSegmentNames.Modules + '/{mname}/' + TSegmentNames.Resources, // do not localize
AName,
procedure begin FRequest.AddParameter('mname', AModuleID, TRESTRequestParameterKind.pkURLSEGMENT); end); // Do not localize
end;
function TEMSClientAPI.UpdatedAtFromObject(const AJSONObject: TJSONObject): TUpdatedAt;
var
LUpdatedAt: TDateTime;
begin
if AJSONObject.GetValue(TJSONNames.MetaUpdated) <> nil then
LUpdatedAt := TJSONDates.AsDateTime
(AJSONObject.GetValue(TJSONNames.MetaUpdated), TJSONDates.TFormat.ISO8601,
DateTimeIsUTC)
else
LUpdatedAt := 0;
Result := TUpdatedAt.Create(LUpdatedAt);
end;
procedure TEMSClientAPI.PutResource(const AResource, AID: string; const AJSON: TJSONObject; const AAddParameters: TProc);
var
LJSON: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPUT;
FRequest.Resource := AResource + '/{id}'; // do not localize
FRequest.AddParameter('id', AID,
TRESTRequestParameterKind.pkURLSEGMENT); // Do not localize
if Assigned(AAddParameters) then
AAddParameters();
if AJSON <> nil then
FRequest.AddBody(AJSON)
else
begin
LJSON := TJSONObject.Create;
try
FRequest.AddBody(LJSON);
finally
LJSON.Free;
end;
end;
FRequest.Execute;
CheckForResponseError;
end;
procedure TEMSClientAPI.UpdateGroup(const AGroupName: string;
const AGroupObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
CheckGroupName(AGroupName);
PutResource(TSegmentNames.Groups, AGroupName, AGroupObject);
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUpdatedAt := UpdatedAtFromObject(LResponse);
end;
procedure TEMSClientAPI.UpdateGroup(const AGroup: TGroup;
const AGroupObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
begin
UpdateGroup(AGroup.GroupName, AGroupObject, AUpdatedAt);
end;
procedure TEMSClientAPI.UpdateUser(const AUser: TUser;
const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
begin
UpdateUser(AUser.UserID, AUserObject, AUpdatedAt);
end;
function TEMSClientAPI.MetaDataFromObject(const AJSONObject: TJSONObject; out ACreatedAt, AUpdatedAt: TDateTime; out ACreator: string): Boolean;
var
LInnerJSONObject: TJSONObject;
LJSONValue: TJSONValue;
begin
Result := AJSONObject.TryGetValue<TJSONObject>(TJSONNames.MetaData, LInnerJSONObject);
if Result then
begin
ACreatedAt := 0;
AUpdatedAt := 0;
if LInnerJSONObject.TryGetValue<TJSONValue>(TJSONNames.MetaCreated, LJSONValue) then
ACreatedAt := TJSONDates.AsDateTime
(LJSONValue,
TJSONDates.TFormat.ISO8601, DateTimeIsUTC);
if LInnerJSONObject.TryGetValue<TJSONValue>(TJSONNames.MetaUpdated, LJSONValue) then
AUpdatedAt := TJSONDates.AsDateTime
(LJSONValue,
TJSONDates.TFormat.ISO8601, DateTimeIsUTC);
ACreator := LInnerJSONObject.GetValue(TJSONNames.MetaCreator, '');
end;
end;
function TEMSClientAPI.UserFromObject(const AUserName: string;
const AJSONObject: TJSONObject): TUser;
var
LCreatedAt, LUpdatedAt: TDateTime;
LCreator: string;
begin
Result := TUser.Create(AUserName);
Result.FUserID := AJSONObject.GetValue<string>(TJSONNames.UserID, '');
Assert(Result.FUserID <> '');
if MetaDataFromObject(AJSONObject, LCreatedAt, LUpdatedAt, LCreator) then
begin
Result.FCreatedAt := LCreatedAt;
Result.FUpdatedAt := LUpdatedAt;
Result.FCreator := LCreator;
end;
end;
function TEMSClientAPI.UserFromObject(const AJSONObject: TJSONObject): TUser;
var
LUserName: string;
begin
if AJSONObject.GetValue(TJSONNames.UserName) <> nil then
LUserName := AJSONObject.GetValue(TJSONNames.UserName).Value;
Result := UserFromObject(LUserName, AJSONObject);
end;
function TEMSClientAPI.GroupFromObject(const AJSONObject: TJSONObject): TGroup;
var
LGroupName: string;
begin
LGroupName := AJSONObject.GetValue<string>(TJSONNames.GroupName, '');
Assert(LGroupName <> '');
Result := GroupFromObject(LGroupName, AJSONObject);
end;
function TEMSClientAPI.PushStatusFromObject(const AJSONObject: TJSONObject): TPushStatus;
var
LIOS: Integer;
LAndroid: Integer;
begin
LAndroid := AJSONObject.GetValue<Integer>('queued.android', 0);
LIOS := AJSONObject.GetValue<Integer>('queued.ios', 0);
Result := TPushStatus.Create(LIOS, LAndroid);
end;
function TEMSClientAPI.GroupFromObject(const AGroupName: string;
const AJSONObject: TJSONObject): TGroup;
var
LCreatedAt, LUpdatedAt: TDateTime;
LCreator: string;
begin
Result := TGroup.Create(AGroupName);
if MetaDataFromObject(AJSONObject, LCreatedAt, LUpdatedAt, LCreator) then
begin
Result.FCreatedAt := LCreatedAt;
Result.FUpdatedAt := LUpdatedAt;
Result.FCreator := LCreator;
end;
end;
function TEMSClientAPI.InstallationFromObject(const AJSONObject: TJSONObject): TInstallation;
var
LInstallationID: string;
begin
LInstallationID := AJSONObject.GetValue<string>(TJSONNames.InstallationID, '');
Assert(LInstallationID <> '');
Result := InstallationFromObject(LInstallationID, AJSONObject);
end;
function TEMSClientAPI.InstallationFromObject(const AInstallationID: string;
const AJSONObject: TJSONObject): TInstallation;
var
LCreatedAt, LUpdatedAt: TDateTime;
LCreator: string;
begin
Result := TInstallation.Create(AInstallationID);
if MetaDataFromObject(AJSONObject, LCreatedAt, LUpdatedAt, LCreator) then
begin
Result.FCreatedAt := LCreatedAt;
Result.FUpdatedAt := LUpdatedAt;
Result.FCreator := LCreator;
end;
end;
procedure TEMSClientAPI.PushBody(const AMessage: TJSONObject; out AStatus: TPushStatus);
var
LResponse: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := TSegmentNames.Push;
FRequest.AddBody(AMessage);
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AStatus := PushStatusFromObject(LResponse);
end;
procedure TEMSClientAPI.PushBody(const AMessage: TJSONObject);
var
LStatus: TPushStatus;
begin
PushBody(AMessage, LStatus);
end;
//curl -X POST \
// -H "Content-Type: application/json" \
// -d '{
// "where": {
// "devicetype": "ios,android",
/// },
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
procedure TEMSClientAPI.PushBroadcast(const AData: TJSONObject);
begin
PushToTarget(AData, nil);
end;
procedure TEMSClientAPI.PushBroadcast(const AData: TJSONObject; out AStatus: TPushStatus);
begin
PushToTarget(AData, nil, AStatus);
end;
procedure TEMSClientAPI.PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject);
var
LStatus: TPushStatus;
begin
PushToTarget(AData, ATarget, LStatus);
end;
procedure TEMSClientAPI.PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject; out AStatus: TPushStatus);
var
LJSON: TJSONObject;
LPair: TJSONPair;
begin
LJSON := TJSONObject.Create;
try
if AData <> nil then
LJSON.AddPair(TJSONNames.PushData, AData.Clone as TJSONObject); // Do not localize
if ATarget <> nil then
for LPair in ATarget do
// such as "where" and "channels"
LJSON.AddPair(LPair.Clone as TJSONPair);
PushBody(LJSON, AStatus);
finally
LJSON.Free;
end;
end;
//curl -X POST \
// -H "Content-Type: application/json" \
// -d '{
// "channels": [
// "Giants",
// "Mets"
// ],
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
procedure TEMSClientAPI.PushToChannels(const AData: TJSONObject; const AChannels: array of string; out AStatus: TPushStatus);
var
LJSON: TJSONObject;
LChannels: TJSONArray;
S: string;
begin
if Length(AChannels) = 0 then
raise EEMSClientAPIError.Create(sChannelNamesExpected);
LJSON := TJSONObject.Create;
try
LChannels := TJSONArray.Create;
for S in AChannels do
LChannels.Add(S);
LJSON.AddPair(TJSONNames.PushChannels, LChannels); // Do not localize
PushToTarget(AData, LJSON, AStatus);
finally
LJSON.Free;
end;
end;
procedure TEMSClientAPI.PushToChannels(const AData: TJSONObject; const AChannels: array of string);
var
LStatus: TPushStatus;
begin
PushToChannels(AData, AChannels, LStatus);
end;
//curl -X POST \
// -H "Content-Type: application/json" \
// -d '{
// "where": {
// {"deviceType":{"$in":["ios", "android"]}}
// },
// "data": {
// "alert": "The Giants won against the Mets 2-3."
// }
// }' \
procedure TEMSClientAPI.PushWhere(const AData: TJSONObject; const AWhere: TJSONObject; out AStatus: TPushStatus);
var
LJSON: TJSONObject;
begin
LJSON := TJSONObject.Create;
try
if AWhere <> nil then
LJSON.AddPair(TJSONNames.PushWhere, AWhere.Clone as TJSONObject); // Do not localize
if AData <> nil then
LJSON.AddPair(TJSONNames.PushData, AData.Clone as TJSONObject); // Do not localize
PushBody(LJSON, AStatus);
finally
LJSON.Free;
end;
end;
procedure TEMSClientAPI.PushWhere(const AData: TJSONObject; const AWhere: TJSONObject);
var
LStatus: TPushStatus;
begin
PushWhere(AData, AWhere, LStatus);
end;
procedure TEMSClientAPI.SetConnectionInfo(const Value: TConnectionInfo);
begin
FConnectionInfo := Value;
ApplyConnectionInfo;
end;
procedure TEMSClientAPI.QueryResource(const AResource: string;
const AQuery: array of string; const AJSONArray: TJSONArray; AReset: Boolean; const AAddParameters: TProc);
var
LRoot: TJSONArray;
S: String;
I: Integer;
LTrim: string;
LJSONValue: TJSONValue;
begin
if AReset then
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := AResource;
if Assigned(AAddParameters) then
AAddParameters();
for S in AQuery do
begin
LTrim := Trim(S);
if LTrim = '' then
continue;
I := LTrim.IndexOf('=');
if I > 0 then
FRequest.AddParameter(S.Substring(0, I).Trim, S.Substring(I + 1).Trim);
end;
FRequest.Execute;
CheckForResponseError;
if AJSONArray <> nil then
begin
LRoot := FRequest.Response.JSONValue as TJSONArray;
for LJSONValue in LRoot do
AJSONArray.AddElement(TJSONValue(LJSONValue.Clone))
end;
end;
function TEMSClientAPI.DeleteGroup(const AGroup: TGroup): Boolean;
begin
Result := DeleteGroup(AGroup.GroupName);
end;
function TEMSClientAPI.DeleteResource(const AResource, AID: string; const AAddParameters: TProc): Boolean;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmDELETE;
FRequest.Resource := AResource + '/{id}'; // do not localize
FRequest.AddParameter('id', AID,
TRESTRequestParameterKind.pkURLSEGMENT); // Do not localize
if Assigned(AAddParameters) then
AAddParameters();
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.NotFound]);
Result := FRequest.Response.StatusCode <> EEMSClientHTTPError.TCodes.NotFound
end;
function TEMSClientAPI.DeleteGroup(const AGroupName: string): Boolean;
begin
CheckGroupName(AGroupName);
Result := DeleteResource(TSegmentNames.Groups, AGroupName);
end;
function TEMSClientAPI.DeleteUser(const AUser: TUser): Boolean;
begin
Result := DeleteUser(AUser.FUserID);
end;
function TEMSClientAPI.DeleteUser(const AObjectID: string): Boolean;
begin
CheckUserID(AObjectID);
Result := DeleteResource(TSegmentNames.Users, AObjectID);
end;
procedure TEMSClientAPI.UpdateUser(const AObjectID: string;
const AUserObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
LJSON: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmPUT;
FRequest.Resource := TSegmentNames.Users + '/{userId}'; // do not localize
FRequest.AddParameter('userId', AObjectID,
TRESTRequestParameterKind.pkURLSEGMENT); // Do not localize
if AUserObject <> nil then
FRequest.AddBody(AUserObject)
else
begin
LJSON := TJSONObject.Create;
try
FRequest.AddBody(LJSON)
finally
LJSON.Free;
end;
end;
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUpdatedAt := UpdatedAtFromObject(LResponse);
end;
procedure TEMSClientAPI.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray);
var
LResource: string;
begin
LResource := TSegmentNames.Users + '/';
QueryResource(LResource, AQuery, AJSONArray, True);
end;
procedure TEMSClientAPI.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray; out AUsers: TArray<TUser>);
var
LJSONValue: TJSONValue;
LJSONArray: TJSONArray;
LList: TList<TUser>;
LUser: TUser;
LResource: string;
begin
LList := nil;
LResource := TSegmentNames.Users + '/';
if AJSONArray = nil then
LJSONArray := TJSONArray.Create
else
LJSONArray := AJSONArray;
try
QueryResource(LResource, AQuery, LJSONArray, True);
LList := TList<TUser>.Create;
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LUser := UserFromObject(TJSONObject(LJSONValue));
LList.Add(LUser);
end
else
raise EEMSClientAPIError.Create(sJSONObjectExpected);
end;
AUsers := LList.ToArray;
finally
LList.Free;
if LJSONArray <> AJSONArray then
LJSONArray.Free;
end;
end;
function TEMSClientAPI.MakeLoginResource(const ASegmentName: string): string;
begin
if FConnectionInfo.LoginResource <> '' then
Result := FConnectionInfo.LoginResource + '/' + ASegmentName
else
Result := TSegmentNames.Users + '/' + ASegmentName;
end;
function TEMSClientAPI.ModuleFromObject(const AJSONObject: TJSONObject): TModule;
var
LModuleID: string;
begin
LModuleID := AJSONObject.GetValue<string>(TJSONNames.ModuleID, '');
Assert(LModuleID <> '');
Result := ModuleFromObject(LModuleID, AJSONObject);
end;
function TEMSClientAPI.ModuleFromObject(const AModuleID: string; const AJSONObject: TJSONObject): TModule;
var
LModuleName, LProtocol, LProtocolProps: string;
LCreatedAt, LUpdatedAt: TDateTime;
LCreator: string;
begin
AJSONObject.TryGetValue<string>(TJSONNames.ModuleName, LModuleName);
Result := TModule.Create(AModuleID, LModuleName);
if AJSONObject.TryGetValue<string>(TJSONNames.Protocol, LProtocol) then
Result.FProtocol := LProtocol;
if AJSONObject.TryGetValue<string>(TJSONNames.ProtocolProps, LProtocolProps) then
Result.FProtocolProps := LProtocolProps;
if MetaDataFromObject(AJSONObject, LCreatedAt, LUpdatedAt, LCreator) then
begin
Result.FCreatedAt := LCreatedAt;
Result.FUpdatedAt := LUpdatedAt;
Result.FCreator := LCreator;
end;
end;
function TEMSClientAPI.ResourceFromObject(
const AJSONObject: TJSONObject): TModuleResource;
var
LModuleName, LModuleID: string;
LResourceName: string;
LCreatedAt, LUpdatedAt: TDateTime;
LCreator: string;
begin
AJSONObject.TryGetValue<string>(TJSONNames.ResourceName, LResourceName);
AJSONObject.TryGetValue<string>(TJSONNames.ModuleName, LModuleName);
AJSONObject.TryGetValue<string>(TJSONNames.ResourceModuleID, LModuleID);
Result := TModuleResource.Create(LResourceName, LModuleID, LModuleName);
if MetaDataFromObject(AJSONObject, LCreatedAt, LUpdatedAt, LCreator) then
begin
Result.FCreatedAt := LCreatedAt;
Result.FUpdatedAt := LUpdatedAt;
Result.FCreator := LCreator;
end;
end;
procedure TEMSClientAPI.LoginUser(const AUserName, APassword: string;
out ALogin: TLogin; const AJSON: TJSONArray; AProc: TLoginProc);
var
LJSON: TJSONObject;
LResponse: TJSONObject;
begin
FInLogin := True;
try
FRequest.ResetToDefaults;
DoAddAuthParameters; // (TAuthentication.AppSecret); // Always use AppSecret
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := MakeLoginResource(TSegmentNames.Login);
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
FRequest.AddBody(LJSON);
finally
LJSON.Free;
end;
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONObject;
ALogin := LoginFromObject(AUserName, LResponse);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(ALogin, LResponse);
finally
FInLogin := False;
end;
end;
procedure TEMSClientAPI.LoginUser(const AUserName, APassword: string;
out ALogin: TLogin; const AJSON: TJSONArray);
begin
LoginUser(AUserName, APassword, ALogin, AJSON, nil);
end;
procedure TEMSClientAPI.LoginUser(const AUserName, APassword: string;
AProc: TLoginProc);
var
LLogin: TLogin;
begin
LoginUser(AUserName, APassword, LLogin, nil, AProc);
end;
procedure TEMSClientAPI.QueryGroups(const AQuery: array of string;
const AJSONArray: TJSONArray);
var
LResource: string;
begin
LResource := TSegmentNames.Groups + '/';
QueryResource(LResource, AQuery, AJSONArray, True);
end;
procedure TEMSClientAPI.QueryGroups(const AQuery: array of string;
const AJSONArray: TJSONArray; out AGroups: TArray<TGroup>);
var
LJSONValue: TJSONValue;
LList: TList<TGroup>;
LGroup: TGroup;
LResource: string;
LJSONArray: TJSONArray;
begin
LList := nil;
LResource := TSegmentNames.Groups + '/';
if AJSONArray = nil then
LJSONArray := TJSONArray.Create
else
LJSONArray := AJSONArray;
try
QueryResource(LResource, AQuery, LJSONArray, True);
LList := TList<TGroup>.Create;
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LGroup := GroupFromObject(TJSONObject(LJSONValue));
LList.Add(LGroup);
end
else
raise EEMSClientAPIError.Create(sJSONObjectExpected);
end;
AGroups := LList.ToArray;
finally
LList.Free;
if LJSONArray <> AJSONArray then
LJSONArray.Free;
end;
end;
procedure TEMSClientAPI.Logout;
begin
FSessionAuthToken := '';
if FAuthentication = TAuthentication.Session then
FAuthentication := TAuthentication.Default;
end;
procedure TEMSClientAPI.LogoutUser;
begin
FRequest.ResetToDefaults;
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := TSegmentNames.Users + '/' + TSegmentNames.Logout;
DoAddAuthParameters; // (TAuthentication.Session); // Required
try
FRequest.Execute;
CheckForResponseError;
except
on E: EEMSClientHTTPUnauthorized do
; // session expired, user deleted, etc
end;
FSessionAuthToken := ''; // No longer valid
end;
procedure TEMSClientAPI.SignupUser(const AUserName, APassword: string;
const AUserFields: TJSONObject; out ALogin: TLogin);
var
LJSON: TJSONObject;
LResponse: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters; //(TAuthentication.AppSecret); // Required
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := MakeLoginResource(TSegmentNames.Signup); // TSegmentNames.Users + '/' + TSegmentNames.Signup;
if AUserFields <> nil then
LJSON := AUserFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
FRequest.AddBody(LJSON);
finally
LJSON.Free;
end;
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.Duplicate]);
if FRequest.Response.StatusCode = EEMSClientHTTPError.TCodes.Duplicate then
raise CreateHTTPException(FRequest.Response);
LResponse := FRequest.Response.JSONValue as TJSONObject;
ALogin := LoginFromObject(AUserName, LResponse);
end;
procedure TEMSClientAPI.AddResource(const AResource: string; const AJSON: TJSONObject; const AAddParameters: TProc);
begin
FRequest.ResetToDefaults;
DoAddAuthParameters; //(TAuthentication.AppSecret); // Required
FRequest.Method := TRESTRequestMethod.rmPOST;
FRequest.Resource := AResource;
if Assigned(AAddParameters) then
AAddParameters();
FRequest.AddBody(AJSON);
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.Duplicate]);
if FRequest.Response.StatusCode = EEMSClientHTTPError.TCodes.Duplicate then
raise CreateHTTPException(FRequest.Response);
end;
// Add user but do not create a session
procedure TEMSClientAPI.AddUser(const AUserName, APassword: string;
const AUserFields: TJSONObject; out AUser: TUser);
var
LJSON: TJSONObject;
LResponse: TJSONObject;
begin
if AUserFields <> nil then
LJSON := AUserFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
AddResource(TSegmentNames.Users, LJSON);
// FRequest.AddBody(LJSON);
finally
LJSON.Free;
end;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUser := UserFromObject(AUserName, LResponse);
end;
function TEMSClientAPI.QueryUserName(const AUserName: string; out AUser: TUser;
const AJSON: TJSONArray; AProc: TQueryUserNameProc): Boolean;
var
LUsers: TJSONArray;
LUserObject: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
// Closing '/' required
FRequest.Resource := TSegmentNames.Users + '/';
FRequest.AddParameter(TQueryParamNames.Where,
TJSONObject.Create.AddPair(TJSONNames.UserName, TJSONString.Create(AUserName)));
FRequest.Execute;
CheckForResponseError;
LUsers := FRequest.Response.JSONValue as TJSONArray;
if LUsers.Count > 1 then
raise EEMSClientAPIError.Create(sOneUserExpected);
Result := LUsers.Count = 1;
if Result then
begin
LUserObject := LUsers.Items[0] as TJSONObject;
AUser := UserFromObject(LUserObject);
if Assigned(AJSON) then
AJSON.AddElement(LUserObject.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AUser, LUserObject);
end;
end;
function TEMSClientAPI.QueryUserName(const AUserName: string;
AProc: TQueryUserNameProc): Boolean;
var
LUser: TUser;
begin
Result := QueryUserName(AUserName, LUser, nil, AProc);
end;
function TEMSClientAPI.QueryUserName(const AUserName: string; out AUser: TUser;
const AJSON: TJSONArray): Boolean;
begin
Result := QueryUserName(AUserName, AUser, AJSON, nil);
end;
function TEMSClientAPI.RetrieveUser(const AObjectID: string; out AUser: TUser;
const AJSON: TJSONArray; AProc: TRetrieveUserProc): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckUserID(AObjectID);
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Users + '/{userId}'; // do not localize
FRequest.AddParameter('userId', AObjectID,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.NotFound]); // 404 = not found
if FRequest.Response.StatusCode <> EEMSClientHTTPError.TCodes.NotFound then
begin
Result := True;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUser := UserFromObject(LResponse);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AUser, LResponse);
end
end;
function TEMSClientAPI.RetrieveUser(const AObjectID: string;
AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveUser(AObjectID, LUser, nil, AProc);
end;
procedure TEMSClientAPI.RetrieveUsersFields(const AFields: TJSONArray);
begin
RetrieveFields(TSegmentNames.UsersFields, AFields);
end;
function TEMSClientAPI.RetrieveUsersNames: TArray<string>;
var
LUsers: TArray<TUser>;
LUser: TUser;
LSkip: Integer;
LResult: TList<string>;
begin
LResult := TList<string>.Create;
try
LSkip := 0;
while True do
begin
QueryUsers([Format('skip=%d', [LSkip]), 'limit=100'], nil, LUsers);
if Length(LUsers) = 0 then
break;
for LUser in LUsers do
LResult.Add(LUser.UserName);
Inc(LSkip, 100);
end;
Result := LResult.ToArray;
finally
LResult.Free;
end;
end;
function TEMSClientAPI.RetrieveUser(const AUser: TUser; out AFoundUser: TUser;
const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveUser(AUser.UserID, AFoundUser, AJSON, nil);
end;
function TEMSClientAPI.RetrieveUser(const AUser: TUser;
AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveUser(AUser.UserID, LUser, nil, AProc);
end;
function TEMSClientAPI.RetrieveUser(const AObjectID: string; out AUser: TUser;
const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveUser(AObjectID, AUser, AJSON, nil);
end;
function TEMSClientAPI.RetrieveCurrentUser(AProc: TRetrieveUserProc): Boolean;
var
LUser: TUser;
begin
Result := RetrieveUser(TSegmentNames.Me, LUser, nil, AProc);
end;
function TEMSClientAPI.RetrieveInstallationsChannelNames: TArray<string>;
var
LResponse: TJSONArray;
I: Integer;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.InstallationsChannels;
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONArray;
SetLength(Result, LResponse.Count);
for I := 0 to Length(Result) - 1 do
Result[I] := LResponse.Items[I].Value;
end;
procedure TEMSClientAPI.RetrieveFields(const AResourceName: string; const AFields: TJSONArray);
var
LResponse: TJSONArray;
LValue: TJSONValue;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := AResourceName;
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONArray;
for LValue in LResponse do
AFields.AddElement(LValue.Clone as TJSONValue);
end;
procedure TEMSClientAPI.RetrieveInstallationsFields(const AFields: TJSONArray);
begin
RetrieveFields(TSegmentNames.InstallationsFields, AFields);
end;
function TEMSClientAPI.RetrieveCurrentUser(out AUser: TUser;
const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveUser(TSegmentNames.Me, AUser, AJSON, nil);
end;
function TEMSClientAPI.RetrieveModule(const AModuleID: string;
out AModule: TModule; const AJSON: TJSONArray;
AProc: TRetrieveModuleProc): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckModuleID(AModuleID);
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Modules + '/{id}'; // do not localize
FRequest.AddParameter('id', AModuleID,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.NotFound]); // 404 = not found
if FRequest.Response.StatusCode <> EEMSClientHTTPError.TCodes.NotFound then
begin
Result := True;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AModule := ModuleFromObject(AModuleId, LResponse);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AModule, LResponse);
end
end;
function TEMSClientAPI.RetrieveModuleResource(const AModuleID, AResourceName: string;
out AResource: TModuleResource; const AJSON: TJSONArray;
AProc: TRetrieveModuleResourceProc): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckModuleID(AModuleID);
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Modules + '/{mname}/' + TSegmentNames.Resources + '/{name}'; // do not localize
FRequest.AddParameter('mname', AModuleID,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.AddParameter('name', AResourceName,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.NotFound]); // 404 = not found
if FRequest.Response.StatusCode <> EEMSClientHTTPError.TCodes.NotFound then
begin
Result := True;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AResource := ResourceFromObject(LResponse);
Assert(AResource.ResourceName = AResourceName);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AResource, LResponse);
end
end;
function TEMSClientAPI.RetrieveModuleResource(const AModuleID, AResourceName: string;
out AFoundResource: TModuleResource; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveModuleResource(AModuleID, AResourceName, AFoundResource, AJSON, nil);
end;
function TEMSClientAPI.RetrieveModule(const AModuleID: string;
out AFoundModule: TModule; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveModule(AModuleID, AFoundModule, AJSON, nil);
end;
function TEMSClientAPI.RetrieveGroup(const AGroupName: string;
out AGroup: TGroup; const AJSON: TJSONArray;
AProc: TRetrieveGroupProc): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckGroupName(AGroupName);
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Groups + '/{id}'; // do not localize
FRequest.AddParameter('id', AGroupName,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.Execute;
CheckForResponseError([EEMSClientHTTPError.TCodes.NotFound]); // 404 = not found
if FRequest.Response.StatusCode <> EEMSClientHTTPError.TCodes.NotFound then
begin
Result := True;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AGroup := GroupFromObject(LResponse);
if Assigned(AJSON) then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AGroup, LResponse);
end
end;
function TEMSClientAPI.RetrieveGroup(const AGroupName: string;
out AFoundGroup: TGroup; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveGroup(AGroupName, AFoundGroup, AJSON, nil);
end;
procedure TEMSClientAPI.AddUsersToGroup(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedAt: TUpdatedAt);
var
LJSONObject: TJSONObject;
LJSONArray: TJSONArray;
S: string;
begin
LJSONObject := nil;
try
if not RetrieveGroup(AGroupName,
procedure(const AGroup: TEMSClientAPI.TGroup; const AJSONObject: TJSONObject)
begin
LJSONObject := AJSONObject.Clone as TJSONObject;
end) then
raise EEMSClientAPIError.CreateFmt(sGroupNotFound, [AGroupName]);
if not LJSONObject.TryGetValue<TJSONArray>('users', LJSONArray) then
begin
LJSONArray := TJSONArray.Create;
LJSONObject.AddPair('users', LJSONArray);
end;
for S in AUsers do
LJSONArray.Add(S);
UpdateGroup(AGroupName, LJSONObject, AUpdatedAt);
finally
LJSONObject.Free;
end;
end;
procedure TEMSClientAPI.RegisterModule(const AName, AProtocol, AProtocolProps: string;
const ADetails: TJSONObject; const AResources: TJSONArray; out AModule: TModule);
var
LJSON: TJSONObject;
LResponse: TJSONObject;
begin
if ADetails <> nil then
LJSON := ADetails.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.ModuleName, AName);
LJSON.AddPair(TJSONNames.Protocol, AProtocol);
LJSON.AddPair(TJSONNames.ProtocolProps, AProtocolProps);
if AResources <> nil then
LJSON.AddPair(TJSONPair.Create(TJSONNames.Resources, TJSONValue(AResources.Clone)));
AddResource(TSegmentNames.Modules, LJSON);
// FRequest.AddBody(LJSON);
finally
LJSON.Free;
end;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AModule := ModuleFromObject(LResponse);
end;
procedure TEMSClientAPI.RegisterModule(const AModuleName, AProtocol, AProtocolProps: string;
const ADetails: TJSONObject; const Resources: TResourceList; out AModule: TModule);
var
LPair: TPair<string, TJSONObject>;
LJSONResources: TJSONArray;
LJSONResource: TJSONObject;
begin
LJSONResources := nil;
try
for LPair in Resources do
begin
if LJSONResources = nil then
LJSONResources := TJSONArray.Create;
if LPair.Value <> nil then
LJSONResource := TJSONObject(LPair.Value.Clone)
else
LJSONResource := TJSONObject.Create;
LJSONResource.AddPair(TJSONNames.ResourceName, LPair.Key);
LJSONResources.AddElement(LJSONResource);
end;
RegisterModule(AModuleName, AProtocol, AProtocolProps, ADetails, LJSONResources, AModule);
finally
LJSONResources.Free;
end;
end;
function TEMSClientAPI.RemoveUsersFromGroup(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedAt: TUpdatedAt): Boolean;
var
LJSONObject: TJSONObject;
LJSONArray: TJSONArray;
S: string;
LJSONValue: TJSONValue;
LPair: TJSONPair;
LList: TList<string>;
begin
Result := False;
LJSONObject := nil;
try
if not RetrieveGroup(AGroupName,
procedure(const AGroup: TEMSClientAPI.TGroup; const AJSONObject: TJSONObject)
begin
LJSONObject := AJSONObject.Clone as TJSONObject;
end) then
raise Exception.CreateFmt(sGroupNotFound, [AGroupName]);
if LJSONObject.TryGetValue<TJSONArray>('users', LJSONArray) then
begin
LList := TList<string>.Create;
try
for LJSONValue in LJSONArray do
LList.Add(LJSONValue.Value);
for S in AUsers do
if LList.Contains(S) then
begin
Result := True;
LList.Remove(S);
end;
LJSONArray := TJSONArray.Create;
for S in LList do
LJSONArray.Add(S);
LPair := LJSONObject.RemovePair('users');
LPair.Free;
LJSONObject.AddPair('users', LJSONArray);
finally
LList.Free;
end;
UpdateGroup(AGroupName, LJSONObject, AUpdatedAt);
end;
finally
LJSONObject.Free;
end;
end;
function TEMSClientAPI.RetrieveModule(const AModuleID: string;
AProc: TRetrieveModuleProc): Boolean;
var
LModule: TModule;
begin
Result := RetrieveModule(AModuleID, LModule, nil, AProc);
end;
function TEMSClientAPI.RetrieveModule(const AModule: TModule;
out AFoundModule: TModule; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveModule(AModule.ModuleName, AFoundModule, AJSON, nil);
end;
function TEMSClientAPI.RetrieveModule(const AModule: TModule;
AProc: TRetrieveModuleProc): Boolean;
var
LModule: TModule;
begin
Result := RetrieveModule(AModule.ModuleName, LModule, nil, AProc);
end;
procedure TEMSClientAPI.RetrieveModulesFields(const AFields: TJSONArray);
begin
RetrieveFields(TSegmentNames.ModulesFields, AFields);
end;
function TEMSClientAPI.RetrieveModuleResource(const AModuleID, AResourceName: string;
AProc: TRetrieveModuleResourceProc): Boolean;
var
LModule: TModuleResource;
begin
Result := RetrieveModuleResource(AModuleID, AResourceName, LModule, nil, AProc);
end;
function TEMSClientAPI.RetrieveModuleResource(const AResource: TModuleResource;
out AFoundResource: TModuleResource; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveModuleResource(AResource.ModuleName, AResource.ResourceName, AFoundResource, AJSON, nil);
end;
function TEMSClientAPI.RetrieveModuleResource(const AResource: TModuleResource;
AProc: TRetrieveModuleResourceProc): Boolean;
var
LResource: TModuleResource;
begin
Result := RetrieveModuleResource(AResource.ModuleName, AResource.ResourceName, LResource, nil, AProc);
end;
procedure TEMSClientAPI.RetrieveModuleResourcesFields(const AFields: TJSONArray);
begin
RetrieveFields(TSegmentNames.ResourcesFields, AFields);
end;
function TEMSClientAPI.RetrieveGroup(const AGroupName: string;
AProc: TRetrieveGroupProc): Boolean;
var
LGroup: TGroup;
begin
Result := RetrieveGroup(AGroupName, LGroup, nil, AProc);
end;
function TEMSClientAPI.RetrieveGroup(const AGroup: TGroup;
out AFoundGroup: TGroup; const AJSON: TJSONArray): Boolean;
begin
Result := RetrieveGroup(AGroup.GroupName, AFoundGroup, AJSON, nil);
end;
function TEMSClientAPI.RetrieveGroup(const AGroup: TGroup;
AProc: TRetrieveGroupProc): Boolean;
var
LGroup: TGroup;
begin
Result := RetrieveGroup(AGroup.GroupName, LGroup, nil, AProc);
end;
procedure TEMSClientAPI.RetrieveGroupsFields(const AFields: TJSONArray);
begin
RetrieveFields(TSegmentNames.GroupsFields, AFields);
end;
function TEMSClientAPI.RetrieveGroupsNames: TArray<string>;
var
LGroups: TArray<TGroup>;
LGroup: TGroup;
LSkip: Integer;
LResult: TList<string>;
begin
LResult := TList<string>.Create;
try
LSkip := 0;
while True do
begin
QueryGroups([Format('skip=%d', [LSkip]), 'limit=100'], nil, LGroups);
if Length(LGroups) = 0 then
break;
for LGroup in LGroups do
LResult.Add(LGroup.GroupName);
Inc(LSkip, 100);
end;
Result := LResult.ToArray;
finally
LResult.Free;
end;
end;
function TEMSClientAPI.RetrieveUserGroups(const AUserID: string): TArray<string>;
var
LResponse: TJSONArray;
LValue: TJSONValue;
begin
CheckUserID(AUserID);
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Users + '/{id}' + '/groups'; // do not localize
FRequest.AddParameter('id', AUserID,
TRESTRequestParameterKind.pkURLSEGMENT);
FRequest.Execute;
CheckForResponseError;
LResponse := FRequest.Response.JSONValue as TJSONArray;
if LResponse is TJSONArray then
begin
for LValue in TJSONArray(LResponse) do
Result := Result + [LValue.Value];
end
else
raise EEMSClientAPIError.Create(sJSONArrayExpected);
end;
function TEMSClientAPI.CreateInstallationObject(const ADeviceType: string; const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject;
var
LArray: TJSONArray;
S: string;
LProperties: TJSONObject;
begin
if AProperties <> nil then
begin
LProperties := AProperties.Clone as TJSONObject;
LProperties.RemovePair(TJSONNames.Pushchannels);
end
else
LProperties := TJSONObject.Create;
try
LArray := TJSONArray.Create;
for S in AChannels do
LArray.AddElement(TJSONString.Create(S));
LProperties.AddPair(TJSONNames.Pushchannels, LArray);
Result := CreateInstallationObject(ADeviceType, ADeviceToken, LProperties);
finally
LProperties.Free;
end;
end;
function TEMSClientAPI.CreateInstallationObject(const ADeviceType: string; const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject;
var
LPair: TJSONPair;
begin
Result := TJSONObject.Create;
Result.AddPair('deviceType', TJSONString.Create(ADeviceType)); // Do not localize
Result.AddPair('deviceToken', TJSONString.Create(ADeviceToken)); // Do not localize
if AProperties <> nil then
for LPair in AProperties do
Result.AddPair(LPair.Clone as TJSONPair);
// LProperties.AddPair('timeZone', TJSONString.Create(????));
end;
function TEMSClientAPI.CreateIOSInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject;
begin
Result := CreateInstallationObject(TDeviceTypes.IOS, ADeviceToken, AProperties);
end;
function TEMSClientAPI.CreateIOSInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject;
begin
Result := CreateInstallationObject(TDeviceTypes.IOS, ADeviceToken, AProperties, AChannels);
end;
function TEMSClientAPI.CreateAndroidInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject): TJSONObject;
begin
Result := CreateInstallationObject(TDeviceTypes.Android, ADeviceToken, AProperties);
end;
function TEMSClientAPI.CreateAndroidInstallationObject(const ADeviceToken: string; const AProperties: TJSONObject; AChannels: array of string): TJSONObject;
begin
Result := CreateInstallationObject(TDeviceTypes.Android, ADeviceToken, AProperties, AChannels);
end;
function TEMSClientAPI.DeleteInstallation(const AInstallationID: string): Boolean;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters; // (TAuthentication.MasterKey); // Required
Result := DeleteResource(TSegmentNames.Installations, AInstallationID);
end;
procedure TEMSClientAPI.QueryInstallations(const AQuery: array of string; const AJSONArray: TJSONArray);
begin
FRequest.ResetToDefaults;
DoAddAuthParameters; // (TAuthentication.MasterKey); // Master required
QueryResource(TSegmentNames.Installations, AQuery, AJSONArray, False);
end;
procedure TEMSClientAPI.QueryInstallations(const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TInstallation>);
var
LJSONValue: TJSONValue;
LList: TList<TInstallation>;
LInstallation: TInstallation;
LJSONArray: TJSONArray;
begin
LList := nil;
FRequest.ResetToDefaults;
DoAddAuthParameters; // (TAuthentication.MasterKey); // Master required
if AJSONArray = nil then
LJSONArray := TJSONArray.Create
else
LJSONArray := AJSONArray;
try
QueryResource(TSegmentNames.Installations, AQuery, LJSONArray, False);
LList := TList<TInstallation>.Create;
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
// Blank backend class name
LInstallation := InstallationFromObject(TJSONObject(LJSONValue));
LList.Add(LInstallation);
end
else
raise EEMSClientAPIError.Create(sJSONObjectExpected);
end;
AObjects := LList.ToArray;
finally
LList.Free;
if LJSONArray <> AJSONArray then
LJSONArray.Free;
end;
end;
procedure TEMSClientAPI.QueryModuleResources(const AModuleID: string; const AQuery: array of string; const AJSONArray: TJSONArray);
begin
if AModuleID = '' then
// Get all
QueryResource(TSegmentNames.ModulesResources,
AQuery, AJSONArray, False)
else
QueryResource(TSegmentNames.Modules + '/{mname}/' + TSegmentNames.Resources, // do not localize
AQuery, AJSONArray, False,
procedure begin FRequest.AddParameter('mname', AModuleID, TRESTRequestParameterKind.pkURLSEGMENT); end); // Do not localize
end;
procedure TEMSClientAPI.QueryModuleResources(const AModuleID: string; const AQuery: array of string;
const AJSONArray: TJSONArray; out AResources: TArray<TModuleResource>);
var
LJSONValue: TJSONValue;
LJSONArray: TJSONArray;
LList: TList<TModuleResource>;
LResource: TModuleResource;
begin
LList := nil;
if AJSONArray = nil then
LJSONArray := TJSONArray.Create
else
LJSONArray := AJSONArray;
try
QueryModuleResources(AModuleID, AQuery, LJSONArray);
LList := TList<TModuleResource>.Create;
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LResource := ResourceFromObject(TJSONObject(LJSONValue));
LList.Add(LResource);
end
else
raise EEMSClientAPIError.Create(sJSONObjectExpected);
end;
AResources := LList.ToArray;
finally
LList.Free;
if LJSONArray <> AJSONArray then
LJSONArray.Free;
end;
end;
procedure TEMSClientAPI.QueryModules(const AQuery: array of string;
const AJSONArray: TJSONArray);
begin
QueryResource(TSegmentNames.Modules, AQuery, AJSONArray, False);
end;
procedure TEMSClientAPI.QueryModules(const AQuery: array of string;
const AJSONArray: TJSONArray; out AModules: TArray<TModule>);
var
LJSONValue: TJSONValue;
LJSONArray: TJSONArray;
LList: TList<TModule>;
LModule: TModule;
begin
LList := nil;
if AJSONArray = nil then
LJSONArray := TJSONArray.Create
else
LJSONArray := AJSONArray;
try
QueryModules(AQuery, LJSONArray);
LList := TList<TModule>.Create;
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LModule := ModuleFromObject(TJSONObject(LJSONValue));
LList.Add(LModule);
end
else
raise EEMSClientAPIError.Create(sJSONObjectExpected);
end;
AModules := LList.ToArray;
finally
LList.Free;
if LJSONArray <> AJSONArray then
LJSONArray.Free;
end;
end;
function TEMSClientAPI.QueryModuleName(const AModuleName: string;
AProc: TQueryModuleNameProc): Boolean;
var
LModule: TModule;
begin
Result := QueryModuleName(AModuleName, LModule, nil, AProc);
end;
function TEMSClientAPI.QueryModuleName(const AModuleName: string; out AModule: TModule;
const AJSON: TJSONArray): Boolean;
begin
Result := QueryModuleName(AModuleName, AModule, AJSON, nil);
end;
function TEMSClientAPI.QueryModuleName(const AModuleName: string; out AModule: TModule;
const AJSON: TJSONArray; AProc: TQueryModuleNameProc): Boolean;
var
LModules: TJSONArray;
LModuleObject: TJSONObject;
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
FRequest.Method := TRESTRequestMethod.rmGET;
// Closing '/' required
FRequest.Resource := TSegmentNames.Modules + '/';
FRequest.AddParameter(TQueryParamNames.Where,
TJSONObject.Create.AddPair(TJSONNames.ModuleName, TJSONString.Create(AModuleName)));
FRequest.Execute;
CheckForResponseError;
LModules := FRequest.Response.JSONValue as TJSONArray;
if LModules.Count > 1 then
raise EEMSClientAPIError.Create(sOneModuleExpected);
Result := LModules.Count = 1;
if Result then
begin
LModuleObject := LModules.Items[0] as TJSONObject;
AModule := ModuleFromObject(LModuleObject);
if Assigned(AJSON) then
AJSON.AddElement(LModuleObject.Clone as TJSONObject);
if Assigned(AProc) then
AProc(AModule, LModuleObject);
end;
end;
function TEMSClientAPI.RetrieveInstallation(const AInstallationID: string; out AFoundInstallation: TInstallation; const AJSON: TJSONArray = nil): Boolean;
begin
Result := RetrieveInstallation(AInstallationID, AFoundInstallation, AJSON, nil, True);
end;
function TEMSClientAPI.RetrieveInstallation(const AInstallationID: string; AProc: TRetrieveInstallationProc): Boolean;
var
LInstallation: TInstallation;
begin
Result := RetrieveInstallation(AInstallationID, LInstallation, nil, AProc, True);
end;
function TEMSClientAPI.RetrieveInstallation(const AInstallation: TInstallation; AProc: TRetrieveInstallationProc): Boolean;
var
LInstallation: TInstallation;
begin
Result := RetrieveInstallation(AInstallation.InstallationID, LInstallation, nil, AProc, True);
end;
function TEMSClientAPI.RetrieveInstallation(const AInstallation: TInstallation; out AFoundInstallation: TInstallation;
const AJSON: TJSONArray): Boolean;
var
LInstallation: TInstallation;
begin
Result := RetrieveInstallation(AInstallation.InstallationID, LInstallation, AJSON, nil, True);
end;
function TEMSClientAPI.RetrieveInstallation(const AInstallationID: string; out AFoundInstallation: TInstallation; const AJSON: TJSONArray; AProc: TRetrieveInstallationProc; AReset: Boolean): Boolean;
var
LResponse: TJSONObject;
begin
Result := False;
CheckInstallationID(AInstallationID);
if AReset then
begin
FRequest.ResetToDefaults;
DoAddAuthParameters;
end;
FRequest.Method := TRESTRequestMethod.rmGET;
FRequest.Resource := TSegmentNames.Installations + '/' + AInstallationID;
FRequest.Execute;
CheckForResponseError([404]); // 404 = not found
if FRequest.Response.StatusCode <> 404 then
begin
Result := True;
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
if AJSON <> nil then
AJSON.AddElement(LResponse.Clone as TJSONObject);
if Assigned(AProc) then
AProc(InstallationFromObject(LResponse), LResponse);
end
end;
procedure TEMSClientAPI.UploadInstallation(const AJSON: TJSONObject; out ANewObject: TInstallation);
var
LResponse: TJSONObject;
begin
AddResource(TSegmentNames.Installations, AJSON);
// '{"createdAt":"2013-10-16T20:21:57.326Z","objectId":"5328czuo2e"}'
LResponse := FRequest.Response.JSONValue as TJSONObject;
ANewObject := InstallationFromObject(LResponse);
end;
procedure TEMSClientAPI.UpdateInstallation(const AInstallationID: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
CheckInstallationID(AInstallationID);
PutResource(TSegmentNames.Installations, AInstallationID, AJSONObject);
LResponse := FRequest.Response.JSONValue as TJSONObject;
// '{"updatedAt":"2013-10-16T20:21:57.326Z"}'
AUpdatedAt := UpdatedAtFromObject(LResponse);
end;
procedure TEMSClientAPI.UpdateModule(const AModuleID, AModuleName, AProtocol, AProtocolProps: string; const AJSONObject: TJSONObject; const AResources: TJSONArray; out AUpdatedAt: TUpdatedAt);
var
LJSON: TJSONObject;
begin
CheckModuleID(AModuleID);
if AJSONObject <> nil then
LJSON := AJSONObject.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.ModuleName, AModuleName);
LJSON.AddPair(TJSONNames.Protocol, AProtocol);
LJSON.AddPair(TJSONNames.ProtocolProps, AProtocolProps);
UpdateModule(AModuleID, LJSON, AResources, AUpdatedAt);
finally
LJSON.Free;
end;
end;
procedure TEMSClientAPI.UpdateModule(const AModuleID: string; const AJSONObject: TJSONObject; const AResources: TJSONArray; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
LJSON: TJSONObject;
begin
CheckModuleID(AModuleID);
if AJSONObject <> nil then
LJSON := AJSONObject.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
if AResources <> nil then
LJSON.AddPair(TJSONPair.Create(TJSONNames.Resources, TJSONValue(AResources.Clone)));
PutResource(TSegmentNames.Modules, AModuleID, LJSON);
finally
LJSON.Free;
end;
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUpdatedAt := UpdatedAtFromObject(LResponse);
end;
procedure TEMSClientAPI.UpdateModuleResource(const AModuleID, AResourceName: string; const AJSONObject: TJSONObject; out AUpdatedAt: TUpdatedAt);
var
LResponse: TJSONObject;
begin
CheckModuleID(AModuleID);
CheckResourceName(AResourceName);
PutResource(TSegmentNames.Modules + '/{mname}/' + TSegmentNames.Resources, // do not localize
AResourceName, AJSONObject,
procedure begin FRequest.AddParameter('mname', AModuleID, TRESTRequestParameterKind.pkURLSEGMENT); end); // Do not localize
LResponse := FRequest.Response.JSONValue as TJSONObject;
AUpdatedAt := UpdatedAtFromObject(LResponse);
end;
function ValueToJsonValue(AValue: TValue): TJSONValue;
begin
if AValue.IsType<Int64> then
Result := TJSONNumber.Create(AValue.AsInt64)
else if AValue.IsType<Extended> then
Result := TJSONNumber.Create(AValue.AsExtended)
else if AValue.IsType<string> then
Result := TJSONString.Create(AValue.AsString)
else
Result := TJSONString.Create(AValue.ToString)
end;
{ TEMSClientApi.TUserID }
constructor TEMSClientAPI.TUser.Create(const AUserName, AUserID: string);
begin
FUserName := AUserName;
FUserID := AUserID;
end;
{ TEMSClientApi.TGroup }
constructor TEMSClientAPI.TGroup.Create(const AGroupName: string);
begin
FGroupName := AGroupName;
end;
{ TEMSClientApi.TInstallation }
constructor TEMSClientAPI.TInstallation.Create(const AInstallationID: string);
begin
FInstallationID := AInstallationID;
end;
{ TEMSClientApi.TLogin }
constructor TEMSClientAPI.TLogin.Create(const AAuthToken: string;
const AUser: TUser);
begin
FAuthToken := AAuthToken;
FUser := AUser;
end;
{ TEMSClientAPI.TUpdatedAt }
constructor TEMSClientAPI.TUpdatedAt.Create(AUpdatedAt: TDateTime);
begin
FUpdatedAt := AUpdatedAt;
end;
{ EEMSClientHTTPError }
constructor EEMSClientHTTPError.Create(ACode: Integer; const AError, ADescription: string);
var
LError: string;
begin
FCode := ACode;
FDescription := ADescription;
FError := AError;
if (AError <> '') and (ADescription <> '') then
begin
LError := AError;
if LError.EndsWith('.') then
LError := LError.Substring(0, LError.Length-1);
inherited CreateFmt(sFormatEMSErrorDescription, [LError, ADescription])
end
else if AError <> '' then
inherited CreateFmt(sFormatEMSError, [AError])
else if ADescription <> '' then
inherited CreateFmt(sFormatEMSError, [ADescription]);
end;
{ TEMSClientAPI.TDeviceCounts }
constructor TEMSClientAPI.TPushStatus.Create(AIOS, AAndroid: Integer);
begin
FAndroid := AAndroid;
FIOS := AIOS;
end;
{ TEMSClientAPI.TModule }
constructor TEMSClientAPI.TModule.Create(const AModuleID, AName: string);
begin
FModuleID := AModuleID;
FModuleName := AName;
end;
{ TEMSClientAPI.TModuleResource }
constructor TEMSClientAPI.TModuleResource.Create(const AName, AModuleID, AModuleName: string);
begin
FResourceName := AName;
FModuleName := AModuleName;
FModuleID := AModuleID;
end;
end.
|
Unit controllers;
uses crypto;
var
mtx: System.Threading.Mutex;
function GetUser(login: string): string;
begin
Result := nil;
foreach var s in ReadLines('data/users.txt') do
begin
var ss := s.ToWords;
if (ss[0] = login) then begin
Result := ss[1];
end;
end;
end;
function GetLastUsers(n: integer): string;
begin
var st := new Queue<string>;
foreach var s in ReadLines('data/users.txt') do
begin
var ss := s.ToWords;
st.Enqueue(ss[0]);
if (st.Count > n) then st.Dequeue;
end;
while (st.Count <> 0) do Result += st.Dequeue + '<br>'
end;
procedure AddUser(login,password: string);
begin
{I don't know why append is not atomic in .NET (but should for small chunks).}
mtx.WaitOne();
var f := OpenAppend('data/users.txt');
WriteLn(f, login, ' ', password);
Close(f);
mtx.ReleaseMutex();
end;
function GetIcecreams(login: string): string;
begin
var fname := 'data/' + CreateMd5(login) + '.txt';
if not FileExists(fname) then Result := 'Still no icecreams' else
foreach var s in ReadLines(fname) do
Result += s + '</br>'
end;
procedure AddIcecream(login: string; icecream: string);
begin
var fname := 'data/' + CreateMd5(login) + '.txt';
var f := OpenAppend(fname);
WriteLn(f, icecream);
Close(f);
end;
begin
mtx := new System.Threading.Mutex();
end. |
unit DelphiUtils.Strings;
interface
uses
Winapi.WinNt, System.TypInfo;
type
THintSection = record
Title: String;
Enabled: Boolean;
Content: String;
end;
// Boolean state to string
function EnabledDisabledToString(Value: LongBool): String;
function YesNoToString(Value: LongBool): String;
function CheckboxToString(Value: LongBool): String;
function BytesToString(Size: Cardinal): String;
// Bit flag manipulation
function Contains(Value, Flag: Cardinal): Boolean; inline;
function ContainsAny(Value, Flag: Cardinal): Boolean; inline;
// Converting a set of bit flags to string
function MapFlags(Value: Cardinal; Mapping: array of TFlagName;
Default: String = ''): String;
function MapFlagsList(Value: Cardinal; Mapping: array of TFlagName): String;
// Create a hint from a set of sections
function BuildHint(Sections: array of THintSection): String;
// Mark a value as out of bound
function OutOfBound(Value: Integer): String;
// Make enumeration names look friendly
function PrettifyCamelCase(CamelCaseText: String;
Prefix: String = ''; Suffix: String = ''): String;
function PrettifyCamelCaseEnum(TypeInfo: PTypeInfo; Value: Integer;
Prefix: String = ''; Suffix: String = ''): String;
function PrettifySnakeCase(CapsText: String; Prefix: String = '';
Suffix: String = ''): String;
function PrettifySnakeCaseEnum(TypeInfo: PTypeInfo; Value: Integer;
Prefix: String = ''; Suffix: String = ''): String;
// Hex represenation
function IntToHexEx(Value: Int64; Digits: Integer = 0): String; overload;
function IntToHexEx(Value: UInt64; Digits: Integer = 0): String; overload;
function IntToHexEx(Value: Pointer): String; overload;
// String to int conversion
function TryStrToUInt64Ex(S: String; out Value: UInt64): Boolean;
function StrToUIntEx(S: String; Comment: String): Cardinal; inline;
function StrToUInt64Ex(S: String; Comment: String): UInt64; inline;
implementation
uses
System.SysUtils;
function EnabledDisabledToString(Value: LongBool): String;
begin
if Value then
Result := 'Enabled'
else
Result := 'Disabled';
end;
function YesNoToString(Value: LongBool): String;
begin
if Value then
Result := 'Yes'
else
Result := 'No';
end;
function CheckboxToString(Value: LongBool): String;
begin
if Value then
Result := '☑'
else
Result := '☐';
end;
function BytesToString(Size: Cardinal): String;
begin
if Size mod 1024 = 0 then
Result := (Size div 1024).ToString + ' kB'
else
Result := Size.ToString + ' B';
end;
function Contains(Value, Flag: Cardinal): Boolean;
begin
Result := (Value and Flag = Flag);
end;
function ContainsAny(Value, Flag: Cardinal): Boolean;
begin
Result := (Value and Flag <> 0);
end;
function MapFlags(Value: Cardinal; Mapping: array of TFlagName;
Default: String): String;
var
Strings: array of String;
i, Count: Integer;
begin
SetLength(Strings, Length(Mapping));
Count := 0;
for i := Low(Mapping) to High(Mapping) do
if Contains(Value, Mapping[i].Value) then
begin
Strings[Count] := Mapping[i].Name;
Inc(Count);
end;
SetLength(Strings, Count);
if Count = 0 then
Result := Default
else
Result := String.Join(', ', Strings);
end;
function MapFlagsList(Value: Cardinal; Mapping: array of TFlagName): String;
var
Strings: array of string;
i: Integer;
begin
SetLength(Strings, Length(Mapping));
for i := Low(Mapping) to High(Mapping) do
Strings[i - Low(Mapping)] := CheckboxToString(Contains(Value,
Mapping[i].Value)) + ' ' + Mapping[i].Name;
Result := String.Join(#$D#$A, Strings);
end;
function BuildHint(Sections: array of THintSection): String;
var
Count, i, j: Integer;
Items: array of String;
begin
Count := 0;
for i := Low(Sections) to High(Sections) do
if Sections[i].Enabled then
Inc(Count);
SetLength(Items, Count);
j := 0;
for i := Low(Sections) to High(Sections) do
if Sections[i].Enabled then
begin
Items[j] := Sections[i].Title + ': '#$D#$A' ' + Sections[i].Content +
' ';
Inc(j);
end;
Result := String.Join(#$D#$A, Items);
end;
function OutOfBound(Value: Integer): String;
begin
Result := IntToStr(Value) + ' (out of bound)';
end;
function PrettifyCamelCase(CamelCaseText: String;
Prefix: String; Suffix: String): String;
var
i: Integer;
begin
// Convert a string with from CamelCase to a spaced string removing prefix,
// for example: '__MyExampleText' => 'My example text'
Result := CamelCaseText;
if Result.StartsWith(Prefix) then
Delete(Result, Low(Result), Length(Prefix));
if Result.EndsWith(Suffix) then
Delete(Result, Length(Result) - Length(Suffix) + 1, Length(Suffix));
i := Low(Result) + 1;
while i <= High(Result) do
begin
if CharInSet(Result[i], ['A'..'Z']) then
begin
Result[i] := Chr(Ord('a') + Ord(Result[i]) - Ord('A'));
Insert(' ', Result, i);
Inc(i);
end;
Inc(i);
end;
end;
function PrettifyCamelCaseEnum(TypeInfo: PTypeInfo; Value: Integer;
Prefix: String; Suffix: String): String;
begin
if (TypeInfo.Kind = tkEnumeration) and (Value >= TypeInfo.TypeData.MinValue)
and (Value <= TypeInfo.TypeData.MaxValue) then
Result := PrettifyCamelCase(GetEnumName(TypeInfo, Integer(Value)), Prefix,
Suffix)
else
Result := OutOfBound(Value);
end;
function PrettifySnakeCase(CapsText: String; Prefix: String = '';
Suffix: String = ''): String;
var
i: Integer;
begin
// Convert a string with from capitals with undescores to a spaced string
// removing a prefix/suffix, ex.: 'ERROR_ACCESS_DENIED' => 'Acces denied'
Result := CapsText;
if Result.StartsWith(Prefix) then
Delete(Result, Low(Result), Length(Prefix));
if Result.EndsWith(Suffix) then
Delete(Result, Length(Result) - Length(Suffix) + 1, Length(Suffix));
// Capitalize the first letter
if Length(Result) > 0 then
case Result[Low(Result)] of
'a'..'z':
Result[Low(Result)] := Chr(Ord('A') + Ord(Result[Low(Result)]) -
Ord('a'));
end;
// Lower the rest
for i := Succ(Low(Result)) to High(Result) do
begin
case Result[i] of
'A'..'Z':
Result[i] := Chr(Ord('a') + Ord(Result[i]) - Ord('A'));
'_':
Result[i] := ' ';
end;
end;
end;
function PrettifySnakeCaseEnum(TypeInfo: PTypeInfo; Value: Integer;
Prefix: String = ''; Suffix: String = ''): String;
begin
if (TypeInfo.Kind = tkEnumeration) and (Value >= TypeInfo.TypeData.MinValue)
and (Value <= TypeInfo.TypeData.MaxValue) then
Result := PrettifySnakeCase(GetEnumName(TypeInfo, Integer(Value)),
Prefix, Suffix)
else
Result := OutOfBound(Value);
end;
function IntToHexEx(Value: UInt64; Digits: Integer): String;
begin
Result := '0x' + IntToHex(Value, Digits);
end;
function IntToHexEx(Value: Int64; Digits: Integer): String;
begin
Result := '0x' + IntToHex(Value, Digits);
end;
function IntToHexEx(Value: Pointer): String;
begin
Result := '0x' + IntToHex(NativeUInt(Value), 8);
end;
function TryStrToUInt64Ex(S: String; out Value: UInt64): Boolean;
var
E: Integer;
begin
if S.StartsWith('0x') then
S := S.Replace('0x', '$', []);
Val(S, Value, E);
Result := (E = 0);
end;
function StrToUInt64Ex(S: String; Comment: String): UInt64;
const
E_DECHEX = 'Invalid %s. Please specify a decimal or a hexadecimal value.';
begin
if not TryStrToUInt64Ex(S, Result) then
raise EConvertError.Create(Format(E_DECHEX, [Comment]));
end;
function StrToUIntEx(S: String; Comment: String): Cardinal;
begin
{$R-}
Result := StrToUInt64Ex(S, Comment);
{$R+}
end;
end.
|
{ Module of GUI library routines that manipulate the RENDlib event state.
}
module gui_events;
define gui_events_init_key;
%include 'gui2.ins.pas';
{
*************************************************************************
*
* Subroutine GUI_EVENTS_INIT_KEY
*
* Initialize the RENDlib key events state to that assumed by other GUI library
* routines. All the keys used anywhere in the GUI library are enabled here.
* It is up to each event handler to ignore events for irrelevant keys.
}
procedure gui_events_init_key; {set up RENDlib key events for curr device}
var
keys_p: rend_key_ar_p_t; {pointer to array of all key descriptors}
nk: sys_int_machine_t; {number of keys at KEYS_P}
i: sys_int_machine_t; {scratch integer and loop counter}
begin
rend_set.enter_rend^; {push one level deeper into graphics mode}
rend_get.keys^ (keys_p, nk); {get RENDlib key descriptors info}
{
* Find all the keys that map to individual characters and enable
* these as CHAR keys. Some of these may get remapped as special keys
* further below.
}
for i := 1 to nk do begin {once for each key descriptor in the list}
if keys_p^[i].val_p = nil then next; {this key has no character value ?}
if keys_p^[i].val_p^.len <> 1 then next; {key value is not a single character ?}
rend_set.event_req_key_on^ ( {enable events for this key}
i, {RENDlib index for this key}
ord(gui_key_char_k)); {our internal ID for this key}
end;
rend_set.event_req_key_on^ ( {enable up arrow key}
rend_get.key_sp^ (rend_key_sp_arrow_up_k, 0),
ord(gui_key_arrow_up_k));
rend_set.event_req_key_on^ ( {enable down arrow key}
rend_get.key_sp^ (rend_key_sp_arrow_down_k, 0),
ord(gui_key_arrow_down_k));
rend_set.event_req_key_on^ ( {enable left arrow key}
rend_get.key_sp^ (rend_key_sp_arrow_left_k, 0),
ord(gui_key_arrow_left_k));
rend_set.event_req_key_on^ ( {enable right arrow key}
rend_get.key_sp^ (rend_key_sp_arrow_right_k, 0),
ord(gui_key_arrow_right_k));
rend_set.event_req_key_on^ ( {enable HOME key}
gui_key_names_id ('HOME'),
ord(gui_key_home_k));
rend_set.event_req_key_on^ ( {enable END key}
gui_key_names_id ('END'),
ord(gui_key_end_k));
rend_set.event_req_key_on^ ( {enable DELETE key}
gui_key_names_id ('DELETE'),
ord(gui_key_del_k));
rend_set.event_req_key_on^ (
gui_key_names_id ('DEL'),
ord(gui_key_del_k));
rend_set.event_req_key_on^ ( {enable mouse left button events}
rend_get.key_sp^ (rend_key_sp_pointer_k, 1), {RENDlib key ID}
ord(gui_key_mouse_left_k));
if rend_get.key_sp^ (rend_key_sp_pointer_k, 3) = rend_key_none_k
then begin {pointer only has 2 or fewer keys}
rend_set.event_req_key_on^ ( {enable mouse right button events}
rend_get.key_sp^ (rend_key_sp_pointer_k, 2), {RENDlib key ID}
ord(gui_key_mouse_right_k));
end
else begin {pointer has 3 or more keys}
rend_set.event_req_key_on^ ( {enable mouse middle button events}
rend_get.key_sp^ (rend_key_sp_pointer_k, 2), {RENDlib key ID}
ord(gui_key_mouse_mid_k));
rend_set.event_req_key_on^ ( {enable mouse right button events}
rend_get.key_sp^ (rend_key_sp_pointer_k, 3), {RENDlib key ID}
ord(gui_key_mouse_right_k));
end
;
rend_set.event_req_key_on^ ( {enable TAB key}
gui_key_alpha_id (chr(9)),
ord(gui_key_esc_k));
rend_set.event_req_key_on^ ( {enable ESCAPE key}
gui_key_alpha_id (chr(27)),
ord(gui_key_esc_k));
rend_set.event_req_key_on^ ( {enable ENTER key}
gui_key_alpha_id (chr(13)),
ord(gui_key_enter_k));
rend_set.exit_rend^; {pop one level back out of graphics mode}
end;
|
unit uUpdateYZBH;
interface
uses
FireDAC.Comp.Client, uLogger, System.Generics.Collections, SysUtils, Classes,
uSQLHelper;
type
TUpdateYZBH = Class
private
class var FConn: TSQLHelper;
class var FDicYzbh: TDictionary<string, TDictionary<string, string>>;
class function LoadDicmail()
: TDictionary<string, TDictionary<string, string>>;
class function GetYzbh(jc, dz: string): string;
public
class procedure Run(conn: TSQLHelper);
end;
implementation
class procedure TUpdateYZBH.Run(conn: TSQLHelper);
var
yzbh, sql: String;
ts: TStrings;
begin
logger.logging('Start UpdateYZBH', 1);
FConn := conn;
FDicYzbh := LoadDicmail();
ts := TStringList.Create;
sql := 'select XH, left(HPHM, 1) as sf, ZSXXDZ from [dbo].[T_VIO_Surveil] with(nolock) '
+ ' where GXSJ > dateadd(dd, -15, getdate()) and HPHM > '''' and ZSXXDZ > '''' and ZSXXDZ <> ''Пе'' '
+ ' and (YZBH is null or YZBH='''') order by GXSJ desc ';
with FConn.Query(sql) do
begin
while not Eof do
begin
yzbh := GetYzbh(FieldByName('sf').AsString, FieldByName('ZSXXDZ').AsString);
if yzbh <> '' then
ts.Add(' update T_VIO_Surveil set YZBH = ' + yzbh.QuotedString + ' where XH = ''' + FieldByName('XH').AsString+'''');
if ts.Count > 500 then
begin
FConn.ExecuteSql(ts.Text);
ts.Clear;
end;
Next;
end;
Free;
end;
if ts.Count > 0 then
FConn.ExecuteSql(ts.Text);
FDicYzbh.Free;
ts.Free;
logger.logging('finished UpdateYZBH', 1);
end;
class function TUpdateYZBH.LoadDicmail(): TDictionary<string, TDictionary<string, string>>;
var
key, CSMC, yzbm: string;
begin
Result := TDictionary < string, TDictionary < string, string >>.Create();
with FConn.Query('select * from S_MAIL ') do
begin
while not Eof do
begin
key := UpperCase(Trim(FieldByName('jc').AsString));
CSMC := UpperCase(FieldByName('CSMC').AsString);
yzbm := UpperCase(FieldByName('YZBM').AsString);
if not Result.ContainsKey(key) then
Result.Add(key, TDictionary<string, string>.Create);
if not Result[key].ContainsKey(CSMC) then
Result[key].Add(CSMC, yzbm);
Next;
end;
Free;
end;
end;
class function TUpdateYZBH.GetYzbh(jc, dz: string): string;
var
s: string;
dicSf: TDictionary<string, string>;
begin
Result := '';
if not FDicYzbh.ContainsKey(jc) then
exit;
dicSf := FDicYzbh[jc];
for s in dicSf.Keys do
begin
if Pos(s, dz) > 0 then
begin
if Result < dicSf[s] then
Result := dicSf[s];
end;
end;
end;
end.
|
unit UHandleObject;
{
封包分发对象基类
用户继承后可以扩展为对单一协议的解析
}
interface
uses
Windows,UPacketManager,UProtocol;
type
THandleObjct = class
private
mHandleName:String;
protected
Function GetProtocol(pBuffer:Pointer):Integer;
public
constructor Create(_HandleName:String);
Procedure OnRecv(_PacketObject:PPacketObject);virtual;abstract;
Procedure OnSend(_PacketObject:PPacketObject);virtual;abstract;
property HandleName:String read mHandleName;
end;
implementation
{ TGameBaseObj }
constructor THandleObjct.Create(_HandleName: String);
begin
Packet.AddItem(C_SEND_PACKET,'s_' + HandleName,OnSend);
Packet.AddItem(C_RECV_PACKET,'r_' +HandleName,OnRecv);
mHandleName:=_HandleName;
end;
function THandleObjct.GetProtocol(pBuffer: Pointer): Integer;
begin
Result:=GetProtocolId(pBuffer);
end;
end.
|
unit IdHostnameServer;
interface
uses
Classes,
IdTCPServer;
const
KnownCommands: array[1..9] of string =
(
'HNAME',
'HADDR',
'ALL',
'HELP',
'VERSION',
'ALL-OLD',
'DOMAINS',
'ALL-DOM',
'ALL-INGWAY'
);
type
THostNameGetEvent = procedure(Thread: TIdPeerThread) of object;
THostNameOneParmEvent = procedure(Thread: TIdPeerThread; Parm: string) of
object;
TIdHostNameServer = class(TIdTCPServer)
protected
FOnCommandHNAME: THostNameOneParmEvent;
FOnCommandHADDR: THostNameOneParmEvent;
FOnCommandALL: THostNameGetEvent;
FOnCommandHELP: THostNameGetEvent;
FOnCommandVERSION: THostNameGetEvent;
FOnCommandALLOLD: THostNameGetEvent;
FOnCommandDOMAINS: THostNameGetEvent;
FOnCommandALLDOM: THostNameGetEvent;
FOnCommandALLINGWAY: THostNameGetEvent;
function DoExecute(Thread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
property OnCommandHNAME: THostNameOneParmEvent read fOnCommandHNAME write
fOnCommandHNAME;
property OnCommandHADDR: THostNameOneParmEvent read fOnCommandHADDR write
fOnCommandHADDR;
property OnCommandALL: THostNameGetEvent read fOnCommandALL write
fOnCommandALL;
property OnCommandHELP: THostNameGetEvent read fOnCommandHELP write
fOnCommandHELP;
property OnCommandVERSION: THostNameGetEvent read fOnCommandVERSION write
fOnCommandVERSION;
property OnCommandALLOLD: THostNameGetEvent read fOnCommandALLOLD write
fOnCommandALLOLD;
property OnCommandDOMAINS: THostNameGetEvent read fOnCommandDOMAINS write
fOnCommandDOMAINS;
property OnCommandALLDOM: THostNameGetEvent read fOnCommandALLDOM write
fOnCommandALLDOM;
property OnCommandALLINGWAY: THostNameGetEvent read fOnCommandALLINGWAY write
fOnCommandALLINGWAY;
end;
implementation
uses
IdGlobal,
SysUtils;
constructor TIdHostNameServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DefaultPort := IdPORT_HOSTNAME;
end;
function TIdHostNameServer.DoExecute(Thread: TIdPeerThread): boolean;
var
S, sCmd: string;
begin
result := true;
while Thread.Connection.Connected do
begin
S := Thread.Connection.ReadLn;
sCmd := UpperCase(Fetch(s, CHAR32));
case Succ(PosInStrArray(Uppercase(sCmd), KnownCommands)) of
1: {hname}
if assigned(OnCommandHNAME) then
OnCommandHNAME(Thread, S);
2: {haddr}
if assigned(OnCommandHADDR) then
OnCommandHADDR(Thread, S);
3: {all}
if assigned(OnCommandALL) then
OnCommandALL(Thread);
4: {help}
if assigned(OnCommandHELP) then
OnCommandHELP(Thread);
5: {version}
if assigned(OnCommandVERSION) then
OnCommandVERSION(Thread);
6: {all-old}
if assigned(OnCommandALLOLD) then
OnCommandALLOLD(Thread);
7: {domains}
if assigned(OnCommandDOMAINS) then
OnCommandDOMAINS(Thread);
8: {all-dom}
if assigned(OnCommandALLDOM) then
OnCommandALLDOM(Thread);
9: {all-ingway}
if assigned(OnCommandALLINGWAY) then
OnCommandALLINGWAY(Thread);
end; //while Thread.Connection.Connected do
end; //while Thread.Connection.Connected do
Thread.Connection.Disconnect;
end; {doExecute}
end.
|
unit caControls;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Windows,
Classes,
Messages,
Controls,
Sysutils,
Graphics,
Forms,
StdCtrls,
ExtCtrls,
Dialogs,
// ca units
caUtils,
caTypes,
caClasses,
caFrame;
type
TcaPaintEvent = procedure(Sender: TObject; ACanvas: TCanvas; ARect: TRect) of object;
TcaClickOutsideEvent = procedure(Sender: TObject; AClickedControl: TControl) of object;
//---------------------------------------------------------------------------
// IcaComponentFactory
//---------------------------------------------------------------------------
IcaComponentFactory = interface
['{3D7E850A-B6DD-4B60-9722-5456A12FF94D}']
function GetComponentClass: TComponentClass;
function GetComponentOwner: TComponent;
function GetNextComponentName: String;
function NewComponent: TComponent;
procedure SetComponentClass(const Value: TComponentClass);
procedure SetComponentOwner(const Value: TComponent);
property ComponentClass: TComponentClass read GetComponentClass write SetComponentClass;
property ComponentOwner: TComponent read GetComponentOwner write SetComponentOwner;
end;
//---------------------------------------------------------------------------
// TcaComponentFactory
//---------------------------------------------------------------------------
TcaComponentFactory = class(TInterfacedObject, IcaComponentFactory)
private
FComponentClass: TComponentClass;
FComponentOwner: TComponent;
function GetComponentClass: TComponentClass;
function GetComponentOwner: TComponent;
procedure SetComponentClass(const Value: TComponentClass);
procedure SetComponentOwner(const Value: TComponent);
public
constructor Create(AClass: TComponentClass; AOwner: TComponent); overload;
function GetNextComponentName: String;
property ComponentClass: TComponentClass read GetComponentClass write SetComponentClass;
function NewComponent: TComponent;
end;
//---------------------------------------------------------------------------
// IcaMargin
//---------------------------------------------------------------------------
IcaMargin = interface
['{2E99C170-05EE-40A0-A074-BA4F485551C8}']
// Property methods
function GetBottom: Integer;
function GetLeft: Integer;
function GetOnChanged: TNotifyEvent;
function GetRight: Integer;
function GetTop: Integer;
procedure SetBottom(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetOnChanged(const Value: TNotifyEvent);
procedure SetRight(const Value: Integer);
procedure SetTop(const Value: Integer);
// Properties
property Bottom: Integer read GetBottom write SetBottom;
property Left: Integer read GetLeft write SetLeft;
property OnChanged: TNotifyEvent read GetOnChanged write SetOnChanged;
property Right: Integer read GetRight write SetRight;
property Top: Integer read GetTop write SetTop;
end;
//---------------------------------------------------------------------------
// TcaMargin
//---------------------------------------------------------------------------
TcaMargin = class(TcaInterfacedPersistent, IcaMargin)
private
FBottom: Integer;
FLeft: Integer;
FOnChanged: TNotifyEvent;
FRight: Integer;
FTop: Integer;
FUpdateCount: Integer;
function GetBottom: Integer;
function GetLeft: Integer;
function GetOnChanged: TNotifyEvent;
function GetRight: Integer;
function GetTop: Integer;
procedure Changed;
procedure SetBottom(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetOnChanged(const Value: TNotifyEvent);
procedure SetRight(const Value: Integer);
procedure SetTop(const Value: Integer);
protected
procedure DoChanged; virtual;
public
procedure Assign(Source: TPersistent); override;
procedure BeginUpdate;
procedure EndUpdate;
published
property Bottom: Integer read GetBottom write SetBottom;
property Left: Integer read GetLeft write SetLeft;
property OnChanged: TNotifyEvent read GetOnChanged write SetOnChanged;
property Right: Integer read GetRight write SetRight;
property Top: Integer read GetTop write SetTop;
end;
//---------------------------------------------------------------------------
// IcaCustomPanel
//---------------------------------------------------------------------------
IcaCustomPanel = interface
['{EB2CD5CD-954A-46B3-A009-614FB67923E8}']
// Property methods
function GetTransparent: Boolean;
procedure SetTransparent(const Value: Boolean);
// Properties
property Transparent: Boolean read GetTransparent write SetTransparent;
end;
//---------------------------------------------------------------------------
// TcaCustomPanel
//---------------------------------------------------------------------------
TcaCustomPanel = class(TCustomPanel, IcaCustomPanel, IcaFrame)
private
// Private fields
FDefaultWindowProc: TWndMethod;
FFrame: TcaFrameProperties;
FFrameImpl: IcaFrame;
FOffScreenBitmap: TBitmap;
FOnClickOutside: TcaClickOutsideEvent;
FOnMouseEnter: TNotifyEvent;
FOnMouseLeave: TNotifyEvent;
FSubClassForm: Boolean;
FTransparent: Boolean;
// Property methods
function GetTransparent: Boolean;
procedure SetSubClassForm(const Value: Boolean);
procedure SetTransparent(const Value: Boolean);
// Private methods
procedure CreateFrameObjects;
procedure CreateOffScreenBitmap;
procedure FreeFrameObjects;
procedure FreeOffScreenBitmap;
procedure HookWindowProc(var Message: TMessage);
procedure ReplaceWindowProc;
procedure RestoreWindowProc;
// Component mesage handlers
procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE;
procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
procedure CMMouseenter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseleave(var Message: TMessage); message CM_MOUSELEAVE;
protected
// Protected methods
function GetOffScreenCanvas: TCanvas;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure DoClickOutside(AClickedControl: TControl); virtual;
procedure DoHookWindowProc(var Message: TMessage); virtual;
procedure DoMouseEnter; virtual;
procedure DoMouseLeave; virtual;
procedure Paint; override;
procedure UpdateOffScreenBitmap;
procedure UpdateOnScreenBitmap;
// Protected properties
property Frame: TcaFrameProperties read FFrame write FFrame;
property FrameImpl: IcaFrame read FFrameImpl implements IcaFrame;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
property SubClassForm: Boolean read FSubClassForm write SetSubClassForm;
property Transparent: Boolean read GetTransparent write SetTransparent;
// Protected event properties
property OnClickOutside: TcaClickOutsideEvent read FOnClickOutside write FOnClickOutside;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
//---------------------------------------------------------------------------
// TcaPanel
//---------------------------------------------------------------------------
TcaPanel = class(TcaCustomPanel)
public
// TCustomPanel
property DockManager;
published
// TcaCustomPanel
property Frame;
property SubClassForm;
property Transparent;
// Event properties
property OnClickOutside;
// TCustomPanel
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BiDiMode;
property BorderWidth;
property BorderStyle;
property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
property Locked;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
// Event properties
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDblClick;
property OnDockDrop;
property OnDockOver;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
//---------------------------------------------------------------------------
// TcaFormPanel
//---------------------------------------------------------------------------
TcaFormCreateEvent = procedure(Sender: TObject; var AForm: TForm) of object;
TcaFormShowEvent = procedure(Sender: TObject; AForm: TForm) of object;
TcaCustomFormPanel = class(TcaPanel)
private
// Private fields
FForm: TForm;
// Event property fields
FOnBeforeShowForm: TcaFormShowEvent;
FOnCreateForm: TcaFormCreateEvent;
// Private methods
procedure UpdateChildForm;
protected
// Protected methods
procedure CreateWnd; override;
procedure DoCreateForm(var AForm: TForm); virtual;
procedure DoBeforeShowForm(AForm: TForm); virtual;
// Event properties
property OnCreateForm: TcaFormCreateEvent read FOnCreateForm write FOnCreateForm;
property OnBeforeShowForm: TcaFormShowEvent read FOnBeforeShowForm write FOnBeforeShowForm;
public
// Public methods
procedure CreateChildForm(AForm: TForm); overload;
procedure CreateChildForm(AFormClass: TFormClass); overload;
end;
//```````````````````````````````````````````````````````````````````````````
// TcaFormPanel
//```````````````````````````````````````````````````````````````````````````
TcaFormPanel = class(TcaCustomFormPanel)
published
// TcaCustomFormPanel event properties
property OnCreateForm;
// Promoted properties
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BiDiMode;
property BorderWidth;
property BorderStyle;
// property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
property Locked;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
// Event properties
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDblClick;
property OnDockDrop;
property OnDockOver;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
//---------------------------------------------------------------------------
// IcaGraphicControl
//---------------------------------------------------------------------------
IcaGraphicControl = interface
['{52F8AC8E-BCB3-4088-BF18-6EAC25F2B316}']
function GetCanvas: TCanvas;
function GetMouseIsDown: Boolean;
function GetMouseIsOver: Boolean;
function GetOnPaint: TcaPaintEvent;
procedure Paint;
procedure SetOnPaint(const Value: TcaPaintEvent);
property Canvas: TCanvas read GetCanvas;
property MouseIsDown: Boolean read GetMouseIsDown;
property MouseIsOver: Boolean read GetMouseIsOver;
property OnPaint: TcaPaintEvent read GetOnPaint write SetOnPaint;
end;
//---------------------------------------------------------------------------
// TcaGraphicControl
//---------------------------------------------------------------------------
TcaGraphicControl = class(TControl, IcaGraphicControl)
private
// Private fields
FAutoSizeMargin: Integer;
FCanvas: TCanvas;
FMouseIsDown: Boolean;
FMouseIsOver: Boolean;
FOffScreenBitmap: TBitmap;
FOnPaint: TcaPaintEvent;
FUpdateCount: Integer;
// Property methods
function GetCanvas: TCanvas;
function GetMouseIsDown: Boolean;
function GetMouseIsOver: Boolean;
function GetOnPaint: TcaPaintEvent;
procedure SetAutoSizeMargin(const Value: Integer);
procedure SetOnPaint(const Value: TcaPaintEvent);
// Component message handlers
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
// Windows message handlers
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
protected
// Protected methods
function GetAdjustSizeDelta: Integer; virtual;
function GetOffScreenCanvas: TCanvas;
procedure AdjustSize; override;
procedure BufferedPaint(C: TCanvas; R: TRect); virtual;
procedure DoMouseEnter; virtual;
procedure DoMouseLeave; virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Paint; virtual;
procedure RequestPaint; virtual;
procedure UpdateOnScreenBitmap;
// Protected properties
property AutoSizeMargin: Integer read FAutoSizeMargin write SetAutoSizeMargin;
property Canvas: TCanvas read GetCanvas;
property MouseIsDown: Boolean read GetMouseIsDown;
property MouseIsOver: Boolean read GetMouseIsOver;
property OffScreenCanvas: TCanvas read GetOffScreenCanvas;
property OnPaint: TcaPaintEvent read GetOnPaint write SetOnPaint;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// Public methods
procedure BeginUpdate;
procedure EndUpdate;
end;
//---------------------------------------------------------------------------
// TcaXPGraphicControl
//---------------------------------------------------------------------------
TcaXPGraphicControl = class(TcaGraphicControl)
private
protected
public
end;
//---------------------------------------------------------------------------
// IcaSpacer
//---------------------------------------------------------------------------
IcaSpacer = interface
['{18414C8C-B37A-4111-8881-03B9F4C8088B}']
// Property methods
function GetGrooved: Boolean;
procedure SetGrooved(const Value: Boolean);
// Properties
property Grooved: Boolean read GetGrooved write SetGrooved;
end;
//---------------------------------------------------------------------------
// TcaSpacer
//---------------------------------------------------------------------------
TcaSpacer = class(TcaGraphicControl, IcaSpacer)
private
FGrooved: Boolean;
// Property methods
function GetGrooved: Boolean;
procedure SetGrooved(const Value: Boolean);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
// Properties
property Align;
property Grooved: Boolean read GetGrooved write SetGrooved;
property Width default 8;
property Height default 25;
end;
//---------------------------------------------------------------------------
// TcaSplitter
//---------------------------------------------------------------------------
TcaSplitter = class(TSplitter)
private
// Private fields
FPosition: Integer;
// Property methods
function GetPosition: Integer;
procedure SetPosition(const Value: Integer);
// Private methods
function FindControl: TControl;
procedure UpdateControlSize;
procedure UpdatePosition;
published
property Position: Integer read GetPosition write SetPosition;
end;
//---------------------------------------------------------------------------
// TcaMemo
//---------------------------------------------------------------------------
TcaMemo = class(TMemo)
published
property Action;
end;
//---------------------------------------------------------------------------
// IcaGraphicBox
//---------------------------------------------------------------------------
IcaGraphicBox = interface
['{E1D58E76-1FDA-41E5-906E-24060574BE6C}']
// Property methods
function GetColor: TColor;
function GetFrameColor: TColor;
function GetFrameWidth: Integer;
procedure SetColor(const Value: TColor);
procedure SetFrameColor(const Value: TColor);
procedure SetFrameWidth(const Value: Integer);
// Properties
property Color: TColor read GetColor write SetColor;
property FrameColor: TColor read GetFrameColor write SetFrameColor;
property FrameWidth: Integer read GetFrameWidth write SetFrameWidth;
end;
//---------------------------------------------------------------------------
// TcaGraphicBox
//---------------------------------------------------------------------------
TcaGraphicBox = class(TcaGraphicControl, IcaGraphicBox)
private
// Property fields
FColor: TColor;
FFrameColor: TColor;
FFrameWidth: Integer;
// Property methods
function GetColor: TColor;
function GetFrameColor: TColor;
function GetFrameWidth: Integer;
procedure SetColor(const Value: TColor);
procedure SetFrameColor(const Value: TColor);
procedure SetFrameWidth(const Value: Integer);
protected
// Protected methods
procedure BufferedPaint(C: TCanvas; R: TRect); override;
published
// Properties
property Align;
property Color: TColor read GetColor write SetColor;
property FrameColor: TColor read GetFrameColor write SetFrameColor;
property FrameWidth: Integer read GetFrameWidth write SetFrameWidth;
// Event properties
property OnPaint;
end;
implementation
//---------------------------------------------------------------------------
// TcaComponentFactory
//---------------------------------------------------------------------------
constructor TcaComponentFactory.Create(AClass: TComponentClass; AOwner: TComponent);
begin
inherited Create;
FComponentClass := AClass;
FComponentOwner := AOwner;
end;
function TcaComponentFactory.GetComponentClass: TComponentClass;
begin
Result := FComponentClass;
end;
function TcaComponentFactory.GetComponentOwner: TComponent;
begin
Result := FComponentOwner;
end;
function TcaComponentFactory.GetNextComponentName: String;
var
BaseName: String;
Index: Integer;
begin
BaseName := FComponentClass.ClassName;
System.Delete(BaseName, 1, 1);
Index := 1;
while FComponentOwner.FindComponent(BaseName + IntToStr(Index)) <> nil do
Inc(Index);
Result := BaseName + IntToStr(Index);
end;
function TcaComponentFactory.NewComponent: TComponent;
var
CompState: IcaComponentState;
begin
Result := TComponent(FComponentClass.Create(FComponentOwner));
if FComponentOwner <> nil then
begin
CompState := TcaComponentState.Create;
CompState.Component := FComponentOwner;
if CompState.IsDesigning then
if (FComponentOwner is TCustomForm) or (FComponentOwner is TDataModule) then
Result.Name := GetNextComponentName;
end;
end;
procedure TcaComponentFactory.SetComponentClass(const Value: TComponentClass);
begin
FComponentClass := Value;
end;
procedure TcaComponentFactory.SetComponentOwner(const Value: TComponent);
begin
FComponentOwner := Value;
end;
//---------------------------------------------------------------------------
// TcaMargin
//---------------------------------------------------------------------------
procedure TcaMargin.Assign(Source: TPersistent);
var
AMargin: TcaMargin;
begin
if Source is TcaMargin then
begin
AMargin := TcaMargin(Source);
Left := AMargin.Left;
Top := AMargin.Top;
Right := AMargin.Right;
Bottom := AMargin.Bottom;
end;
inherited;
end;
procedure TcaMargin.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TcaMargin.Changed;
begin
if FUpdateCount = 0 then DoChanged;
end;
procedure TcaMargin.DoChanged;
begin
if Assigned(FOnChanged) then FOnChanged(Self);
end;
procedure TcaMargin.EndUpdate;
begin
Dec(FUpdateCount);
Changed;
end;
function TcaMargin.GetBottom: Integer;
begin
Result := FBottom;
end;
function TcaMargin.GetLeft: Integer;
begin
Result := FLeft;
end;
function TcaMargin.GetOnChanged: TNotifyEvent;
begin
Result := FOnChanged;
end;
function TcaMargin.GetRight: Integer;
begin
Result := FRight;
end;
function TcaMargin.GetTop: Integer;
begin
Result := FTop;
end;
procedure TcaMargin.SetBottom(const Value: Integer);
begin
if Value <> FBottom then
begin
FBottom := Value;
Changed;
end;
end;
procedure TcaMargin.SetLeft(const Value: Integer);
begin
if Value <> FLeft then
begin
FLeft := Value;
Changed;
end;
end;
procedure TcaMargin.SetOnChanged(const Value: TNotifyEvent);
begin
FOnChanged := Value;
end;
procedure TcaMargin.SetRight(const Value: Integer);
begin
if Value <> FRight then
begin
FRight := Value;
Changed;
end;
end;
procedure TcaMargin.SetTop(const Value: Integer);
begin
if Value <> FTop then
begin
FTop := Value;
Changed;
end;
end;
//---------------------------------------------------------------------------
// TcaCustomPanel
//---------------------------------------------------------------------------
constructor TcaCustomPanel.Create(AOwner: TComponent);
begin
inherited;
CreateOffScreenBitmap;
CreateFrameObjects;
end;
destructor TcaCustomPanel.Destroy;
begin
FreeFrameObjects;
FreeOffScreenBitmap;
RestoreWindowProc;
inherited;
end;
// Protected methods
function TcaCustomPanel.GetOffScreenCanvas: TCanvas;
begin
Result := nil;
if FOffScreenBitmap <> nil then
begin
FOffScreenBitmap.Width := Width;
FOffScreenBitmap.Height := Height;
Result := FOffScreenBitmap.Canvas;
end;
end;
procedure TcaCustomPanel.CreateWnd;
begin
inherited;
end;
procedure TcaCustomPanel.DoClickOutside(AClickedControl: TControl);
begin
if Assigned(FOnClickOutside) then FOnClickOutside(Self, AClickedControl);
end;
procedure TcaCustomPanel.DoMouseEnter;
begin
if Assigned(FOnMouseEnter) then FOnMouseEnter(Self);
end;
procedure TcaCustomPanel.DoMouseLeave;
begin
if Assigned(FOnMouseLeave) then FOnMouseLeave(Self);
end;
procedure TcaCustomPanel.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
if NewStyleControls then
begin
if FTransparent then ExStyle := ExStyle or WS_EX_TRANSPARENT;
end;
end;
end;
procedure TcaCustomPanel.Paint;
var
C: TCanvas;
begin
if not FTransparent then
begin
C := GetOffScreenCanvas;
C.Brush.Color := Color;
C.Brush.Style := bsSolid;
C.FillRect(Rect(0, 0, Width, Height));
FFrameImpl.Update;
UpdateOnScreenBitmap;
end
else
inherited;
end;
procedure TcaCustomPanel.UpdateOffScreenBitmap;
begin
BitBlt(FOffScreenBitmap.Canvas.Handle, 0, 0, Width, Height, Canvas.Handle, 0, 0, SRCCOPY);
end;
procedure TcaCustomPanel.UpdateOnScreenBitmap;
begin
BitBlt(Canvas.Handle, 0, 0, Width, Height, FOffScreenBitmap.Canvas.Handle, 0, 0, SRCCOPY);
end;
// Private methods
procedure TcaCustomPanel.CreateFrameObjects;
begin
FFrameImpl := TcaFrame.Create; // FFrameImpl: IcaFrame
FFrameImpl.Control := Self;
FFrameImpl.AdjustOffsets(0, 0, -2, -2);
FFrameImpl.Sides := [sdLeft, sdTop, sdRight, sdBottom];
FFrameImpl.Style := fsRaisedPanel;
FFrameImpl.LineColor := clBtnShadow;
FFrameImpl.FocusedSides := [sdLeft, sdTop, sdRight, sdBottom];
FFrameImpl.FocusedStyle := fsRaisedPanel;
FFrameImpl.FocusedLineColor := clBtnShadow;
FFrame := TcaFrameProperties.Create;
FFrame.Frame := FFrameImpl;
end;
procedure TcaCustomPanel.CreateOffScreenBitmap;
begin
FOffScreenBitmap := TBitmap.Create;
end;
procedure TcaCustomPanel.FreeFrameObjects;
begin
FFrame.Free;
end;
procedure TcaCustomPanel.FreeOffScreenBitmap;
begin
FOffScreenBitmap.Free;
end;
procedure TcaCustomPanel.HookWindowProc(var Message: TMessage);
begin
DoHookWindowProc(Message);
FDefaultWindowProc(Message);
end;
procedure TcaCustomPanel.ReplaceWindowProc;
begin
if Owner is TForm then
begin
FDefaultWindowProc := TControl(Owner).WindowProc;
TControl(Owner).WindowProc := HookWindowProc;
end;
end;
procedure TcaCustomPanel.RestoreWindowProc;
begin
if Owner is TForm then
if Assigned(FDefaultWindowProc) then
TControl(Owner).WindowProc := FDefaultWindowProc;
end;
// Component mesage handlers
procedure TcaCustomPanel.CMCancelMode(var Message: TCMCancelMode);
begin
inherited;
DoClickOutside(Message.Sender);
end;
procedure TcaCustomPanel.CMFocusChanged(var Message: TCMFocusChanged);
begin
inherited;
FFrameImpl.Focused := Focused;
end;
procedure TcaCustomPanel.DoHookWindowProc(var Message: TMessage);
begin
if Message.Msg = WM_LBUTTONDOWN then
Pass;
inherited;
end;
procedure TcaCustomPanel.CMMouseenter(var Message: TMessage);
begin
inherited;
DoMouseEnter;
end;
procedure TcaCustomPanel.CMMouseleave(var Message: TMessage);
begin
inherited;
DoMouseLeave;
end;
// Property methods
function TcaCustomPanel.GetTransparent: Boolean;
begin
Result := FTransparent;
end;
procedure TcaCustomPanel.SetSubClassForm(const Value: Boolean);
begin
if Value <> FSubClassForm then
begin
FSubClassForm := Value;
if FSubClassForm then
ReplaceWindowProc
else
RestoreWindowProc;
end;
end;
procedure TcaCustomPanel.SetTransparent(const Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
RecreateWnd;
end;
end;
//---------------------------------------------------------------------------
// TcaCustomFormPanel
//---------------------------------------------------------------------------
// Public methods
procedure TcaCustomFormPanel.CreateChildForm(AForm: TForm);
begin
FForm := AForm;
UpdateChildForm;
end;
procedure TcaCustomFormPanel.CreateChildForm(AFormClass: TFormClass);
begin
FForm := AFormClass.Create(Application);
UpdateChildForm;
end;
// Protected methods
procedure TcaCustomFormPanel.CreateWnd;
begin
inherited;
UpdateChildForm;
end;
procedure TcaCustomFormPanel.DoBeforeShowForm(AForm: TForm);
begin
if Assigned(FOnBeforeShowForm) then FOnBeforeShowForm(Self, FForm);
end;
procedure TcaCustomFormPanel.DoCreateForm(var AForm: TForm);
begin
if Assigned(FOnCreateForm) then FOnCreateForm(Self, FForm);
end;
// Private methods
procedure TcaCustomFormPanel.UpdateChildForm;
begin
if not Assigned(FForm) then
if Assigned(FOnCreateForm) then FOnCreateForm(Self, FForm);
if FForm <> nil then
begin
FForm.BorderStyle := bsNone;
FForm.BorderIcons := [];
FForm.Caption := '';
FForm.Align := alClient;
FForm.Parent := Self;
DoBeforeShowForm(FForm);
FForm.Show;
end;
end;
//---------------------------------------------------------------------------
// TcaGraphicControl
//---------------------------------------------------------------------------
constructor TcaGraphicControl.Create(AOwner: TComponent);
begin
inherited;
FOffScreenBitmap := TBitmap.Create;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FAutoSizeMargin := 5;
end;
destructor TcaGraphicControl.Destroy;
begin
if GetCaptureControl = Self then SetCaptureControl(nil);
FCanvas.Free;
FOffScreenBitmap.Free;
inherited;
end;
// Public methods
procedure TcaGraphicControl.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TcaGraphicControl.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then Invalidate;
end;
// Protected methods
function TcaGraphicControl.GetAdjustSizeDelta: Integer;
begin
Result := FAutoSizeMargin * 2 + 1;
end;
function TcaGraphicControl.GetOffScreenCanvas: TCanvas;
begin
Result := nil;
if FOffScreenBitmap <> nil then
begin
FOffScreenBitmap.Width := Width;
FOffScreenBitmap.Height := Height;
Result := FOffScreenBitmap.Canvas;
end;
end;
procedure TcaGraphicControl.AdjustSize;
begin
if Parent <> nil then
begin
Canvas.Font.Assign(Font);
Width := Canvas.TextWidth(Caption) + GetAdjustSizeDelta;
end;
end;
procedure TcaGraphicControl.BufferedPaint(C: TCanvas; R: TRect);
begin
// Virtual
end;
procedure TcaGraphicControl.DoMouseEnter;
begin
// Virtual
end;
procedure TcaGraphicControl.DoMouseLeave;
begin
// Virtual
end;
procedure TcaGraphicControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
FMouseIsDown := True;
end;
procedure TcaGraphicControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
FMouseIsDown := False;
end;
procedure TcaGraphicControl.Paint;
var
C: TCanvas;
CompState: IcaComponentState;
begin
CompState := TcaComponentState.Create(Self);
if not CompState.IsDestroying then
if AutoSize then AdjustSize;
C := GetOffScreenCanvas;
BufferedPaint(C, ClientRect);
if Assigned(FOnPaint) then
FOnPaint(Self, C, ClientRect);
UpdateOnScreenBitmap;
end;
procedure TcaGraphicControl.RequestPaint;
begin
Invalidate;
end;
procedure TcaGraphicControl.UpdateOnScreenBitmap;
begin
BitBlt(FCanvas.Handle, 0, 0, Width, Height, FOffScreenBitmap.Canvas.Handle, 0, 0, SRCCOPY);
end;
// Message handlers
procedure TcaGraphicControl.CMMouseEnter(var Message: TMessage);
begin
inherited;
FMouseIsOver := True;
DoMouseEnter;
end;
procedure TcaGraphicControl.CMMouseLeave(var Message: TMessage);
begin
inherited;
FMouseIsOver := False;
DoMouseLeave;
end;
procedure TcaGraphicControl.WMPaint(var Message: TWMPaint);
begin
if (FOffScreenBitmap <> nil) and (Message.DC <> 0) then
begin
FCanvas.Lock;
try
FCanvas.Handle := Message.DC;
try
Paint;
finally
FCanvas.Handle := 0;
end;
finally
FCanvas.Unlock;
end;
end;
end;
// Property methods
function TcaGraphicControl.GetCanvas: TCanvas;
begin
Result := FCanvas;
end;
function TcaGraphicControl.GetMouseIsDown: Boolean;
begin
Result := FMouseIsDown;
end;
function TcaGraphicControl.GetMouseIsOver: Boolean;
begin
Result := FMouseIsOver;
end;
function TcaGraphicControl.GetOnPaint: TcaPaintEvent;
begin
Result := FOnPaint;
end;
procedure TcaGraphicControl.SetAutoSizeMargin(const Value: Integer);
begin
if Value <> FAutoSizeMargin then
begin
FAutoSizeMargin := Value;
RequestPaint;
end;
end;
procedure TcaGraphicControl.SetOnPaint(const Value: TcaPaintEvent);
begin
FOnPaint := Value;
end;
//---------------------------------------------------------------------------
// TcaSpacer
//---------------------------------------------------------------------------
constructor TcaSpacer.Create(AOwner: TComponent);
begin
inherited;
Width := 8;
Height := 25;
end;
// Protected methods
type
TControlEx = class(TControl);
procedure TcaSpacer.Paint;
var
C: TCanvas;
X1: Integer;
X2: Integer;
Y1: Integer;
Y2: Integer;
O: TControlEx;
R: TRect;
begin
if FGrooved then
begin
C := OffScreenCanvas;
X1 := Width div 2;
X2 := X1 + 1;
Y1 := 1;
Y2 := Height;
if Owner <> nil then
if Owner is TControl then
begin
O := TControlEx(Owner);
C.Brush.Color := O.Color;
R := ClientRect;
C.FillRect(R);
end;
C.Pen.Style := psSolid;
C.Pen.Color := clBtnShadow;
C.MoveTo(X1, Y1);
C.LineTo(X1, Y2);
C.Pen.Color := clBtnHighlight;
C.MoveTo(X2, Y1);
C.LineTo(X2, Y2);
UpdateOnScreenBitmap;
end;
end;
// Property methods
function TcaSpacer.GetGrooved: Boolean;
begin
Result := FGrooved;
end;
procedure TcaSpacer.SetGrooved(const Value: Boolean);
begin
if Value <> FGrooved then
begin
FGrooved := Value;
RequestPaint;
end;
end;
//---------------------------------------------------------------------------
// TcaSplitter
//---------------------------------------------------------------------------
function TcaSplitter.FindControl: TControl;
var
P: TPoint;
I: Integer;
R: TRect;
begin
Result := nil;
P := Point(Left, Top);
case Align of
alLeft: Dec(P.X);
alRight: Inc(P.X, Width);
alTop: Dec(P.Y);
alBottom: Inc(P.Y, Height);
else
Exit;
end;
for I := 0 to Parent.ControlCount - 1 do
begin
Result := Parent.Controls[I];
if Result.Visible and Result.Enabled then
begin
R := Result.BoundsRect;
if (R.Right - R.Left) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Left)
else
Inc(R.Right);
if (R.Bottom - R.Top) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Top)
else
Inc(R.Bottom);
if PtInRect(R, P) then Exit;
end;
end;
Result := nil;
end;
procedure TcaSplitter.UpdateControlSize;
var
Control: TControl;
begin
Control := FindControl;
if Control <> nil then
begin
case Align of
alNone: Pass;
alTop: Control.Height := FPosition;
alBottom: Control.Height := FPosition;
alLeft: Control.Width := FPosition;
alRight: Control.Width := FPosition;
alClient: Pass;
{$IFDEF D7_UP}
alCustom: Pass;
{$ENDIF}
end;
end;
end;
procedure TcaSplitter.UpdatePosition;
var
Control: TControl;
begin
Control := FindControl;
if Control <> nil then
begin
case Align of
alNone: Pass;
alTop: FPosition := Control.Height;
alBottom: FPosition := Control.Height;
alLeft: FPosition := Control.Width;
alRight: FPosition := Control.Width;
alClient: Pass;
{$IFDEF D7_UP}
alCustom: Pass;
{$ENDIF}
end;
end;
end;
// Property methods
function TcaSplitter.GetPosition: Integer;
begin
UpdatePosition;
Result := FPosition;
end;
procedure TcaSplitter.SetPosition(const Value: Integer);
begin
if Value <> FPosition then
begin
FPosition := Value;
UpdateControlSize;
end;
end;
//---------------------------------------------------------------------------
// TcaGraphicBox
//---------------------------------------------------------------------------
// Protected methods
procedure TcaGraphicBox.BufferedPaint(C: TCanvas; R: TRect);
var
P1, P2, P3, P4: TPoint;
begin
C.Brush.Color := FColor;
C.Brush.Style := bsSolid;
C.Pen.Color := FFrameColor;
C.Pen.Style := psSolid;
P1 := Point(0, 0);
P2 := Point(Pred(Width), 0);
P3 := Point(Pred(Width), Pred(Height));
P4 := Point(0, Pred(Height));
C.Polygon([P1, P2, P3, P4]);
end;
// Property methods
function TcaGraphicBox.GetColor: TColor;
begin
Result := FColor;
end;
function TcaGraphicBox.GetFrameColor: TColor;
begin
Result := FFrameColor;
end;
function TcaGraphicBox.GetFrameWidth: Integer;
begin
Result := FFrameWidth;
end;
procedure TcaGraphicBox.SetColor(const Value: TColor);
begin
if Value <> FColor then
begin
FColor := Value;
RequestPaint;
end;
end;
procedure TcaGraphicBox.SetFrameColor(const Value: TColor);
begin
if Value <> FFrameColor then
begin
FFrameColor := Value;
RequestPaint;
end;
end;
procedure TcaGraphicBox.SetFrameWidth(const Value: Integer);
begin
if Value <> FFrameWidth then
begin
FFrameWidth := Value;
RequestPaint;
end;
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Collections;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Comparers.Intf,
ADAPT.Collections.Intf, ADAPT.Collections.Abstract;
{$I ADAPT_RTTI.inc}
type
/// <summary><c>A Simple Generic Array with basic Management Methods.</c></summary>
/// <remarks>
/// <para><c>Use IADArray or IADArrayReader if you want to take advantage of Reference Counting.</c></para>
/// <para><c>This is NOT Threadsafe</c></para>
/// </remarks>
TADArray<T> = class(TADObject, IADArrayReader<T>, IADArray<T>)
private
FArray: TArray<IADValueHolder<T>>;
FCapacityInitial: Integer;
// Getters
{ IADArrayReader<T> }
function GetCapacity: Integer;
function GetItem(const AIndex: Integer): T;
{ IADArray<T> }
function GetReader: IADArrayReader<T>;
// Setters
{ IADArray<T> }
procedure SetCapacity(const ACapacity: Integer);
procedure SetItem(const AIndex: Integer; const AItem: T);
public
constructor Create(const ACapacity: Integer = 0); reintroduce; virtual;
destructor Destroy; override;
// Management Methods
{ IADArray<T> }
procedure Clear;
procedure Delete(const AIndex: Integer); overload;
procedure Delete(const AFirstIndex, ACount: Integer); overload;
procedure Finalize(const AIndex, ACount: Integer);
procedure Insert(const AItem: T; const AIndex: Integer);
procedure Move(const AFromIndex, AToIndex, ACount: Integer);
// Properties
{ IADArrayReader<T> }
property Capacity: Integer read GetCapacity;
property Items[const AIndex: Integer]: T read GetItem; default;
{ IADArray<T> }
property Items[const AIndex: Integer]: T read GetItem write SetItem; default;
property Reader: IADArrayReader<T> read GetReader;
end;
/// <summary><c>A Geometric Allocation Algorithm for Lists.</c></summary>
/// <remarks>
/// <para><c>When the number of Vacant Slots falls below the Threshold, the number of Vacant Slots increases by the value of the current Capacity multiplied by the Mulitplier.</c></para>
/// <para><c>This Expander Type is NOT Threadsafe.</c></para>
/// </remarks>
TADExpanderGeometric = class(TADExpander, IADExpanderGeometric)
private
FMultiplier: Single;
FThreshold: Integer;
protected
// Getters
{ IADExpanderGeometric }
function GetCapacityMultiplier: Single; virtual;
function GetCapacityThreshold: Integer; virtual;
// Setters
{ IADExpanderGeometric }
procedure SetCapacityMultiplier(const AMultiplier: Single); virtual;
procedure SetCapacityThreshold(const AThreshold: Integer); virtual;
public
{ IADExpanderGeometric }
function CheckExpand(const ACapacity, ACurrentCount, AAdditionalRequired: Integer): Integer; override;
public
// Properties
{ IADExpanderGeometric }
property CapacityMultiplier: Single read GetCapacityMultiplier write SetCapacityMultiplier;
property CapacityThreshold: Integer read GetCapacityThreshold write SetCapacityThreshold;
end;
/// <summary><c>Generic List Collection.</c></summary>
/// <remarks>
/// <para><c>Use IADListReader for Read-Only access.</c></para>
/// <para><c>Use IADList for Read/Write access.</c></para>
/// <para><c>Use IADIterableList for Iterators.</c></para>
/// <para><c>Call .Iterator against IADListReader to return the IADIterableList interface reference.</c></para>
/// <para><c>Cast to IADCompactable to define a Compactor Type.</c></para>
/// <para><c>Cast to IADExpandable to define an Expander Type.</c></para>
/// </remarks>
TADList<T> = class(TADListExpandableBase<T>)
protected
// Overrides
{ TADListBase Overrides }
function AddActual(const AItem: T): Integer; override;
procedure DeleteActual(const AIndex: Integer); override;
procedure InsertActual(const AItem: T; const AIndex: Integer); override;
procedure SetItem(const AIndex: Integer; const AItem: T); override;
public
/// <summary><c>Creates an instance of your Collection using the Default Expander and Compactor Types.</c></summary>
constructor Create(const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using a Custom Expander Instance, and the default Compactor Type.</c></summary>
constructor Create(const AExpander: IADExpander; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using the default Expander Type, and a Custom Compactor Instance.</c></summary>
constructor Create(const ACompactor: IADCompactor; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using a Custom Expander and Compactor Instance.</c></summary>
constructor Create(const AExpander: IADExpander; const ACompactor: IADCompactor; const AInitialCapacity: Integer = 0); reintroduce; overload; virtual;
end;
/// <summary><c>Generic Sorted List Collection.</c></summary>
/// <remarks>
/// <para><c>Use IADListReader for Read-Only access.</c></para>
/// <para><c>Use IADList for Read/Write access.</c></para>
/// <para><c>Use IADIterableList for Iterators.</c></para>
/// <para><c>Call .Iterator against IADListReader to return the IADIterableList interface reference.</c></para>
/// <para><c>Cast to IADCompactable to define a Compactor Type.</c></para>
/// <para><c>Cast to IADExpandable to define an Expander Type.</c></para>
/// </remarks>
TADSortedList<T> = class(TADListExpandableBase<T>, IADSortedListReader<T>, IADSortedList<T>, IADComparable<T>)
private
FComparer: IADComparer<T>;
protected
// Getters
{ IADComparable<T> }
function GetComparer: IADComparer<T>; virtual;
{ IADSortedList<T> }
function GetReader: IADSortedListReader<T>;
// Setters
{ IADComparable<T> }
procedure SetComparer(const AComparer: IADComparer<T>); virtual;
// Overrides
{ TADCollection Overrides }
function GetSortedState: TADSortedState; override;
{ TADListBase Overrides }
/// <summary><c>Adds the Item to the correct Index of the Array WITHOUT checking capacity.</c></summary>
/// <returns>
/// <para>-1<c> if the Item CANNOT be added.</c></para>
/// <para>0 OR GREATER<c> if the Item has be added, where the Value represents the Index of the Item.</c></para>
/// </returns>
function AddActual(const AItem: T): Integer; override;
procedure DeleteActual(const AIndex: Integer); override;
procedure InsertActual(const AItem: T; const AIndex: Integer); override; // This effectively passes the call along to AddAcutal as we cannot Insert with explicit Indexes on a Sorted List.
procedure SetItem(const AIndex: Integer; const AItem: T); override; // This effectively deletes the item at AIndex, then calls AddActual to add AItem at its Sorted Index. We cannot explicitly set Items on a Sorted List.
// Overridables
/// <summary><c>Determines the Index at which an Item would need to be Inserted for the List to remain in-order.</c></summary>
/// <remarks>
/// <para><c>This is basically a Binary Sort implementation.<c></para>
/// </remarks>
function GetSortedPosition(const AItem: T): Integer; virtual;
public
/// <summary><c>Creates an instance of your Collection using the Default Expander and Compactor Types.</c></summary>
constructor Create(const AComparer: IADComparer<T>; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using a Custom Expander Instance, and the default Compactor Type.</c></summary>
constructor Create(const AComparer: IADComparer<T>; const AExpander: IADExpander; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using the default Expander Type, and a Custom Compactor Instance.</c></summary>
constructor Create(const AComparer: IADComparer<T>; const ACompactor: IADCompactor; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Collection using a Custom Expander and Compactor Instance.</c></summary>
constructor Create(const AComparer: IADComparer<T>; const AExpander: IADExpander; const ACompactor: IADCompactor; const AInitialCapacity: Integer = 0); reintroduce; overload; virtual;
// Management Methods
{ IADSortedListReader<T> }
function Contains(const AItem: T): Boolean;
function ContainsAll(const AItems: Array of T): Boolean;
function ContainsAny(const AItems: Array of T): Boolean;
function ContainsNone(const AItems: Array of T): Boolean;
function EqualItems(const AList: IADList<T>): Boolean;
function IndexOf(const AItem: T): Integer;
{ IADSortedList<T> }
procedure Remove(const AItem: T);
procedure RemoveItems(const AItems: Array of T);
end;
/// <summary><c>A Generic Fixed-Capacity Revolving List</c></summary>
/// <remarks>
/// <para><c>When the current Index is equal to the Capacity, the Index resets to 0, and Items are subsequently Replaced by new ones.</c></para>
/// <para><c>Use IADListReader for Read-Only List access.</c></para>
/// <para><c>Use IADList for Read/Write List access.</c></para>
/// <para><c>Use IADIterableList for Iterators.</c></para>
/// <para><c>Call .Iterator against IADListReader to return the IADIterableList interface reference.</c></para>
/// <para><c>Use IADCircularListReader for Read-Only Circular List access.</c></para>
/// <para><c>Use IADCircularList for Read/Write Circular List access.</c></para> ///
/// <para><c>This type is NOT Threadsafe.</c></para>
/// </remarks>
TADCircularList<T> = class(TADListBase<T>, IADCircularListReader<T>, IADCircularList<T>)
private
// Getters
protected
// Getters
{ IADCircularListReader<T> }
function GetNewestIndex: Integer; virtual;
function GetNewest: T; virtual;
function GetOldestIndex: Integer; virtual;
function GetOldest: T; virtual;
{ IADCircularList<T> }
function GetReader: IADCircularListReader<T>;
// Setters
{ TADListBase<T> Overrides }
procedure SetItem(const AIndex: Integer; const AItem: T); override;
{ IADCircularListReader<T> }
{ IADCircularList<T> }
// Overrides
{ TADListBase<T> }
function AddActual(const AItem: T): Integer; override;
procedure DeleteActual(const AIndex: Integer); override;
procedure InsertActual(const AItem: T; const AIndex: Integer); override;
public
// Properties
{ IADCircularListReader<T> }
property NewestIndex: Integer read GetNewestIndex;
property Newest: T read GetNewest;
property OldestIndex: Integer read GetOldestIndex;
property Oldest: T read GetOldest;
{ IADCircularList<T> }
property Reader: IADCircularListReader<T> read GetReader;
end;
/// <summary><c>Generic Map Collection.</c></summary>
/// <remarks>
/// <para><c>Use IADMapReader for Read-Only access.</c></para>
/// <para><c>Use IADMap for Read/Write access.</c></para>
/// <para><c>Use IADIterableMap for Iterators.</c></para>
/// <para><c>Call .Iterator against IADMapReader to return the IADIterableMap interface reference.</c></para>
/// <para><c>Use IADCompactable to Get/Set the Compactor.</c></para>
/// <para><c>Use IADExpandable to Get/Set the Expander.</c></para>
/// </remarks>
TADMap<TKey, TValue> = class(TADMapExpandableBase<TKey, TValue>)
protected
// Overrides
{ TADMapBase<TKey, TValue> Override }
procedure CreateSorter; override;
public
/// <summary><c>Creates an instance of your Sorted List using the Default Expander and Compactor Types.</c></summary>
constructor Create(const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Sorted List using a Custom Expander Instance, and the default Compactor Type.</c></summary>
constructor Create(const AExpander: IADExpander; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Sorted List using the default Expander Type, and a Custom Compactor Instance.</c></summary>
constructor Create(const ACompactor: IADCompactor; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer = 0); reintroduce; overload;
/// <summary><c>Creates an instance of your Sorted List using a Custom Expander and Compactor Instance.</c></summary>
constructor Create(const AExpander: IADExpander; const ACompactor: IADCompactor; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer = 0); reintroduce; overload; virtual;
end;
/// <summary><c>Generic Circular Map Collection.</c></summary>
/// <remarks>
/// <para><c>Designed to have a fixed Capacity, it automatically removes older Items to make way for new ones.</c></para>
/// <para><c>Use IADMapReader for Read-Only access.</c></para>
/// <para><c>Use IADMap for Read/Write access.</c></para>
/// <para><c>Use IADIterableMap for Iterators.</c></para>
/// <para><c>Call .Iterator against IADMapReader to return the IADIterableMap interface reference.</c></para>
/// </remarks>
TADCircularMap<TKey, TValue> = class(TADMapBase<TKey, TValue>)
protected
// Overrides
{ TADMapBase<TKey, TValue> Override }
procedure CreateSorter; override;
function AddActual(const AItem: IADKeyValuePair<TKey, TValue>): Integer; override;
public
/// <summary><c>Creates an instance of your Circular Map with the given Capacity (Default = 10).</c></summary>
constructor Create(const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer = 10); reintroduce; overload;
end;
/// <summary><c>Generic Tree Collection.</c></summary>
/// <remarks>
/// <para><c>Use IADTreeNodeReader for Read-Only access.</c></para>
/// <para><c>Use IADTreeNode for Read/Write access.</c></para>
/// <para><c>Use IADCompactable to define a Compactor for the Child List.</c></para>
/// <para><c>Use IADExpandable to define an Expander for the Child List.</c></para>
/// <para><c>Iterators are defined in both IADTreeNodeReader and IADTreeNode Interfaces.</c></para>
/// <para><c>Call IADTreeNode.Reader to return an IADTreeNodeReader referenced Interface.</c></para>
/// </remarks>
TADTreeNode<T> = class(TADObject, IADTreeNodeReader<T>, IADTreeNode<T>, IADCompactable, IADExpandable)
private
FChildren: IADList<IADTreeNode<T>>;
FParent: Pointer;
FValue: T;
protected
// Geters
{ IADTreeNodeReader<T> }
function GetChildCount: Integer;
function GetChildCountRecursive: Integer;
function GetChildReader(const AIndex: Integer): IADTreeNodeReader<T>;
function GetDepth: Integer;
function GetIndexAsChild: Integer;
function GetIndexOf(const AChild: IADTreeNodeReader<T>): Integer;
function GetIsBranch: Boolean;
function GetIsLeaf: Boolean;
function GetIsRoot: Boolean;
function GetParentReader: IADTreeNodeReader<T>;
function GetRootReader: IADTreeNodeReader<T>;
function GetValue: T;
{ IADTreeNode<T> }
function GetChild(const AIndex: Integer): IADTreeNode<T>;
function GetParent: IADTreeNode<T>;
function GetReader: IADTreeNodeReader<T>;
function GetRoot: IADTreeNode<T>;
{ IADCompactable }
function GetCompactor: IADCompactor;
{ IADExpandable }
function GetExpander: IADExpander;
// Setters
{ IADTreeNode<T> }
procedure SetParent(const AParent: IADTreeNode<T>); virtual;
procedure SetValue(const AValue: T); virtual;
{ IADCompactable }
procedure SetCompactor(const ACompactor: IADCompactor);
{ IADExpandable }
procedure SetExpander(const AExpander: IADExpander);
public
constructor Create(const AParent: IADTreeNode<T>; const AValue: T); reintroduce; overload;
constructor Create(const AParent: IADTreeNode<T>); reintroduce; overload;
constructor Create(const AValue: T); reintroduce; overload;
// Iterators
{ IADTreeNodeReader<T> }
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>); overload;
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>); overload;
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>); overload;
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>); overload;
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>); overload;
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>); overload;
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>); overload;
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>); overload;
{ IADTreeNode<T> }
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>); overload;
procedure PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>); overload;
procedure PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>); overload;
// Management Methods
{ IADTreeNode<T> }
procedure AddChild(const AChild: IADTreeNode<T>; const AIndex: Integer = -1);
procedure MoveTo(const ANewParent: IADTreeNode<T>; const AIndex: Integer = -1); overload;
procedure MoveTo(const AIndex: Integer); overload;
procedure RemoveChild(const AChild: IADTreeNodeReader<T>);
{ IADCompactable }
procedure Compact;
// Properties
{ IADTreeNodeReader<T> }
property ChildCount: Integer read GetChildCount;
property ChildCountRecursive: Integer read GetChildCountRecursive;
property ChildReader[const AIndex: Integer]: IADTreeNodeReader<T> read GetChildReader;
property Depth: Integer read GetDepth;
property IndexAsChild: Integer read GetIndexAsChild;
property IndexOf[const AChild: IADTreeNodeReader<T>]: Integer read GetIndexOf;
property IsBranch: Boolean read GetIsBranch;
property IsLeaf: Boolean read GetIsLeaf;
property IsRoot: Boolean read GetIsRoot;
property ParentReader: IADTreeNodeReader<T> read GetParentReader;
property RootReader: IADTreeNodeReader<T> read GetRootReader;
{ IADTreeNode<T> }
property Child[const AIndex: Integer]: IADTreeNode<T> read GetChild; default;
property Parent: IADTreeNode<T> read GetParent;
property Root: IADTreeNode<T> read GetRoot;
property Value: T read GetValue write SetValue;
end;
TADStackQueue<T> = class(TADObject, IADStackQueueReader<T>, IADStackQueue<T>, IADIterableList<T>)
private
FPriorityCount: Integer;
FQueues: IADArray<IADList<T>>; // Bucket of Queues (one per Priority)
FStacks: IADArray<IADList<T>>; // Bucket of Stacks (one per Priority)
function CheckPriority(const APriority: Integer; const AReturnArrayIndex: Boolean = False): Integer;
protected
// Getters
{ IADStackQueueReader<T> }
function GetCount: Integer; overload;
function GetCount(const APriority: Integer): Integer; overload;
function GetIterator: IADIterableList<T>; virtual;
function GetQueueCount: Integer; overload; virtual;
function GetQueueCount(const APriority: Integer): Integer; overload; virtual;
function GetStackCount: Integer; overload; virtual;
function GetStackCount(const APriority: Integer): Integer; overload; virtual;
{ IADStackQueue<T> }
function GetReader: IADStackQueueReader<T>;
public
/// <summary><c>Creates a Stack/Queue instance containing the given number of Priority Stacks and Queues (respectively).</c></summary>
/// <remarks>
/// <para>NOTE: <c>Once instanciated, you cannot change the number of Priority Stacks and Queues.</c></para>
/// </remarks>
constructor Create(const APriorityCount: Integer = 5); reintroduce;
// Management Methods
procedure Queue(const AItem: T); overload; virtual;
procedure Queue(const AItem: T; const APriority: Integer); overload; virtual;
procedure Queue(const AItems: IADListReader<T>); overload; virtual;
procedure Queue(const AItems: IADListReader<T>; const APriority: Integer); overload; virtual;
procedure Queue(const AItems: Array of T); overload; virtual;
procedure Queue(const AItems: Array of T; const APriority: Integer); overload; virtual;
procedure Stack(const AItem: T); overload; virtual;
procedure Stack(const AItem: T; const APriority: Integer); overload; virtual;
procedure Stack(const AItems: IADListReader<T>); overload; virtual;
procedure Stack(const AItems: IADListReader<T>; const APriority: Integer); overload; virtual;
procedure Stack(const AItems: Array of T); overload; virtual;
procedure Stack(const AItems: Array of T; const APriority: Integer); overload; virtual;
// Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListItemCallbackAnon<T>; const ADirection: TADIterateDirection = idRight); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure Iterate(const ACallback: TADListItemCallbackOfObject<T>; const ADirection: TADIterateDirection = idRight); overload;
procedure Iterate(const ACallback: TADListItemCallbackUnbound<T>; const ADirection: TADIterateDirection = idRight); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateBackward(const ACallback: TADListItemCallbackOfObject<T>); overload;
procedure IterateBackward(const ACallback: TADListItemCallbackUnbound<T>); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure IterateForward(const ACallback: TADListItemCallbackOfObject<T>); overload;
procedure IterateForward(const ACallback: TADListItemCallbackUnbound<T>); overload;
// Specialized Queue Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessQueue(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessQueue(const AOnItem: TADListItemCallbackOfObject<T>); overload;
procedure ProcessQueue(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Specialized Stack Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessStack(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessStack(const AOnItem: TADListItemCallbackOfObject<T>); overload;
procedure ProcessStack(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Specialized Stack/Queue Iterators
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackAnon<T>); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackOfObject<T>); overload;
procedure ProcessStackQueue(const AOnItem: TADListItemCallbackUnbound<T>); overload;
// Properties
{ IADStackQueueReader<T> }
property CountTotal: Integer read GetCount;
property Count[const APriority: Integer]: Integer read GetCount;
property Iterator: IADIterableList<T> read GetIterator;
property QueueTotalCount: Integer read GetQueueCount;
property QueueCount[const APriority: Integer]: Integer read GetQueueCount;
property StackTotalCount: Integer read GetStackCount;
property StackCount[const APriority: Integer]: Integer read GetStackCount;
{ IADStackQueue<T> }
property Reader: IADStackQueueReader<T> read GetReader;
end;
{ List Sorters }
/// <summary><c>Sorter for Lists using the Quick Sort implementation.</c></summary>
TADListSorterQuick<T> = class(TADListSorter<T>)
public
procedure Sort(const AArray: IADArray<T>; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload; override;
procedure Sort(AArray: Array of T; const AComparer: IADComparer<T>; AFrom, ATo: Integer); overload; override;
end;
{ Map Sorters }
/// <summary><c>Sorter for Maps using the Quick SOrt implementation.</c></summary>
TADMapSorterQuick<TKey, TValue> = class(TADMapSorter<TKey, TValue>)
public
procedure Sort(const AArray: IADArray<IADKeyValuePair<TKey,TValue>>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload; override;
procedure Sort(AArray: Array of IADKeyValuePair<TKey,TValue>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer); overload; override;
end;
// Allocators
function ADCollectionExpanderDefault: IADExpander;
function ADCollectionExpanderGeometric: IADExpanderGeometric;
function ADCollectionCompactorDefault: IADCompactor;
implementation
uses
ADAPT.Comparers;
type
/// <summary><c>The Default Allocation Algorithm for Lists.</c></summary>
/// <remarks><c>By default, the Array will grow by 1 each time it becomes full</c></remarks>
TADExpanderDefault = class(TADExpander)
public
function CheckExpand(const ACapacity, ACurrentCount, AAdditionalRequired: Integer): Integer; override;
end;
/// <summary><c>The Default Deallocation Algorithm for Lists.</c></summary>
/// <remarks><c>By default, the Array will shrink by 1 each time an Item is removed.</c></remarks>
TADCompactorDefault = class(TADCompactor)
public
function CheckCompact(const ACapacity, ACurrentCount, AVacating: Integer): Integer; override;
end;
var
GCollectionExpanderDefault: IADExpander;
GCollectionCompactorDefault: IADCompactor;
function ADCollectionExpanderDefault: IADExpander;
begin
Result := GCollectionExpanderDefault;
end;
function ADCollectionExpanderGeometric: IADExpanderGeometric;
begin
Result := TADExpanderGeometric.Create;
end;
function ADCollectionCompactorDefault: IADCompactor;
begin
Result := GCollectionCompactorDefault;
end;
{ TADExpanderDefault }
function TADExpanderDefault.CheckExpand(const ACapacity, ACurrentCount, AAdditionalRequired: Integer): Integer;
begin
if ACurrentCount + AAdditionalRequired > ACapacity then
Result := (ACapacity - ACurrentCount) + AAdditionalRequired
else
Result := 0;
end;
{ TADCompactorDefault }
function TADCompactorDefault.CheckCompact(const ACapacity, ACurrentCount, AVacating: Integer): Integer;
begin
Result := AVacating;
end;
{ TADArray<T> }
procedure TADArray<T>.Clear;
begin
SetLength(FArray, FCapacityInitial);
if FCapacityInitial > 0 then
Finalize(0, FCapacityInitial);
end;
procedure TADArray<T>.Delete(const AIndex: Integer);
var
I: Integer;
begin
FArray[AIndex] := nil;
// System.FillChar(FArray[AIndex], SizeOf(IADValueHolder<T>), 0);
if AIndex < Length(FArray) - 1 then
begin
// System.Move(FArray[AIndex + 1],
// FArray[AIndex],
// ((Length(FArray) - 1) - AIndex) * SizeOf(IADValueHolder<T>));
for I := AIndex to Length(FArray) - 2 do
FArray[I] := FArray[I + 1];
end;
//TODO -oSJS -cGeneric Collections: Figure out why block Finalize/Move/Reallocation isn't working properly.
end;
constructor TADArray<T>.Create(const ACapacity: Integer);
begin
inherited Create;
FCapacityInitial := ACapacity;
SetLength(FArray, ACapacity);
end;
procedure TADArray<T>.Delete(const AFirstIndex, ACount: Integer);
var
I: Integer;
begin
for I := AFirstIndex + (ACount - 1) downto AFirstIndex do
Delete(I);
end;
destructor TADArray<T>.Destroy;
begin
inherited;
end;
procedure TADArray<T>.Finalize(const AIndex, ACount: Integer);
begin
System.Finalize(FArray[AIndex], ACount);
System.FillChar(FArray[AIndex], ACount * SizeOf(T), 0);
end;
function TADArray<T>.GetCapacity: Integer;
begin
Result := Length(FArray);
end;
function TADArray<T>.GetItem(const AIndex: Integer): T;
begin
if (AIndex < Low(FArray)) or (AIndex > High(FArray)) then
raise EADGenericsRangeException.CreateFmt('Index [%d] Out Of Range', [AIndex]);
Result := FArray[AIndex].Value;
end;
function TADArray<T>.GetReader: IADArrayReader<T>;
begin
Result := IADArrayReader<T>(Self);
end;
procedure TADArray<T>.Insert(const AItem: T; const AIndex: Integer);
begin
Move(AIndex, AIndex + 1, (Capacity - AIndex) - 1);
Finalize(AIndex, 1);
FArray[AIndex] := TADValueHolder<T>.Create(AItem);
end;
procedure TADArray<T>.Move(const AFromIndex, AToIndex, ACount: Integer);
var
LItem: T;
I: Integer;
begin
if AFromIndex < AToIndex then
begin
for I := AFromIndex + ACount downto AFromIndex + 1 do
FArray[I] := FArray[I - (AToIndex - AFromIndex)];
end else
System.Move(FArray[AFromIndex], FArray[AToIndex], ACount * SizeOf(T));
end;
procedure TADArray<T>.SetCapacity(const ACapacity: Integer);
begin
SetLength(FArray, ACapacity);
end;
procedure TADArray<T>.SetItem(const AIndex: Integer; const AItem: T);
begin
FArray[AIndex] := TADValueHolder<T>.Create(AItem);
end;
{ TADExpanderGeometric }
function TADExpanderGeometric.CheckExpand(const ACapacity, ACurrentCount, AAdditionalRequired: Integer): Integer;
begin
if (AAdditionalRequired < FThreshold) then
begin
if (Round(ACapacity * FMultiplier)) > (FMultiplier + FThreshold) then
Result := Round(ACapacity * FMultiplier)
else
Result := ACapacity + AAdditionalRequired + FThreshold; // Expand to ensure everything fits
end else
Result := 0;
end;
function TADExpanderGeometric.GetCapacityMultiplier: Single;
begin
Result := FMultiplier;
end;
function TADExpanderGeometric.GetCapacityThreshold: Integer;
begin
Result := FThreshold;
end;
procedure TADExpanderGeometric.SetCapacityMultiplier(const AMultiplier: Single);
begin
FMultiplier := AMultiplier;
end;
procedure TADExpanderGeometric.SetCapacityThreshold(const AThreshold: Integer);
begin
FThreshold := AThreshold;
end;
{ TADList<T> }
function TADList<T>.AddActual(const AItem: T): Integer;
begin
CheckExpand(1);
FArray[FCount] := AItem;
Result := FCount;
Inc(FCount);
FSortedState := ssUnsorted;
end;
constructor TADList<T>.Create(const AExpander: IADExpander; const AInitialCapacity: Integer);
begin
Create(AExpander, ADCollectionCompactorDefault, AInitialCapacity);
end;
constructor TADList<T>.Create(const AInitialCapacity: Integer);
begin
Create(ADCollectionExpanderDefault, ADCollectionCompactorDefault, AInitialCapacity);
end;
constructor TADList<T>.Create(const AExpander: IADExpander; const ACompactor: IADCompactor; const AInitialCapacity: Integer);
begin
inherited Create(AInitialCapacity);
FExpander := AExpander;
FCompactor := ACompactor;
end;
constructor TADList<T>.Create(const ACompactor: IADCompactor; const AInitialCapacity: Integer);
begin
Create(ADCollectionExpanderDefault, ACompactor, AInitialCapacity);
end;
procedure TADList<T>.DeleteActual(const AIndex: Integer);
begin
FArray.Delete(AIndex);
Dec(FCount);
CheckCompact(1);
end;
procedure TADList<T>.InsertActual(const AItem: T; const AIndex: Integer);
begin
CheckExpand(1);
FArray.Insert(AItem, AIndex);
Inc(FCount);
FSortedState := ssUnsorted;
end;
procedure TADList<T>.SetItem(const AIndex: Integer; const AItem: T);
begin
FArray[AIndex] := AItem;
end;
{ TADSortedList<T> }
function TADSortedList<T>.AddActual(const AItem: T): Integer;
begin
CheckExpand(1);
Result := GetSortedPosition(AItem);
if Result = FCount then
FArray[FCount] := AItem
else
FArray.Insert(AItem, Result);
Inc(FCount);
end;
function TADSortedList<T>.Contains(const AItem: T): Boolean;
begin
Result := (IndexOf(AItem) > -1);
end;
function TADSortedList<T>.ContainsAll(const AItems: array of T): Boolean;
var
I: Integer;
begin
Result := True; // Optimistic
for I := Low(AItems) to High(AItems) do
if (not Contains(AItems[I])) then
begin
Result := False;
Break;
end;
end;
function TADSortedList<T>.ContainsAny(const AItems: array of T): Boolean;
var
I: Integer;
begin
Result := False; // Pessimistic
for I := Low(AItems) to High(AItems) do
if Contains(AItems[I]) then
begin
Result := True;
Break;
end;
end;
function TADSortedList<T>.ContainsNone(const AItems: array of T): Boolean;
begin
Result := (not ContainsAny(AItems));
end;
constructor TADSortedList<T>.Create(const AComparer: IADComparer<T>; const AExpander: IADExpander; const AInitialCapacity: Integer);
begin
Create(AComparer, AExpander, ADCollectionCompactorDefault, AInitialCapacity);
end;
constructor TADSortedList<T>.Create(const AComparer: IADComparer<T>; const AInitialCapacity: Integer);
begin
Create(AComparer, ADCollectionExpanderDefault, ADCollectionCompactorDefault, AInitialCapacity);
end;
constructor TADSortedList<T>.Create(const AComparer: IADComparer<T>; const AExpander: IADExpander; const ACompactor: IADCompactor; const AInitialCapacity: Integer);
begin
inherited Create(AInitialCapacity);
FComparer := AComparer;
FExpander := AExpander;
FCompactor := ACompactor;
end;
constructor TADSortedList<T>.Create(const AComparer: IADComparer<T>; const ACompactor: IADCompactor; const AInitialCapacity: Integer);
begin
Create(AComparer, ADCollectionExpanderDefault, ACompactor, AInitialCapacity);
end;
procedure TADSortedList<T>.DeleteActual(const AIndex: Integer);
begin
FArray.Delete(AIndex);
Dec(FCount);
CheckCompact(1);
end;
function TADSortedList<T>.EqualItems(const AList: IADList<T>): Boolean;
var
I: Integer;
begin
Result := AList.Count = FCount;
if Result then
for I := 0 to AList.Count - 1 do
if (not FComparer.AEqualToB(AList[I], FArray[I])) then
begin
Result := False;
Break;
end;
end;
function TADSortedList<T>.GetComparer: IADComparer<T>;
begin
Result := FComparer;
end;
function TADSortedList<T>.GetReader: IADSortedListReader<T>;
begin
Result := Self as IADSortedListReader<T>;
end;
function TADSortedList<T>.GetSortedPosition(const AItem: T): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := FCount - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if FComparer.ALessThanOrEqualToB(AItem, FArray[LIndex]) then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if FComparer.ALessThanB(FArray[LHigh], AItem) then
Result := LHigh + 1
else if FComparer.ALessThanB(FArray[LLow], AItem) then
Result := LLow + 1
else
Result := LLow;
end;
function TADSortedList<T>.GetSortedState: TADSortedState;
begin
Result := TADSortedState.ssSorted;
end;
procedure TADSortedList<T>.Remove(const AItem: T);
var
LIndex: Integer;
begin
LIndex := IndexOf(AItem);
if LIndex > -1 then
Delete(LIndex);
end;
procedure TADSortedList<T>.RemoveItems(const AItems: array of T);
var
I: Integer;
begin
for I := Low(AItems) to High(AItems) do
Remove(AItems[I]);
end;
procedure TADSortedList<T>.SetComparer(const AComparer: IADComparer<T>);
begin
FComparer := AComparer;
end;
procedure TADSortedList<T>.SetItem(const AIndex: Integer; const AItem: T);
begin
DeleteActual(AIndex);
AddActual(AItem);
end;
function TADSortedList<T>.IndexOf(const AItem: T): Integer;
var
LLow, LHigh, LMid: Integer;
begin
Result := -1; // Pessimistic
if (FCount = 0) then
Exit;
LLow := 0;
LHigh := FCount - 1;
repeat
LMid := (LLow + LHigh) div 2;
if FComparer.AEqualToB(FArray[LMid], AItem) then
begin
Result := LMid;
Break;
end
else if FComparer.ALessThanB(AItem, FArray[LMid]) then
LHigh := LMid - 1
else
LLow := LMid + 1;
until LHigh < LLow;
end;
procedure TADSortedList<T>.InsertActual(const AItem: T; const AIndex: Integer);
begin
AddActual(AItem);
end;
{ TADCircularList<T> }
function TADCircularList<T>.AddActual(const AItem: T): Integer;
begin
if FCount < FArray.Capacity then
Inc(FCount)
else
FArray.Delete(0);
Result := FCount - 1;
FArray[Result] := AItem; // Assign the Item to the Array at the Index.
end;
procedure TADCircularList<T>.DeleteActual(const AIndex: Integer);
begin
FArray.Delete(AIndex);
end;
function TADCircularList<T>.GetNewest: T;
begin
if FCount > 0 then
Result := FArray[FCount - 1];
end;
function TADCircularList<T>.GetNewestIndex: Integer;
begin
Result := FCount - 1;
end;
function TADCircularList<T>.GetOldest: T;
begin
if FCount > 0 then
Result := FArray[0];
end;
function TADCircularList<T>.GetOldestIndex: Integer;
begin
if FCount = 0 then
Result := -1
else
Result := 0;
end;
function TADCircularList<T>.GetReader: IADCircularListReader<T>;
begin
Result := IADCircularListReader<T>(Self);
end;
procedure TADCircularList<T>.InsertActual(const AItem: T; const AIndex: Integer);
begin
if FCount < FArray.Capacity then
begin
FArray.Insert(AItem, AIndex);
Inc(FCount);
end else
begin
FArray.Delete(0);
FArray.Insert(AItem, AIndex);
end;
end;
procedure TADCircularList<T>.SetItem(const AIndex: Integer; const AItem: T);
begin
FArray[AIndex] := AItem;
end;
{ TADMap<TKey, TValue> }
constructor TADMap<TKey, TValue>.Create(const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer);
begin
Create(ADCollectionExpanderDefault, ADCollectionCompactorDefault, AComparer, AInitialCapacity);
end;
constructor TADMap<TKey, TValue>.Create(const AExpander: IADExpander; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer);
begin
Create(AExpander, ADCollectionCompactorDefault, AComparer, AInitialCapacity);
end;
constructor TADMap<TKey, TValue>.Create(const ACompactor: IADCompactor; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer);
begin
Create(ADCollectionExpanderDefault, ACompactor, AComparer, AInitialCapacity);
end;
constructor TADMap<TKey, TValue>.Create(const AExpander: IADExpander; const ACompactor: IADCompactor; const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer);
begin
inherited Create(AInitialCapacity);
FExpander := AExpander;
FCompactor := ACompactor;
FComparer := AComparer;
end;
procedure TADMap<TKey, TValue>.CreateSorter;
begin
FSorter := TADMapSorterQuick<TKey, TValue>.Create;
end;
{ TADCircularMap<TKey, TValue> }
function TADCircularMap<TKey, TValue>.AddActual(const AItem: IADKeyValuePair<TKey, TValue>): Integer;
begin
Result := GetSortedPosition(AItem.Key);
if Result = FCount then
begin
FArray[FCount] := AItem;
if (FCount < FArray.Capacity) then
Inc(FCount);
end else
begin
if FCount = FArray.Capacity then // If the Array is full, we need to bump off 0
begin
FArray.Delete(0);
if Result > 0 then
Dec(Result); // Since we've removed Item 0 (lowest-order item) we need to decrement the position by 1
end
else
Inc(FCount);
FArray.Insert(AItem, Result);
end;
end;
constructor TADCircularMap<TKey, TValue>.Create(const AComparer: IADComparer<TKey>; const AInitialCapacity: Integer);
begin
inherited Create(AInitialCapacity);
FComparer := AComparer;
end;
procedure TADCircularMap<TKey, TValue>.CreateSorter;
begin
FSorter := TADMapSorterQuick<TKey, TValue>.Create;
end;
{ TADTreeNode<T> }
procedure TADTreeNode<T>.AddChild(const AChild: IADTreeNode<T>; const AIndex: Integer);
begin
if AIndex < 0 then
FChildren.Add(AChild)
else
FChildren.Insert(AChild, AIndex);
end;
constructor TADTreeNode<T>.Create(const AParent: IADTreeNode<T>; const AValue: T);
begin
inherited Create;
FParent := nil;
if AParent <> nil then
SetParent(AParent);
FChildren := TADList<IADTreeNode<T>>.Create(10);
FValue := AValue;
end;
constructor TADTreeNode<T>.Create(const AParent: IADTreeNode<T>);
begin
Create(AParent, Default(T));
end;
procedure TADTreeNode<T>.Compact;
begin
(FChildren as IADCompactable).Compact;
end;
constructor TADTreeNode<T>.Create(const AValue: T);
begin
Create(nil, AValue);
end;
function TADTreeNode<T>.GetChildCount: Integer;
begin
Result := FChildren.Count;
end;
function TADTreeNode<T>.GetChildCountRecursive: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to FChildren.Count - 1 do
begin
Inc(Result);
Result := Result + FChildren[I].ChildCountRecursive;
end;
end;
function TADTreeNode<T>.GetChildReader(const AIndex: Integer): IADTreeNodeReader<T>;
begin
Result := FChildren[AIndex];
end;
function TADTreeNode<T>.GetCompactor: IADCompactor;
begin
end;
function TADTreeNode<T>.GetChild(const AIndex: Integer): IADTreeNode<T>;
begin
Result := FChildren[AIndex];
end;
function TADTreeNode<T>.GetDepth: Integer;
var
Ancestor: IADTreeNodeReader<T>;
begin
Ancestor := ParentReader;
Result := 0;
while Ancestor <> nil do
begin
Inc(Result);
Ancestor := Ancestor.ParentReader;
end;
end;
function TADTreeNode<T>.GetExpander: IADExpander;
begin
end;
function TADTreeNode<T>.GetIndexAsChild: Integer;
begin
if Parent = nil then
Result := -1
else
Result := Parent.IndexOf[Self];
end;
function TADTreeNode<T>.GetIndexOf(const AChild: IADTreeNodeReader<T>): Integer;
begin
if (not ADInterfaceComparer.AEqualToB(AChild.ParentReader, Self)) then
Result := -1
else
Result := AChild.IndexAsChild;
end;
function TADTreeNode<T>.GetIsBranch: Boolean;
begin
Result := (not GetIsRoot) and (not GetIsLeaf);
end;
function TADTreeNode<T>.GetIsLeaf: Boolean;
begin
Result := FChildren.Count = 0;
end;
function TADTreeNode<T>.GetIsRoot: Boolean;
begin
Result := FParent = nil;
end;
function TADTreeNode<T>.GetParent: IADTreeNode<T>;
begin
if FParent = nil then
Result := nil
else
Result := IADTreeNode<T>(FParent);
end;
function TADTreeNode<T>.GetParentReader: IADTreeNodeReader<T>;
begin
if FParent = nil then
Result := nil
else
Result := IADTreeNodeReader<T>(FParent);
end;
function TADTreeNode<T>.GetReader: IADTreeNodeReader<T>;
begin
Result := Self;
end;
function TADTreeNode<T>.GetRoot: IADTreeNode<T>;
begin
if IsRoot then
Result := Self
else
Result := Parent.Root;
end;
function TADTreeNode<T>.GetRootReader: IADTreeNodeReader<T>;
begin
if IsRoot then
Result := Self
else
Result := Parent.RootReader;
end;
function TADTreeNode<T>.GetValue: T;
begin
Result := FValue;
end;
procedure TADTreeNode<T>.MoveTo(const ANewParent: IADTreeNode<T>; const AIndex: Integer);
begin
if (Parent = nil) and (ANewParent = nil) then
Exit;
if Parent = ANewParent then // If it's the existing Parent...
begin
if AIndex <> IndexAsChild then // If the Index of this Child is NOT the same as we're attempting to Move it to...
begin
Parent.RemoveChild(Self); // Remove the Child
Parent.AddChild(Self, AIndex); // Add it again at the given Index
end;
end else // If it's a NEW Parent
begin
if Parent <> nil then
Parent.RemoveChild(Self);
ANewParent.AddChild(Self, AIndex);
end;
FParent := Pointer(ANewParent);
end;
procedure TADTreeNode<T>.MoveTo(const AIndex: Integer);
begin
MoveTo(Parent, AIndex);
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>);
begin
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>);
begin
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>);
begin
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>);
begin
end;
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>);
begin
end;
procedure TADTreeNode<T>.PostOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>);
begin
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<T>);
begin
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<T>);
begin
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackAnon<IADTreeNode<T>>);
begin
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<IADTreeNode<T>>);
begin
end;
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNode<T>>);
begin
end;
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackOfObject<T>);
begin
end;
procedure TADTreeNode<T>.PreOrderWalk(const AAction: TADTreeNodeValueCallbackUnbound<IADTreeNodeReader<T>>);
begin
end;
procedure TADTreeNode<T>.RemoveChild(const AChild: IADTreeNodeReader<T>);
var
LIndex: Integer;
begin
LIndex := IndexOf[AChild];
if LIndex > -1 then
FChildren.Delete(LIndex);
end;
procedure TADTreeNode<T>.SetCompactor(const ACompactor: IADCompactor);
begin
(FChildren as IADCompactable).Compactor := ACompactor;
end;
procedure TADTreeNode<T>.SetExpander(const AExpander: IADExpander);
begin
(FChildren as IADExpandable).Expander := AExpander;
end;
procedure TADTreeNode<T>.SetParent(const AParent: IADTreeNode<T>);
var
LParent: IADTreeNode<T>;
begin
LParent := GetParent;
if LParent <> nil then
LParent.RemoveChild(Self);
FParent := Pointer(AParent);
AParent.AddChild(Self);
end;
procedure TADTreeNode<T>.SetValue(const AValue: T);
begin
FValue := AValue;
end;
{ TADStackQueue<T> }
function TADStackQueue<T>.CheckPriority(const APriority: Integer; const AReturnArrayIndex: Boolean = False): Integer;
begin
if APriority < 1 then
Result := 1
else if APriority > FPriorityCount then
Result := FPriorityCount
else
Result := APriority;
if (AReturnArrayIndex) then
Dec(Result); // This accounts for the 0-based Array Offset.
end;
constructor TADStackQueue<T>.Create(const APriorityCount: Integer);
var
I: Integer;
begin
inherited Create;
FPriorityCount := APriorityCount;
FQueues := TADArray<IADList<T>>.Create(APriorityCount);
FStacks := TADArray<IADList<T>>.Create(APriorityCount);
for I := 0 to APriorityCount - 1 do
begin
FQueues[I] := TADList<T>.Create;
FStacks[I] := TADList<T>.Create;
end;
end;
function TADStackQueue<T>.GetCount: Integer;
begin
Result := GetQueueCount + GetStackCount;
end;
function TADStackQueue<T>.GetCount(const APriority: Integer): Integer;
begin
Result := GetQueueCount(APriority) + GetStackCount(APriority);
end;
function TADStackQueue<T>.GetIterator: IADIterableList<T>;
begin
Result := Self;
end;
function TADStackQueue<T>.GetQueueCount: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to FQueues.Capacity - 1 do
Result := Result + FQueues[I].Count;
end;
function TADStackQueue<T>.GetQueueCount(const APriority: Integer): Integer;
var
LPriority: Integer;
begin
LPriority := CheckPriority(APriority, True);
Result := FQueues[LPriority].Count;
end;
function TADStackQueue<T>.GetReader: IADStackQueueReader<T>;
begin
Result := Self;
end;
function TADStackQueue<T>.GetStackCount(const APriority: Integer): Integer;
var
LPriority: Integer;
begin
LPriority := CheckPriority(APriority, True);
Result := FStacks[LPriority].Count;
end;
function TADStackQueue<T>.GetStackCount: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to FStacks.Capacity - 1 do
Result := Result + FStacks[I].Count;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.Iterate(const ACallback: TADListItemCallbackAnon<T>; const ADirection: TADIterateDirection);
begin
case ADirection of
idLeft: IterateBackward(ACallback);
idRight: IterateForward(ACallback);
else
raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.');
end;
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.Iterate(const ACallback: TADListItemCallbackUnbound<T>; const ADirection: TADIterateDirection);
begin
case ADirection of
idLeft: IterateBackward(ACallback);
idRight: IterateForward(ACallback);
else
raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.');
end;
end;
procedure TADStackQueue<T>.Iterate(const ACallback: TADListItemCallbackOfObject<T>; const ADirection: TADIterateDirection);
begin
case ADirection of
idLeft: IterateBackward(ACallback);
idRight: IterateForward(ACallback);
else
raise EADGenericsIterateDirectionUnknownException.Create('Unhandled Iterate Direction given.');
end;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.IterateBackward(const ACallback: TADListItemCallbackAnon<T>);
var
LPriority, I: Integer;
begin
for LPriority := FQueues.Capacity - 1 downto 0 do
for I := FQueues[LPriority].Count - 1 downto 0 do
ACallback(FQueues[LPriority][I]);
for LPriority := FStacks.Capacity - 1 downto 0 do
for I := 0 to FStacks[LPriority].Count - 1 do
ACallback(FStacks[LPriority][I]);
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.IterateBackward(const ACallback: TADListItemCallbackUnbound<T>);
var
LPriority, I: Integer;
begin
for LPriority := FQueues.Capacity - 1 downto 0 do
for I := FQueues[LPriority].Count - 1 downto 0 do
ACallback(FQueues[LPriority][I]);
for LPriority := FStacks.Capacity - 1 downto 0 do
for I := 0 to FStacks[LPriority].Count - 1 do
ACallback(FStacks[LPriority][I]);
end;
procedure TADStackQueue<T>.IterateBackward(const ACallback: TADListItemCallbackOfObject<T>);
var
LPriority, I: Integer;
begin
for LPriority := FQueues.Capacity - 1 downto 0 do
for I := FQueues[LPriority].Count - 1 downto 0 do
ACallback(FQueues[LPriority][I]);
for LPriority := FStacks.Capacity - 1 downto 0 do
for I := 0 to FStacks[LPriority].Count - 1 do
ACallback(FStacks[LPriority][I]);
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.IterateForward(const ACallback: TADListItemCallbackAnon<T>);
var
LPriority, I: Integer;
begin
for LPriority := 0 to FStacks.Capacity - 1 do
for I := FStacks[LPriority].Count - 1 downto 0 do
ACallback(FStacks[LPriority][I]);
for LPriority := 0 to FQueues.Capacity - 1 do
for I := 0 to FQueues[LPriority].Count - 1 do
ACallback(FQueues[LPriority][I]);
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.IterateForward(const ACallback: TADListItemCallbackOfObject<T>);
var
LPriority, I: Integer;
begin
for LPriority := 0 to FStacks.Capacity - 1 do
for I := FStacks[LPriority].Count - 1 downto 0 do
ACallback(FStacks[LPriority][I]);
for LPriority := 0 to FQueues.Capacity - 1 do
for I := 0 to FQueues[LPriority].Count - 1 do
ACallback(FQueues[LPriority][I]);
end;
procedure TADStackQueue<T>.IterateForward(const ACallback: TADListItemCallbackUnbound<T>);
var
LPriority, I: Integer;
begin
for LPriority := 0 to FStacks.Capacity - 1 do
for I := FStacks[LPriority].Count - 1 downto 0 do
ACallback(FStacks[LPriority][I]);
for LPriority := 0 to FQueues.Capacity - 1 do
for I := 0 to FQueues[LPriority].Count - 1 do
ACallback(FQueues[LPriority][I]);
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessQueue(const AOnItem: TADListItemCallbackAnon<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := 0 to FQueues[LPriority].Count - 1 do
AOnItem(FQueues[LPriority][I]);
FQueues[LPriority].Clear; // This empties the Priority Queue when it has been fully processed via the AOnItem Callback.
end;
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessQueue(const AOnItem: TADListItemCallbackUnbound<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := 0 to FQueues[LPriority].Count - 1 do
AOnItem(FQueues[LPriority][I]);
FQueues[LPriority].Clear; // This empties the Priority Queue when it has been fully processed via the AOnItem Callback.
end;
end;
procedure TADStackQueue<T>.ProcessQueue(const AOnItem: TADListItemCallbackOfObject<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := 0 to FQueues[LPriority].Count - 1 do
AOnItem(FQueues[LPriority][I]);
FQueues[LPriority].Clear; // This empties the Priority Queue when it has been fully processed via the AOnItem Callback.
end;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessStack(const AOnItem: TADListItemCallbackAnon<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := FStacks[LPriority].Count - 1 downto 0 do
AOnItem(FStacks[LPriority][I]);
FStacks[LPriority].Clear; // This empties the Priority Stack when it has been fully processed via the AOnItem Callback.
end;
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessStack(const AOnItem: TADListItemCallbackUnbound<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := FStacks[LPriority].Count - 1 downto 0 do
AOnItem(FStacks[LPriority][I]);
FStacks[LPriority].Clear; // This empties the Priority Stack when it has been fully processed via the AOnItem Callback.
end;
end;
procedure TADStackQueue<T>.ProcessStack(const AOnItem: TADListItemCallbackOfObject<T>);
var
LPriority: Integer;
I: Integer;
begin
for LPriority := 0 to FPriorityCount - 1 do
begin
for I := FStacks[LPriority].Count - 1 downto 0 do
AOnItem(FStacks[LPriority][I]);
FStacks[LPriority].Clear; // This empties the Priority Stack when it has been fully processed via the AOnItem Callback.
end;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessStackQueue(const AOnItem: TADListItemCallbackAnon<T>);
begin
ProcessStack(AOnItem);
ProcessQueue(AOnItem);
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADStackQueue<T>.ProcessStackQueue(const AOnItem: TADListItemCallbackOfObject<T>);
begin
ProcessStack(AOnItem);
ProcessQueue(AOnItem);
end;
procedure TADStackQueue<T>.ProcessStackQueue(const AOnItem: TADListItemCallbackUnbound<T>);
begin
ProcessStack(AOnItem);
ProcessQueue(AOnItem);
end;
procedure TADStackQueue<T>.Queue(const AItem: T);
begin
Queue(AItem, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Queue(const AItem: T; const APriority: Integer);
var
LPriority: Integer;
begin
LPriority := CheckPriority(APriority, True);
FQueues[LPriority].Add(AItem);
end;
procedure TADStackQueue<T>.Queue(const AItems: IADListReader<T>);
begin
Queue(AItems, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Queue(const AItems: IADListReader<T>; const APriority: Integer);
var
I: Integer;
begin
for I := 0 to AItems.Count - 1 do
Queue(AItems[I], APriority);
end;
procedure TADStackQueue<T>.Queue(const AItems: array of T);
begin
Queue(AItems, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Queue(const AItems: array of T; const APriority: Integer);
var
I: Integer;
begin
for I := Low(AItems) to High(AItems) do
Queue(AItems[I], APriority);
end;
procedure TADStackQueue<T>.Stack(const AItem: T);
begin
Stack(AItem, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Stack(const AItem: T; const APriority: Integer);
var
LPriority: Integer;
begin
LPriority := CheckPriority(APriority, True);
FStacks[LPriority].Add(AItem);
end;
procedure TADStackQueue<T>.Stack(const AItems: IADListReader<T>);
begin
Stack(AItems, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Stack(const AItems: IADListReader<T>; const APriority: Integer);
var
I: Integer;
begin
for I := 0 to AItems.Count - 1 do
Stack(AItems[I], APriority);
end;
procedure TADStackQueue<T>.Stack(const AItems: array of T);
begin
Stack(AItems, FPriorityCount div 2);
end;
procedure TADStackQueue<T>.Stack(const AItems: array of T; const APriority: Integer);
var
I: Integer;
begin
for I := Low(AItems) to High(AItems) do
Stack(AItems[I], APriority);
end;
{ TADListSorterQuick<T> }
procedure TADListSorterQuick<T>.Sort(const AArray: IADArray<T>; const AComparer: IADComparer<T>; AFrom, ATo: Integer);
var
I, J: Integer;
LPivot, LTemp: T;
begin
repeat
I := AFrom;
J := ATo;
LPivot := AArray[AFrom + (ATo - AFrom) shr 1];
repeat
while AComparer.ALessThanB(AArray[I], LPivot) do
Inc(I);
while AComparer.AGreaterThanB(AArray[J], LPivot) do
Dec(J);
if I <= J then
begin
if I <> J then
begin
LTemp := AArray[I];
AArray[I] := AArray[J];
AArray[J] := LTemp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if AFrom < J then
Sort(AArray, AComparer, AFrom, J);
AFrom := I;
until I >= ATo;
end;
procedure TADListSorterQuick<T>.Sort(AArray: array of T; const AComparer: IADComparer<T>; AFrom, ATo: Integer);
var
I, J: Integer;
LPivot, LTemp: T;
begin
repeat
I := AFrom;
J := ATo;
LPivot := AArray[AFrom + (ATo - AFrom) shr 1];
repeat
while AComparer.ALessThanB(AArray[I], LPivot) do
Inc(I);
while AComparer.AGreaterThanB(AArray[J], LPivot) do
Dec(J);
if I <= J then
begin
if I <> J then
begin
LTemp := AArray[I];
AArray[I] := AArray[J];
AArray[J] := LTemp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if AFrom < J then
Sort(AArray, AComparer, AFrom, J);
AFrom := I;
until I >= ATo;
end;
{ TMapSorterQuick<TKey, TValue> }
procedure TADMapSorterQuick<TKey, TValue>.Sort(const AArray: IADArray<IADKeyValuePair<TKey, TValue>>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer);
var
I, J: Integer;
LPivot: TKey;
LTemp: IADKeyValuePair<TKey, TValue>;
begin
repeat
I := AFrom;
J := ATo;
LPivot := AArray[AFrom + (ATo - AFrom) shr 1].Key;
repeat
while AComparer.ALessThanB(AArray[I].Key, LPivot) do
Inc(I);
while AComparer.AGreaterThanB(AArray[J].Key, LPivot) do
Dec(J);
if I <= J then
begin
if I <> J then
begin
LTemp := AArray[I];
AArray[I] := AArray[J];
AArray[J] := LTemp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if AFrom < J then
Sort(AArray, AComparer, AFrom, J);
AFrom := I;
until I >= ATo;
end;
procedure TADMapSorterQuick<TKey, TValue>.Sort(AArray: array of IADKeyValuePair<TKey, TValue>; const AComparer: IADComparer<TKey>; AFrom, ATo: Integer);
var
I, J: Integer;
LPivot: TKey;
LTemp: IADKeyValuePair<TKey, TValue>;
begin
repeat
I := AFrom;
J := ATo;
LPivot := AArray[AFrom + (ATo - AFrom) shr 1].Key;
repeat
while AComparer.ALessThanB(AArray[I].Key, LPivot) do
Inc(I);
while AComparer.AGreaterThanB(AArray[J].Key, LPivot) do
Dec(J);
if I <= J then
begin
if I <> J then
begin
LTemp := AArray[I];
AArray[I] := AArray[J];
AArray[J] := LTemp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if AFrom < J then
Sort(AArray, AComparer, AFrom, J);
AFrom := I;
until I >= ATo;
end;
initialization
GCollectionExpanderDefault := TADExpanderDefault.Create;
GCollectionCompactorDefault := TADCompactorDefault.Create;
end.
|
unit RecursoDataUn;
interface
uses
SysUtils, Classes, FMTBcd, Provider, osSQLDataSetProvider, DB, SqlExpr,
osCustomDataSetProvider, osUtils, osSQLDataSet;
type
TRecursoData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
MasterDataSetIDRECURSO: TIntegerField;
MasterDataSetIDTIPORECURSO: TIntegerField;
MasterDataSetDESCRICAO: TStringField;
MasterDataSource: TDataSource;
MasterDataSetIDDOMINIO: TIntegerField;
MasterDataSetNOME: TStringField;
MasterDataSetFILTERDEFNAME: TStringField;
MasterDataSetDATACLASSNAME: TStringField;
MasterDataSetRESCLASSNAME: TStringField;
MasterDataSetREPORTCLASSNAME: TStringField;
MasterDataSetINDICEIMAGEM: TIntegerField;
MasterDataSetNUMORDEM: TIntegerField;
RecursosUsuarioDataSet: TosSQLDataset;
RecursosUsuarioProvider: TosSQLDataSetProvider;
AcaoDataSet: TosSQLDataset;
AcaoDataSetDESCRICAO: TStringField;
AcaoDataSetIDACAO: TIntegerField;
AcaoDataSetIDRECURSO: TIntegerField;
AcaoDataSetINDICEIMAGEM: TIntegerField;
AcaoDataSetNOME: TStringField;
AcaoDataSetNOMECOMPONENTE: TStringField;
AcoesUsuarioDataSet: TosSQLDataset;
AcoesUsuarioDataSetNOMECOMPONENTE: TStringField;
AcoesUsuarioProvider: TosSQLDataSetProvider;
UsuarioDataSet: TosSQLDataset;
UsuarioDataSetAPELIDO: TStringField;
UsuarioDataSetSENHA: TStringField;
UsuarioDataSetNOME: TStringField;
UsuarioProvider: TosSQLDataSetProvider;
MasterDataSetHABILITAEDITARTODOS: TStringField;
MasterDataSetFORCAREEXECUCAOFILTRO: TStringField;
UsuarioDataSetSTATUS: TStringField;
UsuarioDataSetDATASENHA: TDateField;
procedure DataModuleCreate(Sender: TObject);
private
public
procedure Validate (PDataSet : TDataSet);
procedure ValidateAcao (PDataSet : TDataSet);
function CheckResource(const User, Resource, Action: string): boolean;
end;
var
RecursoData: TRecursoData;
implementation
uses osAppResources, osErrorHandler, acCustomSQLMainDataUn;
{$R *.dfm}
{ TRecursoData }
function TRecursoData.CheckResource(const User, Resource, Action: string): boolean;
var
Query: TSQLDataSet;
begin
Query := TSQLDataSet.Create(nil);
try
Query.SQLConnection := acCustomSQLMainData.SQLConnection;
Query.CommandText := 'SELECT ' +
' COUNT(DU.IDDireitoUso) HasRight ' +
'FROM ' +
' DireitoUso DU ' +
' JOIN GrupoUsuario GU ' +
' ON DU.IDGrupo = GU.IDGrupo ' +
' JOIN Usuario U ' +
' ON GU.IDUsuario = U.IDUsuario ' +
' JOIN Recurso R ' +
' ON DU.IDRecurso = R.IDRecurso ' +
' JOIN Acao A ' +
' ON DU.IDAcao = A.IDAcao ' +
'WHERE ' +
' U.Apelido LIKE ''' + User + ''' ' +
' AND R.Nome LIKE ''' + Resource + ''' ' +
' AND A.Nome LIKE ''' + Action + '''';
Query.Open;
Result := Query.FieldByName('HASRIGHT').Value > 0;
finally
Query.Free;
end;
end;
procedure TRecursoData.Validate(PDataSet: TDataSet);
var
TipoRecursoField: TIntegerField;
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('IdDominio'));
TipoRecursoField := TIntegerField(FieldByName('IdTipoRecurso'));
CheckEmpty(TipoRecursoField);
CheckEmpty(FieldByName('Nome'));
WarningEmpty(FieldByName('Descricao'));
if TipoRecursoField.AsInteger = Ord(rtReport) then
begin
CheckEmpty(FieldByName('ReportClassName'));
end
else
begin
CheckEmpty(FieldByName('DataClassName'));
CheckEmpty(FieldByName('ResClassName'));
end;
CheckEmpty(FieldByName('IndiceImagem'));
CheckEmpty(FieldByName('NumOrdem'));
Check;
end;
end;
procedure TRecursoData.ValidateAcao(PDataSet: TDataSet);
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('NomeComponente'));
WarningEmpty(FieldByName('Descricao'));
CheckEmpty(FieldByName('IndiceImagem'));
Check;
end;
end;
procedure TRecursoData.DataModuleCreate(Sender: TObject);
begin
MasterDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
AcaoDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
AcoesUsuarioDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
RecursosUsuarioDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
UsuarioDataSet.SQLConnection := acCustomSQLMainData.SQLConnection;
end;
initialization
OSRegisterClass(TRecursoData);
end.
|
{ CRT (Crt Replacement Tool)
Portable BP compatible CRT unit for GPC with many extensions
This unit is aware of terminal types. This means programs using
this unit will work whether run locally or while being logged in
remotely from a system with a completely different terminal type
(as long as the appropriate terminfo entry is present on the
system where the program is run).
NOTES:
- The CRT unit needs the ncurses and panel libraries which should
be available for almost any system. For Dos systems, where
ncurses is not available, it is configured to use the PDCurses
and its panel library instead. On Unix systems with X11, it can
also use PDCurses (xcurses) and xpanel to produce X11 programs.
The advantage is that the program won't need an xterm with a
valid terminfo entry, the output may look a little nicer and
function keys work better than in an xterm, but the disadvantage
is that it will only run under X. The ncurses and PDCurses
libraries (including panel and xpanel, resp.) can be found in
http://www.gnu-pascal.de/libs/
(Note that ncurses is already installed on many Unix systems.)
For ncurses, version 5.0 or newer is required.
When an X11 version under Unix is wanted, give `-DX11' when
compiling crt.pas and crtc.c (or when compiling crt.pas or a
program that uses CRT with `--automake'). On pre-X11R6 systems,
give `-DNOX11R6' additionally. You might also have to give the
path to the X11 libraries with `-L', e.g. `-L /usr/X11/lib'.
- A few features cannot be implemented in a portable way and are
only available on some systems:
Sound, NoSound 1) -----------------------.
GetShiftState ------------------. |
TextMode etc. 2) -------------. | |
CRTSavePreviousScreen --------. | | |
Interrupt signal (Ctrl-C) handling ---. | | | |
| | | | |
Linux/IA32 3) (terminal) X X 4) X 5) X 6) X 6)
Other Unix (terminal) X X 7) X 5) - -
Unix (X11 version) X X - X -
Dos (DJGPP) X X X X X
MS-Windows (Cygwin, mingw, MSYS) X - X 8) X -
Notes:
1) If you define NO_CRT_DUMMY_SOUND while compiling CRT, you
will get linking errors when your program tries to use
Sound/NoSound on a platform where it's not supported (which
is useful to detect at compile time if playing sound is a
major task of your program). Otherwise, Sound/NoSound will
simply do nothing (which is usually acceptable if the program
uses these routines just for an occasional beep).
2) Changing to monochrome modes works on all platforms. Changing
the screen size only works on those indicated. However, even
on the platforms not supported, the program will react to
screen size changes by external means (e.g. changing the
window size with the mouse if running in a GUI window or
resizing a console or virtual terminal).
3) Probably also on other processors, but I've had no chance to
test this yet.
4) Only on a local console with access permissions to the
corresponding virtual console memory device or using the
`crtscreen' utility (see crtscreen.c in the demos directory).
5) Only if supported by an external command (e.g., in xterms and
on local Linux consoles). The command to be called can be
defined in the environment variable `RESIZETERM' (where the
variables `columns' and `lines' in the command are set to the
size wanted). If not set, the code will try `resize -s' in an
xterm and otherwise `SVGATextMode' and `setfont'. For this to
work, these utilities need to be present in the PATH or
`/usr/sbin' or `/usr/local/sbin'. Furthermore, SVGATextMode
and setfont require root permissions, either to the
executable of the program compiled with CRT or to resizecons
(called by setfont) or SVGATextMode. To allow the latter, do
"chmod u+s `which resizecons`" and/or
"chmod u+s `which SVGATextMode`", as root once, but only if
you really want each user to be allowed to change the text
mode.
6) Only on local consoles.
7) Some terminals only. Most xterms etc. support it as well as
other terminals that support an "alternate screen" in the
smcup/rmcup terminal capabilities.
8) Only with PDCurses, not with ncurses. Changing the number of
screen *columns* doesn't work in a full-screen session.
- When CRT is initialized (automatically or explicitly; see the
comments for CRTInit), the screen is cleared, and at the end of
the program, the cursor is placed at the bottom of the screen
(curses behaviour).
- All the other things (including most details like color and
function key constants) are compatible with BP's CRT unit, and
there are many extensions that BP's unit does not have.
- When the screen size is changed by an external event (e.g.,
resizing an xterm or changing the screen size from another VC
under Linux), the virtual "function key" kbScreenSizeChanged is
returned. Applications can use the virtual key to resize their
windows. kbScreenSizeChanged will not be returned if the screen
size change was initiated by the program itself (by using
TextMode or SetScreenSize). Note that TextMode sets the current
panel to the full screen size, sets the text attribute to the
default and clears the window (BP compatibility), while
SetScreenSize does not.
- After the screen size has been changed, whether by using
TextMode, SetScreenSize or by an external event, ScreenSize will
return the new screen size. The current window and all panels
will have been adjusted to the new screen size. This means, if
their right or lower ends are outside the new screen size, the
windows are moved to the left and/or top as far as necessary. If
this is not enough, i.e., if they are wider/higher than the new
screen size, they are shrinked to the total screen width/height.
When the screen size is enlarged, window sizes are not changed,
with one exception: Windows that extend through the whole screen
width/height are enlarged to the whole new screen width/height
(in particular, full-screen windows remain full-screen). This
behaviour might not be optimal for all purposes, but you can
always resize your windows in your application after the screen
size change.
- (ncurses only) The environment variable `ESCDELAY' specifies the
number of milliseconds allowed between an `Esc' character and
the rest of an escape sequence (default 1000). Setting it to a
value too small can cause problems with programs not recognizing
escape sequences such as function keys, especially over slow
network connections. Setting it to a value too large can delay
the recognition of an `ESC' key press notably. On local Linux
consoles, e.g., 10 seems to be a good value.
- When trying to write portable programs, don't rely on exactly
the same look of your output and the availability of all the key
combinations. Some kinds of terminals support only some of the
display attributes and special characters, and usually not all
of the keys declared are really available. Therefore, it's safer
to provide the same function on different key combinations and
to not use the more exotic ones.
- CRT supports an additional modifier key (if present), called
`Extra'. On DJGPP, it's the <Scroll Lock> key, under X11 it's
the modifier #4, and on a local Linux console, it's the `CtrlL'
modifier (value 64) which is unused on many keytabs and can be
mapped to any key(s), e.g. to those keys on new keyboards with
these ugly symbols waiting to be replaced by penguins (keycodes
125 and 127) by inserting the following two lines into your
/etc/default.keytab and reloading the keytab with `loadkeys'
(you usually have to do this as root):
keycode 125 = CtrlL
keycode 127 = CtrlL
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal 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, or (at your
option) any later version.
GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License.
Please also note the license of the curses library used. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030722}
{$error This unit requires GPC release 20030722 or newer.}
{$endif}
unit {$ifdef THIS_IS_WINCRT} WinCRT {$else} CRT {$endif};
interface
uses GPC;
const
{ CRT modes }
BW40 = 0; { 40x25 Black/White }
CO40 = 1; { 40x25 Color }
BW80 = 2; { 80x25 Black/White }
CO80 = 3; { 80x25 Color }
Mono = 7; { 80x25 Black/White }
Font8x8 = 256; { Add-in for 80x43 or 80x50 mode }
{ Mode constants for Turbo Pascal 3.0 compatibility }
C40 = CO40;
C80 = CO80;
{ Foreground and background color constants }
Black = 0;
Blue = 1;
Green = 2;
Cyan = 3;
Red = 4;
Magenta = 5;
Brown = 6;
LightGray = 7;
{ Foreground color constants }
DarkGray = 8;
LightBlue = 9;
LightGreen = 10;
LightCyan = 11;
LightRed = 12;
LightMagenta = 13;
Yellow = 14;
White = 15;
{ Add-in for blinking }
Blink = 128;
type
TTextAttr = Byte;
var
{ If False (default: True), catch interrupt signals (SIGINT;
Ctrl-C), and other flow control characters as well as SIGTERM,
SIGHUP and perhaps other signals }
CheckBreak: Boolean = True; attribute (name = 'crt_CheckBreak');
{ If True (default : False), replace Ctrl-Z by #0 in input }
CheckEOF: Boolean = False; attribute (name = 'crt_CheckEOF');
{ Ignored -- meaningless here }
DirectVideo: Boolean = True;
{ Ignored -- curses or the terminal driver will take care of that
when necessary }
CheckSnow: Boolean = False;
{ Current (sic!) text mode }
LastMode: CCardinal = 3; attribute (name = 'crt_LastMode');
{ Current text attribute }
TextAttr: TTextAttr = 7; attribute (name = 'crt_TextAttr');
{ Window upper left coordinates. *Obsolete*! Please see WindowMin
below. }
WindMin: CCardinal = High (CCardinal); attribute (name = 'crt_WindMin');
{ Window lower right coordinates. *Obsolete*! Please see WindowMax
below. }
WindMax: CCardinal = High (CCardinal); attribute (name = 'crt_WindMax');
procedure AssignCRT (var f: Text);
function KeyPressed: Boolean; external name 'crt_KeyPressed';
function ReadKey: Char; external name 'crt_ReadKey';
{ Not effective on all platforms, see above. See also SetScreenSize
and SetMonochrome. }
procedure TextMode (Mode: Integer);
procedure Window (x1, y1, x2, y2: CInteger); external name 'crt_Window';
procedure GotoXY (x, y: CInteger); external name 'crt_GotoXY';
function WhereX: CInteger; external name 'crt_WhereX';
function WhereY: CInteger; external name 'crt_WhereY';
procedure ClrScr; external name 'crt_ClrScr';
procedure ClrEOL; external name 'crt_ClrEOL';
procedure InsLine; external name 'crt_InsLine';
procedure DelLine; external name 'crt_DelLine';
procedure TextColor (Color: TTextAttr);
procedure TextBackground (Color: TTextAttr);
procedure LowVideo;
procedure HighVideo;
procedure NormVideo;
procedure Delay (MS: CCardinal); external name 'crt_Delay';
{ Not available on all platforms, see above }
procedure Sound (Hz: CCardinal); external name 'crt_Sound';
procedure NoSound; external name 'crt_NoSound';
{ =================== Extensions over BP's CRT =================== }
{ Initializes the CRT unit. Should be called before using any of
CRT's routines.
Note: For BP compatibility, CRT is initizalized automatically when
(almost) any of its routines are used for the first time. In this
case, some defaults are set to match BP more closely. In
particular, the PC charset (see SetPCCharSet) is enabled then
(disabled otherwise), and the update level (see SetCRTUpdate) is
set to UpdateRegularly (UpdateWaitInput otherwise). This feature
is meant for BP compatibility *only*. Don't rely on it when
writing a new program. Use CRTInit then, and set the defaults to
the values you want explicitly.
SetCRTUpdate is one of those few routines which will not cause CRT
to be initialized immediately, and a value set with it will
survive both automatic and explicit initialization, so you can use
it to set the update level without caring which way CRT will be
initialized. (This does not apply to SetPCCharSet. Since it works
on a per-panel basis, it has to initialize CRT first, so there is
a panel to start with.)
If you terminate the program before calling CRTInit or any routine
that causes automatic initialization, curses will never be
initialized, so e.g., the screen won't be cleared. This can be
useful, e.g., to check the command line arguments (or anything
else) and if there's a problem, write an error and abort. Just be
sure to write the error to StdErr, not Output (because Output will
be assigned to CRT, and therefore writing to Output will cause CRT
to be initialized, and because errors belong to StdErr, anyway),
and to call `RestoreTerminal (True)' before (just to be sure, in
case some code -- perhaps added later, or hidden in the
initialization of some unit -- does initialize CRT). }
procedure CRTInit; external name 'crt_Init';
{ Changes the input and output file and the terminal description CRT
uses. Only effective with ncurses, and only if called before CRT
is initialized (automatically or explicitly; see the comments for
CRTInit). If TerminalType is nil, the default will be used. If
InputFile and/or OutputFile are Null, they remain unchanged. }
procedure CRTSetTerminal (TerminalType: CString; var InputFile, OutputFile: AnyFile); attribute (name = 'crt_SetTerminal');
{ If called with an argument True, it causes CRT to save the
previous screen contents if possible (see the comments at the
beginning of the unit), and restore them when calling
RestoreTerminal (True). After RestoreTerminal (False), they're
saved again, and at the end of the program, they're restored. If
called with an argument False, it will prohibit this behaviour.
The default, if this procedure is not called, depends on the
terminal (generally it is active on most xterms and similar and
not active on most other terminals).
This procedure should be called before initializing CRT (using
CRTInit or automatically), otherwise the previous screen contents
may already have been overwritten. It has no effect under XCurses,
because the program uses its own window, anyway. }
procedure CRTSavePreviousScreen (On: Boolean); external name 'crt_SavePreviousScreen';
{ Returns True if CRTSavePreviousScreen was called with argument
True and the functionality is really available. Note that the
result is not reliable until CRT is initialized, while
CRTSavePreviousScreen should be called before CRT is initialized.
That's why they are two separate routines. }
function CRTSavePreviousScreenWorks: Boolean; external name 'crt_SavePreviousScreenWorks';
{ If CRT is initialized automatically, not via CRTInit, and
CRTAutoInitProc is not nil, it will be called before actually
initializing CRT. }
var
CRTAutoInitProc: procedure = nil; attribute (name = 'crt_AutoInitProc');
{ Aborts with a runtime error saying that CRT was not initialized.
If you set CRTAutoInitProc to this procedure, you can effectively
disable CRT's automatic initialization. }
procedure CRTNotInitialized; attribute (name = 'crt_NotInitialized');
{ Set terminal to shell or curses mode. An internal procedure
registered by CRT via RegisterRestoreTerminal does this as well,
so CRTSetCursesMode has to be called only in unusual situations,
e.g. after executing a process that changes terminal modes, but
does not restore them (e.g. because it crashed or was killed), and
the process was not executed with the Execute routine, and
RestoreTerminal was not called otherwise. If you set it to False
temporarily, be sure to set it back to True before doing any
further CRT operations, otherwise the result may be strange. }
procedure CRTSetCursesMode (On: Boolean); external name 'crt_SetCursesMode';
{ Do the same as `RestoreTerminal (True)', but also clear the screen
after restoring the terminal (except for XCurses, because the
program uses its own window, anyway). Does not restore and save
again the previous screen contents if CRTSavePreviousScreen was
called. }
procedure RestoreTerminalClearCRT; attribute (name = 'crt_RestoreTerminalClearCRT');
{ Keyboard and character graphics constants -- BP compatible! =:-}
{$i crt.inc}
var
{ Tells whether the XCurses version of CRT is used }
XCRT: Boolean = {$ifdef XCURSES} True {$else} False {$endif}; attribute (name = 'crt_XCRT');
{ If True (default: False), the Beep procedure and writing #7 do a
Flash instead }
VisualBell: Boolean = False; attribute (name = 'crt_VisualBell');
{ Cursor shape codes. Only to be used in very special cases. }
CursorShapeHidden: CInteger = 0; attribute (name = 'crt_CursorShapeHidden');
CursorShapeNormal: CInteger = 1; attribute (name = 'crt_CursorShapeNormal');
CursorShapeFull: CInteger = 2; attribute (name = 'crt_CursorShapeFull');
type
TKey = CCardinal;
TCursorShape = (CursorIgnored, CursorHidden, CursorNormal, CursorFat, CursorBlock);
TCRTUpdate = (UpdateNever, UpdateWaitInput, UpdateInput,
UpdateRegularly, UpdateAlways);
TPoint = record
x, y: CInteger
end;
PCharAttr = ^TCharAttr;
TCharAttr = record
ch : Char;
Attr : TTextAttr;
PCCharSet: Boolean
end;
PCharAttrs = ^TCharAttrs;
TCharAttrs = array [1 .. MaxVarSize div SizeOf (TCharAttr)] of TCharAttr;
TWindowXYInternalCard8 = Cardinal attribute (Size = 8);
TWindowXYInternalFill = Integer attribute (Size = BitSizeOf (CCardinal) - 16);
TWindowXY = packed record
{$ifdef __BYTES_BIG_ENDIAN__}
Fill: TWindowXYInternalFill;
y, x: TWindowXYInternalCard8
{$elif defined (__BYTES_LITTLE_ENDIAN__)}
x, y: TWindowXYInternalCard8;
Fill: TWindowXYInternalFill
{$else}
{$error Endianness is not defined!}
{$endif}
end;
{ Make sure TWindowXY really has the same size as WindMin and
WindMax. The value of the constant will always be True, and is of
no further interest. }
const
AssertTWindowXYSize = CompilerAssert ((SizeOf (TWindowXY) = SizeOf (WindMin)) and
(SizeOf (TWindowXY) = SizeOf (WindMax)));
var
{ Window upper and left coordinates. More comfortable to access
than WindMin, but also *obsolete*. WindMin and WindowMin still
work, but have the problem that they implicitly limit the window
size to 255x255 characters. Though that's not really small for a
text window, it's easily possible to create bigger ones (e.g. in
an xterm with a small font, on a high resolution screen and/or
extending over several virutal desktops). When using coordinates
greater than 254, the corresponding bytes in WindowMin/WindowMax
will be set to 254, so, e.g., programs which do
`Inc (WindowMin.x)' will not fail quite as badly (but probably
still fail). The routines Window and GetWindow use Integer
coordinates, and don't suffer from any of these problems, so
they should be used instead. }
WindowMin: TWindowXY absolute WindMin;
{ Window lower right coordinates. More comfortable to access than
WindMax, but also *obsolete* (see the comments for WindowMin).
Use Window and GetWindow instead. }
WindowMax: TWindowXY absolute WindMax;
{ The attribute set by NormVideo }
NormAttr: TTextAttr = 7; attribute (name = 'crt_NormAttr');
{ Tells whether the current mode is monochrome }
IsMonochrome: Boolean = False; attribute (name = 'crt_IsMonochrome');
{ This value can be set to a combination of the shFoo constants
and will be ORed to the actual shift state returned by
GetShiftState. This can be used to easily simulate shift keys on
systems where they can't be accessed. }
VirtualShiftState: CInteger = 0; attribute (name = 'crt_VirtualShiftState');
{ Returns the size of the screen. Note: In BP's WinCRT unit,
ScreenSize is a variable. But since writing to it from a program
is pointless, anyway, providing a function here should not cause
any incompatibility. }
function ScreenSize: TPoint; attribute (name = 'crt_GetScreenSize');
{ Change the screen size if possible. }
procedure SetScreenSize (x, y: CInteger); external name 'crt_SetScreenSize';
{ Turns colors off or on. }
procedure SetMonochrome (Monochrome: Boolean); external name 'crt_SetMonochrome';
{ Tell which modifier keys are currently pressed. The result is a
combination of the shFoo constants defined in crt.inc, or 0 on
systems where this function is not supported -- but note
VirtualShiftState. If supported, ReadKey automatically converts
kbIns and kbDel keys to kbShIns and kbShDel, resp., if shift is
pressed. }
function GetShiftState: CInteger; external name 'crt_GetShiftState';
{ Get the extent of the current window. Use this procedure rather
than reading WindMin and WindMax or WindowMin and WindowMax, since
this routine allows for window sizes larger than 255. The
resulting coordinates are 1-based (like in Window, unlike WindMin,
WindMax, WindowMin and WindowMax). Any of the parameters may be
Null in case you're interested in only some of the coordinates. }
procedure GetWindow (var x1, y1, x2, y2: Integer); attribute (name = 'crt_GetWindow');
{ Determine when to update the screen. The possible values are the
following. The given conditions *guarantee* updates. However,
updates may occur more frequently (even if the update level is set
to UpdateNever). About the default value, see the comments for
CRTInit.
UpdateNever : never (unless explicitly requested with
CRTUpdate)
UpdateWaitInput: before Delay and CRT input, unless typeahead is
detected
UpdateInput : before Delay and CRT input
UpdateRegularly: before Delay and CRT input and otherwise in
regular intervals without causing too much
refresh. This uses a timer on some systems
(currently, Unix with ncurses). This was created
for BP compatibility, but for many applications,
a lower value causes less flickering in the
output, and additionally, timer signals won't
disturb other operations. Under DJGPP, this
always updates immediately, but this fact should
not mislead DJGPP users into thinking this is
always so.
UpdateAlways : after each output. This can be very slow. (Not so
under DJGPP, but this fact should not mislead
DJGPP users ...) }
procedure SetCRTUpdate (UpdateLevel: TCRTUpdate); external name 'crt_SetUpdateLevel';
{ Do an update now, independently of the update level }
procedure CRTUpdate; external name 'crt_Update';
{ Do an update now and completely redraw the screen }
procedure CRTRedraw; external name 'crt_Redraw';
{ Return Ord (key) for normal keys and $100 * Ord (fkey) for
function keys }
function ReadKeyWord: TKey; external name 'crt_ReadKeyWord';
{ Extract the character and scan code from a TKey value }
function Key2Char (k: TKey): Char;
function Key2Scan (k: TKey): Char;
{ Convert a key to upper/lower case if it is a letter, leave it
unchanged otherwise }
function UpCaseKey (k: TKey): TKey;
function LoCaseKey (k: TKey): TKey;
{ Return key codes for the combination of the given key with Ctrl,
Alt, AltGr or Extra, resp. Returns 0 if the combination is
unknown. }
function CtrlKey (ch: Char): TKey; attribute (name = 'crt_CtrlKey');
function AltKey (ch: Char): TKey; external name 'crt_AltKey';
function AltGrKey (ch: Char): TKey; external name 'crt_AltGrKey';
function ExtraKey (ch: Char): TKey; external name 'crt_ExtraKey';
{ Check if k is a pseudo key generated by a deadly signal trapped }
function IsDeadlySignal (k: TKey): Boolean;
{ Produce a beep or a screen flash }
procedure Beep; external name 'crt_Beep';
procedure Flash; external name 'crt_Flash';
{ Get size of current window (calculated using GetWindow) }
function GetXMax: Integer;
function GetYMax: Integer;
{ Get/goto an absolute position }
function WhereXAbs: Integer;
function WhereYAbs: Integer;
procedure GotoXYAbs (x, y: Integer);
{ Turn scrolling on or off }
procedure SetScroll (State: Boolean); external name 'crt_SetScroll';
{ Read back whether scrolling is enabled }
function GetScroll: Boolean; external name 'crt_GetScroll';
{ Determine whether to interpret non-ASCII characters as PC ROM
characters (True), or in a system dependent way (False). About the
default, see the comments for CRTInit. }
procedure SetPCCharSet (PCCharSet: Boolean); external name 'crt_SetPCCharSet';
{ Read back the value set by SetPCCharSet }
function GetPCCharSet: Boolean; external name 'crt_GetPCCharSet';
{ Determine whether to interpret #7, #8, #10, #13 as control
characters (True, default), or as graphics characters (False) }
procedure SetControlChars (UseControlChars: Boolean); external name 'crt_SetControlChars';
{ Read back the value set by SetControlChars }
function GetControlChars: Boolean; external name 'crt_GetControlChars';
procedure SetCursorShape (Shape: TCursorShape); external name 'crt_SetCursorShape';
function GetCursorShape: TCursorShape; external name 'crt_GetCursorShape';
procedure HideCursor;
procedure HiddenCursor;
procedure NormalCursor;
procedure FatCursor;
procedure BlockCursor;
procedure IgnoreCursor;
{ Simulates a block cursor by writing a block character onto the
cursor position. The procedure automatically finds the topmost
visible panel whose shape is not CursorIgnored and places the
simulated cursor there (just like the hardware cursor), with
matching attributes, if the cursor shape is CursorFat or
CursorBlock (otherwise, no simulated cursor is shown).
Calling this procedure again makes the simulated cursor disappear.
In particular, to get the effect of a blinking cursor, you have to
call the procedure repeatedly (say, 8 times a second). CRT will
not do this for you, since it does not intend to be your main
event loop. }
procedure SimulateBlockCursor; external name 'crt_SimulateBlockCursor';
{ Makes the cursor simulated by SimulateBlockCursor disappear if it
is active. Does nothing otherwise. You should call this procedure
after using SimulateBlockCursor before doing any further CRT
output (though failing to do so should not hurt except for
possibly leaving the simulated cursor in its old position longer
than it should). }
procedure SimulateBlockCursorOff; external name 'crt_SimulateBlockCursorOff';
function GetTextColor: Integer;
function GetTextBackground: Integer;
{ Write string at the given position without moving the cursor.
Truncated at the right margin. }
procedure WriteStrAt (x, y: Integer; const s: String; Attr: TTextAttr);
{ Write (several copies of) a char at then given position without
moving the cursor. Truncated at the right margin. }
procedure WriteCharAt (x, y, Count: Integer; ch: Char; Attr: TTextAttr);
{ Write characters with specified attributes at the given position
without moving the cursor. Truncated at the right margin. }
procedure WriteCharAttrAt (x, y, Count: CInteger; CharAttr: PCharAttrs); external name 'crt_WriteCharAttrAt';
{ Write a char while moving the cursor }
procedure WriteChar (ch: Char);
{ Read a character from a screen position }
procedure ReadChar (x, y: CInteger; var ch: Char; var Attr: TTextAttr); external name 'crt_ReadChar';
{ Change only text attributes, leave characters. Truncated at the
right margin. }
procedure ChangeTextAttr (x, y, Count: Integer; NewAttr: TTextAttr);
{ Fill current window }
procedure FillWin (ch: Char; Attr: TTextAttr); external name 'crt_FillWin';
{ Calculate size of memory required for ReadWin in current window. }
function WinSize: SizeType; external name 'crt_WinSize';
{ Save window contents. Buf must be WinSize bytes large. }
procedure ReadWin (var Buf); external name 'crt_ReadWin';
{ Restore window contents saved by ReadWin. The size of the current
window must match the size of the window from which ReadWin was
used, but the position may be different. }
procedure WriteWin (const Buf); external name 'crt_WriteWin';
type
WinState = record
x1, y1, x2, y2, WhereX, WhereY, NewX1, NewY1, NewX2, NewY2: Integer;
TextAttr: TTextAttr;
CursorShape: TCursorShape;
ScreenSize: TPoint;
Buffer: ^Byte
end;
{ Save window position and size, cursor position, text attribute and
cursor shape -- *not* the window contents. }
procedure SaveWin (var State: WinState);
{ Make a new window (like Window), and save the contents of the
screen below the window as well as the position and size, cursor
position, text attribute and cursor shape of the old window. }
procedure MakeWin (var State: WinState; x1, y1, x2, y2: Integer);
{ Create window in full size, save previous text mode and all values
that MakeWin does. }
procedure SaveScreen (var State: WinState);
{ Restore the data saved by SaveWin, MakeWin or SaveScreen. }
procedure RestoreWin (var State: WinState);
{ Panels }
type
TPanel = Pointer;
function GetActivePanel: TPanel; external name 'crt_GetActivePanel';
procedure PanelNew (x1, y1, x2, y2: CInteger; BindToBackground: Boolean); external name 'crt_PanelNew';
procedure PanelDelete (Panel: TPanel); external name 'crt_PanelDelete';
procedure PanelBindToBackground (Panel: TPanel; BindToBackground: Boolean); external name 'crt_PanelBindToBackground';
function PanelIsBoundToBackground (Panel: TPanel): Boolean; external name 'crt_PanelIsBoundToBackground';
procedure PanelActivate (Panel: TPanel); external name 'crt_PanelActivate';
procedure PanelHide (Panel: TPanel); external name 'crt_PanelHide';
procedure PanelShow (Panel: TPanel); external name 'crt_PanelShow';
function PanelHidden (Panel: TPanel): Boolean; external name 'crt_PanelHidden';
procedure PanelTop (Panel: TPanel); external name 'crt_PanelTop';
procedure PanelBottom (Panel: TPanel); external name 'crt_PanelBottom';
procedure PanelMoveAbove (Panel, Above: TPanel); external name 'crt_PanelMoveAbove';
procedure PanelMoveBelow (Panel, Below: TPanel); external name 'crt_PanelMoveBelow';
function PanelAbove (Panel: TPanel): TPanel; external name 'crt_PanelAbove';
function PanelBelow (Panel: TPanel): TPanel; external name 'crt_PanelBelow';
{ TPCRT compatibility }
{ Write a string at the given position without moving the cursor.
Truncated at the right margin. }
procedure WriteString (const s: String; y, x: Integer);
{ Write a string at the given position with the given attribute
without moving the cursor. Truncated at the right margin. }
procedure FastWriteWindow (const s: String; y, x: Integer; Attr: TTextAttr);
{ Write a string at the given absolute position with the given
attribute without moving the cursor. Truncated at the right
margin. }
procedure FastWrite (const s: String; y, x: Integer; Attr: TTextAttr);
{ WinCRT compatibility }
const
cw_UseDefault = Integer ($8000);
var
{ Ignored }
WindowOrg : TPoint = (cw_UseDefault, cw_UseDefault);
WindowSize: TPoint = (cw_UseDefault, cw_UseDefault);
Origin : TPoint = (0, 0);
InactiveTitle: PChar = '(Inactive %s)';
AutoTracking: Boolean = True;
WindowTitle: {$ifdef __BP_TYPE_SIZES__}
array [0 .. 79] of Char
{$else}
TStringBuf
{$endif};
{ Cursor location, 0-based }
Cursor : TPoint = (0, 0); attribute (name = 'crt_Cursor');
procedure InitWinCRT; attribute (name = 'crt_InitWinCRT');
{ Halts the program }
procedure DoneWinCRT; attribute (noreturn, name = 'crt_DoneWinCRT');
procedure WriteBuf (Buffer: PChar; Count: SizeType); attribute (name = 'crt_WriteBuf');
function ReadBuf (Buffer: PChar; Count: SizeType): SizeType; attribute (name = 'crt_ReadBuf');
{ 0-based coordinates! }
procedure CursorTo (x, y: Integer); attribute (name = 'crt_CursorTo');
{ Dummy }
procedure ScrollTo (x, y: Integer); attribute (name = 'crt_ScrollTo');
{ Dummy }
procedure TrackCursor; attribute (name = 'crt_TrackCursor');
implementation
{$ifdef X11}
{$L crtx.c, XPanel, XCurses, Xaw, Xmu, Xt, X11}
{$ifndef NOX11R6} {$L SM, ICE, Xext} {$endif}
{ XCurses under Solaris needs additional libraries. When linking
dynamically, they are automatically referenced by the other libraries.
For static linking, however, we have to name them explicitly. }
{$ifdef __sun__} {$L socket, w, nsl, intl, dl} {$endif}
{$elif defined (USE_PDCURSES)}
{$L crtc.c, panel, pdcurses}
{$else}
{$L crtc.c, panel, ncurses}
{$endif}
procedure CRT_Done; external name 'crt_Done';
procedure CRT_GetWindow (var x1, y1, x2, y2: CInteger); external name 'crt_CGetWindow';
procedure CRT_UnGetCh (k: TKey); external name 'crt_UngetCh';
function CRT_Read (var PrivateData; var Buffer; Size: SizeType): SizeType; external name 'crt_Read';
function CRT_Write (var PrivateData; const Buffer; Size: SizeType): SizeType; external name 'crt_Write';
function CRT_Get_Input_FD: CInteger; external name 'crt_Get_Input_FD';
function CRT_Get_Output_FD: CInteger; external name 'crt_Get_Output_FD';
procedure CRT_Select (var PrivateData; var ReadSelect, WriteSelect, ExceptSelect: Boolean); external name 'crt_Select';
procedure CRT_Restore_Terminal_No_CRT; external name 'crt_Restore_Terminal_No_CRT';
procedure CRT_Restore_Terminal_CRT; external name 'crt_Restore_Terminal_CRT';
procedure CRT_Check_WinChanged; external name 'crt_Check_WinChanged';
{$define DO_CRT_CHECK_WINCHANGED
begin
SetReturnAddress (ReturnAddress (0));
CRT_Check_WinChanged;
RestoreReturnAddress
end}
const
MonoModes = [BW40, BW80, Mono];
var
TerminalNoCRT: Boolean = False; attribute (name = 'crt_TerminalNoCRT');
CRTClearFlag : Boolean = False; attribute (name = 'crt_ClearFlag');
Signaled : Boolean = False; attribute (volatile, name = 'crt_Signaled');
CRTScreenSize: TPoint = (-1, -1); attribute (name = 'crt_ScreenSize');
CRTTerminal : CString = nil; attribute (name = 'crt_Terminal');
CRTInputFD : CInteger = -1; attribute (name = 'crt_InputFD');
CRTOutputFD : CInteger = -1; attribute (name = 'crt_OutputFD');
procedure CRTSetTerminal (TerminalType: CString; var InputFile, OutputFile: AnyFile);
begin
CRTTerminal := TerminalType;
if @InputFile <> nil then CRTInputFD := FileHandle (InputFile);
if @OutputFile <> nil then CRTOutputFD := FileHandle (OutputFile)
end;
procedure TextColor (Color: TTextAttr);
begin
if (Color and $f0) <> 0 then Color := (Color and $f) or Blink;
TextAttr := (TextAttr and $70) or Color
end;
procedure TextBackground (Color: TTextAttr);
begin
TextAttr := (TextAttr and $8f) or ((Color and 7) shl 4)
end;
function GetTextColor: Integer;
begin
GetTextColor := TextAttr and $8f
end;
function GetTextBackground: Integer;
begin
GetTextBackground := (TextAttr and $70) shr 4
end;
procedure LowVideo;
begin
TextAttr := TextAttr and not 8
end;
procedure HighVideo;
begin
TextAttr := TextAttr or 8
end;
procedure NormVideo;
begin
TextAttr := NormAttr
end;
procedure TextMode (Mode: Integer);
var x, y: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
if (Mode and not Font8x8) in [BW40, CO40] then x := 40 else x := 80;
if (Mode and Font8x8) <> 0 then y := 50 else y := 25;
SetMonochrome ((Mode and $ff) in MonoModes);
SetScreenSize (x, y);
NormVideo;
Window (1, 1, CRTScreenSize.x, CRTScreenSize.y);
ClrScr
end;
function ScreenSize: TPoint;
begin
DO_CRT_CHECK_WINCHANGED;
ScreenSize := CRTScreenSize
end;
function CRT_SelectFunc (var PrivateData; Writing: Boolean): Integer;
begin
DO_CRT_CHECK_WINCHANGED;
Discard (PrivateData);
if Writing then
CRT_SelectFunc := CRT_Get_Output_FD
else
CRT_SelectFunc := CRT_Get_Input_FD
end;
procedure AssignCRT (var f: Text);
begin
AssignTFDD (f, nil, CRT_SelectFunc, CRT_Select, CRT_Read, CRT_Write, nil, nil, nil, nil)
end;
procedure WriteStrAt (x, y: Integer; const s: String; Attr: TTextAttr);
var OrigAttr: TTextAttr;
begin
DO_CRT_CHECK_WINCHANGED;
OrigAttr := TextAttr;
TextAttr := Attr;
WriteString (s, y, x);
TextAttr := OrigAttr
end;
procedure WriteCharAt (x, y, Count: Integer; ch: Char; Attr: TTextAttr);
var
OrigAttr: TTextAttr;
Temp: array [1 .. Count] of Char;
i: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
for i := 1 to Count do Temp[i] := ch;
OrigAttr := TextAttr;
TextAttr := Attr;
WriteString (Temp, y, x);
TextAttr := OrigAttr
end;
procedure WriteChar (ch: Char);
begin
DO_CRT_CHECK_WINCHANGED;
Discard (CRT_Write (Null, ch, 1))
end;
procedure WriteString (const s: String; y, x: Integer);
var
OrigX, OrigY, Size: Integer;
UseControlCharsSave, ScrollSave: Boolean;
begin
DO_CRT_CHECK_WINCHANGED;
OrigX := WhereX;
OrigY := WhereY;
GotoXY (x, y);
UseControlCharsSave := GetControlChars;
SetControlChars (False);
ScrollSave := GetScroll;
SetScroll (False);
Size := Min (Length (s), GetXMax - x + 1);
if Size > 0 then Discard (CRT_Write (Null, s[1], Size));
SetScroll (ScrollSave);
SetControlChars (UseControlCharsSave);
GotoXY (OrigX, OrigY)
end;
procedure FastWriteWindow (const s: String; y, x: Integer; Attr: TTextAttr);
begin
DO_CRT_CHECK_WINCHANGED;
WriteStrAt (x, y, s, Attr)
end;
procedure FastWrite (const s: String; y, x: Integer; Attr: TTextAttr);
var x1, y1: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (x1, y1, Null, Null);
WriteStrAt (x - x1 + 1, y - y1 + 1, s, Attr)
end;
procedure ChangeTextAttr (x, y, Count: Integer; NewAttr: TTextAttr);
var
OrigX, OrigY, i: Integer;
ch: Char;
OrigAttr, Attr: TTextAttr;
ScrollSave: Boolean;
begin
DO_CRT_CHECK_WINCHANGED;
OrigAttr := TextAttr;
OrigX := WhereX;
OrigY := WhereY;
GotoXY (x, y);
ScrollSave := GetScroll;
SetScroll (False);
for i := 1 to Min (Count, GetXMax - x + 1) do
begin
ReadChar (x + i - 1, y, ch, Attr);
TextAttr := NewAttr;
WriteChar (ch)
end;
SetScroll (ScrollSave);
GotoXY (OrigX, OrigY);
TextAttr := OrigAttr
end;
function Key2Char (k: TKey): Char;
begin
if k div $100 <> 0 then
Key2Char := #0
else
Key2Char := Chr (k)
end;
function Key2Scan (k: TKey): Char;
begin
Key2Scan := Chr (k div $100)
end;
function UpCaseKey (k: TKey): TKey;
var ch: Char;
begin
ch := Key2Char (k);
if ch = #0 then
UpCaseKey := k
else
UpCaseKey := Ord (UpCase (ch))
end;
function LoCaseKey (k: TKey): TKey;
var ch: Char;
begin
ch := Key2Char (k);
if ch = #0 then
LoCaseKey := k
else
LoCaseKey := Ord (LoCase (ch))
end;
procedure GetWindow (var x1, y1, x2, y2: Integer);
var cx1, cy1, cx2, cy2: CInteger;
begin
CRT_GetWindow (cx1, cy1, cx2, cy2);
if @x1 <> nil then x1 := cx1;
if @y1 <> nil then y1 := cy1;
if @x2 <> nil then x2 := cx2;
if @y2 <> nil then y2 := cy2
end;
function CtrlKey (ch: Char): TKey;
begin
case ch of
'A' .. 'Z': CtrlKey := Ord (Pred (ch, Ord ('A') - Ord (chCtrlA)));
'a' .. 'z': CtrlKey := Ord (Pred (ch, Ord ('a') - Ord (chCtrlA)));
else CtrlKey := 0
end
end;
function IsDeadlySignal (k: TKey): Boolean;
begin
IsDeadlySignal := (k = kbInt) or (k = kbTerm) or (k = kbHUp) or (k = kbError)
end;
function GetXMax: Integer;
var x1, x2: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (x1, Null, x2, Null);
GetXMax := x2 - x1 + 1
end;
function GetYMax: Integer;
var y1, y2: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (Null, y1, Null, y2);
GetYMax := y2 - y1 + 1
end;
function WhereXAbs: Integer;
var x1: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (x1, Null, Null, Null);
WhereXAbs := WhereX + x1 - 1
end;
function WhereYAbs: Integer;
var y1: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (Null, y1, Null, Null);
WhereYAbs := WhereY + y1 - 1
end;
procedure GotoXYAbs (x, y: Integer);
var x1, y1: Integer;
begin
DO_CRT_CHECK_WINCHANGED;
GetWindow (x1, y1, Null, Null);
GotoXY (x - x1 + 1, y - y1 + 1)
end;
procedure HideCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorHidden)
end;
procedure HiddenCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorHidden)
end;
procedure NormalCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorNormal)
end;
procedure FatCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorFat)
end;
procedure BlockCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorBlock)
end;
procedure IgnoreCursor;
begin
DO_CRT_CHECK_WINCHANGED;
SetCursorShape (CursorIgnored)
end;
procedure SaveWin (var State: WinState);
begin
DO_CRT_CHECK_WINCHANGED;
with State do
begin
GetWindow (x1, y1, x2, y2);
NewX1 := x1;
NewY1 := y1;
NewX2 := x2;
NewY2 := y2
end;
State.WhereX := WhereX;
State.WhereY := WhereY;
State.TextAttr := TextAttr;
State.CursorShape := GetCursorShape;
State.ScreenSize.x := -1;
State.ScreenSize.y := -1;
State.Buffer := nil
end;
procedure MakeWin (var State: WinState; x1, y1, x2, y2: Integer);
begin
DO_CRT_CHECK_WINCHANGED;
SaveWin (State);
Window (x1, y1, x2, y2);
with State do GetWindow (NewX1, NewY1, NewX2, NewY2);
SetReturnAddress (ReturnAddress (0));
GetMem (State.Buffer, WinSize);
RestoreReturnAddress;
ReadWin (State.Buffer^)
end;
procedure SaveScreen (var State: WinState);
begin
SetReturnAddress (ReturnAddress (0));
CRT_Check_WinChanged;
MakeWin (State, 1, 1, CRTScreenSize.x, CRTScreenSize.y);
RestoreReturnAddress;
State.ScreenSize := CRTScreenSize
end;
procedure RestoreWin (var State: WinState);
begin
DO_CRT_CHECK_WINCHANGED;
if (State.ScreenSize.x <> - 1) and (State.ScreenSize.y <> - 1) then
begin
if (State.ScreenSize.x <> CRTScreenSize.x) or (State.ScreenSize.y <> CRTScreenSize.y) then
SetScreenSize (State.ScreenSize.x, State.ScreenSize.y);
Window (1, 1, CRTScreenSize.x, CRTScreenSize.y)
end;
SetCursorShape (State.CursorShape);
if State.Buffer <> nil then
begin
with State do Window (NewX1, NewY1, NewX2, NewY2);
WriteWin (State.Buffer^);
FreeMem (State.Buffer);
State.Buffer := nil
end;
with State do Window (x1, y1, x2, y2);
GotoXY (State.WhereX, State.WhereY);
TextAttr := State.TextAttr
end;
procedure InitWinCRT;
begin
DO_CRT_CHECK_WINCHANGED
end;
procedure DoneWinCRT;
begin
Halt
end;
procedure WriteBuf (Buffer: PChar; Count: SizeType);
begin
DO_CRT_CHECK_WINCHANGED;
if Count > 0 then Discard (CRT_Write (Null, Buffer^, Count))
end;
function ReadBuf (Buffer: PChar; Count: SizeType): SizeType;
begin
DO_CRT_CHECK_WINCHANGED;
ReadBuf := CRT_Read (Null, Buffer^, Count)
end;
procedure CursorTo (x, y: Integer);
begin
DO_CRT_CHECK_WINCHANGED;
GotoXY (x + 1, y + 1)
end;
procedure ScrollTo (x, y: Integer);
begin
Discard (x);
Discard (y)
end;
procedure TrackCursor;
begin
end;
procedure RestoreTerminalClearCRT;
begin
CRTClearFlag := True;
RestoreTerminal (True);
CRTClearFlag := False
end;
procedure CRT_RegisterRestoreTerminal; attribute (name = 'crt_RegisterRestoreTerminal');
begin
RegisterRestoreTerminal (True, CRT_Restore_Terminal_No_CRT);
RegisterRestoreTerminal (False, CRT_Restore_Terminal_CRT)
end;
function CRT_GetProgramName: CString; attribute (name = 'crt_GetProgramName');
begin
CRT_GetProgramName := CParameters^[0]
end;
function CRT_GetCEnvironment: PCStrings; attribute (name = 'crt_GetCEnvironment');
begin
CRT_GetCEnvironment := GetCEnvironment
end;
{$ifdef USE_NCURSES}
procedure CRT_DoTextModeCommand (Columns, Lines: CInteger); attribute (name = 'crt_DoTextModeCommand');
var
CommandLine: CString;
Buffer: TString;
Blocked: Boolean;
begin
CommandLine := CStringGetEnv ('RESIZETERM');
if CommandLine = nil then
{$if True}
CommandLine := 'PATH="$PATH:/usr/local/sbin:/usr/sbin"; { if [ x"$DISPLAY" != x ]; then resize -s "$lines" "$columns" < /dev/null; fi; } > /dev/null 2>&1';
{$else}
CommandLine := 'PATH="$PATH:/usr/local/sbin:/usr/sbin"; { if [ x"$DISPLAY" != x ]; then resize -s "$lines" "$columns" < /dev/null; else SVGATextMode "$columns"x"$lines" || if [ "$lines" -gt 25 ]; then setfont cp850-8x8 -u cp437; else setfont cp850-8x16 -u cp437; fi; fi; } > /dev/null 2>&1';
{$endif}
WriteStr (Buffer, 'columns=', Columns, '; lines=', Lines, '; ', CString2String (CommandLine));
Blocked := SignalBlocked (SigWinCh);
BlockSignal (SigWinCh, True);
Signaled := False;
Discard (ExecuteNoTerminal (Buffer));
if not Blocked then BlockSignal (SigWinCh, False)
end;
{$endif}
procedure CRTNotInitialized;
begin
SetReturnAddress (ReturnAddress (0));
RuntimeError (880); { CRT was not initialized }
RestoreReturnAddress
end;
procedure Signal_Handler (Signal: TKey); attribute (name = 'crt_SignalHandler');
begin
if TerminalNoCRT and (Signal = kbInt) then Exit;
Signaled := True;
if CheckBreak then
begin
if Signal = kbInt then Write ('^C');
Halt (255)
end
else
CRT_UnGetCh (Signal)
end;
procedure CRT_Fatal (Reason: CInteger); attribute (noreturn, name = 'crt_Fatal');
begin
case Reason of
1: InternalError (950); { CRT: cannot initialize curses }
2: RuntimeError (881); { CRT: error opening terminal }
3: RuntimeError (882); { attempt to delete invalid CRT panel }
4: RuntimeError (883); { attempt to delete last CRT panel }
5: RuntimeError (884); { attempt to activate invalid CRT panel }
6: RuntimeError (885); { CRT: input error }
else InternalError (951) { cannot create CRT window }
end
end;
to begin do
begin
AssignCRT (Input);
Reset (Input);
AssignCRT (Output);
Rewrite (Output)
end;
to end do
begin
Close (Input);
Reset (Input, '-');
Close (Output);
Rewrite (Output, '-');
CRT_Done
end;
end.
|
unit ParameterPosQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, BaseQuery, DSWrap, BaseEventsQuery;
type
TParameterPosW = class(TDSWrap)
private
FPos: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property Pos: TFieldWrap read FPos;
property ID: TFieldWrap read FID;
end;
TQueryParameterPos = class(TQueryBaseEvents)
private
FW: TParameterPosW;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property W: TParameterPosW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses NotifyEvents;
constructor TQueryParameterPos.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TParameterPosW;
end;
function TQueryParameterPos.CreateDSWrap: TDSWrap;
begin
Result := TParameterPosW.Create(FDQuery);
end;
constructor TParameterPosW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FPos := TFieldWrap.Create(Self, 'Pos', 'Расположение');
end;
end.
|
unit UEditsStatic;
{$mode objfpc}{$H+}
interface
uses
Classes, Controls, Graphics, ExtCtrls, StdCtrls, Spin, Dialogs, sysutils;
type
PointerArray = array of Pointer;
type
TMainEditNewStatic = Class
Prop__Pointer: PointerArray;
class function Tagis: Integer; virtual; abstract;
constructor Create(AObject: TControl; APProp: PointerArray); virtual;
end;
TMainEditStaticClass = Class of TMainEditNewStatic;
PC_PenCol = Class(TMainEditNewStatic)
type
OnMouseDown = procedure(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer) of Object;
strict private
Pen: TShape;
PointerToMethod: OnMouseDown;
procedure PenColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer); virtual;
class function Tagis: Integer; override;
constructor Create(AObject: TControl; APProp: PointerArray); override;
destructor Destroy; override;
end;
BC_BrushCol = Class(PC_PenCol)
class function Tagis: Integer; override;
end;
type
TControl_EditNew = Class
type
TObjArray = array of TObject;
TClassEditNewArray = array of TMainEditStaticClass;
PointerToMethod = procedure of object;
var
EditNew_Array: TObjArray;
Class_EditNew_Array: TClassEditNewArray;
MAIN_Invalidate: PointerToMethod;
Class_Object_Array: array of TControl;
procedure Free_All_Edit;
procedure Add_Edit(ACEdit: TObject);
procedure Register_Edit(CLEdit: TMainEditStaticClass);
function CompareName(AName: String): TMainEditStaticClass;
procedure Register_Controls(CLEdit: TControl);
function CompareName_Controls(TMENC: TMainEditStaticClass): TControl;
end;
var
ControlEditsNew: TControl_EditNew;
implementation
constructor TMainEditNewStatic.Create(AObject: TControl; APProp: PointerArray);
begin
Prop__Pointer := APProp;
ControlEditsNew.Add_Edit(Self);
end;
constructor PC_PenCol.Create(AObject: TControl; APProp: PointerArray);
begin
inherited;
Pen := AObject as TShape;
PointerToMethod := Pen.OnMouseDown;
Pen.OnMouseDown := @PenColorMouseDown;
end;
procedure PC_PenCol.PenColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
var
I: integer;
begin
PointerToMethod(Pen, Button,Shift,X, Y);
for I := 0 to High(Prop__Pointer) do
PColor(Prop__Pointer[I])^ := Pen.Brush.Color;
ControlEditsNew.MAIN_Invalidate;
end;
destructor PC_PenCol.Destroy;
begin
Pen.OnMouseDown := PointerToMethod;
end;
class function PC_PenCol.Tagis: Integer;
begin
Result := 1;
end;
class function BC_BrushCol.Tagis: Integer;
begin
Result := 2;
end;
//------------------------- Работа С Массивами ClassEditNew и EditNew ----------
procedure TControl_EditNew.Free_All_Edit;
var
I: Integer;
begin
for I := 0 to High(EditNew_Array) do
EditNew_Array[I].Free;
SetLength(EditNew_Array, 0);
end;
procedure TControl_EditNew.Add_Edit(ACEdit: TObject);
begin
SetLength(EditNew_Array, Length(EditNew_Array) + 1);
EditNew_Array[High(EditNew_Array)] := ACEdit;
end;
procedure TControl_EditNew.Register_Edit(CLEdit: TMainEditStaticClass);
begin
SetLength(Class_EditNew_Array, Length(Class_EditNew_Array) + 1);
Class_EditNew_Array[High(Class_EditNew_Array)] := CLEdit;
end;
function TControl_EditNew.CompareName(AName: String): TMainEditStaticClass;
var
I: Integer;
SignStr: String;
begin
SignStr := Copy(AName, 1, Pos('_', AName));
for I := 0 to High(Class_EditNew_Array) do
if Pos(SignStr, Class_EditNew_Array[I].ClassName) = 1 then begin
Result := Class_EditNew_Array[I];
exit;
end;
Result := nil;
end;
procedure TControl_EditNew.Register_Controls(CLEdit: TControl);
begin
SetLength(Class_Object_Array, Length(Class_Object_Array) + 1);
Class_Object_Array[High(Class_Object_Array)] := CLEdit;
end;
function TControl_EditNew.CompareName_Controls(TMENC: TMainEditStaticClass): TControl;
var
I: Integer;
begin
for I := 0 to High(Class_Object_Array) do
if TMENC.Tagis = Class_Object_Array[I].Tag then begin
Result := Class_Object_Array[I];
exit;
end;
Result := nil;
end;
initialization
ControlEditsNew := TControl_EditNew.Create;
With ControlEditsNew do begin
Register_Edit(PC_PenCol);
Register_Edit(BC_BrushCol);
end;
end.
|
unit fAllgyFind;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ORFn, ORCtrls, ComCtrls, ImgList, VA508AccessibilityManager,
VA508ImageListLabeler, ExtCtrls, System.ImageList;
type
TfrmAllgyFind = class(TfrmAutoSz)
txtSearch: TCaptionEdit;
cmdSearch: TButton;
cmdOK: TButton;
cmdCancel: TButton;
lblSearch: TLabel;
lblSelect: TLabel;
stsFound: TStatusBar;
ckNoKnownAllergies: TCheckBox;
tvAgent: TORTreeView;
imTree: TImageList;
lblDetail: TLabel;
lblSearchCaption: TLabel;
imgLblAllgyFindTree: TVA508ImageListLabeler;
NoAllergylbl508: TVA508StaticText;
procedure cmdSearchClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure txtSearchChange(Sender: TObject);
procedure BuildAgentTree(AgentList: TStrings; const Parent: string; Node: TORTreeNode);
procedure ckNoKnownAllergiesClick(Sender: TObject);
procedure tvAgentDblClick(Sender: TObject);
private
FAllergy: string ;
FExpanded : boolean;
end;
procedure AllergyLookup(var Allergy: string; NKAEnabled: boolean);
implementation
{$R *.DFM}
uses rODAllergy, fARTFreeTextMsg, VA508AccessibilityRouter, VAUtils;
const
IMG_MATCHES_FOUND = 1;
IMG_NO_MATCHES = 2;
TX_3_CHAR = 'Enter at least 3 characters for a search.';
ST_SEARCHING = 'Searching for allergies...';
ST_FOUND = 'Select from the matching entries on the list, or search again.';
ST_NONE_FOUND = 'No matching items were found.';
TC_FREE_TEXT = 'Causative Agent Not On File - No Matches for ';
(* TX_FREE_TEXT = 'Would you like to request that this term be added to' + #13#10 +
'the list of available allergies?' + #13#10 + #13#10 +
'"YES" will send a bulletin to request addition of your' + #13#10 +
'entry to the ALLERGY file for future use, since ' + #13#10 +
'free-text entries for a patient are not allowed.' + #13#10 + #13#10 +
'"NO" will allow you to enter another search term. Please' + #13#10 +
'check your spelling, try alternate spellings or a trade name,' + #13#10 +
'or contact your allergy coordinator for assistance.' + #13#10 + #13#10 +
'"CANCEL" will abort this entry process completely.';*)
// NEW TEXT SUBSTITUTED IN V26.50 - RV
TX_FREE_TEXT = 'The agent you typed was not found in the database.' + CRLF +
'Consider the common causes of search failure:' + CRLF +
' Misspellings' + CRLF +
' Typing more than one agent in a single entry ' + CRLF +
' Typing "No known allergies"' + CRLF +
CRLF +
'Select "NO" to attempt the search again. Carefully check your spelling,'+ CRLF +
'try an alternate spelling, a trade name, a generic name or just entering' + CRLF +
'the first few characters (minimum of 3). Enter only one allergy at a time.' + CRLF +
'Use the "No Known Allergies" check box to mark a patient as NKA.' + CRLF +
CRLF +
'Select "YES" to send a bulletin to the allergy coordinator to request assistance.' + CRLF +
'Only do this if you''ve tried alternate methods of finding the causative agent' + CRLF +
'and have been unsuccessful.' + CRLF +
CRLF +
'Select "CANCEL" to abort this entry process.';
TX_BULLETIN = 'Bulletin has been sent.' + CRLF +
'NOTE: This reactant was NOT added for this patient.';
TC_BULLETIN_ERROR = 'Unable to Send Bulletin';
TX_BULLETIN_ERROR = 'Free text entries are no longer allowed.' + #13#10 +
'Please contact your allergy coordinator if you need assistance.';
var
uFileCount: integer;
ScreenReader: boolean;
procedure AllergyLookup(var Allergy: string; NKAEnabled: boolean);
var
frmAllgyFind: TfrmAllgyFind;
begin
frmAllgyFind := TfrmAllgyFind.Create(Application);
try
ResizeFormToFont(TForm(frmAllgyFind));
//TDP - CQ#19731 Need adjust 508StaticText label slightly when font 12 or larger
case frmAllgyFind.Font.Size of
18: frmAllgyFind.NoAllergylbl508.Left := frmAllgyFind.NoAllergylbl508.Left - 10;
14: frmAllgyFind.NoAllergylbl508.Left := frmAllgyFind.NoAllergylbl508.Left - 6;
12: frmAllgyFind.NoAllergylbl508.Left := frmAllgyFind.NoAllergylbl508.Left - 3;
end;
frmAllgyFind.ckNoKnownAllergies.Enabled := NKAEnabled;
//TDP - CQ#19731 make sure NoAllergylbl508 is enabled and visible if
// ckNoKnownAllergies is disabled
if (ScreenReaderSystemActive) and (frmAllgyFind.ckNoKnownAllergies.Enabled = False) then
begin
frmAllgyFind.NoAllergylbl508.Enabled := True;
frmAllgyFind.NoAllergylbl508.Visible := True;
end;
//TDP - CQ#19731 make sure NoAllergylbl508 is not enabled or visible if
// ckNoKnownAllergies is enabled
if frmAllgyFind.ckNoKnownAllergies.Enabled = True then
begin
frmAllgyFind.NoAllergylbl508.Enabled := False;
frmAllgyFind.NoAllergylbl508.Visible := False;
end;
frmAllgyFind.ShowModal;
Allergy := frmAllgyFind.FAllergy;
finally
frmAllgyFind.Release;
end;
end;
procedure TfrmAllgyFind.FormCreate(Sender: TObject);
begin
inherited;
FAllergy := '';
cmdOK.Enabled := False;
//TDP - CQ#19731 Allow tab to empty search results (tvAgent) when JAWS running
// and provide 508 hint
if ScreenReaderSystemActive then
begin
tvAgent.TabStop := True;
amgrMain.AccessText[tvAgent] := 'No Search Items to Display';
ScreenReader := True;
end;
end;
procedure TfrmAllgyFind.txtSearchChange(Sender: TObject);
begin
inherited;
cmdSearch.Default := True;
cmdOK.Default := False;
cmdOK.Enabled := False;
end;
procedure TfrmAllgyFind.cmdSearchClick(Sender: TObject);
var
AList: TStringlist;
tmpNode1: TORTreeNode;
i: integer;
begin
inherited;
if Length(txtSearch.Text) < 3 then
begin
InfoBox(TX_3_CHAR, 'Information', MB_OK or MB_ICONINFORMATION);
Exit;
end;
StatusText(ST_SEARCHING);
FExpanded := False;
AList := TStringList.Create;
try
if tvAgent.Items <> nil then tvAgent.Items.Clear;
FastAssign(SearchForAllergies(UpperCase(txtSearch.Text)), AList);
uFileCount := 0;
for i := 0 to AList.Count - 1 do
if Piece(AList[i], U, 5) = 'TOP' then uFileCount := uFileCount + 1;
if AList.Count = uFileCount then
begin
lblSelect.Visible := False;
txtSearch.SetFocus;
txtSearch.SelectAll;
cmdOK.Default := False;
cmdSearch.Default := True;
stsFound.SimpleText := ST_NONE_FOUND;
//TDP - CQ#19731 Provide 508 hint for empty search results (tvAgent) when JAWS active.
if ScreenReader then amgrMain.AccessText[tvAgent] := 'No Search Items to Display'
//TDP - CQ#19731 Stop tab to empty search results (tvAgent) when JAWS not active.
else tvAgent.TabStop := False;
cmdOKClick(Self);
end else
begin
//if tvAgent.Items <> nil then tvAgent.Items.Clear;
AList.Insert(0, 'TOP^' + IntToStr(Alist.Count - uFileCount) + ' matches found.^^^0^+');
AList.Add('FREETEXT^Add new free-text allergy^^^TOP^+');
AList.Add('^' + UpperCase(txtSearch.Text) + '^^^FREETEXT^');
BuildAgentTree(AList, '0', nil);
tmpNode1 := TORTreeNode(tvAgent.Items.getFirstNode);
tmpNode1.Expand(False);
tmpNode1 := TORTreeNode(tmpNode1.GetFirstChild);
if tmpNode1.HasChildren then
begin
tmpNode1.Text := tmpNode1.Text + ' (' + IntToStr(tmpNode1.Count) + ')';
tmpNode1.Bold := True;
tmpNode1.StateIndex := IMG_MATCHES_FOUND;
tmpNode1.Expand(True);
FExpanded := True;
end
else
begin
tmpNode1.Text := tmpNode1.Text + ' (no matches)';
tmpNode1.StateIndex := IMG_NO_MATCHES;
end;
while tmpNode1 <> nil do
begin
tmpNode1 := TORTreeNode(tmpNode1.GetNextSibling);
if tmpNode1 <> nil then
if tmpNode1.HasChildren then
begin
tmpNode1.Text := tmpNode1.Text + ' (' + IntToStr(tmpNode1.Count) + ')';
tmpNode1.StateIndex := IMG_MATCHES_FOUND;
if not FExpanded then
begin
tmpNode1.Bold := True;
tmpNode1.Expand(True);
FExpanded := True;
end;
end
else
begin
tmpNode1.StateIndex := IMG_NO_MATCHES;
tmpNode1.Text := tmpNode1.Text + ' (no matches)';
end;
end;
lblSelect.Visible := True;
//TDP - CQ#19731 Clear 508 hint when JAWS active.
if ScreenReader then amgrMain.AccessText[tvAgent] := ''
//TDP - CQ#19731 Allow tab to search results (tvAgent) when JAWS not active.
else tvAgent.TabStop := True;
tvAgent.SetFocus;
cmdSearch.Default := False;
cmdOK.Enabled := True;
stsFound.SimpleText := ST_FOUND;
end;
finally
AList.Free;
StatusText('');
if stsFound.SimpleText = '' then stsFound.TabStop := False
else if ScreenReaderSystemActive then stsFound.TabStop := True;
end;
end;
procedure TfrmAllgyFind.cmdOKClick(Sender: TObject);
var
x, AGlobal: string;
tmpList: TStringList;
OKtoContinue: boolean ;
begin
inherited;
if ckNoKnownAllergies.Checked then
begin
FAllergy := '-1^No Known Allergy^';
Close;
end
else if (txtSearch.Text = '') and ((tvAgent.Selected = nil) or (tvAgent.Items.Count = uFileCount)) then
{bail out - no search term present, and (no items currently in tree or none selected)}
begin
FAllergy := '';
Exit ;
end
else if ((tvAgent.Selected = nil) or
(tvAgent.Items.Count = uFileCount) or
(Piece(TORTreeNode(tvAgent.Selected).StringData, U, 5) = 'FREETEXT')) then
{entry of free text agent - retry, send bulletin, or abort entry}
begin
FAllergy := '';
case InfoBox(TX_FREE_TEXT, TC_FREE_TEXT + UpperCase(txtSearch.Text), MB_YESNOCANCEL or MB_DEFBUTTON2 or MB_ICONQUESTION)of
ID_YES : // send bulletin and abort free-text entry
begin
tmpList := TStringList.Create;
try
OKtoContinue := False;
GetFreeTextARTComment(tmpList, OKtoContinue);
if not OKtoContinue then
begin
stsFound.SimpleText := '';
txtSearch.SetFocus;
Exit;
end;
x := SendARTBulletin(UpperCase(txtSearch.Text), tmpList);
if Piece(x, U, 1) = '-1' then
InfoBox(TX_BULLETIN_ERROR, TC_BULLETIN_ERROR, MB_OK or MB_ICONWARNING)
else if Piece(x, U, 1) = '1' then
InfoBox(TX_BULLETIN, 'Information', MB_OK or MB_ICONINFORMATION)
else
InfoBox(Piece(x, U, 2), TC_BULLETIN_ERROR, MB_OK or MB_ICONWARNING);
finally
tmpList.Free;
end;
Close;
end;
ID_NO : // clear status message, and allow repeat search
begin
stsFound.SimpleText := '';
txtSearch.SetFocus;
Exit;
end;
ID_CANCEL: // abort entry and return to order menu or whatever
Close;
end;
end
else if Piece(TORTreeNode(tvAgent.Selected).StringData, U, 6) = '+' then
{bail out - tree grouper selected}
begin
FAllergy := '';
Exit;
end
else
{matching item selected}
begin
FAllergy := TORTreeNode(tvAgent.Selected).StringData;
x := Piece(FAllergy, U, 2);
AGlobal := Piece(FAllergy, U, 3);
if ((Pos('GMRD', AGlobal) > 0) or (Pos('PSDRUG', AGlobal) > 0)) and (Pos('<', x) > 0) then
//x := Trim(Piece(x, '<', 1));
x := Copy(x, 1, Length(Piece(x, '<', 1)) - 1);
SetPiece(FAllergy, U, 2, x);
Close;
end;
end;
procedure TfrmAllgyFind.cmdCancelClick(Sender: TObject);
begin
inherited;
FAllergy := '';
Close;
end;
procedure TfrmAllgyFind.ckNoKnownAllergiesClick(Sender: TObject);
begin
inherited;
with ckNoKnownAllergies do
begin
txtSearch.Enabled := not Checked;
cmdSearch.Enabled := not Checked;
lblSearch.Enabled := not Checked;
lblSelect.Enabled := not Checked;
tvAgent.Enabled := not Checked;
// CQ #15770 - Allow OK button again if unchecked and items exist - JCS
//cmdOK.Enabled := Checked;
if Checked then
cmdOK.Enabled := True
else
cmdOK.Enabled := (tvAgent.Items.Count > 0);
end;
end;
procedure TfrmAllgyFind.BuildAgentTree(AgentList: TStrings; const Parent: string; Node: TORTreeNode);
var
MyID, MyParent, Name: string;
i: Integer;
ChildNode, tmpNode: TORTreeNode;
HasChildren, Found: Boolean;
begin
tvAgent.Items.BeginUpdate;
with AgentList do for i := 0 to Count - 1 do
begin
Found := False;
MyParent := Piece(Strings[i], U, 5);
if (MyParent = Parent) then
begin
MyID := Piece(Strings[i], U, 1);
Name := Piece(Strings[i], U, 2);
HasChildren := Piece(Strings[i], U, 6) = '+';
if Node <> nil then
begin
if Node.HasChildren then
begin
tmpNode := TORTreeNode(Node.GetFirstChild);
while tmpNode <> nil do
begin
if tmpNode.Text = Piece(Strings[i], U, 2) then Found := True;
tmpNode := TORTreeNode(Node.GetNextChild(tmpNode));
end;
end
else
Node.StateIndex := 0;
end;
if Found then
Continue
else
begin
ChildNode := TORTreeNode(tvAgent.Items.AddChild(Node, Name));
ChildNode.StringData := AgentList[i];
if HasChildren then BuildAgentTree(AgentList, MyID, ChildNode);
end;
end;
end;
tvAgent.Items.EndUpdate;
end;
procedure TfrmAllgyFind.tvAgentDblClick(Sender: TObject);
begin
inherited;
cmdOKClick(Self);
end;
end.
|
unit FNovo2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, AthFindFile, jpeg, ExtCtrls, FileCtrl;
const
EXT_ARQUIVO = '.fxd';
EXT_IMAGEM = '.bmp';
type
TFormNovo2 = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
ScrollBoxCARTAO: TScrollBox;
ButFechar: TBitBtn;
AthFindFile1: TAthFindFile;
ScrollBoxENVELOPE: TScrollBox;
ScrollBoxTIMBRADO: TScrollBox;
ScrollBoxOUTROS: TScrollBox;
procedure FormShow(Sender: TObject);
procedure ButFecharClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure CarregarModelos(StrDiretorio: String; AuxScrollBox: TSCrollBox);
procedure AlocarThumbnail (ScrollBoxPai: TSCrollBox; StrArquivo, StrImagem: String);
procedure DesalocarThumbnail(ScrollBoxPai: TSCrollBox);
procedure Evento_OnClick(Sender: TObject);
public
{ Public declarations }
end;
var
FormNovo2: TFormNovo2;
implementation
uses FTools, Main;
{$R *.DFM}
procedure TFormNovo2.FormShow(Sender: TObject);
begin
PageControl1.ActivePageIndex:= 0;
CarregarModelos(FormTools.MyGetLocalDir + DIR_MODELOS_CARTAO , ScrollBoxCARTAO );
CarregarModelos(FormTools.MyGetLocalDir + DIR_MODELOS_ENVELOPE, ScrollBoxENVELOPE);
CarregarModelos(FormTools.MyGetLocalDir + DIR_MODELOS_TIMBRADO, ScrollBoxTIMBRADO);
CarregarModelos(FormTools.MyGetLocalDir + DIR_MODELOS_OUTROS , ScrollBoxOUTROS );
end;
procedure TFormNovo2.CarregarModelos(StrDiretorio: String; AuxScrollBox: TSCrollBox);
var Cont: Integer;
StrNome1, StrNome2: String;
begin
if (DirectoryExists(StrDiretorio)) then
begin
AthFindFile1.Diretorio:= StrDiretorio;
AthFindFile1.Filtros := '*' + EXT_ARQUIVO;
AthFindFile1.Execute;
for Cont:= 0 to AthFindFile1.InfoName_Files.Count-1 do
begin
StrNome1:= AthFindFile1.InfoName_Files[Cont];
StrNome2:= StringReplace(StrNome1, EXT_ARQUIVO, EXT_IMAGEM, [rfIgnoreCase, rfReplaceAll]);
if (FileExists(StrNome2))
then AlocarThumbnail(AuxScrollBox, StrNome1, StrNome2);
end;
end;
end;
procedure TFormNovo2.AlocarThumbnail(ScrollBoxPai: TSCrollBox; StrArquivo, StrImagem: String);
const BUTTON_WIDTH = 155;
BUTTON_HEIGHT = 94;
DESLOC_X = 158;
DESLOC_Y = 104;
NUM_ELEM_LINHA = 2;
var AuxSpeedButton: TSpeedButton;
AuxTop, AuxLeft, Quant: Integer;
ValMod, ValDiv: Integer;
begin
AuxTop := 3;
AuxLeft:= 3;
Quant := ScrollBoxPai.ComponentCount;
ValMod := (Quant mod NUM_ELEM_LINHA);
ValDiv := (Quant div NUM_ELEM_LINHA);
AuxTop := AuxTop + (DESLOC_Y * ValDiv);
AuxLeft:= AuxLeft + (DESLOC_X * ValMod);
AuxSpeedButton:= TSpeedButton.Create(ScrollBoxPai);
AuxSpeedButton.Parent := ScrollBoxPai;
AuxSpeedButton.Top := AuxTop;
AuxSpeedButton.Left := AuxLeft;
AuxSpeedButton.Width := BUTTON_WIDTH;
AuxSpeedButton.Height := BUTTON_HEIGHT;
AuxSpeedButton.Flat := True;
AuxSpeedButton.ShowHint:= False;
AuxSpeedButton.Hint := StrArquivo;
AuxSpeedButton.OnClick := Evento_OnClick;
AuxSpeedButton.Glyph.LoadFromFile(StrImagem);
end;
procedure TFormNovo2.DesalocarThumbnail(ScrollBoxPai: TSCrollBox);
var AuxComponent: TComponent;
begin
while (ScrollBoxPai.ComponentCount > 0) do
begin
AuxComponent:= ScrollBoxPai.Components[0];
if (AuxComponent is TSpeedButton)
then (AuxComponent as TSpeedButton).Free
else (AuxComponent as TObject ).Free;
end;
end;
procedure TFormNovo2.ButFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFormNovo2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
DesalocarThumbnail(ScrollBoxCARTAO );
DesalocarThumbnail(ScrollBoxENVELOPE);
DesalocarThumbnail(ScrollBoxTIMBRADO);
DesalocarThumbnail(ScrollBoxOUTROS );
end;
procedure TFormNovo2.Evento_OnClick(Sender: TObject);
begin
if (Sender is TSpeedButton) then
begin
EditMainForm.FileOpenFromTemplate((Sender as TSpeedButton).Hint);
Close;
end;
end;
end.
|
unit SplashScreen;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, StdCtrls, ExtCtrls,
ResourceStrings, LCLIntf;
type
{ TSplash }
TSplash = class(TFrame)
BackgroundImage: TImage;
BeCreativeLabel: TLabel;
BuildDateLabel: TLabel;
CompilerVersionLabel: TLabel;
DescriptionLabel: TLabel;
Easy80Label: TLabel;
Easy80LogoImage: TImage;
HashLabel: TLabel;
GitHubImage: TImage;
Label2: TLabel;
ScrollBox1: TScrollBox;
VersionLabel: TLabel;
procedure GitHubImageClick(Sender: TObject);
procedure GitHubImageMouseEnter(Sender: TObject);
procedure GitHubImageMouseLeave(Sender: TObject);
private
function GetLocalizedBuildDate: string;
public
constructor Create(AOwner: TComponent); override;
end;
var
Splash: TSplash;
implementation
{$R *.lfm}
{ TSplash }
procedure TSplash.GitHubImageClick(Sender: TObject);
begin
OpenURL('https://github.com/daar/easy80');
end;
procedure TSplash.GitHubImageMouseEnter(Sender: TObject);
begin
GitHubImage.Cursor := crHandPoint;
end;
procedure TSplash.GitHubImageMouseLeave(Sender: TObject);
begin
GitHubImage.Cursor := crDefault;
end;
{The compiler generated date string is always of the form y/m/d.
This function gives it a string respresentation according to the
shortdateformat}
function TSplash.GetLocalizedBuildDate: string;
var
BuildDate, BuildTime: string;
SlashPos1, SlashPos2: integer;
Date, Time: TDateTime;
begin
BuildDate := {$i %date%};
BuildTime := {$i %time%};
SlashPos1 := Pos('/',BuildDate);
SlashPos2 := SlashPos1 + Pos('/', Copy(BuildDate, SlashPos1+1, Length(BuildDate)-SlashPos1));
Date := EncodeDate(StrToInt(Copy(BuildDate,1,SlashPos1-1)),
StrToInt(Copy(BuildDate,SlashPos1+1,SlashPos2-SlashPos1-1)),
StrToInt(Copy(BuildDate,SlashPos2+1,Length(BuildDate)-SlashPos2)));
Time := EncodeTime(StrToInt(Copy(BuildTime, 1, 2)), StrToInt(Copy(BuildTime, 4, 2)), 0, 0);
Result := FormatDateTime('c', Date) + ' ' + FormatDateTime('t', Time);
end;
constructor TSplash.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := Format(rsEasy80IDEVS, [{$i version.inc}]);
VersionLabel.Caption := Format(rsEasy80IDEVS, [{$i version.inc}]);
BuildDateLabel.Caption := Format(rsDateS, [GetLocalizedBuildDate]);
HashLabel.Caption := Format('Hash: %s', [{$i hash.inc}]);
CompilerVersionLabel.Caption:= Format('FPC: %s (%s-%s)', [{$i %FPCVERSION%}, {$I %FPCTARGETCPU%}, {$I %FPCTARGETOS%}]);
end;
end.
|
{$A+,B-,D-,E-,F-,G-,I-,L-,N-,O+,R-,S-,V-,X+}
{ graph -- module om snel vga-toeren uit te halen}
unit UGraph;
interface {=================================================================}
uses dos,crt;
{
This is a stand-alone unit :
graph is NOT needed,
it is even recommended that you don't use it.
}
type
uRGB = Record
Red,Grn,Blu : Byte;
end;
uPaletteRegister = Array[0..255] of uRGB;
uVGAScreen = array[1..200,1..320] of byte;
Procedure uSetMode(mode : byte);
{ set graphics mode }
procedure uPlot(x,y : word; Color : byte);
{ Same as PuxPixel }
procedure uClearPalette(var color : uPaletteRegister);
{ clears all colors of a pallette to black }
Procedure uSetPalette(var Hue : uPaletteRegister);
{ initalizes a palette on screen }
Procedure uGetPalette(var Hue : uPaletteRegister);
procedure uInitPalette1(var color : uPaletteRegister);
{ creates a 4 color pallette red, Green, blue, grey }
procedure uCyclePalette( var Hue : uPaletteRegister);
{ cycles complete palette upward }
procedure uCyclePart(x1,x2 :byte; var Hue : uPaletteRegister);
{ cycles from x1 to x2 }
procedure uCircle(x,y,radius : word; color : byte);
{ draws a (real) circle }
procedure uInitGraphics;
{ graphics initalisation}
procedure uExitGraphics;
{ returns display to textscreen}
function VGAPresent : boolean;
Procedure WaitRetrace;
Var
TheScreen : uVGAScreen absolute $A000:0000;
implementation {============================================================}
var regs : registers ;
{-------------------------------------------------------------------------}
Procedure uSetMode(mode : byte);
begin
with regs do
begin
AH :=0;
AL := mode;
end;
intr($10,Regs);
end;
const
MaxXRes = 320;
MaxYRes = 200;
MaxX = (MaxXres-1);
MaxY = (MaxYres-1);
Var
XRes, YRes : Integer;
{-------------------------------------------------------------------------}
procedure uPlot(x,y : word; Color : byte);
begin
TheScreen[y,x]:=Color;
end;
{-------------------------------------------------------------------------}
procedure uClearPalette(var color : uPaletteRegister);
Begin
FillChar(color,768,0);
end;
{$G+}
{-------------------------------------------------------------------------}
Procedure uSetPalette(var Hue : uPaletteRegister); (* Assembler;
asm
mov si,offset Hue
mov cx,256*3
xor al,al
mov dx,03c8h
out dx,al
inc dx
@lp:
rep outsb
End;
*)
begin
with regs do
begin
AX :=$1012;
BX :=0;
CX :=256;
ES := Seg(Hue);
DX := ofs(Hue);
end;
Intr($10,regs);
end;
{-------------------------------------------------------------------------}
Procedure uGetPalette(var Hue : uPaletteRegister);
begin
with regs do
begin
AX :=$1017;
BX :=0;
CX :=256;
ES := Seg(Hue);
DX := ofs(Hue);
end;
Intr($10,regs);
end;
{-------------------------------------------------------------------------}
procedure uInitPalette1(var color : uPaletteRegister);
VAR
I : Byte;
Begin
for i :=0 to 63 do
with Color[i] do
begin
Red := i ;
Grn := i ;
Blu := i ;
end;
for i :=64 to 127 do
with Color[i] do
begin
Red := i-64 ;
Grn := 0 ;
Blu := 0 ;
end;
for i :=128 to 191 do
with Color[i] do
begin
Red := 0 ;
Grn := i-128;
Blu := 0 ;
end;
for i :=192 to 255 do
with Color[i] do
begin
Red := 0 ;
Grn := 0 ;
Blu := i-192;
end;
end;
{-------------------------------------------------------------------------}
procedure uCyclePalette( var Hue : uPaletteRegister);
var
i : byte;
Tmp : uRGB;
begin
Tmp:=Hue[0];
move(Hue[2],Hue[1],765);
Hue[255]:=Tmp;
uSetPalette(Hue);
end;
{-------------------------------------------------------------------------}
procedure uCyclePart(x1,x2 :byte; var Hue : uPaletteRegister);
{ 0<= x1 < x2 <= 255 wordt aangenomen, niet gecontroleerd
om snelheidsredenen }
var
Tmp : uRGB;
begin
Tmp:=Hue[x1];
Move(Hue[x1+1],Hue[x1],3*(x2-x1)); { alles in 1 keer, lekker snel ! }
Hue[x2]:=Tmp;
uSetPalette(Hue);
end;
{-------------------------------------------------------------------------}
procedure uInitGraphics;
begin
uSetMode(19);
end;
{-------------------------------------------------------------------------}
procedure Swap(var first,second : integer);
var
temp : integer;
begin
temp := first;
first := second;
second :=temp;
end;
{-------------------------------------------------------------------------}
procedure uCircle(x,y,radius : word; color : byte);
var
a,af,b,bf,target,r2:integer;
begin
Target :=0;
a :=radius;
b:=0;
r2:=sqr(radius);
while a>=b do
begin
b:=round(Sqrt(r2-sqr(a)));
swap(target,b);
while b <target do
begin
af :=(120*a) div 100;
bf :=(120*b) div 100;
uplot(x+af,y+b,color);
uplot(x+bf,y+a,color);
uplot(x-af,y+b,color);
uplot(x-bf,y+a,color);
uplot(x-af,y-b,color);
uplot(x-bf,y-a,color);
uplot(x+af,y-b,color);
uplot(x+bf,y-a,color);
inc(b);
end;
dec(a);
end
end;
{-------------------------------------------------------------------------}
procedure uExitGraphics;
begin
uSetMode(3);
end;
{------------------------------------------------------------------------}
Function VGAPresent : boolean;
var
R : registers;
begin
with r do
begin
AX := $1A00;
Intr($10,r);
VGaPresent := (AL = $1A);
end;
end;
{-------------------------------------------------------------------------}
Procedure WaitRetrace; assembler;
Asm
mov DX,3DAh { Input #1 status register (page 347) }
@WaitVS1:
in AL,DX
test AL,08h { Let him finish this retrace (if any)}
jnz @WaitVS1
@WaitVS2:
in AL,DX
test AL,08h { Is it still in display mode ? }
jz @WaitVS2 { then wait } { NEW retrace has begun ! GO ! GO ! GO ! }
end;
begin
end.
|
unit caTranslate;
{$INCLUDE ca.inc}
interface
uses
// standard delphi units...
Sysutils,
Windows,
Classes,
Forms,
TypInfo,
IniFiles,
FileCtrl,
// ca units...
caConsts,
caUtils,
caForms,
caLog,
caIni;
type
TcaLanguage = (laEnglish, laFrench, laGerman, laAmerican);
//---------------------------------------------------------------------------
// TcaApplicationProxy
//---------------------------------------------------------------------------
TcaApplicationProxy = class(TObject)
private
// private fields...
FExcludedProperties: TStringList;
FLanguage: TcaLanguage;
FLanguageRoot: string;
FDFMFile: TcaDFMFile;
FDictionary: THashedStringList;
// private methods...
function GetLanguageFile(ALanguage: TcaLanguage): string;
function GetLanguageFolder(ALanguage: TcaLanguage): string;
procedure InitializeLanguages;
procedure ReadSelectedLanguage;
procedure SaveLanguageFile;
function GetMainFormOnTaskbar: Boolean;
procedure SetMainFormOnTaskbar(const Value: Boolean);
protected
// protected methods...
procedure LoadLanguageFile;
procedure SaveSelectedLanguage;
public
// lifetime...
constructor Create;
destructor Destroy; override;
// public methods
procedure AddExcludedProperty(const AProperty: string);
procedure CreateForm(InstanceClass: TComponentClass; var Reference);
procedure Initialize;
procedure Run;
procedure TranslateString(const APropPath: String; var APropValue: String);
procedure TranslateStringEvent(Sender: TObject; const APropPath: String; var APropValue: String);
// properties
property DFMFile: TcaDFMFile read FDFMFile;
property Language: TcaLanguage read FLanguage write FLanguage;
property MainFormOnTaskbar: Boolean read GetMainFormOnTaskbar write SetMainFormOnTaskbar;
end;
//---------------------------------------------------------------------------
// TcaTranslator
//---------------------------------------------------------------------------
TcaTranslator = class(TObject)
public
// public methods...
procedure AddExcludedProperty(const AProperty: string);
function CreateForm(AFormClass: TFormClass; AOwner: TComponent;
ATranslateEvent: TcaDFMTranslateStringEvent = nil): Forms.TForm;
procedure LoadLanguageFile;
procedure TranslateString(const APropPath: String; var APropValue: String);
end;
//---------------------------------------------------------------------------
// TcaApplicationAccess
//---------------------------------------------------------------------------
TcaApplicationAccess = class(TComponent)
private
// private fields - copied from Forms.TApplication...
FHandle: HWnd;
FBiDiMode: TBiDiMode;
FBiDiKeyboard: string;
FNonBiDiKeyboard: string;
FObjectInstance: Pointer;
FMainForm: TForm;
protected
// protected properties - Used to supress compiler hints...
property BiDiKeyboard: string read FBiDiKeyboard;
property BiDiMode: TBiDiMode read FBiDiMode;
property Handle: HWnd read FHandle;
property NonBiDiKeyboard: string read FNonBiDiKeyboard;
property ObjectInstance: Pointer read FObjectInstance;
public
// public properties...
property MainForm: TForm read FMainForm write FMainForm;
end;
//---------------------------------------------------------------------------
// TForm
//---------------------------------------------------------------------------
TForm = class(Forms.TForm)
public
// lifetime...
constructor Create(AOwner: TComponent); override;
end;
var
Application: TcaApplicationProxy;
Translator: TcaTranslator;
const
cSelectedLangauge = 'SelectedLangauge';
implementation
//---------------------------------------------------------------------------
// TcaApplicationProxy
//---------------------------------------------------------------------------
// lifetime...
constructor TcaApplicationProxy.Create;
begin
inherited;
InitializeLanguages;
ReadSelectedLanguage;
FDictionary := THashedStringList.Create;
FDFMFile := TcaDFMFile.Create(nil);
FDFMFile.OnTranslateString := TranslateStringEvent;
FExcludedProperties := TStringList.Create;
end;
destructor TcaApplicationProxy.Destroy;
begin
SaveLanguageFile;
FDictionary.Free;
FDFMFile.Free;
FExcludedProperties.Free;
SaveSelectedLanguage;
inherited;
end;
// public methods...
procedure TcaApplicationProxy.AddExcludedProperty(const AProperty: string);
begin
FExcludedProperties.Add(AProperty);
end;
procedure TcaApplicationProxy.CreateForm(InstanceClass: TComponentClass; var Reference);
var
Instance: TComponent;
begin
FDFMFile.FormClass := TFormClass(InstanceClass);
try
FDFMFile.Translate;
Instance := FDFMFile.CreateForm(Forms.Application);
except
TComponent(Reference) := nil;
raise;
end;
if (Forms.Application.MainForm = nil) and (Instance is Forms.TForm) then
begin
TForm(Instance).HandleNeeded;
TcaApplicationAccess(Forms.Application).MainForm := TForm(Instance);
end;
end;
procedure TcaApplicationProxy.Initialize;
begin
Forms.Application.Initialize;
end;
procedure TcaApplicationProxy.Run;
begin
Forms.Application.Run;
end;
// protected methods...
procedure TcaApplicationProxy.LoadLanguageFile;
var
LanguageFile: string;
begin
LanguageFile := GetLanguageFile(FLanguage);
if FileExists(LanguageFile) then
FDictionary.LoadFromFile(LanguageFile);
end;
procedure TcaApplicationProxy.SaveSelectedLanguage;
var
Ini: IcaIni;
begin
Ini := TcaIni.Create;
Ini.Integers[cSelectedLangauge] := Ord(FLanguage);
end;
// private methods...
function TcaApplicationProxy.GetLanguageFile(ALanguage: TcaLanguage): string;
begin
Result := GetLanguageFolder(ALanguage) + cDictionaryFile;
end;
function TcaApplicationProxy.GetLanguageFolder(ALanguage: TcaLanguage): string;
var
LanguageName: string;
begin
LanguageName := GetEnumName(TypeInfo(TcaLanguage), Ord(ALanguage));
Utils.StripLeadingLowerCase(LanguageName);
Result := FLanguageRoot + LanguageName;
Utils.EnsureBackslash(Result);
end;
procedure TcaApplicationProxy.InitializeLanguages;
var
ALanguage: TcaLanguage;
LanguageFolder: string;
begin
FLanguageRoot := Utils.AppPath + cLanguages;
if not DirectoryExists(FLanguageRoot) then
CreateDir(FLanguageRoot);
Utils.EnsureBackslash(FLanguageRoot);
for ALanguage := Low(TcaLanguage) to High(TcaLanguage) do
begin
LanguageFolder := GetLanguageFolder(ALanguage);
if not DirectoryExists(LanguageFolder) then
CreateDir(LanguageFolder);
end;
end;
procedure TcaApplicationProxy.ReadSelectedLanguage;
var
Ini: IcaIni;
begin
Ini := TcaIni.Create;
FLanguage := TcaLanguage(Ini.Integers[cSelectedLangauge]);
end;
procedure TcaApplicationProxy.SaveLanguageFile;
var
LanguageFile: string;
begin
LanguageFile := GetLanguageFile(FLanguage);
if not FileExists(LanguageFile) then
FDictionary.SaveToFile(LanguageFile);
end;
procedure TcaApplicationProxy.TranslateString(const APropPath: string; var APropValue: string);
var
ExcludeIndex: Integer;
ExcludeProp: string;
Name: string;
NameIndex: Integer;
ShouldExclude: Boolean;
Value: string;
begin
ShouldExclude := False;
for ExcludeIndex := 0 to Pred(FExcludedProperties.Count) do
begin
ExcludeProp := FExcludedProperties[ExcludeIndex];
if Pos(ExcludeProp, APropPath) > 0 then
begin
ShouldExclude := True;
Break;
end;
end;
if not ShouldExclude then
begin
Name := APropValue;
NameIndex := FDictionary.IndexOfName(Name);
if NameIndex >= 0 then
begin
Value := FDictionary.ValueFromIndex[NameIndex];
if Value <> cUndefined then
APropValue := Value;
end
else
begin
Name := APropPath + ' - ' + APropValue;
NameIndex := FDictionary.IndexOfName(Name);
if NameIndex >= 0 then
begin
Value := FDictionary.ValueFromIndex[NameIndex];
if Value <> cUndefined then
APropValue := Value;
end
else
FDictionary.Values[Name] := cUndefined;
end;
end;
end;
procedure TcaApplicationProxy.TranslateStringEvent(Sender: TObject; const APropPath: string; var APropValue: string);
begin
TranslateString(APropPath, APropValue);
end;
// property methods...
function TcaApplicationProxy.GetMainFormOnTaskbar: Boolean;
begin
Result := Forms.Application.MainFormOnTaskBar;
end;
procedure TcaApplicationProxy.SetMainFormOnTaskbar(const Value: Boolean);
begin
Forms.Application.MainFormOnTaskBar := Value;
end;
//---------------------------------------------------------------------------
// TcaTranslator
//---------------------------------------------------------------------------
// public methods
procedure TcaTranslator.AddExcludedProperty(const AProperty: string);
begin
Application.AddExcludedProperty(AProperty);
end;
function TcaTranslator.CreateForm(AFormClass: TFormClass; AOwner: TComponent;
ATranslateEvent: TcaDFMTranslateStringEvent = nil): Forms.TForm;
var
DFMFile: IcaDFMFile;
begin
DFMFile := TcaDFMFile.Create(nil);
DFMFile.FormClass := AFormClass;
if Assigned(ATranslateEvent) then
DFMFile.OnTranslateString := ATranslateEvent
else
DFMFile.OnTranslateString := Application.TranslateStringEvent;
LoadLanguageFile;
DFMFile.Translate;
Result := DFMFile.CreateForm(AOwner);
end;
procedure TcaTranslator.LoadLanguageFile;
begin
Application.LoadLanguageFile;
end;
procedure TcaTranslator.TranslateString(const APropPath: string; var APropValue: string);
begin
Application.TranslateString(APropPath, APropValue);
end;
//---------------------------------------------------------------------------
// TForm
//---------------------------------------------------------------------------
// lifetime...
constructor TForm.Create(AOwner: TComponent);
begin
if AOwner is TcaDFMTempOwner then
inherited Create(AOwner)
else
begin
inherited CreateNew(AOwner);
Application.DFMFile.FormClass := TFormClass(ClassType);
Application.DFMFile.Translate;
Application.DFMFile.Binary.ReadComponent(Self);
end;
end;
//---------------------------------------------------------------------------
// Initialization/Finalization
//---------------------------------------------------------------------------
initialization
Application := TcaApplicationProxy.Create;
Translator := TcaTranslator.Create;
finalization
Application.Free;
Translator.Free;
end.
|
namespace Importer;
interface
uses
System.Collections.Generic,
System.Linq,
System.Reflection,
System.Runtime.InteropServices,
System.Text,
System.IO,
Mono.Cecil,
Mono.Cecil.Cil,
RemObjects.CodeGen4;
type
Importer = public class(IAssemblyResolver)
private
method GetTypeName(aTR: TypeReference): String;
begin
if aTR is GenericInstanceType then
exit aTR.Name.Replace('`', '')+'_'+String.Join('__', GenericInstanceType(aTR).GenericArguments.Select(a -> GetTypeName(a)));
var lRemap := fSettings.Types.FirstOrDefault(a -> a.Name = aTR.FullName);
exit coalesce(lRemap:TargetName, aTR.Name);
end;
class method FixType(aGI: TypeReference; aType: TypeReference): TypeReference;
begin
if aType is GenericParameter then
exit GenericInstanceType(aGI).GenericArguments[GenericParameter(aType).Position];
exit aType;
end;
method Resolve(aType: TypeReference): TypeReference;
begin
if aType is GenericInstanceType then begin
var lGI := new GenericInstanceType(aType.Resolve);
for each el in GenericInstanceType(aType) .GenericArguments do
lGI.GenericArguments.Add(Resolve(el));
exit lGI;
end;
exit aType.Resolve;
end;
property MZObjectTypeReference := new CGNamedTypeReference('MZObject'); lazy; readonly;
method LoadAsm(el: String): ModuleDefinition;
method IsListObjectRef(aType: TypeReference; out aArray: Boolean): Boolean;
method WrapListObject(aVal: CGExpression; aType: CGTypeReference; aArray: Boolean): CGExpression;
method WrapObject(aVal: CGExpression; aType: CGTypeReference): CGExpression;
method SigTypeToString(aType: TypeReference): String;
fSettings: ImporterSettings;
fCodeGenerator: CGCodeGenerator;
fLibraries: List<ModuleDefinition> := new List<ModuleDefinition>;
fTypes: Dictionary<TypeDefinition, String> := new Dictionary<TypeDefinition, String>;
fImportNameMapping: Dictionary<String, String> := new Dictionary<String,String>;
fReservedCocoaMemberNames := new List<String>();
fEnumTypes: HashSet<TypeDefinition> := new HashSet<TypeDefinition>;
fValueTypes: HashSet<TypeReference> := new HashSet<TypeReference>();
fPaths: HashSet<String> := new HashSet<String>;
fLoaded: Dictionary<String, ModuleDefinition> := new Dictionary<String,ModuleDefinition>;
fUnit: CGCodeUnit;
fResolver: DefaultAssemblyResolver := new DefaultAssemblyResolver();
protected
method Resolve(fullName: String): AssemblyDefinition;
method Resolve(fullName: String; parameters: ReaderParameters): AssemblyDefinition;
method Resolve(name: AssemblyNameReference): AssemblyDefinition;
method Resolve(name: AssemblyNameReference; parameters: ReaderParameters): AssemblyDefinition;
method GetMethodSignature(aSig: MethodDefinition): String;
method IsObjectRef(aType: TypeReference): Boolean;
public
constructor (aSettings: ImporterSettings; aCodeGenerator: CGCodeGenerator);
method GetMonoType(aType: TypeReference): CGTypeReference;
method GetMarzipanType(aType: TypeReference): CGTypeReference;
event Log: Action<String> raise;
property Output: String;
property AllowOverloadByName: Boolean := true;
method Run;
end;
implementation
constructor Importer(aSettings: ImporterSettings; aCodeGenerator: CGCodeGenerator);
begin
fSettings := aSettings;
fCodeGenerator := aCodeGenerator;
fImportNameMapping.Add('System.Object', 'MZObject');
fImportNameMapping.Add('System.String', 'String');
fImportNameMapping.Add('System.DateTime', 'MZDateTime');
fImportNameMapping.Add('System.SByte', 'int8_t');
fImportNameMapping.Add('System.Byte', 'uint8_t');
fImportNameMapping.Add('System.Int16', 'int16_t');
fImportNameMapping.Add('System.UInt16', 'uint16_t');
fImportNameMapping.Add('System.Int32', 'int32_t');
fImportNameMapping.Add('System.UInt32', 'uint32_t');
fImportNameMapping.Add('System.Int64', 'int64_t');
fImportNameMapping.Add('System.UInt64', 'uint64_t');
fImportNameMapping.Add('System.IntPtr', 'intptr_t');
fImportNameMapping.Add('System.UIntPtr', 'uintptr_t');
fImportNameMapping.Add('System.Char', 'Char');
fImportNameMapping.Add('System.Single', 'float');
fImportNameMapping.Add('System.Double', 'double');
fImportNameMapping.Add('System.Boolean', 'Boolean');
//fImportNameMapping.Add('System.Guid', 'SystemGuid');
fReservedCocoaMemberNames.Add("description");
end;
method Importer.Run;
begin
Log('Loading libraries');
for each el in fSettings.Libraries do begin
LoadAsm(el);
end;
Log('Resolving types');
for each el in fSettings.Types do begin
var lLib := fLibraries.SelectMany(a -> a.Types.Where(b -> (b.GenericParameters.Count = 0) and (b.FullName = el.Name))).ToArray; // Lets ignore those for a sec.
if lLib.Count = 0 then begin
writeLn('Warning: Type "'+el.Name+'" not found.');
continue;
end;
var lNewName := if not String.IsNullOrEmpty(el.TargetName) then el.TargetName else fSettings.Prefix+ lLib[0].Name;
if lLib.Count = 0 then
raise new Exception('Type "'+el.Name+'" was not found')
else if (not lLib[0].IsValueType) then
fTypes.Add(lLib[0], lNewName);
if (not lLib[0].IsValueType) and (not fImportNameMapping.ContainsKey(lLib[0].FullName)) then begin
Log('Adding type '+lNewName+' from '+lLib[0].FullName);
fImportNameMapping.Add(lLib[0].FullName, lNewName);
end
else begin
Log('Skipping type '+lNewName+' from '+lLib[0].FullName+', already covered.');
end;
end;
fUnit := new CGCodeUnit();
fUnit.HeaderComment := new CGCommentStatement('Marzipan import of '#13#10 + String.Join(#13#10, fLibraries.Select(a->' '+a.Assembly.Name.ToString).ToArray));
var lImportsList := new List<CGImport>();
lImportsList.Add(new CGImport('Foundation'));
lImportsList.Add(new CGImport('RemObjects.Marzipan'));
lImportsList.Add(new CGImport('mono.metadata'));
lImportsList.Add(new CGImport('mono.utils'));
lImportsList.Add(new CGImport('mono.jit'));
fUnit.Imports := lImportsList;
fUnit.Namespace := new CGNamespaceReference(if String.IsNullOrEmpty(fSettings.Namespace) then Path.GetFileNameWithoutExtension(fSettings.OutputFilename) else fSettings.Namespace);
fUnit.FileName := Path.GetFileNameWithoutExtension(fSettings.OutputFilename);
var lVars := new List<CGMemberDefinition>;
var lMethods := new List<CGMemberDefinition>;
var lNames: HashSet<String> := new HashSet<String>;
var lSignatures: HashSet<String> := new HashSet<String>;
var lMethodMap: Dictionary<MethodDefinition, CGMethodDefinition> := new Dictionary<MethodDefinition,CGMethodDefinition>;
for each el in fTypes.OrderBy(t -> t.Key.FullName) do begin
Log('Generating type '+el.Key.FullName);
lMethodMap.Clear;
var lFTypePropertyName := 'fType_'+el.Key.FullName.Replace(".", "_");
var lType := new CGClassTypeDefinition(coalesce(el.Value, el.Key.Name));
lType.Visibility := CGTypeVisibilityKind.Public;
lType.Comment := new CGCommentStatement('Import of '+el.Key.FullName+' from '+el.Key.Scope.Name);
var lpt: String;
if (el.Key.BaseType = nil) or not fImportNameMapping.TryGetValue(el.Key.BaseType.FullName, out lpt) then
lpt := 'MZObject';
lType.Ancestors.Add(new CGNamedTypeReference(lpt));
fUnit.Types.Add(lType);
lNames.Clear;
lSignatures.Clear;
lMethodMap.Clear;
for each meth in el.Key.Methods.OrderBy(m -> GetMethodSignature(m)) index n do begin
if (meth.GenericParameters.Count > 0) or (meth.IsSpecialName and meth.Name.StartsWith('op_')) or (meth.IsConstructor and meth.IsStatic) then continue;
//if (meth.ReturnType.IsGenericInstance and meth.ReturnType.IsValueType) then continue;
//if meth.Parameters.Any(a->a.ParameterType.IsGenericInstance and a.ParameterType.IsValueType) then continue;
if not meth.IsPublic then continue;
if meth.Name.Contains('.') and not meth.Name.StartsWith('.') then continue;
var lMonoSig := new CGBlockTypeDefinition('');
lMonoSig.IsPlainFunctionPointer := true;
if (meth.ReturnType.FullName <> 'System.Void') then
lMonoSig.ReturnType := GetMonoType(meth.ReturnType);
if meth.HasThis then begin
var lCGParameterDefinition: CGParameterDefinition := new CGParameterDefinition('__instance', new CGPointerTypeReference(new CGNamedTypeReference('MonoObject')));
lMonoSig.Parameters.Add(lCGParameterDefinition);
end;
var lCGFieldDefinition := new CGFieldDefinition('f_'+n+'_'+meth.Name.Replace('.', '_'), new CGInlineBlockTypeReference(lMonoSig));
lCGFieldDefinition.Static := true;
lCGFieldDefinition.Visibility := CGMemberVisibilityKind.Private;
var lSignature := meth.Name;
for each elpar in meth.Parameters do begin
elpar.Name := elpar.Name.Replace('.','_').Replace('$', '_').Replace('@', '_');
var lParamType: CGTypeReference;
if elpar.ParameterType.IsByReference then
lParamType := new CGPointerTypeReference( GetMonoType(ByReferenceType(elpar.ParameterType).ElementType))
else
lParamType := GetMonoType(elpar.ParameterType);
lMonoSig.Parameters.Add(new CGParameterDefinition('_' + elpar.Name, lParamType));
lSignature := lSignature+"+"+lParamType.ToString;
end;
lMonoSig.Parameters.Add(new CGParameterDefinition('exception', new CGPointerTypeReference(new CGPointerTypeReference(new CGNamedTypeReference('MonoException')))));
lVars.Add(lCGFieldDefinition);
var lMeth := new CGMethodDefinition(if fReservedCocoaMemberNames.Contains(meth.Name.ToLowerInvariant()) then meth.Name+"_" else meth.Name);
lMeth.Visibility := CGMemberVisibilityKind.Public;
lMethodMap[meth] := lMeth;
lMeth.ReturnType := GetMarzipanType(meth.ReturnType);
//if lMeth.ReturnType = MZObjectTypeReference then
//lMeth.Comment := new CGCommentStatement(meth.ReturnType.FullName);
if meth.IsConstructor then begin
lMeth.Name := 'init';
lMeth.ReturnType := CGPredefinedTypeReference.InstanceType;
end;
if lSignatures.Contains(lSignature) or (lNames.Contains(lMeth.Name) and (not AllowOverloadByName or (lMeth.Name = "init"))) then begin
writeLn(lSignature);
for i: Integer := 2 to Int32.MaxValue -1 do begin
if not lNames.Contains(lMeth.Name+i) then begin
lMeth.Name := lMeth.Name+i;
break;
end;
end;
end;
lNames.Add(lMeth.Name);
lSignatures.Add(lSignature);
lMethods.Add(lMeth);
lMeth.Static := meth.IsStatic;
var lCGBeginEndBlockStatement := new CGBeginEndBlockStatement();
lCGBeginEndBlockStatement.Statements := new List<CGStatement>();
//Create CGIfThenElseStatement
var lCondition := new CGUnaryOperatorExpression(new CGAssignedExpression(new CGNamedIdentifierExpression(lCGFieldDefinition.Name)), CGUnaryOperatorKind.Not);
//Source
var lValue := new CGMethodCallExpression(nil, 'getMethodThunk', [new CGCallParameter(new CGStringLiteralExpression(GetMethodSignature(meth)))]);
lValue.CallSite := new CGNamedIdentifierExpression(lFTypePropertyName);
//Dest
var lCGUnaryOperatorExpression := new CGUnaryOperatorExpression(new CGNamedIdentifierExpression(lCGFieldDefinition.Name), CGUnaryOperatorKind.AddressOf);
var lUnaryValue := new CGTypeCastExpression(lCGUnaryOperatorExpression, new CGPointerTypeReference(new CGPointerTypeReference(CGPredefinedTypeReference.Void)));
var lIfStatement : CGStatement := new CGAssignmentStatement(new CGPointerDereferenceExpression(lUnaryValue), lValue);
var lElseStatement: CGStatement := nil;
var lCGIfThenElseStatement := new CGIfThenElseStatement(lCondition, lIfStatement, lElseStatement);
lCGBeginEndBlockStatement.Statements.Add(lCGIfThenElseStatement);
var lCGVariableDeclarationStatement := new CGVariableDeclarationStatement('ex', new CGPointerTypeReference(new CGNamedTypeReference('MonoException')));
lCGVariableDeclarationStatement.Value := new CGNilExpression();
lCGBeginEndBlockStatement.Statements.Add(lCGVariableDeclarationStatement);
var lHasResult := meth.ReturnType.FullName <> 'System.Void';
if lHasResult then
lCGBeginEndBlockStatement.Statements.Add(new CGVariableDeclarationStatement('res', GetMonoType(meth.ReturnType)));
var lCall := new CGMethodCallExpression(nil, lCGFieldDefinition.Name);
if meth.IsStatic = false then begin
if meth.IsConstructor then begin
var lCGMethodCallExpression := new CGMethodCallExpression(new CGInheritedExpression(), 'init');
lCGBeginEndBlockStatement.Statements.Insert(0, new CGBinaryOperatorExpression(new CGSelfExpression(), lCGMethodCallExpression, CGBinaryOperatorKind.Assign));
var lMonoObject := new CGPointerTypeReference(new CGNamedTypeReference('MonoObject'));
var lDefaultValue := new CGMethodCallExpression(new CGNamedIdentifierExpression(lFTypePropertyName), 'instantiate');
lCGBeginEndBlockStatement.Statements.Add(new CGVariableDeclarationStatement('inst', lMonoObject, lDefaultValue));
end else
lCGBeginEndBlockStatement.Statements.Add(new CGVariableDeclarationStatement('inst', new CGPointerTypeReference(new CGNamedTypeReference('MonoObject')), new CGNamedIdentifierExpression('__instance')));
lCall.Parameters.Add(new CGCallParameter(new CGNamedIdentifierExpression('inst'), ''));
end;
//lMeth.Statements.Add(lCGBeginEndBlockStatement);
var lAfterCall: LinkedList<CGStatement>;
for i: Integer := 0 to meth.Parameters.Count -1 do begin
var lParamName := '_'+meth.Parameters[i].Name;
var lParamType: CGTypeReference;
var lParamModifier: CGParameterModifierKind;
var lPTar: TypeReference := meth.Parameters[i].ParameterType;
var lIsByReference := lPTar.IsByReference;
if lIsByReference then begin
lPTar := ByReferenceType(lPTar).ElementType;
lParamType := GetMarzipanType(lPTar);
if meth.Parameters[i].IsOut then
lParamModifier := CGParameterModifierKind.Out
else
lParamModifier := CGParameterModifierKind.Var;
end
else
lParamType := GetMarzipanType(lPTar);
var lPar := new CGParameterDefinition(lParamName, lParamType);
if lIsByReference then lPar.Modifier := lParamModifier;
//if (llParamType = MZObjectTypeReference) and lIsByReference then
//lPar.Comment := new CGCommentStatement(lPTar.FullName);
lMeth.Parameters.Add(lPar);
if lPTar.FullName = 'System.String' then begin
if lPar.Modifier in [CGParameterModifierKind.Var,CGParameterModifierKind.Out] then begin
lCGBeginEndBlockStatement.Statements.Add(new CGVariableDeclarationStatement('par'+i, GetMonoType(lPTar),
new CGMethodCallExpression(new CGNamedIdentifierExpression('MZString'), 'MonoStringWithNSString', [new CGCallParameter(new CGNamedIdentifierExpression(lPar.Name))]) ));
lCall.Parameters.Add(new CGCallParameter(new CGUnaryOperatorExpression(new CGNamedIdentifierExpression('par'+i), CGUnaryOperatorKind.AddressOf)));
if lAfterCall = nil then begin
lAfterCall := new LinkedList<CGStatement>;
end;
lAfterCall.AddLast(new CGAssignmentStatement(new CGNamedIdentifierExpression(lPar.Name), WrapObject(new CGNamedIdentifierExpression('par'+i), lPar.Type)));
end
else begin
lCall.Parameters.Add(new CGCallParameter(new CGMethodCallExpression(
new CGTypeReferenceExpression(new CGNamedTypeReference('MZString')), 'MonoStringWithNSString',
[new CGCallParameter(new CGNamedIdentifierExpression(lPar.Name))])));
end;
end else
if IsObjectRef(lPTar) then begin
if lPar.Modifier in [CGParameterModifierKind.Var,CGParameterModifierKind.Out] then begin
var lTempExpr := new CGIfThenElseExpression(new CGUnaryOperatorExpression(new CGAssignedExpression(new CGNamedIdentifierExpression(lPar.Name)), CGUnaryOperatorKind.Not), new CGNilExpression(), new CGMethodCallExpression(new CGNamedIdentifierExpression(lPar.Name), '__instance'));
lCGBeginEndBlockStatement.Statements.Add(new CGVariableDeclarationStatement('par'+i, GetMonoType(lPTar), new CGTypeCastExpression(lTempExpr, GetMonoType(lPTar)) ));
lCall.Parameters.Add(new CGCallParameter(new CGUnaryOperatorExpression(new CGNamedIdentifierExpression('par'+i), CGUnaryOperatorKind.AddressOf)));
if lAfterCall = nil then begin
lAfterCall := new LinkedList<CGStatement>;
end;
var lArr: Boolean;
if IsListObjectRef(lPTar, out lArr) then
lAfterCall.AddLast(new CGAssignmentStatement(new CGNamedIdentifierExpression(lPar.Name),
WrapListObject(new CGNamedIdentifierExpression('par'+i),
GetMarzipanType(if lPTar is GenericInstanceType then
GenericInstanceType(lPTar).GenericArguments[0]
else
lPTar.GetElementType), lArr)))
else
lAfterCall.AddLast(new CGAssignmentStatement(new CGNamedIdentifierExpression(lPar.Name), WrapObject(new CGNamedIdentifierExpression('par'+i), lPar.Type)));
end else begin
lCall.Parameters.Add(new CGCallParameter(new CGTypeCastExpression(new CGIfThenElseExpression(new CGUnaryOperatorExpression(new CGAssignedExpression(new CGNamedIdentifierExpression(lPar.Name)), CGUnaryOperatorKind.Not), new CGNilExpression(), new CGMethodCallExpression(new CGNamedIdentifierExpression(lPar.Name), '__instance')) , GetMonoType(lPTar))));
end;
end else begin
if lPar.Modifier in [CGParameterModifierKind.Var,CGParameterModifierKind.Out] then
lCall.Parameters.Add(new CGCallParameter(new CGUnaryOperatorExpression(new CGNamedIdentifierExpression(lPar.Name), CGUnaryOperatorKind.AddressOf)))
else
lCall.Parameters.Add(new CGCallParameter(new CGNamedIdentifierExpression(lPar.Name)));
end;
end;
lCall.Parameters.Add(new CGCallParameter(new CGUnaryOperatorExpression(new CGNamedIdentifierExpression('ex'), CGUnaryOperatorKind.AddressOf)));
if lHasResult then begin
var lCGAssignmentStatement := new CGAssignmentStatement(new CGNamedIdentifierExpression('res'), lCall);
lCGBeginEndBlockStatement.Statements.Add(lCGAssignmentStatement);
end
else begin
lCGBeginEndBlockStatement.Statements.Add(lCall);
end;
for each elz in lAfterCall do
lCGBeginEndBlockStatement.Statements.Add(elz);
var lCGIfElseStat := new CGIfThenElseStatement(new CGAssignedExpression( new CGNamedIdentifierExpression('ex')),
new CGMethodCallExpression(nil, 'raiseException', [new CGCallParameter(new CGNamedIdentifierExpression('ex'))] )
);
lCGBeginEndBlockStatement.Statements.Add(lCGIfElseStat);
if meth.IsConstructor then begin
lCGBeginEndBlockStatement.Statements.Add(new CGAssignmentStatement(new CGNamedIdentifierExpression('__instance'), new CGNamedIdentifierExpression('inst')));
lCGBeginEndBlockStatement.Statements.Add(new CGReturnStatement(new CGSelfExpression()));
end;
var lArr: Boolean;
if lHasResult then
if IsListObjectRef(meth.ReturnType, out lArr) then
lCGBeginEndBlockStatement.Statements.Add(new CGReturnStatement(WrapListObject(new CGNamedIdentifierExpression('res'), GetMarzipanType(
if meth.ReturnType is GenericInstanceType then
GenericInstanceType(meth.ReturnType).GenericArguments[0] else
meth.ReturnType.GetElementType), lArr)))
else if IsObjectRef(meth.ReturnType) then
lCGBeginEndBlockStatement.Statements.Add(new CGReturnStatement(WrapObject(new CGNamedIdentifierExpression('res'), GetMarzipanType(meth.ReturnType))))
else
lCGBeginEndBlockStatement.Statements.Add(new CGReturnStatement(new CGNamedIdentifierExpression('res')));
lMeth.Statements.Add(lCGBeginEndBlockStatement);
end;
var lProperties := new List<CGPropertyDefinition>;
for each prop in el.Key.Properties.OrderBy(p -> p.Name) do begin
if not (((prop.GetMethod <> nil) and (prop.GetMethod.IsPublic)) or ((prop.SetMethod <> nil) and (prop.SetMethod.IsPublic)))then continue;
var lName := if fReservedCocoaMemberNames.Contains(prop.Name.ToLowerInvariant()) then prop.Name+"_" else prop.Name;
var lProp := new CGPropertyDefinition(lName);
if coalesce(prop.GetMethod, prop.SetMethod).IsStatic then
lProp.Static := true;
lProp.Visibility := CGMemberVisibilityKind.Public;
for each elz in prop.Parameters do
lProp.Parameters.Add(new CGParameterDefinition(elz.Name, GetMarzipanType(elz.ParameterType)));
lProp.Type := GetMarzipanType(prop.PropertyType);
//if lProp.Type = MZObjectTypeReference then
//lProp.Comment := new CGCommentStatement(prop.PropertyType.FullName);
if assigned(prop.GetMethod) and lMethodMap.ContainsKey(prop.GetMethod) then begin
var lMeth := lMethodMap[prop.GetMethod];
lMeth.Visibility := CGMemberVisibilityKind.Private;
lMeth.Name := /*"get"+*/lName;
lProp.GetExpression := new CGNamedIdentifierExpression(/*"get"+*/lName);
end;
if assigned(prop.SetMethod) and (prop.SetMethod.IsPublic) and lMethodMap.ContainsKey(prop.SetMethod) then begin
var lMeth := lMethodMap[prop.SetMethod];
lMeth.Visibility := CGMemberVisibilityKind.Private;
// move to top
lMeth.Name := 'set'+prop.Name;
lProp.SetExpression := new CGNamedIdentifierExpression('set'+prop.Name);
end;
lProperties.Add(lProp);
end;
var lFType := new CGPropertyDefinition(lFTypePropertyName);
lFType.Static := true;
lFType.Visibility := CGMemberVisibilityKind.Private;
lFType.Attributes.Add(new CGAttribute(new CGNamedTypeReference('Lazy')));
lFType.Type := new CGNamedTypeReference('MZType');
var lCall := new CGMethodCallExpression(new CGMethodCallExpression(new CGNamedIdentifierExpression('MZMonoRuntime'), 'sharedInstance'), 'getType', [new CGCallParameter(new CGStringLiteralExpression(el.Key.FullName+', '+ModuleDefinition(el.Key.Scope).Assembly.Name.Name))]);
lFType.Initializer := lCall;
lType.Members.Add(lFType);
for each elz in lVars do lType.Members.Add(elz);
lVars.Clear;
for each elz in lMethods.Where(a->a.Visibility = CGMemberVisibilityKind.Private) do lType.Members.Add(elz);
for each elz in lMethods.Where(a->a.Visibility = CGMemberVisibilityKind.Public) do lType.Members.Add(elz);
for each elz in lProperties do lType.Members.Add(elz);
lMethods.Clear;
var lGetType := new CGMethodDefinition('getType');
lGetType.Static := true;
lGetType.Visibility := CGMemberVisibilityKind.Public;
lGetType.ReturnType := new CGNamedTypeReference('MZType');
lGetType.Virtuality := CGMemberVirtualityKind.Override;
var lGetTypeBeginEndStat := new CGBeginEndBlockStatement();
lGetTypeBeginEndStat.Statements.Add(new CGReturnStatement(new CGNamedIdentifierExpression(lFTypePropertyName)));
lGetType.Statements.Add(lGetTypeBeginEndStat);
lType.Members.Add(lGetType);
end;
for each el in fEnumTypes index n do begin
var lTypeDef := new CGEnumTypeDefinition(fImportNameMapping[el.FullName]);
lTypeDef.BaseType := GetMonoType(el.Fields.Single(a->a.IsStatic = false).FieldType);
lTypeDef.Comment := new CGCommentStatement('Import of '+el.FullName+' from '+el.Scope.Name);
lTypeDef.Visibility := CGTypeVisibilityKind.Public;
for each lConst in el.Fields.Where(a->a.IsLiteral) do begin
var lCGField := new CGEnumValueDefinition(lConst.Name);
lCGField.Static := true;
lCGField.Value := new CGIntegerLiteralExpression(Convert.ToInt64(lConst.Constant));
lTypeDef.Members.Add(lCGField);
end;
fUnit.Types.Insert(n, lTypeDef);
end;
var lStart := fEnumTypes.Count;
for each el in fValueTypes.ToList() index n do begin
var lTypeDef := new CGStructTypeDefinition(fImportNameMapping[el.FullName]);
if el.FullName = 'System.Guid' then continue;
lTypeDef.Comment := new CGCommentStatement('Import of '+el.FullName+' from '+el.Scope.Name);
lTypeDef.Visibility := CGTypeVisibilityKind.Public;
for each lConst in el.Resolve.Fields.Where(a->a.IsStatic = false) do begin
lTypeDef.Members.Add(
new CGFieldDefinition(lConst.Name.Replace('@', '_'), GetMonoType(FixType(el, lConst.FieldType)), Visibility := CGMemberVisibilityKind.Public));
end;
if not fUnit.Types.Contains(lTypeDef) then
fUnit.Types.Insert(n + lStart, lTypeDef);
end;
Log('Generating code');
Output := fCodeGenerator.GenerateUnit(fUnit);
case fCodeGenerator type of
CGOxygeneCodeGenerator: Output := '{$HIDE W8}'+Environment.NewLine+Environment.NewLine+Output;
CGCSharpCodeGenerator: Output := '#pragma hide W8'+Environment.NewLine+Environment.NewLine+Output;
end;
var lFilename := Path.ChangeExtension(fSettings.OutputFilename, fCodeGenerator.defaultFileExtension);
File.WriteAllText(lFilename, Output);
Log('Wrote '+lFilename);
// for ObjC, we gotta emit a second file. We probably should refatcor this logic into CG4
if fCodeGenerator is CGObjectiveCHCodeGenerator then begin
var lCodeGenerator2 := new CGObjectiveCMCodeGenerator();
Output := lCodeGenerator2.GenerateUnit(fUnit);
lFilename := Path.ChangeExtension(fSettings.OutputFilename, lCodeGenerator2.defaultFileExtension);
File.WriteAllText(lFilename, Output);
Log('Wrote '+lFilename);
end;
end;
method Importer.GetMonoType(aType: TypeReference): CGTypeReference;
begin
if aType.IsPinned then exit GetMonoType(aType.GetElementType);
if aType.IsPointer then exit new CGPointerTypeReference(GetMonoType(aType.GetElementType));
if aType.IsArray then exit new CGPointerTypeReference(new CGNamedTypeReference('MonoArray'));
//if aType.IsArray then exit new CGPointerTypeReference(new CGNamedTypeReference('MonoArray'));
case aType.FullName of
'System.String': exit new CGPointerTypeReference(new CGNamedTypeReference('MonoString'));
'System.Object': exit new CGPointerTypeReference(new CGNamedTypeReference('MonoObject'));
'System.DateTime': exit new CGNamedTypeReference('MZDateTime');
'System.Char': exit new CGNamedTypeReference('Char');
'System.Single': exit new CGNamedTypeReference('Single');
'System.Double': exit new CGNamedTypeReference('Double');
'System.Boolean': exit new CGNamedTypeReference('Boolean');
'System.SByte': exit new CGNamedTypeReference('int8_t');
'System.Byte': exit new CGNamedTypeReference('uint8_t');
'System.Int16': exit new CGNamedTypeReference('int16_t');
'System.UInt16': exit new CGNamedTypeReference('uint16_t');
'System.Int32': exit new CGNamedTypeReference('int32_t');
'System.UInt32': exit new CGNamedTypeReference('uint32_t');
'System.Int64': exit new CGNamedTypeReference('int64_t');
'System.UInt64': exit new CGNamedTypeReference('uint64_t');
'System.IntPtr': exit new CGNamedTypeReference('intptr_t');
'System.UIntPtr': exit new CGNamedTypeReference('uintptr_t');
end;
var lType := Resolve(aType);
if lType.Resolve.IsEnum then begin
if not fEnumTypes.Contains(lType.Resolve) then begin
fEnumTypes.Add(lType.Resolve);
if not fImportNameMapping.ContainsKey(lType.FullName) then
fImportNameMapping.Add(lType.FullName, lType.Name);
end;
exit new CGNamedTypeReference(lType.Name);
end;
if lType.IsValueType then begin
if not fImportNameMapping.ContainsKey(lType.FullName) then begin
fImportNameMapping.Add(lType.FullName, GetTypeName(lType));
if not fValueTypes.Contains(lType) Then begin
fValueTypes.Add(lType);
end;
end;
exit new CGNamedTypeReference(GetTypeName(lType));
end;
exit new CGPointerTypeReference(new CGNamedTypeReference('MonoObject'));
end;
method Importer.GetMarzipanType(aType: TypeReference): CGTypeReference;
begin
if aType.FullName = 'System.Void' then exit nil;
if aType.FullName = 'System.String' then exit new CGNamedTypeReference('String');
if aType.FullName = 'System.DateTime' then exit new CGNamedTypeReference('MZDateTime');;
if aType.IsPinned then exit GetMonoType(aType.GetElementType);
if aType.IsPointer then exit new CGPointerTypeReference(GetMonoType(aType.GetElementType));
var b: Boolean;
if aType.IsGenericInstance and IsListObjectRef(aType, out b) then
exit new CGNamedTypeReference('MZObjectList');
if aType.IsArray then begin
if aType.GetElementType.IsValueType then
exit new CGNamedTypeReference('MZObject')
else
exit new CGNamedTypeReference('MZArray')
end;
var lRes: String;
if self.fImportNameMapping.TryGetValue(aType.FullName, out lRes) then
exit new CGNamedTypeReference(lRes);
exit MZObjectTypeReference;
end;
method Importer.Resolve(fullName: String): AssemblyDefinition;
begin
raise new NotImplementedException;
end;
method Importer.Resolve(fullName: String; parameters: ReaderParameters): AssemblyDefinition;
begin
raise new NotImplementedException;
end;
method Importer.Resolve(name: AssemblyNameReference): AssemblyDefinition;
begin
var lTmp: ModuleDefinition;
if fLoaded.TryGetValue(name.ToString, out lTmp) then exit lTmp.Assembly;
for each el in fPaths do begin
if File.Exists(Path.Combine(el, name.Name+'.dll')) then
exit LoadAsm(Path.Combine(el, name.Name+'.dll')).Assembly;
if File.Exists(Path.Combine(el, name.Name+'.exe')) then
exit LoadAsm(Path.Combine(el, name.Name+'.exe')).Assembly;
if File.Exists(Path.Combine(el, name.Name+'.DLL')) then
exit LoadAsm(Path.Combine(el, name.Name+'.DLL')).Assembly;
if File.Exists(Path.Combine(el, name.Name+'.EXE')) then
exit LoadAsm(Path.Combine(el, name.Name+'.EXE')).Assembly;
end;
exit fResolver.Resolve(name);
end;
method Importer.Resolve(name: AssemblyNameReference; parameters: ReaderParameters): AssemblyDefinition;
begin
raise new NotImplementedException;
end;
method Importer.LoadAsm(el: String): ModuleDefinition;
begin
var rp := new ReaderParameters(ReadingMode.Deferred);
rp.AssemblyResolver := self;
Log(' Loading '+el);
fPaths.Add(Path.GetDirectoryName(el));
var md := ModuleDefinition.ReadModule(el, rp);
fLibraries.Add(md);
if fLoaded.TryGetValue(md.Assembly.Name.ToString, out result) then exit;
fLoaded.Add(md.Assembly.Name.ToString, md);
exit md;
end;
method Importer.GetMethodSignature(aSig: MethodDefinition): String;
begin
exit ':'+aSig.Name+'('+String.Join(',', aSig.Parameters.Select(a->SigTypeToString(a.ParameterType)).ToArray)+')';
end;
method Importer.IsObjectRef(aType: TypeReference): Boolean;
begin
if aType.IsArray then exit true;
if aType.IsByReference or aType.IsPointer then exit false;
exit not aType.IsValueType;
end;
method Importer.WrapObject(aVal: CGExpression; aType: CGTypeReference): CGExpression;
begin
if CGNamedTypeReference(aType):Name = 'String' then begin
exit
new CGMethodCallExpression(new CGNamedIdentifierExpression('MZString'), 'NSStringWithMonoString', [new CGCallParameter(aVal, "")]);
end;
exit
new CGIfThenElseExpression(new CGUnaryOperatorExpression(new CGAssignedExpression(aVal), CGUnaryOperatorKind.Not),
new CGNilExpression(), new CGNewInstanceExpression(aType, [new CGCallParameter(new CGTypeCastExpression(aVal, new CGPointerTypeReference(new CGNamedTypeReference('MonoObject'))))], ConstructorName := 'withMonoInstance')
);
end;
method Importer.SigTypeToString(aType: TypeReference): String;
begin
if aType = nil then exit nil;
case aType.MetadataType of
MetadataType.Array: exit SigTypeToString(aType.GetElementType)+'[]';
MetadataType.Boolean: exit 'bool';
MetadataType.ByReference: exit SigTypeToString(ByReferenceType(aType).ElementType)+'&';
MetadataType.Byte: exit 'byte';
MetadataType.Int16: exit 'short';
MetadataType.Int32: exit 'int';
MetadataType.Int64: exit 'long';
MetadataType.SByte: exit 'sbyte';
MetadataType.UInt16: exit 'ushort';
MetadataType.UInt32: exit 'uint';
MetadataType.UInt64: exit 'ulong';
MetadataType.Char: exit 'char';
MetadataType.Double: exit 'double';
MetadataType.IntPtr: exit 'intptr';
MetadataType.UIntPtr: exit 'uintptr';
MetadataType.Single: exit 'single';
MetadataType.Void: exit 'void';
MetadataType.Pointer: exit SigTypeToString(aType.GetElementType)+'*';
MetadataType.GenericInstance: exit SigTypeToString(GenericInstanceType(aType).ElementType)+'<'+String.Join(',', GenericInstanceType(aType).GenericArguments.Select(a -> SigTypeToString(a)).ToArray)+'>';
MetadataType.Object: exit 'object';
MetadataType.String: exit 'string';
MetadataType.Var,
MetadataType.MVar,
MetadataType.Class,
MetadataType.ValueType: exit aType.ToString;
else
assert(False);
end;
end;
method Importer.IsListObjectRef(aType: TypeReference; out aArray: Boolean): Boolean;
begin
aArray := false;
if aType.IsArray then begin
if not IsObjectRef(aType.GetElementType) then exit false;
aArray := true;
exit true;
end;
if aType.IsGenericInstance then
if (aType.GetElementType.FullName = 'System.Collections.Generic.List`1') and IsObjectRef(GenericInstanceType(aType).GenericArguments[0]) then
exit true;
exit false;
end;
method Importer.WrapListObject(aVal: CGExpression; aType: CGTypeReference; aArray: Boolean): CGExpression;
begin
var lCondition := new CGUnaryOperatorExpression(new CGAssignedExpression(aVal), CGUnaryOperatorKind.Not);
var lIfExpression := new CGNilExpression();
var lCGCallParamsList := new List<CGCallParameter>();
lCGCallParamsList.Add(new CGCallParameter(new CGTypeCastExpression(aVal, new CGPointerTypeReference(new CGNamedTypeReference('MonoObject'))), 'withMonoInstance'));
lCGCallParamsList.Add(new CGCallParameter(new CGMethodCallExpression(nil, 'typeOf', [new CGCallParameter(new CGTypeReferenceExpression(aType))] ), 'elementType'));
var lTypeForNewExpr := if aArray then new CGNamedTypeReference('MZArray') else new CGNamedTypeReference('MZObjectList');
var lElseExpression := new CGNewInstanceExpression(lTypeForNewExpr, lCGCallParamsList, ConstructorName := 'WithMonoInstance');
result := new CGIfThenElseExpression(lCondition, lIfExpression, lElseExpression);
end;
end. |
unit Downloader.Firmware;
interface
uses
Windows, SysUtils, IdURI, Dialogs, ShellApi,
Form.Alert, Global.LanguageString, OS.EnvironmentVariable, Global.Constant,
OS.ProcessOpener, Device.PhysicalDrive, Thread.Download,
OS.DeleteDirectory, Getter.WebPath, Getter.LatestFirmware,
Getter.CodesignVerifier, Thread.Download.Helper, Extern.Rufus, OS.Handle,
Unlocker;
type
TFirmwareDownloader = class
private
TempFolder: String;
DownloadThread: TDownloadThread;
Request: TDownloadRequest;
PhysicalDrive: IPhysicalDrive;
FirmwareGetter: TFirmwareGetter;
FirmwareQueryResult: TFirmwareQueryResult;
FirmwarePath: String;
procedure PrepareTempFolder;
procedure PrepareRequest;
procedure PostDownloadMethod;
procedure StartDownload;
procedure DownloadLatestFirmware;
procedure RenameTempFileAndSetFirmwarePath;
procedure ExpandAndSetFirmwarePath;
function VerifyCodesign: Boolean;
procedure AlertAndDeleteInvalidFile;
procedure Burn;
procedure UnlockedBurn(const Letter: string);
procedure VerifyAndRunRufus;
procedure CheckFirmwarePathAndRunRufus;
procedure CheckTypeAndRunOrBurn;
function IsExe(const Path: String): Boolean;
public
procedure DownloadFirmware;
end;
implementation
uses Form.Main;
procedure TFirmwareDownloader.PrepareTempFolder;
begin
TempFolder := EnvironmentVariable.TempFolder(true);
CreateDir(TempFolder);
end;
procedure TFirmwareDownloader.PrepareRequest;
var
Query: TFirmwareQuery;
begin
Request.Source.FBaseAddress := '';
Request.Source.FFileAddress := TIdURI.URLEncode(
'http://nstfirmware.naraeon.net/NSTFirmwareDownload.php?' +
'Model=' +
PhysicalDrive.IdentifyDeviceResult.Model + '&' +
'Firmware=' +
PhysicalDrive.IdentifyDeviceResult.Firmware);
Request.Source.FType := dftPlain;
Query.Model := PhysicalDrive.IdentifyDeviceResult.Model;
Query.Firmware := PhysicalDrive.IdentifyDeviceResult.Firmware;
FirmwareQueryResult := FirmwareGetter.CheckFirmware(Query);
Request.Destination.FBaseAddress := TempFolder;
Request.Destination.FFileAddress := FirmwareQueryResult.FirmwarePath;
Request.Destination.FPostAddress := '_tmp';
Request.Destination.FType := dftPlain;
Request.DownloadModelStrings.Download := CapFirmDwld[CurrLang];
Request.DownloadModelStrings.Cancel := BtDnldCncl[CurrLang];
end;
procedure TFirmwareDownloader.StartDownload;
begin
DownloadThread := TDownloadThread.Create;
DownloadThread.SetRequest(Request);
DownloadThread.SetPostDownloadMethod(PostDownloadMethod);
DownloadThread.Start;
end;
procedure TFirmwareDownloader.DownloadFirmware;
begin
self.PhysicalDrive := fMain.SelectedDrive;
fMain.tRefresh.Enabled := false;
fMain.gFirmware.Visible := false;
DownloadLatestFirmware;
end;
procedure TFirmwareDownloader.Burn;
var
Letter: String;
Unlock: IDriveHandleUnlocker;
begin
Letter := Copy(fMain.cUSB.Items[fMain.cUSB.ItemIndex], 1, 3);
Unlock := TDriveHandleUnlocker.Create(Letter, fMain.IdentifiedDriveList,
fMain.SelectedDrive);
UnlockedBurn(Letter);
end;
procedure TFirmwareDownloader.UnlockedBurn(const Letter: string);
begin
AlertCreate(fMain, AlrtStartFormat[CurrLang]);
Rufus.RunRufus(Letter, FirmwarePath, false);
AlertCreate(fMain, AlrtFirmEnd[CurrLang]);
DeleteDirectory(ExtractFilePath(FirmwarePath));
DeleteDirectory(TempFolder);
end;
procedure TFirmwareDownloader.DownloadLatestFirmware;
begin
AlertCreate(fMain, AlrtFirmStart[CurrLang]);
FirmwareGetter := TFirmwareGetter.Create;
try
PrepareTempFolder;
PrepareRequest;
StartDownload;
finally
FreeAndNil(FirmwareGetter);
end;
end;
procedure TFirmwareDownloader.RenameTempFileAndSetFirmwarePath;
begin
RenameFile(Request.Destination.FBaseAddress +
Request.Destination.FFileAddress +
Request.Destination.FPostAddress,
TempFolder + FirmwareQueryResult.FirmwarePath);
FirmwarePath := TempFolder + FirmwareQueryResult.FirmwarePath;
end;
procedure TFirmwareDownloader.ExpandAndSetFirmwarePath;
var
NewPath: String;
begin
if ExtractFileExt(FirmwarePath) = '.is_' then
begin
NewPath := Copy(FirmwarePath, 1, Length(FirmwarePath) -
Length(ExtractFileExt(FirmwarePath))) + '.iso';
ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDir,
'expand.exe "' + FirmwarePath + '" "' + NewPath + '"');
DeleteFile(FirmwarePath);
FirmwarePath := NewPath;
end;
end;
procedure TFirmwareDownloader.AlertAndDeleteInvalidFile;
begin
AlertCreate(fMain, AlrtWrongCodesign[CurrLang]);
DeleteFile(FirmwarePath);
DeleteDirectory(ExtractFilePath(TempFolder));
end;
function TFirmwareDownloader.VerifyCodesign: Boolean;
var
CodesignVerifier: TCodesignVerifier;
begin
result := false;
if ExtractFileExt(FirmwarePath)
[Length(ExtractFileExt(FirmwarePath))] = '_' then
begin
CodesignVerifier := TCodesignVerifier.Create;
result := CodesignVerifier.VerifySignByPublisher(FirmwarePath,
NaraeonPublisher);
if not result then
AlertAndDeleteInvalidFile;
FreeAndNil(CodesignVerifier);
end;
end;
procedure TFirmwareDownloader.PostDownloadMethod;
begin
if not FileExists(Request.Destination.FBaseAddress +
Request.Destination.FFileAddress +
Request.Destination.FPostAddress) then
begin
AlertCreate(fMain, AlrtFirmCanc[CurrLang]);
fMain.gFirmware.Visible := true;
fMain.tRefresh.Enabled := true;
Free; //FI:W515
end
else
VerifyAndRunRufus;
end;
procedure TFirmwareDownloader.VerifyAndRunRufus;
begin
RenameTempFileAndSetFirmwarePath;
if not VerifyCodesign then
begin
fMain.gFirmware.Visible := true;
fMain.tRefresh.Enabled := true;
Free; //FI:W515
end
else
begin
ExpandAndSetFirmwarePath;
CheckFirmwarePathAndRunRufus;
end;
end;
procedure TFirmwareDownloader.CheckFirmwarePathAndRunRufus;
begin
if not FileExists(FirmwarePath) then
begin
AlertCreate(fMain, AlrtFirmFail[CurrLang]);
fMain.gFirmware.Visible := true;
fMain.tRefresh.Enabled := true;
Free; //FI:W515
end
else
CheckTypeAndRunOrBurn;
end;
function TFirmwareDownloader.IsExe(const Path: String): Boolean;
begin
result := ExtractFileExt(Path) = '.exe';
end;
procedure TFirmwareDownloader.CheckTypeAndRunOrBurn;
begin
if (not IsExe(FirmwarePath)) and (not Rufus.CheckRufus) then
begin
AlertCreate(fMain, AlrtFirmFail[CurrLang]);
fMain.gFirmware.Visible := true;
fMain.tRefresh.Enabled := true;
Free; //FI:W515
end;
if IsExe(FirmwarePath) then
begin
ShellExecute(0, 'open', PChar(FirmwarePath), nil, nil, SW_SHOW);
fMain.iFirmUp.OnClick(nil);
end
else
begin
Burn;
end;
fMain.gFirmware.Visible := true;
fMain.tRefresh.Enabled := true;
Free; //FI:W515
end;
end.
|
{
Maximum Netword Flow
Ford Fulkerson Alg. O(N.E2) Implemantation O(N5)
Input:
N: Number of vertices
C: Capacities (No restrictions)
S, T: Source, Target(Sink)
Output:
F: Flow (SkewSymmetric: F[i, j] = - F[j, i])
Flow: Maximum Flow
Reference:
CLR
By Behdad
}
program
MaximumFlow;
const
MaxN = 100 + 2;
var
N, S, T : Integer;
C, F : array [1 .. MaxN, 1 .. MaxN] of Integer;
Mark : array [1 .. MaxN] of Boolean;
Flow : Longint;
function Min (A, B : Integer) : Integer;
begin
if A <= B then
Min := A
else
Min := B;
end;
function FDfs (V, LEpsilon : Integer) : Integer;
var
I, Te : Integer;
begin
if V = T then
begin
FDfs := LEpsilon;
Exit;
end;
Mark[V] := True;
for I := 1 to N do
if (C[V, I] > F[V, I]) and not Mark[I] then
begin
Te := FDfs(I, Min(LEpsilon, C[V, I] - F[V, I]));
if Te > 0 then
begin
F[V, I] := F[V, I] + Te;
F[I, V] := - F[V, I];
FDfs := Te;
Exit;
end;
end;
FDfs := 0;
end;
procedure FordFulkerson;
var
Flow2 : Longint;
begin
repeat
FillChar(Mark, SizeOf(Mark), 0);
Flow2 := Flow;
Inc(Flow, FDfs(S, MaxInt));
until Flow = Flow2;
end;
begin
FordFulkerson;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Web.HTTPDImpl;
interface
uses Web.HTTPDMethods, System.SysUtils;
type
// Base class of HTTPD abstraction. Derive from this class to support a specific Apache version.
TAbstractHTTPDMethods = class abstract
public
procedure InitModule; virtual; abstract;
// Consts
function get_AP_OK: Integer; virtual; abstract;
function get_AP_DONE: Integer; virtual; abstract;
function get_AP_DECLINED: Integer; virtual; abstract;
function get_APR_HOOK_REALLY_FIRST: Integer; virtual; abstract;
function get_APR_HOOK_FIRST: Integer; virtual; abstract;
function get_APR_HOOK_MIDDLE: Integer; virtual; abstract;
function get_APR_HOOK_LAST: Integer; virtual; abstract;
function get_APR_HOOK_REALLY_LAST: Integer; virtual; abstract;
// Utils
function server_root_relative(const ARequestRec: PHTTPDRequest; const AURI: UTF8String): UTF8String; virtual; abstract;
procedure hook_handler(const AHandler: THTTPDMethods.THandlerProc; const APre: PPChar; const ASucc: PPChar; AOrder: Integer); virtual; abstract;
procedure hook_child_init(const AInitiation: THTTPDMethods.TInitiationProc; const APre: PPChar; const ASucc: PPChar; AOrder: Integer); virtual; abstract;
procedure pool_cleanup_register(const p: PHTTPDPool; const data: Pointer; APlainTermination: THTTPDMethods.TTerminationFunc; AChildTermination: THTTPDMethods.TTerminationFunc); virtual; abstract;
// Read request
function get_handler(const ARequestRect: PHTTPDRequest): UTF8String; virtual; abstract;
function get_method(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_ContentType(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_protocol(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_unparsed_uri(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_args(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_path_info(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_filename(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_Field(const ARequestRec: PHTTPDRequest; const AKey: UTF8String): UTF8String; virtual; abstract;
function get_headers_in_Accept(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_From(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_hostname(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_Referer(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_UserAgent(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_content_encoding(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_ContentType(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_ContentLength(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_Title(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_ServerPort(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_client_block(const ARequestRec: PHTTPDRequest; Buffer: PByte; Count: Integer): Integer; virtual; abstract;
function get_Content(const ARequestRec: PHTTPDRequest): TBytes; virtual; abstract;
function get_connection_ClientIP(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_connection_RemoteHost(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_Connection(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
function get_headers_in_Cookie(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
/// <summary> Returns the header Authorization value </summary>
function get_headers_in_Authorization(const ARequestRec: PHTTPDRequest): UTF8String; virtual; abstract;
// write request response
procedure set_status(const ARequestRec: PHTTPDRequest; ACode: Integer); virtual; abstract;
procedure add_headers_out(const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); virtual; abstract;
procedure set_headers_out(const ARequestRec: PHTTPDRequest; const Key, Value: UTF8String); virtual; abstract;
procedure set_headers_out_ContentType(const ARequestRec: PHTTPDRequest; const AType: UTF8String); virtual; abstract;
procedure set_headers_out_ContentEncoding(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); virtual; abstract;
procedure set_ContentType(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); virtual; abstract;
procedure set_headers_out_ContentLength(const ARequestRec: PHTTPDRequest; AValue: Integer); virtual; abstract;
procedure set_headers_out_Location(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); virtual; abstract;
function write_buffer(const ARequestRec: PHTTPDRequest; var Buffer; Count: Integer): Integer; virtual; abstract;
function write_string(const ARequestRec: PHTTPDRequest; const AValue: UTF8String): Integer; virtual; abstract;
end;
TCommonHTTPDMethods = class abstract(TAbstractHTTPDMethods)
public
const
cUserAgent = 'User-Agent';
cContentType = 'Content-Type';
cAccept = 'Accept';
cCookie = 'Cookie';
cAuthorization = 'Authorization';
cFrom = 'From';
cReferer = 'Referer';
cTitle = 'Title';
cConnection = 'Connection';
cContentLength = 'Content-Length';
cLocation = 'Location';
// Typical values
cAP_OK = 0;
cAP_DONE = -2;
cAP_DECLINED = -1;
cAPR_HOOK_REALLY_FIRST = -10;
cAPR_HOOK_FIRST = 0;
cAPR_HOOK_MIDDLE = 10;
cAPR_HOOK_LAST = 20;
cAPR_HOOK_REALLY_LAST = 30;
protected
function get_headers_in(const ARequestRec: PHTTPDRequest; const AKey: UTF8String): UTF8String; virtual; abstract;
public
function get_AP_OK: Integer; override;
function get_AP_DONE: Integer; override;
function get_AP_DECLINED: Integer; override;
function get_APR_HOOK_REALLY_FIRST: Integer; override;
function get_APR_HOOK_FIRST: Integer; override;
function get_APR_HOOK_MIDDLE: Integer; override;
function get_APR_HOOK_LAST: Integer; override;
function get_APR_HOOK_REALLY_LAST: Integer; override;
function get_headers_in_Accept(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_Field(const ARequestRec: PHTTPDRequest; const AKey: UTF8String): UTF8String; override;
function get_headers_in_Connection(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_ContentLength(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_ContentType(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_Cookie(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_Authorization(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_From(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_Referer(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_Title(const ARequestRec: PHTTPDRequest): UTF8String; override;
function get_headers_in_UserAgent(const ARequestRec: PHTTPDRequest): UTF8String; override;
procedure set_headers_out_ContentLength(const ARequestRec: PHTTPDRequest; AValue: Integer); override;
procedure set_headers_out_Location(const ARequestRec: PHTTPDRequest; const AValue: UTF8String); override;
end;
procedure RegisterHTTPD(const AHTTPDImpl: TAbstractHTTPDMethods);
var
GHTTPDImpl: TAbstractHTTPDMethods;
implementation
uses Web.ApacheConst;
function TCommonHTTPDMethods.get_APR_HOOK_FIRST: Integer;
begin
Result := cAPR_HOOK_FIRST
end;
function TCommonHTTPDMethods.get_APR_HOOK_LAST: Integer;
begin
Result := cAPR_HOOK_LAST
end;
function TCommonHTTPDMethods.get_APR_HOOK_MIDDLE: Integer;
begin
Result := cAPR_HOOK_MIDDLE
end;
function TCommonHTTPDMethods.get_APR_HOOK_REALLY_FIRST: Integer;
begin
Result := cAPR_HOOK_REALLY_FIRST
end;
function TCommonHTTPDMethods.get_APR_HOOK_REALLY_LAST: Integer;
begin
Result := cAPR_HOOK_REALLY_LAST
end;
function TCommonHTTPDMethods.get_AP_DECLINED: Integer;
begin
Result := cAP_DECLINED
end;
function TCommonHTTPDMethods.get_AP_DONE: Integer;
begin
Result := cAP_DONE
end;
function TCommonHTTPDMethods.get_AP_OK: Integer;
begin
Result := cAP_OK
end;
function TCommonHTTPDMethods.get_headers_in_Accept(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cAccept);
end;
function TCommonHTTPDMethods.get_headers_in_Cookie(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cCookie);
end;
function TCommonHTTPDMethods.get_headers_in_Authorization(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cAuthorization);
end;
function TCommonHTTPDMethods.get_headers_in_Connection(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cConnection);
end;
function TCommonHTTPDMethods.get_headers_in_ContentLength(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cContentLength);
end;
function TCommonHTTPDMethods.get_headers_in_ContentType(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cContentType);
end;
function TCommonHTTPDMethods.get_headers_in_Field(
const ARequestRec: PHTTPDRequest; const AKey: UTF8String): UTF8String;
begin
Result := get_headers_in(ARequestRec, AKey);
end;
function TCommonHTTPDMethods.get_headers_in_From(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cFrom);
end;
function TCommonHTTPDMethods.get_headers_in_Referer(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cReferer);
end;
function TCommonHTTPDMethods.get_headers_in_Title(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cTitle);
end;
function TCommonHTTPDMethods.get_headers_in_UserAgent(
const ARequestRec: PHTTPDRequest): UTF8String;
begin
Result := get_headers_in(ARequestRec, cUserAgent);
end;
procedure TCommonHTTPDMethods.set_headers_out_ContentLength(
const ARequestRec: PHTTPDRequest; AValue: Integer);
begin
set_headers_out(ARequestRec, cContentLength, PUTF8Char(UTF8String(IntToStr(AValue))));
end;
procedure TCommonHTTPDMethods.set_headers_out_Location(const ARequestRec: PHTTPDRequest;
const AValue: UTF8String);
begin
set_headers_out(ARequestRec, cLocation, PUTF8Char(AValue));
end;
procedure RegisterHTTPD(const AHTTPDImpl: TAbstractHTTPDMethods);
begin
if GHTTPDImpl <> nil then
begin
GHTTPDImpl.Free;
raise EHTTPMethodsError.CreateRes(@sMultipleVersions);
end;
GHTTPDImpl := AHTTPDImpl;
end;
initialization
finalization
FreeAndNil(GHTTPDImpl);
end.
|
unit Ths.Erp.Database.Table.AyarEFaturaIletisimKanali;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TAyarEFaturaIletisimKanali = class(TTable)
private
FKod: TFieldDB;
FAciklama: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property Kod: TFieldDB read FKod write FKod;
Property Aciklama: TFieldDB read FAciklama write FAciklama;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAyarEFaturaIletisimKanali.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_efatura_iletisim_kanali';
SourceCode := '1000';
FKod := TFieldDB.Create('kod', ftString, '', 0, False, False);
FAciklama := TFieldDB.Create('aciklama', ftString, '', 0, False, True);
end;
procedure TAyarEFaturaIletisimKanali.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKod.FieldName,
TableName + '.' + FAciklama.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FKod.FieldName).DisplayLabel := 'Kod';
Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama';
end;
end;
end;
procedure TAyarEFaturaIletisimKanali.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FKod.FieldName,
TableName + '.' + FAciklama.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FKod.Value := FormatedVariantVal(FieldByName(FKod.FieldName).DataType, FieldByName(FKod.FieldName).Value);
FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAyarEFaturaIletisimKanali.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FKod.FieldName,
FAciklama.FieldName
]);
NewParamForQuery(QueryOfInsert, FKod);
NewParamForQuery(QueryOfInsert, FAciklama);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarEFaturaIletisimKanali.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FKod.FieldName,
FAciklama.FieldName
]);
NewParamForQuery(QueryOfUpdate, FKod);
NewParamForQuery(QueryOfUpdate, FAciklama);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAyarEFaturaIletisimKanali.Clone():TTable;
begin
Result := TAyarEFaturaIletisimKanali.Create(Database);
Self.Id.Clone(TAyarEFaturaIletisimKanali(Result).Id);
FKod.Clone(TAyarEFaturaIletisimKanali(Result).FKod);
FAciklama.Clone(TAyarEFaturaIletisimKanali(Result).FAciklama);
end;
end.
|
unit BCEditor.Editor.CompletionProposal.Columns;
interface
uses
System.Classes, Vcl.Graphics, System.SysUtils;
type
TBCEditorProposalColumn = class(TCollectionItem)
strict private
FAutoWidth: Boolean;
FItemList: TStrings;
FWidth: Integer;
procedure SetItemList(const AValue: TStrings);
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
published
property AutoWidth: Boolean read FAutoWidth write FAutoWidth default True;
property ItemList: TStrings read FItemList write SetItemList;
property Width: Integer read FWidth write FWidth default 0;
end;
XTBCEditorProposalColumnsException = class(Exception);
TBCEditorProposalColumns = class(TCollection)
strict private
FOwner: TPersistent;
function GetItem(AIndex: Integer): TBCEditorProposalColumn;
procedure SetItem(AIndex: Integer; AValue: TBCEditorProposalColumn);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent; AItemClass: TCollectionItemClass);
function Add: TBCEditorProposalColumn;
procedure AddItemToColumns(items: array of string);
procedure AddItemsToColumns(items: array of TStrings);
procedure ClearAll;
function FindItemID(AID: Integer): TBCEditorProposalColumn;
function Insert(AIndex: Integer): TBCEditorProposalColumn;
property Items[AIndex: Integer]: TBCEditorProposalColumn read GetItem write SetItem; default;
end;
implementation
{ TBCEditorProposalColumn }
constructor TBCEditorProposalColumn.Create(ACollection: TCollection);
begin
inherited;
FItemList := TStringList.Create;
FAutoWidth := True;
FWidth := 0;
end;
destructor TBCEditorProposalColumn.Destroy;
begin
FItemList.Free;
inherited;
end;
procedure TBCEditorProposalColumn.Assign(ASource: TPersistent);
begin
if ASource is TBCEditorProposalColumn then
with ASource as TBCEditorProposalColumn do
Self.FItemList.Assign(FItemList)
else
inherited Assign(ASource);
end;
procedure TBCEditorProposalColumn.SetItemList(const AValue: TStrings);
begin
FItemList.Assign(AValue);
end;
{ TBCEditorProposalColumns }
constructor TBCEditorProposalColumns.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass);
begin
inherited Create(AItemClass);
FOwner := AOwner;
end;
function TBCEditorProposalColumns.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TBCEditorProposalColumns.AddItemsToColumns(items: array of TStrings);
var
i: Integer;
begin
for i := Low(items) to High(items) do
Self[i].ItemList.AddStrings(items[i]);
end;
procedure TBCEditorProposalColumns.AddItemToColumns(items: array of string);
var
i: Integer;
begin
if Length(items) <> Self.Count then
raise XTBCEditorProposalColumnsException.Create('Items does not matches columns.');
for i := Low(items) to High(items) do
Self[i].ItemList.Add(items[i]);
end;
procedure TBCEditorProposalColumns.ClearAll;
var
i: Integer;
begin
for i := 0 to Self.Count - 1 do
Self[i].ItemList.Clear;
end;
function TBCEditorProposalColumns.GetItem(AIndex: Integer): TBCEditorProposalColumn;
begin
Result := inherited GetItem(AIndex) as TBCEditorProposalColumn;
end;
procedure TBCEditorProposalColumns.SetItem(AIndex: Integer; AValue: TBCEditorProposalColumn);
begin
inherited SetItem(AIndex, AValue);
end;
function TBCEditorProposalColumns.Add: TBCEditorProposalColumn;
begin
Result := inherited Add as TBCEditorProposalColumn;
end;
function TBCEditorProposalColumns.FindItemID(AID: Integer): TBCEditorProposalColumn;
begin
Result := inherited FindItemID(AID) as TBCEditorProposalColumn;
end;
function TBCEditorProposalColumns.Insert(AIndex: Integer): TBCEditorProposalColumn;
begin
Result := inherited Insert(AIndex) as TBCEditorProposalColumn;
end;
end.
|
UNIT myGenerics;
INTERFACE
USES sysutils;
{$MACRO ON}
TYPE
T_arrayOfString =array of ansistring;
T_arrayOfPointer=array of pointer ;
T_arrayOfDouble =array of double ;
T_arrayOfLongint=array of longint ;
T_arrayOfInt64 =array of int64 ;
{$define arrayOp:=OPERATOR :=(x:M_VALUE_TYPE):M_ARRAY_TYPE}
{$define arrayFunctions:=
FUNCTION arrEquals(CONST x,y:M_ARRAY_TYPE):boolean;
PROCEDURE prepend(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
PROCEDURE append(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
PROCEDURE append(VAR x:M_ARRAY_TYPE; CONST y:M_ARRAY_TYPE);
FUNCTION arrContains(CONST x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE):boolean;
PROCEDURE appendIfNew(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
PROCEDURE dropFirst(VAR x:M_ARRAY_TYPE; CONST dropCount:longint);
PROCEDURE dropValues(VAR x:M_ARRAY_TYPE; CONST toDrop:M_VALUE_TYPE);
PROCEDURE sort(VAR entry:M_ARRAY_TYPE);
PROCEDURE sortUnique(VAR entry:M_ARRAY_TYPE)}
{$define M_ARRAY_TYPE:=T_arrayOfString } {$define M_VALUE_TYPE:=ansistring} arrayFunctions; arrayOp;
{$define M_ARRAY_TYPE:=T_arrayOfPointer} {$define M_VALUE_TYPE:=pointer } arrayFunctions;
{$define M_ARRAY_TYPE:=T_arrayOfDouble } {$define M_VALUE_TYPE:=double } arrayFunctions; arrayOp;
{$define M_ARRAY_TYPE:=T_arrayOfLongint} {$define M_VALUE_TYPE:=longint } arrayFunctions; arrayOp;
{$define M_ARRAY_TYPE:=T_arrayOfInt64 } {$define M_VALUE_TYPE:=int64 } arrayFunctions; arrayOp;
{$undef arrayFunctions}
{$undef arrayOp}
CONST C_EMPTY_STRING_ARRAY :T_arrayOfString =();
CONST C_EMPTY_POINTER_ARRAY:T_arrayOfPointer=();
CONST C_EMPTY_DOUBLE_ARRAY :T_arrayOfDouble =();
CONST C_EMPTY_LONGINT_ARRAY:T_arrayOfLongint=();
CONST C_EMPTY_INT64_ARRAY :T_arrayOfInt64 =();
TYPE
{$define someKeyMapInterface:=
object
TYPE VALUE_TYPE_ARRAY=array of VALUE_TYPE;
KEY_VALUE_PAIR=record
key:M_KEY_TYPE;
value:VALUE_TYPE;
end;
KEY_VALUE_LIST=array of KEY_VALUE_PAIR;
VALUE_DISPOSER=PROCEDURE(VAR v:VALUE_TYPE);
MY_TYPE=specialize M_MAP_TYPE<VALUE_TYPE>;
private VAR
entryCount:longint;
rebalanceFac:double;
bucket:array of KEY_VALUE_LIST;
disposer:VALUE_DISPOSER;
PROCEDURE rehash(CONST grow:boolean);
protected
TYPE MY_VALUE_TYPE=VALUE_TYPE;
PROCEDURE disposeValue(VAR v:VALUE_TYPE); virtual;
public
CONSTRUCTOR create(CONST rebalanceFactor:double; CONST disposer_:VALUE_DISPOSER=nil);
CONSTRUCTOR create(CONST disposer_:VALUE_DISPOSER=nil);
CONSTRUCTOR createClone(VAR map:MY_TYPE);
PROCEDURE overrideDisposer(CONST newDisposer:VALUE_DISPOSER);
DESTRUCTOR destroy;
FUNCTION containsKey(CONST key:M_KEY_TYPE; OUT value:VALUE_TYPE):boolean;
FUNCTION containsKey(CONST key:M_KEY_TYPE):boolean;
FUNCTION get(CONST key:M_KEY_TYPE):VALUE_TYPE;
PROCEDURE put(CONST key:M_KEY_TYPE; CONST value:VALUE_TYPE);
PROCEDURE putAll(CONST entries:KEY_VALUE_LIST);
PROCEDURE dropKey(CONST key:M_KEY_TYPE);
PROCEDURE clear;
FUNCTION keySet:M_KEY_ARRAY_TYPE;
FUNCTION valueSet:VALUE_TYPE_ARRAY;
FUNCTION entrySet:KEY_VALUE_LIST;
FUNCTION size:longint;
end}
{$define someSetInterface:=
object
TYPE backingMapType=specialize M_MAP_TYPE<boolean>;
private
map:backingMapType;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE put(CONST e:M_KEY_TYPE);
PROCEDURE put(CONST e:M_KEY_ARRAY_TYPE);
PROCEDURE put(CONST e:M_SET_TYPE);
PROCEDURE drop(CONST e:M_KEY_TYPE);
PROCEDURE clear;
FUNCTION values:M_KEY_ARRAY_TYPE;
FUNCTION contains(CONST e:M_KEY_TYPE):boolean;
FUNCTION size:longint;
end}
{$define M_KEY_TYPE:=ansistring}
{$define M_MAP_TYPE:=G_stringKeyMap}
{$define M_SET_TYPE:=T_setOfString}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfString}
{$define M_HASH_FUNC:=hashOfAnsistring}
GENERIC G_stringKeyMap<VALUE_TYPE>=someKeyMapInterface;
T_setOfString=someSetInterface;
{$define M_KEY_TYPE:=pointer}
{$define M_MAP_TYPE:=G_pointerKeyMap}
{$define M_SET_TYPE:=T_setOfPointer}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfPointer}
{$define M_HASH_FUNC:=ptruint}
GENERIC G_pointerKeyMap<VALUE_TYPE>=someKeyMapInterface;
T_setOfPointer=someSetInterface;
{$define M_KEY_TYPE:=longint}
{$define M_MAP_TYPE:=G_longintKeyMap}
{$define M_SET_TYPE:=T_setOfLongint}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfLongint}
{$define M_HASH_FUNC:=}
GENERIC G_longintKeyMap<VALUE_TYPE>=someKeyMapInterface;
T_setOfLongint=someSetInterface;
{$undef someKeyMapInterface}
{$undef someSetInterface}
GENERIC G_safeVar<ENTRY_TYPE>=object
private VAR
v :ENTRY_TYPE;
saveCS:TRTLCriticalSection;
FUNCTION getValue:ENTRY_TYPE;
PROCEDURE setValue(CONST newValue:ENTRY_TYPE);
public
CONSTRUCTOR create(CONST intialValue:ENTRY_TYPE);
DESTRUCTOR destroy;
PROPERTY value:ENTRY_TYPE read getValue write setValue;
PROCEDURE lock;
PROCEDURE unlock;
end;
GENERIC G_safeArray<ENTRY_TYPE>=object
TYPE ENTRY_TYPE_ARRAY=array of ENTRY_TYPE;
private VAR
data :ENTRY_TYPE_ARRAY;
saveCS:TRTLCriticalSection;
FUNCTION getValue(index:longint):ENTRY_TYPE;
PROCEDURE setValue(index:longint; newValue:ENTRY_TYPE);
public
CONSTRUCTOR create();
DESTRUCTOR destroy;
PROCEDURE clear;
FUNCTION size:longint;
PROPERTY value[index:longint]:ENTRY_TYPE read getValue write setValue; default;
PROCEDURE append(CONST newValue:ENTRY_TYPE);
PROCEDURE appendAll(CONST newValue:ENTRY_TYPE_ARRAY);
PROCEDURE lock;
PROCEDURE unlock;
end;
GENERIC G_lazyVar<ENTRY_TYPE>=object
TYPE T_obtainer=FUNCTION():ENTRY_TYPE;
T_disposer=PROCEDURE(x:ENTRY_TYPE);
private
valueObtained:boolean;
obtainer:T_obtainer;
disposer:T_disposer;
v :ENTRY_TYPE;
saveCS:TRTLCriticalSection;
FUNCTION getValue:ENTRY_TYPE;
public
CONSTRUCTOR create(CONST o:T_obtainer; CONST d:T_disposer);
DESTRUCTOR destroy;
PROPERTY value:ENTRY_TYPE read getValue;
FUNCTION isObtained:boolean;
end;
GENERIC G_instanceRegistry<ENTRY_TYPE>=object
TYPE T_operationOnEntry=PROCEDURE(x:ENTRY_TYPE);
T_parameterizedOperationOnEntry=PROCEDURE(x:ENTRY_TYPE;p:pointer);
T_attributeOnEntry=FUNCTION(x:ENTRY_TYPE):boolean;
T_parameterizedAttributeOnEntry=FUNCTION(x:ENTRY_TYPE;p:pointer):boolean;
ARRAY_OF_ENTRY_TYPE=array of ENTRY_TYPE;
private
cs:TRTLCriticalSection;
registered:ARRAY_OF_ENTRY_TYPE;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE forEach (CONST op:T_operationOnEntry);
PROCEDURE forEach (CONST op:T_parameterizedOperationOnEntry; p:pointer);
FUNCTION anyMatch (CONST at:T_attributeOnEntry):boolean;
FUNCTION anyMatch (CONST at:T_parameterizedAttributeOnEntry; p:pointer):boolean;
FUNCTION filter (CONST at:T_attributeOnEntry):ARRAY_OF_ENTRY_TYPE;
FUNCTION filter (CONST at:T_parameterizedAttributeOnEntry; p:pointer):ARRAY_OF_ENTRY_TYPE;
PROCEDURE onCreation (CONST x:ENTRY_TYPE);
PROCEDURE onDestruction(CONST x:ENTRY_TYPE);
PROCEDURE enterCs;
PROCEDURE leaveCs;
FUNCTION registeredCount:longint;
end;
GENERIC G_queue<ENTRY_TYPE>=object
TYPE ELEMENT_ARRAY=array of ENTRY_TYPE;
EQUALS_METHOD=FUNCTION(CONST x,y:ENTRY_TYPE):boolean;
private
CONST MINIMUM_DATA_SIZE=16;
VAR firstIdx,lastIdx:longint;
data:ELEMENT_ARRAY;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE append(CONST newValue:ENTRY_TYPE);
FUNCTION next:ENTRY_TYPE;
FUNCTION hasNext:boolean;
FUNCTION getAll:ELEMENT_ARRAY;
FUNCTION fill:longint;
FUNCTION isQueued(CONST value:ENTRY_TYPE; CONST equals:EQUALS_METHOD):boolean;
end;
GENERIC G_threadsafeQueue<ENTRY_TYPE>=object
TYPE T_innerQueue=specialize G_queue<ENTRY_TYPE>;
TYPE ELEMENT_ARRAY=array of ENTRY_TYPE;
private
queueCs:TRTLCriticalSection;
queue:T_innerQueue;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE append(CONST newValue:ENTRY_TYPE);
FUNCTION canGetNext(OUT v:ENTRY_TYPE):boolean;
FUNCTION hasNext:boolean;
FUNCTION getAll:ELEMENT_ARRAY;
FUNCTION isQueued(CONST value:ENTRY_TYPE; CONST equals:T_innerQueue.EQUALS_METHOD):boolean;
PROCEDURE appendIfNew(CONST newValue:ENTRY_TYPE; CONST equals:T_innerQueue.EQUALS_METHOD);
end;
FUNCTION hashOfAnsiString(CONST x:ansistring):PtrUInt; {$ifndef debugMode} inline; {$endif}
IMPLEMENTATION
{$define arrayFunctionImpl:=
FUNCTION arrEquals(CONST x,y:M_ARRAY_TYPE):boolean;
VAR i:longint;
begin
if length(x)<>length(y) then exit(false);
for i:=0 to length(x)-1 do if x[i]<>y[i] then exit(false);
result:=true;
end;
PROCEDURE prepend(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
VAR i:longint;
begin
setLength(x,length(x)+1);
for i:=length(x)-1 downto 1 do x[i]:=x[i-1];
x[0]:=y;
end;
PROCEDURE append(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
begin
setLength(x,length(x)+1);
x[length(x)-1]:=y;
end;
PROCEDURE append(VAR x:M_ARRAY_TYPE; CONST y:M_ARRAY_TYPE);
VAR i,i0:longint;
begin
i0:=length(x);
setLength(x,i0+length(y));
for i:=0 to length(y)-1 do x[i+i0]:=y[i];
end;
FUNCTION arrContains(CONST x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE):boolean;
VAR i:longint;
begin
for i:=0 to length(x)-1 do if x[i]=y then exit(true);
result:=false;
end;
PROCEDURE appendIfNew(VAR x:M_ARRAY_TYPE; CONST y:M_VALUE_TYPE);
VAR i:longint;
begin
i:=0;
while (i<length(x)) and (x[i]<>y) do inc(i);
if i>=length(x) then begin
setLength(x,length(x)+1);
x[length(x)-1]:=y;
end;
end;
PROCEDURE dropFirst(VAR x:M_ARRAY_TYPE; CONST dropCount:longint);
VAR i,dc:longint;
begin
if dropCount<=0 then exit;
if dropCount>length(x) then dc:=length(x) else dc:=dropCount;
for i:=0 to length(x)-dc-1 do x[i]:=x[i+dc];
setLength(x,length(x)-dc);
end;
PROCEDURE dropValues(VAR x:M_ARRAY_TYPE; CONST toDrop:M_VALUE_TYPE);
VAR i,j:longint;
begin
j:=0;
for i:=0 to length(x)-1 do if x[i]<>toDrop then begin
x[j]:=x[i]; inc(j);
end;
setLength(x,j);
end;
PROCEDURE sort(VAR entry:M_ARRAY_TYPE);
VAR scale :longint;
i,j0,j1,k:longint;
temp :M_ARRAY_TYPE=();
begin
scale:=1;
setLength(temp,length(entry));
while scale<length(temp) do begin
//merge lists of size [scale] to lists of size [scale+scale]:---------------
i:=0;
while i<length(temp) do begin
j0:=i;
j1:=i+scale;
k :=i;
while (j0<i+scale) and (j1<i+scale+scale) and (j1<length(entry)) do begin
if entry[j0]<=entry[j1]
then begin temp[k]:=entry[j0]; inc(k); inc(j0); end
else begin temp[k]:=entry[j1]; inc(k); inc(j1); end;
end;
while (j0<i+scale) and (j0<length(entry)) do begin temp[k]:=entry[j0]; inc(k); inc(j0); end;
while (j1<i+scale+scale) and (j1<length(entry)) do begin temp[k]:=entry[j1]; inc(k); inc(j1); end;
inc(i,scale+scale);
end;
//---------------:merge lists of size [scale] to lists of size [scale+scale]
inc(scale,scale);
if (scale<length(temp)) then begin
//The following is equivalent to the above with swapped roles of "list" and "temp".
//while making the code a little more complicated it avoids unnecessary copys.
//merge lists of size [scale] to lists of size [scale+scale]:---------------
i:=0;
while i<length(temp) do begin
j0:=i;
j1:=i+scale;
k :=i;
while (j0<i+scale) and (j1<i+scale+scale) and (j1<length(temp)) do begin
if temp[j0]<=temp[j1]
then begin entry[k]:=temp[j0]; inc(k); inc(j0); end
else begin entry[k]:=temp[j1]; inc(k); inc(j1); end;
end;
while (j0<i+scale) and (j0<length(temp)) do begin entry[k]:=temp[j0]; inc(k); inc(j0); end;
while (j1<i+scale+scale) and (j1<length(temp)) do begin entry[k]:=temp[j1]; inc(k); inc(j1); end;
inc(i,scale+scale);
end;
//---------------:merge lists of size [scale] to lists of size [scale+scale]
inc(scale,scale);
end else for k:=0 to length(temp)-1 do entry[k]:=temp[k];
end;
end;
PROCEDURE sortUnique(VAR entry:M_ARRAY_TYPE);
VAR i,j:longint;
begin
if length(entry)=0 then exit;
sort(entry);
j:=1;
for i:=1 to length(entry)-1 do if entry[i]<>entry[i-1] then begin
entry[j]:=entry[i]; inc(j);
end;
setLength(entry,j);
end}
{$define arrayOpImpl:=
OPERATOR :=(x:M_VALUE_TYPE):M_ARRAY_TYPE;
begin
setLength(result,1);
result[0]:=x;
end}
{$define M_ARRAY_TYPE:=T_arrayOfString } {$define M_VALUE_TYPE:=ansistring} arrayFunctionImpl; arrayOpImpl;
{$define M_ARRAY_TYPE:=T_arrayOfPointer} {$define M_VALUE_TYPE:=pointer } arrayFunctionImpl;
{$define M_ARRAY_TYPE:=T_arrayOfDouble } {$define M_VALUE_TYPE:=double } arrayFunctionImpl; arrayOpImpl;
{$define M_ARRAY_TYPE:=T_arrayOfLongint} {$define M_VALUE_TYPE:=longint } arrayFunctionImpl; arrayOpImpl;
{$define M_ARRAY_TYPE:=T_arrayOfInt64 } {$define M_VALUE_TYPE:=int64 } arrayFunctionImpl; arrayOpImpl;
{$undef arrayFunctionImpl}
{$undef arrayOpImpl}
FUNCTION hashOfAnsiString(CONST x:ansistring):PtrUInt; {$ifndef debugMode} inline; {$endif}
VAR i:longint;
begin
{$Q-}{$R-}
result:=length(x);
for i:=1 to length(x) do result:=result*31+ord(x[i]);
{$Q+}{$R+}
end;
CONSTRUCTOR G_threadsafeQueue.create;
begin
initCriticalSection(queueCs);
queue.create;
end;
DESTRUCTOR G_threadsafeQueue.destroy;
begin
enterCriticalSection(queueCs);
queue.destroy;
leaveCriticalSection(queueCs);
doneCriticalSection(queueCs);
end;
PROCEDURE G_threadsafeQueue.append(CONST newValue: ENTRY_TYPE);
begin
enterCriticalSection(queueCs);
queue.append(newValue);
leaveCriticalSection(queueCs);
end;
FUNCTION G_threadsafeQueue.canGetNext(OUT v: ENTRY_TYPE): boolean;
begin
enterCriticalSection(queueCs);
result:=queue.hasNext;
if result then v:=queue.next;
leaveCriticalSection(queueCs);
end;
FUNCTION G_threadsafeQueue.hasNext: boolean;
begin
enterCriticalSection(queueCs);
result:=queue.hasNext;
leaveCriticalSection(queueCs);
end;
FUNCTION G_threadsafeQueue.getAll: ELEMENT_ARRAY;
begin
enterCriticalSection(queueCs);
result:=queue.getAll;
leaveCriticalSection(queueCs);
end;
FUNCTION G_threadsafeQueue.isQueued(CONST value:ENTRY_TYPE; CONST equals:T_innerQueue.EQUALS_METHOD):boolean;
begin
enterCriticalSection(queueCs);
result:=queue.isQueued(value,equals);
leaveCriticalSection(queueCs);
end;
PROCEDURE G_threadsafeQueue.appendIfNew(CONST newValue:ENTRY_TYPE; CONST equals:T_innerQueue.EQUALS_METHOD);
begin
enterCriticalSection(queueCs);
if not(queue.isQueued(newValue,equals)) then queue.append(newValue);
leaveCriticalSection(queueCs);
end;
CONSTRUCTOR G_instanceRegistry.create;
begin
initCriticalSection(cs);
setLength(registered,0);
end;
DESTRUCTOR G_instanceRegistry.destroy;
begin
enterCriticalSection(cs);
setLength(registered,0);
leaveCriticalSection(cs);
doneCriticalSection(cs);
end;
PROCEDURE G_instanceRegistry.forEach(CONST op: T_operationOnEntry);
VAR regCopy:array of ENTRY_TYPE=();
i:longint;
x:ENTRY_TYPE;
begin
enterCriticalSection(cs);
try
setLength(regCopy,length(registered));
for i:=0 to length(registered)-1 do regCopy[i]:=registered[i];
finally
leaveCriticalSection(cs);
end;
for x in regCopy do op(x);
end;
PROCEDURE G_instanceRegistry.forEach(CONST op:T_parameterizedOperationOnEntry; p:pointer);
VAR regCopy:array of ENTRY_TYPE=();
i:longint;
x:ENTRY_TYPE;
begin
enterCriticalSection(cs);
try
setLength(regCopy,length(registered));
for i:=0 to length(registered)-1 do regCopy[i]:=registered[i];
finally
leaveCriticalSection(cs);
end;
for x in regCopy do op(x,p);
end;
FUNCTION G_instanceRegistry.anyMatch(CONST at:T_attributeOnEntry):boolean;
VAR regCopy:array of ENTRY_TYPE=();
i:longint;
x:ENTRY_TYPE;
begin
enterCriticalSection(cs);
try
setLength(regCopy,length(registered));
for i:=0 to length(registered)-1 do regCopy[i]:=registered[i];
finally
leaveCriticalSection(cs);
end;
result:=false;
for x in regCopy do if at(x) then result:=true;
end;
FUNCTION G_instanceRegistry.anyMatch(CONST at:T_parameterizedAttributeOnEntry; p:pointer):boolean;
VAR regCopy:array of ENTRY_TYPE=();
i:longint;
x:ENTRY_TYPE;
begin
enterCriticalSection(cs);
try
setLength(regCopy,length(registered));
for i:=0 to length(registered)-1 do regCopy[i]:=registered[i];
finally
leaveCriticalSection(cs);
end;
result:=false;
for x in regCopy do if at(x,p) then result:=true;
end;
FUNCTION G_instanceRegistry.filter(CONST at:T_attributeOnEntry):ARRAY_OF_ENTRY_TYPE;
VAR i:longint;
begin
initialize(result);
setLength(result,0);
enterCriticalSection(cs);
try
for i:=0 to length(registered)-1 do if at(registered[i]) then begin
setLength(result,length(result)+1);
result[length(result)-1]:=registered[i];
end;
finally
leaveCriticalSection(cs);
end;
end;
FUNCTION G_instanceRegistry.filter(CONST at:T_parameterizedAttributeOnEntry; p:pointer):ARRAY_OF_ENTRY_TYPE;
VAR i:longint;
begin
initialize(result);
setLength(result,0);
enterCriticalSection(cs);
try
for i:=0 to length(registered)-1 do if at(registered[i],p) then begin
setLength(result,length(result)+1);
result[length(result)-1]:=registered[i];
end;
finally
leaveCriticalSection(cs);
end;
end;
PROCEDURE G_instanceRegistry.onCreation(CONST x: ENTRY_TYPE);
VAR y:ENTRY_TYPE;
begin
enterCriticalSection(cs);
for y in registered do if y=x then begin
leaveCriticalSection(cs);
exit;
end;
try
setLength(registered,length(registered)+1);
registered[length(registered)-1]:=x;
finally
leaveCriticalSection(cs);
end;
end;
PROCEDURE G_instanceRegistry.onDestruction(CONST x: ENTRY_TYPE);
VAR i,j:longint;
begin
enterCriticalSection(cs);
try
j:=0;
for i:=0 to length(registered)-1 do if registered[i]<>x then begin
registered[j]:=registered[i];
inc(j);
end;
setLength(registered,j);
finally
leaveCriticalSection(cs);
end;
end;
PROCEDURE G_instanceRegistry.enterCs;
begin
enterCriticalSection(cs);
end;
PROCEDURE G_instanceRegistry.leaveCs;
begin
leaveCriticalSection(cs);
end;
FUNCTION G_instanceRegistry.registeredCount:longint;
begin
enterCriticalSection(cs);
try
result:=length(registered);
finally
leaveCriticalSection(cs);
end;
end;
CONSTRUCTOR G_safeArray.create;
begin
system.initCriticalSection(saveCS);
clear;
end;
FUNCTION G_safeArray.getValue(index: longint): ENTRY_TYPE;
begin
system.enterCriticalSection(saveCS);
try
result:=data[index];
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeArray.setValue(index: longint; newValue: ENTRY_TYPE);
begin
system.enterCriticalSection(saveCS);
try
if index=length(data) then append(newValue)
else data[index]:=newValue;
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeArray.clear;
begin
system.enterCriticalSection(saveCS);
try
setLength(data,0);
finally
system.leaveCriticalSection(saveCS);
end;
end;
FUNCTION G_safeArray.size: longint;
begin
system.enterCriticalSection(saveCS);
try
result:=length(data);
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeArray.append(CONST newValue: ENTRY_TYPE);
begin
system.enterCriticalSection(saveCS);
try
setLength(data,length(data)+1);
data[length(data)-1]:=newValue;
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeArray.appendAll(CONST newValue: ENTRY_TYPE_ARRAY);
VAR i,i0:longint;
begin
system.enterCriticalSection(saveCS);
try
i0:=length(data);
setLength(data,i0+length(newValue));
for i:=0 to length(newValue)-1 do data[i0+i]:=newValue[i];
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeArray.lock;
begin
system.enterCriticalSection(saveCS);
end;
PROCEDURE G_safeArray.unlock;
begin
system.leaveCriticalSection(saveCS);
end;
DESTRUCTOR G_safeArray.destroy;
begin
clear;
system.doneCriticalSection(saveCS);
end;
FUNCTION G_lazyVar.getValue: ENTRY_TYPE;
begin
enterCriticalSection(saveCS);
try
if not(valueObtained) then begin
v:=obtainer();
valueObtained:=true;
end;
result:=v;
finally
leaveCriticalSection(saveCS);
end;
end;
CONSTRUCTOR G_lazyVar.create(CONST o:T_obtainer; CONST d:T_disposer);
begin
obtainer:=o;
disposer:=d;
valueObtained:=false;
initCriticalSection(saveCS);
end;
DESTRUCTOR G_lazyVar.destroy;
begin
if valueObtained and (disposer<>nil) then disposer(v);
doneCriticalSection(saveCS);
end;
FUNCTION G_lazyVar.isObtained:boolean;
begin
enterCriticalSection(saveCS);
try
result:=valueObtained;
finally
leaveCriticalSection(saveCS);
end;
end;
{ G_safeVar }
CONSTRUCTOR G_safeVar.create(CONST intialValue: ENTRY_TYPE);
begin
system.initCriticalSection(saveCS);
v:=intialValue;
end;
FUNCTION G_safeVar.getValue: ENTRY_TYPE;
begin
system.enterCriticalSection(saveCS);
try
result:=v;
finally
system.leaveCriticalSection(saveCS);
end;
end;
PROCEDURE G_safeVar.setValue(CONST newValue: ENTRY_TYPE);
begin
system.enterCriticalSection(saveCS);
try
v:=newValue;
finally
system.leaveCriticalSection(saveCS);
end;
end;
DESTRUCTOR G_safeVar.destroy;
begin
system.doneCriticalSection(saveCS);
end;
PROCEDURE G_safeVar.lock;
begin
system.enterCriticalSection(saveCS);
end;
PROCEDURE G_safeVar.unlock;
begin
system.leaveCriticalSection(saveCS);
end;
{$define someKeyMapImplementation:=
PROCEDURE M_MAP_TYPE.rehash(CONST grow: boolean);
VAR i,i0,j,k,c0,c1:longint;
temp:array of KEY_VALUE_PAIR;
begin
if grow then begin
i0:=length(bucket);
setLength(bucket,i0+i0);
for i:=0 to i0-1 do begin
temp:=bucket[i];
setLength(bucket[i+i0],length(bucket[i]));
c0:=0;
c1:=0;
for j:=0 to length(temp)-1 do begin
k:=M_HASH_FUNC(temp[j].key) and (length(bucket)-1);
if k=i then begin
bucket[i][c0]:=temp[j];
inc(c0);
end else begin
bucket[k][c1]:=temp[j];
inc(c1);
end;
end;
setLength(bucket[i ],c0);
setLength(bucket[i+i0],c1);
setLength(temp,0);
end;
end else if length(bucket)>1 then begin
i0:=length(bucket) shr 1;
for i:=0 to i0-1 do
for j:=0 to length(bucket[i0+i])-1 do begin
setLength(bucket[i],length(bucket[i])+1);
bucket[i][length(bucket[i])-1]:=bucket[i0+i][j];
end;
setLength(bucket,i0);
end;
end;
CONSTRUCTOR M_MAP_TYPE.create(CONST rebalanceFactor: double; CONST disposer_:VALUE_DISPOSER=nil);
begin
rebalanceFac:=rebalanceFactor;
setLength(bucket,1);
setLength(bucket[0],0);
entryCount:=0;
disposer:=disposer_;
end;
PROCEDURE M_MAP_TYPE.disposeValue(VAR v:VALUE_TYPE);
begin
if disposer<>nil then disposer(v);
end;
PROCEDURE M_MAP_TYPE.clear;
VAR i,j:longint;
begin
for i:=0 to length(bucket)-1 do begin
for j:=0 to length(bucket[i])-1 do disposeValue(bucket[i,j].value);
setLength(bucket[i],0);
end;
setLength(bucket,1);
entryCount:=0;
end;
CONSTRUCTOR M_MAP_TYPE.create(CONST disposer_:VALUE_DISPOSER=nil);
begin
create(4,disposer_);
end;
CONSTRUCTOR M_MAP_TYPE.createClone(VAR map:MY_TYPE);
VAR i,j:longint;
begin
create(map.rebalanceFac,map.disposer);
if disposer<>nil then raise Exception.create('You must not clone maps with an associated disposer');
setLength(bucket,length(map.bucket));
for i:=0 to length(bucket)-1 do begin
setLength(bucket[i],length(map.bucket[i]));
for j:=0 to length(bucket[i])-1 do bucket[i,j]:=map.bucket[i,j];
end;
entryCount:=map.entryCount;
end;
PROCEDURE M_MAP_TYPE.overrideDisposer(CONST newDisposer:VALUE_DISPOSER);
begin
disposer:=newDisposer;
end;
DESTRUCTOR M_MAP_TYPE.destroy;
begin
clear;
setLength(bucket,0);
end;
FUNCTION M_MAP_TYPE.containsKey(CONST key: M_KEY_TYPE; OUT value: VALUE_TYPE): boolean;
VAR i,j:longint;
begin
i:=M_HASH_FUNC(key) and (length(bucket)-1);
j:=0;
while (j<length(bucket[i])) and (bucket[i][j].key<>key) do inc(j);
if (j<length(bucket[i])) then begin
value:=bucket[i][j].value;
result:=true;
end else result:=false;
end;
FUNCTION M_MAP_TYPE.containsKey(CONST key:M_KEY_TYPE):boolean;
VAR i,j:longint;
begin
i:=M_HASH_FUNC(key) and (length(bucket)-1);
j:=0;
while (j<length(bucket[i])) and (bucket[i][j].key<>key) do inc(j);
result:=(j<length(bucket[i]));
end;
FUNCTION M_MAP_TYPE.get(CONST key: M_KEY_TYPE): VALUE_TYPE;
begin
containsKey(key,result);
end;
PROCEDURE M_MAP_TYPE.put(CONST key: M_KEY_TYPE; CONST value: VALUE_TYPE);
VAR i,j:longint;
begin
i:=M_HASH_FUNC(key) and (length(bucket)-1);
j:=0;
while (j<length(bucket[i])) and (bucket[i][j].key<>key) do inc(j);
if j>=length(bucket[i]) then begin
setLength(bucket[i],j+1);
bucket[i][j].key:=key;
bucket[i][j].value:=value;
inc(entryCount);
if entryCount>length(bucket)*rebalanceFac then rehash(true);
end else begin
disposeValue(bucket[i][j].value);
bucket[i][j].value:=value;
end;
end;
PROCEDURE M_MAP_TYPE.putAll(CONST entries:KEY_VALUE_LIST);
VAR i:longint;
begin
for i:=0 to length(entries)-1 do put(entries[i].key,entries[i].value);
end;
PROCEDURE M_MAP_TYPE.dropKey(CONST key: M_KEY_TYPE);
VAR i,j:longint;
begin
i:=M_HASH_FUNC(key) and (length(bucket)-1);
j:=0;
while (j<length(bucket[i])) and (bucket[i][j].key<>key) do inc(j);
if j<length(bucket[i]) then begin
disposeValue(bucket[i][j].value);
while j<length(bucket[i])-1 do begin
bucket[i][j]:=bucket[i][j+1];
inc(j);
end;
setLength(bucket[i],length(bucket[i])-1);
dec(entryCount);
if entryCount<0.4*length(bucket)*rebalanceFac then rehash(false);
end;
end;
FUNCTION M_MAP_TYPE.keySet: M_KEY_ARRAY_TYPE;
VAR k,i,j:longint;
begin
setLength(result,entryCount);
k:=0;
for i:=0 to length(bucket)-1 do
for j:=0 to length(bucket[i])-1 do begin
result[k]:=bucket[i][j].key;
inc(k);
end;
end;
FUNCTION M_MAP_TYPE.valueSet: VALUE_TYPE_ARRAY;
VAR k,i,j:longint;
begin
setLength(result,entryCount);
k:=0;
for i:=0 to length(bucket)-1 do
for j:=0 to length(bucket[i])-1 do begin
result[k]:=bucket[i][j].value;
inc(k);
end;
end;
FUNCTION M_MAP_TYPE.entrySet: KEY_VALUE_LIST;
VAR k,i,j:longint;
begin
setLength(result,entryCount);
k:=0;
for i:=0 to length(bucket)-1 do
for j:=0 to length(bucket[i])-1 do begin
result[k]:=bucket[i][j];
inc(k);
end;
end;
FUNCTION M_MAP_TYPE.size: longint;
begin
result:=entryCount;
end}
{$define someSetImplementation:=
CONSTRUCTOR M_SET_TYPE.create; begin map.create; end;
DESTRUCTOR M_SET_TYPE.destroy; begin map.destroy; end;
PROCEDURE M_SET_TYPE.put(CONST e:M_KEY_TYPE); begin map.put(e,true); end;
PROCEDURE M_SET_TYPE.put(CONST e:M_KEY_ARRAY_TYPE); VAR k:M_KEY_TYPE; begin for k in e do map.put(k,true); end;
PROCEDURE M_SET_TYPE.put(CONST e:M_SET_TYPE); VAR k:M_KEY_TYPE; begin for k in e.map.keySet do map.put(k,true); end;
PROCEDURE M_SET_TYPE.drop(CONST e:M_KEY_TYPE); begin map.dropKey(e); end;
PROCEDURE M_SET_TYPE.clear; begin map.clear; end;
FUNCTION M_SET_TYPE.values:M_KEY_ARRAY_TYPE; begin result:=map.keySet; sort(result); end;
FUNCTION M_SET_TYPE.contains(CONST e:M_KEY_TYPE):boolean; begin result:=map.containsKey(e); end;
FUNCTION M_SET_TYPE.size:longint; begin result:=map.size; end}
{$define M_KEY_TYPE:=ansistring}
{$define M_MAP_TYPE:=G_stringKeyMap}
{$define M_SET_TYPE:=T_setOfString}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfString}
{$define M_HASH_FUNC:=hashOfAnsistring}
someKeyMapImplementation;
someSetImplementation;
{$define M_KEY_TYPE:=pointer}
{$define M_MAP_TYPE:=G_pointerKeyMap}
{$define M_SET_TYPE:=T_setOfPointer}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfPointer}
{$define M_HASH_FUNC:=ptruint}
someKeyMapImplementation;
someSetImplementation;
{$define M_KEY_TYPE:=longint}
{$define M_MAP_TYPE:=G_longintKeyMap}
{$define M_SET_TYPE:=T_setOfLongint}
{$define M_KEY_ARRAY_TYPE:=T_arrayOfLongint}
{$define M_HASH_FUNC:=}
someKeyMapImplementation;
someSetImplementation;
CONSTRUCTOR G_queue.create;
begin
setLength(data,MINIMUM_DATA_SIZE);
firstIdx:=0;
lastIdx:=-1;
end;
DESTRUCTOR G_queue.destroy;
begin
setLength(data,0);
firstIdx:=0;
lastIdx:=-1;
end;
PROCEDURE G_queue.append(CONST newValue:ENTRY_TYPE);
begin
inc(lastIdx);
if (lastIdx>=length(data)) then setLength(data,length(data)*2);
data[lastIdx]:=newValue;
end;
FUNCTION G_queue.next:ENTRY_TYPE;
VAR i:longint;
begin
if firstIdx>lastIdx then begin
{$ifdef debugMode}
raise Exception.create('THIS MUST NOT BE CALLED WHEN THE QUEUE IS EMPTY!');
{$endif}
initialize(result);
exit;
end;
result:=data[firstIdx];
inc(firstIdx);
if (firstIdx+firstIdx>length(data)) then begin
for i:=firstIdx to lastIdx do data[i-firstIdx]:=data[i];
dec(lastIdx,firstIdx);
firstIdx:=0;
i:=lastIdx+lastIdx;
if i<MINIMUM_DATA_SIZE then i:=MINIMUM_DATA_SIZE;
if (length(data)>i) then setLength(data,i);
end;
end;
FUNCTION G_queue.hasNext:boolean;
begin
result:=firstIdx<=lastIdx;
end;
FUNCTION G_queue.getAll:ELEMENT_ARRAY;
VAR i:longint;
begin
if firstIdx>lastIdx then begin
setLength(result,0);
exit(result);
end;
setLength(result,lastIdx-firstIdx+1);
for i:=0 to length(result)-1 do result[i]:=data[firstIdx+i];
i:=length(result) shr 1;
if i<MINIMUM_DATA_SIZE then i:=MINIMUM_DATA_SIZE;
setLength(data,i);
firstIdx:=0;
lastIdx:=-1;
end;
FUNCTION G_queue.fill:longint;
begin
result:=lastIdx-firstIdx+1;
end;
FUNCTION G_queue.isQueued(CONST value:ENTRY_TYPE; CONST equals:EQUALS_METHOD):boolean;
VAR i:longint;
begin
result:=false;
for i:=firstIdx to lastIdx do if equals(data[i],value) then exit(true);
end;
end.
|
unit Kafka.FMX.Form.Consumer;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.Generics.Collections,System.Rtti,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types,
FMX.Edit, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.Layouts,
FMX.Grid.Style, FMX.Grid,
Kafka.Lib,
Kafka.Factory,
Kafka.Interfaces,
Kafka.Helper,
Kafka.Types,
Kafka.FMX.Helper;
type
TKafkaMsg = record
Key: TBytes;
Data: TBytes;
Partition: Integer;
end;
TfrmConsume = class(TForm)
layConsumeControl: TLayout;
btnStart: TButton;
btnStop: TButton;
Layout1: TLayout;
Layout2: TLayout;
Label2: TLabel;
edtTopic: TEdit;
tmrUpdate: TTimer;
lblStatus: TLabel;
Layout3: TLayout;
layKafkaConfiguration: TLayout;
Label1: TLabel;
memKafkaConfig: TMemo;
Layout5: TLayout;
Label3: TLabel;
memTopicConfig: TMemo;
grdMessages: TGrid;
colPartition: TStringColumn;
colKey: TStringColumn;
colPayload: TStringColumn;
Layout4: TLayout;
Label4: TLabel;
edtPartitions: TEdit;
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure layConsumeControlResize(Sender: TObject);
procedure tmrUpdateTimer(Sender: TObject);
procedure grdMessagesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
procedure grdMessagesResize(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FKafkaConsumer: IKafkaConsumer;
FKafkaServers: String;
FStringEncoding: TEncoding;
FMsgs: TList<TKafkaMsg>;
procedure UpdateStatus;
procedure Start;
procedure Stop;
procedure Log(const Text: String);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute(const KafkaServers: String);
end;
var
frmConsume: TfrmConsume;
implementation
{$R *.fmx}
procedure TfrmConsume.btnStartClick(Sender: TObject);
begin
Start;
end;
procedure TfrmConsume.btnStopClick(Sender: TObject);
begin
Stop;
end;
constructor TfrmConsume.Create(AOwner: TComponent);
begin
inherited;
FStringEncoding := TEncoding.UTF8;
FMsgs := TList<TKafkaMsg>.Create;
UpdateStatus;
end;
destructor TfrmConsume.Destroy;
begin
FreeAndNil(FMsgs);
inherited;
end;
procedure TfrmConsume.Execute(const KafkaServers: String);
begin
FKafkaServers := KafkaServers;
memKafkaConfig.Lines.Add('bootstrap.servers=' + KafkaServers);
Show;
end;
procedure TfrmConsume.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
end;
procedure TfrmConsume.grdMessagesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
begin
case ACol of
0: Value := FMsgs[ARow].Partition.ToString;
1: Value := FStringEncoding.GetString(FMsgs[ARow].Key);
2: Value := FStringEncoding.GetString(FMsgs[ARow].Data);
end;
end;
procedure TfrmConsume.grdMessagesResize(Sender: TObject);
begin
// StringColumn1.Width := grdMessages.Width - 22;
end;
procedure TfrmConsume.layConsumeControlResize(Sender: TObject);
begin
btnStart.Width := (layConsumeControl.Width - 20) / 2;
layKafkaConfiguration.Width := btnStart.Width;
end;
procedure TfrmConsume.Log(const Text: String);
begin
end;
procedure TfrmConsume.Start;
var
KafkaNames, KafkaValues, TopicNames, TopicValues: TArray<String>;
begin
if FKafkaConsumer = nil then
begin
TKafkaUtils.StringsToConfigArrays(memKafkaConfig.Lines, KafkaNames, KafkaValues);
TKafkaUtils.StringsToConfigArrays(memTopicConfig.Lines, TopicNames, TopicValues);
FKafkaConsumer := TKafkaFactory.NewConsumer(
KafkaNames,
KafkaValues,
TopicNames,
TopicValues,
FKafkaServers,
[edtTopic.Text],
TKafkaUtils.StringsToIntegerArray(edtPartitions.Text),
procedure(const Msg: prd_kafka_message_t)
begin
TThread.Synchronize(
TThread.Current,
procedure
var
MsgRec: TKafkaMsg;
begin
MsgRec.Key := TKafkaUtils.PointerToBytes(Msg.key, Msg.key_len);
MsgRec.Partition := Msg.partition;
if TKafkaHelper.IsKafkaError(Msg.err) then
begin
MsgRec.Data := TEncoding.ASCII.GetBytes('ERROR - ' + Integer(Msg.err).ToString);
end
else
begin
MsgRec.Data := TKafkaUtils.PointerToBytes(Msg.payload, Msg.len);
end;
FMsgs.Add(MsgRec);
while FMsgs.Count > TFMXHelper.MAX_LOG_LINES do
begin
FMsgs.Delete(0);
end;
end);
end);
end;
end;
procedure TfrmConsume.Stop;
begin
FKafkaConsumer := nil;
end;
procedure TfrmConsume.tmrUpdateTimer(Sender: TObject);
begin
UpdateStatus;
end;
procedure TfrmConsume.UpdateStatus;
var
ConsumedStr: String;
begin
if FKafkaConsumer = nil then
begin
ConsumedStr := 'Idle';
end
else
begin
ConsumedStr := FKafkaConsumer.ConsumedCount.ToString;
end;
lblStatus.Text := format('Consumed: %s', [ConsumedStr]);
btnStart.Enabled := FKafkaConsumer = nil;
btnStop.Enabled := FKafkaConsumer <> nil;
memKafkaConfig.Enabled := FKafkaConsumer = nil;
memTopicConfig.Enabled := FKafkaConsumer = nil;
edtTopic.Enabled := FKafkaConsumer = nil;
edtPartitions.Enabled := FKafkaConsumer = nil;
TFMXHelper.SetGridRowCount(grdMessages, FMsgs.Count);
end;
end.
|
unit NvConst;
interface
const
INIT_KEY = '\Software\NetUtils\NetView\';
NN_KEY = '\CLSID\{208D2C60-3AEA-1069-A2D7-08002B30309D}\shell\Scan with NetView\';
MRU_KEY = 'FindResourceMRU\';
SDefExt = '.txt';
SFilter = 'Text Documents (*' + SDefExt + ')|*' + SDefExt + '|';
SPosition = 'Position';
SWindowState = 'WindowState';
SResourceType = 'Resource Type';
SShowToolBar = 'ShowToolBar';
SShowResourceBar = 'ShowResourceBar';
SShowStatusBar = 'ShowStatusBar';
SShowGridLines = 'ShowGridLines';
SShowHotTrack = 'ShowHotTrack';
SShowRowSelect = 'ShowRowSelect';
SMRUList = 'MRUList';
NetResNames: array [0..2] of string[15] = (
'Computers',
'Shared folders',
'Shared printers');
ColumnNames: array [0..4] of string[11] = (
'Name',
'Group',
'Comment',
'IP Address',
'MAC Address');
resourcestring
SWinSockErr = 'Could not initialize Winsock.';
SProblemWithNA = 'Problem with network adapter.';
SResetLanaErr = 'Reset Lana error.';
SScanWithNetView = 'Scan with Net&View';
SUpdating = 'Updating...';
SLocalInet = 'Local intranet';
SStatusText = '%d %s found';
SResNotFound = 'Resource ''%s'' not found.';
SPingDlgCaption = 'Ping %s';
SInitErr = 'Error: Could not initialize icmp.dll.';
SPinging = 'Pinging %s [%s] with %d bytes of data:'#13#10;
SReqTimedOut = 'Request timed out.';
SPacketTooBig = 'Packet needs to be fragmented.';
SErrorCode = 'Error: %d.';
SReply = 'Reply from %s: bytes=%d time%sms TTL=%d';
SMsgDlgCaption = 'Message from %s';
implementation
end.
|
unit About;
interface
uses Windows, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, SysUtils;
type
TAboutBox = class(TForm)
OKButton: TButton;
Panel1: TPanel;
ProgramIcon: TImage;
ProgramName: TLabel;
Copyright: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AboutBox: TAboutBox;
procedure ShowAboutBox;
implementation
{$R *.dfm}
const
SCopyright = 'Copyright © 1996, 1998 Borland International';
procedure ShowAboutBox;
begin
with TAboutBox.Create(Application) do
try
ShowModal;
finally
Free;
end;
end;
procedure TAboutBox.FormCreate(Sender: TObject);
begin
Caption := Format('About %s', [Application.Title]);
ProgramIcon.Picture.Assign(Application.Icon);
ProgramName.Caption := Application.Title;
CopyRight.Caption := SCopyRight;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Fallback;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport,
Support;
type
TFallbackSMARTSupport = class(TSMARTSupport)
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(const SMARTList: TSMARTValueList): Boolean;
override;
end;
implementation
{ TFallbackSMARTSupport }
function TFallbackSMARTSupport.GetTypeName: String;
begin
result := 'Smart';
end;
function TFallbackSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := true;
end;
function TFallbackSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TFallbackSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result := not CheckIsSSDInCommonWay(IdentifyDevice);
end;
function TFallbackSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TFallbackSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
begin
FillChar(result, SizeOf(result), 0);
end;
end.
|
{$i deltics.inc}
unit Test.TypedExchanges;
interface
uses
Deltics.Smoketest,
Deltics.StringTypes;
type
TTypedExchangeTests = class(TTest)
private
procedure TestExchangeBytesWithData(a, b: Byte);
procedure TestExchangeWordsWithData(a, b: Word);
procedure TestExchangeLongWordsWithData(a, b: LongWord);
procedure TestExchangeShortIntsWithData(a, b: ShortInt);
procedure TestExchangeSmallIntsWithData(a, b: SmallInt);
procedure TestExchangeIntegersWithData(a, b: Integer);
procedure TestExchangeInt64sWithData(a, b: Int64);
procedure TestExchangeDatetimesWithData(a, b: TDatetime);
procedure TestExchangeAnsiStringsWithData(a, b: AnsiString);
procedure TestExchangeStringsWithData(a, b: String);
procedure TestExchangeWideStringsWithData(a, b: WideString);
procedure TestExchangeUnicodeStringsWithData(a, b: UnicodeString);
procedure TestExchangeUtf8StringsWithData(a, b: Utf8String);
published
procedure ExchangeBytesCorrectlyExchangesValues;
procedure ExchangeWordsCorrectlyExchangesValues;
procedure ExchangeLongWordsCorrectlyExchangesValues;
procedure ExchangeShortIntsCorrectlyExchangesValues;
procedure ExchangeSmallIntsCorrectlyExchangesValues;
procedure ExchangeIntegersCorrectlyExchangesValues;
procedure ExchangeInt64sCorrectlyExchangesValues;
procedure ExchangeDatetimesCorrectlyExchangesValues;
procedure ExchangeAnsiStringsCorrectlyExchangesValues;
procedure ExchangeStringsCorrectlyExchangesValues;
procedure ExchangeUnicodeStringsCorrectlyExchangesValues;
procedure ExchangeUtf8StringsCorrectlyExchangesValues;
procedure ExchangeWideStringsCorrectlyExchangesValues;
end;
implementation
uses
Math,
SysUtils,
Deltics.Exchange;
procedure TTypedExchangeTests.TestExchangeBytesWithData(a, b: Byte);
var
oa, ob: Byte;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeWordsWithData(a, b: Word);
var
oa, ob: Word;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeLongWordsWithData(a, b: LongWord);
var
oa, ob: LongWord;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeShortIntsWithData(a, b: ShortInt);
var
oa, ob: ShortInt;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeSmallIntsWithData(a, b: SmallInt);
var
oa, ob: SmallInt;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeIntegersWithData(a, b: Integer);
var
oa, ob: Integer;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeInt64sWithData(a, b: Int64);
var
oa, ob: Int64;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeDatetimesWithData(a, b: TDatetime);
var
oa, ob: TDatetime;
begin
oa := a;
ob := b;
{$ifdef EnhancedOverloads}
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
{$else}
ExchangeDatetime(a, b);
Test('a').AssertDatetime(a).Equals(ob);
Test('b').AssertDatetime(b).Equals(oa);
{$endif}
end;
procedure TTypedExchangeTests.TestExchangeStringsWithData(a, b: String);
var
oa, ob: String;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeUnicodeStringsWithData(a, b: UnicodeString);
var
oa, ob: UnicodeString;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeUtf8StringsWithData(a, b: Utf8String);
var
oa, ob: Utf8String;
begin
oa := a;
ob := b;
ExchangeUtf8(a, b);
Test('a').AssertUtf8(a).Equals(ob);
Test('b').AssertUtf8(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeWideStringsWithData(a, b: WideString);
var
oa, ob: WideString;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
procedure TTypedExchangeTests.TestExchangeAnsiStringsWithData(a, b: AnsiString);
var
oa, ob: AnsiString;
begin
oa := a;
ob := b;
Exchange(a, b);
Test('a').Assert(a).Equals(ob);
Test('b').Assert(b).Equals(oa);
end;
{ TTypedExchangeTests }
procedure TTypedExchangeTests.ExchangeBytesCorrectlyExchangesValues;
const
Max = High(Byte);
begin
TestExchangeBytesWithData( 0, Max);
TestExchangeBytesWithData( Max - 1, Max);
TestExchangeBytesWithData( Max, Max);
end;
procedure TTypedExchangeTests.ExchangeWordsCorrectlyExchangesValues;
const
Max = High(Word);
begin
TestExchangeWordsWithData( 0, Max);
TestExchangeWordsWithData( Max - 1, Max);
TestExchangeWordsWithData( Max, Max);
end;
procedure TTypedExchangeTests.ExchangeLongWordsCorrectlyExchangesValues;
const
Max = High(LongWord);
begin
TestExchangeLongWordsWithData( 0, Max);
TestExchangeLongWordsWithData( Max - 1, Max);
TestExchangeLongWordsWithData( Max, Max);
end;
procedure TTypedExchangeTests.ExchangeShortIntsCorrectlyExchangesValues;
const
Max = High(ShortInt);
begin
TestExchangeShortIntsWithData( 0, Max);
TestExchangeShortIntsWithData( Max - 1, Max);
TestExchangeShortIntsWithData(-Max + 1, -Max);
TestExchangeShortIntsWithData( -Max, Max);
end;
procedure TTypedExchangeTests.ExchangeSmallIntsCorrectlyExchangesValues;
const
Max = High(SmallInt);
begin
TestExchangeSmallIntsWithData( 0, Max);
TestExchangeSmallIntsWithData( Max - 1, Max);
TestExchangeSmallIntsWithData(-Max + 1, -Max);
TestExchangeSmallIntsWithData( -Max, Max);
end;
procedure TTypedExchangeTests.ExchangeIntegersCorrectlyExchangesValues;
begin
TestExchangeIntegersWithData( 0, MaxInt);
TestExchangeIntegersWithData( MaxInt - 1, MaxInt);
TestExchangeIntegersWithData(-MaxInt + 1, -MaxInt);
TestExchangeIntegersWithData( -MaxInt, MaxInt);
end;
procedure TTypedExchangeTests.ExchangeInt64sCorrectlyExchangesValues;
const
Max = High(Int64);
begin
TestExchangeInt64sWithData( 0, Max);
TestExchangeInt64sWithData( Max - 1, Max);
TestExchangeInt64sWithData(-Max + 1, -Max);
TestExchangeInt64sWithData( -Max, Max);
end;
procedure TTypedExchangeTests.ExchangeDatetimesCorrectlyExchangesValues;
begin
TestExchangeDatetimesWithData( 0, Now);
TestExchangeDatetimesWithData( Now - 1, Now);
TestExchangeDatetimesWithData(-Now + 1, -Now);
TestExchangeDatetimesWithData( -Now, Now);
end;
procedure TTypedExchangeTests.ExchangeStringsCorrectlyExchangesValues;
begin
TestExchangeStringsWithData( '', 'foo');
TestExchangeStringsWithData('foo', '');
TestExchangeStringsWithData('foo', 'bar');
end;
procedure TTypedExchangeTests.ExchangeUnicodeStringsCorrectlyExchangesValues;
begin
TestExchangeUnicodeStringsWithData( '', 'foo');
TestExchangeUnicodeStringsWithData('foo', '');
TestExchangeUnicodeStringsWithData('foo', 'bar');
end;
procedure TTypedExchangeTests.ExchangeUtf8StringsCorrectlyExchangesValues;
begin
TestExchangeUtf8StringsWithData( '', 'foo');
TestExchangeUtf8StringsWithData('foo', '');
TestExchangeUtf8StringsWithData('foo', 'bar');
end;
procedure TTypedExchangeTests.ExchangeWideStringsCorrectlyExchangesValues;
begin
TestExchangeWideStringsWithData( '', 'foo');
TestExchangeWideStringsWithData('foo', '');
TestExchangeWideStringsWithData('foo', 'bar');
end;
procedure TTypedExchangeTests.ExchangeAnsiStringsCorrectlyExchangesValues;
begin
TestExchangeAnsiStringsWithData( '', 'foo');
TestExchangeAnsiStringsWithData('foo', '');
TestExchangeAnsiStringsWithData('foo', 'bar');
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.