text stringlengths 14 6.51M |
|---|
unit CustomMap;
interface
type
TCustomMap = class(TObject)
private
FHeight: Integer;
FWidth: Integer;
function GetHeight: Integer;
function GetWidth: Integer;
public
constructor Create;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
end;
implementation
uses gm_engine;
{ TCustomMap }
constructor TCustomMap.Create;
begin
FHeight := MapSide;
FWidth := MapSide;
end;
function TCustomMap.GetHeight: Integer;
begin
Result := FHeight;
end;
function TCustomMap.GetWidth: Integer;
begin
Result := FWidth;
end;
end.
|
unit k2PropertyOperation;
{ Библиотека "K-2" }
{ Автор: Люлин А.В. © }
{ Модуль: k2PropertyOperation - }
{ Начат: 18.10.2005 14:04 }
{ $Id: k2PropertyOperation.pas,v 1.6 2012/07/12 18:33:21 lulin Exp $ }
// $Log: k2PropertyOperation.pas,v $
// Revision 1.6 2012/07/12 18:33:21 lulin
// {RequestLink:237994598}
//
// Revision 1.5 2009/07/23 13:42:34 lulin
// - переносим процессор операций туда куда надо.
//
// Revision 1.4 2009/07/22 17:16:40 lulin
// - оптимизируем использование счётчика ссылок и преобразование к интерфейсам при установке атрибутов тегов.
//
// Revision 1.3 2009/07/06 13:32:12 lulin
// - возвращаемся от интерфейсов к объектам.
//
// Revision 1.2 2005/10/18 10:48:29 lulin
// - реализация базовой Undo-записи удаления/добавления тегов, перенесена в правильное место.
//
// Revision 1.1 2005/10/18 10:32:51 lulin
// - реализация базовой Undo-записи, изменения свойств тегов, перенесена в правильное место.
//
{$Include k2Define.inc }
interface
uses
l3Types,
k2Interfaces,
k2Op,
k2AtomOperation
;
type
Tk2PropOperation = class(Tk2AtomOperation)
protected
// internal methods
function GetPtr(Old: Boolean): PLong;
virtual;
{-}
function GetP(Old: Boolean): Ik2Tag;
{-}
procedure SetP(Old: Boolean; const Value: Ik2Tag);
{-}
procedure DoUndo(const Container: Ik2Op);
override;
{-отменить операцию}
procedure DoRedo(const Container: Ik2Op);
override;
{-повторить операцию}
protected
// property methods
procedure SetValue(Old: Boolean; const Value: Ik2Tag);
{-}
public
// public methods
class procedure ToUndo(const anOpPack : Ik2Op;
const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
const Old, New : Ik2Tag);
reintroduce;
{-}
function SetParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
const Old, New: Ik2Tag): Tk2PropOperation;
reintroduce;
{-}
procedure Clear;
override;
{-}
end;//Tk2PropOperation
Ok2AddProp = class(Tk2PropOperation)
private
// property fields
f_New : Long;
protected
// internal methods
function GetPtr(Old: Boolean): PLong;
override;
{-}
end;//Ok2AddProp
Ok2DelProp = class(Tk2PropOperation)
private
// property fields
f_Old : Long;
protected
// internal methods
function GetPtr(Old: Boolean): PLong;
override;
{-}
public
// public methods
function SetLongParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old : Long): Tk2PropOperation;
{-}
end;//Ok2DelProp
Ok2ModifyProp = class(Tk2PropOperation)
private
// property fields
f_Old : Long;
f_New : Long;
protected
// internal methods
function GetPtr(Old: Boolean): PLong;
override;
{-}
function DoJoin(anOperation: Tk2Op): Tk2Op;
override;
{-соединяет две операции и возвращает:
nil - соединение неудачно
Self - соединение удачно и все поместилось в старую запись
New - распределена новая операция }
function CanJoinWith(anOperation: Tk2Op): Boolean;
override;
{-}
public
// public methods
function SetLongParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old, New : Long): Tk2PropOperation;
{-}
end;//Ok2ModifyProp
implementation
uses
l3Base,
k2Base,
k2BaseStruct
;
// start class Tk2PropOperation
class procedure Tk2PropOperation.ToUndo(const anOpPack : Ik2Op;
const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
const Old, New : Ik2Tag);
{-}
var
l_Op : Tk2PropOperation;
begin
if (anOpPack <> nil) then
begin
l_Op := Create.SetParam(anAtom, aProp, Old, New);
try
l_Op.Put(anOpPack);
finally
l3Free(l_Op);
end;//try..finally
end;//anOpPack <> nil
end;
procedure Tk2PropOperation.Clear;
{override;}
{-}
begin
if (f_Prop <> nil) then
begin
SetP(true, nil);
SetP(false, nil);
end;{f_Prop <> nil}
inherited Clear;
end;
function Tk2PropOperation.SetParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
const Old, New : Ik2Tag): Tk2PropOperation;
{-}
begin
inherited SetParam(anAtom, aProp);
if (f_Prop <> nil) then
begin
SetValue(true, Old);
SetValue(false, New);
end;{f_Prop <> nil}
Result := Self;
end;
function Tk2PropOperation.GetPtr(Old: Boolean): PLong;
//virtual;
{-}
begin
Result := nil;
end;
function Tk2PropOperation.GetP(Old: Boolean): Ik2Tag;
{virtual;}
{-}
var
l_Ptr : PLong;
begin
if (f_Prop = nil) then
Result := k2NullTag
else
begin
l_Ptr := GetPtr(Old);
if (l_Ptr = nil) then
Result := k2NullTag
else
Result := Tk2Type(f_Prop.AtomType).TagFromIntRef(l_Ptr^);
end;//f_Prop = nil
end;
procedure Tk2PropOperation.SetP(Old: Boolean; const Value: Ik2Tag);
{virtual;}
{-}
var
l_P : Ik2Tag;
l_Ptr : PLong;
begin
l_Ptr := GetPtr(Old);
if (l_Ptr <> nil) then
begin
l_P := GetP(Old);
if not l_P.IsSame(Value) then
begin
FreeIntRef(Tk2TypePrim(f_Prop.AtomType), l_Ptr^);
if (Value = nil) then
l_Ptr^ := 0
else
Value.SetIntRef(l_Ptr^);
end;//not l_P.IsSame(Value)
end;//l_Ptr <> nil
end;
procedure Tk2PropOperation.DoUndo(const Container: Ik2Op);
{override;}
{-отменить операцию}
begin
Atom.AttrW[f_Prop.TagIndex, Container] := GetP(true);
end;
procedure Tk2PropOperation.DoRedo(const Container: Ik2Op);
{override;}
{-повторить операцию}
begin
Atom.AttrW[f_Prop.TagIndex, Container] := GetP(false);
end;
procedure Tk2PropOperation.SetValue(Old: Boolean; const Value: Ik2Tag);
{-}
begin
if (Self <> nil) then SetP(Old, Value);
end;
// start class Ok2AddProp
function Ok2AddProp.GetPtr(Old: Boolean): PLong;
{override;}
{-}
begin
if Old then
Result := inherited GetPtr(Old)
else
Result := @f_New;
end;
// start class Ok2DelProp
function Ok2DelProp.GetPtr(Old: Boolean): Plong;
{override;}
{-}
begin
if Old then
Result := @f_Old
else
Result := inherited GetPtr(Old);
end;
function Ok2DelProp.SetLongParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old : Long): Tk2PropOperation;
{-}
(*var
l_AtomW : Tk2AtomW;
l_AtomR : Tk2AtomR absolute l_AtomW;*)
begin
(* l_AtomW.Unlink(aProp.AtomType);
l_AtomW.sLong(Old);*)
Result := SetParam(anAtom, aProp, Tk2Type(aProp.AtomType).IntToTag(Old), k2NullTag);
end;
// start class Ok2ModifyProp
function Ok2ModifyProp.GetPtr(Old: Boolean): PLong;
{override;}
{-}
begin
if Old then
Result := @f_Old
else
Result := @f_New;
end;
function Ok2ModifyProp.SetLongParam(const anAtom : Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old, New : Long): Tk2PropOperation;
{-}
(*var
l_AtomW : Tk2AtomW;
l_AtomR : Tk2AtomR absolute l_AtomW;
l_Old : Tk2AtomR;*)
begin
(* l_AtomW.Unlink(aProp.AtomType);
l_AtomW.sLong(Old);
l_Old := l_AtomR;
l_AtomW.sLong(New);*)
Result := SetParam(anAtom, aProp,
Tk2Type(aProp.AtomType).IntToTag(Old),
Tk2Type(aProp.AtomType).IntToTag(New));
end;
function Ok2ModifyProp.DoJoin(anOperation: Tk2Op): Tk2Op;
//override;
{-соединяет две операции и возвращает:
nil - соединение неудачно
Self - соединение удачно и все поместилось в старую запись
New - распределена новая операция }
begin
Result := nil;
// if (anOperation Is Ok2ModifyProp) then
end;
function Ok2ModifyProp.CanJoinWith(anOperation: Tk2Op): Boolean;
//override;
{-}
begin
Result := (anOperation Is Ok2ModifyProp);
end;
end.
|
unit uMain;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, Dialogs, Registry,
StdCtrls, ComCtrls, uDelphiInstallationCheck, ExtCtrls,
uInstaller, ImgList;
type
TFrmInstall = class(TForm)
ilDelphiIcons: TImageList;
grpDelphiVersions: TGroupBox;
lvDelphis: TListView;
pnlDesc: TPanel;
lblVersion: TLabel;
btnInstall: TButton;
lblDescription: TLabel;
procedure btnInstallDelphiXeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnInstallClick(Sender: TObject);
procedure lvDelphisDblClick(Sender: TObject);
private
FDelphiVersion: TDelphiInstallationCheck;
function GetSelectedPath: string;
function GetDelphiDesc: string;
procedure RefreshDesc(Desc: string);
public
procedure Install;
end;
var
FrmInstall: TFrmInstall;
implementation
const
BPL_FILENAME = 'RfFindUnit.bpl';
{$R *.dfm}
procedure TFrmInstall.btnInstallClick(Sender: TObject);
begin
Install;
end;
procedure TFrmInstall.btnInstallDelphiXeClick(Sender: TObject);
var
Reg: TRegistry;
BplPath: string;
InstalFile: string;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('SOFTWARE\Embarcadero\BDS\8.0', False);
BplPath := Reg.ReadString('RootDir');
Reg.CloseKey;
BplPath := BplPath + 'bin\' + BPL_FILENAME;
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('SOFTWARE\Embarcadero\BDS\8.0\Known Packages', False);
Reg.WriteString('$(BDS)\bin\' + BPL_FILENAME, 'RfUtils');
Reg.CloseKey;
InstalFile := ExtractFilePath(ParamStr(0)) + '\DelphiXE\' + BPL_FILENAME;
if not FileExists(InstalFile) then
begin
MessageDlg('Installation file not found.', mtError,[mbOK],0);
Exit;
end;
CopyFile(PWideChar(InstalFile), PWideChar(BplPath), True);
MessageDlg('Installation finished!', mtInformation, [mbOK], 0);
finally
Reg.Free;
end;
end;
procedure TFrmInstall.FormShow(Sender: TObject);
begin
FDelphiVersion := TDelphiInstallationCheck.Create;
FDelphiVersion.LoadInstalledVersions(ilDelphiIcons, lvDelphis);
end;
function TFrmInstall.GetSelectedPath: string;
var
SelItem: TListItem;
begin
SelItem := lvDelphis.Selected;
if SelItem = nil then
Raise Exception.Create('You must select a Delphi Version.');
Result := SelItem.SubItems[0];
end;
function TFrmInstall.GetDelphiDesc: string;
var
SelItem: TListItem;
begin
SelItem := lvDelphis.Selected;
if SelItem = nil then
Raise Exception.Create('You must select a Delphi Version.');
Result := SelItem.Caption;
end;
procedure TFrmInstall.Install;
var
Installer: TInstaller;
begin
lblDescription.Caption := 'Starting...';
lblDescription.Visible := True;
try
Installer := TInstaller.Create(GetDelphiDesc, GetSelectedPath);
try
Installer.Install(RefreshDesc)
finally
Installer.Free;
end;
MessageDlg('Installation finished!', mtInformation, [mbOK], 0);
except
on E: exception do
MessageDlg('Error on installation: ' + e.Message, mtError, [mbOK], 0);
end;
lblDescription.Visible := False;
end;
procedure TFrmInstall.lvDelphisDblClick(Sender: TObject);
begin
Install;
end;
procedure TFrmInstall.RefreshDesc(Desc: string);
begin
lblDescription.Caption := Desc;
Application.ProcessMessages;
end;
end.
|
program expressionEvaluator(input, output);
(* Interprets expressions such as (+20-3-4+169);*)
var
ch, sign : char;
sum, current : integer;
begin
write('>> ');
read(sign);
ch := ' ';
sum := 0; current := 0;
while (ch <> ';') do
begin
read(ch);
case ch of
'+', '-' :
begin
if sign = '+' then
sum := sum + current
else
sum := sum - current;
current := 0;
sign := ch;
end;
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' :
begin
current := (10 * current) + ord(ch) - ord('0');
end;
end;
end;
if sign = '+' then sum := sum + current
else sum := sum - current;
writeln(sum)
end. |
unit uSaque;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, uRelatorioSaque;
type
TFrmSaque = class(TFrame)
Label1: TLabel;
BtnConfirmar: TButton;
BtnCancelar: TButton;
BtnUm: TButton;
Btn2: TButton;
Btn3: TButton;
Btn4: TButton;
Btn5: TButton;
Btn6: TButton;
Btn7: TButton;
Btn8: TButton;
Btn9: TButton;
Btn0: TButton;
BtnClear: TButton;
PnlValor: TPanel;
BtnBackspace: TButton;
procedure BtnUmClick(Sender: TObject);
procedure Btn2Click(Sender: TObject);
procedure Btn3Click(Sender: TObject);
procedure Btn4Click(Sender: TObject);
procedure Btn5Click(Sender: TObject);
procedure Btn6Click(Sender: TObject);
procedure Btn7Click(Sender: TObject);
procedure Btn8Click(Sender: TObject);
procedure Btn9Click(Sender: TObject);
procedure Btn0Click(Sender: TObject);
procedure BtnClearClick(Sender: TObject);
procedure BtnBackspaceClick(Sender: TObject);
procedure BtnCancelarClick(Sender: TObject);
procedure BtnConfirmarClick(Sender: TObject);
private
{ Private declarations }
FValor:string;
FSaldoDisponivelSacar:Integer;
FSaqueOk:Boolean;
function GetValorSacado:String;
public
procedure Tecla(Valor: integer); { Processa a tecla pressionada }
property ValorSacado:string read GetValorSacado;
procedure Inicializar; { Inicializa o frame }
end;
implementation
uses uFormPrincipal;
{$R *.dfm}
procedure TFrmSaque.BtnUmClick(Sender: TObject);
begin
Tecla(1);
end;
function TFrmSaque.GetValorSacado: String;
begin
Result := PnlValor.Caption;
end;
procedure TFrmSaque.Inicializar;
begin
PnlValor.Caption := '0';
with FrmPrincipal.CdsNotas do
begin
Filtered := false;
Filter := 'QUANTIDADE > 0';
Filtered := true;
FSaldoDisponivelSacar := 0;
First;
while not Eof do
begin
FSaldoDisponivelSacar := FSaldoDisponivelSacar +
(FieldByName('VALOR').Value * FieldByName('QUANTIDADE').Value);
Next;
end;
Filtered := false;
Filter := '';
end;
end;
procedure TFrmSaque.Tecla(Valor: integer);
begin
if Length(PnlValor.Caption) = 9 then
exit;
if PnlValor.Caption = '0' then
PnlValor.Caption := IntToStr(Valor)
else
PnlValor.Caption := PnlValor.Caption + IntToStr(Valor);
end;
procedure TFrmSaque.Btn2Click(Sender: TObject);
begin
Tecla(2);
end;
procedure TFrmSaque.Btn3Click(Sender: TObject);
begin
Tecla(3);
end;
procedure TFrmSaque.Btn4Click(Sender: TObject);
begin
Tecla(4);
end;
procedure TFrmSaque.Btn5Click(Sender: TObject);
begin
Tecla(5);
end;
procedure TFrmSaque.Btn6Click(Sender: TObject);
begin
Tecla(6);
end;
procedure TFrmSaque.Btn7Click(Sender: TObject);
begin
Tecla(7);
end;
procedure TFrmSaque.Btn8Click(Sender: TObject);
begin
Tecla(8);
end;
procedure TFrmSaque.Btn9Click(Sender: TObject);
begin
Tecla(9);
end;
procedure TFrmSaque.Btn0Click(Sender: TObject);
begin
Tecla(0);
end;
procedure TFrmSaque.BtnCancelarClick(Sender: TObject);
begin
FrmPrincipal.AlterarTela(1);
end;
procedure TFrmSaque.BtnClearClick(Sender: TObject);
begin
PnlValor.Caption := '0';
end;
procedure TFrmSaque.BtnConfirmarClick(Sender: TObject);
var
ValorParaSacar:integer;
begin
ValorParaSacar := StrToInt(PnlValor.Caption);
if ValorParaSacar > 0 then
if ValorParaSacar <= FSaldoDisponivelSacar then
FrmPrincipal.AlterarTela(5)
else
ShowMessage('Não á saldo disponivel para efetuar o saque !')
else
ShowMessage('Por favor, informe um valor para sacar !');
end;
procedure TFrmSaque.BtnBackspaceClick(Sender: TObject);
begin
if Length(PnlValor.Caption) <= 1 then
PnlValor.Caption := '0'
else
PnlValor.Caption := copy(PnlValor.Caption, 1, Length(PnlValor.Caption)-1);
end;
end.
|
unit UIWrapper_GroupUnit;
interface
uses
UIWrapper_SchOptPartUnit, FMX.ListBox, FMX.Controls, SearchOption_Intf;
const
ITEM_LIST_GROUP_TIMEUNIT_VIEW: array[0..21] of String = (
'5 sec', '10 sec', '15 sec', '20 sec', '30 sec', //5
'1 min', '2 min', '3 min', '4 min', '5 min', '6 min', '10 min', '15 min', '20 min', '30 min', //10
'1 hour', '2 hour', '3 hour', '4 hour', '6 hour', '8 hour', '12 hour' //7
);
ITEM_LIST_GROUP_TIMEUNIT_FACT: array[0..21] of Integer = (
5, 10, 15, 20, 30,
100, 200, 300, 400, 500, 600, 1000, 1500, 2000, 3000,
10000, 20000, 30000, 40000, 60000, 80000, 100000
);
ITEM_LIST_GROUP_FUNCTION: array[0..2] of String = (
'AVG', 'MIN', 'MAX'
);
ITEM_DEFAULT_GROUP_TIMEUNIT = '1 min';
ITEM_DEFAULT_GROUP_FUNCTION = 'AVG';
type
TUIWrapper_SchOpt_Group = class(TUIWrapper_AbsSearchOptionPart)
private
FCmbTimeUnit: TComboBox;
FCmbFunction: TComboBox;
public
constructor Create(owner: TExpander; cmbTimeUnit, cmbFunction: TComboBox);
function GetSearchOptionPart: ISearchOptionPart; override;
end;
implementation
uses
HashedOptionPart, DCL_intf, Classes, SysUtils, Const_SearchOptionUnit;
constructor TUIWrapper_SchOpt_Group.Create(owner: TExpander; cmbTimeUnit, cmbFunction: TComboBox);
var
sList_TimeUnit: TStringList;
sList_Function: TStringList;
i: Integer;
begin
Init( owner );
FCmbTimeUnit := cmbTimeUnit;
FCmbFunction := cmbFunction;
sList_TimeUnit := StrArrayToStrList( ITEM_LIST_GROUP_TIMEUNIT_VIEW );
sList_Function := StrArrayToStrList( ITEM_LIST_GROUP_FUNCTION );
FCmbTimeUnit.Items := sList_TimeUnit;
FCmbTimeUnit.ItemIndex := sList_TimeUnit.IndexOf( ITEM_DEFAULT_GROUP_TIMEUNIT ); //Default: 1 min
FCmbFunction.Items := sList_Function;
FCmbFunction.ItemIndex := sList_Function.IndexOf( ITEM_DEFAULT_GROUP_FUNCTION ); //Default: AVG
end;
function TUIWrapper_SchOpt_Group.GetSearchOptionPart: ISearchOptionPart;
var
optPart: THashedOptionPart;
begin
optPart := THashedOptionPart.Create;
optPart.SetUse( IsUse );
optPart.Items[ 'timeunit' ] := IntToStr( ITEM_LIST_GROUP_TIMEUNIT_FACT[ FCmbTimeUnit.ItemIndex ] ); //timeunit
optPart.Items[ 'func' ] := ITEM_LIST_GROUP_FUNCTION[ FCmbFunction.ItemIndex ]; //func
result := optPart;
end;
end.
|
unit InfoSYSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoSYSRecord = record
PModCount: String[1];
PNextID: String[5];
Psy_lender: String[4];
Psy_prefix: String[3];
Psy_yrmo: String[6];
Psy_opt: String[50];
Psy_remit1: String[35];
Psy_remit2: String[35];
Psy_remit3: String[35];
Psy_remit4: String[35];
Psy_remit: String[6];
Psy_clnext: String[6];
Pdestid: String[10];
Pdestname: String[23];
Porigid: String[10];
Porigname: String[23];
PCompanyName: String[16];
PCompanyID: String[10];
POrigDFI: String[8];
PBatchDFI: String[8];
PBatchAcct: String[17];
PNextACH: String[10];
PDefaultLenderOpt: String[50];
PSiteID: String[3];
PUTLRetention: Integer;
PLabel1: String[30];
PLabel2: String[30];
PLabel3: String[30];
PLabel4: String[30];
PFaxNumber: String[30];
Phttp: String[40];
PCopyRight: String[40];
PClientID: String[4];
PNextDraftSeq: String[6];
Phttp2: String[150];
Phttp3: String[40];
PhttpLabel: String[25];
PhttpLabel2: String[25];
PhttpLabel3: String[25];
PApplicationName: String[20];
End;
TInfoSYSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoSYSRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoSYS = (InfoSYSPrimaryKey);
TInfoSYSTable = class( TDBISAMTableAU )
private
FDFModCount: TStringField;
FDFNextID: TStringField;
FDFsy_lender: TStringField;
FDFsy_prefix: TStringField;
FDFsy_yrmo: TStringField;
FDFsy_opt: TStringField;
FDFsy_remit1: TStringField;
FDFsy_remit2: TStringField;
FDFsy_remit3: TStringField;
FDFsy_remit4: TStringField;
FDFsy_remit: TStringField;
FDFsy_clnext: TStringField;
FDFdestid: TStringField;
FDFdestname: TStringField;
FDForigid: TStringField;
FDForigname: TStringField;
FDFCompanyName: TStringField;
FDFCompanyID: TStringField;
FDFOrigDFI: TStringField;
FDFBatchDFI: TStringField;
FDFBatchAcct: TStringField;
FDFNextACH: TStringField;
FDFDefaultLenderOpt: TStringField;
FDFSiteID: TStringField;
FDFUTLRetention: TIntegerField;
FDFLabel1: TStringField;
FDFLabel2: TStringField;
FDFLabel3: TStringField;
FDFLabel4: TStringField;
FDFFaxNumber: TStringField;
FDFhttp: TStringField;
FDFCopyRight: TStringField;
FDFClientID: TStringField;
FDFNextDraftSeq: TStringField;
FDFhttp2: TStringField;
FDFhttp3: TStringField;
FDFhttpLabel: TStringField;
FDFhttpLabel2: TStringField;
FDFhttpLabel3: TStringField;
FDFApplicationName: TStringField;
procedure SetPModCount(const Value: String);
function GetPModCount:String;
procedure SetPNextID(const Value: String);
function GetPNextID:String;
procedure SetPsy_lender(const Value: String);
function GetPsy_lender:String;
procedure SetPsy_prefix(const Value: String);
function GetPsy_prefix:String;
procedure SetPsy_yrmo(const Value: String);
function GetPsy_yrmo:String;
procedure SetPsy_opt(const Value: String);
function GetPsy_opt:String;
procedure SetPsy_remit1(const Value: String);
function GetPsy_remit1:String;
procedure SetPsy_remit2(const Value: String);
function GetPsy_remit2:String;
procedure SetPsy_remit3(const Value: String);
function GetPsy_remit3:String;
procedure SetPsy_remit4(const Value: String);
function GetPsy_remit4:String;
procedure SetPsy_remit(const Value: String);
function GetPsy_remit:String;
procedure SetPsy_clnext(const Value: String);
function GetPsy_clnext:String;
procedure SetPdestid(const Value: String);
function GetPdestid:String;
procedure SetPdestname(const Value: String);
function GetPdestname:String;
procedure SetPorigid(const Value: String);
function GetPorigid:String;
procedure SetPorigname(const Value: String);
function GetPorigname:String;
procedure SetPCompanyName(const Value: String);
function GetPCompanyName:String;
procedure SetPCompanyID(const Value: String);
function GetPCompanyID:String;
procedure SetPOrigDFI(const Value: String);
function GetPOrigDFI:String;
procedure SetPBatchDFI(const Value: String);
function GetPBatchDFI:String;
procedure SetPBatchAcct(const Value: String);
function GetPBatchAcct:String;
procedure SetPNextACH(const Value: String);
function GetPNextACH:String;
procedure SetPDefaultLenderOpt(const Value: String);
function GetPDefaultLenderOpt:String;
procedure SetPSiteID(const Value: String);
function GetPSiteID:String;
procedure SetPUTLRetention(const Value: Integer);
function GetPUTLRetention:Integer;
procedure SetPLabel1(const Value: String);
function GetPLabel1:String;
procedure SetPLabel2(const Value: String);
function GetPLabel2:String;
procedure SetPLabel3(const Value: String);
function GetPLabel3:String;
procedure SetPLabel4(const Value: String);
function GetPLabel4:String;
procedure SetPFaxNumber(const Value: String);
function GetPFaxNumber:String;
procedure SetPhttp(const Value: String);
function GetPhttp:String;
procedure SetPCopyRight(const Value: String);
function GetPCopyRight:String;
procedure SetPClientID(const Value: String);
function GetPClientID:String;
procedure SetPNextDraftSeq(const Value: String);
function GetPNextDraftSeq:String;
procedure SetPhttp2(const Value: String);
function GetPhttp2:String;
procedure SetPhttp3(const Value: String);
function GetPhttp3:String;
procedure SetPhttpLabel(const Value: String);
function GetPhttpLabel:String;
procedure SetPhttpLabel2(const Value: String);
function GetPhttpLabel2:String;
procedure SetPhttpLabel3(const Value: String);
function GetPhttpLabel3:String;
procedure SetPApplicationName(const Value: String);
function GetPApplicationName:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoSYS);
function GetEnumIndex: TEIInfoSYS;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoSYSRecord;
procedure StoreDataBuffer(ABuffer:TInfoSYSRecord);
property DFModCount: TStringField read FDFModCount;
property DFNextID: TStringField read FDFNextID;
property DFsy_lender: TStringField read FDFsy_lender;
property DFsy_prefix: TStringField read FDFsy_prefix;
property DFsy_yrmo: TStringField read FDFsy_yrmo;
property DFsy_opt: TStringField read FDFsy_opt;
property DFsy_remit1: TStringField read FDFsy_remit1;
property DFsy_remit2: TStringField read FDFsy_remit2;
property DFsy_remit3: TStringField read FDFsy_remit3;
property DFsy_remit4: TStringField read FDFsy_remit4;
property DFsy_remit: TStringField read FDFsy_remit;
property DFsy_clnext: TStringField read FDFsy_clnext;
property DFdestid: TStringField read FDFdestid;
property DFdestname: TStringField read FDFdestname;
property DForigid: TStringField read FDForigid;
property DForigname: TStringField read FDForigname;
property DFCompanyName: TStringField read FDFCompanyName;
property DFCompanyID: TStringField read FDFCompanyID;
property DFOrigDFI: TStringField read FDFOrigDFI;
property DFBatchDFI: TStringField read FDFBatchDFI;
property DFBatchAcct: TStringField read FDFBatchAcct;
property DFNextACH: TStringField read FDFNextACH;
property DFDefaultLenderOpt: TStringField read FDFDefaultLenderOpt;
property DFSiteID: TStringField read FDFSiteID;
property DFUTLRetention: TIntegerField read FDFUTLRetention;
property DFLabel1: TStringField read FDFLabel1;
property DFLabel2: TStringField read FDFLabel2;
property DFLabel3: TStringField read FDFLabel3;
property DFLabel4: TStringField read FDFLabel4;
property DFFaxNumber: TStringField read FDFFaxNumber;
property DFhttp: TStringField read FDFhttp;
property DFCopyRight: TStringField read FDFCopyRight;
property DFClientID: TStringField read FDFClientID;
property DFNextDraftSeq: TStringField read FDFNextDraftSeq;
property DFhttp2: TStringField read FDFhttp2;
property DFhttp3: TStringField read FDFhttp3;
property DFhttpLabel: TStringField read FDFhttpLabel;
property DFhttpLabel2: TStringField read FDFhttpLabel2;
property DFhttpLabel3: TStringField read FDFhttpLabel3;
property DFApplicationName: TStringField read FDFApplicationName;
property PModCount: String read GetPModCount write SetPModCount;
property PNextID: String read GetPNextID write SetPNextID;
property Psy_lender: String read GetPsy_lender write SetPsy_lender;
property Psy_prefix: String read GetPsy_prefix write SetPsy_prefix;
property Psy_yrmo: String read GetPsy_yrmo write SetPsy_yrmo;
property Psy_opt: String read GetPsy_opt write SetPsy_opt;
property Psy_remit1: String read GetPsy_remit1 write SetPsy_remit1;
property Psy_remit2: String read GetPsy_remit2 write SetPsy_remit2;
property Psy_remit3: String read GetPsy_remit3 write SetPsy_remit3;
property Psy_remit4: String read GetPsy_remit4 write SetPsy_remit4;
property Psy_remit: String read GetPsy_remit write SetPsy_remit;
property Psy_clnext: String read GetPsy_clnext write SetPsy_clnext;
property Pdestid: String read GetPdestid write SetPdestid;
property Pdestname: String read GetPdestname write SetPdestname;
property Porigid: String read GetPorigid write SetPorigid;
property Porigname: String read GetPorigname write SetPorigname;
property PCompanyName: String read GetPCompanyName write SetPCompanyName;
property PCompanyID: String read GetPCompanyID write SetPCompanyID;
property POrigDFI: String read GetPOrigDFI write SetPOrigDFI;
property PBatchDFI: String read GetPBatchDFI write SetPBatchDFI;
property PBatchAcct: String read GetPBatchAcct write SetPBatchAcct;
property PNextACH: String read GetPNextACH write SetPNextACH;
property PDefaultLenderOpt: String read GetPDefaultLenderOpt write SetPDefaultLenderOpt;
property PSiteID: String read GetPSiteID write SetPSiteID;
property PUTLRetention: Integer read GetPUTLRetention write SetPUTLRetention;
property PLabel1: String read GetPLabel1 write SetPLabel1;
property PLabel2: String read GetPLabel2 write SetPLabel2;
property PLabel3: String read GetPLabel3 write SetPLabel3;
property PLabel4: String read GetPLabel4 write SetPLabel4;
property PFaxNumber: String read GetPFaxNumber write SetPFaxNumber;
property Phttp: String read GetPhttp write SetPhttp;
property PCopyRight: String read GetPCopyRight write SetPCopyRight;
property PClientID: String read GetPClientID write SetPClientID;
property PNextDraftSeq: String read GetPNextDraftSeq write SetPNextDraftSeq;
property Phttp2: String read GetPhttp2 write SetPhttp2;
property Phttp3: String read GetPhttp3 write SetPhttp3;
property PhttpLabel: String read GetPhttpLabel write SetPhttpLabel;
property PhttpLabel2: String read GetPhttpLabel2 write SetPhttpLabel2;
property PhttpLabel3: String read GetPhttpLabel3 write SetPhttpLabel3;
property PApplicationName: String read GetPApplicationName write SetPApplicationName;
published
property Active write SetActive;
property EnumIndex: TEIInfoSYS read GetEnumIndex write SetEnumIndex;
end; { TInfoSYSTable }
procedure Register;
implementation
function TInfoSYSTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoSYSTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoSYSTable.GenerateNewFieldName }
function TInfoSYSTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoSYSTable.CreateField }
procedure TInfoSYSTable.CreateFields;
begin
FDFModCount := CreateField( 'ModCount' ) as TStringField;
FDFNextID := CreateField( 'NextID' ) as TStringField;
FDFsy_lender := CreateField( 'sy_lender' ) as TStringField;
FDFsy_prefix := CreateField( 'sy_prefix' ) as TStringField;
FDFsy_yrmo := CreateField( 'sy_yrmo' ) as TStringField;
FDFsy_opt := CreateField( 'sy_opt' ) as TStringField;
FDFsy_remit1 := CreateField( 'sy_remit1' ) as TStringField;
FDFsy_remit2 := CreateField( 'sy_remit2' ) as TStringField;
FDFsy_remit3 := CreateField( 'sy_remit3' ) as TStringField;
FDFsy_remit4 := CreateField( 'sy_remit4' ) as TStringField;
FDFsy_remit := CreateField( 'sy_remit' ) as TStringField;
FDFsy_clnext := CreateField( 'sy_clnext' ) as TStringField;
FDFdestid := CreateField( 'destid' ) as TStringField;
FDFdestname := CreateField( 'destname' ) as TStringField;
FDForigid := CreateField( 'origid' ) as TStringField;
FDForigname := CreateField( 'origname' ) as TStringField;
FDFCompanyName := CreateField( 'CompanyName' ) as TStringField;
FDFCompanyID := CreateField( 'CompanyID' ) as TStringField;
FDFOrigDFI := CreateField( 'OrigDFI' ) as TStringField;
FDFBatchDFI := CreateField( 'BatchDFI' ) as TStringField;
FDFBatchAcct := CreateField( 'BatchAcct' ) as TStringField;
FDFNextACH := CreateField( 'NextACH' ) as TStringField;
FDFDefaultLenderOpt := CreateField( 'DefaultLenderOpt' ) as TStringField;
FDFSiteID := CreateField( 'SiteID' ) as TStringField;
FDFUTLRetention := CreateField( 'UTLRetention' ) as TIntegerField;
FDFLabel1 := CreateField( 'Label1' ) as TStringField;
FDFLabel2 := CreateField( 'Label2' ) as TStringField;
FDFLabel3 := CreateField( 'Label3' ) as TStringField;
FDFLabel4 := CreateField( 'Label4' ) as TStringField;
FDFFaxNumber := CreateField( 'FaxNumber' ) as TStringField;
FDFhttp := CreateField( 'http' ) as TStringField;
FDFCopyRight := CreateField( 'CopyRight' ) as TStringField;
FDFClientID := CreateField( 'ClientID' ) as TStringField;
FDFNextDraftSeq := CreateField( 'NextDraftSeq' ) as TStringField;
FDFhttp2 := CreateField( 'http2' ) as TStringField;
FDFhttp3 := CreateField( 'http3' ) as TStringField;
FDFhttpLabel := CreateField( 'httpLabel' ) as TStringField;
FDFhttpLabel2 := CreateField( 'httpLabel2' ) as TStringField;
FDFhttpLabel3 := CreateField( 'httpLabel3' ) as TStringField;
FDFApplicationName := CreateField( 'ApplicationName' ) as TStringField;
end; { TInfoSYSTable.CreateFields }
procedure TInfoSYSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoSYSTable.SetActive }
procedure TInfoSYSTable.SetPModCount(const Value: String);
begin
DFModCount.Value := Value;
end;
function TInfoSYSTable.GetPModCount:String;
begin
result := DFModCount.Value;
end;
procedure TInfoSYSTable.SetPNextID(const Value: String);
begin
DFNextID.Value := Value;
end;
function TInfoSYSTable.GetPNextID:String;
begin
result := DFNextID.Value;
end;
procedure TInfoSYSTable.SetPsy_lender(const Value: String);
begin
DFsy_lender.Value := Value;
end;
function TInfoSYSTable.GetPsy_lender:String;
begin
result := DFsy_lender.Value;
end;
procedure TInfoSYSTable.SetPsy_prefix(const Value: String);
begin
DFsy_prefix.Value := Value;
end;
function TInfoSYSTable.GetPsy_prefix:String;
begin
result := DFsy_prefix.Value;
end;
procedure TInfoSYSTable.SetPsy_yrmo(const Value: String);
begin
DFsy_yrmo.Value := Value;
end;
function TInfoSYSTable.GetPsy_yrmo:String;
begin
result := DFsy_yrmo.Value;
end;
procedure TInfoSYSTable.SetPsy_opt(const Value: String);
begin
DFsy_opt.Value := Value;
end;
function TInfoSYSTable.GetPsy_opt:String;
begin
result := DFsy_opt.Value;
end;
procedure TInfoSYSTable.SetPsy_remit1(const Value: String);
begin
DFsy_remit1.Value := Value;
end;
function TInfoSYSTable.GetPsy_remit1:String;
begin
result := DFsy_remit1.Value;
end;
procedure TInfoSYSTable.SetPsy_remit2(const Value: String);
begin
DFsy_remit2.Value := Value;
end;
function TInfoSYSTable.GetPsy_remit2:String;
begin
result := DFsy_remit2.Value;
end;
procedure TInfoSYSTable.SetPsy_remit3(const Value: String);
begin
DFsy_remit3.Value := Value;
end;
function TInfoSYSTable.GetPsy_remit3:String;
begin
result := DFsy_remit3.Value;
end;
procedure TInfoSYSTable.SetPsy_remit4(const Value: String);
begin
DFsy_remit4.Value := Value;
end;
function TInfoSYSTable.GetPsy_remit4:String;
begin
result := DFsy_remit4.Value;
end;
procedure TInfoSYSTable.SetPsy_remit(const Value: String);
begin
DFsy_remit.Value := Value;
end;
function TInfoSYSTable.GetPsy_remit:String;
begin
result := DFsy_remit.Value;
end;
procedure TInfoSYSTable.SetPsy_clnext(const Value: String);
begin
DFsy_clnext.Value := Value;
end;
function TInfoSYSTable.GetPsy_clnext:String;
begin
result := DFsy_clnext.Value;
end;
procedure TInfoSYSTable.SetPdestid(const Value: String);
begin
DFdestid.Value := Value;
end;
function TInfoSYSTable.GetPdestid:String;
begin
result := DFdestid.Value;
end;
procedure TInfoSYSTable.SetPdestname(const Value: String);
begin
DFdestname.Value := Value;
end;
function TInfoSYSTable.GetPdestname:String;
begin
result := DFdestname.Value;
end;
procedure TInfoSYSTable.SetPorigid(const Value: String);
begin
DForigid.Value := Value;
end;
function TInfoSYSTable.GetPorigid:String;
begin
result := DForigid.Value;
end;
procedure TInfoSYSTable.SetPorigname(const Value: String);
begin
DForigname.Value := Value;
end;
function TInfoSYSTable.GetPorigname:String;
begin
result := DForigname.Value;
end;
procedure TInfoSYSTable.SetPCompanyName(const Value: String);
begin
DFCompanyName.Value := Value;
end;
function TInfoSYSTable.GetPCompanyName:String;
begin
result := DFCompanyName.Value;
end;
procedure TInfoSYSTable.SetPCompanyID(const Value: String);
begin
DFCompanyID.Value := Value;
end;
function TInfoSYSTable.GetPCompanyID:String;
begin
result := DFCompanyID.Value;
end;
procedure TInfoSYSTable.SetPOrigDFI(const Value: String);
begin
DFOrigDFI.Value := Value;
end;
function TInfoSYSTable.GetPOrigDFI:String;
begin
result := DFOrigDFI.Value;
end;
procedure TInfoSYSTable.SetPBatchDFI(const Value: String);
begin
DFBatchDFI.Value := Value;
end;
function TInfoSYSTable.GetPBatchDFI:String;
begin
result := DFBatchDFI.Value;
end;
procedure TInfoSYSTable.SetPBatchAcct(const Value: String);
begin
DFBatchAcct.Value := Value;
end;
function TInfoSYSTable.GetPBatchAcct:String;
begin
result := DFBatchAcct.Value;
end;
procedure TInfoSYSTable.SetPNextACH(const Value: String);
begin
DFNextACH.Value := Value;
end;
function TInfoSYSTable.GetPNextACH:String;
begin
result := DFNextACH.Value;
end;
procedure TInfoSYSTable.SetPDefaultLenderOpt(const Value: String);
begin
DFDefaultLenderOpt.Value := Value;
end;
function TInfoSYSTable.GetPDefaultLenderOpt:String;
begin
result := DFDefaultLenderOpt.Value;
end;
procedure TInfoSYSTable.SetPSiteID(const Value: String);
begin
DFSiteID.Value := Value;
end;
function TInfoSYSTable.GetPSiteID:String;
begin
result := DFSiteID.Value;
end;
procedure TInfoSYSTable.SetPUTLRetention(const Value: Integer);
begin
DFUTLRetention.Value := Value;
end;
function TInfoSYSTable.GetPUTLRetention:Integer;
begin
result := DFUTLRetention.Value;
end;
procedure TInfoSYSTable.SetPLabel1(const Value: String);
begin
DFLabel1.Value := Value;
end;
function TInfoSYSTable.GetPLabel1:String;
begin
result := DFLabel1.Value;
end;
procedure TInfoSYSTable.SetPLabel2(const Value: String);
begin
DFLabel2.Value := Value;
end;
function TInfoSYSTable.GetPLabel2:String;
begin
result := DFLabel2.Value;
end;
procedure TInfoSYSTable.SetPLabel3(const Value: String);
begin
DFLabel3.Value := Value;
end;
function TInfoSYSTable.GetPLabel3:String;
begin
result := DFLabel3.Value;
end;
procedure TInfoSYSTable.SetPLabel4(const Value: String);
begin
DFLabel4.Value := Value;
end;
function TInfoSYSTable.GetPLabel4:String;
begin
result := DFLabel4.Value;
end;
procedure TInfoSYSTable.SetPFaxNumber(const Value: String);
begin
DFFaxNumber.Value := Value;
end;
function TInfoSYSTable.GetPFaxNumber:String;
begin
result := DFFaxNumber.Value;
end;
procedure TInfoSYSTable.SetPhttp(const Value: String);
begin
DFhttp.Value := Value;
end;
function TInfoSYSTable.GetPhttp:String;
begin
result := DFhttp.Value;
end;
procedure TInfoSYSTable.SetPCopyRight(const Value: String);
begin
DFCopyRight.Value := Value;
end;
function TInfoSYSTable.GetPCopyRight:String;
begin
result := DFCopyRight.Value;
end;
procedure TInfoSYSTable.SetPClientID(const Value: String);
begin
DFClientID.Value := Value;
end;
function TInfoSYSTable.GetPClientID:String;
begin
result := DFClientID.Value;
end;
procedure TInfoSYSTable.SetPNextDraftSeq(const Value: String);
begin
DFNextDraftSeq.Value := Value;
end;
function TInfoSYSTable.GetPNextDraftSeq:String;
begin
result := DFNextDraftSeq.Value;
end;
procedure TInfoSYSTable.SetPhttp2(const Value: String);
begin
DFhttp2.Value := Value;
end;
function TInfoSYSTable.GetPhttp2:String;
begin
result := DFhttp2.Value;
end;
procedure TInfoSYSTable.SetPhttp3(const Value: String);
begin
DFhttp3.Value := Value;
end;
function TInfoSYSTable.GetPhttp3:String;
begin
result := DFhttp3.Value;
end;
procedure TInfoSYSTable.SetPhttpLabel(const Value: String);
begin
DFhttpLabel.Value := Value;
end;
function TInfoSYSTable.GetPhttpLabel:String;
begin
result := DFhttpLabel.Value;
end;
procedure TInfoSYSTable.SetPhttpLabel2(const Value: String);
begin
DFhttpLabel2.Value := Value;
end;
function TInfoSYSTable.GetPhttpLabel2:String;
begin
result := DFhttpLabel2.Value;
end;
procedure TInfoSYSTable.SetPhttpLabel3(const Value: String);
begin
DFhttpLabel3.Value := Value;
end;
function TInfoSYSTable.GetPhttpLabel3:String;
begin
result := DFhttpLabel3.Value;
end;
procedure TInfoSYSTable.SetPApplicationName(const Value: String);
begin
DFApplicationName.Value := Value;
end;
function TInfoSYSTable.GetPApplicationName:String;
begin
result := DFApplicationName.Value;
end;
procedure TInfoSYSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ModCount, String, 1, N');
Add('NextID, String, 5, N');
Add('sy_lender, String, 4, N');
Add('sy_prefix, String, 3, N');
Add('sy_yrmo, String, 6, N');
Add('sy_opt, String, 50, N');
Add('sy_remit1, String, 35, N');
Add('sy_remit2, String, 35, N');
Add('sy_remit3, String, 35, N');
Add('sy_remit4, String, 35, N');
Add('sy_remit, String, 6, N');
Add('sy_clnext, String, 6, N');
Add('destid, String, 10, N');
Add('destname, String, 23, N');
Add('origid, String, 10, N');
Add('origname, String, 23, N');
Add('CompanyName, String, 16, N');
Add('CompanyID, String, 10, N');
Add('OrigDFI, String, 8, N');
Add('BatchDFI, String, 8, N');
Add('BatchAcct, String, 17, N');
Add('NextACH, String, 10, N');
Add('DefaultLenderOpt, String, 50, N');
Add('SiteID, String, 3, N');
Add('UTLRetention, Integer, 0, N');
Add('Label1, String, 30, N');
Add('Label2, String, 30, N');
Add('Label3, String, 30, N');
Add('Label4, String, 30, N');
Add('FaxNumber, String, 30, N');
Add('http, String, 40, N');
Add('CopyRight, String, 40, N');
Add('ClientID, String, 4, N');
Add('NextDraftSeq, String, 6, N');
Add('http2, String, 150, N');
Add('http3, String, 40, N');
Add('httpLabel, String, 25, N');
Add('httpLabel2, String, 25, N');
Add('httpLabel3, String, 25, N');
Add('ApplicationName, String, 20, N');
end;
end;
procedure TInfoSYSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
end;
end;
procedure TInfoSYSTable.SetEnumIndex(Value: TEIInfoSYS);
begin
case Value of
InfoSYSPrimaryKey : IndexName := '';
end;
end;
function TInfoSYSTable.GetDataBuffer:TInfoSYSRecord;
var buf: TInfoSYSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PModCount := DFModCount.Value;
buf.PNextID := DFNextID.Value;
buf.Psy_lender := DFsy_lender.Value;
buf.Psy_prefix := DFsy_prefix.Value;
buf.Psy_yrmo := DFsy_yrmo.Value;
buf.Psy_opt := DFsy_opt.Value;
buf.Psy_remit1 := DFsy_remit1.Value;
buf.Psy_remit2 := DFsy_remit2.Value;
buf.Psy_remit3 := DFsy_remit3.Value;
buf.Psy_remit4 := DFsy_remit4.Value;
buf.Psy_remit := DFsy_remit.Value;
buf.Psy_clnext := DFsy_clnext.Value;
buf.Pdestid := DFdestid.Value;
buf.Pdestname := DFdestname.Value;
buf.Porigid := DForigid.Value;
buf.Porigname := DForigname.Value;
buf.PCompanyName := DFCompanyName.Value;
buf.PCompanyID := DFCompanyID.Value;
buf.POrigDFI := DFOrigDFI.Value;
buf.PBatchDFI := DFBatchDFI.Value;
buf.PBatchAcct := DFBatchAcct.Value;
buf.PNextACH := DFNextACH.Value;
buf.PDefaultLenderOpt := DFDefaultLenderOpt.Value;
buf.PSiteID := DFSiteID.Value;
buf.PUTLRetention := DFUTLRetention.Value;
buf.PLabel1 := DFLabel1.Value;
buf.PLabel2 := DFLabel2.Value;
buf.PLabel3 := DFLabel3.Value;
buf.PLabel4 := DFLabel4.Value;
buf.PFaxNumber := DFFaxNumber.Value;
buf.Phttp := DFhttp.Value;
buf.PCopyRight := DFCopyRight.Value;
buf.PClientID := DFClientID.Value;
buf.PNextDraftSeq := DFNextDraftSeq.Value;
buf.Phttp2 := DFhttp2.Value;
buf.Phttp3 := DFhttp3.Value;
buf.PhttpLabel := DFhttpLabel.Value;
buf.PhttpLabel2 := DFhttpLabel2.Value;
buf.PhttpLabel3 := DFhttpLabel3.Value;
buf.PApplicationName := DFApplicationName.Value;
result := buf;
end;
procedure TInfoSYSTable.StoreDataBuffer(ABuffer:TInfoSYSRecord);
begin
DFModCount.Value := ABuffer.PModCount;
DFNextID.Value := ABuffer.PNextID;
DFsy_lender.Value := ABuffer.Psy_lender;
DFsy_prefix.Value := ABuffer.Psy_prefix;
DFsy_yrmo.Value := ABuffer.Psy_yrmo;
DFsy_opt.Value := ABuffer.Psy_opt;
DFsy_remit1.Value := ABuffer.Psy_remit1;
DFsy_remit2.Value := ABuffer.Psy_remit2;
DFsy_remit3.Value := ABuffer.Psy_remit3;
DFsy_remit4.Value := ABuffer.Psy_remit4;
DFsy_remit.Value := ABuffer.Psy_remit;
DFsy_clnext.Value := ABuffer.Psy_clnext;
DFdestid.Value := ABuffer.Pdestid;
DFdestname.Value := ABuffer.Pdestname;
DForigid.Value := ABuffer.Porigid;
DForigname.Value := ABuffer.Porigname;
DFCompanyName.Value := ABuffer.PCompanyName;
DFCompanyID.Value := ABuffer.PCompanyID;
DFOrigDFI.Value := ABuffer.POrigDFI;
DFBatchDFI.Value := ABuffer.PBatchDFI;
DFBatchAcct.Value := ABuffer.PBatchAcct;
DFNextACH.Value := ABuffer.PNextACH;
DFDefaultLenderOpt.Value := ABuffer.PDefaultLenderOpt;
DFSiteID.Value := ABuffer.PSiteID;
DFUTLRetention.Value := ABuffer.PUTLRetention;
DFLabel1.Value := ABuffer.PLabel1;
DFLabel2.Value := ABuffer.PLabel2;
DFLabel3.Value := ABuffer.PLabel3;
DFLabel4.Value := ABuffer.PLabel4;
DFFaxNumber.Value := ABuffer.PFaxNumber;
DFhttp.Value := ABuffer.Phttp;
DFCopyRight.Value := ABuffer.PCopyRight;
DFClientID.Value := ABuffer.PClientID;
DFNextDraftSeq.Value := ABuffer.PNextDraftSeq;
DFhttp2.Value := ABuffer.Phttp2;
DFhttp3.Value := ABuffer.Phttp3;
DFhttpLabel.Value := ABuffer.PhttpLabel;
DFhttpLabel2.Value := ABuffer.PhttpLabel2;
DFhttpLabel3.Value := ABuffer.PhttpLabel3;
DFApplicationName.Value := ABuffer.PApplicationName;
end;
function TInfoSYSTable.GetEnumIndex: TEIInfoSYS;
var iname : string;
begin
result := InfoSYSPrimaryKey;
iname := uppercase(indexname);
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoSYSTable, TInfoSYSBuffer ] );
end; { Register }
function TInfoSYSBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..40] of string = ('MODCOUNT','NEXTID','SY_LENDER','SY_PREFIX','SY_YRMO','SY_OPT'
,'SY_REMIT1','SY_REMIT2','SY_REMIT3','SY_REMIT4','SY_REMIT'
,'SY_CLNEXT','DESTID','DESTNAME','ORIGID','ORIGNAME'
,'COMPANYNAME','COMPANYID','ORIGDFI','BATCHDFI','BATCHACCT'
,'NEXTACH','DEFAULTLENDEROPT','SITEID','UTLRETENTION','LABEL1'
,'LABEL2','LABEL3','LABEL4','FAXNUMBER','HTTP'
,'COPYRIGHT','CLIENTID','NEXTDRAFTSEQ','HTTP2','HTTP3'
,'HTTPLABEL','HTTPLABEL2','HTTPLABEL3','APPLICATIONNAME' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 40) and (flist[x] <> s) do inc(x);
if x <= 40 then result := x else result := 0;
end;
function TInfoSYSBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
13 : result := ftString;
14 : result := ftString;
15 : result := ftString;
16 : result := ftString;
17 : result := ftString;
18 : result := ftString;
19 : result := ftString;
20 : result := ftString;
21 : result := ftString;
22 : result := ftString;
23 : result := ftString;
24 : result := ftString;
25 : result := ftInteger;
26 : result := ftString;
27 : result := ftString;
28 : result := ftString;
29 : result := ftString;
30 : result := ftString;
31 : result := ftString;
32 : result := ftString;
33 : result := ftString;
34 : result := ftString;
35 : result := ftString;
36 : result := ftString;
37 : result := ftString;
38 : result := ftString;
39 : result := ftString;
40 : result := ftString;
end;
end;
function TInfoSYSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PModCount;
2 : result := @Data.PNextID;
3 : result := @Data.Psy_lender;
4 : result := @Data.Psy_prefix;
5 : result := @Data.Psy_yrmo;
6 : result := @Data.Psy_opt;
7 : result := @Data.Psy_remit1;
8 : result := @Data.Psy_remit2;
9 : result := @Data.Psy_remit3;
10 : result := @Data.Psy_remit4;
11 : result := @Data.Psy_remit;
12 : result := @Data.Psy_clnext;
13 : result := @Data.Pdestid;
14 : result := @Data.Pdestname;
15 : result := @Data.Porigid;
16 : result := @Data.Porigname;
17 : result := @Data.PCompanyName;
18 : result := @Data.PCompanyID;
19 : result := @Data.POrigDFI;
20 : result := @Data.PBatchDFI;
21 : result := @Data.PBatchAcct;
22 : result := @Data.PNextACH;
23 : result := @Data.PDefaultLenderOpt;
24 : result := @Data.PSiteID;
25 : result := @Data.PUTLRetention;
26 : result := @Data.PLabel1;
27 : result := @Data.PLabel2;
28 : result := @Data.PLabel3;
29 : result := @Data.PLabel4;
30 : result := @Data.PFaxNumber;
31 : result := @Data.Phttp;
32 : result := @Data.PCopyRight;
33 : result := @Data.PClientID;
34 : result := @Data.PNextDraftSeq;
35 : result := @Data.Phttp2;
36 : result := @Data.Phttp3;
37 : result := @Data.PhttpLabel;
38 : result := @Data.PhttpLabel2;
39 : result := @Data.PhttpLabel3;
40 : result := @Data.PApplicationName;
end;
end;
end.
|
unit Solid.Samples.LSP.Shapes.Workaround;
interface
type
{ TRectangle }
TRectangle = class
private
FHeight: Integer;
FWidth: Integer;
FLeft: Integer;
FTop: Integer;
protected
procedure SetHeight(AValue: Integer); virtual;
procedure SetWidth(AValue: Integer); virtual;
public
property Height: Integer read FHeight write SetHeight;
property Width: Integer read FWidth write SetWidth;
property Left: Integer read FLeft write FLeft;
property Top: Integer read FTop write FTop;
end;
{ TSquare }
TSquare = class(TRectangle)
protected
procedure SetHeight(AValue: Integer); override;
procedure SetWidth(AValue: Integer); override;
end;
implementation
{ TRectangle }
procedure TRectangle.SetHeight(AValue: Integer);
begin
FHeight := AValue;
end;
procedure TRectangle.SetWidth(AValue: Integer);
begin
FWidth := AValue;
end;
{ TSquare }
procedure TSquare.SetHeight(AValue: Integer);
begin
inherited SetHeight(AValue);
inherited SetWidth(AValue);
end;
procedure TSquare.SetWidth(AValue: Integer);
begin
inherited SetWidth(AValue);
inherited SetHeight(AValue);
end;
end.
|
{ Subroutine SST_R_SYO_ITEM (JTARG, SYM_MFLAG)
*
* Process ITEM syntax.
}
module sst_r_syo_item;
define sst_r_syo_item;
%include 'sst_r_syo.ins.pas';
procedure sst_r_syo_item ( {process ITEM syntax}
in out jtarg: jump_targets_t; {execution block jump targets info}
in sym_mflag: sst_symbol_t); {desc of parent MFLAG variable symbol}
val_param;
var
tag: sys_int_machine_t; {tag from syntax tree}
str_h: syo_string_t; {handle to string from input file}
jt: jump_targets_t; {jump targets for nested routines}
itag: sys_int_machine_t; {tag value if item is tagged}
token: string_var32_t; {scratch token for number conversion}
stat: sys_err_t;
begin
token.max := sizeof(token.str); {init local var string}
syo_level_down; {down into ITEM syntax}
syo_push_pos; {save position at start of ITEM}
syo_get_tag_msg ( {tag for whether item is tagged or not}
tag, str_h, 'sst_syo_read', 'syerr_define', nil, 0);
syo_pop_pos; {restore position to start of ITEM}
case tag of
{
**************************************
*
* Item is tagged.
}
1: begin
syo_get_tag_string (str_h, token); {get tag value string}
string_t_int (token, itag, stat); {make tag value in ITAG}
syo_error_abort (stat, str_h, '', '', nil, 0);
sst_call (sym_tag_start_p^); {create call to SYO_P_TAG_START}
sst_r_syo_jtargets_make ( {make jump targets for nested routine}
jtarg, {template jump targets}
jt, {output jump targets}
lab_fall_k, {YES action}
lab_fall_k, {NO action}
lab_fall_k); {ERR action}
sst_r_syo_utitem (jt, sym_mflag); {process UNTAGGED_ITEM syntax}
sst_r_syo_jtargets_done (jt); {define any implicit labels}
sst_call (sym_tag_end_p^); {create call to SYO_P_TAG_END}
sst_call_arg_var (sst_opc_p^, sym_mflag); {add MFLAG call argument}
sst_call_arg_int (sst_opc_p^, itag); {add tag value argument}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is untagged.
}
2: begin
sst_r_syo_utitem (jtarg, sym_mflag); {ITEM resolves to just this UNTAGGED_ITEM}
end;
{
**************************************
*
* Unexpected expression format tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of item format cases}
syo_level_up; {back up from ITEM syntax}
end;
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.Xml,
RemObjects.Elements.EUnit;
type
DocumentTypeTest = public class (Test)
private
Doc: XmlDocument;
Data: XmlDocumentType;
public
method Setup; override;
method Name;
method LocalName;
method PublicId;
method SystemId;
method NodeType;
method AccessFromDocument;
method Childs;
method Value;
end;
implementation
method DocumentTypeTest.Setup;
begin
Doc := XmlDocument.FromString(XmlTestData.DTDXml);
Assert.IsNotNil(Doc);
Data := Doc.FirstChild as XmlDocumentType;
Assert.IsNotNil(Data);
end;
method DocumentTypeTest.PublicId;
begin
Assert.IsNotNil(Data.PublicId);
Assert.AreEqual(Data.PublicId, "");
Doc := XmlDocument.FromString(XmlTestData.CharXml);
Assert.IsNotNil(Doc);
Assert.IsNotNil(Doc.DocumentType);
Assert.IsNotNil(Doc.DocumentType.PublicId);
Assert.AreEqual(Doc.DocumentType.PublicId, "-//W3C//DTD XHTML 1.0 Transitional//EN");
end;
method DocumentTypeTest.SystemId;
begin
Assert.IsNotNil(Data.SystemId);
Assert.AreEqual(Data.SystemId, "");
Doc := XmlDocument.FromString(XmlTestData.CharXml);
Assert.IsNotNil(Doc);
Assert.IsNotNil(Doc.DocumentType);
Assert.IsNotNil(Doc.DocumentType.SystemId);
Assert.AreEqual(Doc.DocumentType.SystemId, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
end;
method DocumentTypeTest.NodeType;
begin
Assert.AreEqual(Data.NodeType, XmlNodeType.DocumentType);
end;
method DocumentTypeTest.AccessFromDocument;
begin
Assert.IsNotNil(Doc.DocumentType);
Assert.IsTrue(Doc.DocumentType.Equals(Data));
end;
method DocumentTypeTest.Name;
begin
Assert.IsNotNil(Data.Name);
Assert.AreEqual(Data.Name, "note");
end;
method DocumentTypeTest.LocalName;
begin
Assert.IsNotNil(Data.LocalName);
Assert.AreEqual(Data.LocalName, "note");
end;
method DocumentTypeTest.Childs;
begin
Assert.AreEqual(Data.ChildCount, 0);
Assert.IsNil(Data.FirstChild);
Assert.IsNil(Data.LastChild);
Assert.AreEqual(length(Data.ChildNodes), 0);
end;
method DocumentTypeTest.Value;
begin
Assert.IsNil(Data.Value);
end;
end.
|
unit Unt_Principal;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ComCtrls,
Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ProgressBar1: TProgressBar;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const
C_TOTAL_LINHA = 10000;
var
_arquivo : TextFile;
slLinha : TStringList;
i : Integer;
sLinha : string;
iTotalLinha: Integer;
begin
Screen.Cursor := crHourGlass;
slLinha := TStringList.Create;
Self.ProgressBar1.Position := 0;
Self.ProgressBar1.Step := 1;
Self.ProgressBar1.Max := C_TOTAL_LINHA;
try
AssignFile(_arquivo, '.\arquivo.csv');
Rewrite(_arquivo);
for i := 1 to C_TOTAL_LINHA do
begin
slLinha.Clear;
slLinha.Add(IntToStr(i));
slLinha.Add(StringOfChar('n', Random(100)));
slLinha.Add(StringOfChar('9', 14));
slLinha.Add(StringOfChar('c', 14));
slLinha.Add(StringOfChar('8', 11));
slLinha.Add(StringOfChar('7', 11));
slLinha.Add(StringOfChar('a', 20) + '@teste.com.br');
sLinha := slLinha.CommaText;
Writeln(_arquivo, sLinha);
Self.ProgressBar1.StepIt;
end;
finally
CloseFile(_arquivo);
slLinha.Free;
Screen.Cursor := crDefault;
end;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clFtpFileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Windows,
{$ELSE}
System.Classes, System.SysUtils, Winapi.Windows,
{$ENDIF}
clFtpServer, clFtpUtils;
type
TclFtpFileHandler = class(TComponent)
private
FServer: TclFtpServer;
procedure SetServer(const Value: TclFtpServer);
function GetErrorText(AErrorCode: Integer): string;
procedure DoCreateDir(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
procedure DoDelete(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
procedure DoGetFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string);
procedure DoGetFileList(Sender: TObject; AConnection: TclFtpCommandConnection;
const APathName, AFileMask: string; AIncludeHidden: Boolean; AFileList: TclFtpFileInfoList;
var Success: Boolean; var AErrorMessage: string);
procedure DoPutFile(Sender: TObject; AConnection: TclFtpCommandConnection; const AFileName: string;
AOverwrite: Boolean; var ADestination: TStream; var Success: Boolean; var AErrorMessage: string);
procedure DoRename(Sender: TObject; AConnection: TclFtpCommandConnection;
const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
published
property Server: TclFtpServer read FServer write SetServer;
end;
implementation
uses
clUtils;
{ TclFtpFileHandler }
procedure TclFtpFileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclFtpFileHandler.SetServer(const Value: TclFtpServer);
begin
if (FServer <> Value) then
begin
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
procedure TclFtpFileHandler.CleanEventHandlers;
begin
Server.OnCreateDir := nil;
Server.OnDelete := nil;
Server.OnRename := nil;
Server.OnPutFile := nil;
Server.OnGetFile := nil;
Server.OnGetFileList := nil;
end;
procedure TclFtpFileHandler.InitEventHandlers;
begin
Server.OnCreateDir := DoCreateDir;
Server.OnDelete := DoDelete;
Server.OnRename := DoRename;
Server.OnPutFile := DoPutFile;
Server.OnGetFile := DoGetFile;
Server.OnGetFileList := DoGetFileList;
end;
procedure TclFtpFileHandler.DoCreateDir(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
begin
Success := CreateDir(AName);
if not Success then
begin
AErrorMessage := GetErrorText(clGetLastError());
end;
end;
procedure TclFtpFileHandler.DoDelete(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
var
attr: Integer;
sr: TSearchRec;
begin
try
attr := faDirectory;
if (FindFirst(AName, attr, sr) = 0) and ((sr.Attr and faDirectory) > 0) then
begin
Success := RemoveDir(AName);
end else
begin
Success := DeleteFile(PChar(AName));
end;
if not Success then
begin
AErrorMessage := GetErrorText(clGetLastError());
end;
finally
{$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(sr);
end;
end;
procedure TclFtpFileHandler.DoRename(Sender: TObject; AConnection: TclFtpCommandConnection;
const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string);
begin
Success := RenameFile(ACurrentName, ANewName);
if not Success then
begin
AErrorMessage := GetErrorText(clGetLastError());
end;
end;
procedure TclFtpFileHandler.DoPutFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; AOverwrite: Boolean; var ADestination: TStream;
var Success: Boolean; var AErrorMessage: string);
const
modes: array[Boolean] of Word = (fmOpenWrite, fmCreate);
begin
try
ADestination := TFileStream.Create(AFileName, modes[AOverwrite]);
Success := True;
except
on E: Exception do
begin
Success := False;
AErrorMessage := E.Message;
end;
end;
end;
procedure TclFtpFileHandler.DoGetFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string);
begin
try
ASource := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
Success := True;
except
on E: Exception do
begin
Success := False;
AErrorMessage := E.Message;
end;
end;
end;
procedure TclFtpFileHandler.DoGetFileList(Sender: TObject; AConnection: TclFtpCommandConnection;
const APathName, AFileMask: string; AIncludeHidden: Boolean; AFileList: TclFtpFileInfoList;
var Success: Boolean; var AErrorMessage: string);
var
searchRec: TSearchRec;
path: string;
item: TclFtpFileInfo;
attr: Integer;
isDevice: Boolean;
begin
path := APathName;
isDevice := (AFileMask = '') and (APathName <> '') and (APathName[Length(APathName)] = DriveDelim);
if (not isDevice) and (not FileExists(path)) then
begin
path := AddTrailingBackSlash(path) + AFileMask;
end;
attr := faReadOnly or faDirectory or faArchive;
if AIncludeHidden then
begin
attr := attr or faHidden;
end;
if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(path, attr, searchRec) = 0 then
begin
repeat
if (searchRec.Name <> '.') and (searchRec.Name <> '..') then
begin
item := TclFtpFileInfo.Create();
AFileList.Add(item);
if (isDevice) then
begin
item.FileName := path;
end else
begin
item.FileName := searchRec.Name;
end;
item.IsDirectory := (searchRec.Attr and FILE_ATTRIBUTE_DIRECTORY) > 0;
item.IsReadOnly := (searchRec.Attr and FILE_ATTRIBUTE_READONLY) > 0;
item.Size := searchRec.Size;
item.ModifiedDate := ConvertFileTimeToDateTime(searchRec.FindData.ftLastWriteTime);
end;
until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(searchRec) <> 0);
{$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(searchRec);
end;
end;
function TclFtpFileHandler.GetErrorText(AErrorCode: Integer): string;
var
Buffer: array[0..255] of Char;
begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, AErrorCode, 0, Buffer, SizeOf(Buffer), nil);
Result := Trim(Buffer);
end;
end.
|
unit atNotifier;
// Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atNotifier.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatNotifier" MUID: (4807877801B7)
interface
uses
l3IntfUses
, atInterfaces
, Classes
, SysUtils
;
type
TatNotifier = class(TInterfacedObject, IatNotifier)
private
f_Listeners: TInterfaceList;
f_MREWS: TMultiReadExclusiveWriteSynchronizer;
private
function IsNotify(const listener: IatListener): Boolean;
protected
procedure StartNotify(const listener: IatListener);
procedure StopNotify; overload;
procedure StopNotify(const listener: IatListener); overload;
procedure Trigger(sender: TObject;
const notification: IatNotification);
public
constructor Create; reintroduce;
destructor Destroy; override;
end;//TatNotifier
implementation
uses
l3ImplUses
//#UC START# *4807877801B7impl_uses*
//#UC END# *4807877801B7impl_uses*
;
function TatNotifier.IsNotify(const listener: IatListener): Boolean;
//#UC START# *480787C7033C_4807877801B7_var*
//#UC END# *480787C7033C_4807877801B7_var*
begin
//#UC START# *480787C7033C_4807877801B7_impl*
Result := (f_Listeners.IndexOf(listener) <> -1);
//#UC END# *480787C7033C_4807877801B7_impl*
end;//TatNotifier.IsNotify
constructor TatNotifier.Create;
//#UC START# *480787E20035_4807877801B7_var*
//#UC END# *480787E20035_4807877801B7_var*
begin
//#UC START# *480787E20035_4807877801B7_impl*
inherited;
//
f_Listeners := TInterfaceList.Create;
f_MREWS := TMultiReadExclusiveWriteSynchronizer.Create;
//#UC END# *480787E20035_4807877801B7_impl*
end;//TatNotifier.Create
procedure TatNotifier.StartNotify(const listener: IatListener);
//#UC START# *48077F83039B_4807877801B7_var*
//#UC END# *48077F83039B_4807877801B7_var*
begin
//#UC START# *48077F83039B_4807877801B7_impl*
f_MREWS.BeginWrite;
try
if IsNotify(listener) then Exit;
f_Listeners.Add(listener);
listener.StartListen(Self);
finally
f_MREWS.EndWrite;
end;
//#UC END# *48077F83039B_4807877801B7_impl*
end;//TatNotifier.StartNotify
procedure TatNotifier.StopNotify;
//#UC START# *48077F8E00B6_4807877801B7_var*
var
listener : IatListener;
//#UC END# *48077F8E00B6_4807877801B7_var*
begin
//#UC START# *48077F8E00B6_4807877801B7_impl*
f_MREWS.BeginWrite;
try
while (true) do begin
if (f_Listeners.Count = 0) then Exit; // и так никого не слушаем
listener := f_Listeners.First as IatListener;
StopNotify(listener);
end;
finally
f_MREWS.EndWrite;
end;
//#UC END# *48077F8E00B6_4807877801B7_impl*
end;//TatNotifier.StopNotify
procedure TatNotifier.StopNotify(const listener: IatListener);
//#UC START# *48077F9601A1_4807877801B7_var*
//#UC END# *48077F9601A1_4807877801B7_var*
begin
//#UC START# *48077F9601A1_4807877801B7_impl*
f_MREWS.BeginWrite;
try
if NOT IsNotify(listener) then Exit;
f_Listeners.Remove(listener);
listener.StopListen(Self);
finally
f_MREWS.EndWrite;
end;
//#UC END# *48077F9601A1_4807877801B7_impl*
end;//TatNotifier.StopNotify
procedure TatNotifier.Trigger(sender: TObject;
const notification: IatNotification);
//#UC START# *48077FA2038C_4807877801B7_var*
var
i : integer;
listener : IatListener;
//#UC END# *48077FA2038C_4807877801B7_var*
begin
//#UC START# *48077FA2038C_4807877801B7_impl*
f_MREWS.BeginRead;
try
for i := 0 to f_Listeners.Count-1 do
begin
listener := f_Listeners.Items[i] as IatListener;
listener.Fire(sender, notification);
end;
finally
f_MREWS.EndRead;
end;
//#UC END# *48077FA2038C_4807877801B7_impl*
end;//TatNotifier.Trigger
destructor TatNotifier.Destroy;
//#UC START# *48077504027E_4807877801B7_var*
//#UC END# *48077504027E_4807877801B7_var*
begin
//#UC START# *48077504027E_4807877801B7_impl*
StopNotify;
FreeAndNil(f_Listeners);
FreeAndNil(f_MREWS);
//
inherited;
//#UC END# *48077504027E_4807877801B7_impl*
end;//TatNotifier.Destroy
end.
|
unit kwClearSpellDictionary;
{* Очищает пользовательский словарь проверки орфографии. }
// Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\kwClearSpellDictionary.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "ClearSpellDictionary" MUID: (581338320377)
// Имя типа: "TkwClearSpellDictionary"
{$Include w:\archi\source\projects\Archi\arDefine.inc}
interface
{$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwRegisterableWord
, tfwScriptingInterfaces
;
type
TkwClearSpellDictionary = {final} class(TtfwRegisterableWord)
{* Очищает пользовательский словарь проверки орфографии. }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
end;//TkwClearSpellDictionary
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, arArchiTestAdapter2
//#UC START# *581338320377impl_uses*
//#UC END# *581338320377impl_uses*
;
class function TkwClearSpellDictionary.GetWordNameForRegister: AnsiString;
begin
Result := 'ClearSpellDictionary';
end;//TkwClearSpellDictionary.GetWordNameForRegister
procedure TkwClearSpellDictionary.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_581338320377_var*
//#UC END# *4DAEEDE10285_581338320377_var*
begin
//#UC START# *4DAEEDE10285_581338320377_impl*
arClearSpellDictionary;
//#UC END# *4DAEEDE10285_581338320377_impl*
end;//TkwClearSpellDictionary.DoDoIt
initialization
TkwClearSpellDictionary.RegisterInEngine;
{* Регистрация ClearSpellDictionary }
{$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND Defined(AppClientSide) AND NOT Defined(NoScripts)
end.
|
unit TippingForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Inifiles, IOUtils, Vcl.Samples.Spin,
Vcl.StdCtrls;
type
TForm4 = class(TForm)
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
Edit2: TEdit;
ComboBox2: TComboBox;
Edit1: TEdit;
Button1: TButton;
SpinEdit1: TSpinEdit;
Label1: TLabel;
Edit3: TEdit;
procedure loadProfiles();
procedure Button1Click(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
implementation
{$R *.dfm}
procedure TForm4.Button1Click(Sender: TObject);
var iniFile: TIniFile;
begin
iniFile := TIniFile.Create('./tips/' + ChangeFileExt(edit1.Text, '.ini'));
try
iniFile.WriteString('Tipprofil', 'Receiver', edit2.Text);
iniFile.WriteInteger('Tipprofil', 'Percent', SpinEdit1.Value);
iniFile.WriteInteger('Tipprofil', 'MinAmount', strtoint(edit3.Text));
finally
iniFile.Free;
end;
loadProfiles();
end;
procedure TForm4.ComboBox2Change(Sender: TObject);
var iniFile: TIniFile;
begin
iniFile := TIniFile.Create('./tips/' + combobox2.Items[combobox2.ItemIndex]);
try
edit1.Text := combobox2.Items[combobox2.ItemIndex].Remove(combobox2.Items[combobox2.ItemIndex].IndexOf('.', 4));
edit2.Text := iniFile.ReadString('Tipprofil', 'Receiver', '');
SpinEdit1.Value := iniFile.ReadInteger('Tipprofil', 'Percent', 0);
edit3.Text := inttostr(iniFile.ReadInteger('Tipprofil', 'MinAmount', 10000));
finally
iniFile.Free;
end;
end;
procedure TForm4.FormShow(Sender: TObject);
begin
loadProfiles();
end;
procedure TForm4.loadProfiles();
var path: String;
begin
if not DirectoryExists('./tips/') then
CreateDir('./tips');
Combobox2.Clear;
for path in TDirectory.GetFiles('./tips/') do
Combobox2.Items.Add(path.Remove(0, 7));
end;
end.
|
unit nscNavigator;
// Библиотека : "Визуальные компоненты проекта Немезис"
// Автор : М. Морозов.
// Начат : 06.12.2006 г.
// Назначение : Компонент с вкладками
// Версия : $Id: nscNavigator.pas,v 1.5 2009/01/12 17:38:11 lulin Exp $
// $Log: nscNavigator.pas,v $
// Revision 1.5 2009/01/12 17:38:11 lulin
// - <K>: 133138664. № 24.
//
// Revision 1.4 2009/01/12 09:14:30 oman
// - new: Учим навигатор закрываться по Ctrl+F4 (К-113508400)
//
// Revision 1.3 2007/08/20 09:06:07 mmorozov
// - new: уведомление об изменении активной вкладки (CQ: OIT5-26352);
//
// Revision 1.2 2006/12/12 11:42:27 mmorozov
// - new: возможность определять класс плавающего окна;
//
// Revision 1.1 2006/12/07 14:23:11 mmorozov
// - new: используем единые настройки для компонента с вкладками (CQ: OIT5-23819);
//
interface
uses
Classes,
ElPgCtl,
vcmExternalInterfaces,
nscInterfaces,
vtNavigator
;
type
_nscDestPageControl_ = TnpPageControl;
{$Include nscPageControl.inc}
TnscNavigatorPageControl = _nscPageControl_;
TnscNavigator = class(TvtNavigator,
IvcmOperationsProvider)
private
procedure CloseChildExecute(const aParams : IvcmExecuteParamsPrim);
{-}
procedure CloseChildTest(const aParams : IvcmTestParamsPrim);
{-}
protected
// IvcmOperationsProvider
procedure ProvideOps(const aPublisher : IvcmOperationsPublisher);
{* - предоставить список доступных операций. }
protected
// methods
function GetPageControlClass: RnpPageControl;
override;
{-}
function GetFloatingWindowClass: RnpFloatingWindow;
override;
{* - получить класс плавающего окна. }
end;//TnscNavigator
TnscFloatingWindow = class(TnpFloatingWindow)
{* Плавающего окно навигатора. }
protected
// methods
function GetNavigatorClass: RvtNavigator;
override;
{* - ссылка на класс навигатора. }
end;//TnscFloatingWindow
implementation
uses
SysUtils,
Graphics,
Controls,
afwVCL,
{$IfNDef DesignTimeLibrary}
vcmBase,
{$EndIf DesignTimeLibrary}
nscNewInterfaces,
nscTabFont
;
const
vcm_deEnclosedForms = 'EnclosedForms';
vcm_doCloseChild = 'CloseChild';
{$Include nscPageControl.inc}
{ TnscNavigator }
procedure TnscNavigator.CloseChildExecute(
const aParams: IvcmExecuteParamsPrim);
begin
Header.CloseButton.Click
end;
procedure TnscNavigator.CloseChildTest(const aParams: IvcmTestParamsPrim);
begin
if aParams.Op.Flag[vcm_ofEnabled] then
aParams.Op.Flag[vcm_ofEnabled] := Assigned(Header.CloseButton) and Header.CloseButton.Visible;
end;
function TnscNavigator.GetFloatingWindowClass: RnpFloatingWindow;
begin
Result := TnscFloatingWindow;
end;
function TnscNavigator.GetPageControlClass: RnpPageControl;
begin
Result := TnscNavigatorPageControl;
end;//GetPageControlClass
procedure TnscNavigator.ProvideOps(
const aPublisher: IvcmOperationsPublisher);
begin
aPublisher.PublishOp(vcm_deEnclosedForms, vcm_doCloseChild, CloseChildExecute, CloseChildTest);
end;
{ TnscFloatingWindow }
function TnscFloatingWindow.GetNavigatorClass: RvtNavigator;
begin
Result := TnscNavigator;
end;
end. |
unit LinkLabel1;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Graphics, Messages, System.UITypes;
type
TLinkLabel2 = class(TLabel)
private
FLinkVisitedColor: TColor;
FLinkColor: TColor;
FURL: string;
FOldColor : TColor;
FVisitado: Boolean;
FLinkHoverColor: TColor;
procedure SetLinkColor(const Value: TColor);
procedure SetLinkVisitedColor(const Value: TColor);
procedure SetURL(const Value: string);
procedure SetLinkHoverColor(const Value: TColor);
{ Private declarations }
protected
{ Protected declarations }
procedure CMMouseEnter(var Msg : TMessage); message CM_MouseEnter;
procedure CMMouseLeave(var Msg : TMessage); message CM_MouseLeave;
procedure Click; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
property URL : string read FURL write SetURL;
property LinkColor : TColor read FLinkColor write SetLinkColor;
property LinkVisitedColor : TColor read FLinkVisitedColor write SetLinkVisitedColor;
property LinkHoverColor : TColor read FLinkHoverColor write SetLinkHoverColor;
end;
procedure Register;
implementation
uses
Winapi.ShellAPI, Forms, Winapi.Windows;
procedure Register;
begin
RegisterComponents('Samples', [TLinkLabel2]);
end;
{ TLinkLabel }
procedure TLinkLabel2.Click;
begin
inherited;
if FURL <> EmptyStr then
begin
ShellExecute(Application.Handle, nil, PChar(FUrl), nil, nil, SW_Shownormal);
end;
FVisitado := True;
end;
procedure TLinkLabel2.CMMouseEnter(var Msg: TMessage);
begin
if URL <> EmptyStr then
begin
Font.Style := Font.Style + [fsUnderLine];
Font.Color := LinkHoverColor;
end;
end;
procedure TLinkLabel2.CMMouseLeave(var Msg: TMessage);
begin
if URL <> EmptyStr then
begin
Font.Style := Font.Style - [fsUnderLine];
if FVisitado then
Font.Color := LinkVisitedColor
else
Font.Color := LinkColor;
end;
end;
constructor TLinkLabel2.Create(AOwner: TComponent);
begin
inherited;
Cursor := crHandPoint;
if FURL <> EmptyStr then
begin
FOldColor := Font.Color;
Font.Color := LinkColor;
end;
end;
procedure TLinkLabel2.SetLinkColor(const Value: TColor);
begin
FLinkColor := Value;
end;
procedure TLinkLabel2.SetLinkHoverColor(const Value: TColor);
begin
FLinkHoverColor := Value;
end;
procedure TLinkLabel2.SetLinkVisitedColor(const Value: TColor);
begin
FLinkVisitedColor := Value;
end;
procedure TLinkLabel2.SetURL(const Value: string);
begin
FURL := Value;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSHandshakeExtension.pas }
{ File version: 5.03 }
{ Description: TLS handshake extension }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ All rights reserved. }
{ Redistribution and use in source and binary forms, with }
{ or without modification, are permitted provided that }
{ the following conditions are met: }
{ Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the }
{ following disclaimer. }
{ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND }
{ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED }
{ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED }
{ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A }
{ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL }
{ THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, }
{ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR }
{ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, }
{ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF }
{ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) }
{ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER }
{ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING }
{ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE }
{ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE }
{ POSSIBILITY OF SUCH DAMAGE. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/11 5.02 ExtensionType. }
{ SignatureAlgorithms ClientHello extension. }
{ 2020/05/19 5.03 Create flcTLSHandshakeExtension unit from }
{ flcTLSHandshake unit. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSHandshakeExtension;
interface
uses
{ TLS }
flcTLSAlgorithmTypes;
{ }
{ ExtensionType }
{ }
type
TTLSExtensionType = (
tlsetServer_name = 0, // RFC 6066
tlsetMax_fragment_length = 1, // RFC 6066
tlsetStatus_request = 5, // RFC 6066
tlsetSupported_groups = 10, // RFC 8422, 7919
tlsetSignature_algorithms = 13, // RFC 8446 - TLS 1.2
tlsetUse_srtp = 14, // RFC 5764
tlsetHeartbeat = 15, // RFC 6520
tlsetApplication_layer_protocol_negotiation = 16, // RFC 7301
tlsetSigned_certificate_timestamp = 18, // RFC 6962
tlsetClient_certificate_type = 19, // RFC 7250
tlsetServer_certificate_type = 20, // RFC 7250
tlsetPadding = 21, // RFC 7685
tlsetPre_shared_key = 41, // RFC 8446
tlsetEarly_data = 42, // RFC 8446
tlsetSupported_versions = 43, // RFC 8446
tlsetCookie = 44, // RFC 8446
tlsetPsk_key_exchange_modes = 45, // RFC 8446
tlsetCertificate_authorities = 47, // RFC 8446
tlsetOid_filters = 48, // RFC 8446
tlsetPost_handshake_auth = 49, // RFC 8446
tlsetSignature_algorithms_cert = 50, // RFC 8446
tlsetKey_share = 51, // RFC 8446
tlsetMax = 65535
);
{ }
{ SignatureAlgorithms }
{ }
function EncodeTLSExtension_SignatureAlgorithms(
var Buffer; const Size: Integer;
const SignAndHashAlgos: TTLSSignatureAndHashAlgorithmArray): Integer;
implementation
uses
{ TLS }
flcTLSErrors,
flcTLSOpaqueEncoding;
{ }
{ SignatureAlgorithms }
{ }
function EncodeTLSExtension_SignatureAlgorithms(
var Buffer; const Size: Integer;
const SignAndHashAlgos: TTLSSignatureAndHashAlgorithmArray): Integer;
var P : PByte;
L, N : Integer;
C, I : Integer;
begin
N := Size;
P := @Buffer;
Dec(N, 2);
if N < 0 then
raise ETLSError.Create(TLSError_InvalidBuffer);
{$IFDEF DELPHI7}
EncodeTLSWord16(P^, N, Ord(tlsetSignature_algorithms));
{$ELSE}
EncodeTLSWord16(P^, N, Ord(TTLSExtensionType.tlsetSignature_algorithms));
{$ENDIF}
Inc(P, 2);
C := Length(SignAndHashAlgos);
Assert(C > 0);
L := C * TLSSignatureAndHashAlgorithmSize;
EncodeTLSLen16(P^, N, L);
Inc(P, 2);
Dec(N, 2);
Dec(N, L);
if N < 0 then
raise ETLSError.Create(TLSError_InvalidBuffer);
for I := 0 to C - 1 do
begin
P^ := Ord(SignAndHashAlgos[I].Hash);
Inc(P);
P^ := Ord(SignAndHashAlgos[I].Signature);
Inc(P);
end;
Result := Size - N;
end;
end.
|
Program carro_preco_fabrica;
{O preço ao consumidor de um carro novo é a soma do custo de fábrica com a porcentagem do distribuidor e dos impostos,
ambos aplicados ao custo de fábrica. As porcentagens encontram-se na tabela a seguir. Faça um programa que receba
o custo de fábrica de um carro e mostre o preço ao consumidor.
Até R$ 12.000,00 - 5% - isento
Entre R$ 12.000,00 e R$ 25.000,00 - 10% - 15%
Acima de R$ 25.000,00 - 15% - 20%
}
var preco_fab, valor_final : real;
Begin
write('Informe o preço de fábrica do veículo: ');
readln(preco_fab);
if preco_fab <= 12000 then
begin
valor_final := preco_fab * 0.05 + preco_fab;
writeln('Porcentagem do distribuidor R$ ',preco_fab * 0.05:0:2);
writeln('Carros com valores até R$ 12.000 estão isento de impostos.');
writeln('Valo final do carro R$ ',valor_final:0:2);
end;
if (preco_fab > 12000) and (preco_fab <= 25000) then
begin
valor_final := preco_fab * 0.10 + preco_fab * 0.15 + preco_fab;
writeln('Porcentagem do distribuidor R$ ',preco_fab * 0.10:0:2);
writeln('Em um carro com preco de fábrica no valor de R$ ',preco_fab:0:0,' você irá pagar R$ ',preco_fab * 0.15:0:2,' de imposto.');
writeln('Valor final do carro R$ ',valor_final:0:2);
end;
if preco_fab > 25000 then
begin
valor_final := preco_fab * 0.15 + preco_fab * 0.20 + preco_fab;
writeln('Porcentagem do distribuidor R$ ',preco_fab * 0.15:0:2);
writeln('Em um carro com preco de fábrica no valor de R$ ',preco_fab:0:0,' você irá pagar R$ ',preco_fab * 0.20:0:2,' de imposto.');
writeln('Valor final do carro R$ ',valor_final:0:2);
end;
readln;
End. |
unit uDialogUtils;
interface
uses
Vcl.Dialogs;
type
TDialogUtils = class
private
class function CreateDialogTemplate(const aTdiType: Integer; const aCaption: string;
const aText: string; const aShowDirectly: Boolean; const aCreateDefaultButton: Boolean = False
): TTaskDialog;
public
class function ShowDeleteDialog(const aShowDirectly: Boolean = False): TTaskDialog;
class function ShowSaveDialog(const aShowDirectly: Boolean = False): TTaskDialog;
class function ShowErrorDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
class function ShowWarningDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
class function ShowInformationDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
end;
implementation
uses
Vcl.Controls;
{ TDialogUtils }
class function TDialogUtils.CreateDialogTemplate(const aTdiType: Integer;
const aCaption: string; const aText: string; const aShowDirectly: Boolean;
const aCreateDefaultButton: Boolean = False): TTaskDialog;
begin
Result := TTaskDialog.Create(nil);
with Result do
begin
if aCaption = '' then
begin
if aTdiType = tdiError then
Title := 'Error';
if aTdiType = tdiWarning then
Title := 'Warning';
if aTdiType = tdiInformation then
Title := 'Information';
end
else
Title := aCaption;
if aCreateDefaultButton then
begin
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'OK';
ModalResult := mrYes;
end;
end;
Text := aText;
CommonButtons := [];
Flags := [tfUseCommandLinks];
MainIcon := aTdiType;
end;
if aShowDirectly then
Result.Execute;
end;
class function TDialogUtils.ShowDeleteDialog(const aShowDirectly: Boolean = False): TTaskDialog;
begin
Result := TTaskDialog.Create(nil);
with Result do
begin
Title := 'Chcete skutečně smazat vybrané záznamy?';
CommonButtons := [];
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'Smazat';
CommandLinkHint := 'Trvale odstraní všechny vybrané záznamy.';
ModalResult := mrYes;
end;
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'Zrušit';
CommandLinkHint := 'Ukončí proces mazání.';
ModalResult := mrNo;
end;
Flags := [tfUseCommandLinks];
MainIcon := tdiNone;
end;
if aShowDirectly then
Result.Execute;
end;
class function TDialogUtils.ShowErrorDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
begin
Result := CreateDialogTemplate(tdiError, aCaption, aText, aShowDirectly, aCreateDefaultButton);
end;
class function TDialogUtils.ShowInformationDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
begin
Result := CreateDialogTemplate(tdiInformation, aCaption, aText, aShowDirectly, aCreateDefaultButton);
end;
class function TDialogUtils.ShowSaveDialog(const aShowDirectly: Boolean): TTaskDialog;
begin
Result := TTaskDialog.Create(nil);
with Result do
begin
Title := 'Chcete uložit provedené změny?';
CommonButtons := [];
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'Uložit';
CommandLinkHint := 'Uloží všechny provedené změny.';
ModalResult := mrYes;
end;
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'Ukončit';
CommandLinkHint := 'Ukončí formulář a provedené změny budou ztraceny.';
ModalResult := mrNo;
end;
with TTaskDialogButtonItem(Buttons.Add) do
begin
Caption := 'Zpět';
CommandLinkHint := 'Přeruší proces ukončování.';
ModalResult := mrAbort;
end;
Flags := [tfUseCommandLinks];
MainIcon := tdiNone;
end;
if aShowDirectly then
Result.Execute;
end;
class function TDialogUtils.ShowWarningDialog(const aShowDirectly: Boolean = False;
const aCaption: string = ''; const aText: string = '';
const aCreateDefaultButton: Boolean = False): TTaskDialog;
begin
Result := CreateDialogTemplate(tdiWarning, aCaption, aText, aShowDirectly, aCreateDefaultButton);
end;
end.
|
unit ym_2203;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
{$ifndef windows}main_engine,{$endif}
fmopn,ay_8910,timer_engine,sound_engine,cpu_misc;
type
ym2203_chip=class(snd_chip_class)
constructor create(clock:dword;amp:single=1;ay_amp:single=1);
destructor free;
public
procedure reset;
procedure update;
function status:byte;
function read:byte;
procedure control(data:byte);
procedure write(data:byte);
procedure change_irq_calls(irq_handler:type_irq_handler);
procedure change_io_calls(porta_read,portb_read:cpu_inport_call;porta_write,portb_write:cpu_outport_call);
function save_snapshot(data:pbyte):word;
procedure load_snapshot(data:pbyte);
private
OPN:pfm_opn;
REGS:array[0..255] of byte;
timer_adjust:single;
timer1,timer2,chip_number:byte;
ay8910_int:ay8910_chip;
procedure reset_channels(chan:byte);
procedure write_int(port,data:byte);
end;
var
ym2203_0,ym2203_1:ym2203_chip;
procedure ym2203_timer1(index:byte);
procedure ym2203_timer2(index:byte);
procedure ym2203_0_init_timer_a(count:single);
procedure ym2203_0_init_timer_b(count:single);
procedure ym2203_1_init_timer_a(count:single);
procedure ym2203_1_init_timer_b(count:single);
implementation
var
chips_total:integer=-1;
procedure change_ay_clock_0(clock:dword);
begin
if ym2203_0<>nil then ym2203_0.ay8910_int.change_clock(clock);
end;
procedure change_ay_clock_1(clock:dword);
begin
if ym2203_1<>nil then ym2203_1.ay8910_int.change_clock(clock);
end;
constructor ym2203_chip.create(clock:dword;amp:single;ay_amp:single);
begin
chips_total:=chips_total+1;
self.amp:=amp;
self.ay8910_int:=ay8910_chip.create(clock,AY8910,ay_amp,true); //El PSG
self.OPN:=opn_init(4); //Inicializo el OPN
//Inicializo el state
self.OPN.type_:=TYPE_YM2203;
self.OPN.ST.clock:=clock;
self.OPN.ST.rate:=FREQ_BASE_AUDIO;
self.tsample_num:=init_channel;
self.opn.ST.IRQ_Handler:=nil;
self.timer_adjust:=sound_status.cpu_clock/self.OPN.ST.clock;
self.chip_number:=chips_total;
self.timer1:=timers.init(sound_status.cpu_num,1,nil,ym2203_timer1,false,chips_total);
self.timer2:=timers.init(sound_status.cpu_num,1,nil,ym2203_timer2,false,chips_total);
case chips_total of
0:begin
self.OPN.ST.TIMER_set_a:=ym2203_0_init_timer_a;
self.OPN.ST.TIMER_set_b:=ym2203_0_init_timer_b;
self.OPN.ST.SSG_Clock_change:=change_ay_clock_0;
end;
1:begin
self.OPN.ST.TIMER_set_a:=ym2203_1_init_timer_a;
self.OPN.ST.TIMER_set_b:=ym2203_1_init_timer_b;
self.OPN.ST.SSG_Clock_change:=change_ay_clock_1;
end;
end;
self.Reset;
end;
procedure ym2203_chip.change_io_calls(porta_read,portb_read:cpu_inport_call;porta_write,portb_write:cpu_outport_call);
begin
self.ay8910_int.change_io_calls(porta_read,portb_read,porta_write,portb_write);
end;
procedure ym2203_chip.change_irq_calls(irq_handler:type_irq_handler);
begin
self.opn.ST.IRQ_Handler:=irq_handler;
end;
destructor ym2203_chip.free;
begin
//Cierro el OPN
opn_close(self.OPN);
self.OPN:=nil;
self.ay8910_int.Free;
chips_total:=chips_total-1;
end;
procedure ym2203_chip.Reset;
var
i:byte;
OPN:pfm_opn;
begin
OPN:=self.OPN;
// Reset Prescaler
OPNPrescaler_w(OPN,0,1);
// reset SSG section */
self.ay8910_int.reset;
// status clear */
FM_IRQMASK_SET(OPN.ST,$03);
OPNWriteMode(OPN,$27,$30); //mode 0 , timer reset
OPN.eg_timer:=0;
OPN.eg_cnt:=0;
FM_STATUS_RESET(OPN.ST,$ff);
opn.st.mode:=0; //normal mode
opn.st.TA:=0;
opn.ST.TAC:=0;
opn.ST.TB:=0;
opn.ST.TBC:=0;
self.reset_channels(4);
// reset OPerator paramater */
for i:=$b2 downto $30 do OPNWriteReg(OPN,i,0);
for i:=$26 downto $20 do OPNWriteReg(OPN,i,0);
end;
function ym2203_chip.save_snapshot(data:pbyte):word;
var
temp:pbyte;
size:word;
f:byte;
begin
temp:=data;
size:=self.ay8910_int.save_snapshot(temp);inc(temp,size);
copymemory(temp,@self.regs[0],$100);inc(temp,$100);size:=size+$100;
copymemory(temp,@self.timer_adjust,sizeof(single));inc(temp,sizeof(single));size:=size+sizeof(single);
temp^:=self.chip_number;inc(temp);size:=size+1;
//ST:pFM_state;
copymemory(temp,@self.opn.st.clock,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.st.rate,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.st.freqbase,sizeof(single));inc(temp,sizeof(single));size:=size+sizeof(single);
copymemory(temp,@self.opn.st.timer_prescaler,4);inc(temp,4);size:=size+4;
temp^:=self.opn.st.address;inc(temp);size:=size+1;
temp^:=self.opn.st.irq;inc(temp);size:=size+1;
temp^:=self.opn.st.irqmask;inc(temp);size:=size+1;
temp^:=self.opn.st.status;inc(temp);size:=size+1;
copymemory(temp,@self.opn.st.mode,4);inc(temp,4);size:=size+4;
temp^:=self.opn.st.prescaler_sel;inc(temp);size:=size+1;
temp^:=self.opn.st.fn_h;inc(temp);size:=size+1;
copymemory(temp,@self.opn.st.TA,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.st.TAC,sizeof(single));inc(temp,sizeof(single));size:=size+sizeof(single);
copymemory(temp,@self.opn.st.TB,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.st.TBC,sizeof(single));inc(temp,sizeof(single));size:=size+sizeof(single);
copymemory(temp,@self.opn.ST.dt_tab[0,0],8*32*4);inc(temp,8*32*4);size:=size+(8*32*4);
//resto
copymemory(temp,self.opn.SL3,sizeof(FM_3Slot));inc(temp,sizeof(FM_3Slot));size:=size+sizeof(FM_3Slot);
//channels 0..3
for f:=0 to 3 do begin
temp^:=self.opn.P_CH[f].ALGO;inc(temp);size:=size+1;
temp^:=self.opn.P_CH[f].FB;inc(temp);size:=size+1;
copymemory(temp,@self.opn.P_CH[f].op1_out[0],2*4);inc(temp,2*4);size:=size+(2*4);
copymemory(temp,@self.opn.P_CH[f].mem_value,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.P_CH[f].pms,4);inc(temp,4);size:=size+4;
temp^:=self.opn.P_CH[f].ams;inc(temp);size:=size+1;
copymemory(temp,@self.opn.P_CH[f].fc,4);inc(temp,4);size:=size+4;
temp^:=self.opn.P_CH[f].kcode;inc(temp);size:=size+1;
copymemory(temp,@self.opn.P_CH[f].block_fnum,4);inc(temp,4);size:=size+4;
copymemory(temp,self.opn.P_CH[f].SLOT[0],sizeof(fm_slot));inc(temp,sizeof(fm_slot));size:=size+sizeof(fm_slot);
copymemory(temp,self.opn.P_CH[f].SLOT[1],sizeof(fm_slot));inc(temp,sizeof(fm_slot));size:=size+sizeof(fm_slot);
copymemory(temp,self.opn.P_CH[f].SLOT[2],sizeof(fm_slot));inc(temp,sizeof(fm_slot));size:=size+sizeof(fm_slot);
copymemory(temp,self.opn.P_CH[f].SLOT[3],sizeof(fm_slot));inc(temp,sizeof(fm_slot));size:=size+sizeof(fm_slot);
end;
copymemory(temp,@self.opn.pan[0],12*4);inc(temp,12*4);size:=size+(12*4);
copymemory(temp,@self.opn.fn_table[0],4096*4);inc(temp,4096*4);size:=size+(4096*4);
copymemory(temp,@self.opn.lfo_freq[0],8*4);inc(temp,8*4);size:=size+(8*4);
temp^:=self.opn.type_;inc(temp);size:=size+1;
copymemory(temp,@self.opn.eg_cnt,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.eg_timer,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.eg_timer_add,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.eg_timer_overflow,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.fn_max,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.lfo_cnt,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.lfo_inc,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.m2,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.c1,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.c2,4);inc(temp,4);size:=size+4;
copymemory(temp,@self.opn.mem,4);size:=size+4;
save_snapshot:=size;
end;
procedure ym2203_chip.load_snapshot(data:pbyte);
var
temp:pbyte;
f:byte;
begin
temp:=data;
self.ay8910_int.load_snapshot(temp);inc(temp,128);
copymemory(@self.regs[0],temp,$100);inc(temp,$100);
copymemory(@self.timer_adjust,temp,sizeof(single));inc(temp,sizeof(single));
self.chip_number:=temp^;inc(temp);
//ST:pFM_state;
copymemory(@self.opn.st.clock,temp,4);inc(temp,4);
copymemory(@self.opn.st.rate,temp,4);inc(temp,4);
copymemory(@self.opn.st.freqbase,temp,sizeof(single));inc(temp,sizeof(single));
copymemory(@self.opn.st.timer_prescaler,temp,4);inc(temp,4);
self.opn.st.address:=temp^;inc(temp);
self.opn.st.irq:=temp^;inc(temp);
self.opn.st.irqmask:=temp^;inc(temp);
self.opn.st.status:=temp^;inc(temp);
copymemory(@self.opn.st.mode,temp,4);inc(temp,4);
self.opn.st.prescaler_sel:=temp^;inc(temp);
self.opn.st.fn_h:=temp^;inc(temp);
copymemory(@self.opn.st.TA,temp,4);inc(temp,4);
copymemory(@self.opn.st.TAC,temp,sizeof(single));inc(temp,sizeof(single));
copymemory(@self.opn.st.TB,temp,4);inc(temp,4);
copymemory(@self.opn.st.TBC,temp,sizeof(single));inc(temp,sizeof(single));
copymemory(@self.opn.ST.dt_tab[0,0],temp,8*32*4);inc(temp,8*32*4);
//resto
copymemory(self.opn.SL3,temp,sizeof(FM_3Slot));inc(temp,sizeof(FM_3Slot));
//Channels 0..3
for f:=0 to 3 do begin
self.opn.P_CH[f].ALGO:=temp^;inc(temp);
self.opn.P_CH[f].FB:=temp^;inc(temp);
copymemory(@self.opn.P_CH[f].op1_out[0],temp,2*4);inc(temp,2*4);
copymemory(@self.opn.P_CH[f].mem_value,temp,4);inc(temp,4);
copymemory(@self.opn.P_CH[f].pms,temp,4);inc(temp,4);
self.opn.P_CH[f].ams:=temp^;inc(temp);
copymemory(@self.opn.P_CH[f].fc,temp,4);inc(temp,4);
self.opn.P_CH[f].kcode:=temp^;inc(temp);
copymemory(@self.opn.P_CH[f].block_fnum,temp,4);inc(temp,4);
copymemory(self.opn.P_CH[f].SLOT[0],temp,sizeof(fm_slot));inc(temp,sizeof(fm_slot));
copymemory(self.opn.P_CH[f].SLOT[1],temp,sizeof(fm_slot));inc(temp,sizeof(fm_slot));
copymemory(self.opn.P_CH[f].SLOT[2],temp,sizeof(fm_slot));inc(temp,sizeof(fm_slot));
copymemory(self.opn.P_CH[f].SLOT[3],temp,sizeof(fm_slot));inc(temp,sizeof(fm_slot));
setup_connection(self.OPN,self.OPN.P_CH[f],self.chip_number);
self.opn.P_CH[f].SLOT[0].DT:=@self.OPN.ST.dt_tab[self.opn.P_CH[f].SLOT[0].det_mul_val];
self.opn.P_CH[f].SLOT[1].DT:=@self.OPN.ST.dt_tab[self.opn.P_CH[f].SLOT[1].det_mul_val];
self.opn.P_CH[f].SLOT[2].DT:=@self.OPN.ST.dt_tab[self.opn.P_CH[f].SLOT[2].det_mul_val];
self.opn.P_CH[f].SLOT[3].DT:=@self.OPN.ST.dt_tab[self.opn.P_CH[f].SLOT[3].det_mul_val];
end;
copymemory(@self.opn.pan[0],temp,12*4);inc(temp,12*4);
copymemory(@self.opn.fn_table[0],temp,4096*4);inc(temp,4096*4);
copymemory(@self.opn.lfo_freq[0],temp,8*4);inc(temp,8*4);
self.opn.type_:=temp^;inc(temp);
copymemory(@self.opn.eg_cnt,temp,4);inc(temp,4);
copymemory(@self.opn.eg_timer,temp,4);inc(temp,4);
copymemory(@self.opn.eg_timer_add,temp,4);inc(temp,4);
copymemory(@self.opn.eg_timer_overflow,temp,4);inc(temp,4);
copymemory(@self.opn.fn_max,temp,4);inc(temp,4);
copymemory(@self.opn.lfo_cnt,temp,4);inc(temp,4);
copymemory(@self.opn.lfo_inc,temp,4);inc(temp,4);
copymemory(@self.opn.m2,temp,4);inc(temp,4);
copymemory(@self.opn.c1,temp,4);inc(temp,4);
copymemory(@self.opn.c2,temp,4);inc(temp,4);
copymemory(@self.opn.mem,temp,4);
end;
procedure ym2203_chip.reset_channels(chan:byte);
var
c,s:byte;
OPN:pfm_opn;
begin
opn:=self.opn;
for c:=0 to chan-1 do begin
opn.p_CH[c].fc:=0;
for s:=0 to 3 do begin
opn.p_CH[c].SLOT[s].ssg:=0;
opn.p_CH[c].SLOT[s].ssgn:=0;
opn.p_CH[c].SLOT[s].state:=EG_OFF;
opn.p_CH[c].SLOT[s].volume:=MAX_ATT_INDEX;
opn.p_CH[c].SLOT[s].vol_out:=MAX_ATT_INDEX;
end;
end;
end;
procedure ym2203_chip.update;
var
OPN:pfm_opn;
lt:integer;
cch:array[0..2] of pfm_chan;
begin
OPN:=self.OPN;
cch[0]:=OPN.p_CH[0];
cch[1]:=OPN.p_CH[1];
cch[2]:=OPN.p_CH[2];
// refresh PG and EG */
refresh_fc_eg_chan(OPN,cch[0]);
refresh_fc_eg_chan(OPN,cch[1]);
if ((OPN.ST.mode and $c0)<>0) then begin
// 3SLOT MODE */
if (cch[2].SLOT[SLOT1].Incr=-1) then begin
refresh_fc_eg_slot(OPN,cch[2].SLOT[SLOT1],OPN.SL3.fc[1],OPN.SL3.kcode[1] );
refresh_fc_eg_slot(OPN,cch[2].SLOT[SLOT2],OPN.SL3.fc[2],OPN.SL3.kcode[2] );
refresh_fc_eg_slot(OPN,cch[2].SLOT[SLOT3],OPN.SL3.fc[0],OPN.SL3.kcode[0] );
refresh_fc_eg_slot(OPN,cch[2].SLOT[SLOT4],cch[2].fc,cch[2].kcode );
end;
end else begin
refresh_fc_eg_chan(OPN,cch[2]);
end;
// YM2203 doesn't have LFO so we must keep these globals at 0 level */
LFO_AM:= 0;
LFO_PM:= 0;
// buffering */
out_fm[0]:= 0;
out_fm[1]:= 0;
out_fm[2]:= 0;
// advance envelope generator */
OPN.eg_timer:=OPN.eg_timer+OPN.eg_timer_add;
while (OPN.eg_timer>=OPN.eg_timer_overflow) do begin
OPN.eg_timer:=OPN.eg_timer-OPN.eg_timer_overflow;
OPN.eg_cnt:=OPN.eg_cnt+1;
advance_eg_channel(OPN,cch[0]);
advance_eg_channel(OPN,cch[1]);
advance_eg_channel(OPN,cch[2]);
end;
// calculate FM
chan_calc(OPN,cch[0]);
chan_calc(OPN,cch[1]);
chan_calc(OPN,cch[2]);
lt:=self.ay8910_int.update_internal^;
lt:=lt+trunc((out_fm[0]+out_fm[1]+out_fm[2])*self.amp);
if lt>$7fff then lt:=$7fff
else if lt<-$7fff then lt:=-$7fff;
tsample[self.tsample_num,sound_status.posicion_sonido]:=lt;
if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=lt;
INTERNAL_TIMER_A(self.OPN.ST,self.OPN.p_ch[2]);
INTERNAL_TIMER_B(self.OPN.ST)
end;
procedure ym2203_chip.write_int(port,data:byte);
var
OPN:pfm_opn;
addr:integer;
begin
OPN:=self.OPN;
if ((port and 1)=0) then begin // address port */
OPN.ST.address:=data;
// Write register to SSG emulator */
if (data<$10) then self.ay8910_int.Control(data);
// prescaler select : 2d,2e,2f */
if ((data>=$2d) and (data<=$2f)) then OPNPrescaler_w(OPN,data,1);
end else begin // data port */
addr:=OPN.ST.address;
self.REGS[addr]:=data;
case (addr and $f0) of
$00:begin // 0x00-0x0f : SSG section */
self.ay8910_int.Write(data); // Write data to SSG emulator */
end;
$20:begin // 0x20-0x2f : Mode section */
//YM2203UpdateReq(n);
// write register */
OPNWriteMode(OPN,addr,data);
end;
else begin // 0x30-0xff : OPN section */
//YM2203UpdateReq(n);
// write register */
OPNWriteReg(OPN,addr,data);
end;
end;
end;
end;
function ym2203_chip.status:byte;
begin
status:=self.OPN.ST.status;
end;
function ym2203_chip.read:byte;
var
ret:byte;
begin
if (self.OPN.ST.address<16) then ret:=self.ay8910_int.Read
else ret:=0;
read:=ret;
end;
procedure ym2203_chip.control(data:byte);
begin
self.write_int(0,data);
end;
procedure ym2203_chip.write(data:byte);
begin
self.write_int(1,data);
end;
procedure ym2203_timer1(index:byte);
var
chip:ym2203_chip;
begin
case index of
0:chip:=ym2203_0;
1:chip:=ym2203_1;
end;
TimerAOver(chip.OPN.ST);
if (chip.OPN.ST.mode and $80)<>0 then begin
// CSM mode auto key on */
CSMKeyControll(chip.OPN.p_ch[2]);
end;
end;
procedure ym2203_timer2(index:byte);
begin
case index of
0:TimerBOver(ym2203_0.OPN.ST);
1:TimerBOver(ym2203_1.OPN.ST);
end;
end;
procedure change_timer_status(timer_num:byte;timer_adjust:single);
begin
if timer_adjust=0 then timers.enabled(timer_num,false)
else begin
timers.enabled(timer_num,true);
timers.timer[timer_num].time_final:=timer_adjust;
end;
end;
procedure ym2203_0_init_timer_a(count:single);
begin
change_timer_status(ym2203_0.timer1,count*ym2203_0.timer_adjust);
end;
procedure ym2203_0_init_timer_b(count:single);
begin
change_timer_status(ym2203_0.timer2,count*ym2203_0.timer_adjust);
end;
procedure ym2203_1_init_timer_a(count:single);
begin
change_timer_status(ym2203_1.timer1,count*ym2203_1.timer_adjust);
end;
procedure ym2203_1_init_timer_b(count:single);
begin
change_timer_status(ym2203_1.timer2,count*ym2203_1.timer_adjust);
end;
end.
|
unit FFSColorCollection;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
FFSTypes;
type
TFFSColorCollectionItem = class(TCollectionItem)
private
FGridSelect: TColor;
FActionText: TColor;
FMainStatusBar: TColor;
FDataBackground: TColor;
FTabInactive: TColor;
FTabNormalText: TColor;
FTabBackground: TColor;
FActionHighlight: TColor;
FGridHighlight: TColor;
FDataText: TColor;
FDataLabel: TColor;
FGridLowlight: TColor;
FFormStatusBar: TColor;
FActionRollover: TColor;
FTabDataText: TColor;
FDataUnderline: TColor;
FFormActionBar: TColor;
FMainFormBar: TColor;
FTabActive: TColor;
FGridTitlebar: TColor;
FMainFormBarText: TColor;
FActiveEntryField: TColor;
FListText: TColor;
FListSelectedText: TColor;
FListBackground: TColor;
FListRollover: TColor;
FListSelected: TColor;
FCaptions: TColor;
FCaption: String;
FIs256Color: boolean;
FActive: boolean;
procedure SetActionHighlight(const Value: TColor);
procedure SetActionRollover(const Value: TColor);
procedure SetActionText(const Value: TColor);
procedure SetDataBackground(const Value: TColor);
procedure SetDataLabel(const Value: TColor);
procedure SetDataText(const Value: TColor);
procedure SetDataUnderline(const Value: TColor);
procedure SetFormActionBar(const Value: TColor);
procedure SetFormStatusBar(const Value: TColor);
procedure SetGridHighlight(const Value: TColor);
procedure SetGridLowlight(const Value: TColor);
procedure SetGridSelect(const Value: TColor);
procedure SetGridTitlebar(const Value: TColor);
procedure SetMainFormBar(const Value: TColor);
procedure SetMainStatusBar(const Value: TColor);
procedure SetTabActive(const Value: TColor);
procedure SetTabBackground(const Value: TColor);
procedure SetTabDataText(const Value: TColor);
procedure SetTabInactive(const Value: TColor);
procedure SetTabNormalText(const Value: TColor);
procedure SetMainFormBarText(const Value: TColor);
procedure SetActiveEntryField(const Value: TColor);
procedure SetListBackground(const Value: TColor);
procedure SetListRollover(const Value: TColor);
procedure SetListSelected(const Value: TColor);
procedure SetListSelectedText(const Value: TColor);
procedure SetListText(const Value: TColor);
procedure SetCaptions(const Value: TColor);
procedure SetIs256Color(const Value: boolean);
procedure SetActive(const Value: boolean);
{ Private declarations }
protected
function GetDisplayName: string; override;
procedure SetCaption( const Value: string ); virtual;
public
{ Public declarations }
procedure ApplyColors;
constructor Create(Collection: TCollection);override;
published
{ Published declarations }
property Active: boolean read FActive write SetActive default False;
property DisplayCaption: string read FCaption write SetCaption;
property Is256Color : boolean read FIs256Color write SetIs256Color default false;
property DataBackground:TColor read FDataBackground write SetDataBackground default clWhite;
property ActiveEntryField : TColor read FActiveEntryField write SetActiveEntryField default $00EBEBEB;
property DataLabel:TColor read FDataLabel write SetDataLabel default clBlack;
property DataText:TColor read FDataText write SetDataText default clNavy;
property DataUnderline:TColor read FDataUnderline write SetDataUnderline default clSilver;
property ActionText:TColor read FActionText write SetActionText default clBlack;
property ActionHighlight:TColor read FActionHighlight write SetActionHighlight default clMaroon;
property ActionRollover:TColor read FActionRollover write SetActionRollover default clBlue;
property MainStatusBar:TColor read FMainStatusBar write SetMainStatusBar;
property MainFormBar:TColor read FMainFormBar write SetMainFormBar;
property MainFormBarText:TColor read FMainFormBarText write SetMainFormBarText;
property FormStatusBar:TColor read FFormStatusBar write SetFormStatusBar;
property FormActionBar:TColor read FFormActionBar write SetFormActionBar;
property TabActive:TColor read FTabActive write SetTabActive;
property TabInactive:TColor read FTabInactive write SetTabInactive;
property TabBackground:TColor read FTabBackground write SetTabBackground;
property TabNormalText:TColor read FTabNormalText write SetTabNormalText;
property TabDataText:TColor read FTabDataText write SetTabDataText;
property GridHighlight:TColor read FGridHighlight write SetGridHighlight;
property GridLowlight:TColor read FGridLowlight write SetGridLowlight;
property GridSelect:TColor read FGridSelect write SetGridSelect;
property GridTitlebar:TColor read FGridTitlebar write SetGridTitlebar;
property ListBackground:TColor read FListBackground write SetListBackground;
property ListRollover:TColor read FListRollover write SetListRollover;
property ListText:TColor read FListText write SetListText;
property ListSelected:TColor read FListSelected write SetListSelected;
property ListSelectedText:TColor read FListSelectedText write SetListSelectedText;
property Captions:TColor read FCaptions Write SetCaptions;
end;
TFFSColorSchemes = class;
TFFSColorCollection = class(TCollection)
private
FScheme: TFFSColorSchemes;
function GetItem(Index: integer) : TFFSColorCollectionItem;
procedure SetItem(Index: integer; Value : TFFSColorCollectionItem);
protected
function GetOwner: TPersistent; override;
procedure Update( Item: TCollectionItem ); override;
public
function Add: TFFSColorCollectionItem;
constructor Create(AScheme : TFFSColorSchemes);
property Items[Index: integer]: TFFSColorCollectionItem read GetItem write SetItem; default;
published
{ Published declarations }
end;
TFFSColorSchemes = class(TComponent)
private
FSchemes : TFFSColorCollection;
FActiveScheme : string;
procedure ApplyScheme(ASchemeName: string);
protected
procedure SetScheme( Value: TFFSColorCollection ); virtual;
public
procedure AddScheme( AValue: Integer);
function IndexOf(AScheme: string): integer;
constructor Create( AOwner: TComponent ); override;
destructor Destroy; override;
published
property ActiveScheme : string read FActiveScheme Write ApplyScheme;
property Schemes: TFFSColorCollection read FSchemes write SetScheme;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Controls', [TFFSColorSchemes]);
end;
procedure TFFSColorCollectionItem.SetActionHighlight(const Value: TColor);
begin
FActionHighlight := Value;
end;
procedure TFFSColorCollectionItem.SetActionRollover(const Value: TColor);
begin
FActionRollover := Value;
end;
procedure TFFSColorCollectionItem.SetActionText(const Value: TColor);
begin
FActionText := Value;
end;
procedure TFFSColorCollectionItem.SetDataBackground(const Value: TColor);
begin
FDataBackground := Value;
end;
procedure TFFSColorCollectionItem.SetDataLabel(const Value: TColor);
begin
FDataLabel := Value;
end;
procedure TFFSColorCollectionItem.SetDataText(const Value: TColor);
begin
FDataText := Value;
end;
procedure TFFSColorCollectionItem.SetDataUnderline(const Value: TColor);
begin
FDataUnderline := Value;
end;
procedure TFFSColorCollectionItem.SetFormActionBar(const Value: TColor);
begin
FFormActionBar := Value;
end;
procedure TFFSColorCollectionItem.SetFormStatusBar(const Value: TColor);
begin
FFormStatusBar := Value;
end;
procedure TFFSColorCollectionItem.SetGridHighlight(const Value: TColor);
begin
FGridHighlight := Value;
end;
procedure TFFSColorCollectionItem.SetGridLowlight(const Value: TColor);
begin
FGridLowlight := Value;
end;
procedure TFFSColorCollectionItem.SetGridSelect(const Value: TColor);
begin
FGridSelect := Value;
end;
procedure TFFSColorCollectionItem.SetGridTitlebar(const Value: TColor);
begin
FGridTitlebar := Value;
end;
procedure TFFSColorCollectionItem.SetMainFormBar(const Value: TColor);
begin
FMainFormBar := Value;
end;
procedure TFFSColorCollectionItem.SetMainStatusBar(const Value: TColor);
begin
FMainStatusBar := Value;
end;
procedure TFFSColorCollectionItem.SetTabActive(const Value: TColor);
begin
FTabActive := Value;
end;
procedure TFFSColorCollectionItem.SetTabBackground(const Value: TColor);
begin
FTabBackground := Value;
end;
procedure TFFSColorCollectionItem.SetTabDataText(const Value: TColor);
begin
FTabDataText := Value;
end;
procedure TFFSColorCollectionItem.SetTabInactive(const Value: TColor);
begin
FTabInactive := Value;
end;
procedure TFFSColorCollectionItem.SetTabNormalText(const Value: TColor);
begin
FTabNormalText := Value;
end;
procedure TFFSColorCollectionItem.ApplyColors;
var m : TMessage;
i : integer;
begin
FFSColor[fcsDataBackground] := FDataBackground;
FFSColor[fcsDataLabel] := FDataLabel;
FFSColor[fcsActiveEntryField] := FActiveEntryField;
FFSColor[fcsDataText] := FDataText;
FFSColor[fcsDataUnderline] := FDataUnderline;
FFSColor[fcsActionText] := FActionText;
FFSColor[fcsActionRollover] := FActionRollover;
FFSColor[fcsMainStatusBar] := FMainStatusBar;
FFSColor[fcsMainFormBar] := FMainFormBar;
FFSColor[fcsMainFormBarText] := FMainFormBarText;
FFSColor[fcsFormStatusBar] := FFormStatusBar;
FFSColor[fcsFormActionBar] := FFormActionBar;
FFSColor[fcsTabActive] := FTabActive;
FFSColor[fcsTabInactive] := FTabInactive;
FFSColor[fcsTabBackground] := FTabBackground;
FFSColor[fcsTabNormalText] := FTabNormalText;
FFSColor[fcsTabDataText] := FTabDataText;
FFSColor[fcsGridHighlight] := FGridHighlight;
FFSColor[fcsGridLowlight] := FGridLowlight;
FFSColor[fcsGridSelect] := FGridSelect;
FFSColor[fcsGridTitlebar] := FGridTitlebar;
FFSColor[fcsListBackground] := FListBackground;
FFSColor[fcsListRollover] := FListRollover;
FFSColor[fcsListSelected] := FListSelected;
FFSColor[fcsListText] := FListText;
FFSColor[fcsListSelectedText] := FListSelectedText;
FFSColor[fcsCaptions] := FCaptions;
// now send a message to the application that the colors have changed
m.Msg := Msg_FFSColorChange;
m.WParam := 0;
m.LParam := 0;
m.Result := 0;
for i := 0 to Screen.FormCount-1 do begin
Screen.Forms[i].Broadcast(m);
end;
end;
constructor TFFSColorCollectionItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FDataBackground := FFSColor[fcsDataBackground];
FDataLabel := FFSColor[fcsDataLabel];
FActiveEntryField := FFSColor[fcsActiveEntryField];
FDataText := FFSColor[fcsDataText];
FDataUnderline := FFSColor[fcsDataUnderline];
FActionText := FFSColor[fcsActionText];
FActionRollover := FFSColor[fcsActionRollover];
FMainStatusBar := FFSColor[fcsMainStatusBar];
FMainFormBar := FFSColor[fcsMainFormBar];
FMainFormBarText := FFSColor[fcsMainFormBarText];
FFormStatusBar := FFSColor[fcsFormStatusBar];
FFormActionBar := FFSColor[fcsFormActionBar];
FTabActive := FFSColor[fcsTabActive];
FTabInactive := FFSColor[fcsTabInactive];
FTabBackground := FFSColor[fcsTabBackground];
FTabNormalText := FFSColor[fcsTabNormalText];
FTabDataText := FFSColor[fcsTabDataText];
FGridHighlight := FFSColor[fcsGridHighlight];
FGridLowlight := FFSColor[fcsGridLowlight];
FGridSelect := FFSColor[fcsGridSelect];
FGridTitlebar := FFSColor[fcsGridTitlebar];
FListBackground := FFSColor[fcsListBackground];
FListRollover := FFSColor[fcsListRollover];
FListSelected := FFSColor[fcsListSelected];
FListText := FFSColor[fcsListText];
FListSelectedText := FFSColor[fcsListSelectedText];
FCaptions := FFSColor[fcsCaptions];
end;
procedure TFFSColorCollectionItem.SetMainFormBarText(const Value: TColor);
begin
FMainFormBarText := Value;
end;
procedure TFFSColorCollectionItem.SetActiveEntryField(const Value: TColor);
begin
FActiveEntryField := Value;
end;
procedure TFFSColorCollectionItem.SetListBackground(const Value: TColor);
begin
FListBackground := Value;
end;
procedure TFFSColorCollectionItem.SetListRollover(const Value: TColor);
begin
FListRollover := Value;
end;
procedure TFFSColorCollectionItem.SetListSelected(const Value: TColor);
begin
FListSelected := Value;
end;
procedure TFFSColorCollectionItem.SetListSelectedText(const Value: TColor);
begin
FListSelectedText := Value;
end;
procedure TFFSColorCollectionItem.SetListText(const Value: TColor);
begin
FListText := Value;
end;
procedure TFFSColorCollectionItem.SetCaptions(const Value: TColor);
begin
FCaptions := Value;
end;
{ TFFSColorCollection }
function TFFSColorCollection.Add: TFFSColorCollectionItem;
begin
Result := TFFSColorCollectionItem( inherited Add );
end;
constructor TFFSColorCollection.Create(AScheme : TFFSColorSchemes);
begin
inherited Create(TFFSColorCollectionItem);
FScheme := AScheme;
end;
function TFFSColorCollection.GetItem(Index: integer): TFFSColorCollectionItem;
begin
Result := TFFSColorCollectionItem( inherited GetItem(Index));
end;
function TFFSColorCollection.GetOwner: TPersistent;
begin
Result := FScheme;
end;
procedure TFFSColorCollection.SetItem(Index: integer; Value: TFFSColorCollectionItem);
begin
inherited SetItem( Index, Value );
end;
procedure TFFSColorCollection.Update(Item: TCollectionItem);
begin
//FScheme.Refresh;
end;
{ TFFSColorSchemes }
procedure TFFSColorSchemes.AddScheme(AValue: Integer);
begin
//
end;
procedure TFFSColorSchemes.ApplyScheme(ASchemeName: string);
var i: integer;
begin
for i := 0 to FSchemes.Count - 1 do begin
if Uppercase(FSchemes.Items[i].DisplayCaption) = Uppercase(ASchemeName) then begin
FActiveScheme := ASchemeName;
FSchemes.Items[i].ApplyColors;
end;
end;
end;
constructor TFFSColorSchemes.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSchemes := TFFSColorCollection.Create(self);
FActiveScheme := '';
end;
destructor TFFSColorSchemes.Destroy;
begin
FSchemes.Free;
inherited Destroy;
end;
function TFFSColorSchemes.IndexOf(AScheme: string): integer;
var i: integer;
begin
Result := 0;
for i := 0 to FSchemes.Count - 1 do begin
if Uppercase(FSchemes.Items[i].DisplayCaption) = Uppercase(AScheme) then
Result := i;
end;
end;
procedure TFFSColorSchemes.SetScheme(Value: TFFSColorCollection);
begin
FSchemes.Assign(Value);
end;
function TFFSColorCollectionItem.GetDisplayName: string;
begin
Result := FCaption;
if Result = '' then Result := inherited GetDisplayName;
end;
procedure TFFSColorCollectionItem.SetCaption(const Value: string);
begin
if FCaption <> Value then begin
FCaption := Value;
Changed(False);
end;
end;
procedure TFFSColorCollectionItem.SetIs256Color(const Value: boolean);
begin
FIs256Color := Value;
end;
procedure TFFSColorCollectionItem.SetActive(const Value: boolean);
begin
FActive := Value;
end;
end.
|
unit DW.OSDevice.iOS;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// DW
DW.OSDevice;
type
/// <remarks>
/// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS
/// </remarks>
TPlatformOSDevice = record
public
class function GetCurrentLocaleInfo: TLocaleInfo; static;
class function GetDeviceName: string; static;
class function GetPackageID: string; static;
class function GetPackageVersion: string; static;
class function GetUniqueDeviceID: string; static;
class function IsScreenLocked: Boolean; static;
class function IsTouchDevice: Boolean; static;
end;
implementation
uses
// RTL
System.SysUtils,
// Mac
Macapi.Helpers,
// iOS
iOSapi.Helpers,
// DW
DW.Macapi.Helpers, DW.iOSapi.Foundation;
{ TPlatformOSDevice }
class function TPlatformOSDevice.GetCurrentLocaleInfo: TLocaleInfo;
var
LLocale: NSLocale;
begin
LLocale := TNSLocale.Wrap(TNSLocale.OCClass.currentLocale);
Result.LanguageCode := NSStrToStr(LLocale.languageCode);
Result.LanguageDisplayName := NSStrToStr(LLocale.localizedStringForLanguageCode(LLocale.languageCode));
Result.CountryCode := NSStrToStr(LLocale.countryCode);
Result.CountryDisplayName := NSStrToStr(LLocale.localizedStringForCountryCode(LLocale.countryCode));
Result.CurrencySymbol := NSStrToStr(LLocale.currencySymbol);
end;
class function TPlatformOSDevice.GetDeviceName: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.name);
end;
class function TPlatformOSDevice.GetUniqueDeviceID: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.identifierForVendor.UUIDString);
end;
class function TPlatformOSDevice.IsScreenLocked: Boolean;
begin
Result := False; // To be implemented
end;
class function TPlatformOSDevice.IsTouchDevice: Boolean;
begin
Result := True;
end;
class function TPlatformOSDevice.GetPackageID: string;
begin
Result := TMacHelperEx.GetBundleValue('CFBundleIdentifier');
end;
class function TPlatformOSDevice.GetPackageVersion: string;
begin
Result := TMacHelperEx.GetBundleValue('CFBundleVersion');
end;
end.
|
program powerWIN;
uses
SysUtils, Process;
(* BANNER *)
function banner() :string;
begin
writeln('');
writeln(' -------------------- powerWIN ---------------------');
writeln('| |');
writeln('| example : powerwin.exe [OPTIONS.....] |');
writeln('| OPTIONS : |');
writeln('| [ -h | --help ] .......... about this tool |');
writeln('| [ -slp | --sleep ] ....... sleep option |');
writeln('| [ -rst | --restart ] ..... restart option |');
writeln('| [ -shd | --shutdown ] .... shutdown option |');
writeln('| |');
writeln(' --------------------------------------------------- ');
banner:='';
end;
(* SLEEP *)
function sleep() :string;
begin
ExecuteProcess('cmd','/c rundll32.exe powrprof.dll, SetSuspendState Sleep');
sleep:='';
end;
(* RESTART *)
function restart() :string;
begin
ExecuteProcess('cmd','/c shutdown /r');
restart:='';
end;
(* SHUTDOWN *)
function shutdown() :string;
begin
ExecuteProcess('cmd','/c shutdown /s');
shutdown:='';
end;
var
OPTION :string;
begin
OPTION := ParamStr(1);
(* OPTIONS *)
if ( OPTION = '-h' ) or ( OPTION = '--help' ) then
begin
banner();
end
else if ( OPTION = '-slp' ) or ( OPTION = '--sleep' ) then
begin
sleep();
end
else if ( OPTION = '-rst' ) or ( OPTION = '--restart' ) then
begin
restart();
end
else if ( OPTION = '-shd' ) or ( OPTION = '--shutdown' ) then
begin
shutdown();
end
else
begin
banner();
end;
end.
|
unit AST.Delphi.Project;
interface
uses AST.Classes,
AST.Pascal.Project,
AST.Delphi.Parser,
AST.Delphi.Classes;
type
TASTDelphiProject = class(TNPPackage)
protected
function GetUnitClass: TASTUnitClass; override;
end;
implementation
{ TASTDelphiProject }
function TASTDelphiProject.GetUnitClass: TASTUnitClass;
begin
Result := TASTDelphiUnit;
end;
end.
|
// ***************************************************************************
//
// FMXComponents: Firemonkey Opensource Components Set from China
//
// CalendarControl is a calendar component like iOS style, it uses
// listview component internally
//
// This component come from xubzhlin's FMX-UI-Controls, collect and
// arrange by the author's agreement
// The original project at: https://github.com/xubzhlin/FMX-UI-Controls
//
// 该控件来自 xubzhlin的FMX-UI-Controls项目,经作者同意进行收集整理
// 原项目地址为:https://github.com/xubzhlin/FMX-UI-Controls
//
// https://github.com/zhaoyipeng/FMXComponents
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// *************************************************************************** }
// 2017-09-11, v0.1.0.0 :
// first release
// 2017-09-11, v0.2.0.0 :
// add lunar date display option
// add 24 solar terms
// 2017-09-11, v0.2.1.0 :
// small improve in render method
unit FMX.CalendarItemAppearance;
interface
uses
System.Classes, System.SysUtils, FMX.Types, FMX.Controls, System.UITypes,
FMX.Objects, FMX.ListView, FMX.Graphics, System.Types, System.Rtti,
FMX.ListView.Types, FMX.ListView.Appearances, System.DateUtils, System.Math;
type
TClendarListItemAppearanceNames = class
public const
ListItem = 'ClendarDayListItem';
YearItemName = 'YearItemName';
SunItemName = 'SunItemName';
MonItmeName = 'MonItmeName';
TurItmeName = 'TurItmeName';
WedItemName = 'WedItemName';
ThuItemName = 'ThuItemName';
RuiItemName = 'RuiItemName';
SatItemName = 'SatItemName';
end;
TClendarWeekListViewItem = class;
TClendarDayItem = class;
TOnGetItemIsMark = procedure(ADayItem:TClendarDayItem; var AIsMark:Boolean) of object;
TClendarDayItem = class(TListItemDrawable)
private
FOwner:TClendarWeekListViewItem;
FIsPressed: Boolean;
FIsSelected: Boolean;
FDayText:String;
FDay: TDate;
FBitmap: TBitmap;
function GetIsMark: Boolean;
procedure SetDay(const Value: TDate);
procedure SetIsPressed(const Value: Boolean);
procedure SetIsSelected(const Value: Boolean);
procedure DoDrawBitmap(Canvas: TCanvas);
public
procedure Render(const Canvas: TCanvas; const DrawItemIndex: Integer;
const DrawStates: TListItemDrawStates;
const Resources: TListItemStyleResources; const Params: TListItemDrawable.TParams;
const SubPassNo: Integer = 0); override;
constructor Create(const AOwner: TListItem); override;
destructor Destroy; override;
published
property IsPressed: Boolean read FIsPressed write SetIsPressed;
property IsSelected: Boolean read FIsSelected write SetIsSelected;
property Day: TDate read FDay write SetDay;
end;
TClendarDayObjectAppearance = class(TCommonObjectAppearance)
protected
procedure AssignTo(ADest: TPersistent); override;
public
procedure CreateObject(const AListViewItem: TListViewItem); override;
procedure ResetObject(const AListViewItem: TListViewItem); override;
end;
TClendarYearItem = class(TListItemDrawable)
private
FYear:Word;
FYearText:String;
procedure SetYear(const Value: Word);
public
procedure Render(const Canvas: TCanvas; const DrawItemIndex: Integer;
const DrawStates: TListItemDrawStates;
const Resources: TListItemStyleResources; const Params: TListItemDrawable.TParams;
const SubPassNo: Integer = 0); override;
published
property Year:Word read FYear write SetYear;
end;
TClendarYearObjectAppearance = class(TCommonObjectAppearance)
protected
procedure AssignTo(ADest: TPersistent); override;
public
procedure CreateObject(const AListViewItem: TListViewItem); override;
procedure ResetObject(const AListViewItem: TListViewItem); override;
end;
TClendarWeekListViewItem = class(TListViewItem)
private
function GetClendarDayItem(AName: String): TClendarDayItem;
function GetSunDayItem:TClendarDayItem;
function GetMonDayItem:TClendarDayItem;
function GetTurDayItem:TClendarDayItem;
function GetWedDayItem:TClendarDayItem;
function GetThuDayItem:TClendarDayItem;
function GetRuiDayItem:TClendarDayItem;
function GetSatDayItem:TClendarDayItem;
function GetYearItem: TClendarYearItem;
public
function FindDayItem(ADate:Int64):TClendarDayItem;
function GetIsMark(ADayItem:TClendarDayItem):Boolean;
published
property YearItem:TClendarYearItem read GetYearItem;
property SunDayItem:TClendarDayItem read GetSunDayItem;
property MonDayItem:TClendarDayItem read GetMonDayItem;
property TurDayItem:TClendarDayItem read GetTurDayItem;
property WedDayItem:TClendarDayItem read GetWedDayItem;
property ThuDayItem:TClendarDayItem read GetThuDayItem;
property RuiDayItem:TClendarDayItem read GetRuiDayItem;
property SatDayItem:TClendarDayItem read GetSatDayItem;
end;
TCalenderView = class(TListView)
private
FOnGetItemIsMark:TOnGetItemIsMark;
protected
procedure ApplyStyle; override;
function GetDefaultStyleLookupName: string; override;
published
property OnGetItemIsMark:TOnGetItemIsMark read FOnGetItemIsMark write FOnGetItemIsMark;
end;
implementation
uses
qcndate,
FMX.CalendarControl;
type
TClendarDayListItemAppearance = class(TPresetItemObjects)
public const
cDefaultHeight = 50;
private
FYear: TClendarYearObjectAppearance;
FSunDay: TClendarDayObjectAppearance;
FMonDay: TClendarDayObjectAppearance;
FTurDay: TClendarDayObjectAppearance;
FWedDay: TClendarDayObjectAppearance;
FThuDay: TClendarDayObjectAppearance;
FRuiDay: TClendarDayObjectAppearance;
FSatDay: TClendarDayObjectAppearance;
procedure SetMonDay(const Value: TClendarDayObjectAppearance);
procedure SetRuiDay(const Value: TClendarDayObjectAppearance);
procedure SetSatDay(const Value: TClendarDayObjectAppearance);
procedure SetSunDay(const Value: TClendarDayObjectAppearance);
procedure SetThuDay(const Value: TClendarDayObjectAppearance);
procedure SetTurDay(const Value: TClendarDayObjectAppearance);
procedure SetWedDay(const Value: TClendarDayObjectAppearance);
function CreateClendarDayObject(AName: String): TClendarDayObjectAppearance;
procedure SetYear(const Value: TClendarYearObjectAppearance);
protected
function DefaultHeight: Integer; override;
procedure UpdateSizes(const ItemSize: TSizeF); override;
function GetGroupClass: TPresetItemObjects.TGroupClass; override;
public
constructor Create(const Owner: TControl); override;
destructor Destroy; override;
published
property Year: TClendarYearObjectAppearance read FYear write SetYear;
property SunDay: TClendarDayObjectAppearance read FSunDay write SetSunDay;
property MonDay: TClendarDayObjectAppearance read FMonDay write SetMonDay;
property TurDay: TClendarDayObjectAppearance read FTurDay write SetTurDay;
property WedDay: TClendarDayObjectAppearance read FWedDay write SetWedDay;
property ThuDay: TClendarDayObjectAppearance read FThuDay write SetThuDay;
property RuiDay: TClendarDayObjectAppearance read FRuiDay write SetRuiDay;
property SatDay: TClendarDayObjectAppearance read FSatDay write SetSatDay;
end;
{ TClendarDayItem }
constructor TClendarDayItem.Create(const AOwner: TListItem);
begin
inherited;
FOwner := TClendarWeekListViewItem(AOwner);
FIsPressed := False;
FIsSelected := False;
FDay := 0;
end;
destructor TClendarDayItem.Destroy;
begin
FBitMap.Free;
FBitMap:=nil;
inherited;
end;
procedure TClendarDayItem.DoDrawBitmap(Canvas: TCanvas);
var
AtPoint1,AtPoint2:TPointF;
Scale:Single;
begin
if FBitMap = nil then
begin
Scale := Canvas.Scale;
FBitMap := TBitMap.Create(Trunc(LocalRect.Width * Scale), Trunc(LocalRect.Height * Scale));
FBitMap.Clear(0);
AtPoint1 := TPointF.Create(0, 1);
AtPoint2 := TPointF.Create(FBitMap.Width, 1);
FBitMap.Canvas.BeginScene(nil);
FBitMap.Canvas.Stroke.Kind := TBrushKind.Solid;
FBitMap.Canvas.Stroke.Color := TAlphaColors.Cadetblue;
FBitMap.Canvas.Stroke.Thickness := 1;
FBitMap.Canvas.DrawLine(AtPoint1, AtPoint2, 1);
FBitMap.Canvas.EndScene;
end;
Canvas.DrawBitmap(FBitMap, RectF(0, 0, FBitMap.Width, FBitMap.Height), LocalRect, 1, True);
end;
function TClendarDayItem.GetIsMark: Boolean;
begin
Result:=False;
if FOwner<>nil then
Result:=FOwner.GetIsMark(Self);
end;
procedure TClendarDayItem.Render(const Canvas: TCanvas;
const DrawItemIndex: Integer; const DrawStates: TListItemDrawStates;
const Resources: TListItemStyleResources; const Params: TListItemDrawable.TParams;
const SubPassNo: Integer);
var
ARect:TRectF;
TextColor, BackColor: TAlphaColor;
AIsMark: Single;
CenterX: Single;
isNow, isMark: Boolean;
LunarDateStr: string;
Calendar: TFMXCalendarControl;
cv: TCalenderView;
d: TDate;
begin
if (SubPassNo <> 0) or (FDay = 0) then
Exit;
DoDrawBitmap(Canvas);
// Draw Background
isNow := False;
if FDay < Trunc(Now) then
TextColor := TAlphaColors.Gainsboro
else
if FDay = Trunc(Now) then
begin
isNow := True;
TextColor := TAlphaColors.White;
BackColor := TAlphaColors.Red;
end
else
TextColor := TAlphaColors.Black;
if FIsSelected then
begin
TextColor := TAlphaColors.White;
BackColor := TAlphaColors.Blue;
end;
CenterX := LocalRect.CenterPoint.X;
ARect := TRectF.Create(0, 0, 32, 32);
ARect.Offset(CenterX - 16, LocalRect.Top + 2);
cv := Self.FOwner.Controller as TCalenderView;
Calendar := cv.Owner as TFMXCalendarControl;
if Assigned(Calendar) and Calendar.IsShowLunarDate then
begin
if isNow or FIsSelected then
begin
Canvas.Fill.Color := BackColor;
Canvas.FillRect(ARect, 0, 0, AllCorners, 1, TCornerType.Round);
end;
Canvas.Fill.Color := TextColor;
Canvas.FillText(ARect, FDayText, False, 1, [], TTextAlign.Center, TTextAlign.Leading);
LunarDateStr := CnSolarTermName(Self.Day);
if LunarDateStr.IsEmpty then
begin
LunarDateStr := CnDayName(Self.Day);
end;
Canvas.FillText(ARect, LunarDateStr, False, 1, [], TTextAlign.Center, TTextAlign.Trailing);
end
else
begin
if isNow or FIsSelected then
begin
Canvas.Fill.Color := BackColor;
Canvas.FillRect(ARect, 16, 16, AllCorners, 1, TCornerType.Round);
end;
Canvas.Fill.Color := TextColor;
Canvas.FillText(ARect, FDayText, False, 1, [], TTextAlign.Center, TTextAlign.Center);
end;
// 标记
if GetIsMark then
begin
Canvas.Fill.Color := TAlphaColors.Gainsboro;
ARect := TRectF.Create(0, 0, 6, 6);
ARect.Offset(CenterX - 3, LocalRect.Top + 40);
Canvas.FillRect(ARect, 3, 3, AllCorners, 1, TCornerType.Round);
end;
end;
procedure TClendarDayItem.SetIsPressed(const Value: Boolean);
begin
if FIsPressed<>Value then
begin
FIsPressed := Value;
Invalidate;
end;
end;
procedure TClendarDayItem.SetIsSelected(const Value: Boolean);
begin
if FIsSelected<>Value then
begin
FIsSelected := Value;
Invalidate;
end;
end;
procedure TClendarDayItem.SetDay(const Value: TDate);
begin
if FDay<>Value then
begin
FDay := Value;
FDayText:=InttoStr(DayOf(FDay));
Invalidate;
end;
end;
{ TClendarDayObjectAppearance }
procedure TClendarDayObjectAppearance.AssignTo(ADest: TPersistent);
var
DstDrawable: TClendarDayItem;
DstAppearance: TClendarDayObjectAppearance;
begin
inherited;
end;
procedure TClendarDayObjectAppearance.CreateObject(const AListViewItem
: TListViewItem);
var
LItem: TClendarDayItem;
begin
LItem := TClendarDayItem.Create(AListViewItem);
LItem.BeginUpdate;
try
LItem.Name := Name;
LItem.Assign(Self);
finally
LItem.EndUpdate;
end;
end;
procedure TClendarDayObjectAppearance.ResetObject(const AListViewItem
: TListViewItem);
begin
ResetObjectT<TClendarDayItem>(AListViewItem);
end;
{ TClendarDayListItemAppearance }
constructor TClendarDayListItemAppearance.Create(const Owner: TControl);
begin
inherited;
Text.Visible := True;
Text.Width := 0;
Text.Height := 0;
Text.TextAlign := TTextAlign.Leading;
Text.TextVertAlign := TTextAlign.Center;
Text.Font.Size := 20;
Text.TextColor := TAlphaColors.Cadetblue;
FYear := TClendarYearObjectAppearance.Create;
FYear.Owner := Self;
FYear.Visible := True;
FYear.Name := TClendarListItemAppearanceNames.YearItemName;
FYear.DataMembers := TObjectAppearance.TDataMembers.Create
(TObjectAppearance.TDataMember.Create(TClendarListItemAppearanceNames.YearItemName, Format('Data["%s"]',
[TClendarListItemAppearanceNames.YearItemName])));
FYear.Width := 0;
FYear.Height := 0;
FSunDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.SunItemName);
FMonDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.MonItmeName);
FTurDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.TurItmeName);
FWedDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.WedItemName);
FThuDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.ThuItemName);
FRuiDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.RuiItemName);
FSatDay := CreateClendarDayObject
(TClendarListItemAppearanceNames.SatItemName);
AddObject(FSunDay, True);
AddObject(FMonDay, True);
AddObject(FTurDay, True);
AddObject(FWedDay, True);
AddObject(FThuDay, True);
AddObject(FRuiDay, True);
AddObject(FSatDay, True);
AddObject(Text, True);
AddObject(FYear, True);
AddObject(GlyphButton, IsItemEdit);
end;
function TClendarDayListItemAppearance.CreateClendarDayObject(AName: String)
: TClendarDayObjectAppearance;
begin
Result := TClendarDayObjectAppearance.Create;
Result.Owner := Self;
Result.Visible := True;
Result.Name := AName;
Result.DataMembers := TObjectAppearance.TDataMembers.Create
(TObjectAppearance.TDataMember.Create(AName, Format('Data["%s"]',
[AName])));
Result.Align := TListItemAlign.Leading;
end;
function TClendarDayListItemAppearance.DefaultHeight: Integer;
begin
Result := cDefaultHeight;
end;
destructor TClendarDayListItemAppearance.Destroy;
begin
FSunDay.Free;
FMonDay.Free;
FTurDay.Free;
FWedDay.Free;
FThuDay.Free;
FRuiDay.Free;
FSatDay.Free;
inherited;
end;
function TClendarDayListItemAppearance.GetGroupClass
: TPresetItemObjects.TGroupClass;
begin
Result := TClendarDayListItemAppearance;
end;
procedure TClendarDayListItemAppearance.SetMonDay
(const Value: TClendarDayObjectAppearance);
begin
FMonDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetRuiDay
(const Value: TClendarDayObjectAppearance);
begin
FRuiDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetSatDay
(const Value: TClendarDayObjectAppearance);
begin
FSatDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetSunDay
(const Value: TClendarDayObjectAppearance);
begin
FSunDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetThuDay
(const Value: TClendarDayObjectAppearance);
begin
FThuDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetTurDay
(const Value: TClendarDayObjectAppearance);
begin
FTurDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetWedDay
(const Value: TClendarDayObjectAppearance);
begin
FWedDay.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.SetYear(
const Value: TClendarYearObjectAppearance);
begin
FYear.AssignTo(Value);
end;
procedure TClendarDayListItemAppearance.UpdateSizes(const ItemSize: TSizeF);
var
LObjectWidth: Single;
begin
try
BeginUpdate;
inherited;
LObjectWidth := Trunc(ItemSize.Width / 7);
FSunDay.Width := LObjectWidth;
FMonDay.Width := LObjectWidth;
FTurDay.Width := LObjectWidth;
FWedDay.Width := LObjectWidth;
FThuDay.Width := LObjectWidth;
FRuiDay.Width := LObjectWidth;
FSatDay.Width := LObjectWidth;
FSunDay.PlaceOffset.X := 0;
FMonDay.PlaceOffset.X := LObjectWidth;
FTurDay.PlaceOffset.X := LObjectWidth + FMonDay.PlaceOffset.X;
FWedDay.PlaceOffset.X := LObjectWidth + FTurDay.PlaceOffset.X;
FThuDay.PlaceOffset.X := LObjectWidth + FWedDay.PlaceOffset.X;
FRuiDay.PlaceOffset.X := LObjectWidth + FThuDay.PlaceOffset.X;
FSatDay.PlaceOffset.X := LObjectWidth + FRuiDay.PlaceOffset.X;
finally
EndUpdate;
end;
end;
{ TClendarDayListViewItem }
function TClendarWeekListViewItem.FindDayItem(ADate:Int64): TClendarDayItem;
function CheckDayItemDate(ADayItem:TClendarDayItem):Boolean;
begin
Result:=ADate = ADayItem.Day
end;
begin
Result:=nil;
if (YearItem.Year <> 0) or (not Text.IsEmpty) then
Exit;
if CheckDayItemDate(SunDayItem) then
begin
Result:=SunDayItem;
Exit;
end;
if CheckDayItemDate(MonDayItem) then
begin
Result:=MonDayItem;
Exit;
end;
if CheckDayItemDate(TurDayItem) then
begin
Result:=TurDayItem;
Exit;
end;
if CheckDayItemDate(WedDayItem) then
begin
Result:=WedDayItem;
Exit;
end;
if CheckDayItemDate(ThuDayItem) then
begin
Result:=ThuDayItem;
Exit;
end;
if CheckDayItemDate(RuiDayItem) then
begin
Result:=RuiDayItem;
Exit;
end;
if CheckDayItemDate(SatDayItem) then
begin
Result:=SatDayItem;
Exit;
end;
end;
function TClendarWeekListViewItem.GetClendarDayItem(AName: String)
: TClendarDayItem;
begin
Result := TClendarDayItem(Objects.FindDrawable(AName));
end;
function TClendarWeekListViewItem.GetIsMark(ADayItem: TClendarDayItem): Boolean;
begin
Result:=False;
if Controller is TCalenderView then
begin
TCalenderView(Controller).OnGetItemIsMark(ADayItem, Result);
end;
end;
const
sThisUnit = 'FMX.CalendarItemAppearance';
function TClendarWeekListViewItem.GetMonDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.MonItmeName);
end;
function TClendarWeekListViewItem.GetRuiDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.RuiItemName);
end;
function TClendarWeekListViewItem.GetSatDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.SatItemName);
end;
function TClendarWeekListViewItem.GetSunDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.SunItemName);
end;
function TClendarWeekListViewItem.GetThuDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.ThuItemName);
end;
function TClendarWeekListViewItem.GetTurDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.TurItmeName);
end;
function TClendarWeekListViewItem.GetWedDayItem: TClendarDayItem;
begin
Result:=GetClendarDayItem(TClendarListItemAppearanceNames.WedItemName);
end;
function TClendarWeekListViewItem.GetYearItem: TClendarYearItem;
begin
Result:=TClendarYearItem(Objects.FindDrawable(TClendarListItemAppearanceNames.YearItemName));
end;
{ TClendarYearItem }
procedure TClendarYearItem.Render(const Canvas: TCanvas;
const DrawItemIndex: Integer; const DrawStates: TListItemDrawStates;
const Resources: TListItemStyleResources;
const Params: TListItemDrawable.TParams; const SubPassNo: Integer);
var
ATextWidth:Single;
ARect:TRectF;
CenterY:Single;
AtPoint1, AtPoint2:TPointF;
begin
if (SubPassNo <> 0) or (FYear = 0) then
Exit;
Canvas.Font.Size:=16;
Canvas.Fill.Color:=$FF1886ED;
Canvas.FillText(LocalRect, FYearText, False, 1, [], TTextAlign.Leading, TTextAlign.Center);
ATextWidth:=Canvas.TextWidth(FYearText);
CenterY:=LocalRect.CenterPoint.Y;
AtPoint1:=TPointF.Create((LocalRect.Left + ATextWidth + 5), CenterY);
AtPoint2:=TPointF.Create((LocalRect.Right), CenterY);
Canvas.Stroke.Kind:=TBrushKind.Solid;
Canvas.Stroke.Thickness:=1;
Canvas.Stroke.Color:=TAlphaColors.Cadetblue;
Canvas.DrawLine(AtPoint1, AtPoint2, 1);
end;
procedure TClendarYearItem.SetYear(const Value: Word);
var
D: TDate;
begin
if FYear<>Value then
begin
FYear := Value;
D := EncodeDate(FYear, 1, 1);
FYearText := InttoStr(FYear);
Invalidate;
end;
end;
{ TClendarYearObjectAppearance }
procedure TClendarYearObjectAppearance.AssignTo(ADest: TPersistent);
begin
inherited;
end;
procedure TClendarYearObjectAppearance.CreateObject(
const AListViewItem: TListViewItem);
var
LItem: TClendarYearItem;
begin
LItem := TClendarYearItem.Create(AListViewItem);
LItem.BeginUpdate;
try
LItem.Name := Name;
LItem.Assign(Self);
finally
LItem.EndUpdate;
end;
end;
procedure TClendarYearObjectAppearance.ResetObject(
const AListViewItem: TListViewItem);
begin
ResetObjectT<TClendarYearItem>(AListViewItem);
end;
{ TCalenderView }
procedure TCalenderView.ApplyStyle;
var
StyleObject: TFmxObject;
begin
StyleObject := Self.FindStyleResource('frame');
if StyleObject is TColorObject then
TColorObject(StyleObject).Color := $FFFFFFFF;
inherited;
end;
function TCalenderView.GetDefaultStyleLookupName: string;
begin
inherited;
end;
initialization
TAppearancesRegistry.RegisterAppearance(TClendarDayListItemAppearance,
TClendarListItemAppearanceNames.ListItem, [TRegisterAppearanceOption.Item],
sThisUnit);
finalization
TAppearancesRegistry.UnregisterAppearances
(TArray<TItemAppearanceObjectsClass>.Create(TClendarDayListItemAppearance));
end.
|
unit udf_date;
interface
uses Types;
type
Long = Longint;
ULong = DWord;
TISC_TIMESTAMP = record
d_date : Long;
d_time : ULong;
end;
PISC_TIMESTAMP = ^TISC_TIMESTAMP;
TCTime = record
tm_sec : integer; // Seconds
tm_min : integer; // Minutes
tm_hour : integer; // Hour (0--23)
tm_mday : integer; // Day of month (1--31)
tm_mon : integer; // Month (0--11)
tm_year : integer; // Year (calendar year minus 1900)
tm_wday : integer; // Weekday (0--6) Sunday = 0)
tm_yday : integer; // Day of year (0--365)
tm_isdst : integer; // 0 if daylight savings time is not in effect)
end;
PCTime = ^TCTime;
function ExtractDate(var Value : TISC_TIMESTAMP): PISC_TIMESTAMP; cdecl; export;
function IncDate(var Value : TISC_TIMESTAMP): PISC_TIMESTAMP; cdecl; export;
function Now: PISC_TIMESTAMP; cdecl; export;
implementation
uses SysUtils, Windows, DateUtils;
procedure isc_decode_timestamp(ib_date: PISC_TIMESTAMP; tm_date: PCTime); stdcall;
external 'fbclient.dll';
procedure isc_encode_timestamp(tm_date: PCTime; ib_date: PISC_TIMESTAMP); stdcall;
external 'fbclient.dll';
function ib_util_malloc (l: Integer): Pointer; cdecl; external 'ib_util.dll';
procedure InitCTime(var tm: TCTIME);
begin
with tm do begin
tm_sec := 0;
tm_min := 0;
tm_hour := 0;
tm_mday := 0;
tm_mon := 0;
tm_year := 0;
tm_wday := 0;
tm_yday := 0;
tm_isdst := 0;
end;
end;
function IncDate(var Value : TISC_TIMESTAMP): PISC_TIMESTAMP; cdecl; export;
var
tm_res, tm_src: TCTIME;
dd_dest: TDateTime;
yy, mm, dd: Word;
begin
InitCTime(tm_res);
isc_decode_timestamp(@Value, @tm_src);
dd_dest := EncodeDate(tm_src.tm_year + 1900, tm_src.tm_mon + 1, tm_src.tm_mday) + 1;
DecodeDate(dd_dest, yy, mm, dd);
with tm_res do begin
tm_year := yy - 1900;
tm_mon := mm - 1;
tm_mday := dd;
tm_isdst := tm_src.tm_isdst;
end;
Result := ib_util_malloc(SizeOf(TISC_TIMESTAMP));
isc_encode_timestamp(@tm_res, Result);
end;
function ExtractDate(var Value : TISC_TIMESTAMP): PISC_TIMESTAMP; cdecl; export;
var
tm_res, tm_src: TCTIME;
begin
InitCTime(tm_res);
isc_decode_timestamp(@Value, @tm_src);
with tm_res do begin
tm_year := tm_src.tm_year;
tm_mon := tm_src.tm_mon;
tm_mday := tm_src.tm_mday;
tm_isdst := tm_src.tm_isdst;
end;
Result := ib_util_malloc(SizeOf(TISC_TIMESTAMP));
isc_encode_timestamp(@tm_res, Result);
end;
function Now: PISC_TIMESTAMP; cdecl; export;
var
d, m, y, h, mm, s, ms: Word;
tm_res: TCTIME;
begin
DecodeDateTime(SysUtils.Now, y, m, d, h, mm, s, ms);
InitCTime(tm_res);
with tm_res do begin
tm_year := y - 1900;
tm_mon := m - 1;
tm_mday := d;
tm_hour := h;
tm_min := mm;
tm_sec := s;
end;
Result := ib_util_malloc(SizeOf(TISC_TIMESTAMP));
isc_encode_timestamp(@tm_res, Result);
end;
end.
|
(*
JCore WebServices, Controller Handler Classes
Copyright (C) 2015 Joao Morais
See the file LICENSE.txt, included in this distribution,
for details about the copyright.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*)
unit JCoreWSController;
{$I jcore.inc}
{$WARN 5024 OFF} // hint 'parameter not used'
interface
uses
typinfo,
fgl,
HTTPDefs,
JCoreClasses,
JCoreWSInvokers;
type
{ IJCoreWSMethodRegistry }
IJCoreWSMethodRegistry = interface(IInterface)
['{BEBE3BC1-E802-D43D-6F49-E95E733C9439}']
procedure AddInvoker(const AInvokers: array of TJCoreWSMethodInvokerClass);
function FindInvoker(const AMethodData: TJCoreWSMethodData): TJCoreWSMethodInvoker;
end;
{ TJCoreWSMethodRegistry }
TJCoreWSMethodRegistry = class(TInterfacedObject, IJCoreWSMethodRegistry)
private
FInvokers: TJCoreWSMethodInvokerList;
public
destructor Destroy; override;
procedure AddInvoker(const AInvokers: array of TJCoreWSMethodInvokerClass);
function FindInvoker(const AMethodData: TJCoreWSMethodData): TJCoreWSMethodInvoker;
end;
{ TJCoreWSControllerMethod }
TJCoreWSControllerMethod = class(TObject)
private
FControllerClass: TClass;
FInvoker: TJCoreWSMethodInvoker;
FMethodAddr: Pointer;
FMethodData: TJCoreWSMethodData;
FMethodName: string;
FMethodPattern: string;
FMethodRegistry: IJCoreWSMethodRegistry;
FMethodURLFrag: string;
function GetInvoker: TJCoreWSMethodInvoker;
protected
property Invoker: TJCoreWSMethodInvoker read GetInvoker;
property MethodData: TJCoreWSMethodData read FMethodData;
public
constructor Create(const AControllerClass: TClass; const AMethodAddr: Pointer; const AMethodTypeInfo: PTypeInfo; const AMethodPattern: string = '');
destructor Destroy; override;
function AcceptRequestMethod(const ARequestMethod: string): Boolean;
procedure HandleRequest(const ARequest: TRequest; const AResponse: TResponse);
property ControllerClass: TClass read FControllerClass;
property MethodPattern: string read FMethodPattern;
property MethodURLFrag: string read FMethodURLFrag;
end;
TJCoreWSControllerMethodList = specialize TFPGObjectList<TJCoreWSControllerMethod>;
{ TJCoreWSControllerClass }
TJCoreWSControllerClass = class(TObject)
private
FControllerClass: TClass;
FControllerURLFrag: string;
FMethods: TJCoreWSControllerMethodList;
function FormatControllerURLFrag(const AControllerClass: TClass): string;
protected
property Methods: TJCoreWSControllerMethodList read FMethods;
public
constructor Create(const AControllerClass: TClass; const AControllerURLFrag: string = '');
destructor Destroy; override;
function AddMethod(const AMethodAddr: Pointer; const AMethodTypeInfo: PTypeInfo; const AMethodPattern: string = ''): TJCoreWSControllerClass;
function FindMethod(const AMethodURLFrag: string): TJCoreWSControllerMethod;
property ControllerClass: TClass read FControllerClass;
property ControllerURLFrag: string read FControllerURLFrag;
end;
TJCoreWSControllerClassList = specialize TFPGObjectList<TJCoreWSControllerClass>;
implementation
uses
sysutils,
JCoreConsts,
JCoreDIC;
{ TJCoreWSMethodRegistry }
destructor TJCoreWSMethodRegistry.Destroy;
begin
FreeAndNil(FInvokers);
inherited Destroy;
end;
procedure TJCoreWSMethodRegistry.AddInvoker(const AInvokers: array of TJCoreWSMethodInvokerClass);
var
VInvoker: TJCoreWSMethodInvokerClass;
begin
if not Assigned(FInvokers) then
FInvokers := TJCoreWSMethodInvokerList.Create(True);
for VInvoker in AInvokers do
FInvokers.Add(VInvoker.Create);
end;
function TJCoreWSMethodRegistry.FindInvoker(const AMethodData: TJCoreWSMethodData): TJCoreWSMethodInvoker;
var
VCurrent: TJCoreWSMethodInvoker;
I: Integer;
begin
Result := nil;
if Assigned(FInvokers) then
for I := 0 to Pred(FInvokers.Count) do
if FInvokers[I].Match(AMethodData) then
begin
VCurrent := FInvokers[I];
if not Assigned(Result) or VCurrent.InheritsFrom(Result.ClassType) then
Result := VCurrent
else if not Result.InheritsFrom(VCurrent.ClassType) then
raise EJCoreWS.Create(3104, S3104_AmbiguousMethodInvokers, [
VCurrent.ClassName, Result.ClassName]);
end;
end;
{ TJCoreWSControllerMethod }
function TJCoreWSControllerMethod.GetInvoker: TJCoreWSMethodInvoker;
begin
if not Assigned(FInvoker) then
begin
FInvoker := FMethodRegistry.FindInvoker(MethodData);
if not Assigned(FInvoker) then
raise EJCoreWS.Create(3101, S3101_UnsupportedMethod, [ControllerClass.ClassName, FMethodName]);
end;
Result := FInvoker;
end;
constructor TJCoreWSControllerMethod.Create(const AControllerClass: TClass; const AMethodAddr: Pointer;
const AMethodTypeInfo: PTypeInfo; const AMethodPattern: string);
begin
inherited Create;
FControllerClass := AControllerClass;
FMethodAddr := AMethodAddr;
FMethodPattern := AMethodPattern;
FMethodName := FControllerClass.MethodName(FMethodAddr);
FMethodURLFrag := LowerCase(FMethodName);
if AMethodTypeInfo^.Kind <> tkMethod then
raise EJCoreWS.Create(3102, S3102_TypeinfoIsNotMethod, [FControllerClass.ClassName, FMethodName]);
FMethodData := TJCoreWSMethodData.Create(AMethodTypeInfo);
TJCoreDIC.Locate(IJCoreWSMethodRegistry, FMethodRegistry);
end;
destructor TJCoreWSControllerMethod.Destroy;
begin
FreeAndNil(FMethodData);
inherited Destroy;
end;
function TJCoreWSControllerMethod.AcceptRequestMethod(const ARequestMethod: string): Boolean;
begin
{ TODO : Implement }
Result := True;
end;
procedure TJCoreWSControllerMethod.HandleRequest(const ARequest: TRequest; const AResponse: TResponse);
var
VController: TObject;
VMethod: TMethod;
begin
VController := ControllerClass.Create;
try
VMethod.Data := VController;
VMethod.Code := FMethodAddr;
Invoker.Invoke(MethodData, ARequest, AResponse, VMethod);
finally
FreeAndNil(VController);
end;
end;
{ TJCoreWSControllerClass }
function TJCoreWSControllerClass.FormatControllerURLFrag(const AControllerClass: TClass): string;
var
VClassName, VControllerURLFrag: string;
begin
VClassName := AControllerClass.ClassName;
if LowerCase(VClassName[1]) = 't' then
VControllerURLFrag := Copy(VClassName, 2, Length(VClassName))
else
VControllerURLFrag := VClassName;
if LowerCase(RightStr(VControllerURLFrag, 10)) = 'controller' then
VControllerURLFrag := LeftStr(VControllerURLFrag, Length(VControllerURLFrag) - 10);
Result := LowerCase(VControllerURLFrag);
end;
constructor TJCoreWSControllerClass.Create(const AControllerClass: TClass;
const AControllerURLFrag: string);
begin
inherited Create;
FControllerClass := AControllerClass;
if AControllerURLFrag <> '' then
FControllerURLFrag := AControllerURLFrag
else
FControllerURLFrag := FormatControllerURLFrag(FControllerClass);
FMethods := TJCoreWSControllerMethodList.Create(True);
end;
destructor TJCoreWSControllerClass.Destroy;
begin
FreeAndNil(FMethods);
inherited Destroy;
end;
function TJCoreWSControllerClass.AddMethod(const AMethodAddr: Pointer;
const AMethodTypeInfo: PTypeInfo; const AMethodPattern: string): TJCoreWSControllerClass;
var
VMethod: TJCoreWSControllerMethod;
begin
VMethod := TJCoreWSControllerMethod.Create(ControllerClass, AMethodAddr, AMethodTypeInfo, AMethodPattern);
Methods.Add(VMethod);
Result := Self;
end;
function TJCoreWSControllerClass.FindMethod(const AMethodURLFrag: string): TJCoreWSControllerMethod;
var
I: Integer;
begin
for I := 0 to Pred(Methods.Count) do
begin
Result := Methods[I];
if Result.MethodURLFrag = AMethodURLFrag then
Exit;
end;
Result := nil;
end;
initialization
TJCoreDIC.LazyRegister(IJCoreWSMethodRegistry, TJCoreWSMethodRegistry, jdsApplication);
finalization
TJCoreDIC.Unregister(IJCoreWSMethodRegistry, TJCoreWSMethodRegistry);
end.
|
unit property_commands;
interface
//uses
type
TChangePropertyCommand=class(TAbstractTreeCommand)
protected
fComponent: TStreamingClass;
fPropName: string;
fComponentNameStr: string;
function NewGetPropInfo: PPropInfo;
public
Constructor Create(AOwner: TComponent); override;
procedure ResolveMemory; override;
function Execute: Boolean; override;
published
property Component: TStreamingClass read fComponent write fComponent;
property PropName: string read fPropName write fPropName;
end;
TChangeIntegerCommand=class(TChangePropertyCommand)
private
fVal, fBackup: Integer;
public
constructor Create(acomponent: TStreamingClass; propName: string; value: Integer); reintroduce;
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
published
property Val: Integer read fVal write fVal;
property Backup: Integer read fBackup write fBackup;
end;
TChangeFloatCommand=class(TChangePropertyCommand)
private
fVal,fBackup: Real;
public
constructor Create(acomponent: TStreamingClass; propName: string; value: Real); reintroduce;
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
published
property Val: Real read fVal write fVal;
property Backup: Real read fBackup write fBackup;
end;
TChangeBoolCommand=class(TChangePropertyCommand)
private
fVal: boolean;
public
constructor Create(aComponent: TStreamingClass; propName: string; value: boolean); reintroduce;
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
published
property Val: boolean read fVal write fVal;
end;
TChangeStringCommand=class(TChangePropertyCommand)
private
fstring: string;
fbackup: string;
public
constructor Create(aComponent: TStreamingClass; propName: string; value: string); reintroduce;
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
published
property val: string read fstring write fstring;
property backup: string read fbackup write fbackup;
end;
TChangeLocaleStringCommand=class(TChangePropertyCommand)
private
fstring,fbackup,flang: string;
public
constructor Create(aComponent: TStreamingClass; propName: string; alang,value: string); reintroduce;
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
published
property val: string read fstring write fstring;
property lang: string read flang write flang;
property backup: string read fbackup write fbackup;
end;
implementation
(*
TChangePropertyCommand
*)
constructor TChangePropertyCommand.Create(AOwner: TComponent);
begin
inherited Create(aOwner);
fImageIndex:=13;
end;
function TChangePropertyCommand.NewGetPropInfo: PPropInfo;
begin
if fComponent=nil then Raise Exception.Create('ChangePropertyCommand: nil component');
Result:=GetPropInfo(fComponent,fPropName);
if Result=nil then Raise Exception.CreateFmt('ChangeIntegerCommand: property %s not exist',[fPropName]);
if Result.SetProc=nil then Raise Exception.CreateFmt('ChangeIntegerCommand: write to read-only property %s',[fPropName]);
end;
procedure TChangePropertyCommand.ResolveMemory;
var intf: IConstantComponentName;
begin
if not fComponent.GetInterface(IConstantComponentName,intf) then begin
(Owner as TCommandTree).JumpToBranch(self); //попадаем на состояние документа
//после выполнения нашей команды
(Owner as TCommandTree).Undo;
end;
fComponentNameStr:=GetComponentValue(fComponent,fComponent.FindOwner);
if fComponentNameStr='Owner' then fComponentNameStr:=''
else fComponentNameStr:=fComponentNameStr+'.';
// intf:=nil;
end;
function TChangePropertyCommand.Execute: Boolean;
begin
fComponentNameStr:=GetComponentValue(fComponent,fComponent.FindOwner);
if fComponentNameStr='Owner' then fComponentNameStr:=''
else fComponentNameStr:=fComponentNameStr+'.';
Result:=true;
end;
(*
TChangeIntegerCommand
*)
constructor TChangeIntegerCommand.Create(aComponent: TStreamingClass;propName: string; value: Integer);
begin
inherited Create(nil);
fComponent:=aComponent;
fPropName:=propName;
fVal:=value;
end;
function TChangeIntegerCommand.Execute: boolean;
var propInfo: PPropInfo;
begin
inherited Execute;
PropInfo:=NewGetPropInfo;
if PropInfo.PropType^.Kind<>tkInteger then Raise Exception.CreateFmt('ChangeIntegerCommand: property %s is not integer',[fPropName]);
fBackup:=GetOrdProp(fComponent,propInfo);
if fBackup=fVal then result:=false
else begin
SetOrdProp(fComponent,propInfo,fVal);
Result:=true;
end;
end;
function TChangeIntegerCommand.Undo: Boolean;
var propInfo: PPropInfo;
begin
propInfo:=NewGetPropInfo;
if propInfo.PropType^.Kind<>tkInteger then Raise Exception.CreateFmt('ChangeIntegerCommand: property %s is not integer',[fPropName]);
SetOrdProp(fComponent,propInfo,fBackup);
fBackup:=0;
Result:=true;
end;
function TChangeIntegerCommand.Caption: string;
var IntToIdent: TIntToIdent;
propInfo: PPropInfo;
typedata: PTypeData;
s: string;
begin
propInfo:=NewGetPropInfo;
IntToIdent:=FindIntToIdent(propInfo.PropType^);
if Assigned(IntToIdent) then begin
IntToIdent(fVal,s);
if s='' then begin
typeData:=GetTypeData(propInfo^.PropType^);
s:='$'+IntToHex(fVal,typeData^.elSize*2);
end;
end
else
s:=IntToStr(fVal);
Result:=fComponentNameStr+fPropName+'='+s;
end;
(*
TChangeStringCommand
*)
constructor TChangeStringCommand.Create(aComponent: TStreamingClass;PropName: string; value: String);
begin
inherited Create(nil);
fcomponent:=acomponent;
fPropName:=PropName;
fString:=value;
end;
function TChangeStringCommand.Execute: Boolean;
var propInfo: PPropInfo;
begin
inherited Execute;
propInfo:=NewGetPropInfo;
if not (propInfo.PropType^.Kind in [tkString,tkLString,tkWString]) then Raise Exception.CreateFmt('ChangeStringCommand: property %s is not string',[fPropName]);
fBackup:=GetStrProp(fComponent,propInfo);
if fBackup=fstring then Result:=false
else begin
SetStrProp(fComponent,propInfo,fstring);
Result:=true;
end;
end;
function TChangeStringCommand.Undo: Boolean;
var propInfo: PPropInfo;
begin
propInfo:=NewGetPropInfo;
if not (propInfo.PropType^.Kind in [tkString,tkLString,tkWString]) then Raise Exception.CreateFmt('ChangeStringCommand: property %s is not string',[fPropName]);
SetStrProp(fComponent,propInfo,fBackup);
fBackup:='';
Result:=true;
end;
function TChangeStringCommand.Caption: string;
begin
Result:=fComponentNameStr+fPropName+'='+fstring;
end;
(*
TChangeLocaleStringCommand
*)
constructor TChangeLocaleStringCommand.Create(aComponent: TStreamingClass;PropName: string; alang,value: String);
begin
inherited Create(nil);
fcomponent:=acomponent;
fPropName:=PropName;
fString:=value;
flang:=alang;
end;
function TChangeLocaleStringCommand.Execute: Boolean;
var locStr: TLocalizedName;
begin
inherited Execute; //дает имя строки, чтобы отобр. в caption
locStr:=TlocalizedName(GetObjectProp(fComponent,fPropName,TLocalizedName));
// locStr:=(fComponent.FindComponent(fPropName)) as TlocalizedName;
fBackup:=locStr.str[flang];
if fBackup=fstring then Result:=false
else begin
locStr.str[flang]:=fstring;
Result:=true;
end;
end;
function TChangeLocaleStringCommand.Undo: Boolean;
var locStr: TLocalizedName;
begin
locStr:=TLocalizedName(GetObjectProp(fComponent,fPropName,TLocalizedName));
// locStr:=(fComponent.FindComponent(fPropName)) as TLocalizedName;
locStr.str[flang]:=fBackup;
fBackup:='';
Result:=true;
end;
function TChangeLocaleStringCommand.Caption: string;
begin
Result:=fComponentNameStr+fPropName+'.'+fLang+'='+fString;
end;
(*
TChangeFloatCommand
*)
constructor TChangeFloatCommand.Create(acomponent: TStreamingClass;PropName: string;value: Real);
begin
inherited Create(nil);
fcomponent:=acomponent;
fPropName:=PropName;
fVal:=value;
end;
function TChangeFloatCommand.Execute: Boolean;
var propInfo: PPropInfo;
begin
inherited Execute;
propInfo:=NewGetPropInfo;
if propInfo.PropType^.Kind<>tkFloat then Raise Exception.CreateFmt('ChangeFloatCommand: property %s is not float',[fPropName]);
fBackup:=GetFloatProp(fComponent,propInfo);
if fBackup=fVal then Result:=false //совпадение чисел с плав. точкой - очень редко,
// но если не совпадает, то с чистой совестью меняем
else begin
SetFloatProp(fComponent,propInfo,fval);
Result:=true;
end;
end;
function TChangeFloatCommand.Undo: Boolean;
var propInfo: PPropInfo;
begin
propInfo:=NewGetPropInfo;
if propInfo.PropType^.Kind<>tkFloat then Raise Exception.CreateFmt('ChangeFloatCommand: property %s is not float',[fPropName]);
SetFloatProp(fComponent,propInfo,fBackup);
fBackup:=0;
Result:=true;
end;
function TChangeFloatCommand.Caption: string;
begin
Result:=fComponentNameStr+fPropName+'='+FloatToStr(fVal);
end;
(*
TChangeBoolCommand
*)
constructor TChangeBoolCommand.Create(aComponent: TStreamingClass;PropName: string; value: Boolean);
begin
inherited Create(nil);
fComponent:=aComponent;
fPropName:=PropName;
fVal:=value;
end;
function TChangeBoolCommand.Execute: boolean;
var PropInfo: PPropInfo;
res: LongInt;
begin
inherited Execute;
PropInfo:=NewGetPropInfo;
if PropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.CreateFmt('ChangeBoolCommand.Execute: property %s is not boolean', [fPropName] );
res:=GetOrdProp(fComponent,PropInfo);
if fVal=Boolean(res) then result:=false
else begin
SetOrdProp(fComponent,PropInfo,Integer(fVal));
Result:=true;
end;
end;
function TChangeBoolCommand.Undo: boolean;
var PropInfo: PPropInfo;
begin
PropInfo:=NewGetPropInfo;
if PropInfo.PropType^.Kind<>tkEnumeration then Raise Exception.CreateFmt('ChangeBoolCommand.Execute: property %s is not boolean', [fPropName] );
SetOrdProp(fComponent,PropInfo,Integer(not fVal));
Result:=true;
end;
function TChangeBoolCommand.Caption: string;
begin
Result:=fComponentNameStr+fPropName+'='+BoolToStr(fVal,true);
end;
end.
|
unit unitFrame;
interface
uses classes, Types;
type
TFrame = class(TObject)
private
{ Private declarations }
public
{ Public declarations }
polys: TList;
caption: String;
State: String;
ImageFile: String;
Center: TPoint;
constructor Create(ncaption: String);
end;
implementation
constructor TFrame.Create(ncaption: String);
begin
inherited Create;
Caption := ncaption;
polys := TList.Create;
State:='';
ImageFile:='';
Center.X := 0;
Center.Y := 0;
end;
end.
|
unit PI.View.Main;
interface
uses
// RTL
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, System.Json,
// FMX
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls, FMX.TabControl,
FMX.Layouts, FMX.Edit, FMX.Objects, FMX.ComboEdit, FMX.ListBox, FMX.Memo.Types, FMX.ActnList,
// DW
DW.FCMSender,
// PushIt
PI.Types, PI.View.Devices, PI.Config;
type
TMainView = class(TForm)
ResponseMemo: TMemo;
ResponseLabel: TLabel;
TabControl: TTabControl;
JSONTab: TTabItem;
JSONMemo: TMemo;
BottomLayout: TLayout;
SendButton: TButton;
MessageTab: TTabItem;
MessageLayout: TLayout;
TitleEdit: TEdit;
BodyLabel: TLabel;
BodyMemo: TMemo;
ChannelLabel: TLabel;
ChannelIDEdit: TEdit;
TitleLabel: TLabel;
TokenEdit: TEdit;
ClearTokenEditButton: TClearEditButton;
MessageButtonsLayout: TLayout;
ClearMessageFieldsButton: TButton;
ClearChannelIDEditButton: TClearEditButton;
SeparatorLine: TLine;
ClearAllFieldsButton: TButton;
SubtitleLabel: TLabel;
SubtitleEdit: TEdit;
BadgeLabel: TLabel;
BadgeEdit: TEdit;
MessageFieldsLayout: TLayout;
MessageTextLayout: TLayout;
MessagePropsLayout: TLayout;
SoundLabel: TLabel;
SoundEdit: TEdit;
ClickActionLabel: TLabel;
ClickActionEdit: TEdit;
DevicesButton: TButton;
PriorityLabel: TLabel;
PriorityComboBox: TComboBox;
ContentAvailableCheckBox: TCheckBox;
ImageURLLabel: TLabel;
ImageURLEdit: TEdit;
BigPictureCheckBox: TCheckBox;
BigTextCheckBox: TCheckBox;
ActionList: TActionList;
SendAction: TAction;
SelectServiceAccountJSONFileAction: TAction;
ServiceAccountOpenDialog: TOpenDialog;
ServiceAccountJSONLabel: TLabel;
ServiceAccountJSONFileNameEdit: TEdit;
ServiceAccountJSONFileButton: TEllipsesEditButton;
LogCheckBox: TCheckBox;
TokenTopicLayout: TLayout;
TokenRadioButton: TRadioButton;
TopicRadioButton: TRadioButton;
ServiceAccountLayout: TLayout;
DataOnlyCheckBox: TCheckBox;
procedure JSONMemoChangeTracking(Sender: TObject);
procedure MessageFieldChange(Sender: TObject);
procedure ClearMessageFieldsButtonClick(Sender: TObject);
procedure ClearAllFieldsButtonClick(Sender: TObject);
procedure TabControlChange(Sender: TObject);
procedure BadgeEditKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
procedure BadgeEditChangeTracking(Sender: TObject);
procedure DevicesButtonClick(Sender: TObject);
procedure MessageTypeRadioButtonClick(Sender: TObject);
procedure ContentAvailableCheckBoxClick(Sender: TObject);
procedure PriorityComboBoxChange(Sender: TObject);
procedure SelectServiceAccountJSONFileActionExecute(Sender: TObject);
procedure ServiceAccountJSONFileNameEditChangeTracking(Sender: TObject);
procedure SendActionExecute(Sender: TObject);
procedure SendActionUpdate(Sender: TObject);
private
FConfig: TPushItConfig;
FDevicesView: TDevicesView;
FFCMSender: TFCMSender;
FIsJSONModified: Boolean;
FIsMessageModified: Boolean;
FJSONDumpFolder: string;
function CanSend: Boolean;
procedure ConfirmUpdateJSON;
procedure DevicesChangeHandler(Sender: TObject);
procedure DumpJSON(const AJSON: string);
procedure FCMSend;
procedure FCMSenderErrorHandler(Sender: TObject; const AError: TFCMSenderError);
procedure FCMSenderResponseHandler(Sender: TObject; const AResponse: TFCMSenderResponse);
function GetMessageJSON: string;
function HasMinRequiredFields: Boolean;
function IsJSONValid: Boolean;
procedure ParseServiceAccount;
procedure ResponseReceived(const AResponse: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
MainView: TMainView;
implementation
{$R *.fmx}
uses
// RTL
System.Character, System.Net.HttpClient, System.Net.URLClient, System.NetConsts, System.IOUtils,
REST.Types,
// FMX
FMX.DialogService,
// DW
DW.Classes.Helpers, DW.JSON,
// PushIt
PI.Consts, PI.Resources;
{ TMainView }
constructor TMainView.Create(AOwner: TComponent);
begin
inherited;
FJSONDumpFolder := TPath.Combine(TPath.GetTempPath, 'PushIt');
ForceDirectories(FJSONDumpFolder);
TabControl.ActiveTab := MessageTab;
FFCMSender := TFCMSender.Create;
FFCMSender.OnError := FCMSenderErrorHandler;
FFCMSender.OnResponse := FCMSenderResponseHandler;
FDevicesView := TDevicesView.Create(Application);
FDevicesView.OnDevicesChange := DevicesChangeHandler;
FDevicesView.IsMonitoring := True;
FConfig := TPushItConfig.Current;
ServiceAccountJSONFileNameEdit.Text := FConfig.ServiceAccountFileName;
TokenEdit.Text := FConfig.Token;
end;
destructor TMainView.Destroy;
begin
FFCMSender.Free;
inherited;
end;
procedure TMainView.DevicesButtonClick(Sender: TObject);
begin
if FDevicesView.ShowModal = mrOk then
begin
TokenEdit.Text := FDevicesView.SelectedDeviceInfo.Token;
ChannelIDEdit.Text := FDevicesView.SelectedDeviceInfo.ChannelId;
end;
end;
procedure TMainView.DevicesChangeHandler(Sender: TObject);
begin
DevicesButton.Enabled := FDevicesView.DeviceInfos.Count > 0;
end;
procedure TMainView.DumpJSON(const AJSON: string);
var
LFileName: string;
begin
LFileName := TPath.Combine(FJSONDumpFolder, Format('Message-%s.json', [FormatDateTime('yyyy-mm-dd-hh-nn-ss-zzz', Now)]));
TFile.WriteAllText(LFileName, TJsonHelper.Tidy(AJSON));
end;
procedure TMainView.BadgeEditChangeTracking(Sender: TObject);
begin
if StrToIntDef(BadgeEdit.Text, -1) = -1 then
BadgeEdit.Text := ''
else
MessageFieldChange(Sender);
end;
procedure TMainView.BadgeEditKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if not (Key in [vkBack, vkDelete, vkLeft, vkRight]) and not KeyChar.IsDigit then
begin
Key := 0;
KeyChar := #0;
end;
end;
function TMainView.CanSend: Boolean;
begin
Result := not TokenEdit.Text.Trim.IsEmpty and FFCMSender.ServiceAccount.IsValid and (HasMinRequiredFields or IsJSONValid);
end;
function TMainView.HasMinRequiredFields: Boolean;
begin
Result := not TitleEdit.Text.Trim.IsEmpty and not BodyMemo.Text.Trim.IsEmpty;
end;
function TMainView.IsJSONValid: Boolean;
var
LJSON: TJSONValue;
begin
Result := False;
if not JSONMemo.Text.IsEmpty then
begin
LJSON := TJSONObject.ParseJSONValue(JSONMemo.Text);
if LJSON <> nil then
begin
Result := True;
LJSON.Free;
end;
end;
end;
procedure TMainView.ClearAllFieldsButtonClick(Sender: TObject);
begin
TokenEdit.Text := '';
ChannelIDEdit.Text := '';
ClearMessageFieldsButtonClick(ClearMessageFieldsButton);
FIsMessageModified := False;
end;
procedure TMainView.ClearMessageFieldsButtonClick(Sender: TObject);
begin
TitleEdit.Text := '';
SubtitleEdit.Text := '';
BodyMemo.Text := '';
PriorityComboBox.ItemIndex := 0;
ContentAvailableCheckBox.IsChecked := False;
SoundEdit.Text := '';
BadgeEdit.Text := '';
ClickActionEdit.Text := '';
end;
procedure TMainView.ServiceAccountJSONFileNameEditChangeTracking(Sender: TObject);
begin
ParseServiceAccount;
end;
procedure TMainView.FCMSend;
var
LJSON: string;
begin
if TabControl.ActiveTab = MessageTab then
LJSON := GetMessageJSON
else
LJSON := JSONMemo.Text;
DumpJSON(LJSON);
if LogCheckBox.IsChecked then
ResponseMemo.Lines.Add('Sending..');
TDo.Run(
procedure
begin
FFCMSender.Post(LJSON);
end
);
end;
procedure TMainView.FCMSenderErrorHandler(Sender: TObject; const AError: TFCMSenderError);
var
LResponse: string;
begin
LResponse := Format('Error - %s: %s - %s', [AError.Kind.ToString, AError.ErrorMessage, AError.Content]);
TThread.Queue(nil, procedure begin ResponseReceived(LResponse) end);
end;
procedure TMainView.FCMSenderResponseHandler(Sender: TObject; const AResponse: TFCMSenderResponse);
begin
TThread.Queue(nil, procedure begin ResponseReceived(AResponse.Response) end);
end;
procedure TMainView.JSONMemoChangeTracking(Sender: TObject);
begin
FIsJSONModified := True;
end;
procedure TMainView.MessageFieldChange(Sender: TObject);
begin
FIsMessageModified := True;
end;
procedure TMainView.MessageTypeRadioButtonClick(Sender: TObject);
begin
FIsMessageModified := True;
end;
procedure TMainView.ParseServiceAccount;
begin
if FFCMSender.LoadServiceAccount(ServiceAccountJSONFileNameEdit.Text) then
begin
FConfig.ServiceAccountFileName := ServiceAccountJSONFileNameEdit.Text;
FConfig.Save;
end;
end;
procedure TMainView.PriorityComboBoxChange(Sender: TObject);
begin
FIsMessageModified := True;
end;
procedure TMainView.ContentAvailableCheckBoxClick(Sender: TObject);
begin
FIsMessageModified := True;
end;
procedure TMainView.ResponseReceived(const AResponse: string);
begin
ResponseMemo.Text := AResponse;
end;
function TMainView.GetMessageJSON: string;
var
LMessage: TFCMMessage;
begin
LMessage := TFCMMessage.Create;
try
LMessage.IsDataOnly := DataOnlyCheckBox.IsChecked;
LMessage.Title := TitleEdit.Text;
// LMessage.Subtitle := SubtitleEdit.Text;
LMessage.Body := BodyMemo.Text;
LMessage.ImageURL := ImageURLEdit.Text;
if BigTextCheckBox.IsChecked then
LMessage.Options := LMessage.Options + [TFCMMessageOption.BigText];
if not LMessage.ImageURL.IsEmpty and BigPictureCheckBox.IsChecked then
LMessage.Options := LMessage.Options + [TFCMMessageOption.BigImage];
if ContentAvailableCheckBox.IsChecked then
LMessage.Options := LMessage.Options + [TFCMMessageOption.ContentAvailable];
case PriorityComboBox.ItemIndex of
0:
LMessage.Priority := TFCMMessagePriority.None;
1:
LMessage.Priority := TFCMMessagePriority.Normal;
2:
LMessage.Priority := TFCMMessagePriority.High;
end;
LMessage.SoundName := SoundEdit.Text;
LMessage.BadgeCount := StrToIntDef(BadgeEdit.Text, 0);
LMessage.ClickAction := ClickActionEdit.Text;
if TokenRadioButton.IsChecked then
Result := LMessage.GetTokenPayload(TokenEdit.Text)
else
Result := LMessage.GetTopicPayload(TokenEdit.Text);
finally
LMessage.Free;
end;
end;
procedure TMainView.SelectServiceAccountJSONFileActionExecute(Sender: TObject);
begin
if ServiceAccountOpenDialog.Execute then
begin
ServiceAccountJSONFileNameEdit.Text := ServiceAccountOpenDialog.FileName;
ParseServiceAccount;
end;
end;
procedure TMainView.SendActionExecute(Sender: TObject);
begin
ResponseMemo.Text := '';
FConfig.Token := TokenEdit.Text;
FConfig.Save;
FCMSend;
end;
procedure TMainView.SendActionUpdate(Sender: TObject);
begin
SendAction.Enabled := CanSend;
end;
procedure TMainView.ConfirmUpdateJSON;
begin
TDialogService.MessageDialog('Message fields have changed. Update JSON?', TMsgDlgType.mtConfirmation, mbYesNo, TMsgDlgBtn.mbNo, 0,
procedure(const AResult: TModalResult)
begin
if AResult = mrYes then
begin
JSONMemo.Text := TJsonHelper.Tidy(GetMessageJSON);
FIsMessageModified := False;
end;
end
);
end;
procedure TMainView.TabControlChange(Sender: TObject);
begin
if FIsMessageModified and (TabControl.ActiveTab = JSONTab) then
ConfirmUpdateJSON;
end;
end.
|
program TESTTRC ( OUTPUT ) ;
(********)
(*$a+ *)
(********)
var R : REAL ;
X : REAL ;
I : INTEGER ;
C : array [ 1 .. 100 ] of CHAR ;
local procedure DUMP ( PVON : VOIDPTR ; PBIS : VOIDPTR ) ;
/*********************************************************/
/* Speicherbereich von PVON bis PBIS hexadezimal */
/* ausgeben */
/*********************************************************/
var P1 : VOIDPTR ;
P2 : VOIDPTR ;
MOD1 : INTEGER ;
MOD2 : INTEGER ;
procedure DUMPCHAR ( CH : CHAR ) ;
begin (* DUMPCHAR *)
if CH in [ 'a' .. 'i' , 'j' .. 'r' , 's' .. 'z' , 'A' .. 'I' ,
'J' .. 'R' , 'S' .. 'Z' , '0' .. '9' , ' ' , ',' , '.' , '-' ,
';' , ':' , '_' , '!' , '"' , 'õ' , '$' , '%' , '&' , '/' , '('
, ')' , '=' , '?' , '+' , '*' , '#' , '*' ] then
WRITE ( CH )
else
WRITE ( '.' )
end (* DUMPCHAR *) ;
procedure DUMPZEILE ( ADR : VOIDPTR ; P1 : VOIDPTR ; P2 : VOIDPTR )
;
var CH : -> CHAR ;
I : INTEGER ;
const HEXTAB : array [ 0 .. 15 ] of CHAR = '0123456789abcdef' ;
begin (* DUMPZEILE *)
WRITE ( ADR , ': ' ) ;
CH := ADR ;
if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 )
then
WRITE ( '........ ' )
else
begin
for I := 1 to 4 do
begin
WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD
( CH -> ) MOD 16 ] ) ;
CH := PTRADD ( CH , 1 ) ;
end (* for *) ;
WRITE ( ' ' ) ;
end (* else *) ;
ADR := PTRADD ( ADR , 4 ) ;
CH := ADR ;
if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 )
then
WRITE ( '........ ' )
else
begin
for I := 1 to 4 do
begin
WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD
( CH -> ) MOD 16 ] ) ;
CH := PTRADD ( CH , 1 ) ;
end (* for *) ;
WRITE ( ' ' ) ;
end (* else *) ;
ADR := PTRADD ( ADR , 4 ) ;
CH := ADR ;
if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 )
then
WRITE ( '........ ' )
else
begin
for I := 1 to 4 do
begin
WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD
( CH -> ) MOD 16 ] ) ;
CH := PTRADD ( CH , 1 ) ;
end (* for *) ;
WRITE ( ' ' ) ;
end (* else *) ;
ADR := PTRADD ( ADR , 4 ) ;
CH := ADR ;
if ( PTRDIFF ( ADR , P1 ) < 0 ) or ( PTRDIFF ( ADR , P2 ) > 0 )
then
WRITE ( '........ ' )
else
begin
for I := 1 to 4 do
begin
WRITE ( HEXTAB [ ORD ( CH -> ) DIV 16 ] , HEXTAB [ ORD
( CH -> ) MOD 16 ] ) ;
CH := PTRADD ( CH , 1 ) ;
end (* for *) ;
WRITE ( ' ' ) ;
end (* else *) ;
ADR := PTRADD ( ADR , - 12 ) ;
CH := ADR ;
WRITE ( ' *' ) ;
for I := 1 to 16 do
begin
DUMPCHAR ( CH -> ) ;
CH := PTRADD ( CH , 1 )
end (* for *) ;
WRITELN ( '*' ) ;
end (* DUMPZEILE *) ;
begin (* DUMP *)
WRITELN ( 'Dump Speicherbereich von ' , PVON , ' bis ' , PBIS ) ;
P1 := PTRADD ( PVON , - 16 ) ;
MOD1 := PTR2INT ( P1 ) MOD 16 ;
P1 := PTRADD ( P1 , 16 - MOD1 ) ;
P2 := PTRADD ( PBIS , 15 ) ;
MOD2 := PTR2INT ( P2 ) MOD 16 ;
P2 := PTRADD ( P2 , - MOD2 ) ;
while PTRDIFF ( P1 , P2 ) < 0 do
begin
DUMPZEILE ( P1 , PVON , PBIS ) ;
P1 := PTRADD ( P1 , 16 ) ;
end (* while *) ;
end (* DUMP *) ;
function TRUNC1 ( R : REAL ) : INTEGER ;
begin (* TRUNC1 *)
TRUNC1 := TRUNC ( R ) ;
end (* TRUNC1 *) ;
begin (* HAUPTPROGRAMM *)
R := 0.012345678912 ;
WRITELN ( 'many fraction digits: ' , R : 20 ) ;
MEMSET ( ADDR ( C ) , 'A' , 20 ) ;
MEMSET ( PTRADD ( ADDR ( C ) , 20 ) , CHR ( 10 ) , 20 ) ;
MEMCPY ( PTRADD ( ADDR ( C ) , 40 ) , ADDR ( R ) , SIZEOF ( REAL ) )
;
MEMSET ( PTRADD ( ADDR ( C ) , 50 ) , CHR ( 0XCD ) , 20 ) ;
DUMP ( ADDR ( C ) , PTRADD ( ADDR ( C ) , 99 ) ) ;
R := 0.01 ;
WRITELN ( 'should be 0.01: ' , R ) ;
R := 0.0 ;
R := TRUNC ( R ) + 1 ;
WRITELN ( 'should be 1: ' , R : 7 : 4 ) ;
R := 0.0 ;
R := TRUNC1 ( R ) + 1 ;
WRITELN ( 'should be 1: ' , R : 7 : 4 ) ;
R := R + 0.5 ;
R := ROUND ( R ) + 1 ;
WRITELN ( 'should be 3: ' , R : 7 : 4 ) ;
R := 0.0 ;
R := 1 + TRUNC ( R ) ;
WRITELN ( 'should be 1: ' , R : 7 : 4 ) ;
R := R + 0.5 ;
R := 1 + ROUND ( R ) ;
WRITELN ( 'should be 3: ' , R : 7 : 4 ) ;
WRITELN ( 'should write 3: ' , ROUND ( R ) : 7 ) ;
R := 0.0067 ;
WRITELN ( 'should be 0.0067: ' , R : 7 : 4 , R : 7 : 3 ) ;
R := 12.30 ;
while R <= 12.50 do
begin
WRITELN ( 'R unkorrigiert ..: ' , R : 7 : 2 , R : 7 : 1 , ROUNDX
( R , - 1 ) : 7 : 1 ) ;
R := ROUNDX ( R , - 2 ) ;
WRITELN ( 'R gerundet ......: ' , R : 7 : 2 , R : 7 : 1 , ROUNDX
( R , - 1 ) : 7 : 1 ) ;
R := R + 0.01 ;
end (* while *) ;
for I := 2 DOWNTO - 14 do
WRITELN ( 'test roundx (' , I : 3 , ') = ' , ROUNDX ( 12.543 *
5.678 , I ) : 20 : 12 ) ;
R := - 10.0 ;
while R < 10.0 do
begin
WRITELN ( 'r = ' , R : 5 : 1 , ' trc = ' , TRUNC ( R ) : 3 ,
' RND = ' , ROUND ( R ) : 3 , ' FLR = ' , FLOOR ( R ) :
5 : 1 ) ;
R := R + 0.1 ;
R := ROUND ( R * 10 ) / 10 ;
R := ROUNDX ( R , - 1 ) ;
end (* while *) ;
if FALSE then
begin
R := - 10.0 ;
while R < 10.0 do
begin
X := FLOOR ( R ) ;
WRITELN ( 'Test Trunc:' ) ;
DUMP ( ADDR ( R ) , PTRADD ( ADDR ( R ) , 7 ) ) ;
DUMP ( ADDR ( X ) , PTRADD ( ADDR ( X ) , 7 ) ) ;
R := R + 0.1 ;
R := ROUNDX ( R , - 1 ) ;
end (* while *)
end (* then *)
end (* HAUPTPROGRAMM *) .
|
unit FIVECacheServer_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ FIVECacheServer Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_FIVECacheServer: TGUID = '{3E83FEA1-952F-11D3-A907-004854602370}';
const
{ Component class GUIDs }
Class_CachedObject: TGUID = '{3E83FEA3-952F-11D3-A907-004854602370}';
type
{ Forward declarations: Interfaces }
ICachedObject = interface;
ICachedObjectDisp = dispinterface;
{ Forward declarations: CoClasses }
CachedObject = ICachedObject;
{ Dispatch interface for CachedObject Object }
ICachedObject = interface(IDispatch)
['{3E83FEA2-952F-11D3-A907-004854602370}']
function SetPath(const aPath: WideString): WordBool; safecall;
function GetPath: WideString; safecall;
function SetWorld(const Name: WideString): WordBool; safecall;
function SetClass(const Name: WideString): WordBool; safecall;
function SetObject(X, Y: Integer): WordBool; safecall;
function SetObjectOfWorld(X, Y: Integer; const World: WideString): WordBool; safecall;
function GetFolderIterator(const Folder: WideString): OleVariant; safecall;
function ContainsFolder(const Name: WideString): WordBool; safecall;
procedure CreateFolder(const Name: WideString); safecall;
function Get_Recache: WordBool; safecall;
procedure Set_Recache(Value: WordBool); safecall;
function Properties(const Name: WideString): WideString; safecall;
procedure KeepAlive; safecall;
property Recache: WordBool read Get_Recache write Set_Recache;
end;
{ DispInterface declaration for Dual Interface ICachedObject }
ICachedObjectDisp = dispinterface
['{3E83FEA2-952F-11D3-A907-004854602370}']
function SetPath(const aPath: WideString): WordBool; dispid 1;
function GetPath: WideString; dispid 2;
function SetWorld(const Name: WideString): WordBool; dispid 3;
function SetClass(const Name: WideString): WordBool; dispid 4;
function SetObject(X, Y: Integer): WordBool; dispid 5;
function SetObjectOfWorld(X, Y: Integer; const World: WideString): WordBool; dispid 6;
function GetFolderIterator(const Folder: WideString): OleVariant; dispid 7;
function ContainsFolder(const Name: WideString): WordBool; dispid 8;
procedure CreateFolder(const Name: WideString); dispid 10;
property Recache: WordBool dispid 12;
function Properties(const Name: WideString): WideString; dispid 13;
procedure KeepAlive; dispid 9;
end;
{ CachedObjectObject }
CoCachedObject = class
class function Create: ICachedObject;
class function CreateRemote(const MachineName: string): ICachedObject;
end;
implementation
uses ComObj;
class function CoCachedObject.Create: ICachedObject;
begin
Result := CreateComObject(Class_CachedObject) as ICachedObject;
end;
class function CoCachedObject.CreateRemote(const MachineName: string): ICachedObject;
begin
Result := CreateRemoteComObject(MachineName, Class_CachedObject) as ICachedObject;
end;
end.
|
unit QuickList_DetailData;
interface
uses
QuickSortList,
define_datetime,
define_stock_quotes;
type
PDetailDataListItem = ^TDetailDataListItem;
TDetailDataListItem = record
DetailDateTime: TDateTimeStock;
DetailData: PRT_Quote_Detail;
end;
TDetailDataList = class(TALBaseQuickSortList)
public
function GetItem(Index: Integer): TDateTimeStock;
procedure SetItem(Index: Integer; const AStockDateTime: TDateTimeStock);
function GetObject(Index: Integer): PRT_Quote_Detail;
procedure PutObject(Index: Integer; ADetailData: PRT_Quote_Detail);
public
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
procedure InsertItem(Index: Integer; const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail);
function CompareItems(const Index1, Index2: Integer): Integer; override;
public
function IndexOf(AStockDateTime: TDateTimeStock): Integer;
function IndexOfObject(ADetailData: PRT_Quote_Detail): Integer;
Function AddDetailData(const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail): Integer;
function Find(AStockDateTime: TDateTimeStock; var Index: Integer): Boolean;
procedure InsertObject(Index: Integer; const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail);
property DetailDateTime[Index: Integer]: TDateTimeStock read GetItem write SetItem; default;
property DetailData[Index: Integer]: PRT_Quote_Detail read GetObject write PutObject;
end;
implementation
{********************************************************************************}
function TDetailDataList.AddDetailData(const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail): Integer;
begin
if not Sorted then
Result := FCount
else if Find(AStockDateTime, Result) then
case Duplicates of
lstDupIgnore: Exit;
lstDupError: Error(@SALDuplicateItem, 0);
end;
InsertItem(Result, AStockDateTime, ADetailData);
end;
{*****************************************************************************************}
procedure TDetailDataList.InsertItem(Index: Integer; const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail);
var
tmpDetailDataListItem: PDetailDataListItem;
begin
New(tmpDetailDataListItem);
tmpDetailDataListItem^.DetailDateTime := AStockDateTime;
tmpDetailDataListItem^.DetailData := ADetailData;
try
inherited InsertItem(index, tmpDetailDataListItem);
except
Dispose(tmpDetailDataListItem);
raise;
end;
end;
{***************************************************************************}
function TDetailDataList.CompareItems(const Index1, Index2: integer): Integer;
var
tmpItem1, tmpItem2: PDetailDataListItem;
begin
tmpItem1 := PDetailDataListItem(Get(Index1));
tmpItem2 := PDetailDataListItem(Get(Index2));
result := tmpItem1^.DetailDateTime.Date.Value - tmpItem2^.DetailDateTime.Date.Value;
if 0 = Result then
begin
result := tmpItem1^.DetailDateTime.Time.Value - tmpItem2^.DetailDateTime.Time.Value;
end;
end;
{***********************************************************************}
function TDetailDataList.Find(AStockDateTime: TDateTimeStock; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := Integer(GetItem(I)) - Integer(AStockDateTime);
if C < 0 then
begin
L := I + 1
end else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> lstDupAccept then
L := I;
end;
end;
end;
Index := L;
end;
{*******************************************************}
function TDetailDataList.GetItem(Index: Integer): TDateTimeStock;
begin
Result := PDetailDataListItem(Get(index))^.DetailDateTime;
end;
{******************************************************}
function TDetailDataList.IndexOf(AStockDateTime: TDateTimeStock): Integer;
begin
if not Sorted then
Begin
Result := 0;
while (Result < FCount) and (Integer(GetItem(result)) <> Integer(AStockDateTime)) do
Inc(Result);
if Result = FCount then
Result := -1;
end else if not Find(AStockDateTime, Result) then
Result := -1;
end;
{*******************************************************************************************}
procedure TDetailDataList.InsertObject(Index: Integer; const AStockDateTime: TDateTimeStock; ADetailData: PRT_Quote_Detail);
var
tmpDetailDataListItem: PDetailDataListItem;
begin
New(tmpDetailDataListItem);
tmpDetailDataListItem^.DetailDateTime := AStockDateTime;
tmpDetailDataListItem^.DetailData := ADetailData;
try
inherited insert(index, tmpDetailDataListItem);
except
Dispose(tmpDetailDataListItem);
raise;
end;
end;
{***********************************************************************}
procedure TDetailDataList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lstDeleted then
dispose(ptr);
inherited Notify(Ptr, Action);
end;
{********************************************************************}
procedure TDetailDataList.SetItem(Index: Integer; const AStockDateTime: TDateTimeStock);
var
tmpDetailDataListItem: PDetailDataListItem;
begin
New(tmpDetailDataListItem);
tmpDetailDataListItem^.DetailDateTime := AStockDateTime;
tmpDetailDataListItem^.DetailData := nil;
Try
Put(Index, tmpDetailDataListItem);
except
Dispose(tmpDetailDataListItem);
raise;
end;
end;
{*********************************************************}
function TDetailDataList.GetObject(Index: Integer): PRT_Quote_Detail;
begin
if (Index < 0) or (Index >= FCount) then
Error(@SALListIndexError, Index);
Result := PDetailDataListItem(Get(index))^.DetailData;
end;
{***************************************************************}
function TDetailDataList.IndexOfObject(ADetailData: PRT_Quote_Detail): Integer;
begin
for Result := 0 to Count - 1 do
begin
if GetObject(Result) = ADetailData then
begin
Exit;
end;
end;
Result := -1;
end;
{*******************************************************************}
procedure TDetailDataList.PutObject(Index: Integer; ADetailData: PRT_Quote_Detail);
begin
if (Index < 0) or (Index >= FCount) then
Error(@SALListIndexError, Index);
PDetailDataListItem(Get(index))^.DetailData := ADetailData;
end;
end.
|
unit MapCompress;
interface
uses
Matrix, Classes, Windows;
type
any = 0..0;
TMapSection = array[any] of single;
TMapImage = string;
function CompressMap ( Matrix : IMatrix; Area : TRect; out image : TMapImage; Resolution : integer ) : boolean;
function DecompressMap( Matrix : IMatrix; const image : TMapImage ) : boolean;
implementation
uses
CompStringsParser, SysUtils;
const
LineSep = ':';
PairSep = ',';
DataSep = '=';
const
Scale = 1000;
function CompressMap( Matrix : IMatrix; Area : TRect; out image : TMapImage; Resolution : integer ) : boolean;
function ConvertValue( val : single ) : integer;
begin
result := Resolution*(round(Scale*val) div Resolution)
end;
var
x, y : integer;
value : integer;
lastvalue : integer;
count : integer;
line : string;
begin
try
image := IntToStr(Area.Bottom - Area.Top + 1) + LineSep + IntToStr(Area.Right - Area.Left + 1) + LineSep;
for y := Area.Top to Area.Bottom do
begin
line := '';
lastvalue := ConvertValue( Matrix.getElement(y, Area.Left) );
count := 0;
for x := Area.Left to Area.Right do
begin
value := ConvertValue( Matrix.getElement(y, x) );
if value <> lastvalue
then
begin
line := line + IntToStr(lastvalue) + DataSep + IntToStr(count) + PairSep;
lastvalue := value;
count := 1;
end
else inc( count );
end;
line := line + IntToStr(lastvalue) + DataSep + IntToStr(count) + PairSep;
image := image + line + LineSep;
end;
result := true;
except
image := '';
result := false;
end;
end;
function DecompressMap( Matrix : IMatrix; const image : TMapImage ) : boolean;
var
p : integer;
p2, p3 : integer;
m, n : integer;
i, j : integer;
line : string;
pair : string;
val : integer;
count : integer;
error : boolean;
begin
try
p := 1;
n := StrToInt(GetNextStringUpTo( image, p, LineSep ));
m := StrToInt(GetNextStringUpTo( image, p, LineSep ));
Matrix.setDimensions( n, m );
i := 0;
j := 0;
error := false;
repeat
line := GetNextStringUpTo( image, p, LineSep );
if line <> ''
then
begin
p2 := 1;
repeat
pair := GetNextStringUpTo( line, p2, PairSep );
if pair <> ''
then
begin
p3 := 1;
try
val := StrToInt( GetNextStringUpTo( pair, p3, DataSep ) );
except
val := 0;
end;
try
count := StrToInt( GetNextStringUpTo( pair, p3, DataSep ) );
except
count := 0;
error := true;
end;
while count > 0 do
begin
Matrix.setElement( i, j, val/Scale );
inc( j );
dec( count );
end;
end
else raise Exception.Create( 'Map image corrupted!' );
until p2 >= length(line);
inc( i );
j := 0;
end
else raise Exception.Create( 'Map image corrupted!' );
until p >= length(image);
result := not error;
except
result := false;
end;
end;
end.
|
unit SQLLang;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections;
type
TFieldType = (ftInteger, ftString, ftFloat, ftDateTime, ftBlob, ftBoolean, ftParam);
TDIType = (diInc, diDec, diDiv, diMul);
TWhereUnion = (wuAnd, wuOr, wuNotAnd, wuNotOr);
TField = record
private
function GetSQL: string;
public
FieldType:TFieldType;
FieldName:string;
PrimaryKey:Boolean;
AutoInc:Boolean;
NotNull:Boolean;
property SQL:string read GetSQL;
end;
TFields = TList<TField>;
TFieldNames = TStringList;
TUnionWhere = TStringList;
TInsertValue = record
public
FieldType:TFieldType;
FieldName:string;
Value:Variant;
end;
TInsertValues = TList<TInsertValue>;
TDIValue = record
public
FieldType:TFieldType;
DIType:TDIType;
FieldName:string;
Value:Variant;
end;
TDIValues = TList<TDIValue>;
TTable = class;
TInsertInto = class;
TUpdate = class;
TSelect = class;
TDelete = class;
TDropTable = class;
TUpdateBlob = class;
BaseSQL = class
private
FName:string;
procedure SetName(const Value: string);
public
property TableName:string read FName write SetName;
end;
SQL = class(BaseSQL)
private
FWhereStr:string;
FUWheres:TUnionWhere;
function GetWhere: string;
function InsertUnion(const Union: TWhereUnion): string;
public
function GetSQL:string; virtual; abstract;
procedure EndCreate; virtual;
procedure Clear; virtual;
procedure WhereParenthesesOpen(Union:TWhereUnion = wuAnd);
procedure WhereParenthesesClose;
procedure WhereFieldBetween(const FieldName:string; const ValueLeft, ValueRight:TDateTime; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldBetween(const FieldName:string; const ValueLeft, ValueRight:Extended; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldBetween(const FieldName:string; const ValueLeft, ValueRight:Integer; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldIsNull(const FieldName:string; const Union:TWhereUnion = wuAnd);
procedure WhereFieldIsNotNull(const FieldName:string; const Union:TWhereUnion = wuAnd);
procedure WhereField(const FieldName, Oper: string; const FieldValue: string; const Union:TWhereUnion = wuAnd); overload;
procedure WhereField(const FieldName, Oper: string; const FieldValue: Extended; const Union:TWhereUnion = wuAnd); overload;
procedure WhereField(const FieldName, Oper: string; const FieldValue: Integer; const Union:TWhereUnion = wuAnd); overload;
procedure WhereField(const FieldName, Oper: string; const FieldValue: TDateTime; const Union:TWhereUnion = wuAnd); overload;
procedure WhereField(const FieldName, Oper: string; const FieldValue: Boolean; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldWOQ(const FieldName, Oper: string; const FieldValue: string; const Union:TWhereUnion = wuAnd); //Без ковычек
procedure WhereFieldIN(const FieldName: string; const FieldValues:array of string; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldIN(const FieldName: string; const FieldValues:array of Extended; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldIN(const FieldName: string; const FieldValues:array of Integer; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldIN(const FieldName: string; const FieldValues:array of TDateTime; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldIN(const FieldName: string; const FieldValues:array of Boolean; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldEqual(const FieldName: string; const FieldValue: string; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldEqual(const FieldName: string; const FieldValue: Extended; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldEqual(const FieldName: string; const FieldValue: Integer; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldEqual(const FieldName: string; const FieldValue: TDateTime; const Union:TWhereUnion = wuAnd); overload;
procedure WhereFieldEqual(const FieldName: string; const FieldValue: Boolean; const Union:TWhereUnion = wuAnd); overload;
procedure WhereNotFieldEqual(const FieldName: string; const FieldValue: string; const Union:TWhereUnion = wuAnd); overload;
procedure WhereNotFieldEqual(const FieldName: string; const FieldValue: Extended; const Union:TWhereUnion = wuAnd); overload;
procedure WhereNotFieldEqual(const FieldName: string; const FieldValue: Integer; const Union:TWhereUnion = wuAnd); overload;
procedure WhereNotFieldEqual(const FieldName: string; const FieldValue: TDateTime; const Union:TWhereUnion = wuAnd); overload;
procedure WhereNotFieldEqual(const FieldName: string; const FieldValue: Boolean; const Union:TWhereUnion = wuAnd); overload;
procedure WhereExists(const Select:string; const Union:TWhereUnion = wuAnd);
procedure WhereStr(const Value:string);
constructor Create; virtual;
property Where:string read GetWhere;
public
class function CreateField:TField;
class function CreateTable:TTable; overload;
class function CreateTable(TableName:string):TTable; overload;
class function InsertInto:TInsertInto; overload;
class function InsertInto(TableName:string):TInsertInto; overload;
class function Delete:TDelete; overload;
class function Delete(TableName:string):TDelete; overload;
class function DropTable:TDropTable;
class function Update:TUpdate; overload;
class function Update(TableName:string):TUpdate; overload;
class function Select:TSelect; overload;
class function Select(TableName:string):TSelect; overload;
class function UpdateBlob:TUpdateBlob; overload;
class function UpdateBlob(TableName:string):TUpdateBlob; overload;
//
class function PRAGMA(Key, Value:string):string;
class function SelectLastInsertID:string;
//
end;
TTable = class(BaseSQL)
private
function GetField(Index: Integer): TField;
procedure SetField(Index: Integer; const Value: TField);
protected
FFields:TFields;
public
function GetSQL:string; virtual;
procedure AddField(Name:string; FieldType:TFieldType; PrimaryKey:Boolean = False; NotNull:Boolean = False; AutoInc:Boolean = False); virtual;
procedure EndCreate; virtual;
procedure Clear; virtual;
constructor Create; overload; virtual;
constructor Create(pTableName:string); overload; virtual;
property Fields[Index:Integer]:TField read GetField write SetField;
property TableName;
end;
TInsertInto = class(BaseSQL)
private
FDoubleDoubleQuote: Boolean;
procedure SetDoubleDoubleQuote(const Value: Boolean);
protected
FFieldValues:TInsertValues;
public
function GetSQL:string;
procedure EndCreate;
procedure Clear;
procedure AddValue(FieldName:string; FieldValue:Integer); overload;
procedure AddValue(FieldName:string; FieldValue:string); overload;
procedure AddValue(FieldName:string; FieldValue:Extended); overload;
procedure AddValue(FieldName:string; FieldValue:TDateTime); overload;
procedure AddValue(FieldName:string; FieldValue:Boolean); overload;
procedure AddValueAsParam(FieldName:string; ParamChar:string = ':'; CharOnly:Boolean = False);
constructor Create; virtual;
property TableName;
property DoubleDoubleQuote:Boolean read FDoubleDoubleQuote write SetDoubleDoubleQuote default False;
end;
TUpdate = class(SQL)
private
FDoubleDoubleQuote: Boolean;
procedure SetDoubleDoubleQuote(const Value: Boolean);
protected
FFieldValues:TInsertValues;
FDIValues:TDIValues;
public
function GetSQL:string; override;
procedure Clear; override;
procedure AddValue(FieldName:string; FieldValue:Integer); overload;
procedure AddValue(FieldName:string; FieldValue:string); overload;
procedure AddValue(FieldName:string; FieldValue:Extended); overload;
procedure AddValue(FieldName:string; FieldValue:TDateTime); overload;
procedure AddValue(FieldName:string; FieldValue:Boolean); overload;
procedure IncValue(FieldName:string; Value:Integer); overload;
procedure IncValue(FieldName:string; Value:Extended); overload;
procedure DecValue(FieldName:string; Value:Integer); overload;
procedure DecValue(FieldName:string; Value:Extended); overload;
procedure MulValue(FieldName:string; Value:Integer); overload;
procedure MulValue(FieldName:string; Value:Extended); overload;
procedure DivValue(FieldName:string; Value:Integer); overload;
procedure DivValue(FieldName:string; Value:Extended); overload;
procedure AddValueAsParam(FieldName:string; ParamChar:string = ':'; CharOnly:Boolean = False);
constructor Create; override;
property TableName;
property DoubleDoubleQuote:Boolean read FDoubleDoubleQuote write SetDoubleDoubleQuote;
end;
TSelect = class(SQL)
private
FOrderBy:TStringList;
FJoins:TStringList;
FLimitInt:Integer;
FDistinct:Boolean;
function GetField(Index: Integer): string;
procedure SetField(Index: Integer; const Value: string);
function GetOrderBy: string;
protected
FFields:TFieldNames;
public
function GetSQL:string; override;
procedure AddField(Name:string; IFNULL:string = '');
procedure AddFieldCount(Name:string; Alias:string = '');
procedure InnerJoin(JoinTable, BaseField, JoinField:string);
procedure LeftJoin(JoinTable, BaseField, JoinField:string; AndWhere:string = '');
procedure RightJoin(JoinTable, BaseField, JoinField:string);
procedure OrderBy(FieldName:string; DESC:Boolean = False);
procedure Clear; override;
constructor Create; override;
property Fields[Index:Integer]:string read GetField write SetField;
property Distinct:Boolean read FDistinct write FDistinct;
property Limit:Integer read FLimitInt write FLimitInt;
property OrderByStr:string read GetOrderBy;
property TableName;
end;
TDelete = class(SQL)
public
function GetSQL:string; override;
procedure Clear; override;
constructor Create; override;
property Where;
property TableName;
end;
TDropTable = class(BaseSQL)
public
function GetSQL:string;
procedure EndCreate;
procedure Clear;
constructor Create; virtual;
property TableName;
end;
TUpdateBlob = class(SQL)
private
FBlobField:string;
public
function GetSQL:string; override;
property BlobField:string read FBlobField write FBlobField;
property Where;
property TableName;
end;
function Field(Name:string; FieldType:TFieldType; PrimaryKey, NotNull, AutoInc:Boolean):TField;
function InsertValue(Name:string; FieldType:TFieldType; Value:Variant):TInsertValue;
function FloatToSQLStr(Value:Extended):string;
function FieldTypeToStr(Value:TFieldType):string;
function FieldTypeToString(Value:TFieldType):string;
implementation
function FloatToSQLStr(Value:Extended):string;
begin
Result:=FloatToStr(Value);
Result:=StringReplace(Result, ',', '.', [rfReplaceAll]);
end;
function BoolToSQLStr(Value:Boolean):string;
begin
if Value then Exit('1') else Exit('0');
end;
function FieldTypeToStr(Value:TFieldType):string;
begin
case Value of
ftInteger: Result:='INTEGER';
ftString: Result:='TEXT';
ftFloat: Result:='REAL';
ftDateTime: Result:='REAL';
ftBlob: Result:='BLOB';
ftBoolean: Result:='INTEGER';
end;
end;
function FieldTypeToString(Value:TFieldType):string;
begin
case Value of
ftInteger: Result:='ftInteger';
ftString: Result:='ftString';
ftFloat: Result:='ftFloat';
ftDateTime: Result:='ftDateTime';
ftBlob: Result:='ftBlob';
ftBoolean: Result:='ftBoolean';
end;
end;
function Field;
begin
Result.FieldType:=FieldType;
Result.FieldName:=Name;
Result.PrimaryKey:=PrimaryKey;
Result.AutoInc:=AutoInc;
Result.NotNull:=NotNull;
end;
function InsertValue(Name:string; FieldType:TFieldType; Value:Variant):TInsertValue; overload;
begin
Result.FieldName:=Name;
Result.FieldType:=FieldType;
Result.Value:=Value;
end;
function DIValue(Name:string; FieldType:TFieldType; DIType:TDIType; Value:Variant):TDIValue; overload;
begin
Result.FieldName:=Name;
Result.FieldType:=FieldType;
Result.DIType:=DIType;
Result.Value:=Value;
end;
{ SQL }
class function SQL.CreateField: TField;
begin
Result:=Field('', ftInteger, False, False, False);
end;
class function SQL.CreateTable: TTable;
begin
Result:=TTable.Create;
end;
class function SQL.Delete: TDelete;
begin
Result:=TDelete.Create;
end;
class function SQL.CreateTable(TableName: string): TTable;
begin
Result:=TTable.Create;
Result.TableName:=TableName;
end;
class function SQL.Delete(TableName: string): TDelete;
begin
Result:=TDelete.Create;
Result.TableName:=TableName;
end;
class function SQL.DropTable:TDropTable;
begin
Result:=TDropTable.Create;
end;
class function SQL.InsertInto(TableName: string): TInsertInto;
begin
Result:=TInsertInto.Create;
Result.TableName:=TableName;
end;
class function SQL.InsertInto: TInsertInto;
begin
Result:=TInsertInto.Create;
end;
class function SQL.PRAGMA(Key, Value: string): string;
begin
Result:='PRAGMA '+Key+' = "'+Value+'"';
end;
class function SQL.Select(TableName: string): TSelect;
begin
Result:=TSelect.Create;
Result.TableName:=TableName;
end;
class function SQL.SelectLastInsertID:string;
begin
Result:='SELECT LAST_INSERT_ID();';
end;
class function SQL.Select:TSelect;
begin
Result:=TSelect.Create;
end;
class function SQL.Update: TUpdate;
begin
Result:=TUpdate.Create;
end;
class function SQL.Update(TableName: string): TUpdate;
begin
Result:=TUpdate.Create;
Result.TableName:=TableName;
end;
class function SQL.UpdateBlob: TUpdateBlob;
begin
Result:=TUpdateBlob.Create;
end;
class function SQL.UpdateBlob(TableName: string): TUpdateBlob;
begin
Result:=TUpdateBlob.Create;
Result.TableName:=TableName;
end;
{ TTable }
constructor TTable.Create(pTableName: string);
begin
Create;
TableName:=pTableName;
end;
constructor TTable.Create;
begin
inherited;
FFields:=TFields.Create;
end;
function TTable.GetField(Index: Integer): TField;
begin
Result:=FFields[Index];
end;
function TTable.GetSQL: string;
var i:Integer;
begin
Result:='CREATE TABLE '+TableName+' (';
for i:= 0 to FFields.Count - 1 do
begin
Result:=Result+FFields[i].GetSQL;
if i <> FFields.Count - 1 then Result:=Result+', ';
end;
Result:=Result+')';
end;
procedure TTable.AddField;
begin
FFields.Add(Field(Name, FieldType, PrimaryKey, NotNull, AutoInc));
end;
procedure TTable.Clear;
begin
TableName:='';
FFields.Clear;
end;
procedure TTable.EndCreate;
begin
Clear;
Free;
end;
procedure TTable.SetField(Index: Integer; const Value: TField);
begin
FFields[Index]:=Value;
end;
{ TField }
function TField.GetSQL: string;
begin
Result:=FieldName+' '+FieldTypeToStr(FieldType);
if PrimaryKey then Result:=Result+' PRIMARY KEY';
if NotNull then Result:=Result+' NOT NULL';
if AutoInc then Result:=Result+' AUTOINCREMENT';
end;
{ TInsertInto }
constructor TInsertInto.Create;
begin
inherited;
FDoubleDoubleQuote:=False;
FFieldValues:=TInsertValues.Create;
end;
function TInsertInto.GetSQL: string;
var i:Integer;
begin
Result:='INSERT INTO '+TableName+' (';
for i:= 0 to FFieldValues.Count - 1 do
begin
Result:=Result+FFieldValues[i].FieldName;
if i <> FFieldValues.Count - 1 then Result:=Result+', ';
end;
Result:=Result+') VALUES (';
for i:= 0 to FFieldValues.Count - 1 do
begin
case FFieldValues[i].FieldType of
ftInteger: Result:=Result+QuotedStr(IntToStr(FFieldValues[i].Value));
ftString: Result:=Result+QuotedStr(FFieldValues[i].Value);
ftFloat: Result:=Result+QuotedStr(FloatToSQLStr(FFieldValues[i].Value));
ftDateTime:Result:=Result+QuotedStr(FloatToSQLStr(FFieldValues[i].Value));
ftBoolean: Result:=Result+QuotedStr(BoolToSQLStr(FFieldValues[i].Value));
ftParam: Result:=Result+FFieldValues[i].Value;
end;
if i <> FFieldValues.Count - 1 then Result:=Result+', ';
end;
Result:=Result+')';
end;
procedure TInsertInto.SetDoubleDoubleQuote(const Value: Boolean);
begin
FDoubleDoubleQuote:=Value;
end;
procedure TInsertInto.AddValue(FieldName: string; FieldValue: Extended);
begin
FFieldValues.Add(InsertValue(FieldName, ftFloat, FieldValue));
end;
procedure TInsertInto.AddValue(FieldName, FieldValue: string);
begin
if FDoubleDoubleQuote then
FieldValue:=StringReplace(FieldValue, '"', '""', [rfReplaceAll]);
FFieldValues.Add(InsertValue(FieldName, ftString, FieldValue));
end;
procedure TInsertInto.AddValue(FieldName: string; FieldValue: Integer);
begin
FFieldValues.Add(InsertValue(FieldName, ftInteger, FieldValue));
end;
procedure TInsertInto.AddValue(FieldName: string; FieldValue: Boolean);
begin
FFieldValues.Add(InsertValue(FieldName, ftBoolean, FieldValue));
end;
procedure TInsertInto.AddValueAsParam(FieldName:string; ParamChar:string = ':'; CharOnly:Boolean = False);
begin
if CharOnly then
FFieldValues.Add(InsertValue(FieldName, ftParam, ParamChar))
else
FFieldValues.Add(InsertValue(FieldName, ftParam, ParamChar+FieldName));
end;
procedure TInsertInto.AddValue(FieldName: string; FieldValue: TDateTime);
begin
FFieldValues.Add(InsertValue(FieldName, ftDateTime, FieldValue));
end;
procedure TInsertInto.Clear;
begin
TableName:='';
FFieldValues.Clear;
end;
procedure TInsertInto.EndCreate;
begin
Clear;
Free;
end;
{ TSelect }
procedure TSelect.AddField(Name:string; IFNULL:string);
begin
if IFNULL.IsEmpty then FFields.Add(Name)
else FFields.Add('IFNULL('+Name+', '+IFNULL+')');
end;
procedure TSelect.AddFieldCount(Name, Alias: string);
begin
Name:='COUNT('+Name+')';
if Alias <> '' then Name:=Name+' as '+Alias;
FFields.Add(Name);
end;
procedure TSelect.Clear;
begin
FName:='';
FFields.Clear;
FJoins.Clear;
FOrderBy.Clear;
end;
constructor TSelect.Create;
begin
inherited;
FFields:=TFieldNames.Create;
FJoins:=TStringList.Create;
FOrderBy:=TStringList.Create;
FLimitInt:=0;
end;
function TSelect.GetField(Index: Integer): string;
begin
Result:=FFields[Index];
end;
function TSelect.GetOrderBy: string;
var i:Integer;
begin
if FOrderBy.Count <= 0 then Exit('');
Result:=' ORDER BY ';
for i:= 0 to FOrderBy.Count-1 do
begin
Result:=Result+FOrderBy[i];
if i <> FOrderBy.Count - 1 then Result:=Result+', ';
end;
end;
function TSelect.GetSQL: string;
var i:Integer;
FieldsStr, ALimit, AJoins:string;
begin
if FLimitInt > 0 then ALimit:=' LIMIT '+IntToStr(FLimitInt);
if FDistinct then Result:='SELECT DISTINCT ' else Result:='SELECT ';
FieldsStr:='';
for i:= 0 to FFields.Count - 1 do
begin
FieldsStr:=FieldsStr+FFields[i];
if i <> FFields.Count - 1 then FieldsStr:=FieldsStr+', ';
end;
AJoins:='';
for i:= 0 to FJoins.Count-1 do AJoins:=AJoins+FJoins[i]+' ';
if AJoins <> '' then AJoins:=' '+AJoins;
Result:=Result+FieldsStr+' FROM '+TableName+AJoins+Where+OrderByStr+ALimit;
end;
procedure TSelect.InnerJoin(JoinTable, BaseField, JoinField:string);
begin
FJoins.Add('INNER JOIN '+JoinTable+' ON '+FName+'.'+BaseField+'='+JoinTable+'.'+JoinField);
end;
procedure TSelect.LeftJoin(JoinTable, BaseField, JoinField: string; AndWhere:string = '');
var tmp:string;
begin
if AndWhere.Length > 0 then tmp:=' and '+AndWhere
else tmp:='';
FJoins.Add('LEFT JOIN '+JoinTable+' ON '+FName+'.'+BaseField+'='+JoinTable+'.'+JoinField+tmp);
end;
procedure TSelect.OrderBy(FieldName: string; DESC: Boolean);
begin
if DESC then FieldName:=FieldName+' DESC';
FOrderBy.Add(FieldName);
end;
procedure TSelect.RightJoin(JoinTable, BaseField, JoinField: string);
begin
FJoins.Add('RIGHT JOIN '+JoinTable+' ON '+FName+'.'+BaseField+'='+JoinTable+'.'+JoinField);
end;
procedure TSelect.SetField(Index: Integer; const Value: string);
begin
FFields[Index]:=Value;
end;
{ TDelete }
procedure TDelete.Clear;
begin
FName:='';
end;
constructor TDelete.Create;
begin
inherited;
end;
function TDelete.GetSQL: string;
begin
Result:='DELETE FROM '+FName+Where;
end;
{ TUpdate }
procedure TUpdate.AddValue(FieldName: string; FieldValue: Extended);
begin
FFieldValues.Add(InsertValue(FieldName, ftFloat, FieldValue));
end;
procedure TUpdate.AddValue(FieldName, FieldValue: string);
begin
if FDoubleDoubleQuote then
FieldValue:=StringReplace(FieldValue, '"', '""', [rfReplaceAll]);
FFieldValues.Add(InsertValue(FieldName, ftString, FieldValue));
end;
procedure TUpdate.AddValue(FieldName: string; FieldValue: Integer);
begin
FFieldValues.Add(InsertValue(FieldName, ftInteger, FieldValue));
end;
procedure TUpdate.AddValue(FieldName: string; FieldValue: Boolean);
begin
FFieldValues.Add(InsertValue(FieldName, ftBoolean, FieldValue));
end;
procedure TUpdate.AddValueAsParam(FieldName: string; ParamChar:string = ':'; CharOnly:Boolean = False);
begin
if CharOnly then
FFieldValues.Add(InsertValue(FieldName, ftParam, ParamChar))
else
FFieldValues.Add(InsertValue(FieldName, ftParam, ParamChar+FieldName));
end;
procedure TUpdate.AddValue(FieldName: string; FieldValue: TDateTime);
begin
FFieldValues.Add(InsertValue(FieldName, ftDateTime, FieldValue));
end;
procedure TUpdate.Clear;
begin
TableName:='';
FFieldValues.Clear;
end;
constructor TUpdate.Create;
begin
inherited;
FDoubleDoubleQuote:=False;
FFieldValues:=TInsertValues.Create;
FDIValues:=TDIValues.Create;
end;
procedure TUpdate.DecValue(FieldName: string; Value: Extended);
begin
FDIValues.Add(DIValue(FieldName, ftFloat, diDec, Value));
end;
procedure TUpdate.DivValue(FieldName: string; Value: Integer);
begin
FDIValues.Add(DIValue(FieldName, ftInteger, diDiv, Value));
end;
procedure TUpdate.DivValue(FieldName: string; Value: Extended);
begin
FDIValues.Add(DIValue(FieldName, ftFloat, diDiv, Value));
end;
procedure TUpdate.DecValue(FieldName: string; Value: Integer);
begin
FDIValues.Add(DIValue(FieldName, ftInteger, diDec, Value));
end;
procedure TUpdate.IncValue(FieldName: string; Value: Extended);
begin
FDIValues.Add(DIValue(FieldName, ftFloat, diInc, Value));
end;
procedure TUpdate.IncValue(FieldName: string; Value: Integer);
begin
FDIValues.Add(DIValue(FieldName, ftInteger, diInc, Value));
end;
procedure TUpdate.MulValue(FieldName: string; Value: Integer);
begin
FDIValues.Add(DIValue(FieldName, ftInteger, diMul, Value));
end;
procedure TUpdate.MulValue(FieldName: string; Value: Extended);
begin
FDIValues.Add(DIValue(FieldName, ftFloat, diMul, Value));
end;
procedure TUpdate.SetDoubleDoubleQuote(const Value: Boolean);
begin
FDoubleDoubleQuote:=Value;
end;
function TUpdate.GetSQL: string;
var i:Integer;
str:string;
begin
Result:='UPDATE '+TableName+' SET ';
for i:= 0 to FFieldValues.Count - 1 do
begin
str:='';
case FFieldValues[i].FieldType of
ftInteger: str:=QuotedStr(IntToStr(FFieldValues[i].Value));
ftString: str:=QuotedStr(FFieldValues[i].Value);
ftFloat: str:=QuotedStr(FloatToSQLStr(FFieldValues[i].Value));
ftDateTime:str:=QuotedStr(FloatToSQLStr(FFieldValues[i].Value));
ftBoolean: str:=QuotedStr(BoolToSQLStr(FFieldValues[i].Value));
ftParam: str:=FFieldValues[i].Value;
end;
Result:=Result+FFieldValues[i].FieldName + ' = '+str;
if i <> FFieldValues.Count - 1 then Result:=Result+', ';
end;
for i:= 0 to FDIValues.Count - 1 do
begin
str:='';
case FDIValues[i].FieldType of
ftInteger: str:=QuotedStr(IntToStr(FDIValues[i].Value));
ftFloat: str:=QuotedStr(FloatToSQLStr(FDIValues[i].Value));
end;
case FDIValues[i].DIType of
diInc: Result:=Result+FDIValues[i].FieldName+' = '+FDIValues[i].FieldName+' + '+str;
diDec: Result:=Result+FDIValues[i].FieldName+' = '+FDIValues[i].FieldName+' - '+str;
diMul: Result:=Result+FDIValues[i].FieldName+' = '+FDIValues[i].FieldName+' * '+str;
diDiv: Result:=Result+FDIValues[i].FieldName+' = '+FDIValues[i].FieldName+' / '+str;
end;
if i <> FDIValues.Count - 1 then Result:=Result+', ';
end;
Result:=Result+Where;
end;
{ TDropTable }
procedure TDropTable.Clear;
begin
TableName:='';
end;
constructor TDropTable.Create;
begin
inherited;
end;
procedure TDropTable.EndCreate;
begin
Clear;
Free;
end;
function TDropTable.GetSQL:string;
begin
Result:='DROP TABLE '+TableName;
end;
{ SQL }
procedure SQL.Clear;
begin
FUWheres.Clear;
end;
constructor SQL.Create;
begin
inherited;
FUWheres:=TUnionWhere.Create;
end;
procedure SQL.EndCreate;
begin
Clear;
FUWheres.Free;
Free;
end;
function SQL.GetWhere: string;
var i:Integer;
begin
Result:='';
for i:= 0 to FUWheres.Count-1 do Result:=Result+FUWheres[i];
if FWhereStr <> '' then Result:=Result+' '+FWhereStr;
if Result <> '' then Result:=' WHERE '+Result;
end;
procedure BaseSQL.SetName(const Value: string);
begin
FName:=Value;
end;
procedure SQL.WhereExists(const Select: string; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+' EXISTS('+Select+')');
end;
procedure SQL.WhereField(const FieldName, Oper: string; const FieldValue: Extended; const Union:TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+QuotedStr(FloatToSQLStr(FieldValue)));
end;
procedure SQL.WhereField(const FieldName, Oper: string; const FieldValue:string; const Union:TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+QuotedStr(FieldValue));
end;
procedure SQL.WhereField(const FieldName, Oper: string; const FieldValue: Integer; const Union:TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+QuotedStr(IntToStr(FieldValue)));
end;
procedure SQL.WhereField(const FieldName, Oper: string; const FieldValue: Boolean; const Union:TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+QuotedStr(BoolToSQLStr(FieldValue)));
end;
procedure SQL.WhereFieldBetween(const FieldName: string; const ValueLeft, ValueRight: TDateTime; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+' between '+FloatToSQLStr(ValueLeft)+' and '+FloatToSQLStr(ValueRight));
end;
procedure SQL.WhereFieldBetween(const FieldName: string; const ValueLeft, ValueRight: Extended; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+' between '+FloatToSQLStr(ValueLeft)+' and '+FloatToSQLStr(ValueRight));
end;
procedure SQL.WhereFieldBetween(const FieldName: string; const ValueLeft, ValueRight: Integer; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+' between '+IntToStr(ValueLeft)+' and '+IntToStr(ValueRight));
end;
procedure SQL.WhereField(const FieldName, Oper: string; const FieldValue: TDateTime; const Union:TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+QuotedStr(FloatToSQLStr(FieldValue)));
end;
procedure SQL.WhereFieldEqual(const FieldName: string; const FieldValue: string; const Union:TWhereUnion);
begin
WhereField(FieldName, '=', FieldValue, Union);
end;
procedure SQL.WhereFieldEqual(const FieldName: string; const FieldValue: Integer; const Union:TWhereUnion);
begin
WhereField(FieldName, '=', FieldValue, Union);
end;
procedure SQL.WhereFieldEqual(const FieldName: string; const FieldValue: Extended; const Union:TWhereUnion);
begin
WhereField(FieldName, '=', FieldValue, Union);
end;
procedure SQL.WhereFieldEqual(const FieldName: string; const FieldValue: Boolean; const Union:TWhereUnion);
begin
WhereField(FieldName, '=', FieldValue, Union);
end;
procedure SQL.WhereFieldIN(const FieldName: string; const FieldValues: array of Extended; const Union: TWhereUnion);
var FieldValue:string;
i:Integer;
begin
FieldValue:='';
for i:= Low(FieldValues) to High(FieldValues) do
begin
FieldValue:=FieldValue+QuotedStr(FloatToSQLStr(FieldValues[i]));
if i <> High(FieldValues) then FieldValue:=FieldValue+', ';
end;
WhereFieldWOQ(FieldName, ' IN ', '('+FieldValue+')', Union);
end;
procedure SQL.WhereFieldIN(const FieldName: string; const FieldValues: array of string; const Union: TWhereUnion);
var FieldValue:string;
i:Integer;
begin
FieldValue:='';
for i:= Low(FieldValues) to High(FieldValues) do
begin
FieldValue:=FieldValue+QuotedStr(FieldValues[i]);
if i <> High(FieldValues) then FieldValue:=FieldValue+', ';
end;
WhereFieldWOQ(FieldName, ' IN ', '('+FieldValue+')', Union);
end;
procedure SQL.WhereFieldIN(const FieldName: string; const FieldValues: array of Integer; const Union: TWhereUnion);
var FieldValue:string;
i:Integer;
begin
FieldValue:='';
for i:= Low(FieldValues) to High(FieldValues) do
begin
FieldValue:=FieldValue+QuotedStr(IntToStr(FieldValues[i]));
if i <> High(FieldValues) then FieldValue:=FieldValue+', ';
end;
WhereFieldWOQ(FieldName, ' IN ', '('+FieldValue+')', Union);
end;
procedure SQL.WhereFieldIN(const FieldName: string; const FieldValues: array of Boolean; const Union: TWhereUnion);
var FieldValue:string;
i:Integer;
begin
FieldValue:='';
for i:= Low(FieldValues) to High(FieldValues) do
begin
FieldValue:=FieldValue+QuotedStr(BoolToSQLStr(FieldValues[i]));
if i <> High(FieldValues) then FieldValue:=FieldValue+', ';
end;
WhereFieldWOQ(FieldName, ' IN ', '('+FieldValue+')', Union);
end;
procedure SQL.WhereFieldIsNotNull(const FieldName: string; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+' not '+FieldName+' is Null');
end;
function SQL.InsertUnion(const Union:TWhereUnion):string;
begin
case Union of
wuAnd: Result:=' AND ';
wuOr: Result:=' OR ';
wuNotAnd: Result:=' NOT AND ';
wuNotOr: Result:=' NOT OR ';
end;
if FUWheres.Count <= 0 then Result:=''
else
if FUWheres[FUWheres.Count-1][Length(FUWheres[FUWheres.Count-1])] = '(' then Result:='';
end;
procedure SQL.WhereFieldIsNull(const FieldName: string; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+' is Null');
end;
procedure SQL.WhereFieldIN(const FieldName: string; const FieldValues: array of TDateTime; const Union: TWhereUnion);
var FieldValue:string;
i:Integer;
begin
FieldValue:='';
for i:= Low(FieldValues) to High(FieldValues) do
begin
FieldValue:=FieldValue+QuotedStr(FloatToSQLStr(FieldValues[i]));
if i <> High(FieldValues) then FieldValue:=FieldValue+', ';
end;
WhereFieldWOQ(FieldName, ' IN ', '('+FieldValue+')', Union);
end;
procedure SQL.WhereFieldWOQ(const FieldName, Oper, FieldValue: string; const Union: TWhereUnion);
begin
FUWheres.Add(InsertUnion(Union)+FieldName+Oper+FieldValue);
end;
procedure SQL.WhereFieldEqual(const FieldName: string; const FieldValue: TDateTime; const Union:TWhereUnion);
begin
WhereField(FieldName, '=', FieldValue, Union);
end;
procedure SQL.WhereNotFieldEqual(const FieldName: string; const FieldValue: Extended; const Union:TWhereUnion);
begin
WhereField(FieldName, '<>', FieldValue, Union);
end;
procedure SQL.WhereNotFieldEqual(const FieldName: string; const FieldValue:string; const Union:TWhereUnion);
begin
WhereField(FieldName, '<>', FieldValue, Union);
end;
procedure SQL.WhereNotFieldEqual(const FieldName: string; const FieldValue: Integer; const Union:TWhereUnion);
begin
WhereField(FieldName, '<>', FieldValue, Union);
end;
procedure SQL.WhereNotFieldEqual(const FieldName: string; const FieldValue: Boolean; const Union:TWhereUnion);
begin
WhereField(FieldName, '<>', FieldValue, Union);
end;
procedure SQL.WhereParenthesesClose;
begin
FUWheres.Add(') ');
end;
procedure SQL.WhereParenthesesOpen;
begin
FUWheres.Add(InsertUnion(Union)+' (');
end;
procedure SQL.WhereStr(const Value: string);
begin
FWhereStr:=Value;
end;
procedure SQL.WhereNotFieldEqual(const FieldName: string; const FieldValue: TDateTime; const Union:TWhereUnion);
begin
WhereField(FieldName, '<>', FieldValue, Union);
end;
{ TUpdateBlob }
function TUpdateBlob.GetSQL: string;
begin
Result:='UPDATE '+FName+' SET '+FBlobField+' = ? '+Where;
end;
end.
|
unit uLayoutPhoenix;
interface
uses
Contnrs, SysUtils, ACBrTXTClass, ACBrUtil, funcoes;
type
TCamposInventario = class
private
FVL_UNIT: Currency;
FALIQ_ICMS: Currency;
FQUANTIDADE: Double;
FNCM: string;
FUNIDADE: string;
FCODIGO: string;
FDESCRICAO: string;
FVALOR_ICMS: Currency;
FCOD_GRUPO: string;
FDESCR_GRUPO: string;
procedure SetCODIGO(const Value: string);
procedure SetDESCRICAO(const Value: string);
procedure SetNCM(const Value: string);
procedure setUNIDADE(const Value: string);
procedure SetCOD_GRUPO(const Value: string);
procedure SetDESCR_GRUPO(const Value: string);
public
property CODIGO: string read fCODIGO write SetCODIGO;
property DESCRICAO: string read fDESCRICAO write SetDESCRICAO;
property NCM: string read FNCM write SetNCM;
property COD_GRUPO: string read FCOD_GRUPO write SetCOD_GRUPO;
property DESCR_GRUPO: string read FDESCR_GRUPO write SetDESCR_GRUPO;
property QUANTIDADE: Double read FQUANTIDADE write FQUANTIDADE;
property UNIDADE: string read FUNIDADE write setUNIDADE;
property VL_UNIT: Currency read FVL_UNIT write FVL_UNIT;
property ALIQ_ICMS: Currency read FALIQ_ICMS write FALIQ_ICMS;
property VALOR_ICMS: Currency read FVALOR_ICMS write FVALOR_ICMS;
end;
TInventarioList = class
private
List: TObjectList;
function GetCountItems: Integer;
function GetItem(Index: Integer): TCamposInventario;
procedure SetItem(Index: Integer; const Value: TCamposInventario);
protected
function Add(AObject: TCamposInventario): Integer; overload;
public
constructor Create(AOwnObjects: Boolean = True);
destructor Destroy; override;
property Items[Index: Integer]: TCamposInventario read GetItem write SetItem;
property Count: Integer read GetCountItems;
function Add: TCamposInventario; overload;
procedure Delete(Index: Integer);
procedure Clear;
end;
TInventarioPhoenix = class
private
ACBrTXT: TACBrTXTClass;
FInicializado: Boolean;
FArquivo: AnsiString;
FPath: AnsiString;
FITENS_INVENT: TInventarioList;
FLinhasBuffer: Integer;
procedure SetArquivo(const Value: AnsiString);
procedure SetPath(const Value: AnsiString);
procedure SetLinhasBuffer(const Value: Integer);
procedure Error(const MsnError: string);
public
constructor Create;
destructor Destroy; override;
procedure IniciaGeracao;
property LinhasBuffer: Integer read FLinhasBuffer write SetLinhasBuffer;
property Path: AnsiString read FPath write SetPath;
property Arquivo: AnsiString read FArquivo write SetArquivo;
property ITENS_INVENT: TInventarioList read FITENS_INVENT write FITENS_INVENT;
end;
implementation
{ TInventarioList }
function TInventarioList.Add(AObject: TCamposInventario): Integer;
begin
Result := List.Add(AObject);
end;
function TInventarioList.Add: TCamposInventario;
begin
Result := TCamposInventario.Create;
Add(Result);
end;
procedure TInventarioList.Clear;
begin
List.Clear;
end;
constructor TInventarioList.Create(AOwnObjects: Boolean);
begin
List := TObjectList.Create(AOwnObjects);
end;
procedure TInventarioList.Delete(Index: Integer);
begin
List.Delete(Index);
end;
destructor TInventarioList.Destroy;
begin
List.Free;
inherited Destroy;
end;
function TInventarioList.GetCountItems: Integer;
begin
Result := List.Count;
end;
function TInventarioList.GetItem(Index: Integer): TCamposInventario;
begin
Result := TCamposInventario(List[Index]);
end;
procedure TInventarioList.SetItem(Index: Integer;
const Value: TCamposInventario);
begin
List[Index] := Value;
end;
{ TCamposInventario }
procedure TCamposInventario.SetCODIGO(const Value: string);
begin
if FCODIGO = Value then
Exit;
FCODIGO := Value;
if Length(Trim(FCODIGO)) > 18 then
FCODIGO := Copy(fCODIGO, 1, 18);
end;
procedure TCamposInventario.SetCOD_GRUPO(const Value: string);
begin
if FCOD_GRUPO = Value then
Exit;
FCOD_GRUPO := Value;
if Length(Trim(FCOD_GRUPO)) > 4 then
FCOD_GRUPO := Copy(FCOD_GRUPO, 1, 4);
end;
procedure TCamposInventario.SetDESCRICAO(const Value: string);
begin
if FDESCRICAO = Value then
Exit;
FDESCRICAO := Value;
if Length(Trim(FDESCRICAO)) > 40 then
FDESCRICAO := Copy(FDESCRICAO, 1, 40);
end;
procedure TCamposInventario.SetDESCR_GRUPO(const Value: string);
begin
if FDESCR_GRUPO = Value then
Exit;
FDESCR_GRUPO := Value;
if Length(Trim(FDESCR_GRUPO)) > 10 then
FDESCR_GRUPO := Copy(FDESCR_GRUPO, 1, 10);
end;
procedure TCamposInventario.SetNCM(const Value: string);
begin
if FNCM = Value then
Exit;
FNCM := Value;
if Length(Trim(FNCM)) > 12 then
FNCM := Copy(FNCM, 1, 12);
end;
procedure TCamposInventario.setUNIDADE(const Value: string);
begin
if FUNIDADE = Value then
Exit;
FUNIDADE := Value;
if Length(Trim(FUNIDADE)) > 3 then
FUNIDADE := Copy(FUNIDADE, 1, 3);
end;
{ TInventarioPhoenix }
constructor TInventarioPhoenix.Create;
begin
ACBrTXT := TACBrTXTClass.create;
FITENS_INVENT := TInventarioList.Create;
FLinhasBuffer := 1000;
FPath := ExtractFilePath(ParamStr(0));
ACBrTXT.Delimitador := '|';
ACBrTXT.CurMascara := '#0.00';
ACBrTXT.TrimString := False;
FInicializado := False;
ACBrTXT.OnError := Error;
end;
destructor TInventarioPhoenix.Destroy;
begin
ACBrTXT.Free;
FITENS_INVENT.Free;
inherited Destroy;
end;
procedure TInventarioPhoenix.Error(const MsnError: string);
begin
raise Exception.Create(ACBrStr(MsnError));
end;
procedure TInventarioPhoenix.IniciaGeracao;
var
Linha: string;
intCont: Integer;
begin
if FInicializado then
Exit;
if (Trim(FArquivo) = EmptyStr) or (Trim(FPath) = EmptyStr) then
raise Exception.Create(ACBrStr('Caminho ou nome do arquivo não informado!'));
ACBrTXT.NomeArquivo := FPath + FArquivo;
ACBrTXT.Reset; // Apaga o Arquivo e limpa memória
FInicializado := True;
if FInicializado then
with ACBrTXT do
begin
for intCont := 0 to Pred(FITENS_INVENT.Count) do
begin
Linha := RFill(FITENS_INVENT.Items[intCont].CODIGO, 18);
Linha := Linha + RFill(FITENS_INVENT.Items[intCont].DESCRICAO, 40);
Linha := Linha + RFill(FITENS_INVENT.Items[intCont].NCM, 12);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].COD_GRUPO, 4);
Linha := Linha + RFill(FITENS_INVENT.Items[intCont].DESCR_GRUPO, 10);
Linha := Linha + LFill(FloatToStr(TBRound(FITENS_INVENT.Items[intCont].QUANTIDADE, 3) * 1000), 10);
Linha := Linha + RFill(FITENS_INVENT.Items[intCont].UNIDADE, 3);
Linha := Linha + LFill(FloatToStr(TBRound(FITENS_INVENT.Items[intCont].VL_UNIT, 2) * 100), 8);
Linha := Linha + LFill(FloatToStr(TBRound(FITENS_INVENT.Items[intCont].ALIQ_ICMS, 2) * 100), 4);
Linha := Linha + LFill(FloatToStr(TBRound(FITENS_INVENT.Items[intCont].VALOR_ICMS, 2) * 100), 8);
Linha := StringReplace(Linha, ACBrTXT.Delimitador, '', [rfReplaceAll]);
Add(Linha, False);
end;
SaveToFile;
end;
end;
procedure TInventarioPhoenix.SetArquivo(const Value: AnsiString);
var
lPath: AnsiString;
begin
if FArquivo = Value then
Exit;
FArquivo := ExtractFileName(Value);
lPath := ExtractFilePath(Value);
if lPath <> EmptyStr then
FPath := lPath;
end;
procedure TInventarioPhoenix.SetLinhasBuffer(const Value: Integer);
begin
if FLinhasBuffer = Value then
Exit;
FLinhasBuffer := Value;
ACBrTXT.LinhasBuffer := FLinhasBuffer;
end;
procedure TInventarioPhoenix.SetPath(const Value: AnsiString);
begin
FPath := PathWithDelim(Value);
end;
end.
|
unit Control.Acareacao;
interface
uses Model.Acareacoes, System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum;
type
TAcareacaoControl = class
private
FAcareacoes: TAcareacoes;
public
constructor Create;
destructor Destroy; override;
function Gravar: Boolean;
function Finalizar: Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function GetId(): Integer;
function ValidaCampos(): Boolean;
function ValidaFinalizar(): Boolean;
function ValidaExclusao(): Boolean;
property Acareacoes: TAcareacoes read FAcareacoes write FAcareacoes;
end;
implementation
{ TAcareacaoControl }
constructor TAcareacaoControl.Create;
begin
FAcareacoes := TAcareacoes.Create;
end;
destructor TAcareacaoControl.Destroy;
begin
FAcareacoes.Free;
inherited;
end;
function TAcareacaoControl.Finalizar: Boolean;
begin
Result := False;
if not ValidaFinalizar then Exit;
Result := FAcareacoes.Gravar;
end;
function TAcareacaoControl.GetId: Integer;
begin
Result := FAcareacoes.GetID;
end;
function TAcareacaoControl.Gravar: Boolean;
begin
Result := False;
if FAcareacoes.Acao = Common.ENum.tacExcluir then
begin
if not ValidaExclusao() then Exit;
end
else
begin
if not ValidaCampos then Exit;
end;
Result := FAcareacoes.Gravar;
end;
function TAcareacaoControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FAcareacoes.Localizar(aParam);
end;
function TAcareacaoControl.ValidaCampos: Boolean;
begin
Result := False;
if FAcareacoes.Id.IsEmpty then
begin
Application.MessageBox('Informe o #ID da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Nossonumero.IsEmpty then
begin
Application.MessageBox('Informe o Nosso Número.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Acao = Common.ENum.tacIncluir then
begin
if FAcareacoes.AcareacaoExiste() then
begin
Application.MessageBox('Existe uma acareação cadastrada com este #ID e Nosso Número!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end;
if (DateTimeToStr(FAcareacoes.Data).IsEmpty) or (FAcareacoes.Data = 0) then
begin
Application.MessageBox('Informe a data da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if (DateTimeToStr(FAcareacoes.DataRetorno).IsEmpty) or (FAcareacoes.DataRetorno = 0) then
begin
Application.MessageBox('Informe a data do retorno da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if (DateTimeToStr(FAcareacoes.DataEntrega).IsEmpty) or (FAcareacoes.DataEntrega = 0) then
begin
Application.MessageBox('Informe a data da entrega.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Entregador = 0 then
begin
Application.MessageBox('Informe o Entregador.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Base = 0 then
begin
Application.MessageBox('Informe a Base.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Motivo.IsEmpty then
begin
Application.MessageBox('Informe o motivo da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Tratativa.IsEmpty then
begin
Application.MessageBox('Informe a tratativa da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Envio.IsEmpty then
begin
Application.MessageBox('Informe se a correspondência foi enviada.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
function TAcareacaoControl.ValidaExclusao: Boolean;
begin
Result := False;
if FAcareacoes.Finalizar then
begin
Application.MessageBox('Acareação já finalizada. Não pode ser excluída.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
function TAcareacaoControl.ValidaFinalizar: Boolean;
begin
Result := False;
if FAcareacoes.Apuracao.IsEmpty then
begin
Application.MessageBox('Informe a apuração da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Resultado.IsEmpty then
begin
Application.MessageBox('Informe o resultado da acareação.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Entregador = 0 then
begin
Application.MessageBox('Informe o Entregador.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Base = 0 then
begin
Application.MessageBox('Informe a Base.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Extravio = 0 then
begin
if (Copy(FAcareacoes.Resultado, 0, 2) = '02') or (Copy(FAcareacoes.Resultado, 0, 2) = '03') then
begin
Application.MessageBox('Informe o valor do extravio.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end
else
begin
if Copy(FAcareacoes.Resultado, 0, 2) = '04' then
begin
FAcareacoes.Extravio := 0;
end;
end;
if FAcareacoes.Multa = 0 then
begin
if (Copy(FAcareacoes.Resultado, 0, 2) = '03') or (Copy(FAcareacoes.Resultado, 0, 2) = '04') then
begin
Application.MessageBox('Informe o valor da multa.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end
else
begin
if Copy(FAcareacoes.Resultado, 0, 2) = '02' then
begin
Application.MessageBox('Valor de multa não deve ser informado para deste resultado.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end;
if FAcareacoes.Envio.IsEmpty then
begin
Application.MessageBox('Informe a situação do envio da correspondência.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FAcareacoes.Retorno.IsEmpty then
begin
Application.MessageBox('Informe o tipo de retorno da correspondência.', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
end.
|
unit EditValidator;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, System.Math;
type
ECaracterInvalido = class(Exception);
EInvalidCPF = class(Exception);
EInvalidCNPJ = class(Exception);
EInvalidCEP = class(Exception);
EInvalidTitulo = class(Exception);
EInvalidTelefone = class(Exception);
EInvalidRG = class(Exception);
TEditType = (etCNPJ, etCPF, etCEP, etTelefone, etTitulo, etRG);
TEditValidator = class(TEdit)
private
FEditType: TEditType;
FInputMask: Boolean;
FValidate: Boolean;
procedure SetEditType(const Value: TEditType);
procedure SetInputMask(const Value: Boolean);
procedure SetValidate(const Value: Boolean);
{ Private declarations }
protected
{ Protected declarations }
function DoValidate : Boolean; virtual;
function ValidateCNPJ: Boolean;virtual;
function ValidateCPF: Boolean;virtual;
procedure DoExit;override;
public
{ Public declarations }
procedure Mascarar; virtual;
procedure KeyPress(var Key : Char);override;
published
{ Published declarations }
property EditType : TEditType read FEditType write SetEditType default etCNPJ;
property InputMask : Boolean read FInputMask write SetInputMask;
property Validate: Boolean read FValidate write SetValidate;
end;
procedure Register;
implementation
uses
System.MaskUtils;
const
mskCNPJ = '##.###.#00/0000.00;0;_';
mskCPF = '###.##0.000-00;0;_';
mskCEP = '00000-000;0;_';
mskTelefone = '(##) 000-0000;0;_';
mskTitulo = '###.##0.00-00;0;_';
mskRG = '##.##0.000-0;0;_';
procedure Register;
begin
RegisterComponents('componenteOW', [TEditValidator]);
end;
{ TEditValidator }
procedure TEditValidator.KeyPress(var Key: Char);
begin
if not(CharInSet(Key, [#48..#57, #9, #13, #27])) then
begin
raise ECaracterInvalido.Create('Caractere inválido');
end;
inherited;
end;
procedure TEditValidator.Mascarar;
begin
case FEditType of
etCNPJ: Text := FormatMaskText(mskCNPJ, Text);
etCPF: Text := FormatMaskText(mskCPF, Text);
etCEP: Text := FormatMaskText(mskCEP, Text);
etTelefone: Text := FormatMaskText(mskTelefone, Text);
etTitulo: Text := FormatMaskText(mskTitulo, Text);
etRG: Text := FormatMaskText(mskRG, Text);
end;
end;
procedure TEditValidator.SetEditType(const Value: TEditType);
begin
FEditType := Value;
end;
procedure TEditValidator.SetInputMask(const Value: Boolean);
begin
FInputMask := Value;
end;
procedure TEditValidator.SetValidate(const Value: Boolean);
begin
FValidate := Value;
end;
procedure TEditValidator.DoExit;
begin
if Validate then
if not(DoValidate) then
begin
case EditType of
etCNPJ: raise EInvalidCNPJ.Create('CNPJ inválido!');
etCPF: raise EInvalidCPF.Create('CPF inválido!');
etCEP: raise EInvalidCEP.Create('CEP inválido!');
etTelefone: raise EInvalidTelefone.Create('Telefone inválido!');
etTitulo: raise EInvalidTitulo.Create('Titulo de eleitor inválido!');
etRG: raise EInvalidRG.Create('RG inválido!');
end;
end;
if InputMask then
Mascarar;
inherited;
end;
function TEditValidator.DoValidate: Boolean;
begin
case FEditType of
etCNPJ: Result := ValidateCNPJ;
etCPF: Result := ValidateCPF;
// etCEP: ;
// etTelefone: ;
// etTituloEleitor: ;
// etRG: ;
else
Result := False;
end;
end;
function TEditValidator.ValidateCNPJ: Boolean;
var
v: array[1..2] of Word;
cnpj: array[1..14] of Byte;
I: Byte;
begin
try
for I := 1 to 14 do
cnpj[i] := StrToInt(Text[i]);
//Nota: Calcula o primeiro dígito de verificação.
v[1] := 5*cnpj[1] + 4*cnpj[2] + 3*cnpj[3] + 2*cnpj[4];
v[1] := v[1] + 9*cnpj[5] + 8*cnpj[6] + 7*cnpj[7] + 6*cnpj[8];
v[1] := v[1] + 5*cnpj[9] + 4*cnpj[10] + 3*cnpj[11] + 2*cnpj[12];
v[1] := 11 - v[1] mod 11;
v[1] := IfThen(v[1] >= 10, 0, v[1]);
//Nota: Calcula o segundo dígito de verificação.
v[2] := 6*cnpj[1] + 5*cnpj[2] + 4*cnpj[3] + 3*cnpj[4];
v[2] := v[2] + 2*cnpj[5] + 9*cnpj[6] + 8*cnpj[7] + 7*cnpj[8];
v[2] := v[2] + 6*cnpj[9] + 5*cnpj[10] + 4*cnpj[11] + 3*cnpj[12];
v[2] := v[2] + 2*v[1];
v[2] := 11 - v[2] mod 11;
v[2] := IfThen(v[2] >= 10, 0, v[2]);
//Nota: Verdadeiro se os dígitos de verificação são os esperados.
Result := ((v[1] = cnpj[13]) and (v[2] = cnpj[14]));
except on E: Exception do
Result := False;
end;
end;
function TEditValidator.ValidateCPF: Boolean;
var
v: array[0..1] of Word;
cpf: array[0..10] of Byte;
I: Byte;
begin
try
for I := 1 to 11 do
cpf[i-1] := StrToInt(Text[i]);
//Nota: Calcula o primeiro dígito de verificação.
v[0] := 10*cpf[0] + 9*cpf[1] + 8*cpf[2];
v[0] := v[0] + 7*cpf[3] + 6*cpf[4] + 5*cpf[5];
v[0] := v[0] + 4*cpf[6] + 3*cpf[7] + 2*cpf[8];
v[0] := 11 - v[0] mod 11;
v[1] := IfThen(v[1] >= 10, 0, v[1]);
//Nota: Calcula o segundo dígito de verificação.
v[1] := 11*cpf[0] + 10*cpf[1] + 9*cpf[2];
v[1] := v[1] + 8*cpf[3] + 7*cpf[4] + 6*cpf[5];
v[1] := v[1] + 5*cpf[6] + 4*cpf[7] + 3*cpf[8];
v[1] := v[1] + 2*v[0];
v[1] := 11 - v[1] mod 11;
v[1] := IfThen(v[1] >= 10, 0, v[1]);
//Nota: Verdadeiro se os dígitos de verificação são os esperados.
Result := ((v[0] = cpf[9]) and (v[1] = cpf[10]));
except on E: Exception do
Result := False;
end;
end;
end.
|
{ Subroutine SST_W_C_EXP (EXP, ADDR_CNT, DT_OUT_P, ENCLOSE)
*
* Write the expression from the expression descriptor EXP.
* ADDR_CNT is the number of times to take the address of the expression.
* It may be negative to indicate the number of times the expression
* should be assumed to be a pointer and dereferenced.
* DT_OUT_P indicates the desired data type of the resulting expression.
* It may be set to NIL to indicate the expression's inherent data type
* need not be altered.
* ENCLOSE indicates whether the final expression should be enclosed in
* parentheses. Values of ENCLOSE can be:
*
* ENCLOSE_YES_K - Enclose in parentheses, if neccessary, to make the
* entire expression be one term.
*
* ENCLOSE_NO_K - Don't enclose expression in parentheses, even if is is
* written as more than one term with operators in between.
}
module sst_W_C_EXP;
define sst_w_c_exp;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_exp ( {write expression}
in exp: sst_exp_t; {expression descriptor}
in addr_cnt: sys_int_machine_t; {number of times to take address of}
in dt_out_p: sst_dtype_p_t; {desired output data type, NIL = as is}
in enclose: enclose_k_t); {enclose in () yes/no}
const
max_str_comm = 40; {max length of string value in comment}
var
term_p: sst_exp_term_p_t; {points to current term in expression}
n_terms: sys_int_machine_t; {number of terms in top level of expression}
dt_p, dt2_p: sst_dtype_p_t; {scratch data type pointers}
sym_p: sst_symbol_p_t; {pointer to implicit variable for exp value}
v: sst_var_t; {"variable" descriptor for implicit var}
enc: enclose_k_t; {local copy of ENCLOSE flag}
i: sys_int_machine_t; {scratch integer and loop counter}
bool_kluge: boolean; {TRUE if due hard TRUE/FALSE assign for bool}
comm: string_var80_t; {end of line comment string}
token: string_var80_t;
label
dtype_loop, dtype_match, implicit_var, fix_string;
{
********************************
*
* Local subroutine DO_ADDR_CNT (CNT)
*
* Write the appropriate number of "address of" (&) or pointer dereference (*)
* operators preceeding the expression.
}
procedure do_addr_cnt (
in cnt: sys_int_machine_t);
var
adrcnt: sys_int_machine_t; {local copy of CNT}
begin
if cnt = 0 then return; {nothing to do ?}
adrcnt := cnt; {make local copy of CNT argument}
while adrcnt > 0 do begin {"address of"s requested ?}
sst_w.appendn^ ('&', 1);
adrcnt := adrcnt - 1;
end;
while adrcnt < 0 do begin {pointer dereferences requested ?}
sst_w.appendn^ ('*', 1);
adrcnt := adrcnt + 1;
end;
enc := enclose_yes_k; {expression now needs to be enclosed in ()}
end;
{
********************************
*
* Start of main routine.
}
begin
comm.max := sizeof(comm.str); {init local var strings}
token.max := sizeof(token.str);
if exp.term1.ttype = sst_term_field_k then begin {exp is record constant ?}
sst_w_c_exp_rec (exp); {handle in separate routine}
return;
end;
if exp.term1.ttype = sst_term_arele_k then begin {exp is array constant ?}
sst_w_c_exp_array (exp); {handle in separate routine}
return;
end;
enc := enclose; {make local copy of ENCLOSE flag}
n_terms := 1; {init number of terms counted}
term_p := addr(exp.term1); {init current term to first term in expression}
while term_p^.next_p <> nil do begin {loop thru all the terms at this level}
n_terms := n_terms + 1; {count one more term in expression}
term_p := term_p^.next_p; {advance to next term in expression}
end;
{
* N_TERMS is the number of terms in the expression, and TERM_P is pointing
* to the last term in the expression.
}
if dt_out_p <> nil then begin {expression must be of DT_OUT_P data type ?}
dt_p := exp.dtype_p; {resolve base expresion data type}
dt2_p := dt_out_p; {resolve base requested data type}
dtype_loop: {back here after resolve pointer layer}
while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p;
while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p;
if dt_p = dt2_p {exactly the same data type descriptors ?}
then goto dtype_match;
if dt_p^.dtype <> dt2_p^.dtype {base data types don't match ?}
then goto implicit_var;
if dt_p^.dtype = sst_dtype_pnt_k then begin {both data types are pointers ?}
if dt_p^.pnt_dtype_p = dt2_p^.pnt_dtype_p {pointers to same data types ?}
then goto dtype_match;
if (dt_p^.pnt_dtype_p = nil) or (dt2_p^.pnt_dtype_p = nil) {one is NIL ptr ?}
then goto implicit_var;
dt_p := dt_p^.pnt_dtype_p; {go one level deeper to pointed-to dtypes}
dt2_p := dt2_p^.pnt_dtype_p;
goto dtype_loop; {try again with pointed-to data types}
end;
goto implicit_var; {data types don't match}
end;
dtype_match: {jump here if exp and required dtypes match}
if {can't do adr of exp, but asked to ?}
(addr_cnt > 0) and {caller wants address of expression ?}
(not sst_w_c_exp_adrable(exp)) {but address of this exp not allowed ?}
then goto implicit_var; {assign exp to var, then take adr of var}
{
* The expression may be written directly at the current position. It
* is not neccessary to create an implicit variable for the expression value.
}
dt_p := exp.dtype_p; {resolve base expresion data type}
while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p;
bool_kluge := {need to force TRUE/FALSE value ?}
(sst_config.manuf = sst_manuf_apollo_k) and {going to run on Apollos ?}
(dt_p^.dtype = sst_dtype_bool_k) and {expression has BOOLEAN data type ?}
(addr_cnt = 0) and {no address ofs or pointer dereference}
(enclose = enclose_no_k); {not a nested expression ?}
if n_terms <= 1
then begin {this expression contains only one term}
if
bool_kluge and {kluge alert ?}
(exp.term1.op1 <> sst_op1_none_k)
then begin {special Apollo boolean kluge in effect}
sst_w_c_term (exp.term1, addr_cnt, enclose_yes_k);
if bool_kluge then begin
sst_w.delimit^;
sst_w.appendn^ ('?', 1);
sst_w.delimit^;
sst_w_c_intrinsic (intr_true_k);
sst_w.delimit^;
sst_w.appendn^ (':', 1);
sst_w.delimit^;
sst_w_c_intrinsic (intr_false_k);
end;
end
else begin {process normally}
sst_w_c_term (exp.term1, addr_cnt, enclose);
end
;
end
else begin {this is a compound expression}
do_addr_cnt (addr_cnt); {write preceeding "&" or "*" operators}
sst_w_c_armode_push (array_pnt_first_k); {force mode in compound expression}
if bool_kluge then begin
enc := enclose_yes_k; {enclose in () if compound expression}
end;
sst_w_c_exp2 ( {write top level operation in expression}
exp.term1, {first term in expression before operator}
n_terms - 1, {number of terms in exp before operator}
term_p^, {first term in expression after operator}
1, {number of terms in exp after operator}
term_p^.op2, {operator between the expressions}
enc); {enclose in () yes/no flag}
if bool_kluge then begin
sst_w.delimit^;
sst_w.appendn^ ('?', 1);
sst_w.delimit^;
sst_w_c_intrinsic (intr_true_k);
sst_w.delimit^;
sst_w.appendn^ (':', 1);
sst_w.delimit^;
sst_w_c_intrinsic (intr_false_k);
end;
sst_w_c_armode_pop; {restore array symbol interpretation mode}
end
;
return;
{
* The expression can not be written directly at the current writing position.
* An implicit variable will be created for the expression value.
}
implicit_var:
if dt_out_p = nil {determine implicit variable's data type}
then dt_p := exp.dtype_p
else dt_p := dt_out_p;
sst_w_c_armode_push (array_pnt_first_k); {override mode inside implicit expression}
sst_w_c_exp_explicit (exp, dt_p^, sym_p); {create variable with expression value}
sst_w_c_armode_pop; {restore array symbol interpretation mode}
v.mod1.next_p := nil; {fill in desc for implicit var reference}
v.mod1.modtyp := sst_var_modtyp_top_k;
v.mod1.top_str_h.first_char.crange_p := nil;
v.mod1.top_str_h.first_char.ofs := 0;
v.mod1.top_str_h.last_char.crange_p := nil;
v.mod1.top_str_h.last_char.ofs := 0;
v.mod1.top_sym_p := sym_p;
v.dtype_p := sym_p^.var_dtype_p;
v.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
v.vtype := sst_vtype_var_k;
{
* Write value of expression as an end of line comment if expression has
* constant value and is of a suitable type.
}
if exp.val_fnd then begin {expression has a constant value ?}
comm.len := 0; {init to no comment generated}
case exp.val.dtype of {what is data type of value ?}
sst_dtype_int_k: begin
string_f_int (comm, exp.val.int_val);
end;
sst_dtype_enum_k: begin
string_copy (exp.val.enum_p^.name_in_p^, comm);
end;
sst_dtype_float_k: begin
string_f_fp_free ( {make floating point value string}
comm, {output string}
exp.val.float_val, {input floating point value}
6); {minimum significant digits required}
end;
sst_dtype_bool_k: begin
if exp.val.bool_val
then string_appendn (comm, 'TRUE', 4)
else string_appendn (comm, 'FALSE', 5);
end;
sst_dtype_char_k: begin
string_append1 (comm, '"');
string_append1 (comm, exp.val.char_val);
string_append1 (comm, '"');
goto fix_string; {fix possible control characters in string}
end;
sst_dtype_array_k: begin
if exp.val.ar_str_p <> nil then begin {array is string, value exists ?}
string_append1 (comm, '"');
string_appendn ( {append string up to max allowed len}
comm, {string to append to}
exp.val.ar_str_p^.str, {the string characters}
min(exp.val.ar_str_p^.len, max_str_comm)); {max allowed str in comment}
string_append1 (comm, '"');
if exp.val.ar_str_p^.len > max_str_comm then begin {got truncated ?}
string_appendn (comm, '...', 3);
end;
fix_string: {common code with CHAR data type}
for i := 2 to comm.len-1 do begin {scan range of possible control chars}
if (comm.str[i] < ' ') or (comm.str[i] > '~') then begin {bad char ?}
comm.str[i] := ' ';
end;
if (comm.str[i] = '*') and (comm.str[i+1] = '/') then begin {"*/" ?}
comm.str[i] := '-'; {change "*/" to "-/"}
end;
end; {back and check next char in COMM}
end;
end; {done with ARRAY data type case}
end; {end of expression value data type cases}
sst_w.comment_set^ (comm); {set this end of line comment}
end;
sst_w_c_var (v, addr_cnt); {write reference to this variable}
end;
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpSecT283K1Curve;
{$I ..\..\..\..\Include\CryptoLib.inc}
interface
uses
ClpHex,
ClpBits,
ClpNat320,
ClpECCurve,
ClpIECInterface,
ClpSecT283FieldElement,
ClpISecT283FieldElement,
ClpSecT283K1Point,
ClpISecT283K1Curve,
ClpISecT283K1Point,
ClpIECFieldElement,
ClpWTauNafMultiplier,
ClpBigInteger,
ClpCryptoLibTypes;
type
TSecT283K1Curve = class sealed(TAbstractF2mCurve, ISecT283K1Curve)
strict private
type
TSecT283K1LookupTable = class sealed(TInterfacedObject,
ISecT283K1LookupTable, IECLookupTable)
strict private
var
Fm_outer: ISecT283K1Curve;
Fm_table: TCryptoLibUInt64Array;
Fm_size: Int32;
function GetSize: Int32; virtual;
public
constructor Create(const outer: ISecT283K1Curve;
const table: TCryptoLibUInt64Array; size: Int32);
function Lookup(index: Int32): IECPoint; virtual;
property size: Int32 read GetSize;
end;
const
SECT283K1_DEFAULT_COORDS = Int32(TECCurve.COORD_LAMBDA_PROJECTIVE);
SECT283K1_FE_LONGS = Int32(5);
function GetM: Int32; inline;
function GetK1: Int32; inline;
function GetK2: Int32; inline;
function GetK3: Int32; inline;
function GetIsTrinomial: Boolean; inline;
strict protected
var
Fm_infinity: ISecT283K1Point;
function GetFieldSize: Int32; override;
function GetInfinity: IECPoint; override;
function GetIsKoblitz: Boolean; override;
function CloneCurve(): IECCurve; override;
function CreateDefaultMultiplier(): IECMultiplier; override;
function CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint; overload; override;
function CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean): IECPoint; overload; override;
public
constructor Create();
function FromBigInteger(const x: TBigInteger): IECFieldElement; override;
function SupportsCoordinateSystem(coord: Int32): Boolean; override;
function CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32)
: IECLookupTable; override;
property Infinity: IECPoint read GetInfinity;
property FieldSize: Int32 read GetFieldSize;
property IsKoblitz: Boolean read GetIsKoblitz;
property M: Int32 read GetM;
property K1: Int32 read GetK1;
property K2: Int32 read GetK2;
property K3: Int32 read GetK3;
property IsTrinomial: Boolean read GetIsTrinomial;
end;
implementation
{ TSecT283K1Curve }
constructor TSecT283K1Curve.Create;
begin
Inherited Create(283, 5, 7, 12);
Fm_infinity := TSecT283K1Point.Create(Self as IECCurve, Nil, Nil);
Fm_a := FromBigInteger(TBigInteger.Zero);
Fm_b := FromBigInteger(TBigInteger.One);
Fm_order := TBigInteger.Create(1,
THex.Decode
('01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61')
);
Fm_cofactor := TBigInteger.ValueOf(4);
Fm_coord := SECT283K1_DEFAULT_COORDS;
end;
function TSecT283K1Curve.CloneCurve: IECCurve;
begin
result := TSecT283K1Curve.Create() as ISecT283K1Curve;
end;
function TSecT283K1Curve.CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32): IECLookupTable;
var
table: TCryptoLibUInt64Array;
pos, i: Int32;
p: IECPoint;
begin
System.SetLength(table, len * SECT283K1_FE_LONGS * 2);
pos := 0;
for i := 0 to System.Pred(len) do
begin
p := points[off + i];
TNat320.Copy64((p.RawXCoord as ISecT283FieldElement).x, 0, table, pos);
pos := pos + SECT283K1_FE_LONGS;
TNat320.Copy64((p.RawYCoord as ISecT283FieldElement).x, 0, table, pos);
pos := pos + SECT283K1_FE_LONGS;
end;
result := TSecT283K1LookupTable.Create(Self as ISecT283K1Curve, table, len);
end;
function TSecT283K1Curve.CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint;
begin
result := TSecT283K1Point.Create(Self as IECCurve, x, y, withCompression);
end;
function TSecT283K1Curve.CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean)
: IECPoint;
begin
result := TSecT283K1Point.Create(Self as IECCurve, x, y, zs, withCompression);
end;
function TSecT283K1Curve.FromBigInteger(const x: TBigInteger): IECFieldElement;
begin
result := TSecT283FieldElement.Create(x);
end;
function TSecT283K1Curve.GetFieldSize: Int32;
begin
result := 283;
end;
function TSecT283K1Curve.GetInfinity: IECPoint;
begin
result := Fm_infinity;
end;
function TSecT283K1Curve.GetIsKoblitz: Boolean;
begin
result := True;
end;
function TSecT283K1Curve.GetIsTrinomial: Boolean;
begin
result := False;
end;
function TSecT283K1Curve.GetK1: Int32;
begin
result := 5;
end;
function TSecT283K1Curve.GetK2: Int32;
begin
result := 7;
end;
function TSecT283K1Curve.GetK3: Int32;
begin
result := 12;
end;
function TSecT283K1Curve.GetM: Int32;
begin
result := 283;
end;
function TSecT283K1Curve.SupportsCoordinateSystem(coord: Int32): Boolean;
begin
case coord of
COORD_LAMBDA_PROJECTIVE:
result := True
else
result := False;
end;
end;
function TSecT283K1Curve.CreateDefaultMultiplier(): IECMultiplier;
begin
result := TWTauNafMultiplier.Create() as IECMultiplier;
end;
{ TSecT283K1Curve.TSecT283K1LookupTable }
constructor TSecT283K1Curve.TSecT283K1LookupTable.Create
(const outer: ISecT283K1Curve; const table: TCryptoLibUInt64Array;
size: Int32);
begin
Inherited Create();
Fm_outer := outer;
Fm_table := table;
Fm_size := size;
end;
function TSecT283K1Curve.TSecT283K1LookupTable.GetSize: Int32;
begin
result := Fm_size;
end;
function TSecT283K1Curve.TSecT283K1LookupTable.Lookup(index: Int32): IECPoint;
var
x, y: TCryptoLibUInt64Array;
pos, i, J: Int32;
MASK: UInt64;
begin
x := TNat320.Create64();
y := TNat320.Create64();
pos := 0;
for i := 0 to System.Pred(Fm_size) do
begin
MASK := UInt64(Int64(TBits.Asr32((i xor index) - 1, 31)));
for J := 0 to System.Pred(SECT283K1_FE_LONGS) do
begin
x[J] := x[J] xor (Fm_table[pos + J] and MASK);
y[J] := y[J] xor (Fm_table[pos + SECT283K1_FE_LONGS + J] and MASK);
end;
pos := pos + (SECT283K1_FE_LONGS * 2);
end;
result := Fm_outer.CreateRawPoint(TSecT283FieldElement.Create(x)
as ISecT283FieldElement, TSecT283FieldElement.Create(y)
as ISecT283FieldElement, False);
end;
end.
|
unit PEStuff;
interface
uses Windows;
type
PImageDosHeader = ^TImageDosHeader;
_IMAGE_DOS_HEADER = packed record { DOS .EXE
header }
e_magic: Word; { Magic
number }
e_cblp: Word; { Bytes on last page of
file }
e_cp: Word; { Pages in
file }
e_crlc: Word; {
Relocations }
e_cparhdr: Word; { Size of header in
paragraphs }
e_minalloc: Word; { Minimum extra paragraphs
needed }
e_maxalloc: Word; { Maximum extra paragraphs
needed }
e_ss: Word; { Initial (relative) SS
value }
e_sp: Word; { Initial SP
value }
e_csum: Word; {
Checksum }
e_ip: Word; { Initial IP
value }
e_cs: Word; { Initial (relative) CS
value }
e_lfarlc: Word; { File address of relocation
table }
e_ovno: Word; { Overlay
number }
e_res: array [0..3] of Word; { Reserved
words }
e_oemid: Word; { OEM identifier (for
e_oeminfo) }
e_oeminfo: Word; { OEM information; e_oemid
specific}
e_res2: array [0..9] of Word; { Reserved
words }
_lfanew: LongInt; { File address of new exe
header }
end;
TImageDosHeader = _IMAGE_DOS_HEADER;
PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER;
IMAGE_FILE_HEADER = packed record
Machine : WORD;
NumberOfSections : WORD;
TimeDateStamp : DWORD;
PointerToSymbolTable : DWORD;
NumberOfSymbols : DWORD;
SizeOfOptionalHeader : WORD;
Characteristics : WORD;
end;
PIMAGE_DATA_DIRECTORY = ^IMAGE_DATA_DIRECTORY;
IMAGE_DATA_DIRECTORY = packed record
VirtualAddress : DWORD;
Size : DWORD;
end;
PIMAGE_SECTION_HEADER = ^IMAGE_SECTION_HEADER;
IMAGE_SECTION_HEADER = packed record
Name : packed array [0..IMAGE_SIZEOF_SHORT_NAME-1] of
Char;
VirtualSize : DWORD; // or VirtualSize (union);
VirtualAddress : DWORD;
SizeOfRawData : DWORD;
PointerToRawData : DWORD;
PointerToRelocations : DWORD;
PointerToLinenumbers : DWORD;
NumberOfRelocations : WORD;
NumberOfLinenumbers : WORD;
Characteristics : DWORD;
end;
PIMAGE_OPTIONAL_HEADER = ^IMAGE_OPTIONAL_HEADER;
IMAGE_OPTIONAL_HEADER = packed record
{ Standard fields. }
Magic : WORD;
MajorLinkerVersion : Byte;
MinorLinkerVersion : Byte;
SizeOfCode : DWORD;
SizeOfInitializedData : DWORD;
SizeOfUninitializedData : DWORD;
AddressOfEntryPoint : DWORD;
BaseOfCode : DWORD;
BaseOfData : DWORD;
{ NT additional fields. }
ImageBase : DWORD;
SectionAlignment : DWORD;
FileAlignment : DWORD;
MajorOperatingSystemVersion : WORD;
MinorOperatingSystemVersion : WORD;
MajorImageVersion : WORD;
MinorImageVersion : WORD;
MajorSubsystemVersion : WORD;
MinorSubsystemVersion : WORD;
Reserved1 : DWORD;
SizeOfImage : DWORD;
SizeOfHeaders : DWORD;
CheckSum : DWORD;
Subsystem : WORD;
DllCharacteristics : WORD;
SizeOfStackReserve : DWORD;
SizeOfStackCommit : DWORD;
SizeOfHeapReserve : DWORD;
SizeOfHeapCommit : DWORD;
LoaderFlags : DWORD;
NumberOfRvaAndSizes : DWORD;
DataDirectory : packed array
[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of IMAGE_DATA_DIRECTORY;
Sections: packed array [0..9999] of IMAGE_SECTION_HEADER;
end;
PIMAGE_NT_HEADERS = ^IMAGE_NT_HEADERS;
IMAGE_NT_HEADERS = packed record
Signature : DWORD;
FileHeader : IMAGE_FILE_HEADER;
OptionalHeader : IMAGE_OPTIONAL_HEADER;
end;
PImageNtHeaders = PIMAGE_NT_HEADERS;
TImageNtHeaders = IMAGE_NT_HEADERS;
{ PIMAGE_IMPORT_DESCRIPTOR = ^IMAGE_IMPORT_DESCRIPTOR;
IMAGE_IMPORT_DESCRIPTOR = packed record
Characteristics: DWORD; // or original first thunk // 0 for
terminating null import descriptor // RVA to original unbound IAT
TimeDateStamp: DWORD; // 0 if not bound,
// -1 if bound, and real date\time stamp
// in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
(new BIND)
// O.W. date/time stamp of DLL bound to (Old
BIND)
Name: DWORD;
FirstThunk: DWORD; // PIMAGE_THUNK_DATA // RVA to IAT (if bound
this IAT has actual addresses)
ForwarderChain: DWORD; // -1 if no forwarders
end;
TImageImportDescriptor = IMAGE_IMPORT_DESCRIPTOR;
PImageImportDescriptor = PIMAGE_IMPORT_DESCRIPTOR;}
PIMAGE_IMPORT_BY_NAME = ^IMAGE_IMPORT_BY_NAME;
IMAGE_IMPORT_BY_NAME = record
Hint: Word;
Name: Array[0..0] of Char;
end;
PIMAGE_THUNK_DATA = ^IMAGE_THUNK_DATA;
IMAGE_THUNK_DATA = record
Whatever: DWORD;
end;
PImage_Import_Entry = ^Image_Import_Entry;
Image_Import_Entry = record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
Name: DWORD;
LookupTable: DWORD;
end;
const
IMAGE_DOS_SIGNATURE = $5A4D; // MZ
IMAGE_OS2_SIGNATURE = $454E; // NE
IMAGE_OS2_SIGNATURE_LE = $454C; // LE
IMAGE_VXD_SIGNATURE = $454C; // LE
IMAGE_NT_SIGNATURE = $00004550; // PE00
implementation
end.
|
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. }
{$INCLUDE flcTCPTest.inc}
unit flcTCPTest_ClientServerTLS;
interface
{ }
{ Test }
{ }
{$IFDEF TCPCLIENTSERVER_TEST_TLS}
procedure Test;
{$ENDIF}
implementation
{$IFDEF TCPCLIENTSERVER_TEST_TLS}
uses
SysUtils,
flcTLSTransportTypes,
flcTLSTransportClient,
flcSocketLib,
flcTCPConnection,
flcTCPClient,
flcTCPServer,
flcTCPTest_ClientServer;
{$ENDIF}
{ }
{ Test }
{ }
{$IFDEF TCPCLIENTSERVER_TEST_TLS}
{$ASSERTIONS ON}
procedure TestClientServerTLS_ReadWrite(
const TestClientCount: Integer;
const TestLargeBlock: Boolean;
const TLSOptions: TTCPClientTLSOptions = DefaultTCPClientTLSOptions;
const TLSClientOptions: TTCPClientTLSClientOptions = DefaultTLSClientOptions;
const TLSVersionOptions: TTCPClientTLSVersionOptions = DefaultTLSClientVersionOptions;
const TLSKeyExchangeOptions: TTCPClientTLSKeyExchangeOptions = DefaultTLSClientKeyExchangeOptions;
const TLSCipherOptions: TTCPClientTLSCipherOptions = DefaultTLSClientCipherOptions;
const TLSHashOptions: TTCPClientTLSHashOptions = DefaultTLSClientHashOptions
);
procedure WaitClientConnected(const Client: TF5TCPClient);
var I : Integer;
begin
// wait for client to connect and finish TLS
I := 0;
repeat
Inc(I);
Sleep(1);
until (I >= 8000) or
(
(Client.State in [csReady, csClosed])
and
(
not Client.TLSEnabled or
(Client.TLSClient.IsFinishedState or Client.TLSClient.IsReadyState)
)
);
Assert(Client.State = csReady);
Assert(Client.Connection.State = cnsConnected);
Assert(not Client.TLSEnabled or Client.TLSClient.IsReadyState);
end;
var C : TF5TCPClientArray;
S : TF5TCPServer;
T : TTCPServerClientArray;
TSC : TTCPServerClient;
I, K : Integer;
// CtL : TTLSCertificateList;
DebugObj : TTCPClientServerTestObj;
begin
DebugObj := TTCPClientServerTestObj.Create;
S := TF5TCPServer.Create(nil);
SetLength(C, TestClientCount);
SetLength(T, TestClientCount);
for K := 0 to TestClientCount - 1 do
begin
C[K] := TF5TCPClient.Create(nil);
// init client
C[K].Tag := K + 1;
C[K].OnLog := DebugObj.ClientLog;
C[K].TLSOptions := TLSOptions;
C[K].TLSClientOptions := TLSClientOptions;
C[K].TLSVersionOptions := TLSVersionOptions;
C[K].TLSKeyExchangeOptions := TLSKeyExchangeOptions;
C[K].TLSCipherOptions := TLSCipherOptions;
C[K].TLSHashOptions := TLSHashOptions;
end;
try
// init server
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12545;
S.MaxClients := -1;
S.TLSEnabled := True;
(*
S.TLSServer.PrivateKeyRSAPEM := // from stunnel pem file
'MIICXAIBAAKBgQCxUFMuqJJbI9KnB8VtwSbcvwNOltWBtWyaSmp7yEnqwWel5TFf' +
'cOObCuLZ69sFi1ELi5C91qRaDMow7k5Gj05DZtLDFfICD0W1S+n2Kql2o8f2RSvZ' +
'qD2W9l8i59XbCz1oS4l9S09L+3RTZV9oer/Unby/QmicFLNM0WgrVNiKywIDAQAB' +
'AoGAKX4KeRipZvpzCPMgmBZi6bUpKPLS849o4pIXaO/tnCm1/3QqoZLhMB7UBvrS' +
'PfHj/Tejn0jjHM9xYRHi71AJmAgzI+gcN1XQpHiW6kATNDz1r3yftpjwvLhuOcp9' +
'tAOblojtImV8KrAlVH/21rTYQI+Q0m9qnWKKCoUsX9Yu8UECQQDlbHL38rqBvIMk' +
'zK2wWJAbRvVf4Fs47qUSef9pOo+p7jrrtaTqd99irNbVRe8EWKbSnAod/B04d+cQ' +
'ci8W+nVtAkEAxdqPOnCISW4MeS+qHSVtaGv2kwvfxqfsQw+zkwwHYqa+ueg4wHtG' +
'/9+UgxcXyCXrj0ciYCqURkYhQoPbWP82FwJAWWkjgTgqsYcLQRs3kaNiPg8wb7Yb' +
'NxviX0oGXTdCaAJ9GgGHjQ08lNMxQprnpLT8BtZjJv5rUOeBuKoXagggHQJAaUAF' +
'91GLvnwzWHg5p32UgPsF1V14siX8MgR1Q6EfgKQxS5Y0Mnih4VXfnAi51vgNIk/2' +
'AnBEJkoCQW8BTYueCwJBALvz2JkaUfCJc18E7jCP7qLY4+6qqsq+wr0t18+ogOM9' +
'JIY9r6e1qwNxQ/j1Mud6gn6cRrObpRtEad5z2FtcnwY=';
TLSCertificateListAppend(CtL,
MIMEBase64Decode( // from stunnel pem file
'MIICDzCCAXigAwIBAgIBADANBgkqhkiG9w0BAQQFADBCMQswCQYDVQQGEwJQTDEf' +
'MB0GA1UEChMWU3R1bm5lbCBEZXZlbG9wZXJzIEx0ZDESMBAGA1UEAxMJbG9jYWxo' +
'b3N0MB4XDTk5MDQwODE1MDkwOFoXDTAwMDQwNzE1MDkwOFowQjELMAkGA1UEBhMC' +
'UEwxHzAdBgNVBAoTFlN0dW5uZWwgRGV2ZWxvcGVycyBMdGQxEjAQBgNVBAMTCWxv' +
'Y2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsVBTLqiSWyPSpwfF' +
'bcEm3L8DTpbVgbVsmkpqe8hJ6sFnpeUxX3Djmwri2evbBYtRC4uQvdakWgzKMO5O' +
'Ro9OQ2bSwxXyAg9FtUvp9iqpdqPH9kUr2ag9lvZfIufV2ws9aEuJfUtPS/t0U2Vf' +
'aHq/1J28v0JonBSzTNFoK1TYissCAwEAAaMVMBMwEQYJYIZIAYb4QgEBBAQDAgZA' +
'MA0GCSqGSIb3DQEBBAUAA4GBAAhYFTngWc3tuMjVFhS4HbfFF/vlOgTu44/rv2F+' +
'ya1mEB93htfNxx3ofRxcjCdorqONZFwEba6xZ8/UujYfVmIGCBy4X8+aXd83TJ9A' +
'eSjTzV9UayOoGtmg8Dv2aj/5iabNeK1Qf35ouvlcTezVZt2ZeJRhqUHcGaE+apCN' +
'TC9Y'));
S.TLSServer.CertificateList := CtL;
*)
S.TLSServer.PEMText :=
'-----BEGIN CERTIFICATE-----' +
'MIIDQjCCAiqgAwIBAgIJAKDslQh3d8kdMA0GCSqGSIb3DQEBBQUAMB8xHTAbBgNV' +
'BAMTFHd3dy5ldGVybmFsbGluZXMuY29tMB4XDTExMTAxODEwMzYwOVoXDTIxMTAx' +
'NTEwMzYwOVowHzEdMBsGA1UEAxMUd3d3LmV0ZXJuYWxsaW5lcy5jb20wggEiMA0G' +
'CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCw/7d6zyehR69DaJCGbk3oMP7pSWya' +
'U1tDMG+CdqikLqHoo3SBshbvquOVFcy9yY8fECTbNXfOjhV0M6SJgGQ/SP/nfZgx' +
'MHAK9sWc5G6V5sqPqrTRgkv0Wu25mdO6FRh8DIxOMY0Ppqno5hHZ0emSj1amvtWX' +
'zBD6pXNGgrFln6HL2eyCwqlL0wTXWO/YrvblF/83Ln9i6luVQ9NtACQBiPcYqoNM' +
'1OG142xYNpRNp7zrHkNCQeXVxmC6goCgj0BmcSqrUPayLdgkgv8hniUwLYQIt91r' +
'cxJwGNWxlbLgqQqTdhecKp01JVgO8jy3yFpMEoqCj9+BuuxVqDfvHK1tAgMBAAGj' +
'gYAwfjAdBgNVHQ4EFgQUbLgD+S3ZSNlU1nxTsjTmAQIfpCQwTwYDVR0jBEgwRoAU' +
'bLgD+S3ZSNlU1nxTsjTmAQIfpCShI6QhMB8xHTAbBgNVBAMTFHd3dy5ldGVybmFs' +
'bGluZXMuY29tggkAoOyVCHd3yR0wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUF' +
'AAOCAQEACSQTcPC8ga5C/PysnoTNAk4OB+hdgMoS3Fv7ROUV9GqgYED6rJo0+CxD' +
'g19GLlKt/aBlglh4Ddc7X84dWtftS4JIjjVVkWevt8/sDoZ+ISd/tC9aDX3gOAlW' +
'RORhfp3Qtyy0AjZcIOAGNkzkotuMG/uOVifPFhTNXwa8hHOGN60riGXEj5sNFFop' +
'EaxplTfakVq8TxlQivnIETjrEbVX8XkOl4nlsHevC2suXE1ZkQIbQoaAy0WzGGUR' +
'54GBIzXf32t80S71w5rs/mzVaGOeTZYcHtv5Epd9CNVrEle6w0NW9R7Ov4gXI9n8' +
'GV9jITGfsOdqu7j9Iaf7MVj+JRE7Dw==' +
'-----END CERTIFICATE-----' +
'-----BEGIN RSA PRIVATE KEY-----' +
'MIIEpQIBAAKCAQEAsP+3es8noUevQ2iQhm5N6DD+6UlsmlNbQzBvgnaopC6h6KN0' +
'gbIW76rjlRXMvcmPHxAk2zV3zo4VdDOkiYBkP0j/532YMTBwCvbFnORulebKj6q0' +
'0YJL9FrtuZnTuhUYfAyMTjGND6ap6OYR2dHpko9Wpr7Vl8wQ+qVzRoKxZZ+hy9ns' +
'gsKpS9ME11jv2K725Rf/Ny5/YupblUPTbQAkAYj3GKqDTNThteNsWDaUTae86x5D' +
'QkHl1cZguoKAoI9AZnEqq1D2si3YJIL/IZ4lMC2ECLfda3MScBjVsZWy4KkKk3YX' +
'nCqdNSVYDvI8t8haTBKKgo/fgbrsVag37xytbQIDAQABAoIBAQCdnZnOCtrHjAZO' +
'iLbqfx9xPPBC3deQNdp3IpKqIvBaBAy6FZSSSfySwCKZiCgieXKxvraTXjGqBmyk' +
'ZbiHmYWrtV3szrLQWsnreYTQCbtQUYzgEquiRd1NZAt907XvZwm+rY3js8xhu5Bi' +
'jT4oMf1FPc9z/UxHOLmF+f+FMqy2SM2Fxh3jAsxJBaMVEJXpqdQDI86CATgYrqVY' +
'mlAWQcQ8pL0wwRctZ+XgjQH52V3sk4cIzqIBTO+MN6emmxDl9JdrGZKRei9YEIhG' +
'mFeXH7rsGg+TZtfvu1M9Kfy2fdgNwTUoTTn93v8gcrwCbyvl5JCzKy07Om/aOXFr' +
'I8bSWXIhAoGBANu07hegU99zIhvTWmh2Fuml0Lr+cHcZTObh+oeZg1xaDUrlnFOY' +
'3fyA5x5Jxib3V7OOAeIz/AsmcYq/649nR8NfeiizY5or84Fy1mazRR8diGDV3nUG' +
'ZATv6yaOY/z31FOLaxT95tDvqWK+Qr5cykq4e6XDDp9P8odCIjJmUdt7AoGBAM48' +
'vCjtGQ99BVwkcFIj0IacRj3YKzsp06W6V2Z+czlKctJAMAQN8hu9IcXMEIUsi9GD' +
'MkyzzxjvGRdmIuS58IFqRbr/fIAQLVpY9SPAL771ZCFHmIrKrCYiLYAcg/BSoR29' +
'me6aFaEcLBFvzHPFNymdyMsaOHSRMZYUlq6VUbI3AoGBAINJeMURf00VRZqPD4VA' +
'm6x+813qUVY5/iQxgT2qVD7JaQwKbQHfZTdP58vHlesO/o9DGokLO1+GV27sBF0r' +
'AE0VLrBHkgs8nEQMVWYFVhaj1SzYYBhZ+0af/0qI5+LwTSanNxPSLS1JKVTiEIwk' +
'cpV37Bs/letJIMoGkNzBG8UlAoGBAKrSfZt8f3RnvmfKusoeZhsJF9kj0vMHOwob' +
'ZUc8152Nf7uMdPj2wCGfr3iRBOH5urnH7ILBsHjbmjHaZG6FYKMg7i7sbSf5vkcG' +
'Rc3d4u5NfSlfjwbuxlYzmvJxLAuDtXXX1MdgEyhGGG485uDBamZrDaTEzBwpIyRH' +
'W2OxxGBTAoGAZHJQKTajcqQQoRSgPPWWU3X8zdlu5hCgNU54bXaPAfJ6IBWvicMZ' +
'QLw+9mtshtz+Xy0aBbkxUeUlwwzexb9rg1KZppTq/yRqkOlEkI3ZdqiclTK13BCh' +
'6r6dC2qqq+DVm9Nlm/S9Gab9YSIA0g5MFg5WLwu1KNwuOODE4Le/91c=' +
'-----END RSA PRIVATE KEY-----';
Assert(S.State = ssInit);
Assert(not S.Active);
// start server
S.Start;
Assert(S.Active);
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.State <> ssStarting) or (I >= 5000);
Sleep(100);
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
for K := 0 to TestClientCount - 1 do
begin
// init client
C[K].AddressFamily := cafIP4;
C[K].Host := '127.0.0.1';
C[K].Port := '12545';
C[K].TLSEnabled := True;
Assert(C[K].State = csInit);
Assert(not C[K].Active);
// start client
C[K].WaitForStartup := True;
C[K].Start;
Assert(Assigned(C[K].Connection));
Assert(C[K].Active);
end;
for K := 0 to TestClientCount - 1 do
// wait for client to connect
WaitClientConnected(C[K]);
// wait for server connections
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.ClientCount >= TestClientCount) or (I >= 5000);
Assert(S.ClientCount = TestClientCount);
// wait for server clients
TSC := S.ClientIterateFirst;
for K := 0 to TestClientCount - 1 do
begin
T[K] := TSC;
Assert(Assigned(T[K]));
Assert(T[K].State in [scsStarting, scsNegotiating, scsReady]);
Assert(T[K].Connection.State in [cnsProxyNegotiation, cnsConnected]);
I := 0;
repeat
Inc(I);
Sleep(1);
until (T[K].Connection.State = cnsConnected) or (I >= 5000);
Assert(T[K].Connection.State = cnsConnected);
Assert(not C[K].TLSEnabled or T[K].TLSClient.IsReadyState);
TSC.ReleaseReference;
TSC := S.ClientIterateNext(TSC);
end;
// test read/write
TestClientServer_ReadWrite_Blocks(
TestClientCount,
TestLargeBlock,
DebugObj,
C, T);
// release reference
for K := 0 to TestClientCount - 1 do
T[K].ReleaseReference;
// stop clients
for K := TestClientCount - 1 downto 0 do
begin
C[K].Stop;
Assert(C[K].State = csStopped);
end;
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.ClientCount = 0) or (I >= 5000);
Assert(S.ClientCount = 0);
// stop server
S.Stop;
Assert(not S.Active);
finally
for K := TestClientCount - 1 downto 0 do
begin
C[K].Finalise;
FreeAndNil(C[K]);
end;
S.Finalise;
FreeAndNil(S);
DebugObj.Free;
end;
end;
procedure Test_ClientServerTLS_ReadWrite;
begin
// TestClientServerTLS_ReadWrite(tmTLS, 1, True, [ctoDisableTLS10, ctoDisableTLS11, ctoDisableTLS12]); // SSL 3.0
TestClientServerTLS_ReadWrite(1, True, DefaultTCPClientTLSOptions, DefaultTLSClientOptions,
[tlsvoTLS12]); // TLS 1.2
TestClientServerTLS_ReadWrite(1, True, DefaultTCPClientTLSOptions, DefaultTLSClientOptions,
[tlsvoTLS11]); // TLS 1.1
TestClientServerTLS_ReadWrite(1, True, DefaultTCPClientTLSOptions, DefaultTLSClientOptions,
[tlsvoTLS10]); // TLS 1.0
end;
procedure Test;
begin
Test_ClientServerTLS_ReadWrite;
end;
{$ENDIF}
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSyncUtils;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, SyncObjs;
{$ELSE}
System.Classes, System.SyncObjs, System.Types;
{$ENDIF}
type
TclThreadSynchronizer = class
private
FMethod: TThreadMethod;
FSynchronizeException: TObject;
FSyncBaseThreadID: LongWord;
FAccessor: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Synchronize(Method: TThreadMethod);
procedure BeginWork;
procedure EndWork;
property SyncBaseThreadID: LongWord read FSyncBaseThreadID;
end;
resourcestring
cSyncInfoNotFound = 'Cannot find SyncInfo for the specified thread synchronizer';
implementation
uses
{$IFNDEF DELPHIXE2}
Windows{$IFDEF LOGGER}, SysUtils, clLogger{$ENDIF};
{$ELSE}
Winapi.Windows{$IFDEF LOGGER}, System.SysUtils, clLogger{$ENDIF};
{$ENDIF}
const
CM_EXECPROC = $8FFD;
CM_DESTROYWINDOW = $8FFC;
{$IFNDEF DELPHI6}
type
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = record
NextRaise: PRaiseFrame;
ExceptAddr: Pointer;
ExceptObject: TObject;
ExceptionRecord: PExceptionRecord;
end;
{$ENDIF}
type
TclSyncInfo = class
public
FSyncBaseThreadID: LongWord;
FThreadWindow: HWND;
FThreadCount: Integer;
end;
TclSynchronizerManager = class
private
FThreadLock: TRTLCriticalSection;
FList: TList;
procedure FreeSyncInfo(AInfo: TclSyncInfo);
procedure DoDestroyWindow(AInfo: TclSyncInfo);
function InfoBySync(ASyncBaseThreadID: LongWord): TclSyncInfo;
function FindSyncInfo(ASyncBaseThreadID: LongWord): TclSyncInfo;
public
class function Instance: TclSynchronizerManager;
constructor Create();
destructor Destroy; override;
procedure AddThread(ASynchronizer: TclThreadSynchronizer);
procedure RemoveThread(ASynchronizer: TclThreadSynchronizer);
procedure Synchronize(ASynchronizer: TclThreadSynchronizer);
end;
var
SynchronizerManager: TclSynchronizerManager = nil;
function ThreadWndProc(Window: HWND; Message, wParam, lParam: Longint): Longint; stdcall;
begin
case Message of
CM_EXECPROC:
with TclThreadSynchronizer(lParam) do
begin
Result := 0;
try
FSynchronizeException := nil;
FMethod();
except
{$IFDEF DELPHI6}
FSynchronizeException := AcquireExceptionObject();
{$ELSE}
if RaiseList <> nil then
begin
FSynchronizeException := PRaiseFrame(RaiseList)^.ExceptObject;
PRaiseFrame(RaiseList)^.ExceptObject := nil;
end;
{$ENDIF}
end;
end;
CM_DESTROYWINDOW:
begin
TclSynchronizerManager.Instance().DoDestroyWindow(TclSyncInfo(lParam));
Result := 0;
end;
else
Result := DefWindowProc(Window, Message, wParam, lParam);
end;
end;
var
ThreadWindowClass: TWndClass = (
style: 0;
lpfnWndProc: @ThreadWndProc;
cbClsExtra: 0;
cbWndExtra: 0;
hInstance: 0;
hIcon: 0;
hCursor: 0;
hbrBackground: 0;
lpszMenuName: nil;
lpszClassName: 'TclThreadSynchronizerWindow');
{ TclSynchronizerManager }
constructor TclSynchronizerManager.Create;
begin
inherited Create();
InitializeCriticalSection(FThreadLock);
FList := TList.Create();
end;
destructor TclSynchronizerManager.Destroy;
var
i: Integer;
begin
for i := FList.Count - 1 downto 0 do
begin
FreeSyncInfo(TclSyncInfo(FList[i]));
end;
FList.Free();
DeleteCriticalSection(FThreadLock);
inherited Destroy();
end;
class function TclSynchronizerManager.Instance: TclSynchronizerManager;
begin
if (SynchronizerManager = nil) then
begin
SynchronizerManager := TclSynchronizerManager.Create();
end;
Result := SynchronizerManager;
end;
procedure TclSynchronizerManager.AddThread(ASynchronizer: TclThreadSynchronizer);
function AllocateWindow: HWND;
var
TempClass: TWndClass;
ClassRegistered: Boolean;
begin
ThreadWindowClass.hInstance := HInstance;
ClassRegistered := GetClassInfo(HInstance, ThreadWindowClass.lpszClassName,
TempClass);
if not ClassRegistered or (TempClass.lpfnWndProc <> @ThreadWndProc) then
begin
if ClassRegistered then
{$IFDEF DELPHIXE2}Winapi.{$ENDIF}Windows.UnregisterClass(ThreadWindowClass.lpszClassName, HInstance);
{$IFDEF DELPHIXE2}Winapi.{$ENDIF}Windows.RegisterClass(ThreadWindowClass);
end;
Result := CreateWindow(ThreadWindowClass.lpszClassName, '', 0,
0, 0, 0, 0, 0, 0, HInstance, nil);
{$IFDEF LOGGER}
if (Result = 0) then
begin
clPutLogMessage(Self, edInside, 'AllocateWindow failed: %d', nil, [GetLastError()]);
end;
{$ENDIF}
end;
var
info: TclSyncInfo;
begin
EnterCriticalSection(FThreadLock);
try
info := FindSyncInfo(ASynchronizer.SyncBaseThreadID);
if (info = nil) then
begin
info := TclSyncInfo.Create();
info.FSyncBaseThreadID := ASynchronizer.SyncBaseThreadID;
FList.Add(info);
end;
if (info.FThreadCount = 0) then
begin
info.FThreadWindow := AllocateWindow();
end;
Inc(info.FThreadCount);
finally
LeaveCriticalSection(FThreadLock);
end;
end;
procedure TclSynchronizerManager.RemoveThread(ASynchronizer: TclThreadSynchronizer);
var
info: TclSyncInfo;
begin
EnterCriticalSection(FThreadLock);
try
info := InfoBySync(ASynchronizer.SyncBaseThreadID);
PostMessage(info.FThreadWindow, CM_DESTROYWINDOW, 0, Longint(info));
finally
LeaveCriticalSection(FThreadLock);
end;
end;
procedure TclSynchronizerManager.DoDestroyWindow(AInfo: TclSyncInfo);
begin
EnterCriticalSection(FThreadLock);
try
Dec(AInfo.FThreadCount);
if AInfo.FThreadCount = 0 then
begin
FreeSyncInfo(AInfo);
end;
finally
LeaveCriticalSection(FThreadLock);
end;
end;
procedure TclSynchronizerManager.FreeSyncInfo(AInfo: TclSyncInfo);
begin
if AInfo.FThreadWindow <> 0 then
begin
DestroyWindow(AInfo.FThreadWindow);
AInfo.Free();
FList.Remove(AInfo);
end;
end;
procedure TclSynchronizerManager.Synchronize(ASynchronizer: TclThreadSynchronizer);
begin
SendMessage(InfoBySync(ASynchronizer.SyncBaseThreadID).FThreadWindow, CM_EXECPROC, 0, Longint(ASynchronizer));
end;
function TclSynchronizerManager.FindSyncInfo(
ASyncBaseThreadID: LongWord): TclSyncInfo;
var
i: Integer;
begin
for i := 0 to FList.Count - 1 do
begin
Result := TclSyncInfo(FList[i]);
if (Result.FSyncBaseThreadID = ASyncBaseThreadID) then Exit;
end;
Result := nil;
end;
function TclSynchronizerManager.InfoBySync(
ASyncBaseThreadID: LongWord): TclSyncInfo;
begin
Result := FindSyncInfo(ASyncBaseThreadID);
{$IFDEF LOGGER}
if (Result = nil) then
begin
try
clPutLogMessage(Self, edInside, 'InfoBySync: Result = nil, ASyncBaseThreadID = %d, list.count = %d', nil, [ASyncBaseThreadID, FList.Count]);
except
on E: Exception do clPutLogMessage(Self, edInside, 'InfoBySync', E);
end;
end;
{$ENDIF}
Assert(Result <> nil, cSyncInfoNotFound);
end;
{ TclThreadSynchronizer }
procedure TclThreadSynchronizer.BeginWork;
begin
FAccessor.Enter();
end;
constructor TclThreadSynchronizer.Create;
begin
inherited Create();
FAccessor := TCriticalSection.Create();
FSyncBaseThreadID := GetCurrentThreadId();
TclSynchronizerManager.Instance().AddThread(Self);
end;
destructor TclThreadSynchronizer.Destroy;
begin
TclSynchronizerManager.Instance().RemoveThread(Self);
FAccessor.Free();
inherited Destroy();
end;
procedure TclThreadSynchronizer.EndWork;
begin
FAccessor.Leave();
end;
procedure TclThreadSynchronizer.Synchronize(Method: TThreadMethod);
begin
FSynchronizeException := nil;
FMethod := Method;
TclSynchronizerManager.Instance().Synchronize(Self);
if Assigned(FSynchronizeException) then raise FSynchronizeException;
end;
initialization
finalization
SynchronizerManager.Free();
SynchronizerManager := nil;
end.
|
unit uMain;
{$mode delphi}
interface
uses
glr_core, glr_math,
glr_render,
glr_render2d,
glr_scene,
glr_particles2d,
uBox2DImport, uSpace, uMoon,
UPhysics2D;
const
MAX_FUEL = 100.0;
FUEL_PER_SEC = 3.0;
SAFE_SPEED = 0.75;
LAND_SPEED = 0.10;
type
{ TFuelLevel }
TFuelLevel = class
Level: Single;
sBack, sLevel: TglrSprite;
sLevelOrigWidth: Single;
constructor Create();
destructor Destroy(); override;
procedure Update(const dt: Double);
end;
TGameStatus = (sPlay, sPause);
TGameEndReason = (rWin, rCrash, rAway);
TEditType = (etVertices, etLandingZones);
{ TGame }
TGame = class (TglrGame)
protected
fMoveFlag: Boolean;
fGameStatus: TGameStatus;
fPoint1, fPoint2: Byte;
fShipEngineDirection: TglrVec2f;
fCameraScale: Single;
fShipLinearSpeed: Single;
fSelectedObjectIndex: Integer;
fEditType: TEditType;
// debug purposes only
fEmitter: TglrCustomParticleEmitter2D;
procedure InitParticles();
procedure DeinitParticles();
procedure OnParticlesUpdate(const dt: Double);
function GetShipDistanceToNearestMoonVertex(): Single;
procedure PhysicsAfter(const FixedDeltaTime: Double);
procedure PhysicsContactBegin(var contact: Tb2Contact);
procedure PhysicsContactEnd(var contact: Tb2Contact);
procedure OnGameEnd(aReason: TGameEndReason);
public
//Resources
Atlas: TglrTextureAtlas;
Font: TglrFont;
Material, MoonMaterial: TglrMaterial;
MoonShader: TglrShaderProgram;
MoonTexture: TglrTexture;
//Batches
FontBatch, FontBatchHud: TglrFontBatch;
SpriteBatch: TglrSpriteBatch;
//Texts
HudEditorText, DebugText, HudMainText: TglrText;
//Sprites
Ship: TglrSprite;
Flame: TglrSprite;
ShipSpeedVec: TglrSprite;
Trigger1, Trigger2: TglrSprite;
IGDCFlag: TglrSprite;
//Box2D
World: Tglrb2World;
b2Ship: Tb2Body;
b2Trigger1, b2Trigger2: Tb2Body;
//Special Objects
FuelLevel: TFuelLevel;
Space: TSpace;
Moon: TMoon;
//Scenes
Scene, SceneHud: TglrScene;
procedure OnFinish; override;
procedure OnInput(Event: PglrInputEvent); override;
procedure OnPause; override;
procedure OnRender; override;
procedure OnResize(aNewWidth, aNewHeight: Integer); override;
procedure OnResume; override;
procedure OnStart; override;
procedure OnUpdate(const dt: Double); override;
end;
var
Game: TGame;
implementation
uses
glr_filesystem,
glr_utils,
UPhysics2DTypes;
{ TFuelLevel }
constructor TFuelLevel.Create;
begin
inherited;
sBack := TglrSprite.Create();
sBack.SetTextureRegion(Game.Atlas.GetRegion('fuel_level_back.png'));
sLevel := TglrSprite.Create(1, 1, Vec2f(0, 0.5));
sLevel.SetTextureRegion(Game.Atlas.GetRegion('fuel_level.png'));
sLevel.Height := sLevel.Height * 0.9;
sLevelOrigWidth := sLevel.Width;
Level := MAX_FUEL;
end;
destructor TFuelLevel.Destroy;
begin
sBack.Free();
sLevel.Free();
inherited;
end;
procedure TFuelLevel.Update(const dt: Double);
begin
sBack.Position := Game.Ship.Position + Vec3f(0, -65, 1);
sLevel.Position := sBack.Position + Vec3f(-50.5, 5.5, 1);
sLevel.Width := sLevelOrigWidth * Level / MAX_FUEL;
sLevel.SetVerticesColor(Vec4f(1, 0.3 + Level / MAX_FUEL, 0.3 + Level / MAX_FUEL, 1));
end;
{ TGame }
procedure TGame.OnStart;
var
landerV: array[0..5] of TglrVec2f =
(
(x: -0.5; y: 0.48),
(x: 0; y: 0.35),
(x: 0.48; y: 0.12),
(x: 0; y:-0.35),
(x: 0.48; y:-0.12),
(x: -0.5; y:-0.48)
);
i: Integer;
begin
Render.SetClearColor(0.1, 0.1, 0.13);
Atlas := TglrTextureAtlas.Create(
FileSystem.ReadResource('lander/atlas.tga'),
FileSystem.ReadResource('lander/atlas.atlas'),
extTga, aextCheetah);
Material := TglrMaterial.Create(Default.SpriteShader);
Material.AddTexture(Atlas, 'uDiffuse');
Font := TglrFont.Create(FileSystem.ReadResource('lander/AmazingGrotesk19.fnt'));
MoonTexture := TglrTexture.Create(FileSystem.ReadResource('lander/moon.tga'), extTga, True);
MoonTexture.SetWrapS(wRepeat);
MoonTexture.SetWrapR(wRepeat);
MoonTexture.SetWrapT(wRepeat);
MoonShader := TglrShaderProgram.Create();
MoonShader.Attach(FileSystem.ReadResource('lander/MoonShaderV.txt'), stVertex);
MoonShader.Attach(FileSystem.ReadResource('lander/MoonShaderF.txt'), stFragment);
MoonShader.Link();
MoonMaterial := TglrMaterial.Create(MoonShader);
MoonMaterial.AddTexture(MoonTexture, 'uDiffuse');
MoonMaterial.Color := Vec4f(0.70, 0.70, 0.55, 1.0);
World := Tglrb2World.Create(TVector2.From(0, 9.8 * C_COEF), false, 1 / 40, 8);
World.AddOnBeginContact(Self.PhysicsContactBegin);
World.AddOnEndContact(Self.PhysicsContactEnd);
World.OnAfterSimulation := Self.PhysicsAfter;
Ship := TglrSprite.Create();
Ship.SetTextureRegion(Atlas.GetRegion('lander.png'));
Ship.Position := Vec3f(200, 100, 2);
Trigger1 := TglrSprite.Create();
Trigger1.SetTextureRegion(Atlas.GetRegion('star.png'), False);
Trigger1.SetSize(10, 10);
Trigger1.SetVerticesColor(Vec4f(1, 0, 0, 0.5));
Trigger1.Parent := Ship;
Trigger1.Position := Vec3f(-0.5 * Ship.Width, 0.5 * Ship.Height, 1);
Trigger2 := TglrSprite.Create();
Trigger2.SetTextureRegion(Atlas.GetRegion('star.png'), False);
Trigger2.SetSize(10, 10);
Trigger2.SetVerticesColor(Vec4f(1, 0, 0, 0.5));
Trigger2.Parent := Ship;
Trigger2.Position := Vec3f(-0.5 * Ship.Width, - 0.5 * Ship.Height, 1);
b2Trigger1 := Box2D.BoxSensor(World, Vec2f(Trigger1.Position), Vec2f(Trigger1.Width * 1.2, Trigger1.Height), 0, $0002, $0001, False);
b2Trigger1.UserData := @fPoint1;
b2Trigger2 := Box2D.BoxSensor(World, Vec2f(Trigger2.Position), Vec2f(Trigger2.Width * 1.2, Trigger2.Height), 0, $0002, $0001, False);
b2Trigger2.UserData := @fPoint2;
for i := 0 to Length(landerV) - 1 do
landerV[i] *= Ship.Width;
b2Ship := Box2d.Polygon(World, Vec2f(Ship.Position), landerV, 0.5, 1.0, 0.0, $0002, $0001, 1);
b2Ship.AngularDamping := 1.0;
b2Ship.UserData := Ship;
Flame := TglrSprite.Create();
Flame.SetTextureRegion(Atlas.GetRegion('flame.png'));
Flame.Position := Vec3f(-50, 0, -1);
Flame.SetVerticesColor(Vec4f(0.9, 0.85, 0.1, 1.0));
Flame.Parent := Ship;
ShipSpeedVec := TglrSprite.Create();
ShipSpeedVec.SetTextureRegion(Atlas.GetRegion('arrow.png'));
SpriteBatch := TglrSpriteBatch.Create();
//Text for editor purposes
HudEditorText := TglrText.Create();
HudEditorText.Position := Vec3f(Render.Width / 2 - 150, 20, 5);
HudEditorText.LetterSpacing := 1.2;
//Text at spaceship' right
DebugText := TglrText.Create();
DebugText.Position.z := 10;
DebugText.LetterSpacing := 1.2;
//Text for win/lose
HudMainText := TglrText.Create();
HudMainText.Position := Vec3f(50, 50, 15);
HudMainText.LetterSpacing := 1.2;
HudMainText.LineSpacing := 1.5;
FontBatch := TglrFontBatch.Create(Font);
FontBatchHud := TglrFontBatch.Create(Font);
Scene := TglrScene.Create();
Scene.Camera.SetProjParams(0, 0, Render.Width, Render.Height, 90, -1, 200, pmOrtho, pCenter);
Scene.Camera.SetViewParams(
Vec3f(Render.Width / 2, Render.Height / 2, 100),
Vec3f(Render.Width / 2, Render.Height / 2, 0),
Vec3f(0, 1, 0));
SceneHud := TglrScene.Create();
SceneHud.Camera.SetProjParams(0, 0, Render.Width, Render.Height, 90, -1, 200, pmOrtho, pTopLeft);
SceneHud.Camera.SetViewParams(
Vec3f(0, 0, 100),
Vec3f(0, 0, 0),
Vec3f(0, 1, 0));
FuelLevel := TFuelLevel.Create();
Space := TSpace.Create(Vec2f(-1.5 * Render.Width, -1.5 * Render.Height),
Vec2f(3 * Render.Width, 3 * Render.Height),
Atlas.GetRegion('star.png'), Material, 3);
Space.Camera := Scene.Camera;
Moon := TMoon.Create(MoonMaterial, Material, Atlas.GetRegion('blank.png'), SpriteBatch, FontBatch);
Moon.MaxY := Render.Height * 2;
Moon.LoadLevel(FileSystem.ReadResource('lander/level1.bin'));
IGDCFlag := TglrSprite.Create(1, 1, Vec2f(0, 1));
IGDCFlag.SetTextureRegion(Atlas.GetRegion('flag.png'));
IGDCFlag.Visible := False;
fGameStatus := sPlay;
fPoint1 := 0;
fPoint2 := 0;
fMoveFlag := False;
InitParticles();
end;
procedure TGame.InitParticles;
begin
fEmitter := TglrCustomParticleEmitter2D.Create(SpriteBatch, Material, Atlas.GetRegion('particle.png'));
fEmitter.OnUpdate := OnParticlesUpdate;
end;
procedure TGame.DeinitParticles;
begin
fEmitter.Free();
end;
procedure TGame.OnParticlesUpdate(const dt: Double);
procedure SetParticleAlpha(aParticle: TglrParticle2D; alpha: Single);
var
i: Integer;
begin
for i := 0 to 3 do
aParticle.Vertices[i].col.w := alpha;
end;
var
p: TglrParticle2D;
i: Integer;
begin
for i := 0 to fEmitter.Particles.Count - 1 do
begin
p := fEmitter.Particles[i];
if (not p.Visible) then
continue;
SetParticleAlpha(p, (p.LifeTime - p.T) / p.LifeTime);
end;
end;
function TGame.GetShipDistanceToNearestMoonVertex: Single;
var
i: Integer;
s: Single;
begin
Result := 1 / 0;
for i := 0 to Length(Moon.Vertices) - 1 do
begin
s := (Vec2f(Ship.Position) - Moon.Vertices[i]).Length;
if s < Result then
Result := s;
end;
Result -= (Ship.Width / 2);
end;
procedure TGame.PhysicsAfter(const FixedDeltaTime: Double);
begin
end;
procedure TGame.PhysicsContactBegin(var contact: Tb2Contact);
var
b1, b2: Tb2Body;
//vel1, vel2, imp: TVector2;
//worldManifold: Tb2WorldManifold;
begin
b1 := contact.m_fixtureA.GetBody;
b2 := contact.m_fixtureB.GetBody;
//contact.GetWorldManifold(worldManifold);
if ((b1.UserData = Ship) and (b2.UserData = Moon))
or ((b2.UserData = Ship) and (b1.UserData = Moon)) then
begin
//vel1 := b1.GetLinearVelocityFromWorldPoint(worldManifold.points[0]);
//vel2 := b2.GetLinearVelocityFromWorldPoint(worldManifold.points[0]);
//imp := vel1 - vel2;
if {imp.Length} fShipLinearSpeed > SAFE_SPEED then
begin
OnGameEnd(rCrash);
end
else if fShipLinearSpeed > LAND_SPEED then
begin
HudMainText.Text := UTF8Decode('Осторожно!');
HudMainText.Color := Vec4f(1, 1, 0.1, 1);
end
else
begin
// OnGameEnd(rWin);
end;
end
else if ( (contact.m_fixtureA.IsSensor) and (b2.UserData = Moon) ) then
begin
Byte(b1.UserData^) += 1;
end
else if ( (contact.m_fixtureB.IsSensor) and (b1.UserData = Moon) ) then
begin
Byte(b2.UserData^) += 1;
end;
end;
procedure TGame.PhysicsContactEnd(var contact: Tb2Contact);
var
b1, b2: Tb2Body;
begin
b1 := contact.m_fixtureA.GetBody;
b2 := contact.m_fixtureB.GetBody;
if ( (contact.m_fixtureA.IsSensor) and (b2.UserData = Moon) ) then
begin
Byte(b1.UserData^) -= 1;
end
else if ( (contact.m_fixtureB.IsSensor) and (b1.UserData = Moon) ) then
begin
Byte(b2.UserData^) -= 1;
end;
end;
procedure TGame.OnGameEnd(aReason: TGameEndReason);
var
scores: Integer;
i1, i2: Integer;
begin
fGameStatus := sPause;
if aReason = rWin then
begin
scores := Ceil((FuelLevel.Level / MAX_FUEL) * 1000);
i1 := Moon.GetLandingZoneAtPos(Vec2f(Trigger1.AbsoluteMatrix.Pos));
i2 := Moon.GetLandingZoneAtPos(Vec2f(Trigger2.AbsoluteMatrix.Pos));
if (i1 = i2) and (i1 <> -1) then
scores *= Moon.LandingZones[i1].Multiply;
HudMainText.Text := UTF8Decode('Очки: ' + Convert.ToString(scores)
+ #13#10#13#10'Вы успешно прилунились!'
+ #13#10'Пора искать селенитов!'
+ #13#10'Но, может еще разок?'
+ #13#10#13#10'Enter — рестарт');
HudMainText.Color := Vec4f(0.1, 1, 0.1, 1);
fMoveFlag := True;
IGDCFlag.Position := Ship.Position + Vec3f(0, 40, -1);
IGDCFlag.Visible := True;
FuelLevel.sBack.Visible := False;
FuelLevel.sLevel.Visible := False;
DebugText.Visible := False;
ShipSpeedVec.Visible := False;
end
else if aReason = rCrash then
begin
HudMainText.Text := UTF8Decode('Потрачено!'
+ #13#10#13#10'Аппарат разбит, вы погибли!'
+ #13#10'ЦУП воет и не знает, кого винить!'
+ #13#10'А пока там неразбериха — давайте еще раз...'
+ #13#10#13#10'Enter — рестарт');
HudMainText.Color := Vec4f(1.0, 0.1, 0.1, 1);
DebugText.Visible := False;
ShipSpeedVec.Visible := False;
end
else if aReason = rAway then
begin
HudMainText.Text := UTF8Decode('Вы покинули зону посадки!'
+ #13#10#13#10'ЦУП негодует, вы разжалованы, осуждены и'
+ #13#10'будете уничтожены с помощью Большого Боевого Лазера!'
+ #13#10'Пожалуйста, оставайтесь на месте!'
+ #13#10#13#10'Enter — рестарт');
HudMainText.Color := Vec4f(1.0, 0.1, 0.1, 1);
end;
end;
procedure TGame.OnFinish;
begin
DeinitParticles();
Space.Free();
Moon.Free();
Scene.Free();
SceneHud.Free();
FuelLevel.Free();
Material.Free();
MoonMaterial.Free();
MoonShader.Free();
Atlas.Free();
MoonTexture.Free();
Font.Free();
World.DestroyBody(b2Ship);
World.DestroyBody(b2Trigger1);
World.DestroyBody(b2Trigger2);
World.Free();
Trigger1.Free();
Trigger2.Free();
Flame.Free();
Ship.Free();
ShipSpeedVec.Free();
IGDCFlag.Free();
HudEditorText.Free();
HudMainText.Free();
DebugText.Free();
SpriteBatch.Free();
FontBatch.Free();
FontBatchHud.Free();
end;
procedure TGame.OnInput(Event: PglrInputEvent);
var
i: Integer;
absMousePos: TglrVec2f;
vertexAdded: Boolean;
begin
if (Event.InputType = itKeyUp) and (Event.Key = kE) then
begin
Moon.EditMode := not Moon.EditMode;
if Moon.EditMode then
begin
HudEditorText.Text := UTF8Decode('В режиме редактора'#13#10'Режим: Поверхность');
fEditType := etVertices;
fSelectedObjectIndex := -1;
end
else
HudEditorText.Text := '';
end;
if not Moon.EditMode then
begin
if (Event.InputType = itKeyDown) and (Event.Key = kEscape) then
Core.Quit();
if fGameStatus = sPause then
begin
if (Event.InputType = itKeyDown) and (Event.Key = kReturn) then
begin
Game.OnFinish();
Game.OnStart();
end;
end;
end
//Editor mode
else
begin
if Event.InputType = itKeyUp then
case Event.Key of
kT: begin
if fEditType = etVertices then
begin
fEditType := etLandingZones;
HudEditorText.Text := UTF8Decode('В режиме редактора'#13#10'Режим: Зоны посадки');
end
else if fEditType = etLandingZones then
begin
fEditType := etVertices;
HudEditorText.Text := UTF8Decode('В режиме редактора'#13#10'Режим: Поверхность');
end;
end;
kS: begin
FileSystem.WriteResource('lander/level1.bin', Moon.SaveLevel());
HudEditorText.Text := UTF8Decode('Успешно сохранено');
end;
kL: begin
Moon.LoadLevel(FileSystem.ReadResource('lander/level1.bin'));
HudEditorText.Text := UTF8Decode('Успешно загружено');
end;
k2, k3, k4, k5:
if (fEditType = etLandingZones) and (fSelectedObjectIndex <> -1) then
begin
Moon.LandingZones[fSelectedObjectIndex].Multiply := Ord(Event.Key) - Ord(k0);
Moon.LandingZones[fSelectedObjectIndex].Update();
end;
end;
absMousePos := Scene.Camera.ScreenToWorld(Core.Input.MousePos);
if (Event.InputType = itTouchDown) and (Event.Key = kLeftButton) then
case fEditType of
etVertices: fSelectedObjectIndex := Moon.GetVertexIndexAtPos(absMousePos);
etLandingZones: fSelectedObjectIndex := Moon.GetLandingZoneAtPos(absMousePos);
end;
if (Event.InputType = itTouchDown) and (Event.Key = kRightButton) then
if fEditType = etVertices then
begin
i := Moon.GetVertexIndexAtPos(absMousePos);
if i = -1 then
begin
vertexAdded := False;
for i := 0 to Length(Moon.Vertices) - 1 do
if Moon.Vertices[i].x > absMousePos.x then
begin
Moon.AddVertex(absMousePos, i);
vertexAdded := True;
break;
end;
if not vertexAdded then
Moon.AddVertex(absMousePos);
end
else
Moon.DeleteVertex(i);
Moon.UpdateData();
end
else if fEditType = etLandingZones then
begin
i := Moon.GetLandingZoneAtPos(absMousePos);
if i = -1 then
Moon.AddLandingZone(absMousePos, Vec2f(100, 50), 2)
else
Moon.DeleteLandingZone(i);
end;
if (Event.InputType = itTouchMove) and (Event.Key = kLeftButton) then
if fSelectedObjectIndex <> -1 then
if fEditType = etVertices then
begin
Moon.Vertices[fSelectedObjectIndex] := absMousePos;
Moon.VerticesPoints[fSelectedObjectIndex].Position :=
Vec3f(Moon.Vertices[fSelectedObjectIndex], Moon.VerticesPoints[fSelectedObjectIndex].Position.z);
Moon.UpdateData();
end
else if fEditType = etLandingZones then
begin
Moon.LandingZones[fSelectedObjectIndex].Pos := absMousePos;
Moon.LandingZones[fSelectedObjectIndex].Update();
end;
if (Event.InputType = itTouchUp) and (Event.Key = kLeftButton) then
fSelectedObjectIndex := -1;
if Event.InputType = itWheel then
Scene.Camera.Scale := Scene.Camera.Scale + (Event.W * 0.1);
end;
end;
procedure TGame.OnPause;
begin
end;
procedure TGame.OnRender;
begin
Scene.Camera.Update();
Space.RenderSelf();
Moon.RenderSelf();
//Render.Params.ModelViewProj := Render.Params.ViewProj;
Scene.RenderScene();
Material.Bind();
SpriteBatch.Start();
SpriteBatch.Draw(Flame);
SpriteBatch.Draw(Ship);
SpriteBatch.Draw(Trigger1);
SpriteBatch.Draw(Trigger2);
SpriteBatch.Draw(ShipSpeedVec);
SpriteBatch.Draw(IGDCFlag);
SpriteBatch.Draw(FuelLevel.sBack);
SpriteBatch.Draw(FuelLevel.sLevel);
SpriteBatch.Finish();
FontBatch.Start();
FontBatch.Draw(DebugText);
FontBatch.Finish();
// Render particles
Material.DepthWrite := False;
Material.Bind();
fEmitter.RenderSelf();
Material.DepthWrite := True;
Material.Bind();
// Last - render landing zones
Moon.RenderLandingZones();
// At very last - render hud
SceneHud.RenderScene();
FontBatchHud.Start();
FontBatchHud.Draw(HudMainText);
FontBatchHud.Draw(HudEditorText);
FontBatchHud.Finish();
end;
procedure TGame.OnResize(aNewWidth, aNewHeight: Integer);
begin
end;
procedure TGame.OnResume;
begin
end;
procedure TGame.OnUpdate(const dt: Double);
begin
if not Moon.EditMode then
begin
if fGameStatus = sPlay then
begin
if Core.Input.KeyDown[kLeft] then
b2Ship.ApplyAngularImpulse(- Core.DeltaTime * 3)
else if Core.Input.KeyDown[kRight] then
b2Ship.ApplyAngularImpulse( Core.DeltaTime * 3);
Flame.Visible := (Core.Input.KeyDown[kUp] or Core.Input.KeyDown[kDown] or Core.Input.KeyDown[kSpace])
and (FuelLevel.Level > 0);
if Flame.Visible then
begin
FuelLevel.Level -= dt * FUEL_PER_SEC;
fShipEngineDirection := Vec2f(Ship.Rotation) * dt;
b2Ship.ApplyLinearImpulse(TVector2.From(fShipEngineDirection.x, fShipEngineDirection.y), b2Ship.GetWorldCenter);
if fEmitter.ActiveParticlesCount < 128 then
with fEmitter.GetNewParticle() do
begin
Position := Flame.AbsoluteMatrix.Pos;
Position.z += 1;
Position += Vec3f(10 - Random(20), 10 - Random(20), Random(3));
Rotation := Random(180);
//SetVerticesColor(dfVec4f(Random(), Random(), Random(), 1.0));
SetVerticesColor(Vec4f(1.0, 0.5 * Random(), 0.3 * Random(), 1.0));
Width := 0.3 + Width * Random();
Height := Width;
LifeTime := 1.5;
Velocity := Vec2f(15 - Random(30) + Ship.Rotation) * (120 + Random(40)) * (-1);
end;
end;
Box2d.SyncObjects(b2Ship, Ship);
World.Update(dt);
fCameraScale := 1.0; // * (1 / Clamp(b2Ship.GetLinearVelocity.SqrLength, 1.0, 1.85)); //no fShipLinearSpeed clamp
fCameraScale *= (1 / Clamp(GetShipDistanceToNearestMoonVertex() * 0.01, 0.9, 2.0));
Scene.Camera.Scale := Lerp(Scene.Camera.Scale, fCameraScale, 5 * dt);
with Scene.Camera do
Position := Vec3f(Vec2f(Ship.Position), Position.z);
// Position := dfVec3f(dfVec2f(Position.Lerp(Ship.Position, 5 * dt)), Position.z);
FuelLevel.Update(dt);
fShipLinearSpeed := b2Ship.GetLinearVelocity.Length;
if fShipLinearSpeed > SAFE_SPEED then
DebugText.Color := Vec4f(1, 0.3, 0.3, 1.0)
else
DebugText.Color := Vec4f(0.3, 1.0, 0.3, 1.0);
DebugText.Position := Ship.Position + Vec3f(60, -10, 10);
DebugText.Text := Convert.ToString(fShipLinearSpeed, 2);
ShipSpeedVec.Position := DebugText.Position + Vec3f(20, -20, 0);
ShipSpeedVec.SetVerticesColor(DebugText.Color);
ShipSpeedVec.Rotation := Box2d.ConvertB2ToGL(b2Ship.GetLinearVelocity).GetRotationAngle();
if (Ship.Position.x > Moon.Vertices[High(Moon.Vertices)].x) or
(Ship.Position.x < Moon.Vertices[0].x) then
OnGameEnd(rAway);
Box2d.ReverseSyncObjects(Trigger1, b2Trigger1);
Box2d.ReverseSyncObjects(Trigger2, b2Trigger2);
if fPoint1 > 0 then
Trigger1.SetVerticesColor(Vec4f(0, 1, 0, 0.5))
else
Trigger1.SetVerticesColor(Vec4f(1, 0, 0, 0.5));
if fPoint2 > 0 then
Trigger2.SetVerticesColor(Vec4f(0, 1, 0, 0.5))
else
Trigger2.SetVerticesColor(Vec4f(1, 0, 0, 0.5));
if (fShipLinearSpeed < LAND_SPEED) and (fPoint1 > 0) and (fPoint2 > 0) and not Flame.Visible then
OnGameEnd(rWin);
fEmitter.Update(dt);
end
else if fGameStatus = sPause then
begin
if fMoveFlag then
begin
IGDCFlag.Position.y -= dt * 40;
if (Ship.Position.y - IGDCFlag.Position.y) > Ship.Height / 2 - 15 then
fMoveFlag := False;
end;
end;
end
else
begin
if fSelectedObjectIndex = -1 then
begin
if Core.Input.KeyDown[kUp] then
Scene.Camera.Translate(-dt * 200, 0, 0)
else if Core.Input.KeyDown[kDown] then
Scene.Camera.Translate(dt * 200, 0, 0);
if Core.Input.KeyDown[kLeft] then
Scene.Camera.Translate(0, -dt * 200, 0)
else if Core.Input.KeyDown[kRight] then
Scene.Camera.Translate(0, dt * 200, 0);
end
else if (fEditType = etLandingZones) then
begin
if Core.Input.KeyDown[kUp] then
Moon.LandingZones[fSelectedObjectIndex].Size.y += dt * 30
else if Core.Input.KeyDown[kDown] then
Moon.LandingZones[fSelectedObjectIndex].Size.y -= dt * 30;
if Core.Input.KeyDown[kLeft] then
Moon.LandingZones[fSelectedObjectIndex].Size.x += dt * 30
else if Core.Input.KeyDown[kRight] then
Moon.LandingZones[fSelectedObjectIndex].Size.x -= dt * 30;
Moon.LandingZones[fSelectedObjectIndex].Update();
end;
end;
end;
end.
|
unit l3Languages;
{ Константы и процедуры выдернуты из Windows.pas, входящего в состав Delphi 2009 }
interface
uses
l3Base,
l3ProtoObject;
(*
* Language IDs.
*
* The following two combinations of primary language ID and
* sublanguage ID have special semantics:
*
* Primary Language ID Sublanguage ID Result
* ------------------- --------------- ------------------------
* LANG_NEUTRAL SUBLANG_NEUTRAL Language neutral
* LANG_NEUTRAL SUBLANG_DEFAULT User default language
* LANG_NEUTRAL SUBLANG_SYS_DEFAULT System default language
* LANG_INVARIANT SUBLANG_NEUTRAL Invariant locale
*)
const
{ Primary language IDs. }
LANG_NEUTRAL = $00;
{$EXTERNALSYM LANG_NEUTRAL}
LANG_INVARIANT = $7f;
{$EXTERNALSYM LANG_INVARIANT}
LANG_AFRIKAANS = $36;
{$EXTERNALSYM LANG_AFRIKAANS}
LANG_ALBANIAN = $1c;
{$EXTERNALSYM LANG_ALBANIAN}
LANG_ARABIC = $01;
{$EXTERNALSYM LANG_ARABIC}
LANG_BASQUE = $2d;
{$EXTERNALSYM LANG_BASQUE}
LANG_BELARUSIAN = $23;
{$EXTERNALSYM LANG_BELARUSIAN}
LANG_BULGARIAN = $02;
{$EXTERNALSYM LANG_BULGARIAN}
LANG_CATALAN = $03;
{$EXTERNALSYM LANG_CATALAN}
LANG_CHINESE = $04;
{$EXTERNALSYM LANG_CHINESE}
LANG_CROATIAN = $1a;
{$EXTERNALSYM LANG_CROATIAN}
LANG_CZECH = $05;
{$EXTERNALSYM LANG_CZECH}
LANG_DANISH = $06;
{$EXTERNALSYM LANG_DANISH}
LANG_DUTCH = $13;
{$EXTERNALSYM LANG_DUTCH}
LANG_ENGLISH = $09;
{$EXTERNALSYM LANG_ENGLISH}
LANG_ESTONIAN = $25;
{$EXTERNALSYM LANG_ESTONIAN}
LANG_FAEROESE = $38;
{$EXTERNALSYM LANG_FAEROESE}
LANG_FARSI = $29;
{$EXTERNALSYM LANG_FARSI}
LANG_FINNISH = $0b;
{$EXTERNALSYM LANG_FINNISH}
LANG_FRENCH = $0c;
{$EXTERNALSYM LANG_FRENCH}
LANG_GERMAN = $07;
{$EXTERNALSYM LANG_GERMAN}
LANG_GREEK = $08;
{$EXTERNALSYM LANG_GREEK}
LANG_HEBREW = $0d;
{$EXTERNALSYM LANG_HEBREW}
LANG_HUNGARIAN = $0e;
{$EXTERNALSYM LANG_HUNGARIAN}
LANG_ICELANDIC = $0f;
{$EXTERNALSYM LANG_ICELANDIC}
LANG_INDONESIAN = $21;
{$EXTERNALSYM LANG_INDONESIAN}
LANG_ITALIAN = $10;
{$EXTERNALSYM LANG_ITALIAN}
LANG_JAPANESE = $11;
{$EXTERNALSYM LANG_JAPANESE}
LANG_KOREAN = $12;
{$EXTERNALSYM LANG_KOREAN}
LANG_LATVIAN = $26;
{$EXTERNALSYM LANG_LATVIAN}
LANG_LITHUANIAN = $27;
{$EXTERNALSYM LANG_LITHUANIAN}
LANG_NORWEGIAN = $14;
{$EXTERNALSYM LANG_NORWEGIAN}
LANG_POLISH = $15;
{$EXTERNALSYM LANG_POLISH}
LANG_PORTUGUESE = $16;
{$EXTERNALSYM LANG_PORTUGUESE}
LANG_ROMANIAN = $18;
{$EXTERNALSYM LANG_ROMANIAN}
LANG_RUSSIAN = $19;
{$EXTERNALSYM LANG_RUSSIAN}
LANG_SERBIAN = $1a;
{$EXTERNALSYM LANG_SERBIAN}
LANG_SLOVAK = $1b;
{$EXTERNALSYM LANG_SLOVAK}
LANG_SLOVENIAN = $24;
{$EXTERNALSYM LANG_SLOVENIAN}
LANG_SPANISH = $0a;
{$EXTERNALSYM LANG_SPANISH}
LANG_SWEDISH = $1d;
{$EXTERNALSYM LANG_SWEDISH}
LANG_TATAR = $44;
LANG_THAI = $1e;
{$EXTERNALSYM LANG_THAI}
LANG_TURKISH = $1f;
{$EXTERNALSYM LANG_TURKISH}
LANG_UKRAINIAN = $22;
{$EXTERNALSYM LANG_UKRAINIAN}
LANG_VIETNAMESE = $2a;
{$EXTERNALSYM LANG_VIETNAMESE}
{ Sublanguage IDs. }
{ The name immediately following SUBLANG_ dictates which primary
language ID that sublanguage ID can be combined with to form a
valid language ID. }
SUBLANG_NEUTRAL = $00; { language neutral }
{$EXTERNALSYM SUBLANG_NEUTRAL}
SUBLANG_DEFAULT = $01; { user default }
{$EXTERNALSYM SUBLANG_DEFAULT}
SUBLANG_SYS_DEFAULT = $02; { system default }
{$EXTERNALSYM SUBLANG_SYS_DEFAULT}
SUBLANG_CUSTOM_DEFAULT = $03; { default custom language/locale }
{$EXTERNALSYM SUBLANG_CUSTOM_DEFAULT}
SUBLANG_CUSTOM_UNSPECIFIED = $04; { custom language/locale }
{$EXTERNALSYM SUBLANG_CUSTOM_UNSPECIFIED}
SUBLANG_UI_CUSTOM_DEFAULT = $05; { Default custom MUI language/locale }
{$EXTERNALSYM SUBLANG_UI_CUSTOM_DEFAULT}
SUBLANG_ARABIC_SAUDI_ARABIA = $01; { Arabic (Saudi Arabia) }
{$EXTERNALSYM SUBLANG_ARABIC_SAUDI_ARABIA}
SUBLANG_ARABIC_IRAQ = $02; { Arabic (Iraq) }
{$EXTERNALSYM SUBLANG_ARABIC_IRAQ}
SUBLANG_ARABIC_EGYPT = $03; { Arabic (Egypt) }
{$EXTERNALSYM SUBLANG_ARABIC_EGYPT}
SUBLANG_ARABIC_LIBYA = $04; { Arabic (Libya) }
{$EXTERNALSYM SUBLANG_ARABIC_LIBYA}
SUBLANG_ARABIC_ALGERIA = $05; { Arabic (Algeria) }
{$EXTERNALSYM SUBLANG_ARABIC_ALGERIA}
SUBLANG_ARABIC_MOROCCO = $06; { Arabic (Morocco) }
{$EXTERNALSYM SUBLANG_ARABIC_MOROCCO}
SUBLANG_ARABIC_TUNISIA = $07; { Arabic (Tunisia) }
{$EXTERNALSYM SUBLANG_ARABIC_TUNISIA}
SUBLANG_ARABIC_OMAN = $08; { Arabic (Oman) }
{$EXTERNALSYM SUBLANG_ARABIC_OMAN}
SUBLANG_ARABIC_YEMEN = $09; { Arabic (Yemen) }
{$EXTERNALSYM SUBLANG_ARABIC_YEMEN}
SUBLANG_ARABIC_SYRIA = $0a; { Arabic (Syria) }
{$EXTERNALSYM SUBLANG_ARABIC_SYRIA}
SUBLANG_ARABIC_JORDAN = $0b; { Arabic (Jordan) }
{$EXTERNALSYM SUBLANG_ARABIC_JORDAN}
SUBLANG_ARABIC_LEBANON = $0c; { Arabic (Lebanon) }
{$EXTERNALSYM SUBLANG_ARABIC_LEBANON}
SUBLANG_ARABIC_KUWAIT = $0d; { Arabic (Kuwait) }
{$EXTERNALSYM SUBLANG_ARABIC_KUWAIT}
SUBLANG_ARABIC_UAE = $0e; { Arabic (U.A.E) }
{$EXTERNALSYM SUBLANG_ARABIC_UAE}
SUBLANG_ARABIC_BAHRAIN = $0f; { Arabic (Bahrain) }
{$EXTERNALSYM SUBLANG_ARABIC_BAHRAIN}
SUBLANG_ARABIC_QATAR = $10; { Arabic (Qatar) }
{$EXTERNALSYM SUBLANG_ARABIC_QATAR}
SUBLANG_CHINESE_TRADITIONAL = $01; { Chinese (Taiwan) }
{$EXTERNALSYM SUBLANG_CHINESE_TRADITIONAL}
SUBLANG_CHINESE_SIMPLIFIED = $02; { Chinese (PR China) }
{$EXTERNALSYM SUBLANG_CHINESE_SIMPLIFIED}
SUBLANG_CHINESE_HONGKONG = $03; { Chinese (Hong Kong) }
{$EXTERNALSYM SUBLANG_CHINESE_HONGKONG}
SUBLANG_CHINESE_SINGAPORE = $04; { Chinese (Singapore) }
{$EXTERNALSYM SUBLANG_CHINESE_SINGAPORE}
SUBLANG_DUTCH = $01; { Dutch }
{$EXTERNALSYM SUBLANG_DUTCH}
SUBLANG_DUTCH_BELGIAN = $02; { Dutch (Belgian) }
{$EXTERNALSYM SUBLANG_DUTCH_BELGIAN}
SUBLANG_ENGLISH_US = $01; { English (USA) }
{$EXTERNALSYM SUBLANG_ENGLISH_US}
SUBLANG_ENGLISH_UK = $02; { English (UK) }
{$EXTERNALSYM SUBLANG_ENGLISH_UK}
SUBLANG_ENGLISH_AUS = $03; { English (Australian) }
{$EXTERNALSYM SUBLANG_ENGLISH_AUS}
SUBLANG_ENGLISH_CAN = $04; { English (Canadian) }
{$EXTERNALSYM SUBLANG_ENGLISH_CAN}
SUBLANG_ENGLISH_NZ = $05; { English (New Zealand) }
{$EXTERNALSYM SUBLANG_ENGLISH_NZ}
SUBLANG_ENGLISH_EIRE = $06; { English (Irish) }
{$EXTERNALSYM SUBLANG_ENGLISH_EIRE}
SUBLANG_ENGLISH_SOUTH_AFRICA = $07; { English (South Africa) }
{$EXTERNALSYM SUBLANG_ENGLISH_SOUTH_AFRICA}
SUBLANG_ENGLISH_JAMAICA = $08; { English (Jamaica) }
{$EXTERNALSYM SUBLANG_ENGLISH_JAMAICA}
SUBLANG_ENGLISH_CARIBBEAN = $09; { English (Caribbean) }
{$EXTERNALSYM SUBLANG_ENGLISH_CARIBBEAN}
SUBLANG_ENGLISH_BELIZE = $0a; { English (Belize) }
{$EXTERNALSYM SUBLANG_ENGLISH_BELIZE}
SUBLANG_ENGLISH_TRINIDAD = $0b; { English (Trinidad) }
{$EXTERNALSYM SUBLANG_ENGLISH_TRINIDAD}
SUBLANG_FRENCH = $01; { French }
{$EXTERNALSYM SUBLANG_FRENCH}
SUBLANG_FRENCH_BELGIAN = $02; { French (Belgian) }
{$EXTERNALSYM SUBLANG_FRENCH_BELGIAN}
SUBLANG_FRENCH_CANADIAN = $03; { French (Canadian) }
{$EXTERNALSYM SUBLANG_FRENCH_CANADIAN}
SUBLANG_FRENCH_SWISS = $04; { French (Swiss) }
{$EXTERNALSYM SUBLANG_FRENCH_SWISS}
SUBLANG_FRENCH_LUXEMBOURG = $05; { French (Luxembourg) }
{$EXTERNALSYM SUBLANG_FRENCH_LUXEMBOURG}
SUBLANG_GERMAN = $01; { German }
{$EXTERNALSYM SUBLANG_GERMAN}
SUBLANG_GERMAN_SWISS = $02; { German (Swiss) }
{$EXTERNALSYM SUBLANG_GERMAN_SWISS}
SUBLANG_GERMAN_AUSTRIAN = $03; { German (Austrian) }
{$EXTERNALSYM SUBLANG_GERMAN_AUSTRIAN}
SUBLANG_GERMAN_LUXEMBOURG = $04; { German (Luxembourg) }
{$EXTERNALSYM SUBLANG_GERMAN_LUXEMBOURG}
SUBLANG_GERMAN_LIECHTENSTEIN = $05; { German (Liechtenstein) }
{$EXTERNALSYM SUBLANG_GERMAN_LIECHTENSTEIN}
SUBLANG_ITALIAN = $01; { Italian }
{$EXTERNALSYM SUBLANG_ITALIAN}
SUBLANG_ITALIAN_SWISS = $02; { Italian (Swiss) }
{$EXTERNALSYM SUBLANG_ITALIAN_SWISS}
SUBLANG_KOREAN = $01; { Korean (Extended Wansung) }
{$EXTERNALSYM SUBLANG_KOREAN}
SUBLANG_KOREAN_JOHAB = $02; { Korean (Johab) }
{$EXTERNALSYM SUBLANG_KOREAN_JOHAB}
SUBLANG_NORWEGIAN_BOKMAL = $01; { Norwegian (Bokmal) }
{$EXTERNALSYM SUBLANG_NORWEGIAN_BOKMAL}
SUBLANG_NORWEGIAN_NYNORSK = $02; { Norwegian (Nynorsk) }
{$EXTERNALSYM SUBLANG_NORWEGIAN_NYNORSK}
SUBLANG_PORTUGUESE = $02; { Portuguese }
{$EXTERNALSYM SUBLANG_PORTUGUESE}
SUBLANG_PORTUGUESE_BRAZILIAN = $01; { Portuguese (Brazilian) }
{$EXTERNALSYM SUBLANG_PORTUGUESE_BRAZILIAN}
SUBLANG_RUSSIAN_RUSSIA = $01; { Russia (RU) }
SUBLANG_TATAR_RUSSIA = $01; { }
SUBLANG_SERBIAN_LATIN = $02; { Serbian (Latin) }
{$EXTERNALSYM SUBLANG_SERBIAN_LATIN}
SUBLANG_SERBIAN_CYRILLIC = $03; { Serbian (Cyrillic) }
{$EXTERNALSYM SUBLANG_SERBIAN_CYRILLIC}
SUBLANG_SPANISH = $01; { Spanish (Castilian) }
{$EXTERNALSYM SUBLANG_SPANISH}
SUBLANG_SPANISH_MEXICAN = $02; { Spanish (Mexican) }
{$EXTERNALSYM SUBLANG_SPANISH_MEXICAN}
SUBLANG_SPANISH_MODERN = $03; { Spanish (Modern) }
{$EXTERNALSYM SUBLANG_SPANISH_MODERN}
SUBLANG_SPANISH_GUATEMALA = $04; { Spanish (Guatemala) }
{$EXTERNALSYM SUBLANG_SPANISH_GUATEMALA}
SUBLANG_SPANISH_COSTA_RICA = $05; { Spanish (Costa Rica) }
{$EXTERNALSYM SUBLANG_SPANISH_COSTA_RICA}
SUBLANG_SPANISH_PANAMA = $06; { Spanish (Panama) }
{$EXTERNALSYM SUBLANG_SPANISH_PANAMA}
SUBLANG_SPANISH_DOMINICAN_REPUBLIC = $07; { Spanish (Dominican Republic) }
{$EXTERNALSYM SUBLANG_SPANISH_DOMINICAN_REPUBLIC}
SUBLANG_SPANISH_VENEZUELA = $08; { Spanish (Venezuela) }
{$EXTERNALSYM SUBLANG_SPANISH_VENEZUELA}
SUBLANG_SPANISH_COLOMBIA = $09; { Spanish (Colombia) }
{$EXTERNALSYM SUBLANG_SPANISH_COLOMBIA}
SUBLANG_SPANISH_PERU = $0a; { Spanish (Peru) }
{$EXTERNALSYM SUBLANG_SPANISH_PERU}
SUBLANG_SPANISH_ARGENTINA = $0b; { Spanish (Argentina) }
{$EXTERNALSYM SUBLANG_SPANISH_ARGENTINA}
SUBLANG_SPANISH_ECUADOR = $0c; { Spanish (Ecuador) }
{$EXTERNALSYM SUBLANG_SPANISH_ECUADOR}
SUBLANG_SPANISH_CHILE = $0d; { Spanish (Chile) }
{$EXTERNALSYM SUBLANG_SPANISH_CHILE}
SUBLANG_SPANISH_URUGUAY = $0e; { Spanish (Uruguay) }
{$EXTERNALSYM SUBLANG_SPANISH_URUGUAY}
SUBLANG_SPANISH_PARAGUAY = $0f; { Spanish (Paraguay) }
{$EXTERNALSYM SUBLANG_SPANISH_PARAGUAY}
SUBLANG_SPANISH_BOLIVIA = $10; { Spanish (Bolivia) }
{$EXTERNALSYM SUBLANG_SPANISH_BOLIVIA}
SUBLANG_SPANISH_EL_SALVADOR = $11; { Spanish (El Salvador) }
{$EXTERNALSYM SUBLANG_SPANISH_EL_SALVADOR}
SUBLANG_SPANISH_HONDURAS = $12; { Spanish (Honduras) }
{$EXTERNALSYM SUBLANG_SPANISH_HONDURAS}
SUBLANG_SPANISH_NICARAGUA = $13; { Spanish (Nicaragua) }
{$EXTERNALSYM SUBLANG_SPANISH_NICARAGUA}
SUBLANG_SPANISH_PUERTO_RICO = $14; { Spanish (Puerto Rico) }
{$EXTERNALSYM SUBLANG_SPANISH_PUERTO_RICO}
SUBLANG_SWEDISH = $01; { Swedish }
{$EXTERNALSYM SUBLANG_SWEDISH}
SUBLANG_SWEDISH_FINLAND = $02; { Swedish (Finland) }
{$EXTERNALSYM SUBLANG_SWEDISH_FINLAND}
(*
* A language ID is a 16 bit value which is the combination of a
* primary language ID and a secondary language ID. The bits are
* allocated as follows:
*
* +-----------------------+-------------------------+
* | Sublanguage ID | Primary Language ID |
* +-----------------------+-------------------------+
* 15 10 9 0 bit
*
* Language ID creation/extraction macros:
*
* MAKELANGID - construct language id from a primary language id and
* a sublanguage id.
* PRIMARYLANGID - extract primary language id from a language id.
* SUBLANGID - extract sublanguage id from a language id.
*
*)
function MakeLangID(p, s: WORD): WORD;
{$EXTERNALSYM MAKELANGID}
function PrimaryLangID(lgid: WORD): WORD;
{$EXTERNALSYM PRIMARYLANGID}
function SubLangID(lgid: WORD): WORD;
{$EXTERNALSYM SUBLANGID}
function l3CodePageFromLangID(aLangID: Word; aIsOEM: Boolean): Integer;
function l3ANSICodePage(aLangID: Word): Integer;
function l3OEMCodePage(aLangID: Word): Integer;
type
TLanguageObj = class(Tl3ProtoObject)
private
f_AnsiCodePage: Integer;
f_LanguageID: Integer;
f_OEMCodePage: Integer;
procedure pm_SetLanguageID(const aValue: Integer);
public
property AnsiCodePage: Integer read f_AnsiCodePage;
property LanguageID: Integer read f_LanguageID write pm_SetLanguageID;
property OEMCodePage: Integer read f_OEMCodePage;
end;
implementation
uses l3Chars, SysUtils, Math;
// #define MAKELANGID(p, s) ((((WORD )(s)) << 10) | (WORD )(p))
function MakeLangID(p, s: WORD): WORD;
begin
Result := WORD(s shl 10) or p;
end;
// #define PRIMARYLANGID(lgid) ((WORD )(lgid) & 0x3ff)
function PrimaryLangID(lgid: WORD): WORD;
begin
Result := WORD(lgid and $3FF);
end;
// #define SUBLANGID(lgid) ((WORD )(lgid) >> 10)
function SubLangID(lgid: WORD): WORD;
begin
Result := lgid shr 10;
end;
function l3CodePageFromLangID(aLangID: Word; aIsOEM: Boolean): Integer;
var
l_Lang, l_SubLang: Word;
begin
Assert(aLangID > 0, 'function l3CodePageFromLangID: aLangID = 0');
l_Lang := PrimaryLangID(aLangID);
l_SubLang := SubLangID(aLangID);
case l_Lang of
LANG_RUSSIAN : Result := IfThen(aIsOEM, CP_OEMLite, CP_RussianWin);
LANG_TATAR : Result := IfThen(aIsOEM, CP_TatarOEM, CP_Tatar);
else
Assert(false, format('function l3CodePageFromLangID: Codepage not defined for LangID=',[aLangID]));
//Result := CP_KeepExisting;
end;
end;
function l3ANSICodePage(aLangID: Word): Integer;
begin
Result:= l3CodePageFromLangID(aLangID, false);
end;
function l3OEMCodePage(aLangID: Word): Integer;
begin
Result:= l3CodePageFromLangID(aLangID, true);
end;
procedure TLanguageObj.pm_SetLanguageID(const aValue: Integer);
begin
f_LanguageID := IfThen(aValue <= 0, MakeLangID(LANG_RUSSIAN, SUBLANG_RUSSIAN_RUSSIA), aValue);
f_AnsiCodePage:= l3AnsiCodePage(f_LanguageID);
f_OEMCodePage:= l3OEMCodePage(f_LanguageID);
end;
(*
*)
end.
|
{*******************************************************}
{ }
{ SoftName }
{ }
{ Copyright (C) 2014 }
{ }
{ This unit describe tcp socket client }
{ }
{*******************************************************}
unit fmxSocket;
interface
uses
System.sysutils, idTcpClient, fmx.dialogs,
FmxJabberTools,fmxReceiveThread;
type
TJabberSocket = Class
private
fIdSocket : TIdTCPClient; // TCP Client
fReceiveThread : TfmxReceiveThread; //thread receiving tcp responses
fOnReceivedData : TOnResponseWithStrData; // event fired once a jabber response is received
function GetConnectedStatus : Boolean;
public
constructor Create;
Destructor Destroy;Override;
procedure Initialize(AServer : string; APort : Integer); //Initialize TCP client
procedure UnInitialize; // finalize Tcp client
procedure SendRequest(ARequest : String); // send jabber request
property Connected : Boolean read GetConnectedStatus;
property OnDataReceived : TOnResponseWithStrData read fOnReceivedData write fOnReceivedData;
End;
implementation
{ TJabberSocket }
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.Create : constructor
Arguments: None
Result: None
-------------------------------------------------------------------------------}
constructor TJabberSocket.Create;
begin
try
fIdSocket := TIdTCPClient.Create(nil); // Create indy tcp client
except
On E:Exception do
Raise Exception.create('[TJabberSocket.Create] : '+E.message);
end;
end;
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.Destroy
Arguments: None
Result: None
-------------------------------------------------------------------------------}
destructor TJabberSocket.Destroy;
begin
try
if assigned(fReceiveThread) then
begin
fReceiveThread.Terminate; // Terminate thread
Sleep(1000); // wait a second for the thread destroying (TODO : must be replaced y an event system)
end;
if Assigned(fIdSocket) then
fIdSocket.Free;
inherited;
except
On E:Exception do
Raise Exception.create('[TJabberSocket.Destroy] : '+E.message);
end;
end;
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.GetConnectedStatus
Arguments: None
Result: Boolean
-------------------------------------------------------------------------------}
function TJabberSocket.GetConnectedStatus: Boolean;
begin
try
Result := fIdSocket.Connected; // get if socket is connected
except
On E:Exception do
Raise Exception.create('[TJabberSocket.GetConnectedStatus] : '+E.message);
end;
end;
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.Initialize
Arguments: AServer: string; APort: Integer
Result: None
-------------------------------------------------------------------------------}
procedure TJabberSocket.Initialize(AServer: string; APort: Integer);
begin
try
fIdSocket.Host := AServer;
fIdSocket.Port := APort;
fIdSocket.Connect; // Connect tcp client to server
if not fIdSocket.Connected then
raise Exception.Createfmt('Cannot connect to server %s:%d',[AServer,APort]);
fReceiveThread := TfmxReceiveThread.create(fIdSocket); //Create listening thread
if assigned(fOnReceivedData) then
fReceiveThread.OnDataRecieved := fOnReceivedData; //Attach onmessagereceived event
fReceiveThread.Resume; // start thread
except
On E:Exception do
Raise Exception.create('[TJabberSocket.Initialize] : '+E.message);
end;
end;
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.SendRequest
Arguments: ARequest: String
Result: None
-------------------------------------------------------------------------------}
procedure TJabberSocket.SendRequest(ARequest: String);
begin
try
fIdSocket.IOHandler.WriteLn(ARequest); // Send message to server
except
On E:Exception do
Raise Exception.create('[TJabberSocket.SendRequest] : '+E.message);
end;
end;
{-------------------------------------------------------------------------------
Procedure: TJabberSocket.UnInitialize
Arguments: None
Result: None
-------------------------------------------------------------------------------}
procedure TJabberSocket.UnInitialize;
begin
fReceiveThread.Terminate;
fIdSocket.Disconnect;
end;
end.
|
unit avl_tree;
interface
uses SysUtils, Math;
type
Pavl_node = ^Tavl_node;
Tavl_node = record
parent, left, right : Pavl_node;
bf : integer;
prev, next : Pavl_node;
end;
{$IFDEF _LAMBDA_CALLBACK}
Tavl_cmp_func = TFunc<Pavl_node, Pavl_node, Pointer, integer>;
{$ELSE}
Tavl_cmp_func = function(a,b : Pavl_node; aux: Pointer) : integer;
{$ENDIF}
pavl_tree = ^Tavl_tree;
Tavl_tree = record
root : Pavl_node;
func: Tavl_cmp_func;
aux : Pointer;
end;
function avl_first( tree : pavl_tree):Pavl_node;
function avl_last( tree : pavl_tree):Pavl_node;
function avl_next( node : pavl_node):Pavl_node;
function avl_prev( node : pavl_node):Pavl_node;
function avl_search( tree : pavl_tree; node : pavl_node):Pavl_node;
function avl_search_greater( tree : pavl_tree; node : pavl_node):Pavl_node;
function avl_search_smaller( tree : pavl_tree; node : pavl_node):Pavl_node;
procedure avl_init( tree : pavl_tree);
function avl_insert( tree : pavl_tree; node : pavl_node):Pavl_node;
procedure avl_remove( tree : pavl_tree; node : pavl_node);
implementation
function ifthen(b: Boolean;a1,a2 : integer) : integer; inline;
begin
if b then
result := a1
else
result := a2;
end;
procedure avl_set_parent(node: Pavl_node; parent: Pavl_node); inline;
begin
node.parent := parent;
end;
procedure avl_set_bf(node: Pavl_node; abf: integer); inline;
begin
node.bf := abf;
end;
function avl_bf(node: Pavl_node) : integer; inline;
begin
result := node.bf;
end;
function _get_balance(node : pavl_node) : integer; inline;
begin
if node=nil then
result := 0
else
result := avl_bf(node);
end;
function avl_parent(node: Pavl_node) : Pavl_node; inline;
begin
result := node.parent;
end;
function _rotate_LL(parent : pavl_node; parent_bf : integer;child_bf, height_delta : Pinteger):Pavl_node;
var
p_right, c_left, c_right : integer;
child : pavl_node;
begin
child := parent.left;
c_left := ifthen(child.left<>nil,1,0);
c_right := ifthen(child.right<>nil,1,0);
if child_bf^ < 0 then
begin
c_left := c_right - ( child_bf^);
p_right := c_left + 1 + parent_bf;
if height_delta<>nil then
height_delta^ := max(c_left, max(c_right, p_right)+1) - (c_left + 1);
end
else
begin
c_right := c_left + ( child_bf^);
p_right := c_right + 1 + parent_bf;
if height_delta<>nil then
height_delta^ := max(c_left, max(c_right, p_right)+1) - (c_right + 1);
end;
child_bf^ := (max(c_right, p_right) + 1) - c_left;
parent.bf := p_right - c_right;
parent.left := child.right;
if child.right<>nil then avl_set_parent(child.right, parent);
child.right := parent;
avl_set_parent(child, avl_parent(parent));
avl_set_parent(parent, child);
Result := child;
end;
function _rotate_RR(parent : pavl_node; parent_bf : integer; child_bf, height_delta : Pinteger):Pavl_node;
var
p_left, c_left, c_right : integer;
child : pavl_node;
begin
child := parent.right;
c_left := ifthen(child.left<>nil,1,0);
c_right := ifthen(child.right<>nil,1,0);
if child_bf^ < 0 then
begin
c_left := c_right - ( child_bf^);
p_left := c_left + 1 - parent_bf;
if height_delta<>nil then
height_delta^ := max(c_right, max(c_left, p_left)+1) - (c_left + 1);
end
else
begin
c_right := c_left + ( child_bf^);
p_left := c_right + 1 - parent_bf;
if height_delta<>nil then
height_delta^ := max(c_right, max(c_left, p_left)+1) - (c_right + 1);
end;
child_bf^ := c_right - (max(c_left, p_left) + 1);
avl_set_bf(parent, c_left - p_left);
parent.right := child.left;
if child.left<>nil then avl_set_parent(child.left, parent);
child.left := parent;
avl_set_parent(child, avl_parent(parent));
avl_set_parent(parent, child);
Result := child;
end;
function _rotate_LR( parent : pavl_node; parent_bf : integer):Pavl_node;
var
child_bf,
height_delta : integer;
child,
ret : pavl_node;
begin
height_delta := 0;
child := parent.left;
if child.right<>nil then
begin
child_bf := avl_bf(child.right);
parent.left := _rotate_RR(child, avl_bf(child), @child_bf, @height_delta);
end
else
begin
child_bf := avl_bf(child);
end;
ret := _rotate_LL(parent, parent_bf-height_delta, @child_bf, nil);
avl_set_bf(ret, child_bf);
Result := ret;
end;
function _rotate_RL( parent : pavl_node; parent_bf : integer):Pavl_node;
var
child_bf,
height_delta : integer;
child,
ret : pavl_node;
begin
height_delta := 0;
child := parent.right;
if child.left<>nil then
begin
child_bf := avl_bf(child.left);
parent.right := _rotate_LL(child, avl_bf(child), @child_bf, @height_delta);
end
else
begin
child_bf := avl_bf(child);
end;
ret := _rotate_RR(parent, parent_bf+height_delta, @child_bf, nil);
avl_set_bf(ret, child_bf);
Result := ret;
end;
function _balance_tree( node : pavl_node; bf : integer):Pavl_node;
var
child_bf,
height_diff : integer;
begin
height_diff := _get_balance(node) + bf;
if node<>nil then
begin
if (height_diff < -1) and (node.left<>nil) then
begin
if _get_balance(node.left) <= 0 then
begin
child_bf := avl_bf(node.left);
node := _rotate_LL(node, height_diff, @child_bf, nil);
avl_set_bf(node, child_bf);
end
else
begin
node := _rotate_LR(node, height_diff);
end;
end
else
if (height_diff > 1) and (node.right <> nil) then
begin
if _get_balance(node.right) >= 0 then
begin
child_bf := avl_bf(node.right);
node := _rotate_RR(node, height_diff, @child_bf, nil);
avl_set_bf(node, child_bf);
end
else
begin
node := _rotate_RL(node, height_diff);
end;
end
else
begin
avl_set_bf(node, avl_bf(node) + bf);
end;
end;
Result := node;
end;
function avl_first( tree : pavl_tree):Pavl_node;
var
p, node : pavl_node;
begin
p := nil;
node := tree.root;
while node<>nil do
begin
p := node;
node := node.left;
end;
Result := p;
end;
function avl_last( tree : pavl_tree):Pavl_node;
var
p, node : pavl_node;
begin
p := nil;
node := tree.root;
while node<>nil do
begin
p := node;
node := node.right;
end;
Result := p;
end;
function avl_next( node : pavl_node):Pavl_node;
begin
if node = nil then Exit(nil);
Result := node.next;
end;
function avl_prev( node : pavl_node):Pavl_node;
begin
if node = nil then Exit(nil);
Result := node.prev;
end;
function avl_search( tree : pavl_tree; node : pavl_node):Pavl_node;
var
p : pavl_node;
cmp : integer;
begin
p := tree.root;
while p<>nil do
begin
cmp := tree.func(p, node, tree.aux);
if cmp > 0 then
begin
p := p.left;
end
else
if (cmp < 0) then
begin
p := p.right;
end
else
begin
Exit(p);
end;
end;
Result := nil;
end;
function avl_search_greater( tree : pavl_tree; node : pavl_node):Pavl_node;
var
p, pp : pavl_node;
cmp : integer;
begin
p := tree.root;
pp := nil;
while p<>nil do
begin
cmp := tree.func(p, node, tree.aux);
pp := p;
if cmp > 0 then
begin
p := p.left;
end
else
if (cmp < 0) then
begin
p := p.right;
end
else
begin
Exit(p);
end;
end;
if pp=nil then
begin
Exit(nil);
end;
cmp := tree.func(pp, node, tree.aux);
if cmp > 0 then
begin
Exit(pp);
end
else
begin
Exit(avl_next(pp));
end;
end;
function avl_search_smaller( tree : pavl_tree; node : pavl_node):Pavl_node;
var
p, pp : pavl_node;
cmp : integer;
begin
p := tree.root;
pp := nil;
while p<>nil do
begin
cmp := tree.func(p, node, tree.aux);
pp := p;
if cmp > 0 then
begin
p := p.left;
end
else
if (cmp < 0) then
begin
p := p.right;
end
else
begin
Exit(p);
end;
end;
if pp=nil then
begin
Exit(nil);
end;
cmp := tree.func(pp, node, tree.aux);
if cmp < 0 then
begin
Exit(pp);
end
else
begin
Exit(avl_prev(pp));
end;
end;
procedure avl_init( tree : pavl_tree);
begin
tree.root := nil;
tree.aux := nil;
end;
function avl_insert( tree : pavl_tree; node : pavl_node):Pavl_node;
var
node_original,
p,
cur : pavl_node;
cmp,
bf,
bf_old : integer;
begin
node_original := node;
p := nil;
cur := tree.root;
while cur<> nil do
begin
cmp := tree.func(cur, node, tree.aux);
p := cur;
if cmp > 0 then
begin
cur := cur.left;
end
else
if (cmp < 0) then
begin
cur := cur.right;
end
else
begin
Exit(cur);
end;
end;
avl_set_parent(node, p);
avl_set_bf(node, 0);
node.left := nil;
node.right := nil;
node.prev := nil;
node.next := nil;
if p<>nil then
begin
if tree.func(p, node, tree.aux) > 0 then
begin
p.left := node;
node.next := p;
node.prev := p.prev;
if p.prev<>nil then
p.prev.next := node;
p.prev := node;
end
else
begin
p.right := node;
node.prev := p;
node.next := p.next;
if p.next<>nil then
p.next.prev := node;
p.next := node;
end;
end
else
begin
tree.root := node;
end;
// recursive balancing process .. scan from leaf to root
bf := 0;
while node<>nil do
begin
p := avl_parent(node);
if p<>nil then
begin
bf_old := avl_bf(node);
if p.right = node then
begin
node := _balance_tree(node, bf);
p.right := node;
end
else
begin
node := _balance_tree(node, bf);
p.left := node;
end;
// calculate balance facter BF for parent
if (node.left = nil) and (node.right = nil) then
begin
// leaf node
if p.left = node then
bf := -1
else
bf := 1;
end
else
begin
// index ndoe
bf := 0;
if abs(bf_old) < abs(avl_bf(node)) then
begin
// if ABS of balance factor increases
// cascade to parent
if p.left = node then
bf := -1
else
bf := 1;
end;
end;
end
else
if(node = tree.root) then
begin
tree.root := _balance_tree(tree.root, bf);
break;
end;
if bf = 0 then break;
node := p;
end;
Result := node_original;
end;
procedure avl_remove( tree : pavl_tree; node : pavl_node);
var
right_subtree : Tavl_tree;
p, cur, next : pavl_node;
bf, bf_old : integer;
begin
if node = nil then exit;
p := nil;
next:=nil;
cur :=nil;
bf := 0;
if node.prev<>nil then node.prev.next := node.next;
if node.next<>nil then node.next.prev := node.prev;
right_subtree.root := node.right;
right_subtree.func := tree.func;
next := avl_first(@right_subtree);
if next <> nil then
begin
// 1. NEXT exists
if avl_parent(next) <> nil then
begin
if avl_parent(next) <> node then
begin
avl_parent(next).left := next.right;
if next.right<>nil then
avl_set_parent(next.right, avl_parent(next));
end;
end;
if avl_parent(node)<>nil then
begin
// replace NODE by NEXT
if avl_parent(node).left = node then
begin
avl_parent(node).left := next;
end
else
begin
avl_parent(node).right := next;
end;
end;
// re-link pointers
if node.right <> next then
begin
next.right := node.right;
if node.right<>nil then
avl_set_parent(node.right, next);
cur := avl_parent(next);
bf := 1;
end
else
begin
cur := next;
bf := -1;
end;
next.left := node.left;
if node.left<>nil then avl_set_parent(node.left, next);
avl_set_parent(next, avl_parent(node));
// inherit NODE's balance factor
avl_set_bf(next, avl_bf(node));
end
else
begin
// 2. NEXT == NULL (only when there's no right sub-tree)
p := avl_parent(node);
if p<>nil then
begin
if p.left = node then
begin
p.left := node.left;
bf := 1;
end
else
begin
p.right := node.left;
bf := -1;
end;
end;
if node.left<>nil then avl_set_parent(node.left, p);
cur := avl_parent(node);
end;
// reset root
if tree.root = node then
begin
tree.root := next;
if next = nil then
begin
if node.left<>nil then
tree.root := node.left;
end;
end;
// recursive balancing process .. scan from CUR to root
while cur<>nil do
begin
p := avl_parent(cur);
if p<>nil then
begin
bf_old := avl_bf(cur);
if p.right = cur then
begin
cur := _balance_tree(cur, bf);
p.right := cur;
end
else
begin
cur := _balance_tree(cur, bf);
p.left := cur;
end;
// calculate balance facter BF for parent
if (cur.left = nil) and (cur.right = nil) then
begin
// leaf node
if p.left = cur then
bf := 1
else
bf := -1;
end
else
begin
// index ndoe
bf := 0;
if abs(bf_old) > abs(avl_bf(cur)) then
begin
if p.left = cur then
bf := 1
else
bf := -1;
end;
end;
end
else
if(cur = tree.root) then
begin
tree.root := _balance_tree(tree.root, bf);
break;
end;
if bf = 0 then break;
cur := p;
end;
end;
end.
|
unit TestClientFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TClientForm = class(TForm)
Cache: TButton;
Path: TEdit;
Label1: TLabel;
Links: TEdit;
Label2: TLabel;
Address: TEdit;
Label3: TLabel;
procedure CacheClick(Sender: TObject);
procedure AddressChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ClientForm: TClientForm;
implementation
uses
CacheCommon, MSObjectCacher;
{$R *.DFM}
type
TFormCacher =
class(TCacheAgent)
class function GetPath (Obj : TObject) : string; override;
class function GetCache(Obj : TObject) : TObjectCache; override;
class function UpdateCache(Obj : TObject) : TObjectCache; override;
end;
class function TFormCacher.GetPath(Obj : TObject) : string;
begin
with TClientForm(Obj) do
result := Path.Text;
end;
class function TFormCacher.GetCache(Obj : TObject) : TObjectCache;
begin
result := TObjectCache.Create;
with TClientForm(Obj) do
begin
result.WriteString('Caption', Caption);
result.WriteInteger('Top', Top);
result.WriteInteger('Width', Width);
result.Links := Links.Text;
end;
end;
class function TFormCacher.UpdateCache(Obj : TObject) : TObjectCache;
begin
result := TObjectCache.Create;
with TClientForm(Obj) do
begin
result.WriteString('Caption', Caption);
result.WriteInteger('Top', Top);
result.WriteInteger('Width', Width);
end
end;
procedure TClientForm.CacheClick(Sender: TObject);
begin
CacheObject(Self);
end;
procedure TClientForm.AddressChange(Sender: TObject);
begin
WSURL := Address.Text;
end;
initialization
RegisterCacher('TClientForm', TFormCacher);
end.
|
{ 2020/05/11 5.01 Move tests from unit flcTests into seperate units. }
{$INCLUDE flcTCPTest.inc}
unit flcTCPTest_ClientServer;
interface
{$IFDEF TCPCLIENTSERVER_TEST}
uses
{$IFDEF OS_MSWIN}
Windows,
{$ENDIF}
SysUtils,
SyncObjs,
Classes,
flcStdTypes,
flcTCPUtils,
flcTCPConnection,
flcTCPClient,
flcTCPServer;
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST}
{ }
{ TCP ClientServer Test Object }
{ }
type
TTCPClientServerTestObj = class
Lock : TCriticalSection;
constructor Create;
destructor Destroy; override;
procedure Log(Msg: String);
procedure ClientLog(Client: TF5TCPClient; LogType: TTCPClientLogType; Msg: String; LogLevel: Integer);
procedure ServerLog(Sender: TF5TCPServer; LogType: TTCPLogType; Msg: String; LogLevel: Integer);
end;
TTCPClientServerBlockTestObj = class
FinC, FinS : Boolean;
procedure ClientExec(Client: TF5TCPClient; Connection: TTCPBlockingConnection; var CloseOnExit: Boolean);
procedure ServerExec(Sender: TTCPServerClient; Connection: TTCPBlockingConnection; var CloseOnExit: Boolean);
end;
{ }
{ Test functions }
{ }
type
TF5TCPClientArray = array of TF5TCPClient;
TTCPServerClientArray = array of TTCPServerClient;
procedure TestClientServer_ReadWrite_Blocks(
const TestClientCount: Integer;
const TestLargeBlock: Boolean;
const DebugObj : TTCPClientServerTestObj;
const C: TF5TCPClientArray;
const T: TTCPServerClientArray);
{ }
{ Test }
{ }
procedure Test;
{$ENDIF}
implementation
{$IFDEF TCPCLIENTSERVER_TEST}
uses
flcSocketLib,
flcTimers;
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST}
{$ASSERTIONS ON}
{ }
{ TCP ClientServer Test Object }
{ }
{ TTCPClientServerTestObj }
constructor TTCPClientServerTestObj.Create;
begin
inherited Create;
Lock := TCriticalSection.Create;
end;
destructor TTCPClientServerTestObj.Destroy;
begin
FreeAndNil(Lock);
inherited Destroy;
end;
{$IFDEF TCP_TEST_LOG_TO_CONSOLE}
procedure TTCPClientServerTestObj.Log(Msg: String);
var S : String;
begin
S := FormatDateTime('hh:nn:ss.zzz', Now) + ' ' + Msg;
Lock.Acquire;
try
Writeln(S);
finally
Lock.Release;
end;
end;
{$ELSE}
procedure TTCPClientServerTestObj.Log(Msg: String);
begin
end;
{$ENDIF}
procedure TTCPClientServerTestObj.ClientLog(Client: TF5TCPClient; LogType: TTCPClientLogType; Msg: String; LogLevel: Integer);
begin
Log('C[' + IntToStr(Client.Tag) + ']:' + Msg);
end;
procedure TTCPClientServerTestObj.ServerLog(Sender: TF5TCPServer; LogType: TTCPLogType; Msg: String; LogLevel: Integer);
begin
Log('S:' + Msg);
end;
{ TTCPClientServerBlockTestObj }
procedure TTCPClientServerBlockTestObj.ClientExec(Client: TF5TCPClient;Connection: TTCPBlockingConnection; var CloseOnExit: Boolean);
var
B1 : LongWord;
begin
Sleep(200);
B1 := 1234;
Connection.Write(B1, 4, 10000);
B1 := 0;
Connection.Read(B1, 4, 10000);
Assert(B1 = 22222);
FinC := True;
end;
procedure TTCPClientServerBlockTestObj.ServerExec(Sender: TTCPServerClient; Connection: TTCPBlockingConnection; var CloseOnExit: Boolean);
var
B1 : LongWord;
begin
B1 := 0;
Connection.Read(B1, 4, 10000);
Assert(B1 = 1234);
B1 := 22222;
Connection.Write(B1, 4, 10000);
FinS := True;
end;
{ }
{ Test }
{ }
procedure TestClientServer_ReadWrite_Blocks(
const TestClientCount: Integer;
const TestLargeBlock: Boolean;
const DebugObj : TTCPClientServerTestObj;
const C: TF5TCPClientArray;
const T: TTCPServerClientArray);
const
LargeBlockSize = 256 * 1024;
var
K, I, J : Integer;
F : RawByteString;
B : Byte;
begin
DebugObj.Log('--------------');
DebugObj.Log('TestClientServer_ReadWrite_Blocks:');
// read & write (small block): client to server
for K := 0 to TestClientCount - 1 do
C[K].Connection.WriteByteString('Fundamentals');
for K := 0 to TestClientCount - 1 do
begin
DebugObj.Log('{RWS:' + IntToStr(K + 1) + ':A}');
I := 0;
repeat
Inc(I);
Sleep(1);
until (T[K].Connection.ReadBufferUsed >= 12) or (I >= 5000);
DebugObj.Log('{RWS:' + IntToStr(K + 1) + ':B}');
Assert(T[K].Connection.ReadBufferUsed = 12);
F := T[K].Connection.PeekByteString(3);
Assert(F = 'Fun');
Assert(T[K].Connection.PeekByte(B));
Assert(B = Ord('F'));
F := T[K].Connection.ReadByteString(12);
Assert(F = 'Fundamentals');
DebugObj.Log('{RWS:' + IntToStr(K + 1) + ':Z}');
end;
// read & write (small block): server to client
for K := 0 to TestClientCount - 1 do
T[K].Connection.WriteByteString('123');
for K := 0 to TestClientCount - 1 do
begin
C[K].BlockingConnection.WaitForReceiveData(3, 5000);
F := C[K].Connection.ReadByteString(3);
Assert(F = '123');
end;
DebugObj.Log('{RWS:1}');
if TestLargeBlock then
begin
// read & write (large block): client to server
F := '';
for I := 1 to LargeBlockSize do
F := F + #1;
for K := 0 to TestClientCount - 1 do
C[K].Connection.WriteByteString(F);
for K := 0 to TestClientCount - 1 do
begin
J := LargeBlockSize;
repeat
I := 0;
repeat
Inc(I);
Sleep(1);
Assert(C[K].State = csReady);
Assert(T[K].State = scsReady);
until (T[K].Connection.ReadBufferUsed > 0) or (I >= 5000);
Assert(T[K].Connection.ReadBufferUsed > 0);
F := T[K].Connection.ReadByteString(T[K].Connection.ReadBufferUsed);
Assert(Length(F) > 0);
for I := 1 to Length(F) do
Assert(F[I] = #1);
Dec(J, Length(F));
until J <= 0;
Assert(J = 0);
Sleep(2);
Assert(T[K].Connection.ReadBufferUsed = 0);
end;
DebugObj.Log('{RWS:L1}');
// read & write (large block): server to client
F := '';
for I := 1 to LargeBlockSize do
F := F + #1;
for K := 0 to TestClientCount - 1 do
T[K].Connection.WriteByteString(F);
for K := 0 to TestClientCount - 1 do
begin
J := LargeBlockSize;
repeat
C[K].BlockingConnection.WaitForReceiveData(1, 5000);
Assert(C[K].State = csReady);
Assert(T[K].State = scsReady);
Assert(C[K].Connection.ReadBufferUsed > 0);
F := C[K].Connection.ReadByteString(C[K].Connection.ReadBufferUsed);
Assert(Length(F) > 0);
for I := 1 to Length(F) do
Assert(F[I] = #1);
Dec(J, Length(F));
until J <= 0;
Assert(J = 0);
Sleep(2);
Assert(C[K].Connection.ReadBufferUsed = 0);
end;
DebugObj.Log('{RWS:L2}');
end;
DebugObj.Log('--------------');
end;
procedure TestClientServer_ReadWrite(
const TestClientCount: Integer;
const TestLargeBlock: Boolean
);
procedure WaitClientConnected(const Client: TF5TCPClient);
var I : Integer;
begin
I := 0;
repeat
Inc(I);
Sleep(1);
until (I >= 8000) or
(Client.State in [csReady, csClosed]);
Assert(Client.State = csReady);
Assert(Client.Connection.State = cnsConnected);
end;
var C : TF5TCPClientArray;
S : TF5TCPServer;
T : TTCPServerClientArray;
TSC : TTCPServerClient;
I, K : Integer;
DebugObj : TTCPClientServerTestObj;
begin
DebugObj := TTCPClientServerTestObj.Create;
DebugObj.Log('--------------');
DebugObj.Log('TestClientServer_ReadWrite:');
S := TF5TCPServer.Create(nil);
SetLength(C, TestClientCount);
SetLength(T, TestClientCount);
for K := 0 to TestClientCount - 1 do
begin
C[K] := TF5TCPClient.Create(nil);
// init client
C[K].Tag := K + 1;
C[K].OnLog := DebugObj.ClientLog;
end;
try
// init server
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12545;
S.MaxClients := -1;
Assert(S.State = ssInit);
Assert(not S.Active);
// start server
S.Start;
Assert(S.Active);
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.State <> ssStarting) or (I >= 5000);
Sleep(100);
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
for K := 0 to TestClientCount - 1 do
begin
// init client
C[K].AddressFamily := cafIP4;
C[K].Host := '127.0.0.1';
C[K].Port := '12545';
Assert(C[K].State = csInit);
Assert(not C[K].Active);
// start client
C[K].WaitForStartup := True;
C[K].Start;
Assert(Assigned(C[K].Connection));
Assert(C[K].Active);
end;
for K := 0 to TestClientCount - 1 do
// wait for client to connect
WaitClientConnected(C[K]);
// wait for server connections
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.ClientCount >= TestClientCount) or (I >= 5000);
Assert(S.ClientCount = TestClientCount);
// wait for server clients
TSC := S.ClientIterateFirst;
for K := 0 to TestClientCount - 1 do
begin
T[K] := TSC;
Assert(Assigned(T[K]));
Assert(T[K].State in [scsStarting, scsNegotiating, scsReady]);
Assert(T[K].Connection.State in [cnsProxyNegotiation, cnsConnected]);
TSC.ReleaseReference;
TSC := S.ClientIterateNext(TSC);
end;
// test read/write
TestClientServer_ReadWrite_Blocks(
TestClientCount,
TestLargeBlock,
DebugObj,
C, T);
// release reference
for K := 0 to TestClientCount - 1 do
T[K].ReleaseReference;
// stop clients
for K := TestClientCount - 1 downto 0 do
begin
C[K].Stop;
Assert(C[K].State = csStopped);
end;
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.ClientCount = 0) or (I >= 5000);
Assert(S.ClientCount = 0);
// stop server
DebugObj.Log('S.Stop');
S.Stop;
Assert(not S.Active);
finally
for K := TestClientCount - 1 downto 0 do
begin
C[K].Finalise;
FreeAndNil(C[K]);
end;
DebugObj.Log('S.Finalise');
S.Finalise;
DebugObj.Log('S.Free');
FreeAndNil(S);
DebugObj.Log('S=nil');
DebugObj.Log('--------------');
DebugObj.Free;
end;
end;
procedure Test_ClientServer_StopStart(const AWaitForServerStartup: Boolean);
const
TestClientCount = 10;
TestRepeatCount = 3;
var C : array of TF5TCPClient;
S : TF5TCPServer;
I, K : Integer;
J : Integer;
DebugObj : TTCPClientServerTestObj;
begin
DebugObj := TTCPClientServerTestObj.Create;
DebugObj.Log('--------------');
DebugObj.Log('Test_ClientServer_StopStart:');
S := TF5TCPServer.Create(nil);
SetLength(C, TestClientCount);
for K := 0 to TestClientCount - 1 do
begin
C[K] := TF5TCPClient.Create(nil);
// init client
C[K].Tag := K + 1;
C[K].OnLog := DebugObj.ClientLog;
end;
try
// init server
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12645;
S.MaxClients := -1;
Assert(S.State = ssInit);
Assert(not S.Active);
// start server
S.Start(AWaitForServerStartup, 30000);
Assert(S.Active);
if not AWaitForServerStartup then
begin
I := 0;
repeat
Inc(I);
Sleep(1);
until (S.State <> ssStarting) or (I >= 5000);
end;
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
// init clients
for K := 0 to TestClientCount - 1 do
begin
C[K].AddressFamily := cafIP4;
C[K].Host := '127.0.0.1';
C[K].Port := '12645';
C[K].WaitForStartup := True;
Assert(C[K].State = csInit);
Assert(not C[K].Active);
end;
// test quickly starting and stopping clients
for J := 0 to TestRepeatCount - 1 do
begin
// start client
for K := 0 to TestClientCount - 1 do
begin
C[K].Start;
// connection must exist when Start exits
Assert(Assigned(C[K].Connection));
Assert(C[K].Active);
end;
// delay
if J > 0 then
Sleep(J - 1);
// stop clients
for K := TestClientCount - 1 downto 0 do
begin
C[K].Stop;
Assert(C[K].State = csStopped);
Assert(not Assigned(C[K].Connection));
end;
// delay
if J > 0 then
Sleep(J - 1);
// re-start client
for K := 0 to TestClientCount - 1 do
begin
C[K].Start;
// connection must exist when Start exits
Assert(Assigned(C[K].Connection));
Assert(C[K].Active);
end;
// delay
if J > 0 then
Sleep(J - 1);
// re-stop clients
for K := TestClientCount - 1 downto 0 do
begin
C[K].Stop;
Assert(C[K].State = csStopped);
Assert(not Assigned(C[K].Connection));
end;
end;
// stop server
DebugObj.Log('S.Stop');
S.Stop;
Assert(not S.Active);
finally
DebugObj.Log('Clients.Free');
for K := TestClientCount - 1 downto 0 do
begin
C[K].Finalise;
FreeAndNil(C[K]);
end;
DebugObj.Log('S.Finalise');
S.Finalise;
DebugObj.Log('S.Free');
FreeAndNil(S);
DebugObj.Log('S=nil');
DebugObj.Log('--------------');
DebugObj.Free;
end;
end;
procedure Test_ClientServer_ReadWrite;
begin
TestClientServer_ReadWrite(1, True);
TestClientServer_ReadWrite(2, True);
TestClientServer_ReadWrite(5, True);
{$IFNDEF LINUX} // FAILS
TestClientServer_ReadWrite(30, False);
{$ENDIF}
end;
procedure Test_ClientServer_Shutdown;
var
S : TF5TCPServer;
C : TF5TCPClient;
T : TTCPServerClient;
B, X : RawByteString;
I, L, N, M : Integer;
begin
S := TF5TCPServer.Create(nil);
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12213;
S.MaxClients := -1;
S.Active := True;
Sleep(100);
C := TF5TCPClient.Create(nil);
C.LocalHost := '0.0.0.0';
C.Host := '127.0.0.1';
C.Port := '12213';
C.WaitForStartup := True;
C.UseWorkerThread := False;
C.Active := True;
Sleep(100);
Assert(C.State = csReady);
SetLength(B, 1024 * 1024);
for I := 1 to Length(B) do
B[I] := #1;
L := C.Connection.WriteByteString(B);
Assert(L > 1024);
Sleep(1);
Assert(not C.IsShutdownComplete);
C.Shutdown;
for I := 1 to 10 do
begin
if C.IsShutdownComplete then
break;
Sleep(50);
end;
Assert(C.IsShutdownComplete);
T := S.ClientIterateFirst;
Assert(Assigned(T));
SetLength(X, L);
M := 0;
repeat
N := T.Connection.Read(X[1], L);
Inc(M, N);
Sleep(10);
until N <= 0;
Assert(M = L);
Sleep(100);
Assert(C.State = csClosed);
Assert(T.State = scsClosed);
T.ReleaseReference;
C.Close;
C.Finalise;
C.Free;
S.Active := False;
S.Finalise;
S.Free;
end;
procedure Test_ClientServer_Block;
var
S : TF5TCPServer;
C : TF5TCPClient;
DebugObj : TTCPClientServerTestObj;
TestObj : TTCPClientServerBlockTestObj;
begin
DebugObj := TTCPClientServerTestObj.Create;
TestObj := TTCPClientServerBlockTestObj.Create;
DebugObj.Log('--------------');
DebugObj.Log('Test_ClientServer_Block:');
S := TF5TCPServer.Create(nil);
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12145;
S.MaxClients := -1;
S.UseWorkerThread := True;
S.OnClientWorkerExecute := TestObj.ServerExec;
S.Active := True;
Sleep(50);
C := TF5TCPClient.Create(nil);
C.OnLog := DebugObj.ClientLog;
C.LocalHost := '0.0.0.0';
C.Host := '127.0.0.1';
C.Port := '12145';
C.WaitForStartup := True;
C.UseWorkerThread := True;
C.OnWorkerExecute := TestObj.ClientExec;
C.Active := True;
repeat
Sleep(1);
until TestObj.FinC and TestObj.FinS;
C.Active := False;
S.Active := False;
C.Finalise;
FreeAndNil(C);
S.Finalise;
FreeAndNil(S);
DebugObj.Log('--------------');
TestObj.Free;
DebugObj.Free;
end;
procedure Test_ClientServer_RetryConnect;
var
S : TF5TCPServer;
C : TF5TCPClient;
DebugObj : TTCPClientServerTestObj;
TestObj : TTCPClientServerBlockTestObj;
I : Integer;
begin
DebugObj := TTCPClientServerTestObj.Create;
TestObj := TTCPClientServerBlockTestObj.Create;
DebugObj.Log('--------------');
DebugObj.Log('Test_ClientServer_RetryConnect:');
S := TF5TCPServer.Create(nil);
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
S.ServerPort := 12045;
S.MaxClients := -1;
S.UseWorkerThread := True;
S.OnClientWorkerExecute := TestObj.ServerExec;
C := TF5TCPClient.Create(nil);
C.OnLog := DebugObj.ClientLog;
C.LocalHost := '0.0.0.0';
C.Host := '127.0.0.1';
C.Port := '12045';
C.WaitForStartup := True;
C.UseWorkerThread := True;
C.OnWorkerExecute := TestObj.ClientExec;
C.RetryFailedConnect := True;
C.RetryFailedConnectDelaySec := 2;
C.RetryFailedConnectMaxAttempts := 3;
C.ReconnectOnDisconnect := False;
C.Active := True;
Sleep(2000);
S.Active := True;
I := 0;
repeat
Sleep(1);
Inc(I);
until (TestObj.FinC and TestObj.FinS) or (I > 4000);
Assert(TestObj.FinC and TestObj.FinS);
//S.Active := False;
//Sleep(100000);
C.Active := False;
S.Active := False;
C.Finalise;
FreeAndNil(C);
S.Finalise;
FreeAndNil(S);
DebugObj.Log('--------------');
TestObj.Free;
DebugObj.Free;
end;
procedure Test_ClientServer_Latency;
procedure DoYield;
begin
{$IFDEF DELPHI}
{$IFDEF OS_MSWIN}
Yield;
{$ELSE}
TThread.Yield;
{$ENDIF}
{$ELSE}
TThread.Yield;
{$ENDIF}
end;
procedure WaitClientConnected(const Client: TF5TCPClient);
var I : Integer;
begin
// wait for client to connect
I := 0;
repeat
Inc(I);
Sleep(1);
until (I >= 8000) or
(Client.State in [csReady, csClosed]);
Assert(Client.State = csReady);
Assert(Client.Connection.State = cnsConnected);
end;
var C : TF5TCPClient;
S : TF5TCPServer;
TSC : TTCPServerClient;
I, Nr : Integer;
F : RawByteString;
DebugObj : TTCPClientServerTestObj;
T : Word64;
Buf : array[0..15] of Byte;
const
Test1N = 5;
begin
DebugObj := TTCPClientServerTestObj.Create;
DebugObj.Log('--------------');
DebugObj.Log('Test_ClientServer_Latency:');
S := TF5TCPServer.Create(nil);
C := TF5TCPClient.Create(nil);
// init client
C.Tag := 1;
C.OnLog := DebugObj.ClientLog;
try
// init server
S.OnLog := DebugObj.ServerLog;
S.AddressFamily := iaIP4;
S.BindAddress := '127.0.0.1';
Randomize;
S.ServerPort := 12513 + Random(1000);
S.MaxClients := -1;
Assert(S.State = ssInit);
Assert(not S.Active);
// start server
S.Start;
Assert(S.Active);
I := 0;
repeat
Inc(I);
Sleep(10);
until (S.State <> ssStarting) or (I >= 400);
Sleep(100);
Assert(S.State = ssReady);
Assert(S.ClientCount = 0);
// init client
C.AddressFamily := cafIP4;
C.Host := '127.0.0.1';
C.Port := IntToStr(S.ServerPort);
Assert(C.State = csInit);
Assert(not C.Active);
// start client
C.WaitForStartup := True;
C.Start;
Assert(Assigned(C.Connection));
Assert(C.Active);
// wait for client to connect
WaitClientConnected(C);
// wait for server connections
I := 0;
repeat
Inc(I);
Sleep(10);
until (S.ClientCount >= 1) or (I >= 10000);
Assert(S.ClientCount = 1);
// wait for server clients
TSC := S.ClientIterateFirst;
Assert(Assigned(TSC));
Assert(TSC.State in [scsStarting, scsNegotiating, scsReady]);
Assert(TSC.Connection.State in [cnsProxyNegotiation, cnsConnected]);
for Nr := 1 to Test1N do
begin
// read & write (small block): client to server
// read directly from connection before buffered
T := GetMicroTick;
C.Connection.WriteByteString('Fundamentals');
repeat
DoYield;
F := TSC.Connection.ReadByteString(12);
if F = 'Fundamentals' then
break;
until MicroTickDelta(T, GetMicroTick) >= 5000000; // 5s
T := MicroTickDelta(T, GetMicroTick);
DebugObj.Log(' Latency1_ClientToServer:' + IntToStr(T));
Assert(F = 'Fundamentals');
// read & write (small block): server to client
// read directly from connection before buffered
FillChar(Buf, SizeOf(Buf), 0);
T := GetMicroTick;
TSC.Connection.WriteByteString('123');
repeat
DoYield;
if C.Connection.Read(Buf[0], 3) = 3 then
if (Buf[0] = Ord('1')) and (Buf[1] = Ord('2')) and (Buf[2] = Ord('3')) then
break;
until MicroTickDelta(T, GetMicroTick) >= 5000000; // 5s
T := MicroTickDelta(T, GetMicroTick);
DebugObj.Log(' Latency2_ServerToClient:' + IntToStr(T));
Assert((Buf[0] = Ord('1')) and (Buf[1] = Ord('2')) and (Buf[2] = Ord('3')));
// read & write (small block): client to server
T := GetMicroTick;
C.Connection.WriteByteString('Fundamentals');
repeat
DoYield;
until (TSC.Connection.ReadBufferUsed >= 12) or (MicroTickDelta(T, GetMicroTick) >= 5000000);
T := MicroTickDelta(T, GetMicroTick);
DebugObj.Log(' Latency3_ClientToServer:' + IntToStr(T));
Assert(TSC.Connection.ReadBufferUsed = 12);
F := TSC.Connection.ReadByteString(12);
Assert(F = 'Fundamentals');
// read & write (small block): server to client
T := GetMicroTick;
TSC.Connection.WriteByteString('123');
repeat
DoYield;
until (C.Connection.ReadBufferUsed >= 3) or (MicroTickDelta(T, GetMicroTick) >= 5000000);
T := MicroTickDelta(T, GetMicroTick);
DebugObj.Log(' Latency4_ServerToClient:' + IntToStr(T));
F := C.Connection.ReadByteString(3);
Assert(F = '123');
end;
TSC.ReleaseReference;
finally
C.Free;
S.Free;
end;
DebugObj.Log('--------------');
FreeAndNil(DebugObj);
end;
procedure Test;
begin
Test_ClientServer_StopStart(False);
Test_ClientServer_StopStart(True);
Test_ClientServer_ReadWrite;
Test_ClientServer_StopStart(False);
Test_ClientServer_StopStart(True);
Test_ClientServer_Shutdown;
Test_ClientServer_Block;
Test_ClientServer_RetryConnect;
Test_ClientServer_Block;
Test_ClientServer_ReadWrite;
Test_ClientServer_Latency;
end;
{$ENDIF}
end.
|
{**************************************************}
{ }
{ WLXProc - Total Commander Lister API Wrapper }
{ Copyright (C) Alexey Torgashin }
{ http://uvviewsoft.com }
{ }
{**************************************************}
{$BOOLEVAL OFF} //Short boolean evaluation required.
{$I ATViewerOptions.inc} //ATViewer options.
unit WLXProc;
interface
uses
Windows, Messages, SysUtils, Controls,
{$ifdef WLX_FORM} Forms, {$endif}
WLXPlugin;
const
WlxPluginsMaxCount = 200;
type
TListLoad = function(ParentWin: THandle; FileToLoad: PAnsiChar; ShowFlags: Integer): THandle; stdcall;
TListLoadW = function(ParentWin: THandle; FileToLoad: PWideChar; ShowFlags: Integer): THandle; stdcall;
TListLoadNext = function(ParentWin, PluginWin: THandle; FileToLoad: PAnsiChar;
ShowFlags: Integer): Integer; stdcall;
TListCloseWindow = procedure(ListWin: THandle); stdcall;
TListSetDefaultParams = procedure(dps: pListDefaultParamStruct); stdcall;
TListGetDetectString = procedure(DetectString: PAnsiChar; maxlen: Integer); stdcall;
TListSendCommand = function(ListWin: THandle; Command, Parameter: Integer): Integer; stdcall;
TListPrint = function(ListWin: THandle; FileToPrint, DefPrinter: PAnsiChar;
PrintFlags: Integer; const {was var!} Margins: TRect): Integer; stdcall;
TListSearchText = function(ListWin: THandle; SearchString: PAnsiChar;
SearchParameter: Integer): Integer; stdcall;
TListSearchDialog = function(ListWin: THandle; FindNext: Integer): Integer; stdcall;
type
TWlxFileName = string; //No support for WideString
TWlxDetectString = string;
TWlxNameEvent = procedure(const APluginName: string) of object;
TWlxPluginRecord = record
FileName: TWlxFileName;
DetectStr: TWlxDetectString;
HLib: THandle;
HWnd: THandle;
ListLoad: TListLoad;
ListLoadW: TListLoadW;
ListLoadNext: TListLoadNext;
ListCloseWindow: TListCloseWindow;
ListSetDefaultParams: TListSetDefaultParams;
ListSendCommand: TListSendCommand;
ListPrint: TListPrint;
ListSearchText: TListSearchText;
ListSearchDialog: TListSearchDialog;
end;
TWlxPlugins = class
private
FPlugins: array[1 .. WlxPluginsMaxCount] of TWlxPluginRecord;
FCount: Word;
FActive: Word;
FActiveFileName: AnsiString;
FActivePosPercent: Word;
FActiveForceMode: Boolean;
FParent: TWinControl;
FParentWnd: HWnd;
FIniFileName: AnsiString;
{$ifdef WLX_FORM}
FTCWindow: TForm;
{$endif}
FFocused: Boolean;
FBeforeLoading: TWlxNameEvent;
FAfterLoading: TWlxNameEvent;
function IsIndexValid(N: Word): Boolean;
function Present(const AFileName: TWlxFileName): Boolean;
function Load(N: Word): Boolean;
procedure Unload(N: Word);
function OpenWnd(N: Word; const AFileName: WideString; AFlags: Integer): Boolean;
function ReopenWnd(const AFileName: WideString; AFlags: Integer): Boolean;
procedure CloseWnd(N: Word);
procedure ResizeWnd(N: Word; const ARect: TRect);
procedure SendCommandWnd(N: Word; ACmd, AParam: Integer);
procedure SetActivePosPercent(AValue: Word);
function GetName(N: Word): AnsiString;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure InitParams(AParent: TWinControl; const AIniFileName: AnsiString);
procedure InitParams2(AParentWnd: HWnd; const AIniFileName: AnsiString);
function AddPlugin(const AFileName: TWlxFileName; const ADetectStr: TWlxDetectString): Boolean;
function GetPlugin(N: Word; var AFileName: TWlxFileName; var ADetectStr: TWlxDetectString): Boolean;
procedure ShowDebugInfo;
function OpenMatched(const AFileName: WideString; AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP, ANewFile: Boolean): Boolean;
procedure CloseActive;
procedure ResizeActive(const ARect: TRect);
procedure SendCommandToActive(ACmd, AParam: Integer);
procedure SendParamsToActive(AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP: Boolean);
function SendMessageToActive(const AMessage: TMessage): LRESULT;
function PrintActive(const ARect: TRect): Boolean;
function SearchActive(const AString: AnsiString; AFindFirst, AWholeWords, ACaseSens, ABackwards: Boolean): Boolean;
function SearchDialogActive(AFindNext: Boolean): Boolean;
function GetActiveName: AnsiString;
procedure SetFocusToActive;
property ActivePosPercent: Word read FActivePosPercent write SetActivePosPercent;
function ActiveSupportsSearch: Boolean;
function ActiveSupportsPrint: Boolean;
function ActiveSupportsCommands: Boolean;
function ActiveWindowHandle: THandle;
property IsFocused: Boolean read FFocused write FFocused;
property OnBeforeLoading: TWlxNameEvent read FBeforeLoading write FBeforeLoading;
property OnAfterLoading: TWlxNameEvent read FAfterLoading write FAfterLoading;
end;
function WlxGetDetectString(const AFileName: TWlxFileName): TWlxDetectString;
implementation
uses
ATxSProc, ATxFProc, ATViewerMsg, Dialogs;
{ Not published Lister API constants }
const
cWlxFindFirst = 0;
cWlxFindNext = 1;
{ Helper fake TC window }
{$ifdef WLX_FORM}
{$R WLXProc_FormTC.dfm}
type
TTOTAL_CMD = class(TForm)
public
end;
{$endif}
{ Helper functions }
// Currently we use simplified detect-string checking:
//
// 1) If string is empty (i.e. it doesn't contain 'EXT=' part), it's matched.
// 2) If it's not empty, it's matched when corresponding 'EXT=' part is present.
// 3) 'FORCE' special word is supported now. It's expected not as file extension.
// 4) String may be "EXT:ext1,ext2,ext3 FORCE" - the extended syntax for extensions
// comma-separated list.
//
function WlxDetectMatch(const AFileName: AnsiString; const ADetectStr: TWlxDetectString; AForceMode: Boolean): Boolean;
const
cList = 'EXT:';
var
FN, Str, Ext: AnsiString;
Empty, ExtMatch, ForceMatch: Boolean;
begin
//Delete last slash from folder names:
FN := AFileName;
SDelLastSlash(FN);
Str := UpperCase(ADetectStr);
Ext := UpperCase(ExtractFileExt(FN));
Delete(Ext, 1, 1);
//Handle EXT:...
if Copy(Str, 1, Length(cList)) = cList then
begin
Delete(Str, 1, Length(cList));
ForceMatch := Pos(' FORCE', Str) > 0;
SDeleteFromStrA(Str, ' ');
ExtMatch := SFileExtensionMatch(FN, Str);
Result := ExtMatch or (AForceMode and ForceMatch);
Exit
end;
//Handle EXT="..."
Empty := Pos('EXT=', Str) = 0;
ExtMatch := Pos(Format('EXT="%s"', [Ext]), Str) > 0;
ForceMatch := Pos('FORCE', Str) > 0;
Result := Empty or ExtMatch or (AForceMode and ForceMatch);
end;
procedure MsgErrorWlx(const AFileName: TWlxFileName; const AFuncName: AnsiString);
begin
MsgError(Format(MsgViewerWlxException, [ExtractFileName(AFileName), AFuncName]));
end;
function WlxGetDetectString(const AFileName: TWlxFileName): TWlxDetectString;
const
cBufSize = 4 * 1024;
var
HLib: THandle;
Buffer: array[0 .. Pred(cBufSize)] of AnsiChar;
ListGetDetectString: TListGetDetectString;
begin
Result := '';
HLib := LoadLibraryA(PAnsiChar(AnsiString(AFileName)));
if HLib <> 0 then
begin
ListGetDetectString := GetProcAddress(HLib, 'ListGetDetectString');
if Assigned(ListGetDetectString) then
try
FillChar(Buffer, SizeOf(Buffer), 0);
ListGetDetectString(Buffer, SizeOf(Buffer));
Result := AnsiString(Buffer);
except
MsgErrorWlx(AFileName, 'ListGetDetectString');
end;
FreeLibrary(HLib);
end;
end;
procedure InitPluginRecord(var Rec: TWlxPluginRecord);
begin
with Rec do
begin
HLib := 0;
HWnd := 0;
ListLoad := nil;
ListLoadW := nil;
ListLoadNext := nil;
ListCloseWindow := nil;
ListSetDefaultParams := nil;
ListSendCommand := nil;
ListPrint := nil;
ListSearchText := nil;
ListSearchDialog := nil;
end;
end;
function ParamsToFlags(AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP, AForceMode: Boolean): Integer;
begin
Result := 0;
if AFit then
Inc(Result, lcp_fittowindow);
if AFit and AFitLargeOnly then
Inc(Result, lcp_fitlargeronly);
if ACenter then
Inc(Result, lcp_center);
if ATextWrap then
Inc(Result, lcp_wraptext);
if AAnsiCP then
Inc(Result, lcp_ansi)
else
Inc(Result, lcp_ascii);
if AForceMode then
Inc(Result, lcp_forceshow);
end;
{ Helper cracker class }
type
TWinControlCracker = class(TWinControl);
{ TWlxPlugins }
constructor TWlxPlugins.Create;
begin
inherited Create;
FillChar(FPlugins, SizeOf(FPlugins), 0);
FCount := 0;
FActive := 0;
FActiveFileName := '';
FActivePosPercent := 0;
FActiveForceMode := False;
FParent := nil;
FParentWnd := 0;
FIniFileName := '';
{$ifdef WLX_FORM}
FTCWindow := nil;
{$endif}
FFocused := False;
FBeforeLoading := nil;
FAfterLoading := nil;
end;
destructor TWlxPlugins.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TWlxPlugins.Clear;
var
i: Word;
begin
CloseActive;
for i := FCount downto 1 do
with FPlugins[i] do
begin
FileName := '';
DetectStr := '';
end;
FCount := 0;
FActive := 0;
FActiveFileName := '';
FActivePosPercent := 0;
FActiveForceMode := False;
end;
function TWlxPlugins.IsIndexValid(N: Word): Boolean;
begin
Result := (N > 0) and (N <= FCount);
end;
function TWlxPlugins.Present(const AFileName: TWlxFileName): Boolean;
var
i: Word;
begin
Result := False;
for i := 1 to FCount do
if UpperCase(AFileName) = UpperCase(FPlugins[i].FileName) then
begin Result := True; Break end;
end;
function TWlxPlugins.AddPlugin(const AFileName: TWlxFileName; const ADetectStr: TWlxDetectString): Boolean;
begin
Result := (FCount < WlxPluginsMaxCount) and (not Present(AFileName));
if Result then
begin
Inc(FCount);
with FPlugins[FCount] do
begin
FileName := AFileName;
DetectStr := ADetectStr;
SReplaceAll(DetectStr, ' = ', '='); //Some plugins give string_ with 'EXT = "extension"'
InitPluginRecord(FPlugins[FCount]);
end;
end;
end;
function TWlxPlugins.GetPlugin(N: Word; var AFileName: TWlxFileName; var ADetectStr: TWlxDetectString): Boolean;
begin
Result := IsIndexValid(N);
if Result then
begin
AFileName := FPlugins[N].FileName;
ADetectStr := FPlugins[N].DetectStr;
end
else
begin
AFileName := '';
ADetectStr := '';
end;
end;
procedure TWlxPlugins.InitParams(AParent: TWinControl; const AIniFileName: AnsiString);
begin
FParent := AParent;
FIniFileName := AIniFileName;
end;
procedure TWlxPlugins.InitParams2(AParentWnd: HWnd; const AIniFileName: AnsiString);
begin
FParentWnd := AParentWnd;
FIniFileName := AIniFileName;
end;
procedure TWlxPlugins.Unload(N: Word);
begin
if not IsIndexValid(N) then Exit;
with FPlugins[N] do
if HLib <> 0 then
begin
CloseWnd(N);
{$ifdef WLX_UNLOAD}
FreeLibrary(HLib);
InitPluginRecord(FPlugins[N]);
{$endif}
end;
{$ifdef WLX_FORM}
if Assigned(FTCWindow) then
begin
FTCWindow.Release;
FTCWindow := nil;
end;
{$endif}
end;
function TWlxPlugins.Load(N: Word): Boolean;
var
dps: TListDefaultParamStruct;
begin
Result := False;
if not IsIndexValid(N) then Exit;
{$ifdef WLX_FORM}
if not Assigned(FTCWindow) then
begin
FTCWindow := TTOTAL_CMD.Create(nil);
FTCWindow.Visible := False;
end;
{$endif}
with FPlugins[N] do
begin
if HLib <> 0 then
begin Result := True; Exit end;
Unload(N);
HLib := LoadLibraryA(PAnsiChar(AnsiString(FileName)));
if HLib = 0 then Exit;
ListLoad := GetProcAddress(HLib, 'ListLoad');
ListLoadW := GetProcAddress(HLib, 'ListLoadW');
ListLoadNext := GetProcAddress(HLib, 'ListLoadNext');
ListCloseWindow := GetProcAddress(HLib, 'ListCloseWindow');
ListSetDefaultParams := GetProcAddress(HLib, 'ListSetDefaultParams');
ListSendCommand := GetProcAddress(HLib, 'ListSendCommand');
ListPrint := GetProcAddress(HLib, 'ListPrint');
ListSearchText := GetProcAddress(HLib, 'ListSearchText');
ListSearchDialog := GetProcAddress(HLib, 'ListSearchDialog');
if Assigned(ListSetDefaultParams) then
try
FillChar(dps, SizeOf(dps), 0);
dps.Size := SizeOf(dps);
dps.PluginInterfaceVersionLow := 50;
dps.PluginInterfaceVersionHi := 1;
lstrcpyA(dps.DefaultIniName, PAnsiChar(AnsiString(FIniFileName)));
ListSetDefaultParams(@dps);
except
MsgErrorWlx(FileName, 'ListSetDefaultParams');
Exit;
end;
end;
Result := True;
end;
procedure TWlxPlugins.CloseWnd(N: Word);
begin
if IsIndexValid(N) then
with FPlugins[N] do
if HLib <> 0 then
if HWnd <> 0 then
begin
try
if Assigned(ListCloseWindow) then
ListCloseWindow(HWnd)
else
DestroyWindow(HWnd);
except
MsgErrorWlx(FileName, 'ListCloseWindow/DestroyWindow');
end;
HWnd := 0;
end;
end;
function TWlxPlugins.OpenWnd(N: Word; const AFileName: WideString; AFlags: Integer): Boolean;
begin
Result := False;
if not IsIndexValid(N) then Exit;
CloseWnd(N);
if Assigned(FBeforeLoading) then
FBeforeLoading(GetName(N));
with FPlugins[N] do
if Assigned(ListLoad) or Assigned(ListLoadW) then
try
if FParent <> nil then
FParentWnd := FParent.Handle;
if Assigned(ListLoadW) then
HWnd := ListLoadW(FParentWnd, PWideChar(WideString(AFileName)), AFlags)
else
HWnd := ListLoad(FParentWnd, PAnsiChar(AnsiString(FFileNameWideToAnsi(AFileName))), AFlags);
Result := HWnd <> 0;
if Result then
begin
FActive := N;
FActiveFileName := AFileName;
FActivePosPercent := 0;
SetParent(HWnd, FParentWnd);
if FFocused then
SetFocus(HWnd);
if FParent <> nil then
if Assigned(TWinControlCracker(FParent).OnResize) then
TWinControlCracker(FParent).OnResize(FParent);
end;
except
MsgErrorWlx(FileName, 'ListLoad');
end;
if Assigned(FAfterLoading) then
FAfterLoading(GetName(N));
end;
function TWlxPlugins.ReopenWnd(const AFileName: WideString; AFlags: Integer): Boolean;
begin
Result := False;
if IsIndexValid(FActive) then
with FPlugins[FActive] do
if Assigned(ListLoadNext) and
WlxDetectMatch(AFileName, DetectStr, False{ForceMode}) and
(ListLoadNext(FParentWnd, HWnd,
PAnsiChar(AnsiString(FFileNameWideToAnsi(AFileName))),
AFlags) = LISTPLUGIN_OK) then
begin
FActiveFileName := AFileName;
Result := True;
end;
end;
procedure TWlxPlugins.ResizeWnd(N: Word; const ARect: TRect);
begin
if IsIndexValid(N) then
with FPlugins[N] do
if (HLib <> 0) and (HWnd <> 0) then
with ARect do
MoveWindow(HWnd, Left, Top, Right - Left, Bottom - Top, True{bRepaint});
end;
procedure TWlxPlugins.SendCommandWnd(N: Word; ACmd, AParam: Integer);
begin
if IsIndexValid(N) then
with FPlugins[N] do
if (HLib <> 0) and (HWnd <> 0) then
if Assigned(ListSendCommand) then
try
ListSendCommand(HWnd, ACmd, AParam);
except
MsgErrorWlx(FileName, 'ListSendCommand');
end;
end;
procedure TWlxPlugins.ResizeActive(const ARect: TRect);
begin
ResizeWnd(FActive, ARect);
end;
procedure TWlxPlugins.CloseActive;
begin
Unload(FActive);
FActive := 0;
FActiveFileName := '';
FActivePosPercent := 0;
end;
procedure TWlxPlugins.SendCommandToActive(ACmd, AParam: Integer);
begin
SendCommandWnd(FActive, ACmd, AParam);
SetFocusToActive;
end;
procedure TWlxPlugins.SendParamsToActive(AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP: Boolean);
begin
SendCommandToActive(lc_newparams,
ParamsToFlags(AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP, FActiveForceMode));
end;
procedure TWlxPlugins.SetActivePosPercent(AValue: Word);
begin
FActivePosPercent := AValue;
if FActivePosPercent > 100 then
FActivePosPercent := 100;
end;
function TWlxPlugins.SendMessageToActive(const AMessage: TMessage): LRESULT;
begin
Result := 0;
if IsIndexValid(FActive) then
with FPlugins[FActive] do
Result := SendMessage(HWnd, AMessage.Msg, AMessage.WParam, AMessage.LParam);
end;
function TWlxPlugins.PrintActive(const ARect: TRect): Boolean;
begin
Result := True;
if IsIndexValid(FActive) and (FActiveFileName <> '') then
with FPlugins[FActive] do
if Assigned(ListPrint) then
try
Result := ListPrint(HWnd, PAnsiChar(AnsiString(FActiveFileName)), nil, 0, ARect) = LISTPLUGIN_OK;
except
MsgErrorWlx(FileName, 'ListPrint');
end;
end;
function TWlxPlugins.SearchActive(const AString: AnsiString; AFindFirst, AWholeWords, ACaseSens, ABackwards: Boolean): Boolean;
var
AFlags: Integer;
begin
Result := True;
if IsIndexValid(FActive) then
with FPlugins[FActive] do
if Assigned(ListSearchText) then
try
AFlags := 0;
if AFindFirst then Inc(AFlags, lcs_findfirst);
if AWholeWords then Inc(AFlags, lcs_wholewords);
if ACaseSens then Inc(AFlags, lcs_matchcase);
if ABackwards then Inc(AFlags, lcs_backwards);
Result := ListSearchText(HWnd, PAnsiChar(AnsiString(AString)), AFlags) = LISTPLUGIN_OK;
except
MsgErrorWlx(FileName, 'ListSearchText');
end;
end;
function TWlxPlugins.SearchDialogActive(AFindNext: Boolean): Boolean;
const
cModes: array[Boolean] of Integer = (cWlxFindFirst, cWlxFindNext);
begin
Result := False;
if IsIndexValid(FActive) then
with FPlugins[FActive] do
if Assigned(ListSearchDialog) then
try
Result := ListSearchDialog(HWnd, cModes[AFindNext]) = LISTPLUGIN_OK;
except
MsgErrorWlx(FileName, 'ListSearchDialog');
end;
end;
function TWlxPlugins.GetName(N: Word): AnsiString;
begin
Result := '';
if IsIndexValid(N) then
Result := ChangeFileExt(ExtractFileName(FPlugins[N].FileName), '');
end;
function TWlxPlugins.GetActiveName: AnsiString;
begin
Result := GetName(FActive);
end;
procedure TWlxPlugins.SetFocusToActive;
begin
if IsIndexValid(FActive) then
with FPlugins[FActive] do
if HWnd <> 0 then
if GetFocus <> HWnd then
SetFocus(HWnd);
end;
function TWlxPlugins.OpenMatched(
const AFileName: WideString;
AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP, ANewFile: Boolean): Boolean;
var
OldActive, i: Word;
AFlags: Integer;
fn: WideString;
begin
Result := False;
if FCount = 0 then Exit;
if (FParent = nil) and (FParentWnd = 0) then
begin MsgError(MsgViewerWlxParentNotSpecified); Exit end;
//Convert Unicode name to plugin-acceptable form
fn := AFileName;
if fn = '' then Exit;
//Try to load file in active plugin (TC 7 feature)
FActiveForceMode := not ANewFile;
AFlags := ParamsToFlags(AFit, AFitLargeOnly, ACenter, ATextWrap, AAnsiCP, FActiveForceMode);
if ANewFile and ReopenWnd(fn, AFlags) then
begin Result := True; Exit end;
//Calculate OldActive: plugin to start cycling from
if FActive = 0 then
OldActive := 0
else
begin
if not ANewFile then
OldActive := FActive
else
OldActive := FActive - 1;
end;
CloseActive;
//Cycling through all plugins from OldActive
i := OldActive;
repeat
Inc(i);
if i > FCount then i := 1;
if i > FCount then Break;
with FPlugins[i] do
begin
//1. Test for DetectString
if WlxDetectMatch(fn, DetectStr, FActiveForceMode) then
//2. Load
if Load(i) then
//3. Test for opening
if OpenWnd(i, fn, AFlags) then
Break
else
Unload(i);
end;
//Stop cycling at last plugin, if OldActive=0
if (i = FCount) and (OldActive = 0) then Break;
//Stop cycling at OldActive plugin
if i = OldActive then Break;
until False;
Result := IsIndexValid(FActive);
end;
procedure TWlxPlugins.ShowDebugInfo;
var
S: AnsiString;
i: Word;
begin
S := '';
for i := 1 to FCount do
with FPlugins[i] do
S := S + Format('%d: FileName: "%s", DetectString: "%s"',
[i, FileName, DetectStr]) + #13;
MsgInfo(S);
end;
function TWlxPlugins.ActiveSupportsSearch: Boolean;
begin
Result :=
IsIndexValid(FActive) and
( Assigned(FPlugins[FActive].ListSearchText) or
Assigned(FPlugins[FActive].ListSearchDialog) );
end;
function TWlxPlugins.ActiveSupportsPrint: Boolean;
begin
Result :=
IsIndexValid(FActive) and
Assigned(FPlugins[FActive].ListPrint);
end;
function TWlxPlugins.ActiveSupportsCommands: Boolean;
begin
Result :=
IsIndexValid(FActive) and
Assigned(FPlugins[FActive].ListSendCommand);
end;
function TWlxPlugins.ActiveWindowHandle: THandle;
begin
if IsIndexValid(FActive) then
Result := FPlugins[FActive].HWnd
else
Result := 0;
end;
end.
|
unit InfoXAPPRSRTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoXAPPRSRRecord = record
PCode: String[4];
PName: String[30];
PAddress: String[30];
PCityState: String[25];
PZip: String[10];
PContact: String[30];
PPhone: String[30];
PTaxID: String[12];
PExpCode: String[5];
PMisc: Boolean;
PAppraiser: Boolean;
PModCount: SmallInt;
End;
TInfoXAPPRSRClass2 = class
public
PCode: String[4];
PName: String[30];
PAddress: String[30];
PCityState: String[25];
PZip: String[10];
PContact: String[30];
PPhone: String[30];
PTaxID: String[12];
PExpCode: String[5];
PMisc: Boolean;
PAppraiser: Boolean;
PModCount: SmallInt;
End;
// function CtoRInfoXAPPRSR(AClass:TInfoXAPPRSRClass):TInfoXAPPRSRRecord;
// procedure RtoCInfoXAPPRSR(ARecord:TInfoXAPPRSRRecord;AClass:TInfoXAPPRSRClass);
TInfoXAPPRSRBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoXAPPRSRRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoXAPPRSR = (InfoXAPPRSRPrimaryKey);
TInfoXAPPRSRTable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFName: TStringField;
FDFAddress: TStringField;
FDFCityState: TStringField;
FDFZip: TStringField;
FDFContact: TStringField;
FDFPhone: TStringField;
FDFTaxID: TStringField;
FDFExpCode: TStringField;
FDFMisc: TBooleanField;
FDFAppraiser: TBooleanField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCityState(const Value: String);
function GetPCityState:String;
procedure SetPZip(const Value: String);
function GetPZip:String;
procedure SetPContact(const Value: String);
function GetPContact:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetPTaxID(const Value: String);
function GetPTaxID:String;
procedure SetPExpCode(const Value: String);
function GetPExpCode:String;
procedure SetPMisc(const Value: Boolean);
function GetPMisc:Boolean;
procedure SetPAppraiser(const Value: Boolean);
function GetPAppraiser:Boolean;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetEnumIndex(Value: TEIInfoXAPPRSR);
function GetEnumIndex: TEIInfoXAPPRSR;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoXAPPRSRRecord;
procedure StoreDataBuffer(ABuffer:TInfoXAPPRSRRecord);
property DFCode: TStringField read FDFCode;
property DFName: TStringField read FDFName;
property DFAddress: TStringField read FDFAddress;
property DFCityState: TStringField read FDFCityState;
property DFZip: TStringField read FDFZip;
property DFContact: TStringField read FDFContact;
property DFPhone: TStringField read FDFPhone;
property DFTaxID: TStringField read FDFTaxID;
property DFExpCode: TStringField read FDFExpCode;
property DFMisc: TBooleanField read FDFMisc;
property DFAppraiser: TBooleanField read FDFAppraiser;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PName: String read GetPName write SetPName;
property PAddress: String read GetPAddress write SetPAddress;
property PCityState: String read GetPCityState write SetPCityState;
property PZip: String read GetPZip write SetPZip;
property PContact: String read GetPContact write SetPContact;
property PPhone: String read GetPPhone write SetPPhone;
property PTaxID: String read GetPTaxID write SetPTaxID;
property PExpCode: String read GetPExpCode write SetPExpCode;
property PMisc: Boolean read GetPMisc write SetPMisc;
property PAppraiser: Boolean read GetPAppraiser write SetPAppraiser;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEIInfoXAPPRSR read GetEnumIndex write SetEnumIndex;
end; { TInfoXAPPRSRTable }
TInfoXAPPRSRQuery = class( TDBISAMQueryAU )
private
FDFCode: TStringField;
FDFName: TStringField;
FDFAddress: TStringField;
FDFCityState: TStringField;
FDFZip: TStringField;
FDFContact: TStringField;
FDFPhone: TStringField;
FDFTaxID: TStringField;
FDFExpCode: TStringField;
FDFMisc: TBooleanField;
FDFAppraiser: TBooleanField;
FDFModCount: TSmallIntField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCityState(const Value: String);
function GetPCityState:String;
procedure SetPZip(const Value: String);
function GetPZip:String;
procedure SetPContact(const Value: String);
function GetPContact:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetPTaxID(const Value: String);
function GetPTaxID:String;
procedure SetPExpCode(const Value: String);
function GetPExpCode:String;
procedure SetPMisc(const Value: Boolean);
function GetPMisc:Boolean;
procedure SetPAppraiser(const Value: Boolean);
function GetPAppraiser:Boolean;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoXAPPRSRRecord;
procedure StoreDataBuffer(ABuffer:TInfoXAPPRSRRecord);
property DFCode: TStringField read FDFCode;
property DFName: TStringField read FDFName;
property DFAddress: TStringField read FDFAddress;
property DFCityState: TStringField read FDFCityState;
property DFZip: TStringField read FDFZip;
property DFContact: TStringField read FDFContact;
property DFPhone: TStringField read FDFPhone;
property DFTaxID: TStringField read FDFTaxID;
property DFExpCode: TStringField read FDFExpCode;
property DFMisc: TBooleanField read FDFMisc;
property DFAppraiser: TBooleanField read FDFAppraiser;
property DFModCount: TSmallIntField read FDFModCount;
property PCode: String read GetPCode write SetPCode;
property PName: String read GetPName write SetPName;
property PAddress: String read GetPAddress write SetPAddress;
property PCityState: String read GetPCityState write SetPCityState;
property PZip: String read GetPZip write SetPZip;
property PContact: String read GetPContact write SetPContact;
property PPhone: String read GetPPhone write SetPPhone;
property PTaxID: String read GetPTaxID write SetPTaxID;
property PExpCode: String read GetPExpCode write SetPExpCode;
property PMisc: Boolean read GetPMisc write SetPMisc;
property PAppraiser: Boolean read GetPAppraiser write SetPAppraiser;
property PModCount: SmallInt read GetPModCount write SetPModCount;
published
property Active write SetActive;
end; { TInfoXAPPRSRTable }
procedure Register;
implementation
procedure TInfoXAPPRSRTable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCityState := CreateField( 'CityState' ) as TStringField;
FDFZip := CreateField( 'Zip' ) as TStringField;
FDFContact := CreateField( 'Contact' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
FDFTaxID := CreateField( 'TaxID' ) as TStringField;
FDFExpCode := CreateField( 'ExpCode' ) as TStringField;
FDFMisc := CreateField( 'Misc' ) as TBooleanField;
FDFAppraiser := CreateField( 'Appraiser' ) as TBooleanField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXAPPRSRTable.CreateFields }
procedure TInfoXAPPRSRTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXAPPRSRTable.SetActive }
procedure TInfoXAPPRSRTable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXAPPRSRTable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXAPPRSRTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXAPPRSRTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXAPPRSRTable.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoXAPPRSRTable.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoXAPPRSRTable.SetPCityState(const Value: String);
begin
DFCityState.Value := Value;
end;
function TInfoXAPPRSRTable.GetPCityState:String;
begin
result := DFCityState.Value;
end;
procedure TInfoXAPPRSRTable.SetPZip(const Value: String);
begin
DFZip.Value := Value;
end;
function TInfoXAPPRSRTable.GetPZip:String;
begin
result := DFZip.Value;
end;
procedure TInfoXAPPRSRTable.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoXAPPRSRTable.GetPContact:String;
begin
result := DFContact.Value;
end;
procedure TInfoXAPPRSRTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoXAPPRSRTable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoXAPPRSRTable.SetPTaxID(const Value: String);
begin
DFTaxID.Value := Value;
end;
function TInfoXAPPRSRTable.GetPTaxID:String;
begin
result := DFTaxID.Value;
end;
procedure TInfoXAPPRSRTable.SetPExpCode(const Value: String);
begin
DFExpCode.Value := Value;
end;
function TInfoXAPPRSRTable.GetPExpCode:String;
begin
result := DFExpCode.Value;
end;
procedure TInfoXAPPRSRTable.SetPMisc(const Value: Boolean);
begin
DFMisc.Value := Value;
end;
function TInfoXAPPRSRTable.GetPMisc:Boolean;
begin
result := DFMisc.Value;
end;
procedure TInfoXAPPRSRTable.SetPAppraiser(const Value: Boolean);
begin
DFAppraiser.Value := Value;
end;
function TInfoXAPPRSRTable.GetPAppraiser:Boolean;
begin
result := DFAppraiser.Value;
end;
procedure TInfoXAPPRSRTable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXAPPRSRTable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoXAPPRSRTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 4, N');
Add('Name, String, 30, N');
Add('Address, String, 30, N');
Add('CityState, String, 25, N');
Add('Zip, String, 10, N');
Add('Contact, String, 30, N');
Add('Phone, String, 30, N');
Add('TaxID, String, 12, N');
Add('ExpCode, String, 5, N');
Add('Misc, Boolean, 0, N');
Add('Appraiser, Boolean, 0, N');
Add('ModCount, SmallInt, 0, N');
end;
end;
procedure TInfoXAPPRSRTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoXAPPRSRTable.SetEnumIndex(Value: TEIInfoXAPPRSR);
begin
case Value of
InfoXAPPRSRPrimaryKey : IndexName := '';
end;
end;
function TInfoXAPPRSRTable.GetDataBuffer:TInfoXAPPRSRRecord;
var buf: TInfoXAPPRSRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PName := DFName.Value;
buf.PAddress := DFAddress.Value;
buf.PCityState := DFCityState.Value;
buf.PZip := DFZip.Value;
buf.PContact := DFContact.Value;
buf.PPhone := DFPhone.Value;
buf.PTaxID := DFTaxID.Value;
buf.PExpCode := DFExpCode.Value;
buf.PMisc := DFMisc.Value;
buf.PAppraiser := DFAppraiser.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXAPPRSRTable.StoreDataBuffer(ABuffer:TInfoXAPPRSRRecord);
begin
DFCode.Value := ABuffer.PCode;
DFName.Value := ABuffer.PName;
DFAddress.Value := ABuffer.PAddress;
DFCityState.Value := ABuffer.PCityState;
DFZip.Value := ABuffer.PZip;
DFContact.Value := ABuffer.PContact;
DFPhone.Value := ABuffer.PPhone;
DFTaxID.Value := ABuffer.PTaxID;
DFExpCode.Value := ABuffer.PExpCode;
DFMisc.Value := ABuffer.PMisc;
DFAppraiser.Value := ABuffer.PAppraiser;
DFModCount.Value := ABuffer.PModCount;
end;
function TInfoXAPPRSRTable.GetEnumIndex: TEIInfoXAPPRSR;
var iname : string;
begin
result := InfoXAPPRSRPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoXAPPRSRPrimaryKey;
end;
procedure TInfoXAPPRSRQuery.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCityState := CreateField( 'CityState' ) as TStringField;
FDFZip := CreateField( 'Zip' ) as TStringField;
FDFContact := CreateField( 'Contact' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
FDFTaxID := CreateField( 'TaxID' ) as TStringField;
FDFExpCode := CreateField( 'ExpCode' ) as TStringField;
FDFMisc := CreateField( 'Misc' ) as TBooleanField;
FDFAppraiser := CreateField( 'Appraiser' ) as TBooleanField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
end; { TInfoXAPPRSRQuery.CreateFields }
procedure TInfoXAPPRSRQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoXAPPRSRQuery.SetActive }
procedure TInfoXAPPRSRQuery.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoXAPPRSRQuery.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoXAPPRSRQuery.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoXAPPRSRQuery.SetPCityState(const Value: String);
begin
DFCityState.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPCityState:String;
begin
result := DFCityState.Value;
end;
procedure TInfoXAPPRSRQuery.SetPZip(const Value: String);
begin
DFZip.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPZip:String;
begin
result := DFZip.Value;
end;
procedure TInfoXAPPRSRQuery.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPContact:String;
begin
result := DFContact.Value;
end;
procedure TInfoXAPPRSRQuery.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoXAPPRSRQuery.SetPTaxID(const Value: String);
begin
DFTaxID.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPTaxID:String;
begin
result := DFTaxID.Value;
end;
procedure TInfoXAPPRSRQuery.SetPExpCode(const Value: String);
begin
DFExpCode.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPExpCode:String;
begin
result := DFExpCode.Value;
end;
procedure TInfoXAPPRSRQuery.SetPMisc(const Value: Boolean);
begin
DFMisc.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPMisc:Boolean;
begin
result := DFMisc.Value;
end;
procedure TInfoXAPPRSRQuery.SetPAppraiser(const Value: Boolean);
begin
DFAppraiser.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPAppraiser:Boolean;
begin
result := DFAppraiser.Value;
end;
procedure TInfoXAPPRSRQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoXAPPRSRQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
function TInfoXAPPRSRQuery.GetDataBuffer:TInfoXAPPRSRRecord;
var buf: TInfoXAPPRSRRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PName := DFName.Value;
buf.PAddress := DFAddress.Value;
buf.PCityState := DFCityState.Value;
buf.PZip := DFZip.Value;
buf.PContact := DFContact.Value;
buf.PPhone := DFPhone.Value;
buf.PTaxID := DFTaxID.Value;
buf.PExpCode := DFExpCode.Value;
buf.PMisc := DFMisc.Value;
buf.PAppraiser := DFAppraiser.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TInfoXAPPRSRQuery.StoreDataBuffer(ABuffer:TInfoXAPPRSRRecord);
begin
DFCode.Value := ABuffer.PCode;
DFName.Value := ABuffer.PName;
DFAddress.Value := ABuffer.PAddress;
DFCityState.Value := ABuffer.PCityState;
DFZip.Value := ABuffer.PZip;
DFContact.Value := ABuffer.PContact;
DFPhone.Value := ABuffer.PPhone;
DFTaxID.Value := ABuffer.PTaxID;
DFExpCode.Value := ABuffer.PExpCode;
DFMisc.Value := ABuffer.PMisc;
DFAppraiser.Value := ABuffer.PAppraiser;
DFModCount.Value := ABuffer.PModCount;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoXAPPRSRTable, TInfoXAPPRSRQuery, TInfoXAPPRSRBuffer ] );
end; { Register }
function TInfoXAPPRSRBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..12] of string = ('CODE','NAME','ADDRESS','CITYSTATE','ZIP','CONTACT'
,'PHONE','TAXID','EXPCODE','MISC','APPRAISER'
,'MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 12) and (flist[x] <> s) do inc(x);
if x <= 12 then result := x else result := 0;
end;
function TInfoXAPPRSRBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftBoolean;
11 : result := ftBoolean;
12 : result := ftSmallInt;
end;
end;
function TInfoXAPPRSRBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PName;
3 : result := @Data.PAddress;
4 : result := @Data.PCityState;
5 : result := @Data.PZip;
6 : result := @Data.PContact;
7 : result := @Data.PPhone;
8 : result := @Data.PTaxID;
9 : result := @Data.PExpCode;
10 : result := @Data.PMisc;
11 : result := @Data.PAppraiser;
12 : result := @Data.PModCount;
end;
end;
end.
|
unit uIndexMenu;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function IndexMenu(const aPath: string): longint;
function LoadMenuFromLines(Const aLines: TStringList; const aPath: string): longint;
implementation
uses
uAppContext, FileUtil, uIndexCmd, uMenuItem, uTools, process, StreamIO, strutils;
function IndexMenu(const aPath: string): longint;
var
sl: TStringList;
begin
Result := 0;
sl := TStringList.Create;
try
sl.LoadFromFile(aPath);
Result := LoadMenuFromLines(sl, aPath);
finally
FreeAndNil(sl);
end;
end;
function LoadMenuFromLines(Const aLines: TStringList; const aPath: string): longint;
var
lLine, lName: string;
i: integer;
lMenuItemParser: TMenuItemParser;
begin
Result := 0;
// insert into menu
for i := 0 to aLines.Count - 1 do
begin
lLine := Trim(aLines[i]);
lLine := DelSpace1(lLine);
if (lLine <> '') and not AnsiStartsStr('#', lLine) then
begin
lMenuItemParser := TMenuItemParser.Create(lLine);
try
if (lMenuItemParser.itemType in [MITprog, MITrunonce]) and (lMenuItemParser.cmd <> '') then
begin
if lMenuItemParser.Name <> '' then
lName := lMenuItemParser.Name
else
lName := lMenuItemParser.cmd;
insertCmd('#' + aPath + '#/' + lMenuItemParser.cmd, lName, lMenuItemParser.cmd, false, '', lMenuItemParser.icon);
Inc(Result);
End;
finally
FreeAndNil(lMenuItemParser);
end;
end;
end;
end;
end.
|
unit uGSMainMenu;
interface
uses
glr_core,
glr_scene,
glr_gui,
glr_gamescreens,
glr_utils,
glr_tween;
type
{ TglrMainMenu }
TglrMainMenu = class (TglrGameScreen)
protected
Container: TglrNode;
GameName, AuthorName: TglrGuiLabel;
NewGameBtn, SettingsBtn, ExitBtn: TglrGuiButton;
GuiManager: TglrGuiManager;
ActionManager: TglrActionManager;
procedure ButtonInit(var Button: TglrGuiButton);
procedure ButtonTween(aObject: TglrTweenObject; aValue: Single);
procedure ButtonClicked(Sender: TglrGuiElement; Event: PglrInputEvent);
procedure DoExit();
procedure ToSettings();
public
constructor Create(ScreenName: UnicodeString); override;
destructor Destroy; override;
procedure OnInput(Event: PglrInputEvent); override;
procedure OnRender; override;
procedure OnUpdate (const DeltaTime: Double); override;
procedure OnLoadStarted(); override;
procedure OnUnloadStarted(); override;
end;
implementation
uses
uAssets,
uGame,
glr_render,
glr_math;
{ TglrMainMenu }
procedure TglrMainMenu.ButtonInit(var Button: TglrGuiButton);
begin
Button := TglrGuiButton.Create();
with Button do
begin
SetVerticesColor(Colors.MenuButton);
NormalTextureRegion := Assets.GuiAtlas.GetRegion(R_GUI_ATLAS_BUTTON);
OverTextureRegion := Assets.GuiAtlas.GetRegion(R_GUI_ATLAS_BUTTON_OVER);
TextLabel.Text := 'Button';
TextLabel.Position := Vec3f(-115, -15, 0);
TextLabel.Color := Colors.MenuButtonText;
Position := Vec3f(Render.Width div 2, 240, 1);
OnClick := ButtonClicked;
Parent := Container;
end;
end;
procedure TglrMainMenu.ButtonTween(aObject: TglrTweenObject; aValue: Single);
var
v: TglrVec3f;
begin
v := Vec3f(1,1,1);
(aObject as TglrGuiButton).SetVerticesColor(Vec4f(v.Lerp(Vec3f(Colors.MenuButton), aValue), 1.0));
end;
procedure TglrMainMenu.ButtonClicked(Sender: TglrGuiElement;
Event: PglrInputEvent);
begin
Game.Tweener.AddTweenSingle(Sender, ButtonTween, tsExpoEaseIn, 0.0, 1.0, 2.0, 0.1);
if (Sender = SettingsBtn) then
ActionManager.AddIndependent(ToSettings, 0.2)
else if (Sender = ExitBtn) then
ActionManager.AddIndependent(DoExit, 0.2)
else if (Sender = NewGameBtn) then
begin
end;
end;
procedure TglrMainMenu.DoExit;
begin
Core.Quit();
end;
procedure TglrMainMenu.ToSettings;
begin
Game.GameScreenManager.SwitchTo('SettingsMenu');
end;
procedure TglrMainMenu.OnInput(Event: PglrInputEvent);
begin
GuiManager.ProcessInput(Event, Assets.GuiCamera);
end;
procedure TglrMainMenu.OnRender;
begin
Assets.GuiCamera.Update();
GuiManager.Render();
end;
procedure TglrMainMenu.OnUpdate(const DeltaTime: Double);
begin
GuiManager.Update(DeltaTime);
ActionManager.Update(DeltaTime);
end;
procedure TglrMainMenu.OnLoadStarted;
begin
Render.SetClearColor(Colors.MenuBackground);
Game.Tweener.AddTweenPSingle(@Container.Position.y, tsExpoEaseIn, -Render.Height, 0, 1.5);
inherited OnLoadStarted;
end;
procedure TglrMainMenu.OnUnloadStarted;
begin
Game.Tweener.AddTweenPSingle(@Container.Position.y, tsExpoEaseIn, 0, -Render.Height, 1.5);
ActionManager.AddIndependent(UnloadCompleted, 0.5);
end;
constructor TglrMainMenu.Create(ScreenName: UnicodeString);
begin
inherited Create(ScreenName);
ActionManager := TglrActionManager.Create();
Container := TglrNode.Create();
ButtonInit(NewGameBtn);
ButtonInit(SettingsBtn);
ButtonInit(ExitBtn);
NewGameBtn.TextLabel.Text := Texts.MenuNewGame;
SettingsBtn.TextLabel.Text := Texts.MenuSettings;
ExitBtn.TextLabel.Text := Texts.MenuExit;
SettingsBtn.Position += Vec3f(0, 70, 0);
ExitBtn.Position += Vec3f(0, 140, 0);
GameName := TglrGuiLabel.Create();
GameName.Position := Vec3f(Render.Width div 2, 70, 5);
GameName.TextLabel.Text := Texts.MenuTitle;
GameName.TextLabel.Scale := 1.2;
GameName.TextLabel.PivotPoint := Vec2f(0.5, 0.0);
GameName.TextLabel.ShadowEnabled := True;
GameName.TextLabel.ShadowOffset := Vec2f(2,2);
GameName.TextLabel.Color := Colors.MenuText;
GameName.Parent := Container;
AuthorName := TglrGuiLabel.Create();
AuthorName.Position := Vec3f(Render.Width div 2, Render.Height - 50, 5);
AuthorName.TextLabel.Text := Texts.MenuAuthorName;
AuthorName.TextLabel.Scale := 0.7;
AuthorName.TextLabel.PivotPoint := Vec2f(0.5, 0.5);
AuthorName.TextLabel.ShadowEnabled := True;
AuthorName.TextLabel.ShadowOffset := Vec2f(3,3);
AuthorName.TextLabel.Color := Colors.MenuText;
AuthorName.Parent := Container;
GuiManager := TglrGuiManager.Create(Assets.GuiMaterial, Assets.FontMain);
GuiManager.Add(NewGameBtn);
GuiManager.Add(SettingsBtn);
GuiManager.Add(ExitBtn);
GuiManager.Add(GameName);
GuiManager.Add(AuthorName);
end;
destructor TglrMainMenu.Destroy();
begin
Container.Free();
ActionManager.Free();
GuiManager.Free(True);
inherited;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerBitString;
{$I ..\Include\CryptoLib.inc}
interface
uses
SysUtils,
Classes,
Math,
ClpBits,
ClpArrayUtils,
ClpDerStringBase,
ClpAsn1Tags,
ClpBigInteger,
ClpAsn1Object,
ClpDerOutputStream,
ClpIProxiedInterface,
ClpCryptoLibTypes,
ClpIAsn1TaggedObject,
ClpIAsn1OctetString,
ClpIDerBitString;
resourcestring
SIllegalObject = 'Illegal Object in GetInstance: %s';
SEncodingError = 'Encoding Error in GetInstance: %s "obj"';
SDataNil = '"data"';
SInvalidRange = 'Must be in the Range 0 to 7", "padBits"';
SPadBitError = 'If ''data'' is Empty, ''padBits'' Must be 0';
SUnalignedData = 'Attempt to Get non-octet Aligned Data from BIT STRING"';
STruncatedBitString = 'Truncated BIT STRING Detected", "octets"';
type
/// <summary>
/// Der Bit string object.
/// </summary>
TDerBitString = class(TDerStringBase, IDerBitString)
strict private
const
FTable: array [0 .. 15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
strict protected
var
FmData: TCryptoLibByteArray;
FmPadBits: Int32;
function GetmPadBits: Int32; inline;
function GetmData: TCryptoLibByteArray; inline;
function Asn1GetHashCode(): Int32; override;
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
property mPadBits: Int32 read GetmPadBits;
property mData: TCryptoLibByteArray read GetmData;
public
constructor Create(const data: TCryptoLibByteArray;
padBits: Int32); overload;
constructor Create(const data: TCryptoLibByteArray); overload;
constructor Create(namedBits: Int32); overload;
constructor Create(const obj: IAsn1Encodable); overload;
function GetString(): String; override;
function GetOctets(): TCryptoLibByteArray; virtual;
function GetBytes(): TCryptoLibByteArray; virtual;
procedure Encode(const derOut: TStream); override;
function GetInt32Value: Int32; virtual;
property Int32Value: Int32 read GetInt32Value;
/// <summary>
/// return a Der Bit string from the passed in object
/// </summary>
/// <param name="obj">
/// a Bit string or an object that can be converted into one.
/// </param>
/// <returns>
/// return a Der Bit string instance, or null.
/// </returns>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TObject): IDerBitString; overload;
static; inline;
class function GetInstance(const obj: TCryptoLibByteArray): IDerBitString;
overload; static;
/// <summary>
/// return a Der Bit string from a tagged object.
/// </summary>
/// <param name="obj">
/// the tagged object holding the object we want
/// </param>
/// <param name="isExplicit">
/// true if the object is meant to be explicitly tagged false otherwise.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the tagged object cannot be converted.
/// </exception>
class function GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerBitString; overload; static; inline;
class function FromAsn1Octets(const octets: TCryptoLibByteArray)
: IDerBitString; static;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpBerBitString;
{ TDerBitString }
class function TDerBitString.GetInstance(const obj: TCryptoLibByteArray)
: IDerBitString;
begin
try
result := FromByteArray(obj) as IDerBitString;
except
on e: Exception do
begin
raise EArgumentCryptoLibException.CreateResFmt(@SEncodingError,
[e.Message]);
end;
end;
end;
function TDerBitString.GetmData: TCryptoLibByteArray;
begin
result := FmData;
end;
function TDerBitString.GetmPadBits: Int32;
begin
result := FmPadBits;
end;
function TDerBitString.GetOctets: TCryptoLibByteArray;
begin
if (mPadBits <> 0) then
begin
raise EInvalidOperationCryptoLibException.CreateRes(@SUnalignedData);
end;
result := System.Copy(mData);
end;
function TDerBitString.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IDerBitString;
begin
if (not Supports(asn1Object, IDerBitString, other)) then
begin
result := false;
Exit;
end;
result := (mPadBits = other.mPadBits) and
(TArrayUtils.AreEqual(mData, other.mData));
end;
constructor TDerBitString.Create(const data: TCryptoLibByteArray;
padBits: Int32);
begin
Inherited Create();
if (data = Nil) then
begin
raise EArgumentNilCryptoLibException.CreateRes(@SDataNil);
end;
if ((padBits < 0) or (padBits > 7)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidRange);
end;
if ((System.Length(data) = 0) and (padBits <> 0)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SPadBitError);
end;
FmData := System.Copy(data);
FmPadBits := padBits;
end;
constructor TDerBitString.Create(const data: TCryptoLibByteArray);
begin
Create(data, 0);
end;
constructor TDerBitString.Create(namedBits: Int32);
var
bits, bytes, i, padBits: Int32;
data: TCryptoLibByteArray;
begin
Inherited Create();
if (namedBits = 0) then
begin
System.SetLength(FmData, 0);
FmPadBits := 0;
Exit;
end;
bits := TBigInteger.BitLen(namedBits);
bytes := (bits + 7) div 8;
{$IFDEF DEBUG}
System.Assert((0 < bytes) and (bytes <= 4));
{$ENDIF DEBUG}
System.SetLength(data, bytes);
System.Dec(bytes);
for i := 0 to System.Pred(bytes) do
begin
data[i] := Byte(namedBits);
namedBits := TBits.Asr32(namedBits, 8);
end;
{$IFDEF DEBUG}
System.Assert((namedBits and $FF) <> 0);
{$ENDIF DEBUG}
data[bytes] := Byte(namedBits);
padBits := 0;
while ((namedBits and (1 shl padBits)) = 0) do
begin
System.Inc(padBits);
end;
{$IFDEF DEBUG}
System.Assert(padBits < 8);
{$ENDIF DEBUG}
FmData := data;
FmPadBits := padBits;
end;
procedure TDerBitString.Encode(const derOut: TStream);
var
last, mask, unusedBits: Int32;
contents: TCryptoLibByteArray;
begin
if (mPadBits > 0) then
begin
last := mData[System.Length(mData) - 1];
mask := (1 shl mPadBits) - 1;
unusedBits := last and mask;
if (unusedBits <> 0) then
begin
contents := TArrayUtils.Prepend(mData, Byte(mPadBits));
// /*
// * X.690-0207 11.2.1: Each unused bit in the final octet of the encoding of a bit string value shall be set to zero.
// */
contents[System.Length(contents) - 1] := Byte(last xor unusedBits);
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.BitString, contents);
Exit;
end;
end;
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.BitString,
Byte(mPadBits), mData);
end;
class function TDerBitString.FromAsn1Octets(const octets: TCryptoLibByteArray)
: IDerBitString;
var
padBits, last, mask: Int32;
data: TCryptoLibByteArray;
begin
if (System.Length(octets) < 1) then
begin
raise EArgumentCryptoLibException.CreateRes(@STruncatedBitString);
end;
padBits := octets[0];
data := TArrayUtils.CopyOfRange(octets, 1, System.Length(octets));
if ((padBits > 0) and (padBits < 8) and (System.Length(data) > 0)) then
begin
last := data[System.Length(data) - 1];
mask := (1 shl padBits) - 1;
if ((last and mask) <> 0) then
begin
result := TBerBitString.Create(data, padBits);
Exit;
end;
end;
result := TDerBitString.Create(data, padBits);
end;
function TDerBitString.GetBytes: TCryptoLibByteArray;
begin
result := System.Copy(mData);
// DER requires pad bits be zero
if (mPadBits > 0) then
begin
result[System.Length(result) - 1] := result[System.Length(result) - 1] and
Byte($FF shl mPadBits);
end;
end;
class function TDerBitString.GetInstance(const obj: TObject): IDerBitString;
begin
if ((obj = Nil) or (obj is TDerBitString)) then
begin
result := obj as TDerBitString;
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject,
[obj.ClassName]);
end;
class function TDerBitString.GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerBitString;
var
o: IAsn1Object;
begin
o := obj.GetObject();
if ((isExplicit) or (Supports(o, IDerBitString))) then
begin
result := GetInstance(o as TAsn1Object);
Exit;
end;
result := FromAsn1Octets((o as IAsn1OctetString).GetOctets());
end;
function TDerBitString.GetInt32Value: Int32;
var
value, &length, i, mask: Int32;
begin
value := 0;
Length := Min(4, System.Length(mData));
for i := 0 to System.Pred(Length) do
begin
value := value or (Int32(mData[i]) shl (8 * i));
end;
if ((mPadBits > 0) and (Length = System.Length(mData))) then
begin
mask := (1 shl mPadBits) - 1;
value := value and (not(mask shl (8 * (Length - 1))));
end;
result := value;
end;
function TDerBitString.GetString: String;
var
buffer: TStringList;
i: Int32;
str: TCryptoLibByteArray;
ubyte: UInt32;
begin
buffer := TStringList.Create();
buffer.LineBreak := '';
str := GetDerEncoded();
buffer.Add('#');
i := 0;
try
while i <> System.Length(str) do
begin
ubyte := str[i];
buffer.Add(FTable[(ubyte shr 4) and $F]);
buffer.Add(FTable[str[i] and $F]);
System.Inc(i);
end;
result := buffer.Text;
finally
buffer.Free;
end;
end;
function TDerBitString.Asn1GetHashCode: Int32;
begin
result := mPadBits xor TArrayUtils.GetArrayHashCode(mData);
end;
constructor TDerBitString.Create(const obj: IAsn1Encodable);
begin
Create(obj.GetDerEncoded());
end;
end.
|
unit Entidade.TipoSaida;
interface
uses SimpleAttributes;
type
TTIPO_SAIDA = class
private
FDESCRICAO: string;
FID: integer;
FTIPO: string;
procedure SetID(const Value: integer);
procedure SetDESCRICAO(const Value: string);
procedure SetTIPO(const Value: string);
published
[PK,AutoInc]
property ID:integer read FID write SetID;
property DESCRICAO:string read FDESCRICAO write SetDESCRICAO;
property TIPO:string read FTIPO write SetTIPO;
end;
implementation
{ TTIPO_CULTO }
procedure TTIPO_SAIDA.SetID(const Value: integer);
begin
FID := Value;
end;
procedure TTIPO_SAIDA.SetDESCRICAO(const Value: string);
begin
FDESCRICAO := Value;
end;
procedure TTIPO_SAIDA.SetTIPO(const Value: string);
begin
FTIPO := Value;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraProcSource;
interface
uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs,
OraGrants, OraSynonym, VirtualTable;
type
TProcSource = class(TObject)
private
FOWNER,
FSOURCE_NAME,
FCODE: string;
FBODY_CODE: string;
FSOURCE_TYPE: TSourceType;
FGrantList : TGrantList;
FSynonymList : TSynonymList;
FOraSession: TOraSession;
FMode: TMode;
function GetSourceArguments: String;
function GetSourceDetail: String;
function GetSourceStatus: string;
function GetArguments: TVirtualTable;
function GetUsedByList: TVirtualTable;
function GetUsesList: TVirtualTable;
function GetSourceErrors: TVirtualTable;
function GetSourceBodyErrors: TVirtualTable;
public
property OWNER: String read FOWNER write FOWNER;
property SOURCE_NAME: string read FSOURCE_NAME write FSOURCE_NAME;
property SOURCE_TYPE: TSourceType read FSOURCE_TYPE write FSOURCE_TYPE;
property CODE: string read FCODE write FCODE;
property BODY_CODE: string read FBODY_CODE write FBODY_CODE;
property GrantList: TGrantList read FGrantList write FGrantList;
property SynonymList : TSynonymList read FSynonymList write FSynonymList;
property SourceStatus: string read GetSourceStatus;
property UsedByList: TVirtualTable read GetUsedByList;
property UsesList: TVirtualTable read GetUsesList;
property Arguments: TVirtualTable read GetArguments;
property SourceErrors: TVirtualTable read GetSourceErrors;
property SourceBodyErrors: TVirtualTable read GetSourceBodyErrors;
property Mode: TMode read FMode write FMode;
property OraSession: TOraSession read FOraSession write FOraSession;
constructor Create;
destructor Destroy; override;
procedure SetDDL;
function GetDDL: string;
function GetBodyDDL: string;
function GetDefaultDDL: string;
function GetDefaultBodyDDL: string;
function CreateSource(SourceScript: string) : boolean;
function AlterSource(SourceScript: string) : boolean;
function RunSource(SourceScript: string) : boolean;
function DropSource: boolean;
function CompileSource: boolean;
end;
function GetProcSources(ObjectType, OwnerName: string): string;
implementation
uses Util, frmSchemaBrowser, OraScripts, Languages;
resourcestring
strSourceCompiled = '%s has been compiled.';
strSourceDropped = '%s has been dropped.';
strSourceCompleted = '%s completed.';
strSourceCreated = '%s has been created/replaced.';
function GetProcSources(ObjectType, OwnerName: string): string;
begin
result := 'select * from all_objects '
+' where OWNER = '+Str(OwnerName)
+' and object_type = '+Str(ObjectType)
+' order by object_name ';
end;
function GetSourceErrorsSQL: string;
begin
result :=
'SELECT LINE,POSITION,TEXT FROM ALL_ERRORS '
+'WHERE NAME = :pName '
+' AND OWNER = :pOwner '
+' AND TYPE = :pType '
+' ORDER BY LINE,POSITION ';
end;
constructor TProcSource.Create;
begin
inherited;
FGrantList := TGrantList.Create;
FSynonymList := TSynonymList.Create;
end;
destructor TProcSource.destroy;
begin
inherited;
FGrantList.Free;
FSynonymList.Free;
end;
function TProcSource.GetSourceArguments: String;
begin
Result :=
' SELECT object_name , sequence, RPAD('' '', data_level*2, '' '') || argument_name AS argument_name, '
+' (CASE '
+' WHEN data_type IN (''VARCHAR2'',''CHAR'') then TO_CHAR(nvl(data_length,200)) '
+' WHEN data_scale IS NULL OR data_scale = 0 THEN TO_CHAR(data_precision) '
+' ELSE TO_CHAR(data_precision) || '','' || TO_CHAR(data_scale) '
+' END) DATA_SIZE, '
+' data_type, in_out, default_value '
+'FROM ALL_arguments '
+'WHERE package_name is null '
+' AND object_name = DECODE(UPPER(:pName), ''ALL'', object_name, UPPER(:pName)) '
+' and owner = :pOwner '
+'ORDER BY object_name, overload, sequence';
end;
function TProcSource.GetSourceDetail: String;
begin
Result :=
'Select * from SYS.ALL_SOURCE '
+'WHERE NAME = :pName '
+' AND OWNER = :pOwner '
+' AND TYPE = :pType '
+' order by LINE ';
end;
function TProcSource.GetSourceStatus: string;
var
q1: TOraQuery;
begin
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetObjectStatusSQL;
q1.ParamByName('pOName').AsString := FSOURCE_NAME;
q1.ParamByName('pOType').AsString := DBSourceType[FSOURCE_TYPE];
q1.ParamByName('pOwner').AsString := FOWNER;
q1.Open;
result := FSOURCE_NAME+' ( Created: '+q1.FieldByName('CREATED').AsString
+' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString
+' Status: '+q1.FieldByName('STATUS').AsString+' )';
q1.Close;
end;
function TProcSource.GetArguments: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetSourceArguments;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
function TProcSource.GetUsedByList: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetObjectUsedsql;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := DBSourceType[FSOURCE_TYPE];
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
function TProcSource.GetUsesList: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetObjectUsesSQL;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := DBSourceType[FSOURCE_TYPE];
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
function TProcSource.GetSourceErrors: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetSourceErrorsSQL;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := DBSourceType[FSOURCE_TYPE];
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
function TProcSource.GetSourceBodyErrors: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetSourceErrorsSQL;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := 'PACKAGE BODY';
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
procedure TProcSource.SetDDL;
var
q1: TOraQuery;
DBFormType: TDBFormType;
begin
if FSOURCE_NAME = '' then exit;
if FOWNER = '' then exit;
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetSourceDetail;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := DBSourceType[FSOURCE_TYPE];
q1.Open;
FCODE := '';
while not q1.Eof do
begin
FCODE := FCODE + q1.FieldByName('TEXT').AsString;
q1.Next;
end;
Q1.close;
if FSOURCE_TYPE = stPackage then
begin
q1.SQL.Text := GetSourceDetail;
q1.ParamByName('pName').AsString := FSOURCE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.ParamByName('pType').AsString := 'PACKAGE BODY';
q1.Open;
FBODY_CODE := '';
while not q1.Eof do
begin
FBODY_CODE := FBODY_CODE + q1.FieldByName('TEXT').AsString;
q1.Next;
end;
Q1.close;
end;
DBFormType := dbProcedures;
if FSOURCE_TYPE = stProcedure then
DBFormType := dbProcedures;
if FSOURCE_TYPE = stFunction then
DBFormType := dbFunctions;
if FSOURCE_TYPE = stPackage then
DBFormType := dbPackages;
if FSOURCE_TYPE = stType then
DBFormType := dbTypes;
FGrantList.OraSession := OraSession;
FGrantList.TableName := FSOURCE_NAME;
FGrantList.TableSchema := FOWNER;
FGrantList.ObjectType := DBFormType;
FGrantList.SetDDL;
FSynonymList.OraSession := OraSession;
FSynonymList.TableName := FSOURCE_NAME;
FSynonymList.TableOwner := FOWNER;
FSynonymList.ObjectType := DBFormType;
FSynonymList.SetDDL;
end;
function TProcSource.GetDDL: string;
begin
with self do
begin
result := 'CREATE OR REPLACE '//+DBSourceType[FSOURCE_TYPE]+' '+FSOURCE_NAME +' IS '+ln
+FCODE;
end;
end;
function TProcSource.GetBodyDDL: string;
begin
with self do
begin
result := 'CREATE OR REPLACE '//+DBSourceType[FSOURCE_TYPE]+' '+FSOURCE_NAME +' IS '+ln
+FBODY_CODE;
end;
end;
function TProcSource.GetDefaultBodyDDL: string;
begin
if FSOURCE_TYPE = stPackage then
result := 'CREATE OR REPLACE PACKAGE BODY '+FOWNER+'.'+FSOURCE_NAME+ln
+'AS '+ln
+'END '+FSOURCE_NAME+';'+ln
+'/'+ln;
end;
function TProcSource.GetDefaultDDL: string;
begin
if FSOURCE_TYPE = stProcedure then
result := 'CREATE OR REPLACE PROCEDURE '+FOWNER+'.'+FSOURCE_NAME+' IS '+ln
+'tmpVar NUMBER;'+ln
+'BEGIN'+ln
+' tmpVar := 0;'+ln
+' EXCEPTION'+ln
+' WHEN NO_DATA_FOUND THEN'+ln
+' NULL;'+ln
+' WHEN OTHERS THEN'+ln
+' RAISE;'+ln
+'END '+FSOURCE_NAME+';'+ln
+'/'+ln;
if FSOURCE_TYPE = stPackage then
result := 'CREATE OR REPLACE PACKAGE '+FOWNER+'.'+FSOURCE_NAME+ln
+'AS'+ln
+'END '+FSOURCE_NAME+';'+ln
+'/'+ln;
{+'CREATE OR REPLACE PACKAGE BODY '+FOWNER+'.'+FSOURCE_NAME+ln
+'AS '+ln
+'END '+FSOURCE_NAME+';'+ln
+'/'+ln;}
if FSOURCE_TYPE = stFunction then
result := 'CREATE OR REPLACE FUNCTION '+FOWNER+'.'+FSOURCE_NAME+' RETURN NUMBER IS '+ln
+'tmpVar NUMBER;'+ln
+'BEGIN'+ln
+' tmpVar := 0;'+ln
+' RETURN tmpVar;'+ln
+' EXCEPTION'+ln
+' WHEN NO_DATA_FOUND THEN'+ln
+' NULL;'+ln
+' WHEN OTHERS THEN'+ln
+' RAISE;'+ln
+'END '+FSOURCE_NAME+';'+ln
+'/'+ln;
if FSOURCE_TYPE = stType then
result := 'CREATE OR REPLACE TYPE '+FOWNER+'.'+FSOURCE_NAME+' AS OBJECT '+ln
+'('+ln
+' NewAttribute VARCHAR2(255), '+ln
+' MEMBER FUNCTION MyFunction(Param1 IN NUMBER) RETURN NUMBER, '+ln
+' MEMBER PROCEDURE MyProcedure(Param1 IN NUMBER) '+ln
+'); '+ln
+'/'+ln;
end;
function TProcSource.CreateSource(SourceScript: string) : boolean;
begin
result := false;
if FSOURCE_NAME = '' then exit;
result := ExecSQL(SourceScript, Format(ChangeSentence('strSourceCreated',strSourceCreated),[DBSourceType[FSOURCE_TYPE]+' '+FSOURCE_NAME]), FOraSession);
end;
function TProcSource.AlterSource(SourceScript: string) : boolean;
begin
result := false;
if FSOURCE_NAME = '' then exit;
result := ExecSQL(SourceScript, '', FOraSession);
end;
function TProcSource.RunSource(SourceScript: string) : boolean;
begin
result := false;
if FSOURCE_NAME = '' then exit;
result := ExecSQL(SourceScript, Format(ChangeSentence('strSourceCompleted',strSourceCompleted),[DBSourceType[FSOURCE_TYPE]]), FOraSession);
end;
function TProcSource.DropSource: boolean;
var
FSQL: string;
begin
result := false;
if FSOURCE_NAME = '' then exit;
FSQL := 'drop '+DBSourceType[FSOURCE_TYPE]+' '+FOWNER+'.'+FSOURCE_NAME;
result := ExecSQL(FSQL, Format(ChangeSentence('strSourceDropped',strSourceDropped),[DBSourceType[FSOURCE_TYPE]+' '+FSOURCE_NAME]), FOraSession);
end;
function TProcSource.CompileSource: boolean;
var
FSQL: string;
begin
result := false;
if FSOURCE_NAME = '' then exit;
FSQL := 'alter '+DBSourceType[FSOURCE_TYPE]+' '+FOWNER+'.'+FSOURCE_NAME+' compile';
result := ExecSQL(FSQL, Format(ChangeSentence('strSourceCompiled',strSourceCompiled),[DBSourceType[FSOURCE_TYPE]+' '+FSOURCE_NAME]), FOraSession);
end;
end.
|
unit uSplashForm;
interface
uses
SysUtils,
Classes,
Controls,
Messages,
Windows,
Forms,
pngimage,
Graphics;
type
TSplashEkran = class(TCustomControl)
private
FAlphaDegeri: integer;
FResim: TPngImage;
FBitmap: TBitmap; // png resmin tutamac? i?in gerekli.
Fhandle: THandle; // Sahip formun tutamac?.
procedure SetAlphaDegeri(const Value: integer);
procedure SetResim(const Value: TPngImage);
procedure ResizCiz;
procedure Setbuffer(const Value: TPngImage);
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
procedure CreateWnd; override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
public
Fbuffer: TBitmap;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute;
published
property Resim: TPngImage read FResim write SetResim;
property AlphaDegeri: integer read FAlphaDegeri write SetAlphaDegeri default 255; //
end;
procedure register;
implementation
procedure register;
begin
RegisterComponents('Adiitional', [TSplashEkran]);
end;
{ TSplashEkran }
constructor TSplashEkran.Create(AOwner: TComponent);
begin
if not(AOwner is TForm) then
raise EInvalidCast.Create('SplashForm');
inherited Create(AOwner);
// Controlstyle ?zelli?ine di?er bile?enleri kabul etmek i?in.
ControlStyle := ControlStyle + [csAcceptsControls];
// Sahip formun tutamac?n? al?yor.
Fhandle := TForm(AOwner).Handle;
FResim := TPngImage.Create;
TForm(AOwner).BorderStyle := bsNone;
FAlphaDegeri := 255;
FBitmap := TBitmap.Create;
Fbuffer := TBitmap.Create;
Align := alClient;
end;
procedure TSplashEkran.CreateWnd;
begin
// pen?ere olu?turulduktan sonra resmi buffera at?yor.
inherited CreateWnd;
if not(csDesigning in ComponentState) then
Fbuffer.Assign(FResim);
end;
destructor TSplashEkran.Destroy;
begin
FBitmap.Free;
FResim.Free;
Fbuffer.Free;
inherited;
end;
procedure TSplashEkran.Execute;
var
BlendFunction: TBlendFunction;
BitmapPos: TPoint;
BitmapSize: TSize;
exStyle: DWORD;
begin
if Fhandle = 0 then
exit;
if csDesigning in ComponentState then
exit;
if FResim = nil then
exit;
exStyle := GetWindowLongA(Fhandle, GWL_EXSTYLE);
if (exStyle and WS_EX_LAYERED = 0) then
SetWindowLong(Fhandle, GWL_EXSTYLE, exStyle or WS_EX_LAYERED);
FBitmap.Assign(FResim);
TForm(Owner).ClientWidth := FBitmap.Width;
TForm(Owner).ClientHeight := FBitmap.Height;
BitmapPos := Point(0, 0);
BitmapSize.cx := FBitmap.Width;
BitmapSize.cy := FBitmap.Height;
BlendFunction.BlendOp := AC_SRC_OVER;
BlendFunction.BlendFlags := 0;
BlendFunction.SourceConstantAlpha := FAlphaDegeri;
BlendFunction.AlphaFormat := AC_SRC_ALPHA;
UpdateLayeredWindow(Fhandle, 0, nil, @BitmapSize, FBitmap.Canvas.Handle, @BitmapPos, 0,
@BlendFunction, ULW_ALPHA);
end;
procedure TSplashEkran.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
Windows.SetFocus(Handle);
ReleaseCapture;
SendMessage(Fhandle, WM_SYSCOMMAND, SC_MOVE + 1, 0);
end;
procedure TSplashEkran.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
SetCapture(Handle);
end;
procedure TSplashEkran.Paint;
begin
inherited;
ResizCiz;
if not(csDesigning in ComponentState) then
Execute;
end;
procedure TSplashEkran.ResizCiz;
begin
// Tasar?m zaman?nda atanan resmi g?stermek i?in.
if (not FResim.Empty) then
begin
Canvas.Rectangle(0, 0, FResim.Width, FResim.Height);
Canvas.Draw(0, 0, FResim);
end;
end;
procedure TSplashEkran.SetAlphaDegeri(const Value: integer);
begin
if FAlphaDegeri <> Value then
begin
FAlphaDegeri := Value;
if FAlphaDegeri > 255 then
FAlphaDegeri := 255;
if FAlphaDegeri < 0 then
FAlphaDegeri := 0;
Invalidate;
end;
end;
procedure TSplashEkran.Setbuffer(const Value: TPngImage);
begin
Fbuffer.Assign(Value);
end;
procedure TSplashEkran.SetResim(const Value: TPngImage);
var
r: TRect;
begin
FResim.Assign(Value);
FBitmap.Assign(FResim);
GetWindowRect(Fhandle, r);
MoveWindow(Fhandle, r.Left, r.Top, FResim.Width, FResim.Height, true);
Invalidate;
end;
end.
|
unit ssBevel;
interface
uses
SysUtils, Classes, Controls, ExtCtrls, Graphics, Messages,
ssGraphUtil, ImgList, Windows;
const
clXPHotTrack = $206B2408;
type
TssMouseMoveEvent = procedure(Sender: TObject) of object;
TssVertAlignment = (vaTop, vaCenter, vaBottom);
TssMargins = class(TPersistent)
private
FControl: TControl;
FRightMargin: Integer;
FTopMargin: Integer;
FLeftMargin: Integer;
FBottomMargin: Integer;
procedure SetBottomMargin(const Value: Integer);
procedure SetLeftMargin(const Value: Integer);
procedure SetRightMargin(const Value: Integer);
procedure SetTopMargin(const Value: Integer);
public
constructor Create(AOwner: TControl); virtual;
published
property Bottom: Integer read FBottomMargin write SetBottomMargin default 0;
property Left: Integer read FLeftMargin write SetLeftMargin default 4;
property Right: Integer read FRightMargin write SetRightMargin default 4;
property Top: Integer read FTopMargin write SetTopMargin default 0;
end;
TssAlignments = class(TPersistent)
private
FControl: TControl;
FHorz: TAlignment;
FVert: TssVertAlignment;
procedure SetHorz(const Value: TAlignment);
procedure SetVert(const Value: TssVertAlignment);
public
constructor Create(AOwner: TControl); virtual;
published
property Horz: TAlignment read FHorz write SetHorz default taLeftJustify;
property Vert: TssVertAlignment read FVert write SetVert default vaCenter;
end;
TssBevelStyle = (bsLowered, bsRaised, bsSingle);
TssBevelEdge = (beLeft, beRight, beTop, beBottom);
TssBevelEdges = set of TssBevelEdge;
TssBevel = class(TGraphicControl)
private
FShape: TBevelShape;
FStyle: TssBevelStyle;
FColorInner: TColor;
FColorOuter: TColor;
FColorGrBegin: TColor;
FColorGrEnd: TColor;
FGradientDirection: TGradientDirection;
FCaption: TCaption;
FEdges: TssBevelEdges;
FUseGradient: boolean;
FImages: TImageList;
FImageIndex: TImageIndex;
FImagesChangeLink: TChangeLink;
//FAlignment: TAlignment;
FMargins: TssMargins;
FAlignments: TssAlignments;
FHotTrack: Boolean;
FHotTrackColor: TColor;
FOver: Boolean;
FOnMouseLeave: TssMouseMoveEvent;
FOnMouseEnter: TssMouseMoveEvent;
FWordBreak: Boolean;
procedure SetShape(const Value: TBevelShape);
procedure SetStyle(const Value: TssBevelStyle);
procedure SetColorInner(const Value: TColor);
procedure SetColorOuter(const Value: TColor);
procedure SetColorGrBegin(const Value: TColor);
procedure SetColorGrEnd(const Value: TColor);
procedure SetGradientDirection(const Value: TGradientDirection);
procedure SetCaption(const Value: TCaption);
procedure SetEdges(const Value: TssBevelEdges);
procedure SetUseGradient(const Value: boolean);
procedure SetImages(const Value: TImageList);
procedure ImageListChange(Sender: TObject);
procedure SetImageIndex(const Value: TImageIndex);
procedure SetAlignments(const Value: TssAlignments);
procedure SetMargins(const Value: TssMargins);
procedure SetHotTrack(const Value: Boolean);
procedure SetHotTrackColor(const Value: TColor);
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure SetWordBreak(const Value: Boolean);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure PaintFrame;
published
property Align;
property Alignments: TssAlignments read FAlignments write SetAlignments;
property Anchors;
property Caption: TCaption read FCaption write SetCaption;
property Color;
property ColorGrBegin: TColor read FColorGrBegin write SetColorGrBegin;
property ColorGrEnd: TColor read FColorGrEnd write SetColorGrEnd;
property ColorInner: TColor read FColorInner write SetColorInner;
property ColorOuter: TColor read FColorOuter write SetColorOuter;
property Constraints;
property Edges: TssBevelEdges read FEdges write SetEdges;
property Font;
property GradientDirection: TGradientDirection read FGradientDirection write SetGradientDirection;
property HotTrack: Boolean read FHotTrack write SetHotTrack;
property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default clXPHotTrack;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex;
property Images: TImageList read FImages write SetImages;
property Margins: TssMargins read FMargins write SetMargins;
property ParentShowHint;
property ParentColor;
property Shape: TBevelShape read FShape write SetShape default bsBox;
property ShowHint;
property Style: TssBevelStyle read FStyle write SetStyle default bsLowered;
property UseGradient: boolean read FUseGradient write SetUseGradient;
property Visible;
property WordBreak: Boolean read FWordBreak write SetWordBreak default True;
property OnClick;
property OnDblClick;
property OnMouseEnter: TssMouseMoveEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TssMouseMoveEvent read FOnMouseLeave write FOnMouseLeave;
end;
implementation
uses Types;
procedure TssBevel.CMMouseEnter(var Message: TMessage);
var
FControl: TControl;
begin
if not FHotTrack then Exit;
if Assigned(FOnMouseEnter) then FOnMouseEnter(Self);
FControl := Self.Parent.ControlAtPos(Self.Parent.ScreenToClient(Mouse.CursorPos), False, False);
if (FControl = Self) and not FOver then begin
FOver := True;
//Invalidate;
PaintFrame;
end;
end;
procedure TssBevel.CMMouseLeave(var Message: TMessage);
var
FControl: TControl;
R: TRect;
//pinr: string;
mr: tpoint;
begin
if not FHotTrack then Exit;
if Assigned(FOnMouseLeave) then FOnMouseLeave(Self);
GetCursorPos(mr);
//sleep(20);
FControl := Self.Parent.ControlAtPos(Self.Parent.ScreenToClient(Mouse.CursorPos), False, False);
R := Rect(Left, Top, Left + Width, Top + Height);
{if PointInRect(Self.Parent.ScreenToClient(Mouse.CursorPos), R)
then pinr:='true'
else pinr:='false';
Self.Caption := 'ClRect: (' + IntToStr(R.Left) + ',' + IntToStr(R.Top)+')-('+
IntToStr(R.Right) + ',' + IntToStr(R.Bottom)+') ;'+
IntToStr(Self.Parent.ScreenToClient(Mouse.CursorPos).X) + ',' +
IntToStr(Self.Parent.ScreenToClient(Mouse.CursorPos).Y) + ' '+
IntToStr(Self.Parent.ScreenToClient(mr).X) + ',' +
IntToStr(Self.Parent.ScreenToClient(mr).Y) + ' '+
pinr +
' LParam: ' + IntToStr(message.lparam)+
' WParam: ' + IntToStr(message.wparam);
}
if (FControl <> Self) and not PointInRect(Self.Parent.ScreenToClient(Mouse.CursorPos), R)
then begin
FOver := False;
//Invalidate;
PaintFrame;
end;
end;
constructor TssBevel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FImagesChangeLink:=TChangeLink.Create;
FImagesChangeLink.OnChange:=ImageListChange;
ControlStyle := ControlStyle + [csReplicatable];
FStyle := bsLowered;
FShape := bsBox;
FColorInner:=clBtnShadow;
FColorOuter:=clBtnHighlight;
Width := 50;
Height := 50;
FColorGrBegin:=clBtnFace;
FColorGrEnd:=clBtnFace;
Edges:=[beLeft, beRight, beTop, beBottom];
FHotTrack := False;
FHotTrackColor := clXPHotTrack;
FWordBreak := True;
FMargins:=TssMargins.Create(Self);
FAlignments:=TssAlignments.Create(Self);
end;
destructor TssBevel.Destroy;
begin
FImagesChangeLink.Free;
FMargins.Free;
FAlignments.Free;
inherited;
end;
procedure TssBevel.ImageListChange(Sender: TObject);
begin
Invalidate;
end;
procedure TssBevel.Paint;
const
XorColor = $00FFD8CE;
Als: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER);
var
th: integer;
R, IR: TRect;
Flags: Longint;
begin
R := ClientRect;
with Canvas do begin
if UseGradient then begin
if not DrawGradient(Canvas, R, FColorGrBegin, FColorGrEnd, FGradientDirection) then begin
Canvas.Brush.Color:=FColorGrBegin;
Canvas.FillRect(R);
end;
end
else if not ParentColor then begin
Canvas.Brush.Color := Color;
Canvas.FillRect(R);
end;
if (csDesigning in ComponentState) then begin
if (FShape = bsSpacer) then begin
Pen.Style := psDot;
Pen.Mode := pmXor;
Pen.Color := XorColor;
Brush.Style := bsClear;
Rectangle(0, 0, ClientWidth, ClientHeight);
end
else begin
Pen.Style := psSolid;
Pen.Mode := pmCopy;
Pen.Color := clBlack;
Brush.Style := bsSolid;
end;
end;
PaintFrame;
Font:=Self.Font;
Brush.Style:=bsClear;
with R do begin
Top := Top + FMargins.Top;
Bottom := Bottom - FMargins.Bottom;
Left := Left + FMargins.Left;
Right := Right - FMargins.Right;
end;
if Assigned(FImages) and (FImageIndex<>-1) then begin
IR := R;
IR.Top := ClientRect.Top+FMargins.Top;
IR.Right := IR.Left+FImages.Width;
IR.Bottom := IR.Top+FImages.Height;
R.Left := R.Left + FImages.Width + 4;
FImages.Draw(Canvas, IR.Left, IR.Top, FImageIndex, True);
end;
Flags:=DT_CALCRECT or DT_EXPANDTABS or Als[FAlignments.Horz];
if FWordBreak then Flags := Flags or DT_WORDBREAK;
Flags := DrawTextBiDiModeFlags(Flags);
DrawText(Handle, PChar(FCaption), -1, R, Flags);
th:=R.Bottom-R.Top;
case FAlignments.Vert of
vaCenter: R.Top := ClientRect.Top + FMargins.Top+((ClientRect.Bottom-ClientRect.Top-th) div 2);
vaTop: R.Top := ClientRect.Top + FMargins.Top;
vaBottom: R.Top := ClientRect.Bottom - FMargins.Bottom - th;
end;
R.Bottom:=R.Top+th;
R.Left:=ClientRect.Left+FMargins.Left;
R.Right:=ClientRect.Right-FMargins.Right;
Flags := DT_EXPANDTABS or Als[FAlignments.Horz];
if FWordBreak then Flags := Flags or DT_WORDBREAK;
Flags := DrawTextBiDiModeFlags(Flags);
DrawText(Handle, PChar(FCaption), -1, R, Flags);
end;
end;
procedure TssBevel.PaintFrame;
var
Color1, Color2, Temp: TColor;
procedure BevelRect(const R: TRect);
begin
with Canvas do begin
Pen.Color := Color1;
PolyLine([Point(R.Left, R.Bottom), Point(R.Left, R.Top), Point(R.Right, R.Top)]);
Pen.Color := Color2;
PolyLine([Point(R.Right, R.Top), Point(R.Right, R.Bottom), Point(R.Left, R.Bottom)]);
end;
end;
procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer);
begin
with Canvas do
begin
Pen.Color := C;
MoveTo(X1, Y1);
LineTo(X2, Y2);
end;
end;
begin
with Canvas do begin
Pen.Width := 1;
if FStyle = bsLowered then begin
Color1 := FColorInner;
Color2 := FColorOuter;
end
else begin
Color1 := FColorOuter;
Color2 := FColorInner;
end;
if not (csDesigning in ComponentState) and FHotTrack and FOver then begin
Color1 := FHotTrackColor;
Color2 := FHotTrackColor;
end;
case FShape of
bsBox:
begin
if FStyle<>bsSingle then BevelRect(Rect(0, 0, Width - 1, Height - 1))
else begin
if beLeft in FEdges then BevelLine(Color1, 0, 0, 0, Height);
if beRight in FEdges then BevelLine(Color1, Width-1, 0, Width-1, Height);
if beTop in FEdges then BevelLine(Color1, 0, 0, Width, 0);
if beBottom in FEdges then BevelLine(Color1, 0, Height-1, Width, Height-1);
end;
end;
bsFrame:
begin
Temp := Color1;
Color1 := Color2;
BevelRect(Rect(1, 1, Width - 1, Height - 1));
Color2 := Temp;
Color1 := Temp;
BevelRect(Rect(0, 0, Width - 2, Height - 2));
end;
bsTopLine:
begin
BevelLine(Color1, 0, 0, Width, 0);
if FStyle <> bsSingle then BevelLine(Color2, 0, 1, Width, 1);
end;
bsBottomLine:
begin
BevelLine(Color1, 0, Height - 2, Width, Height - 2);
if FStyle <> bsSingle then BevelLine(Color2, 0, Height - 1, Width, Height - 1);
end;
bsLeftLine:
begin
BevelLine(Color1, 0, 0, 0, Height);
if FStyle <> bsSingle then BevelLine(Color2, 1, 0, 1, Height);
end;
bsRightLine:
begin
BevelLine(Color1, Width - 2, 0, Width - 2, Height);
if FStyle <> bsSingle then BevelLine(Color2, Width - 1, 0, Width - 1, Height);
end;
end;
end;
end;
procedure TssBevel.SetAlignments(const Value: TssAlignments);
begin
FAlignments.Assign(Value);
end;
procedure TssBevel.SetCaption(const Value: TCaption);
begin
FCaption := Value;
Invalidate;
end;
procedure TssBevel.SetColorGrBegin(const Value: TColor);
begin
FColorGrBegin := Value;
Invalidate;
end;
procedure TssBevel.SetColorGrEnd(const Value: TColor);
begin
FColorGrEnd := Value;
Invalidate;
end;
procedure TssBevel.SetColorInner(const Value: TColor);
begin
if Value <> FColorInner then begin
FColorInner := Value;
Invalidate;
end;
end;
procedure TssBevel.SetColorOuter(const Value: TColor);
begin
if Value <> FColorOuter then begin
FColorOuter := Value;
Invalidate;
end;
end;
procedure TssBevel.SetEdges(const Value: TssBevelEdges);
begin
FEdges := Value;
Invalidate;
end;
procedure TssBevel.SetGradientDirection(const Value: TGradientDirection);
begin
FGradientDirection := Value;
Invalidate;
end;
procedure TssBevel.SetHotTrack(const Value: Boolean);
begin
FHotTrack := Value;
Invalidate;
end;
procedure TssBevel.SetHotTrackColor(const Value: TColor);
begin
FHotTrackColor := Value;
Invalidate;
end;
procedure TssBevel.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then begin
FImageIndex := Value;
Invalidate;
end;
end;
procedure TssBevel.SetImages(const Value: TImageList);
begin
if FImages <> nil then
FImages.UnRegisterChanges(FImagesChangeLink);
FImages := Value;
if FImages <> nil then
FImages.RegisterChanges(FImagesChangeLink);
Invalidate;
end;
procedure TssBevel.SetMargins(const Value: TssMargins);
begin
FMargins.Assign(Value);
end;
procedure TssBevel.SetShape(const Value: TBevelShape);
begin
if Value <> FShape then begin
FShape := Value;
Invalidate;
end;
end;
procedure TssBevel.SetStyle(const Value: TssBevelStyle);
begin
if Value <> FStyle then begin
FStyle := Value;
Invalidate;
end;
end;
procedure TssBevel.SetUseGradient(const Value: boolean);
begin
FUseGradient := Value;
Invalidate;
end;
{ TssMargins }
constructor TssMargins.Create(AOwner: TControl);
begin
inherited Create;
FControl:=AOwner;
FLeftMargin:=4;
FRightMargin:=4;
FTopMargin:=0;
FBottomMargin:=0;
end;
procedure TssMargins.SetBottomMargin(const Value: Integer);
begin
FBottomMargin := Value;
FControl.Invalidate;
end;
procedure TssMargins.SetLeftMargin(const Value: Integer);
begin
FLeftMargin := Value;
FControl.Invalidate;
end;
procedure TssMargins.SetRightMargin(const Value: Integer);
begin
FRightMargin := Value;
FControl.Invalidate;
end;
procedure TssMargins.SetTopMargin(const Value: Integer);
begin
FTopMargin := Value;
FControl.Invalidate;
end;
{ TssAlignments }
constructor TssAlignments.Create(AOwner: TControl);
begin
FControl:=AOwner;
FHorz:=taLeftJustify;
FVert:=vaCenter;
end;
procedure TssAlignments.SetHorz(const Value: TAlignment);
begin
FHorz := Value;
FControl.Invalidate;
end;
procedure TssAlignments.SetVert(const Value: TssVertAlignment);
begin
FVert := Value;
FControl.Invalidate;
end;
procedure TssBevel.SetWordBreak(const Value: Boolean);
begin
FWordBreak := Value;
Invalidate;
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, LoggerInterface,
ThreadManager, System.SyncObjs;
type
TMainForm = class(TForm)
Memo: TMemo;
strict private
procedure UpdateLogMessages(AMessages: TArray<String>);
procedure WaitLogUpdates;
private
FCancellationEvent: TEvent;
FLoggerI: ILogger;
FThreadManager: TThreadManager;
FWaitLogUpdatesThread: TThread;
procedure CreateWaitLogUpdatesThread;
procedure TerminateWaitLogUpdatesThread;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses
AppSettings, AppLogger;
{$R *.dfm}
constructor TMainForm.Create(AOwner: TComponent);
begin
inherited;
try
FLoggerI := TAppLoger.Logger;
CreateWaitLogUpdatesThread;
FThreadManager := TThreadManager.Create(FLoggerI,
TAppSettings.Settings.MessageThread);
except
on E: Exception do
begin
ShowMessage(E.Message);
Application.ShowMainForm := False;
Application.Terminate;
end;
end;
end;
destructor TMainForm.Destroy;
begin
TerminateWaitLogUpdatesThread;
if FThreadManager <> nil then
FreeAndNil(FThreadManager);
FLoggerI := nil;
inherited;
end;
procedure TMainForm.CreateWaitLogUpdatesThread;
begin
// Событие, которого будет ждать поток
FCancellationEvent := TEvent.Create;
FWaitLogUpdatesThread := TThread.CreateAnonymousThread(
procedure
begin
WaitLogUpdates;
end);
FWaitLogUpdatesThread.FreeOnTerminate := False;
FWaitLogUpdatesThread.Start;
end;
procedure TMainForm.TerminateWaitLogUpdatesThread;
begin
if FCancellationEvent <> nil then
begin
FCancellationEvent.SetEvent;
FWaitLogUpdatesThread.WaitFor;
FreeAndNil(FWaitLogUpdatesThread);
FreeAndNil(FCancellationEvent);
end;
end;
procedure TMainForm.UpdateLogMessages(AMessages: TArray<String>);
var
s: string;
begin
Memo.Lines.BeginUpdate;
try
Memo.Clear;
for s in AMessages do
begin
Memo.Lines.Add(s.Trim([#13, #10]));
end;
finally
Memo.Lines.EndUpdate;
end;
end;
procedure TMainForm.WaitLogUpdates;
var
ASignaledObject: THandleObject;
AWaitResult: TWaitResult;
ALastMessages: TArray<String>;
begin
while True do
begin
AWaitResult := TEvent.WaitForMultiple
([FCancellationEvent, FLoggerI.AddMessageEvent], 1000, False, ASignaledObject);
// Если дождались
if AWaitResult <> wrTimeout then
begin
if ASignaledObject = FLoggerI.AddMessageEvent then
begin
ALastMessages := FLoggerI.GetLastMessages;
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
UpdateLogMessages(ALastMessages);
end);
end
else
// Если пора завершать
if ASignaledObject = FCancellationEvent then
break
end;
end;
end;
end.
|
unit Banks;
interface
type
TBanks = class
private
Fname: String;
Fnumber: String;
public
property number : String read Fnumber write Fnumber;
property name : String read Fname write Fname;
end;
implementation
end.
|
unit View.ImportaCapaFinanceiroDIRECT;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
dxSkinsCore, dxSkinsDefaultPainters, dxGDIPlusClasses, cxImage, cxLabel, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.StdCtrls,
cxButtons, Vcl.ExtCtrls, cxTextEdit, cxMaskEdit, cxButtonEdit, cxClasses, dxLayoutContainer, dxLayoutControl,
dxLayoutcxEditAdapters, dxLayoutControlAdapters, Vcl.ComCtrls, cxProgressBar, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxMemo, Thread.CapaDIRECT,
dxActivityIndicator, ShellAPI, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxCheckBox, cxCurrencyEdit;
type
Tview_ImportaCapaFinanceiroDIRECT = class(TForm)
actionListImportar: TActionList;
actionFecharTela: TAction;
actionSelecionarArquivo: TAction;
actionLimparCampo: TAction;
actionImportar: TAction;
OpenDialog: TOpenDialog;
dxLayoutControl1Group_Root: TdxLayoutGroup;
dxLayoutControl1: TdxLayoutControl;
labelTitle: TcxLabel;
dxLayoutItem1: TdxLayoutItem;
dxLayoutGroup1: TdxLayoutGroup;
cxButton1: TcxButton;
dxLayoutItem2: TdxLayoutItem;
dxLayoutGroup2: TdxLayoutGroup;
nomeArquivo: TcxButtonEdit;
dxLayoutItem3: TdxLayoutItem;
dxLayoutGroup3: TdxLayoutGroup;
labelAtalhos: TcxLabel;
dxLayoutItem4: TdxLayoutItem;
dxLayoutGroup4: TdxLayoutGroup;
dxLayoutGroup5: TdxLayoutGroup;
dxLayoutGroup6: TdxLayoutGroup;
totalRegistros: TcxMaskEdit;
dxLayoutItem5: TdxLayoutItem;
registrosProcessados: TcxMaskEdit;
dxLayoutItem6: TdxLayoutItem;
totalInconsistências: TcxMaskEdit;
dxLayoutItem7: TdxLayoutItem;
progressBar: TcxProgressBar;
dxLayoutItem8: TdxLayoutItem;
Timer: TTimer;
cxButton2: TcxButton;
dxLayoutItem10: TdxLayoutItem;
actionCancelar: TAction;
indicador: TdxActivityIndicator;
actionSalvarArquivo: TAction;
memTableLOG: TFDMemTable;
memTableLOGdes_descricao: TStringField;
memTableLOGnum_remessa: TStringField;
memTableLOGqtd_peso_baixa: TFloatField;
memTableLOGqtd_peso_capa: TFloatField;
memTableLOGval_verba_entregador: TCurrencyField;
memTableLOGval_verba_Empresa: TCurrencyField;
memTableLOGnom_motorista: TStringField;
memTableLOGnum_cep: TStringField;
gridInconsistenciasDBTableView1: TcxGridDBTableView;
gridInconsistenciasLevel1: TcxGridLevel;
gridInconsistencias: TcxGrid;
dxLayoutItem9: TdxLayoutItem;
dsLOG: TDataSource;
gridInconsistenciasDBTableView1des_descricao: TcxGridDBColumn;
gridInconsistenciasDBTableView1num_remessa: TcxGridDBColumn;
gridInconsistenciasDBTableView1qtd_peso_baixa: TcxGridDBColumn;
gridInconsistenciasDBTableView1qtd_peso_capa: TcxGridDBColumn;
gridInconsistenciasDBTableView1val_verba_entregador: TcxGridDBColumn;
gridInconsistenciasDBTableView1val_verba_Empresa: TcxGridDBColumn;
gridInconsistenciasDBTableView1nom_motorista: TcxGridDBColumn;
gridInconsistenciasDBTableView1num_cep: TcxGridDBColumn;
actionExpandirGrupos: TAction;
actionColapsarGrupos: TAction;
actionRestaurar: TAction;
dxLayoutGroup7: TdxLayoutGroup;
cxButton3: TcxButton;
dxLayoutItem11: TdxLayoutItem;
procedure FormShow(Sender: TObject);
procedure actionFecharTelaExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actionSelecionarArquivoExecute(Sender: TObject);
procedure actionLimparCampoExecute(Sender: TObject);
procedure actionImportarExecute(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure actionCancelarExecute(Sender: TObject);
procedure gridInconsistenciasDBTableView1NavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer;
var ADone: Boolean);
procedure actionExpandirGruposExecute(Sender: TObject);
procedure actionColapsarGruposExecute(Sender: TObject);
procedure actionRestaurarExecute(Sender: TObject);
private
{ Private declarations }
procedure StartForm;
procedure Openfile;
procedure StartImport(sFile: String);
procedure ProcessaCapa(sFile: String; iCliente: Integer; memTab: TFDMemTable);
procedure UpdateDashboard;
procedure TerminateProcess;
procedure ExportarGrade;
procedure SaveLayout;
procedure RestoreLayout;
public
{ Public declarations }
end;
var
view_ImportaCapaFinanceiroDIRECT: Tview_ImportaCapaFinanceiroDIRECT;
capa : Thread_CapaDirect;
sFileLayout: String;
implementation
{$R *.dfm}
uses Data.SisGeF, Common.Utils, Global.Parametros;
{ Tview_ImportaCapaFinanceiroDIRECT }
procedure Tview_ImportaCapaFinanceiroDIRECT.actionCancelarExecute(Sender: TObject);
begin
capa.Cancelar := True;
capa.Terminate;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionColapsarGruposExecute(Sender: TObject);
begin
gridInconsistenciasDBTableView1.ViewData.Collapse(True);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionExpandirGruposExecute(Sender: TObject);
begin
gridInconsistenciasDBTableView1.ViewData.Expand(True);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionFecharTelaExecute(Sender: TObject);
begin
Close;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionImportarExecute(Sender: TObject);
begin
StartImport(nomeArquivo.Text);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionLimparCampoExecute(Sender: TObject);
begin
nomeArquivo.Clear;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionRestaurarExecute(Sender: TObject);
begin
RestoreLayout;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.actionSelecionarArquivoExecute(Sender: TObject);
begin
Openfile;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.ExportarGrade;
var
fnUtil : Common.Utils.TUtils;
sMensagem: String;
begin
try
fnUtil := Common.Utils.TUtils.Create;
if memTableLOG.IsEmpty then Exit;
if Data_Sisgef.SaveDialog.Execute() then
begin
if FileExists(Data_Sisgef.SaveDialog.FileName) then
begin
sMensagem := 'Arquivo ' + Data_Sisgef.SaveDialog.FileName + ' já existe! Sobrepor ?';
if Application.MessageBox(PChar(sMensagem), 'Sobrepor', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit
end;
fnUtil.ExportarDados(gridInconsistencias,Data_Sisgef.SaveDialog.FileName);
end;
finally
fnUtil.Free;
end;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if memTableLOG.Active then memTableLOG.Close;
if FileExists(sFileLayout) then
DeleteFile(sFileLayout);
Action := caFree;
view_ImportaCapaFinanceiroDIRECT := nil;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.FormShow(Sender: TObject);
begin
StartForm;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.gridInconsistenciasDBTableView1NavigatorButtonsButtonClick(Sender: TObject;
AButtonIndex: Integer; var ADone: Boolean);
begin
case AButtonIndex of
16 : ExportarGrade;
17 : gridInconsistenciasDBTableView1.ViewData.Expand(True);
18 : gridInconsistenciasDBTableView1.ViewData.Collapse(True);
19 : RestoreLayout;
end;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.Openfile;
begin
if OpenDialog.Execute then
nomeArquivo.Text := OpenDialog.FileName;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.ProcessaCapa(sFile: String; iCliente: Integer; memTab: TFDMemTable);
begin
dsLOG.Enabled := False;
if memTableLOG.Active then
memTableLOG.Close;
memTableLOG.Open;
capa := Thread_CapaDirect.Create(True);
capa.Arquivo := sFile;
capa.Cliente := iCliente;
capa.MemTab := memTab;
capa.Priority := tpNormal;
Timer.Enabled := True;
actionSelecionarArquivo.Enabled := False;
actionLimparCampo.Enabled := False;
actionImportar.Enabled := False;
actionCancelar.Enabled := True;
indicador.Active := True;
capa.Start;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.RestoreLayout;
begin
gridInconsistenciasDBTableView1.RestoreFromIniFile(sFileLayout);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.StartImport(sFile: String);
begin
if sFile.IsEmpty then
begin
Application.MessageBox('Informe o arquivo!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if not FileExists(sFile) then
begin
Application.MessageBox(PChar('Arquivo ' + sFile + ' não encontrado!'), 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if Application.MessageBox(PChar('Confirma a importação do arquivo ' + sFile + ' ?'), 'Importar', MB_YESNO + MB_ICONQUESTION) = IDYES then
ProcessaCapa(sFile, 4, memTableLOG);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.TerminateProcess;
begin
if Assigned(capa) then
begin
capa.Free;
end;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.TimerTimer(Sender: TObject);
begin
UpdateDashboard;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.UpdateDashboard;
begin
if not capa.Processo then
begin
Timer.Enabled := False;
actionSelecionarArquivo.Enabled := True;
actionLimparCampo.Enabled := True;
actionImportar.Enabled := True;
actionCancelar.Enabled := False;
indicador.Active := False;
progressBar.Position := capa.Progresso;
totalRegistros.EditValue := capa.TotalRegistros;
totalInconsistências.EditValue := capa.TotalInconsistencias;
registrosProcessados.EditValue := capa.TotalGravados;
if Capa.Cancelar then
Application.MessageBox('Importação Cancelada!', 'Atenção', MB_OK + MB_ICONEXCLAMATION)
else
Application.MessageBox('Importação concluída!', 'Atenção', MB_OK + MB_ICONINFORMATION);
dsLOG.Enabled := True;
nomeArquivo.Text := '';
progressBar.Position := 0;
TerminateProcess;
end
else
begin
progressBar.Position := capa.Progresso;
totalRegistros.EditValue := capa.TotalRegistros;
totalInconsistências.EditValue := capa.TotalInconsistencias;
registrosProcessados.EditValue := capa.TotalGravados;
end;
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.SaveLayout;
begin
gridInconsistenciasDBTableView1.StoreToIniFile(sFileLayout);
end;
procedure Tview_ImportaCapaFinanceiroDIRECT.StartForm;
begin
labelTitle.Caption := Self.Caption;
sFileLayout := ExtractFilePath(Application.ExeName) + '\layoutcapa' + Global.Parametros.pUser_ID.ToString + '.ini';
SaveLayout;
end;
end.
|
unit DAO.Conexao;
interface
uses
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.MySQLDef,
FireDAC.Phys.FB, System.SysUtils, FireDAC.DApt, FireDAC.VCLUI.Wait, Global.Parametros;
type
TConexao = class
private
FConn: TFDConnection;
procedure SetupConnection;
public
constructor Create;
destructor Destroy; override;
function GetConn: TFDConnection;
function ReturnQuery: TFDQuery;
end;
implementation
{ TConexao }
constructor TConexao.Create;
begin
Fconn := TFDConnection.Create(nil);
Self.SetupConnection();
end;
destructor TConexao.Destroy;
begin
FConn.Free;
inherited;
end;
function TConexao.GetConn: TFDConnection;
begin
Result := FConn;
end;
function TConexao.ReturnQuery: TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := TFDQuery.Create(nil);
FDQuery.Connection := FConn;
Result := FDQuery;
end;
procedure TConexao.SetupConnection;
begin
FConn.LoginPrompt := False;
FConn.ConnectionString := 'DriverID=' + Global.Parametros.pDriverID +
';Server=' + Global.Parametros.pServer +
';Database=' + Global.Parametros.pDatabase +
';Port=' + Global.Parametros.pPort +
';User_name=' + Global.Parametros.pUBD +
';Password=' + Global.Parametros.pPBD;
end;
end.
|
unit CustomWebBrowser;
interface
uses
Windows, ActiveX, SHDocVw, Mshtmhst;
type
TCustomWebBrowser =
class(TWebBrowser, IServiceProvider, IDocHostUIHandler)
private // IServiceProvider
function QueryService(const rsid, iid: TGuid; out Obj): HResult; stdcall;
private // IDocHostUIHandler
function ShowContextMenu(dwID : DWORD; ppt : PPoint; pcmdtReserved : IUnknown; pdispReserved : IDispatch) : HRESULT; stdcall;
function GetHostInfo(var pInfo : DOCHOSTUIINFO) : HRESULT; stdcall;
function ShowUI(dwID : DWORD; pActiveObject : IOleInPlaceActiveObject; pCommandTarget : IOleCommandTarget; pFrame : IOleInPlaceFrame; pDoc : IOleInPlaceUIWindow) : HRESULT; stdcall;
function HideUI : HRESULT; stdcall;
function UpdateUI : HRESULT; stdcall;
function EnableModeless(fEnable : BOOL) : HRESULT; stdcall;
function OnDocWindowActivate(fActivate : BOOL) : HRESULT; stdcall;
function OnFrameWindowActivate(fActivate : BOOL) : HRESULT; stdcall;
function ResizeBorder(prcBorder : PRect; pUIWindow : IOleInPlaceUIWindow; fRameWindow : BOOL) : HRESULT; stdcall;
function TranslateAccelerator(lpMsg : PMsg; const pguidCmdGroup : PGUID; nCmdID : DWORD) : HRESULT; stdcall;
function GetOptionKeyPath(out pchKey : PWideChar; dw : DWORD ) : HRESULT; stdcall;
function GetDropTarget(pDropTarget : IDropTarget; out ppDropTarget : IDropTarget) : HRESULT; stdcall;
function GetExternal(out ppDispatch : IDispatch) : HRESULT; stdcall;
function TranslateUrl(dwTranslate : DWORD; pchURLIn : PWideChar; out ppchURLOut : PWideChar) : HRESULT; stdcall;
function FilterDataObject(pDO : IDataObject; out ppDORet : IDataObject) : HRESULT; stdcall;
private
fHideScrollbars : boolean;
fFlatScrollbars : boolean;
fHideBorders : boolean;
fAllowTextSelection : boolean;
public
property HideScrollbars : boolean read fHideScrollbars write fHideScrollbars;
property FlatScrollbars : boolean read fFlatScrollbars write fFlatScrollbars;
property HideBorders : boolean read fHideBorders write fHideBorders;
property AllowTextSelection : boolean read fAllowTextSelection write fAllowTextSelection;
end;
implementation
uses
URLMon2, InternetSecurityManager, LogFile;
// TCustomWebBrowser
function TCustomWebBrowser.QueryService(const rsid, iid : TGuid; out Obj) : HResult;
begin
if IsEqualGUID(rsid, SID_IInternetSecurityManager)
then
begin
{$IFDEF Logs}
LogThis('InternetSecurityManager requested');
{$ENDIF}
IInternetSecurityManager(Obj) := TInternetSecurityManager.Create as IInternetSecurityManager;
Result := S_OK;
end
else
begin
IUnknown(Obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TCustomWebBrowser.ShowContextMenu(dwID : DWORD; ppt : PPoint; pcmdtReserved : IUnknown; pdispReserved : IDispatch) : HRESULT;
begin
{$IFDEF Logs}
LogThis('ShowContextMenu called');
{$ENDIF}
Result := S_OK;
end;
function TCustomWebBrowser.GetHostInfo(var pInfo : DOCHOSTUIINFO) : HRESULT;
begin
{$IFDEF Logs}
LogThis('GetHostInfo called');
{$ENDIF}
pInfo.cbSize := sizeof(DOCHOSTUIINFO);
pInfo.dwFlags := 0; // could disable help menus and text selection also, there are flags available for that
if fHideScrollbars
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_SCROLL_NO;
if fFlatScrollbars
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_FLAT_SCROLLBAR;
if fHideBorders
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_NO3DBORDER;
if not fAllowTextSelection
then pInfo.dwFlags := pInfo.dwFlags or DOCHOSTUIFLAG_DIALOG;
pInfo.dwDoubleClick := DOCHOSTUIDBLCLK_DEFAULT;
{
pInfo.pchHostCss := nil;
pInfo.pchHostNS := nil;
}
Result := S_OK;
end;
function TCustomWebBrowser.ShowUI(dwID : DWORD; pActiveObject : IOleInPlaceActiveObject; pCommandTarget : IOleCommandTarget; pFrame : IOleInPlaceFrame; pDoc : IOleInPlaceUIWindow) : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.HideUI : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.UpdateUI : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.EnableModeless(fEnable : BOOL) : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.OnDocWindowActivate(fActivate : BOOL) : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.OnFrameWindowActivate(fActivate : BOOL) : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.ResizeBorder(prcBorder : PRect; pUIWindow : IOleInPlaceUIWindow; fRameWindow : BOOL) : HRESULT;
begin
Result := S_OK;
end;
function TCustomWebBrowser.TranslateAccelerator(lpMsg : PMsg; const pguidCmdGroup : PGUID; nCmdID : DWORD) : HRESULT;
begin
Result := S_FALSE;
end; // S_FALSE or S_OK, test this
function TCustomWebBrowser.GetOptionKeyPath(out pchKey : PWideChar; dw : DWORD) : HRESULT;
begin
pchKey := nil;
Result := S_FALSE;
end; // it's not really clear if S_FALSE should be returned
function TCustomWebBrowser.GetDropTarget(pDropTarget : IDropTarget; out ppDropTarget : IDropTarget) : HRESULT;
begin
Result := S_FALSE;
end; // might need to set ppDropTarget to nil
function TCustomWebBrowser.GetExternal(out ppDispatch : IDispatch) : HRESULT;
begin
ppDispatch := nil;
Result := S_OK; // check if S_OK or S_FALSE
end;
function TCustomWebBrowser.TranslateUrl(dwTranslate : DWORD; pchURLIn : PWideChar; out ppchURLOut : PWideChar) : HRESULT;
begin
ppchURLOut := nil; // this was added
Result := S_FALSE;
end;
function TCustomWebBrowser.FilterDataObject(pDO : IDataObject; out ppDORet : IDataObject) : HRESULT;
begin
ppDORet := nil;
Result := S_FALSE;
end;
end.
|
unit Model.CCEPDistribuidor;
interface
uses Common.ENum, FireDAC.Comp.Client;
type
TCCEPDistribuidor = class
private
FAcao: TAcao;
FFaixa: Integer;
FLOG: String;
FCCEP: String;
FCodigoDistribuidor: Integer;
FGrupo: Integer;
public
property CodigoDistribuidor: Integer read FCodigoDistribuidor write FCodigoDistribuidor;
property CCEP: String read FCCEP write FCCEP;
property Grupo: Integer read FGrupo write FGrupo;
property Faixa: Integer read FFaixa write FFaixa;
property LOG: String read FLOG write FLOG;
property Acao: TAcao read FAcao write FAcao;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TCCEPDistribuidor }
uses DAO.CCEPDistribuidor;
function TCCEPDistribuidor.Gravar: Boolean;
var
CCEPDAO : TCCEPDistribuidorDAO;
begin
try
Result := False;
CCEPDAO := TCCEPDistribuidorDAO.Create;
case FAcao of
Common.ENum.tacIncluir: Result := CCEPDAO.Inserir(Self);
Common.ENum.tacAlterar: Result := CCEPDAO.Alterar(Self);
Common.ENum.tacExcluir: Result := CCEPDAO.Excluir(Self);
end;
finally
CCEPDAO.Free;
end;end;
function TCCEPDistribuidor.Localizar(aParam: array of variant): TFDQuery;
var
CCEPDAO: TCCEPDistribuidorDAO;
begin
try
CCEPDAO := TCCEPDistribuidorDAO.Create;
Result := CCEPDAO.Pesquisar(aParam);
finally
CCEPDAO.Free;
end;
end;
end.
|
unit deco_common;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}gfx_engine,ym_2203,ym_2151,oki6295,hu6280,
cpu_misc,main_engine;
type
tdeco16_sprite=class
constructor create(gfx,pant:byte;global_x_size,color_add,mask:word);
destructor free;
public
ram:array[0..$3ff] of word;
procedure draw_sprites(pri:byte=0);
procedure reset;
private
global_x_size,color_add,mask:word;
gfx,pant:byte;
end;
var
deco16_sound_latch:byte;
snd_ram:array[0..$1fff] of byte;
oki_rom:array[0..1,0..$3ffff] of byte;
deco_sprites_0:tdeco16_sprite;
//Sound
procedure deco16_snd_simple_init(cpu_clock,sound_clock:dword;sound_bank:cpu_outport_call);
procedure deco16_snd_simple_reset;
function deco16_simple_snd_getbyte(direccion:dword):byte;
procedure deco16_simple_snd_putbyte(direccion:dword;valor:byte);
procedure deco16_simple_sound;
procedure deco16_snd_double_init(cpu_clock,sound_clock:dword;sound_bank:cpu_outport_call);
procedure deco16_snd_double_reset;
function deco16_double_snd_getbyte(direccion:dword):byte;
procedure deco16_double_snd_putbyte(direccion:dword;valor:byte);
procedure deco16_double_sound;
procedure deco16_snd_irq(irqstate:byte);
implementation
constructor tdeco16_sprite.create(gfx,pant:byte;global_x_size,color_add,mask:word);
begin
self.global_x_size:=global_x_size;
self.color_add:=color_add;
self.mask:=mask;
self.gfx:=gfx;
self.pant:=pant;
end;
destructor tdeco16_sprite.free;
begin
end;
procedure tdeco16_sprite.reset;
begin
fillchar(self.ram,$400*2,0);
end;
procedure tdeco16_sprite.draw_sprites(pri:byte=0);
var
f,color:byte;
y,x,nchar:word;
fx,fy:boolean;
multi,inc,mult:integer;
begin
for f:=0 to $ff do begin
x:=self.ram[(f*4)+2];
if pri<>((x shr 8) and $c0) then continue;
y:=self.ram[(f*4)+0];
if (((y and $1000)<>0) and ((main_vars.frames_sec and 1)<>0)) then continue;
color:=(x shr 9) and $1f;
fx:=(y and $2000)<>0;
fy:=(y and $4000)<>0;
multi:=(1 shl ((y and $0600) shr 9))-1; // 1x, 2x, 4x, 8x height
x:=(self.global_x_size-x) and $1ff;
y:=(240-y) and $1ff;
nchar:=(self.ram[(f*4)+1] and not(multi)) and self.mask;
if fy then inc:=-1
else begin
nchar:=nchar+multi;
inc:=1;
end;
mult:=-16;
while (multi>=0) do begin
if nchar<>0 then begin
put_gfx_sprite(nchar-multi*inc,(color shl 4)+self.color_add,fx,fy,self.gfx);
actualiza_gfx_sprite(x,y+mult*multi,self.pant,self.gfx);
end;
multi:=multi-1;
end;
end;
end;
//Sound
procedure deco16_snd_double_init(cpu_clock,sound_clock:dword;sound_bank:cpu_outport_call);
begin
h6280_0:=cpu_h6280.create(cpu_clock,$100);
h6280_0.change_ram_calls(deco16_double_snd_getbyte,deco16_double_snd_putbyte);
h6280_0.init_sound(deco16_double_sound);
ym2203_0:=ym2203_chip.create(sound_clock div 8);
ym2151_0:=ym2151_chip.create(sound_clock div 9);
ym2151_0.change_port_func(sound_bank);
ym2151_0.change_irq_func(deco16_snd_irq);
oki_6295_0:=snd_okim6295.Create(sound_clock div 32,OKIM6295_PIN7_HIGH,2);
oki_6295_1:=snd_okim6295.Create(sound_clock div 16,OKIM6295_PIN7_HIGH,2);
end;
procedure deco16_snd_double_reset;
begin
h6280_0.reset;
ym2203_0.reset;
ym2151_0.reset;
oki_6295_0.reset;
oki_6295_1.reset;
deco16_sound_latch:=0;
end;
function deco16_double_snd_getbyte(direccion:dword):byte;
begin
case direccion of
0..$ffff:deco16_double_snd_getbyte:=mem_snd[direccion];
$100000:deco16_double_snd_getbyte:=ym2203_0.status;
$100001:deco16_double_snd_getbyte:=ym2203_0.Read;
$110001:deco16_double_snd_getbyte:=ym2151_0.status;
$120000..$120001:deco16_double_snd_getbyte:=oki_6295_0.read;
$130000..$130001:deco16_double_snd_getbyte:=oki_6295_1.read;
$140000..$140001:deco16_double_snd_getbyte:=deco16_sound_latch;
$1f0000..$1f1fff:deco16_double_snd_getbyte:=snd_ram[direccion and $1fff];
end;
end;
procedure deco16_double_snd_putbyte(direccion:dword;valor:byte);
begin
case direccion of
0..$ffff:; //ROM
$100000:ym2203_0.Control(valor);
$100001:ym2203_0.Write(valor);
$110000:ym2151_0.reg(valor);
$110001:ym2151_0.write(valor);
$120000..$120001:oki_6295_0.write(valor);
$130000..$130001:oki_6295_1.write(valor);
$1f0000..$1f1fff:snd_ram[direccion and $1fff]:=valor;
$1fec00..$1fec01:h6280_0.timer_w(direccion and $1,valor);
$1ff400..$1ff403:h6280_0.irq_status_w(direccion and $3,valor);
end;
end;
procedure deco16_double_sound;
begin
ym2151_0.update;
ym2203_0.Update;
oki_6295_0.update;
oki_6295_1.update;
end;
procedure deco16_snd_simple_init(cpu_clock,sound_clock:dword;sound_bank:cpu_outport_call);
begin
h6280_0:=cpu_h6280.create(cpu_clock,$100);
h6280_0.change_ram_calls(deco16_simple_snd_getbyte,deco16_simple_snd_putbyte);
h6280_0.init_sound(deco16_simple_sound);
ym2151_0:=ym2151_chip.create(sound_clock div 9);
ym2151_0.change_port_func(sound_bank);
ym2151_0.change_irq_func(deco16_snd_irq);
oki_6295_0:=snd_okim6295.Create(sound_clock div 32,OKIM6295_PIN7_HIGH,1);
end;
procedure deco16_snd_simple_reset;
begin
h6280_0.reset;
ym2151_0.reset;
oki_6295_0.reset;
deco16_sound_latch:=0;
end;
function deco16_simple_snd_getbyte(direccion:dword):byte;
begin
case direccion of
0..$ffff:deco16_simple_snd_getbyte:=mem_snd[direccion];
$110001:deco16_simple_snd_getbyte:=ym2151_0.status;
$120000..$120001:deco16_simple_snd_getbyte:=oki_6295_0.read;
$140000..$140001:deco16_simple_snd_getbyte:=deco16_sound_latch;
$1f0000..$1f1fff:deco16_simple_snd_getbyte:=snd_ram[direccion and $1fff];
end;
end;
procedure deco16_simple_snd_putbyte(direccion:dword;valor:byte);
begin
case direccion of
0..$ffff:; //ROM
$110000:ym2151_0.reg(valor);
$110001:ym2151_0.write(valor);
$120000..$120001:oki_6295_0.write(valor);
$1f0000..$1f1fff:snd_ram[direccion and $1fff]:=valor;
$1fec00..$1fec01:h6280_0.timer_w(direccion and $1,valor);
$1ff400..$1ff403:h6280_0.irq_status_w(direccion and $3,valor);
end;
end;
procedure deco16_snd_irq(irqstate:byte);
begin
h6280_0.set_irq_line(1,irqstate);
end;
procedure deco16_simple_sound;
begin
ym2151_0.update;
oki_6295_0.update;
end;
end.
|
unit DMPools;
interface
uses
System.SysUtils, System.Classes, System.Types, Generics.Collections, YWTypes;
type
TDataModuleClass = class of TDataModule;
TDataModuleHelper = class helper for TDataModule
procedure ReturnToPool;
procedure ResetPool;
procedure AfterGet; virtual;
procedure BeforeReturn; virtual;
end;
TDMHolder = class(TComponent)
protected
DestroyPool : Boolean;
AllocateTime : TDateTime;
public
function DM : TDataModule; virtual; abstract;
class function DMClass : TDataModuleClass; virtual; abstract;
class function GetFromPool:TDMHolder; virtual; abstract;
procedure ReturnToPool; virtual; abstract;
class procedure RegisterClass; virtual;
constructor Create; reintroduce; virtual;
end;
TDMHolder<T : TDataModule,constructor> = class(TDMHolder)
private
_DM : T;
public
class var Pool : TRingQueue512;
class var DestroyTime : TDateTime;
class function DMClass : TDataModuleClass; override;
class function GetFromPool:TDMHolder; override;
class procedure Return(D: TDMHolder); inline; static;
class destructor Done;
function DM : TDataModule; override;
procedure ReturnToPool; override;
constructor Create; override;
end;
TDMHolderClass = class of TDMHolder;
DMPool = class
private
type THolderRec = record
DC : TDataModuleClass;
HC : TDMHolderClass;
end;
class var
Pools : TList<THolderRec>;
class procedure RegisterClass(H : TDMHolderClass); static;
public
class function GetDM<T : TDataModule,constructor>:T; overload;
class function GetDM(C : TDataModuleClass) : TDataModule; overload;
class constructor Create;
class destructor Destroy;
end;
implementation
uses Threading;
{%CLASSGROUP 'System.Classes.TPersistent'}
{ DMPool }
class constructor DMPool.Create;
begin
Pools := TList<THolderRec>.Create;
end;
class destructor DMPool.Destroy;
begin
Pools.Free;
end;
class function DMPool.GetDM(C: TDataModuleClass): TDataModule;
var L : THolderRec;
R : TDMHolder;
begin
Result := nil;
for L in Pools do if L.DC=C then begin
R := L.HC.GetFromPool;
if R=nil then R := L.HC.Create;
Result := R.DM;
try
Result.AfterGet;
except on E: Exception do
end;
exit;
end;
end;
class function DMPool.GetDM<T>: T;
var R : TDMHolder<T>;
begin
R := TDMHolder<T>(TDMHolder<T>.GetFromPool);
if R=nil then R := TDMHolder<T>.Create;
Result := R._DM;
try
Result.AfterGet;
except on E: Exception do
end;
end;
class procedure DMPool.RegisterClass(H: TDMHolderClass);
var L : THolderRec;
begin
for L in Pools do if L.HC=H then exit;
L.DC := H.DMClass;
L.HC := H;
Pools.Add(L);
end;
{ TDataModuleHelper }
procedure TDataModuleHelper.AfterGet;
begin
end;
procedure TDataModuleHelper.BeforeReturn;
begin
end;
procedure TDataModuleHelper.ResetPool;
begin
if self.Owner is TDMHolder then begin
TDMHolder(Owner).DestroyPool := true;
TDMHolder(Owner).ReturnToPool;
end;
end;
procedure TDataModuleHelper.ReturnToPool;
begin
if self.Owner is TDMHolder then
TDMHolder(Owner).ReturnToPool;
end;
{ TDMHolder<T> }
constructor TDMHolder<T>.Create;
begin
inherited;
_DM := T(DMClass.Create(Self));
end;
function TDMHolder<T>.DM: TDataModule;
begin
Result := _DM;
end;
class function TDMHolder<T>.DMClass: TDataModuleClass;
begin
Result := T;
end;
class destructor TDMHolder<T>.Done;
var a : TDMHolder;
begin
a := TDMHolder(Pool.Get);
while a<>nil do begin
a.free;
a := TDMHolder(Pool.Get);
end;
end;
class function TDMHolder<T>.GetFromPool: TDMHolder;
begin
Result := TDMHolder(Pool.Get);
while (Result<>nil)and(Result.AllocateTime<DestroyTime) do begin
Result.Free;
Result := TDMHolder(Pool.Get);
end;
end;
class procedure TDMHolder<T>.Return(D: TDMHolder);
begin
if D.DestroyPool then begin
DestroyTime := Now;
D.Free;
TTask.Run(procedure begin
var a := TDMHolder(Pool.Get);
while (a<>nil)and(a.AllocateTime<DestroyTime) do begin
a.Free;
a := TDMHolder(Pool.Get);
end;
if (a<>nil)and(not Pool.Put(a)) then a.Free;
end);
end else if (D.AllocateTime<DestroyTime) or (not Pool.Put(D)) then D.Free;
end;
procedure TDMHolder<T>.ReturnToPool;
begin
try
_DM.BeforeReturn;
except
Free;
exit;
end;
Return(self);
end;
{ TDMHolder }
constructor TDMHolder.Create;
begin
inherited Create(nil);
AllocateTime := Now;
end;
class procedure TDMHolder.RegisterClass;
begin
DMPool.RegisterClass(self);
end;
end.
|
unit ChangeLoanNumberForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons,sLabel , sEdit, sBitBtn;
type
TfrmChangeLoanNumber = class(TForm)
lblText: TsLabel;
btnOk: TsBitBtn;
btnCancel: TsBitBtn;
edtNewNumber: TsEdit;
lblNumber: TsLabel;
Label1: TsLabel;
procedure btnOkClick(Sender: TObject);
procedure edtNewNumberChange(Sender: TObject);
private
FOldLoanNumber: string;
FNewLoanNumber: string;
procedure SetOldLoanNumber(const Value: string);
public
property OldLoanNumber:string read FOldLoanNumber write SetOldLoanNumber;
property NewLoanNumber:string read FNewLoanNumber;
end;
implementation
uses FFSUtils;
{$R *.DFM}
{ TForm1 }
procedure TfrmChangeLoanNumber.btnOkClick(Sender: TObject);
var NewNum : string;
begin
NewNum := RJust(edtNewNumber.Text,20);
try
if OldLoanNumber = NewNum then raise exception.create('Old Number and New Number can not be the same.');
FNewLoanNumber := NewNum;
ModalResult := mrOk;
except
on e:exception do MessageDlg(e.Message,mtInformation,[mbOk],0);
end;
end;
procedure TfrmChangeLoanNumber.SetOldLoanNumber(const Value: string);
begin
FOldLoanNumber := Value;
lblNumber.caption := trim(value);
end;
procedure TfrmChangeLoanNumber.edtNewNumberChange(Sender: TObject);
begin
btnOk.Enabled := trim(edtNewNumber.Text) > EmptyStr;
end;
end .
|
unit FeatureParser;
interface
uses
FeatureParserIntf, FeatureIntf, Classes;
type
TFeatureParser = class(TInterfacedObject, IFeatureParser)
private
FErrors: IInterfaceList;
FFeatureFileName: string;
FLoadedFeature: TStringList;
function GetErrors: IInterfaceList;
function GetFeatureFileName: string;
procedure SetFeatureFileName(const Value: string);
function LoadedFeature: TStringList;
procedure SetErrors(const Value: IInterfaceList);
public
destructor Destroy; override;
function Parse: IFeature;
property Errors: IInterfaceList read GetErrors write SetErrors;
property FeatureFileName: string read GetFeatureFileName write SetFeatureFileName;
end;
implementation
uses
Feature, SysUtils, Types, TypeUtils, Scenario, ScenarioIntf, StepIntf, Step, Constants, Error, FeatureError;
destructor TFeatureParser.Destroy;
begin
if FLoadedFeature <> nil then
FLoadedFeature.Free;
if FErrors <> nil then
begin
FErrors.Clear;
FErrors := nil;
end;
inherited;
end;
function TFeatureParser.GetErrors: IInterfaceList;
begin
if FErrors = nil then
FErrors := TInterfaceList.Create;
Result := FErrors;
end;
function TFeatureParser.GetFeatureFileName: string;
begin
Result := FFeatureFileName;
end;
function TFeatureParser.LoadedFeature: TStringList;
begin
if FLoadedFeature = nil then
FLoadedFeature := TStringList.Create;
if FileExists(FFeatureFileName) and (FLoadedFeature.Count = 0) then
FLoadedFeature.LoadFromFile(FFeatureFileName);
Result := FLoadedFeature;
end;
procedure TFeatureParser.SetFeatureFileName(const Value: string);
begin
FFeatureFileName := Value;
end;
function TFeatureParser.Parse: IFeature;
var
I, LFirstScenarioLine: Integer;
LFeatureLine: IXString;
LMatchData: IMatchData;
LSection: IXString;
LPrevSection: IXString;
LScenario: IScenario;
LStep: IStep;
begin
Result := TFeature.Create;
Errors.Clear;
if not FileExists(FFeatureFileName) then
begin
Errors.Add(TFeatureError.NewError(Format(InvalidFeatureFileName, [FFeatureFileName]), 0, SugestionToInvalidFeatureName));
Exit;
end;
LSection := SX('');
LPrevSection := SX('');
LFeatureLine := SX('');
LFeatureLine.Value := LoadedFeature[0];
LMatchData := LFeatureLine.MatchDataFor(FeatureRegex);
LFirstScenarioLine := 0;
if LMatchData <> nil then
begin
Result.Titulo := LMatchData.PostMatch.Value;
for I := 1 to LoadedFeature.Count - 1 do
begin
LFeatureLine.Value := LoadedFeature[I];
if not LFeatureLine.Match(ScenarioRegex) and not LFeatureLine.Trim.IsEmpty then
begin
LSection.Mais(LFeatureLine).Mais(#13#10);
Inc(LFirstScenarioLine);
end else
Break;
end;
Result.Descricao := LSection.Ate(LSection.Length - 3).Value;
end
else
begin
Errors.Add(TFeatureError.NewError(Format(InvalidFeature, [FFeatureFileName]), 1, SugestionToFeatureInitialize));
Exit;
end;
Inc(LFirstScenarioLine);
for I := LFirstScenarioLine to LoadedFeature.Count - 1 do
begin
LFeatureLine.Value := LoadedFeature[I];
if LFeatureLine.Trim.IsEmpty then
Continue;
LMatchData := LFeatureLine.MatchDataFor(ScenarioRegex);
if LMatchData <> nil then
begin
LScenario := TScenario.Create(LMatchData.PostMatch.AsClassName.Value);
LScenario.Titulo := LMatchData.PostMatch.Value;
Result.Scenarios.Add(LScenario);
Continue;
end;
LMatchData := LFeatureLine.MatchDataFor(StepRegex);
if LMatchData <> nil then
begin
LStep := TStep.Create;
LStep.Descricao := LMatchData.MatchedData.TrimLeft.Value;
(Result.Scenarios.Last as IScenario).Steps.Add(LStep);
Continue;
end;
if LFeatureLine.Match(StepValidWord) then
begin
Errors.Add(TFeatureError.NewError(Format(InvalidStepDefinition, [I + 1]), I + 1, Format(SugestionToStepInitialize, [LFeatureLine.MatchDataFor(FirstWordRegex).MatchedData.Value])));
Continue;
end;
if (LMatchData = nil) then
Errors.Add(TFeatureError.NewError(Format(InvalidStepIdentifierError, [I + 1, LFeatureLine.MatchDataFor(FirstWordRegex).MatchedData.Value]), I + 1, SugestedActionToStepError));
end;
end;
procedure TFeatureParser.SetErrors(const Value: IInterfaceList);
begin
FErrors := Value;
end;
end.
|
unit WorkJournalKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы WorkJournal }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\WorkJournal\Forms\WorkJournalKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "WorkJournalKeywordsPack" MUID: (4A811C620210_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, WorkJournal_Form
, tfwPropertyLike
, nscTreeViewWithAdapterDragDrop
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4A811C620210_Packimpl_uses*
//#UC END# *4A811C620210_Packimpl_uses*
;
type
TkwWorkJournalFormJournalTree = {final} class(TtfwPropertyLike)
{* Слово скрипта .TWorkJournalForm.JournalTree }
private
function JournalTree(const aCtx: TtfwContext;
aWorkJournalForm: TWorkJournalForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TWorkJournalForm.JournalTree }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwWorkJournalFormJournalTree
Tkw_Form_WorkJournal = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы WorkJournal
----
*Пример использования*:
[code]форма::WorkJournal TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_WorkJournal
Tkw_WorkJournal_Control_JournalTree = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола JournalTree
----
*Пример использования*:
[code]контрол::JournalTree TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_WorkJournal_Control_JournalTree
Tkw_WorkJournal_Control_JournalTree_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола JournalTree
----
*Пример использования*:
[code]контрол::JournalTree:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_WorkJournal_Control_JournalTree_Push
function TkwWorkJournalFormJournalTree.JournalTree(const aCtx: TtfwContext;
aWorkJournalForm: TWorkJournalForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TWorkJournalForm.JournalTree }
begin
Result := aWorkJournalForm.JournalTree;
end;//TkwWorkJournalFormJournalTree.JournalTree
class function TkwWorkJournalFormJournalTree.GetWordNameForRegister: AnsiString;
begin
Result := '.TWorkJournalForm.JournalTree';
end;//TkwWorkJournalFormJournalTree.GetWordNameForRegister
function TkwWorkJournalFormJournalTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwWorkJournalFormJournalTree.GetResultTypeInfo
function TkwWorkJournalFormJournalTree.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwWorkJournalFormJournalTree.GetAllParamsCount
function TkwWorkJournalFormJournalTree.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWorkJournalForm)]);
end;//TkwWorkJournalFormJournalTree.ParamsTypes
procedure TkwWorkJournalFormJournalTree.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству JournalTree', aCtx);
end;//TkwWorkJournalFormJournalTree.SetValuePrim
procedure TkwWorkJournalFormJournalTree.DoDoIt(const aCtx: TtfwContext);
var l_aWorkJournalForm: TWorkJournalForm;
begin
try
l_aWorkJournalForm := TWorkJournalForm(aCtx.rEngine.PopObjAs(TWorkJournalForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWorkJournalForm: TWorkJournalForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(JournalTree(aCtx, l_aWorkJournalForm));
end;//TkwWorkJournalFormJournalTree.DoDoIt
function Tkw_Form_WorkJournal.GetString: AnsiString;
begin
Result := 'WorkJournalForm';
end;//Tkw_Form_WorkJournal.GetString
class procedure Tkw_Form_WorkJournal.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TWorkJournalForm);
end;//Tkw_Form_WorkJournal.RegisterInEngine
class function Tkw_Form_WorkJournal.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::WorkJournal';
end;//Tkw_Form_WorkJournal.GetWordNameForRegister
function Tkw_WorkJournal_Control_JournalTree.GetString: AnsiString;
begin
Result := 'JournalTree';
end;//Tkw_WorkJournal_Control_JournalTree.GetString
class procedure Tkw_WorkJournal_Control_JournalTree.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_WorkJournal_Control_JournalTree.RegisterInEngine
class function Tkw_WorkJournal_Control_JournalTree.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::JournalTree';
end;//Tkw_WorkJournal_Control_JournalTree.GetWordNameForRegister
procedure Tkw_WorkJournal_Control_JournalTree_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('JournalTree');
inherited;
end;//Tkw_WorkJournal_Control_JournalTree_Push.DoDoIt
class function Tkw_WorkJournal_Control_JournalTree_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::JournalTree:push';
end;//Tkw_WorkJournal_Control_JournalTree_Push.GetWordNameForRegister
initialization
TkwWorkJournalFormJournalTree.RegisterInEngine;
{* Регистрация WorkJournalForm_JournalTree }
Tkw_Form_WorkJournal.RegisterInEngine;
{* Регистрация Tkw_Form_WorkJournal }
Tkw_WorkJournal_Control_JournalTree.RegisterInEngine;
{* Регистрация Tkw_WorkJournal_Control_JournalTree }
Tkw_WorkJournal_Control_JournalTree_Push.RegisterInEngine;
{* Регистрация Tkw_WorkJournal_Control_JournalTree_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TWorkJournalForm));
{* Регистрация типа TWorkJournalForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit uisplit;
interface
uses ui, uimpl, uihandle, uicomp, uipanel;
type
TWinSplit=class(TWinComp)
private
wSplitAlign:TAlign;
wWin1, wWin2:TWinComp;
wSplitActive:boolean;
protected
procedure SplitterPerform(deltaX,deltaY:integer);
public
constructor Create(Owner:TWinHandle);override;
procedure CreatePerform;override;
procedure SizePerform;override;
procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
procedure MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
procedure MouseMovePerform(AButtonControl:cardinal; x,y:integer);override;
procedure MouseLeavePerform;override;
procedure CapturePerform(AWindow:HWND);override;
property SplitAlign:TAlign read wSplitAlign write wSplitAlign;
property Win1:TWinComp read wWin1;
property Win2:TWinComp read wWin2;
end;
implementation
constructor TWinSplit.Create(Owner:TWinHandle);
begin
inherited;
wSplitActive:=false;
wSplitAlign:=alTop;
end;
procedure TWinSplit.CreatePerform;
begin
inherited;
wWin1:=TWinPanel.Create(self);
wWin2:=TWinPanel.Create(self);
if (wSplitAlign=alTop)or(wSplitAlign=alBottom)
then begin
wCursor:=crSizeNS;
wWin1.Align:=alTop;
wWin2.Align:=alBottom;
wWin1.Height:=Height div 2 - 2;
wWin2.Height:=Height div 2 - 2;
end
else begin
wCursor:=crSizeWE;
wWin1.Align:=alLeft;
wWin2.Align:=alRight;
wWin1.Width:=Width div 2 - 2;
wWin2.Width:=Width div 2 - 2;
end;
wWin1.CreatePerform;
wWin2.CreatePerform;
end;
procedure TWinSplit.SizePerform;
begin
case wSplitAlign of
alTop:wWin2.Height:=Height - wWin1.Height - 4;
alBottom:wWin1.Height:=Height - wWin2.Height - 4;
alLeft:wWin2.Width:=Width - wWin1.Width - 4;
alRight:wWin1.Width:=Width - wWin2.Width - 4;
end;
inherited;
end;
procedure TWinSplit.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
inherited;
if (AButton=mbLeft)
then begin
wSplitActive:=true;
SetCapture(window);
end;
end;
procedure TWinSplit.MouseButtonUpPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
inherited;
wSplitActive:=false;
ReleaseCapture();
end;
procedure TWinSplit.CapturePerform(AWindow:HWND);
begin
inherited;
wSplitActive := window = AWindow;
end;
procedure TWinSplit.MouseMovePerform(AButtonControl:cardinal; x,y:integer);
var p:tpoint;
begin
inherited;
if wSplitActive
then begin
case wSplitAlign of
alTop:wWin1.Height:=y - 2;
alBottom:wWin2.Height:=Height - y - 2;
alLeft:wWin1.Width:=x - 2;
alRight:wWin2.Width:=Width - x - 2;
end;
SizePerform;
end;
end;
procedure TWinSplit.MouseLeavePerform;
begin
inherited;
end;
procedure TWinSplit.SplitterPerform(deltaX,deltaY:integer);
var sp,i:integer;
comp:TWinHandle;
begin
sp:=-1;
for i:=0 to Parent.ChildHandleList.Count-1 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp=self
then begin
sp:=i;
break
end;
end;
if sp>-1
then begin
//todo if comp.Height-deltaY<comp.MinHeight then exit;
case align of
alLeft:begin
for i:=sp-1 downto 0 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alLeft
then begin
comp.Width:=comp.Width-deltaX;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
for i:=sp+1 to Parent.ChildHandleList.Count-1 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alLeft
then begin
comp.Left:=comp.Left-deltaX;
comp.SetPosPerform;
comp.SizePerform;
end;
if comp.Align=alClient
then begin
comp.Left:=comp.Left-deltaX;
comp.Width:=comp.Width+deltaX;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
Left:=Left-deltaX;
end;
alTop:begin
for i:=sp-1 downto 0 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alTop
then begin
comp.Height:=comp.Height-deltaY;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
for i:=sp+1 to Parent.ChildHandleList.Count-1 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alTop
then begin
comp.Top:=comp.Top-deltaY;
comp.SetPosPerform;
comp.SizePerform;
end;
if comp.Align=alClient
then begin
comp.Top:=comp.Top-deltaY;
comp.Height:=comp.Height+deltaY;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
Top:=Top-deltaY;
end;
alBottom:begin
for i:=sp-1 downto 0 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alBottom
then begin
comp.Top:=comp.Top-deltaY;
comp.Height:=comp.Height+deltaY;
comp.SetPosPerform;
comp.SizePerform;
end;
if comp.Align=alClient
then begin
comp.Height:=comp.Height-deltaY;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
for i:=sp+1 to Parent.ChildHandleList.Count-1 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alBottom
then begin
comp.Top:=comp.Top-deltaY;
comp.Height:=comp.Height+deltaY;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
Top:=Top-deltaY;
end;
alRight:begin
for i:=sp-1 downto 0 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alRight
then begin
comp.Left:=comp.Left-deltaX;
comp.SetPosPerform;
comp.SizePerform;
end;
if comp.Align=alClient
then begin
comp.Width:=comp.Width-deltaX;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
for i:=sp+1 to Parent.ChildHandleList.Count-1 do begin
comp:=TWinHandle(Parent.ChildHandleList[i]);
if comp.Align=alRight
then begin
comp.Left:=comp.Left-deltaX;
comp.Width:=comp.Width+deltaX;
comp.SetPosPerform;
comp.SizePerform;
break
end;
end;
Left:=Left-deltaX;
end;
end;
SetPosPerform;
SizePerform;
end;
end;
end.
|
unit uGioCreateDirectoryOperation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uFileSourceCreateDirectoryOperation,
uFileSource;
type
TGioCreateDirectoryOperation = class(TFileSourceCreateDirectoryOperation)
public
procedure MainExecute; override;
end;
implementation
uses
uFileSourceOperationUI, uLog, uLng, uGlobs, uGio2, uGLib2, uGObject2;
procedure TGioCreateDirectoryOperation.MainExecute;
var
AGFile: PGFile;
AResult: Boolean;
AError: PGError = nil;
begin
AGFile:= g_file_new_for_commandline_arg(Pgchar(AbsolutePath));
AResult:= g_file_make_directory_with_parents(AGFile, nil, @AError);
g_object_unref(PGObject(AGFile));
if Assigned(AError) then
begin
AResult:= g_error_matches (AError, g_io_error_quark(), G_IO_ERROR_EXISTS);
if not AResult then;
begin
if g_error_matches (AError, g_io_error_quark(), G_IO_ERROR_NOT_SUPPORTED) then
AskQuestion(rsMsgErrNotSupported, '', [fsourOk], fsourOk, fsourOk)
else begin
// write log error
if (log_vfs_op in gLogOptions) and (log_errors in gLogOptions) then
logWrite(Thread, Format(rsMsgLogError+rsMsgLogMkDir, [AbsolutePath]), lmtError);
end;
end;
g_error_free(AError);
end;
if AResult then
begin
// write log success
if (log_vfs_op in gLogOptions) and (log_success in gLogOptions) then
logWrite(Thread, Format(rsMsgLogSuccess+rsMsgLogMkDir, [AbsolutePath]), lmtSuccess)
end
end;
end.
|
unit uComunicaServer;
interface
uses
FGX.ProgressDialog, FMX.Dialogs, Data.FireDACJSONReflect;
type
TComunicaServer = class(TObject)
private
FvloProgresso: TfgActivityDialog;
FvlsMensagemErro: String;
procedure SetvloProgresso(const Value: TfgActivityDialog);
procedure SetvlsMensagemErro(const Value: String);
function retornaErroTimeOut(vlClassName, vlErro: String): String;
public
constructor Create();
destructor Destroy; override;
function fncValidaConexaoServidor : Boolean;
function fncValidaConexaoServidorSemMsg : Boolean;
procedure getListaCheques;
published
property vloProgresso : TfgActivityDialog read FvloProgresso write SetvloProgresso;
property vlsMensagemErro : String read FvlsMensagemErro write SetvlsMensagemErro;
end;
const
vlMsgErro = 'Não foi possível conectar-se ao servidor. Por favor verifique!';
implementation
{ TComunicaServer }
uses ClientClassesUnit1, System.Classes, ClientModuleUnit1, System.SysUtils,
udmPrincipal, uConfiguracao;
constructor TComunicaServer.Create;
begin
inherited;
end;
destructor TComunicaServer.Destroy;
begin
inherited;
end;
function TComunicaServer.fncValidaConexaoServidor: Boolean;
var
vloServico : TServerMethods1Client;
vlRetorno : String;
begin
TThread.CreateAnonymousThread(procedure ()
begin
FvloProgresso.show;
try
vloServico := TServerMethods1Client.Create(ClientModule1.DSRestConnection1);
try
vlRetorno := vloServico.fncTesteServidor();
Except
on e : exception do
begin
vlRetorno := '';
FvlsMensagemErro := e.message;
end;
end;
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
if vlRetorno = 'OK' then
ShowMessage('Comunicação com o servidor efetuada com sucesso!')
else
ShowMessage('Não foi possível efetuar a comunicação com servidor. Erro: ' + FvlsMensagemErro);
end);
finally
FvloProgresso.Hide;
if Assigned(vloServico) then
FreeAndNil(vloServico);
end;
end).Start;
end;
function TComunicaServer.fncValidaConexaoServidorSemMsg: Boolean;
var
vlservico : TServerMethods1Client;
vlRetorno : String;
begin
try
vlservico := TServerMethods1Client.Create(ClientModule1.DSRestConnection1);
try
vlRetorno := vlservico.fncTesteServidor();
Except
on e:exception do
begin
vlRetorno := '';
vlsMensagemErro := e.Message;
end;
end;
if vlRetorno = 'OK' then
begin
Result := True;
end
else
begin
Result := False;
end;
finally
if Assigned(vlservico) then
FreeAndNil(vlservico);
end;
end;
procedure TComunicaServer.getListaCheques;
begin
TThread.CreateAnonymousThread(procedure ()
var
vlServico : TServerMethods1Client;
vlRetornoServer : TFDJSONDataSets;
begin
try //finally
try
FvloProgresso.Message := 'Buscando informações do servidor...';
FvloProgresso.Show;
vlServico := TServerMethods1Client.Create(ClientModule1.DSRestConnection1);
if fncValidaConexaoServidorSemMsg then
begin
vlRetornoServer := vlServico.fncBuscaCheques();
dmPrincipal.FDMCheques.Active := False;
//Fazemos um teste para verifica se realmente há DataSets no retorno da função
Assert(TFDJSONDataSetsReader.GetListCount(vlRetornoServer) = 1);
//Adicionamos o conteúdo do DataSet "baixado" ao Memory Table
dmPrincipal.FDMCheques.AppendData(TFDJSONDataSetsReader.GetListValue(vlRetornoServer, 0));
if not dmPrincipal.FDMCheques.Active then
dmPrincipal.FDMCheques.Open;
// TThread.Synchronize (TThread.CurrentThread,
// procedure ()
// begin
// vlAppDao := TAppDAO.Create;
// try
// vlAppDao.carregaListaReprese(frmLogin.edtUsuario);
// finally
// FreeAndNil(vlAppDao);
// end;
// end);
end
else
begin
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
ShowMessage(vlsMensagemErro);
end);
end;
Except
on e :exception do
begin
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
{if e.ClassName = 'EIdSocketError' then
ShowMessage(vlMsgErro)
else
ShowMessage(e.Message + ' ' + e.ClassName);}
ShowMessage(retornaErroTimeOut(e.ClassName, e.Message));
FConfiguracao.Show;
end);
end;
end;
finally
FvloProgresso.Hide;
if Assigned(vlServico) then
FreeAndNil(vlServico);
if Assigned(vlRetornoServer) then
FreeAndNil(vlRetornoServer);
end;
end).Start;
end;
function TComunicaServer.retornaErroTimeOut(vlClassName, vlErro : String): String;
begin
if (Trim(vlClassName) = 'EIdSocketError') or
(Pos('TIMEOUT' , AnsiUpperCase(vlErro)) > 0) or
(Pos('TIME OUT', AnsiUpperCase(vlErro)) > 0) or
(Pos('FAILED TO CONNECT', AnsiUpperCase(vlErro)) > 0) then
begin
Result := vlMsgErro;
end
else
begin
Result := vlErro + ' ' + vlClassName;
end;
end;
procedure TComunicaServer.SetvloProgresso(const Value: TfgActivityDialog);
begin
FvloProgresso := Value;
end;
procedure TComunicaServer.SetvlsMensagemErro(const Value: String);
begin
FvlsMensagemErro := Value;
end;
end.
|
unit uContaEmailVO;
interface
uses
System.SysUtils;
type
TContaEmailVO = class
private
FEmail: string;
FAtivo: Boolean;
FCodigo: Integer;
FId: Integer;
FAutenticarSSL: Boolean;
FSMTP: string;
FSenha: string;
FPorta: Integer;
FNome: string;
FAutenticar: Boolean;
procedure SetAtivo(const Value: Boolean);
procedure SetAutenticar(const Value: Boolean);
procedure SetAutenticarSSL(const Value: Boolean);
procedure SetCodigo(const Value: Integer);
procedure SetEmail(const Value: string);
procedure SetId(const Value: Integer);
procedure SetNome(const Value: string);
procedure SetPorta(const Value: Integer);
procedure SetSenha(const Value: string);
procedure SetSMTP(const Value: string);
public
property Id: Integer read FId write SetId;
property Codigo: Integer read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Email: string read FEmail write SetEmail;
property Senha: string read FSenha write SetSenha;
property SMTP: string read FSMTP write SetSMTP;
property Porta: Integer read FPorta write SetPorta;
property Ativo: Boolean read FAtivo write SetAtivo;
property Autenticar: Boolean read FAutenticar write SetAutenticar;
property AutenticarSSL: Boolean read FAutenticarSSL write SetAutenticarSSL;
end;
implementation
{ TContaEmailVO }
procedure TContaEmailVO.SetAtivo(const Value: Boolean);
begin
FAtivo := Value;
end;
procedure TContaEmailVO.SetAutenticar(const Value: Boolean);
begin
FAutenticar := Value;
end;
procedure TContaEmailVO.SetAutenticarSSL(const Value: Boolean);
begin
FAutenticarSSL := Value;
end;
procedure TContaEmailVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TContaEmailVO.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TContaEmailVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TContaEmailVO.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TContaEmailVO.SetPorta(const Value: Integer);
begin
FPorta := Value;
end;
procedure TContaEmailVO.SetSenha(const Value: string);
begin
FSenha := Value;
end;
procedure TContaEmailVO.SetSMTP(const Value: string);
begin
FSMTP := Value;
end;
end.
|
unit cmdlinecfgjson;
{$mode delphi}
interface
uses
Classes, SysUtils, cmdlinecfg, fpjson, jsonparser;
function CmdLineCfgJSONReadFile(stream: TStream; cfg: TCmdLineCfg): Boolean; overload;
function CmdLineCfgJSONReadFile(const FileName: String; cfg: TCmdLineCfg): Boolean; overload;
procedure CmdLineCfgJSONLoadFilesFromDir(const Dir: String; list: TList; const Mask : string = '*.copt');
implementation
// ugh... no better way to do it anyway. ... see TValueIterator below
type
{ TCfgIterator }
TCfgIterator = class(TObject)
class procedure Iterate(Const AName : TJSONStringType; Item: TJSONData; Data: TObject; var DoContinue: Boolean);
class procedure IterateOption(Const AName : TJSONStringType; Item: TJSONData; Data: TObject; var DoContinue: Boolean);
class procedure IterateValue(const AName: TJSONStringType; Item: TJSONdata; Data: TObject; var DoContinue: Boolean);
end;
type
TIterateValue = class(TObject)
opt : TCmdLineCfgOption;
idx : Integer;
end;
class procedure TCfgIterator.IterateOption(Const AName : TJSONStringType; Item: TJSONData; Data: TObject; var DoContinue: Boolean);
var
opt : TCmdLineCfgOption;
nm : String;
ja : TJSONArray;
i : Integer;
iv : TIterateValue;
begin
opt:=TCmdLineCfgOption(Data);
nm:=lowerCase(AName);
if nm='section' then opt.Section:=Item.AsString
else if nm='subsection' then opt.SubSection:=Item.AsString
else if nm='type' then opt.OptType:=Item.AsString
else if nm='name' then opt.Name:=Item.AsString
else if nm='key' then opt.Key:=Item.AsString
else if nm='masterkey' then opt.MasterKey:=Item.AsString
else if nm='display' then opt.Display:=Item.AsString
else if (nm='condition') or (nm='cond') then opt.Condition:=Item.AsString
else if (nm='value') then opt.SetValue(Item.AsString)
else if (nm='alias') then opt.AliasToKey:=Item.AsString
else if (nm='multiple') then opt.isMultiple:=(Item.JSONType=jtBoolean) and (Item.AsBoolean)
else if (nm='options') then begin
ja:=TJSONArray(Item);
if ja.Count>0 then begin
iv:=TIterateValue.Create;
try
iv.opt:=opt;
for i:=0 to ja.Count-1 do begin
if ja.Items[i].JSONType = jtObject then begin
iv.idx:=opt.ValCount;
TJSONObject(ja.Items[i]).Iterate ( TCfgIterator.IterateValue, iv);
end;
end;
finally
iv.Free;
end;
end;
end
end;
class procedure TCfgIterator.IterateValue(const AName: TJSONStringType;
Item: TJSONdata; Data: TObject; var DoContinue: Boolean);
var
opt : TCmdLineCfgOption;
idx : Integer;
nm : String;
begin
idx:=TIterateValue(Data).idx;
opt:=TIterateValue(Data).opt;
nm:=lowerCase(AName);
if nm='display' then opt.SetValDisplay(Item.AsString, idx)
else if nm='value' then opt.SetValue(Item.AsString, idx)
else if nm='condition' then opt.SetCondition(Item.AsString, idx);
end;
class procedure TCfgIterator.Iterate(Const AName : TJSONStringType; Item: TJSONData; Data: TObject; var DoContinue: Boolean);
var
cfg : TCmdLineCfg;
nm : string;
ja : TJSONArray;
j : TJSONData;
i : Integer;
opt : TCmdLineCfgOption;
begin
cfg:=TCmdLineCfg(data);
nm:=lowerCase(AName);
if nm='options' then begin
if Item.JSONType<>jtArray then Exit; // options must be an array of options
ja:=TJSONArray(Item);
for i:=0 to ja.Count-1 do begin
j:=ja.Items[i];
if j.JSONType<>jtObject then Continue;
opt:=TCmdLineCfgOption.Create;
TJSONObject(j).Iterate(TCfgIterator.IterateOption, opt);
if (opt.Key='') then begin
opt.Free
end else begin
CmdLineOptionNormalize(opt);
cfg.Options.Add(opt);
end;
end;
end else begin
if Item.JSONType<>jtString then Exit;
if nm='executable' then cfg.Executable:=Item.AsString
else if nm='version' then cfg.Version:=Item.AsString
else if nm='fromversion' then cfg.FromVersion:=Item.AsString
else if nm='testvalue' then cfg.TestValue:=Item.AsString
else if nm='testkey' then cfg.TestKey:=Item.AsString
end;
end;
function CmdLineCfgJSONReadFile(stream: TStream; cfg: TCmdLineCfg): Boolean;
var
p : TJSONParser;
d : TJSONData;
core : TJSONObject;
begin
Result:=False;
d:=nil;
p:=TJSONParser.Create(stream);
try
d:=p.Parse;
if d.JSONType<>jtObject then Exit;
core:=TJSONObject(d);
core.Iterate(TCfgIterator.Iterate, cfg);
Result:=cfg.Executable<>'';
finally
d.Free;
p.Free;
end;
end;
function CmdLineCfgJSONReadFile(const FileName: String; cfg: TCmdLineCfg): Boolean;
var
fs : TFileStream;
begin
fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
Result:=CmdLineCfgJSONReadFile(fs, cfg);
finally
fs.Free;
end;
end;
procedure CmdLineCfgJSONLoadFilesFromDir(const Dir: String; list: TList; const Mask: string);
var
rslt : TSearchRec;
res : Integer;
pth : string;
cfg : TCmdLineCfg;
begin
pth:=IncludeTrailingPathDelimiter(Dir);
res:=FindFirst( pth+Mask, faAnyFile, rslt);
try
while res = 0 do begin
if (rslt.Attr and faDirectory=0) and (rslt.Size>0) then begin
cfg := TCmdLineCfg.Create;
if not CmdLineCfgJSONReadFile(pth+rslt.Name, cfg) then cfg.Free
else list.Add(cfg);
end;
res:=FindNext(rslt);
end;
finally
FindClose(rslt);
end;
end;
end.
|
unit EventType;
interface
uses
Pkg.Json.DTO, System.Generics.Collections, REST.Json.Types;
{$M+}
type
TEventTypes = class
private
FId: string;
[JSONName('label')]
FLabel: string;
FName: string;
FStatus: string;
published
property Id: string read FId write FId;
property &Label: string read FLabel write FLabel;
property Name: string read FName write FName;
property Status: string read FStatus write FStatus;
end;
TRootDTO = class(TJsonDTO)
private
[JSONName('eventTypes')]
FEventTypesArray: TArray<TEventTypes>;
[GenericListReflect]
FEventTypes: TObjectList<TEventTypes>;
function GetEventTypes: TObjectList<TEventTypes>;
published
property EventTypes: TObjectList<TEventTypes> read GetEventTypes;
destructor Destroy; override;
end;
implementation
{ TRootDTO }
destructor TRootDTO.Destroy;
begin
GetEventTypes.Free;
inherited;
end;
function TRootDTO.GetEventTypes: TObjectList<TEventTypes>;
begin
if not Assigned(FEventTypes) then
begin
FEventTypes := TObjectList<TEventTypes>.Create;
FEventTypes.AddRange(FEventTypesArray);
end;
Result := FEventTypes;
end;
end.
|
unit evSimpleTextPainter;
{* Класс для раскраски строк текста. Без нарезки на строки. И без форматирования таблиц в псевдографику. Для решения задачи [$91848978]. }
// Модуль: "w:\common\components\gui\Garant\Everest\evSimpleTextPainter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevSimpleTextPainter" MUID: (4836C450038D)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evCustomTextFormatter
, k2Base
, k2DocumentGenerator
, l3Variant
;
type
TevSimpleTextPainter = class(TevCustomTextFormatter)
{* Класс для раскраски строк текста. Без нарезки на строки. И без форматирования таблиц в псевдографику. Для решения задачи [$91848978]. }
private
f_InCell: Integer;
f_OldNSRC: Integer;
{* Пишем таблицы в старом формате NSRC }
f_TableType: Tk2Type;
{* Тип таблицы }
f_Zoom: Integer;
{* Масштаб }
f_WasSoftEnter: Boolean;
private
function NeedTranslateToNext(const anAtom: Tk2StackAtom): Boolean;
protected
function OpenTableIfNeeded: Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure DoStartAtom(var Atom: Tk2StackAtom); override;
procedure DoFinishAtom(var anAtom: Tk2StackAtom); override;
function DoBeforeFinishAtom(var Atom: Tk2StackAtom): Boolean; override;
procedure DoAddAtom(const Atom: Tk2StackAtom;
Prop: Integer;
aSource: Tl3Variant); override;
procedure AddAtom(AtomIndex: Integer;
aValue: Tl3Variant); override;
procedure StartChild(TypeID: Tl3Type); override;
procedure StartTag(TagID: Integer); override;
procedure CloseStructure(NeedUndo: Boolean); override;
{* вызывается на закрывающуюся "скобку". Для перекрытия в потомках. }
function NeedAddSpaces: Boolean; override;
end;//TevSimpleTextPainter
implementation
uses
l3ImplUses
, k2Tags
, TextPara_Const
, Document_Const
, ObjectSegment_Const
, TableCell_Const
, Table_Const
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, k2Facade
, l3CustomString
, evNSRCConst
, l3String
, l3Chars
, SBS_Const
, k2Interfaces
//#UC START# *4836C450038Dimpl_uses*
//#UC END# *4836C450038Dimpl_uses*
;
function TevSimpleTextPainter.OpenTableIfNeeded: Boolean;
//#UC START# *4AFAD5860039_4836C450038D_var*
var
l_TableType : Tk2Type;
//#UC END# *4AFAD5860039_4836C450038D_var*
begin
//#UC START# *4AFAD5860039_4836C450038D_impl*
Result := (f_TableType <> nil);
if Result then
begin
l_TableType := f_TableType;
f_TableType := nil;
inherited StartChild(l_TableType);
if (f_Zoom <> 0) then
begin
Generator.AddIntegerAtom(k2_tiZoom, f_Zoom);
f_Zoom := 0;
end;//f_Zoom <> 0
end;//Result
//#UC END# *4AFAD5860039_4836C450038D_impl*
end;//TevSimpleTextPainter.OpenTableIfNeeded
function TevSimpleTextPainter.NeedTranslateToNext(const anAtom: Tk2StackAtom): Boolean;
//#UC START# *4836E100028A_4836C450038D_var*
//#UC END# *4836E100028A_4836C450038D_var*
begin
//#UC START# *4836E100028A_4836C450038D_impl*
if anAtom.IsKindOf(k2_typTextPara) then
begin
with anAtom do
if ((Parent = nil) OR not Parent.IsKindOf(k2_typObjectSegment)) then
Result := false
else
Result := true;
end
else
Result := true;
//#UC END# *4836E100028A_4836C450038D_impl*
end;//TevSimpleTextPainter.NeedTranslateToNext
procedure TevSimpleTextPainter.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4836C450038D_var*
//#UC END# *479731C50290_4836C450038D_var*
begin
//#UC START# *479731C50290_4836C450038D_impl*
f_WasSoftEnter := false;
f_InCell := 0;
f_OldNSRC := 0;
f_TableType := nil;
f_Zoom := 0;
inherited;
//#UC END# *479731C50290_4836C450038D_impl*
end;//TevSimpleTextPainter.Cleanup
procedure TevSimpleTextPainter.DoStartAtom(var Atom: Tk2StackAtom);
//#UC START# *4836B39C025E_4836C450038D_var*
//#UC END# *4836B39C025E_4836C450038D_var*
begin
//#UC START# *4836B39C025E_4836C450038D_impl*
if (f_OldNSRC > 0) then
inherited
else
begin
if Atom.IsKindOf(k2_typTableCell) then
Inc(f_InCell);
if not f_InTextPara then
begin
if Atom.IsKindOf(k2_typDocument) then
begin
f_SectionWidth := CharsInLine;
f_InCell := 0;
end
else
f_InTextPara := not NeedTranslateToNext(Atom);
if not f_InTextPara then
begin
if Atom.IsChild then
Generator.StartChild(Atom.TagType)
else
Generator.StartTag(Atom.TagID);
end;//not f_InTextPara
end;//not f_InTextPara
end;//f_OldNSRC
//#UC END# *4836B39C025E_4836C450038D_impl*
end;//TevSimpleTextPainter.DoStartAtom
procedure TevSimpleTextPainter.DoFinishAtom(var anAtom: Tk2StackAtom);
//#UC START# *4836B3A70291_4836C450038D_var*
//#UC END# *4836B3A70291_4836C450038D_var*
begin
//#UC START# *4836B3A70291_4836C450038D_impl*
if (f_OldNSRC > 0) then
inherited
else
begin
if anAtom.IsKindOf(k2_typTableCell) then
Dec(f_InCell);
if not f_InTextPara AND NeedTranslateToNext(anAtom) then
Generator.Finish;
end;//f_OldNSRC
if anAtom.IsKindOf(k2_typTextPara) then
f_WasSoftEnter := false;
//#UC END# *4836B3A70291_4836C450038D_impl*
end;//TevSimpleTextPainter.DoFinishAtom
function TevSimpleTextPainter.DoBeforeFinishAtom(var Atom: Tk2StackAtom): Boolean;
//#UC START# *4836B3B80074_4836C450038D_var*
//#UC END# *4836B3B80074_4836C450038D_var*
begin
//#UC START# *4836B3B80074_4836C450038D_impl*
if (f_OldNSRC > 0) then
Result := inherited DoBeforeFinishAtom(Atom)
else
begin
Result := NeedTranslateToNext(Atom);
if not Result then
DoFinishTextPara(Atom);
end;//f_OldNSRC
//#UC END# *4836B3B80074_4836C450038D_impl*
end;//TevSimpleTextPainter.DoBeforeFinishAtom
procedure TevSimpleTextPainter.DoAddAtom(const Atom: Tk2StackAtom;
Prop: Integer;
aSource: Tl3Variant);
//#UC START# *4836B3DB01C9_4836C450038D_var*
//#UC END# *4836B3DB01C9_4836C450038D_var*
begin
//#UC START# *4836B3DB01C9_4836C450038D_impl*
if (f_OldNSRC > 0) then
inherited
else
if not f_InTextPara then
Generator.AddAtom(Prop, aSource);
//#UC END# *4836B3DB01C9_4836C450038D_impl*
end;//TevSimpleTextPainter.DoAddAtom
procedure TevSimpleTextPainter.AddAtom(AtomIndex: Integer;
aValue: Tl3Variant);
//#UC START# *4836D26F0055_4836C450038D_var*
var
l_Text : Tl3CustomString;
//#UC END# *4836D26F0055_4836C450038D_var*
begin
//#UC START# *4836D26F0055_4836C450038D_impl*
if (f_OldNSRC > 0) then
inherited
else
begin
if (AtomIndex = k2_tiOldNSRC) then
begin
if (f_TableType <> nil) then
begin
(* Case TK of
k2_tkObject :
begin*)
{$IFNDEF evOldNSRCTableOff}
if (aValue.AsLong <> 0) then
Inc(f_OldNSRC);
{$ENDIF evOldNSRCTableOff}
(* end;//k2_tkObject
else
begin
Assert(TK in [k2_tkInteger, k2_tkBool]);
{$IFNDEF evOldNSRCTableOff}
if (Integer(Value) <> 0) then
Inc(f_OldNSRC);
{$ENDIF evOldNSRCTableOff}
end;//else
end;//Case TK of*)
if (f_OldNSRC > 0) then
OpenTableIfNeeded;
end;//f_TableType <> nil
end//AtomIndex = k2_tiOldNSRC
else
if (AtomIndex = k2_tiZoom) then
begin
if (f_TableType <> nil) then
begin
(* Case TK of
k2_tkObject :*)
f_Zoom := aValue.AsLong;
(* else
begin
Assert(TK = k2_tkInteger);
f_Zoom := Integer(Value);
end;//else
end;//Case TK of*)
end;//f_TableType <> nil
end//(AtomIndex = k2_tiZoom)
else
begin
OpenTableIfNeeded;
// - любой другой атом открывает отложенную таблицу
if (AtomIndex = k2_tiData) then
begin
// - пусть картинки обрабатывает предок
inherited;
Exit;
end//AtomIndex = k2_tiData
else
if (AtomIndex = k2_tiText) then
begin
if not (f_OldNSRC > 0)
//AND (f_InCell > 0)
then
begin
// Assert(TK = k2_tkObject);
l_Text := aValue As Tl3CustomString;
f_WasSoftEnter := l3HasChar(cc_SoftEnter, l_Text.AsWStr);
if f_WasSoftEnter then
l3Replace(l_Text.AsWStr, [cc_SoftEnter], ev_NSRCSoftEnter);
end;//not f_OldNSRC AND (f_InCell > 0)
end;//AtomIndex = k2_tiText
if not f_InTextPara then
Generator.AddAtom(AtomIndex, aValue)
else
AddAtomToDocument(AtomIndex, aValue);
end;//AtomIndex = k2_tiOldNSRC
end;//f_OldNSRC
//#UC END# *4836D26F0055_4836C450038D_impl*
end;//TevSimpleTextPainter.AddAtom
procedure TevSimpleTextPainter.StartChild(TypeID: Tl3Type);
//#UC START# *4836D4650177_4836C450038D_var*
//#UC END# *4836D4650177_4836C450038D_var*
begin
//#UC START# *4836D4650177_4836C450038D_impl*
OpenTableIfNeeded;
if TypeID.IsKindOf(k2_typTable) AND
not TypeID.IsKindOf(k2_typSBS) then
begin
if not (f_OldNSRC > 0) then
begin
Assert(f_TableType = nil);
f_TableType := Tk2TYpe(TypeID);
Exit;
end;//not (f_OldNSRC > 0)
end;//k2.TypeTable[TypeID].IsKindOf(k2_typTable)
inherited;
//#UC END# *4836D4650177_4836C450038D_impl*
end;//TevSimpleTextPainter.StartChild
procedure TevSimpleTextPainter.StartTag(TagID: Integer);
//#UC START# *4836D477022A_4836C450038D_var*
//#UC END# *4836D477022A_4836C450038D_var*
begin
//#UC START# *4836D477022A_4836C450038D_impl*
OpenTableIfNeeded;
inherited;
//#UC END# *4836D477022A_4836C450038D_impl*
end;//TevSimpleTextPainter.StartTag
procedure TevSimpleTextPainter.CloseStructure(NeedUndo: Boolean);
{* вызывается на закрывающуюся "скобку". Для перекрытия в потомках. }
//#UC START# *4836D4C20059_4836C450038D_var*
var
l_C : PevStackAtom;
l_ClearOldNSRC : Boolean;
//#UC END# *4836D4C20059_4836C450038D_var*
begin
//#UC START# *4836D4C20059_4836C450038D_impl*
l_ClearOldNSRC := false;
if (f_OldNSRC > 0) then
begin
l_C := Tags.Top;
if (l_C <> nil) then
if l_C.IsKindOf(k2_typTable) then
// if not evInPara(l_C.Parent.Box, k2_idTable) then
if not evInPara(l_C.Parent.Box, k2_typTableCell) then
// - проверяем не вложенная ли это таблица
l_ClearOldNSRC := true;
end;//f_OldNSRC
if not (f_OldNSRC > 0) AND (f_TableType <> nil) then
// - наверное это таблица без детей как в http://mdp.garant.ru/pages/viewpage.action?pageId=224135562
begin
Assert(f_InCell = 0);
f_TableType := nil;
if (CurrentStartLevel = OpenStreamLevel) then
Inc(f_Starts);
// - это хак, но иначе падает на пустой таблице в начале документа
Exit;
end;//not f_OldNSRC AND (f_TableType <> nil)
inherited;
if (f_OldNSRC > 0) AND l_ClearOldNSRC then
begin
PrevTable := nil;
Dec(f_OldNSRC);
end;//f_OldNSRC
//#UC END# *4836D4C20059_4836C450038D_impl*
end;//TevSimpleTextPainter.CloseStructure
function TevSimpleTextPainter.NeedAddSpaces: Boolean;
//#UC START# *4A116B45039B_4836C450038D_var*
//#UC END# *4A116B45039B_4836C450038D_var*
begin
//#UC START# *4A116B45039B_4836C450038D_impl*
{$IfDef evOutDecorToNSRC}
if (f_OldNSRC > 0) then
Result := inherited NeedAddSpaces
else
Result := false;
{$Else evOutDecorToNSRC}
if (f_OldNSRC > 0) then
Result := inherited NeedAddSpaces
else
Result := (f_InCell = 0) AND not f_WasSoftEnter;
{$EndIf evOutDecorToNSRC}
//#UC END# *4A116B45039B_4836C450038D_impl*
end;//TevSimpleTextPainter.NeedAddSpaces
end.
|
unit alcuMultiOperationRequest;
// Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuMultiOperationRequest.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TalcuMultiOperationRequest" MUID: (57F206DC02EB)
{$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc}
interface
{$If Defined(ServerTasks)}
uses
l3IntfUses
, alcuWaitableRequest
{$If NOT Defined(Nemesis)}
, csMultiOperation
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
, csMultiOperationReply
{$IfEnd} // NOT Defined(Nemesis)
, k2Base
{$If NOT Defined(Nemesis)}
, ddProcessTaskPrim
{$IfEnd} // NOT Defined(Nemesis)
;
type
TalcuMultiOperationRequest = class(TalcuWaitableRequest)
private
f_Message: TcsMultiOperation;
f_Reply: TcsMultiOperationReply;
protected
procedure pm_SetMessage(aValue: TcsMultiOperation);
procedure pm_SetReply(aValue: TcsMultiOperationReply);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
{$If NOT Defined(Nemesis)}
procedure DoRun(const aContext: TddRunContext); override;
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
procedure DoAbort; override;
{$IfEnd} // NOT Defined(Nemesis)
public
class function GetTaggedDataType: Tk2Type; override;
public
property Message: TcsMultiOperation
read f_Message
write pm_SetMessage;
property Reply: TcsMultiOperationReply
read f_Reply
write pm_SetReply;
end;//TalcuMultiOperationRequest
{$IfEnd} // Defined(ServerTasks)
implementation
{$If Defined(ServerTasks)}
uses
l3ImplUses
, l3Types
, l3StopWatch
, SysUtils
, TypInfo
, l3Base
, l3IDList
, arDirectMultiOperationHelper
, l3MarshalledTypes
{$If NOT Defined(Nemesis)}
, dtIntf
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
, dt_Sab
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
, dt_Doc
{$IfEnd} // NOT Defined(Nemesis)
, evdTasksHelpers
, l3DatLst
, MultiOperationRequest_Const
//#UC START# *57F206DC02EBimpl_uses*
//#UC END# *57F206DC02EBimpl_uses*
;
procedure TalcuMultiOperationRequest.pm_SetMessage(aValue: TcsMultiOperation);
//#UC START# *57F207570275_57F206DC02EBset_var*
//#UC END# *57F207570275_57F206DC02EBset_var*
begin
//#UC START# *57F207570275_57F206DC02EBset_impl*
aValue.SetRefTo(f_Message);
//#UC END# *57F207570275_57F206DC02EBset_impl*
end;//TalcuMultiOperationRequest.pm_SetMessage
procedure TalcuMultiOperationRequest.pm_SetReply(aValue: TcsMultiOperationReply);
//#UC START# *57F20770026C_57F206DC02EBset_var*
//#UC END# *57F20770026C_57F206DC02EBset_var*
begin
//#UC START# *57F20770026C_57F206DC02EBset_impl*
aValue.SetRefTo(f_Reply);
//#UC END# *57F20770026C_57F206DC02EBset_impl*
end;//TalcuMultiOperationRequest.pm_SetReply
procedure TalcuMultiOperationRequest.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_57F206DC02EB_var*
//#UC END# *479731C50290_57F206DC02EB_var*
begin
//#UC START# *479731C50290_57F206DC02EB_impl*
FreeAndNil(f_Message);
FreeAndNil(f_Reply);
inherited;
//#UC END# *479731C50290_57F206DC02EB_impl*
end;//TalcuMultiOperationRequest.Cleanup
{$If NOT Defined(Nemesis)}
procedure TalcuMultiOperationRequest.DoRun(const aContext: TddRunContext);
//#UC START# *53A2EEE90097_57F206DC02EB_var*
var
l_Helper: TarDirectMultiOperationHelper;
l_Counter: Tl3StopWatch;
l_Sab: ISab;
l_RejectedList: RejectedIDListHelper;
l_DataList: Tl3StringDataList;
l_ID: Cardinal;
l_IDX: Integer;
//#UC END# *53A2EEE90097_57F206DC02EB_var*
begin
//#UC START# *53A2EEE90097_57F206DC02EB_impl*
l_Counter.Reset;
l_Counter.Start;
try
try
DocumentServer.Family := f_Message.FamilyID;
l_Sab := MakeValueSet(DocumentServer.FileTbl, fID_Fld, f_Message.DocumentIDList);
try
l_Helper := TarDirectMultiOperationHelper.Create(f_Message.FamilyID, f_Message.Operation, l_Sab);
finally
l_Sab := nil;
end;
try
l_Helper.ModifyDocs;
f_Reply.ProcessedCount := l_Helper.ProcessedDocsCount;
if l_Helper.HasErrorDocs then
begin
l_RejectedList := f_Reply.RejectedIDList;
l_DataList := Tl3StringDataList.Create;
try
l_Helper.FillErrorDocsList(l_DataList);
Assert(l_DataList.DataSize <= SizeOf(l_ID));
for l_IDX := 0 to l_DataList.Count - 1 do
begin
l_ID := 0;
System.Move(l_DataList.Data[l_IDX]^, l_ID, l_DataList.DataSize);
l_RejectedList.Add(l_ID, l_DataList.PasStr[l_IDX]);
end;
finally
FreeAndNil(l_DataList);
end;
end;
finally
FreeAndNil(l_Helper);
end;
f_Reply.ErrorMessage := '';
f_Reply.IsSuccess := True;
except
on E: Exception do
begin
f_Reply.ErrorMessage := E.Message;
f_Reply.IsSuccess := False;
l3System.Exception2Log(E);
end;
end;
finally
l_Counter.Stop;
SignalReady;
l3System.Msg2Log('Remote multioperation (%s) exec - %s', [GetEnumName(TypeInfo(TarMultiOperation), Ord(f_Message.Operation)), FormatFloat('#,##0 ms', l_Counter.Time * 1000)], l3_msgLevel10);
end;
//#UC END# *53A2EEE90097_57F206DC02EB_impl*
end;//TalcuMultiOperationRequest.DoRun
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
procedure TalcuMultiOperationRequest.DoAbort;
//#UC START# *57C4135700F7_57F206DC02EB_var*
//#UC END# *57C4135700F7_57F206DC02EB_var*
begin
//#UC START# *57C4135700F7_57F206DC02EB_impl*
f_Reply.ErrorMessage := 'Операция прервана';
SignalReady;
//#UC END# *57C4135700F7_57F206DC02EB_impl*
end;//TalcuMultiOperationRequest.DoAbort
{$IfEnd} // NOT Defined(Nemesis)
class function TalcuMultiOperationRequest.GetTaggedDataType: Tk2Type;
begin
Result := k2_typMultiOperationRequest;
end;//TalcuMultiOperationRequest.GetTaggedDataType
{$IfEnd} // Defined(ServerTasks)
end.
|
unit TestUnmarshalOptimizationParametersUnit;
interface
uses
TestFramework, SysUtils,
TestBaseJsonUnmarshalUnit,
IOptimizationParametersProviderUnit;
type
TTestUnmarshalOptimizationParameters = class(TTestBaseJsonUnmarshal)
private
procedure CheckEquals(Etalon: IOptimizationParametersProvider; TestName: String);
published
procedure SingleDriverRoute10Stops();
end;
implementation
{ TTestOptimizationParametersToJson }
uses
Classes, System.JSON,
SingleDriverRoute10StopsTestDataProviderUnit,
OptimizationParametersUnit, MarshalUnMarshalUnit;
procedure TTestUnmarshalOptimizationParameters.CheckEquals(
Etalon: IOptimizationParametersProvider; TestName: String);
var
ActualList: TStringList;
Actual: TOptimizationParameters;
JsonFilename: String;
OptimizationParameters: TOptimizationParameters;
JsonValue: TJSONValue;
begin
JsonFilename := EtalonFilename(TestName);
ActualList := TStringList.Create;
try
ActualList.LoadFromFile(JsonFilename);
OptimizationParameters := Etalon.OptimizationParametersForResponse;
try
JsonValue := TJSONObject.ParseJSONValue(ActualList.Text);
try
Actual := TMarshalUnMarshal.FromJson(
OptimizationParameters.ClassType, JsonValue) as TOptimizationParameters;
finally
FreeAndNil(JsonValue);
end;
CheckTrue(OptimizationParameters.Equals(Actual));
finally
FreeAndNil(OptimizationParameters);
end;
finally
FreeAndNil(ActualList);
end;
Etalon := nil;
end;
procedure TTestUnmarshalOptimizationParameters.SingleDriverRoute10Stops;
begin
CheckEquals(
TSingleDriverRoute10StopsTestDataProvider.Create,
'OptimizationParametersFromJson\SingleDriverRoute10Stops');
end;
initialization
// Register any test cases with the test runner
RegisterTest('JSON\Unmarshal\', TTestUnmarshalOptimizationParameters.Suite);
end.
|
unit uValidaSerial;
interface
uses System.SysUtils;
function validarSerial(Serial: string; cnpj: string): TDate;
implementation
uses uAuxValidacao;
var
Serial: string;
procedure setSerial(pSerial: string);
begin
Serial := StringReplace(pSerial, '-', '', [rfReplaceAll]);
end;
function getSerial(): string;
begin
Result := Serial;
end;
function getPrimeiraSequencia(): string;
begin
Result := Copy(getSerial, 1, 4);
end;
function getSegundaSequencia(): string;
begin
Result := Copy(getSerial, 5, 4);
end;
function getTerceiraSequencia(): string;
begin
Result := Copy(getSerial, 9, 4);
end;
function inverterDataValidade(dataValidade: string): TDate;
begin
dataValidade := Copy(dataValidade, 4, 1) + Copy(dataValidade, 3, 1) +
Copy(dataValidade, 2, 1) + Copy(dataValidade, 1, 1);
Result := StrToDateDef('20' + '/' + Copy(dataValidade, 1, 2) + '/' +
Copy(dataValidade, 3, 2), 0);
end;
function buscarPrimeiraSequenciaTratada(primeiraSequencia: string;
totalCNPJ: Integer): string;
begin
Result := FormatFloat('0000', (StrToInt(primeiraSequencia) + 854 +
totalCNPJ));
Result := Copy(Result, 1, 3);
end;
function buscarSegundaSequenciaTratada(): string;
begin
Result := FormatFloat('0000', (StrToInt(getSegundaSequencia()) + 437));
end;
// Se retornar uma data entao é validade, se retornar zero entao é inválida
function validarSerial(Serial: string; cnpj: string): TDate;
var
primeiraSeq: string;
segundaSeq: string;
terceiraSeq: string;
primeiraSequenciaSomada: string[4];
segundaSequenciaSomada: string[4];
segundaSequenciaValida: Boolean;
terceiraSequenciaValida: Boolean;
totalCNPJ: Integer;
begin
setSerial(Serial);
primeiraSeq := getPrimeiraSequencia();
segundaSeq := getSegundaSequencia();
terceiraSeq := getTerceiraSequencia();
totalCNPJ := StrToInt(resultadoCnpj(cnpj));
primeiraSequenciaSomada := buscarPrimeiraSequenciaTratada(primeiraSeq,
totalCNPJ);
segundaSequenciaSomada := buscarSegundaSequenciaTratada();
segundaSequenciaValida := Copy(segundaSeq, 1, 3) = primeiraSequenciaSomada;
terceiraSequenciaValida := terceiraSeq = segundaSequenciaSomada;
if segundaSequenciaValida and terceiraSequenciaValida then
Result := inverterDataValidade(primeiraSeq);
end;
end.
|
unit DAO.Sistemas;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Sistemas, Control.Sistema;
type
TSistemasDAO = class
private
FConexao : TConexao;
public
constructor Create;
function Inserir(ASistemas: TSistemas): Boolean;
function Alterar(ASistemas: TSistemas): Boolean;
function Excluir(ASistemas: TSistemas): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'seguranca_sistemas';
implementation
{ TSistemasDAO }
function TSistemasDAO.Alterar(ASistemas: TSistemas): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DES_SISTEMA = :PDES_SISTEMA WHERE COD_SISTEMA = :PCOD_SISTEMA',
[ASistemas.Descricao, ASistemas.Codigo]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TSistemasDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TSistemasDAO.Excluir(ASistemas: TSistemas): Boolean;
var
FDQuery : TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery;
Result := False;
FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE COD_SISTEMA = :PCOD_SISTEMA', [ASistemas.Codigo]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TSistemasDAO.Inserir(ASistemas: TSistemas): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' (COD_SISTEMA, DES_SISTEMA) VALUES (:PCOD_SISTEMA, :PDES_SISTEMA)',
[ASistemas.Codigo, ASistemas.Descricao]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TSistemasDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA');
FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1];
end;
if aParam[0] = 'DESCRICAO' then
begin
FDQuery.SQL.Add('WHERE DES_SISTEMA = :PDES_SISTEMA');
FDQuery.ParamByName('PDES_SISTEMA').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
end.
|
unit f2ScnSplash;
interface
uses
d2dTypes,
d2dInterfaces,
d2dSprite,
d2dApplication,
f2Application,
f2Scene;
type
Tf2SplashScene = class(Tf2Scene)
private
f_Logo: Td2dSprite;
f_CurCol: Single;
f_Pause: Single;
f_Speed: Integer;
f_Version: string;
f_VFont: Id2dFont;
f_VX: Integer;
f_VY: Integer;
f_BGColor: Td2dColor;
f_LogoX, f_LogoY: Integer;
protected
procedure DoLoad; override;
procedure DoUnload; override;
procedure DoFrame(aDelta: Single); override;
procedure DoRender; override;
end;
implementation
uses
SysUtils,
JclFileUtils,
SimpleXML,
d2dCore,
f2Skins,
f2FontLoad;
procedure Tf2SplashScene.DoLoad;
var
l_VI : TJclFileVersionInfo;
l_Size: Td2dPoint;
l_Root, l_Node: IxmlNode;
l_VColor: Td2dColor;
l_Tex : Id2dTexture;
l_TexX, l_TexY, l_Width, l_Height: Integer;
l_IsCustomLogo: Boolean;
begin
l_IsCustomLogo := False;
l_VColor := $FFEE9A00;
l_Root := F2App.Skin.XML.DocumentElement.SelectSingleNode('splash');
if l_Root <> nil then
begin
f_BGColor := Td2dColor(l_Root.GetHexAttr('bgcolor'));
l_VColor := Td2dColor(l_Root.GetHexAttr('vcolor', $FFEE9A00));
l_Node := l_Root.SelectSingleNode('logo');
if l_Node <> nil then
begin
l_Tex := F2App.Skin.Textures[l_Node.GetAttr('tex')];
if l_Tex <> nil then
begin
l_TexX := l_Node.GetIntAttr('tx');
l_TexY := l_Node.GetIntAttr('ty');
l_Width := l_Node.GetIntAttr('width');
l_Height := l_Node.GetIntAttr('height');
if (l_Width > 0) and (l_Height > 0) then
begin
f_Logo := Td2dSprite.Create(l_Tex, l_TexX, l_TexY, l_Width, l_Height);
l_IsCustomLogo := True;
end;
end;
end;
end;
if f_Logo = nil then
f_Logo := Td2dSprite.Create(F2App.DefaultTexture, 0, 67, 411, 200);
f_LogoX := (gD2DE.ScreenWidth div 2) - Round(f_Logo.Width/2);
f_LogoY := (gD2DE.ScreenHeight div 2) - Round(f_Logo.Height/2);
f_Logo.BlendMode := BLEND_COLORADD;
f_CurCol := 255;
f_Speed := 1200;
f_VFont := f2LoadFont('sans[12]'{,1.2,0.4]'});
f_VFont.Color := l_VColor;
l_VI := TJclFileVersionInfo.Create(ParamStr(0));
try
if l_IsCustomLogo then
f_Version := 'FireURQ ' + l_VI.ProductVersion
else
f_Version := l_VI.ProductVersion;
finally
l_VI.Free;
end;
f_VFont.CalcSize(f_Version, l_Size);
f_VX := gD2DE.ScreenWidth - Round(l_Size.X) - 3;
f_VY := gD2DE.ScreenHeight - Round(l_Size.Y) - 3;
end;
procedure Tf2SplashScene.DoUnload;
begin
f_Logo.Free;
end;
procedure Tf2SplashScene.DoFrame(aDelta: Single);
var
l_Fract: Byte;
begin
if f_Pause > 0 then
begin
f_Pause := f_Pause - aDelta;
Exit;
end;
f_CurCol := f_CurCol - aDelta * f_Speed;
if f_CurCol < 0 then
f_CurCol := 0;
l_Fract := Trunc(f_CurCol);
if f_Logo.BlendMode = BLEND_COLORADD then
begin
f_Logo.SetColor(ARGB($FF, l_Fract, l_Fract, l_Fract));
if l_Fract = 0 then
begin
f_Logo.BlendMode := BLEND_DEFAULT;
f_Logo.SetColor($FFFFFFFF);
f_CurCol := 255;
f_Pause := 1;
f_Speed := 300;
end;
end
else
begin
f_Logo.SetColor(ARGB(l_Fract, 255, 255, 255));
if l_Fract = 0 then
Application.CurrentScene := 'main';
end;
end;
procedure Tf2SplashScene.DoRender;
begin
gD2DE.Gfx_Clear(f_BGColor);
f_Logo.Render(f_LogoX, f_LogoY);
if not F2App.IsFromExe then
f_VFont.Render(f_VX, f_VY, f_Version);
end;
end.
|
unit GetRoutesUnit;
interface
uses SysUtils, BaseExampleUnit, DataObjectUnit;
type
TGetRoutes = class(TBaseExample)
public
function Execute(Limit, Offset: integer): TDataObjectRouteList;
end;
implementation
function TGetRoutes.Execute(Limit, Offset: integer): TDataObjectRouteList;
var
ErrorString: String;
Route: TDataObjectRoute;
begin
Result := Route4MeManager.Route.GetList(Limit, Offset, ErrorString);
WriteLn('');
if (Result <> nil) and (Result.Count > 0) then
begin
WriteLn(Format('GetRoutes executed successfully, %d routes returned',
[Result.Count]));
WriteLn('');
for Route in Result do
WriteLn(Format('RouteId: %s', [Route.RouteId]));
end
else
WriteLn(Format('GetRoutes error "%s"', [ErrorString]));
end;
end.
|
unit BlockView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Kernel;
type
TBlockViewer = class(TForm)
Memo: TMemo;
BlockId: TLabel;
procedure FormCreate(Sender: TObject);
private
fFacility : TFacility;
private
procedure SetFacility( aFacility : TFacility );
public
property Facility : TFacility write SetFacility;
public
procedure RefreshContent;
end;
var
BlockViewer: TBlockViewer;
implementation
{$R *.DFM}
procedure TBlockViewer.SetFacility( aFacility : TFacility );
begin
fFacility := aFacility;
RefreshContent;
if not Visible
then Show;
end;
procedure TBlockViewer.RefreshContent;
function RenderFluid( FluidData : PFluidData ) : string;
begin
if FluidData.Q < qIlimited
then result := '('+ IntToStr(round(FluidData.Q)) + ', ' + IntToStr(FluidData.K) +')'
else result := '( infinite, ' + IntToStr(FluidData.K) +')'
end;
var
i : integer;
fBlock : TBlock;
begin
Memo.Lines.Clear;
if fFacility <> nil
then
try
fBlock := fFacility.CurrBlock;
BlockId.Caption := fBlock.MetaBlock.Id;
Memo.Lines.BeginUpdate;
Memo.Lines.Add( 'Inputs' );
Memo.Lines.Add( '------' );
for i := 0 to pred(fBlock.InputCount) do
Memo.Lines.Add( ' ' + fBlock.Inputs[i].MetaInput.Name + ' = ' + RenderFluid(@fBlock.Inputs[i].LastValue));
Memo.Lines.Add( '' );
Memo.Lines.Add( 'Outputs' );
Memo.Lines.Add( '-------' );
for i := 0 to pred(fBlock.OutputCount) do
Memo.Lines.Add( ' ' + fBlock.Outputs[i].MetaOutput.Name + ' = ' + RenderFluid(fBlock.Outputs[i].FluidData));
Memo.Lines.EndUpdate;
except
fFacility := nil;
Memo.Lines.EndUpdate;
end
else
begin
BlockId.Caption := 'Nothing';
Memo.Lines.Add( 'No block is focused.' );
end;
end;
procedure TBlockViewer.FormCreate(Sender: TObject);
begin
Left := Screen.Width - Width;
Top := 0;
end;
end.
|
{ Subroutine SST_SYMBOL_NEW_NAME (NAME,SYMBOL_P,STAT)
*
* Add a new symbol to the current scope. It is an error if the symbol
* already exists in that name space, although it may exists in more global
* name spaces. NAME is the name of the new symbol to create.
* SYMBOL_P is returned pointing to the newly created data block for the symbol.
* STAT is returned with an error if the symbol already exists in the current
* scope.
*
* As a special case, an intrinsic symbol may be re-used if the current scope
* is the root scope. This is to support include file translations.
*
* Whether the symbol name existed previously or not, SYMBOL_P is still returned
* pointing to the symbol descriptor.
}
module sst_SYMBOL_NEW_NAME;
define sst_symbol_new_name;
%include 'sst2.ins.pas';
procedure sst_symbol_new_name ( {add symbol to curr scope given symbol name}
in name: univ string_var_arg_t; {name of new symbol}
out symbol_p: sst_symbol_p_t; {points to new symbol descriptor}
out stat: sys_err_t); {completion status code}
var
pos: string_hash_pos_t; {handle to position in hash table}
name_p: string_var_p_t; {points to symbol name in hash table entry}
found: boolean; {TRUE if symbol previously existed}
sym_pp: sst_symbol_pp_t; {points to hash entry user data area}
fnam: string_treename_t; {file name passed to a message}
lnum: sys_int_machine_t; {line number passed to a message}
label
init_sym;
begin
fnam.max := sizeof(fnam.str);
sys_error_none (stat); {init STAT to indicate no error}
string_hash_pos_lookup ( {get position for name in hash table}
sst_scope_p^.hash_h, {handle to hash table for current scope}
name, {name to find position for}
pos, {returned position for this name}
found); {TRUE if symbol already exists}
if found then begin {symbol is already here ?}
string_hash_ent_atpos (pos, name_p, sym_pp); {get pointer to symbol data}
symbol_p := sym_pp^; {get pointer to symbol descriptor}
if symbol_p^.symtype = sst_symtype_illegal_k {previously made by not defined ?}
then return;
if {intrinsic symbol in global scope ?}
(sst_symflag_intrinsic_in_k in symbol_p^.flags) and
(sst_scope_p = sst_scope_root_p)
then goto init_sym; {re-use this symbol descriptor}
sys_stat_set (sst_subsys_k, sst_stat_sym_prev_def_k, stat); {set error code}
sst_charh_info (symbol_p^.char_h, fnam, lnum);
sys_stat_parm_vstr (name, stat);
sys_stat_parm_int (lnum, stat);
sys_stat_parm_vstr (fnam, stat);
return; {return with error}
end;
string_hash_ent_add (pos, name_p, sym_pp); {create hash table entry for new symbol}
util_mem_grab ( {allocate memory for symbol descriptor}
sizeof(symbol_p^), {amount of memory to allocate}
sst_scope_p^.mem_p^, {parent memory context}
false, {we won't need to individually release mem}
symbol_p); {returned pointer to new memory area}
sym_pp^ := symbol_p; {save pointer to symbol block in hash entry}
init_sym: {jump here to reset old symbol descriptor}
with symbol_p^: sym do begin {SYM is symbol data block}
sym.name_in_p := name_p; {init as much of symbol data as we can}
sym.name_out_p := nil; {indicate output name not chosen yet}
sym.next_p := nil;
sym.char_h.crange_p := nil;
sym.scope_p := sst_scope_p;
sym.symtype := sst_symtype_illegal_k; {init to illegal symbol}
sym.flags := [];
end; {done with SYM abbreviation}
end;
|
unit uEmailBase;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TEmailBase = class
private
FDestinatario: string;
FCopiaOculta: string;
FArquivoAnexo: string;
FConfirmarLeitura: Boolean;
FMeuNome: string;
FCopia: string;
FNivelPrioridade: Integer;
FMeuEmail: string;
FPassword: string;
FHost: string;
FPorta: Integer;
FAssunto: string;
FUserName: string;
FTexto: string;
FAutenticarSSL: Boolean;
FAutenticar: Boolean;
procedure SetArquivoAnexo(const Value: string);
procedure SetAssunto(const Value: string);
procedure SetConfirmarLeitura(const Value: Boolean);
procedure SetCopia(const Value: string);
procedure SetCopiaOculta(const Value: string);
procedure SetDestinatario(const Value: string);
procedure SetHost(const Value: string);
procedure SetMeuEmail(const Value: string);
procedure SetMeuNome(const Value: string);
procedure SetNivelPrioridade(const Value: Integer);
procedure SetPassword(const Value: string);
procedure SetPorta(const Value: Integer);
procedure SetTexto(const Value: string);
procedure SetUserName(const Value: string);
procedure SetAutenticar(const Value: Boolean);
procedure SetAutenticarSSL(const Value: Boolean);
protected
procedure Validacao;
function RetornarAnexos(TodosAnexos: string): TList<string>; virtual;
public
function EnviarEmail: Boolean; virtual; abstract;
property Porta: Integer read FPorta write SetPorta;
property Host: string read FHost write SetHost;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property MeuEmail: string read FMeuEmail write SetMeuEmail;
property MeuNome: string read FMeuNome write SetMeuNome;
property Destinatario: string read FDestinatario write SetDestinatario;
property Copia: string read FCopia write SetCopia;
property CopiaOculta: string read FCopiaOculta write SetCopiaOculta;
property Assunto: string read FAssunto write SetAssunto;
property Texto: string read FTexto write SetTexto;
property ArquivoAnexo: string read FArquivoAnexo write SetArquivoAnexo;
property ConfirmarLeitura: Boolean read FConfirmarLeitura write SetConfirmarLeitura;
property NivelPrioridade: Integer read FNivelPrioridade write SetNivelPrioridade;
property Autenticar: Boolean read FAutenticar write SetAutenticar;
property AutenticarSSL: Boolean read FAutenticarSSL write SetAutenticarSSL;
end;
implementation
{ TEmailBase }
function TEmailBase.RetornarAnexos(TodosAnexos: string): TList<string>;
var
sResult: string;
i: Integer;
sChar: string;
Lista: TList<string>;
iTamanho: Integer;
begin
Lista := TList<string>.Create;
iTamanho := TodosAnexos.Length;
for I := 1 to iTamanho do
begin
sChar := Copy(TodosAnexos, i, 1);
if sChar = ';' then
begin
Lista.Add(sResult);
sResult := '';
Continue;
end;
sResult := sResult + sChar;
end;
Lista.Add(sResult);
Result := Lista;
end;
procedure TEmailBase.SetArquivoAnexo(const Value: string);
begin
FArquivoAnexo := Value;
end;
procedure TEmailBase.SetAssunto(const Value: string);
begin
FAssunto := Value;
end;
procedure TEmailBase.SetAutenticar(const Value: Boolean);
begin
FAutenticar := Value;
end;
procedure TEmailBase.SetAutenticarSSL(const Value: Boolean);
begin
FAutenticarSSL := Value;
end;
procedure TEmailBase.SetConfirmarLeitura(const Value: Boolean);
begin
FConfirmarLeitura := Value;
end;
procedure TEmailBase.SetCopia(const Value: string);
begin
FCopia := Value;
end;
procedure TEmailBase.SetCopiaOculta(const Value: string);
begin
FCopiaOculta := Value;
end;
procedure TEmailBase.SetDestinatario(const Value: string);
begin
FDestinatario := Value;
end;
procedure TEmailBase.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TEmailBase.SetMeuEmail(const Value: string);
begin
FMeuEmail := Value;
end;
procedure TEmailBase.SetMeuNome(const Value: string);
begin
FMeuNome := Value;
end;
procedure TEmailBase.SetNivelPrioridade(const Value: Integer);
begin
FNivelPrioridade := Value;
end;
procedure TEmailBase.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TEmailBase.SetPorta(const Value: Integer);
begin
FPorta := Value;
end;
procedure TEmailBase.SetTexto(const Value: string);
begin
FTexto := Value;
end;
procedure TEmailBase.SetUserName(const Value: string);
begin
FUserName := Value;
end;
procedure TEmailBase.Validacao;
begin
if Trim(FDestinatario) = '' then
raise Exception.Create('Informe o Destinatário!');
if Trim(FUserName) = '' then
raise Exception.Create('Informe o Usuário!');
if Trim(FMeuEmail) = '' then
FMeuNome := FUserName;
if Trim(FPassword) = '' then
raise Exception.Create('Informe a Senha!');
if Trim(FHost) = '' then
raise Exception.Create('Informe o Host!');
if Trim(FAssunto) = '' then
raise Exception.Create('Informe o Assunto!');
if FPorta <= 0 then
raise Exception.Create('Informe a Porta!');
end;
end.
|
unit UClasses;
interface
uses
ExtCtrls, Controls, SysUtils, Classes;
const
QtdLeftMov :integer = 57;
QtdTopMov :integer = 53;
type
TTipoObj = (toRaposa, toGanso, toMovN, toMovC); //movNormal, movComer
TPeca = class(TObject)
private
pCodigo,
pTop,
pLeft,
pX,
pY :integer;
pTipo:TTipoObj;
pImagem:TImage;
function YToTop(Y:integer):integer;
function XToLeft(X:integer):integer;
public
constructor Create(CodPeca:integer);
destructor Destroy;
function GetCodigo:integer;
procedure SetTipo(tipo:TTipoObj);
function GetTipo:TTipoObj;
procedure SetImagem(tipo:TTipoObj;Owner:TWinControl;caminho:string);
procedure SetPosicao(X,Y:integer);
function GetPosX:integer;
function GetPosY:integer;
procedure SetClick(evento:TNotifyEvent);
end;
TTabuleiro = class(TObject)
private
mTabuleiro:array [1..7,1..7] of integer; // codigoPeca = ocupado; 0 = vazio;
public
constructor Create();
procedure SetOcupado(posX,posY, ocupado:integer);
function GetPosXY(posX,posY:integer):integer;
end;
implementation
{ TPeca }
constructor TPeca.Create(codPeca:integer);
begin
pCodigo := CodPeca;
end;
destructor TPeca.Destroy;
begin
// FreeAndNil(pImagem);
pImagem.Visible := False;
// pImagem.Destroy;
end;
function TPeca.GetTipo:TTipoObj;
begin
result := pTipo
end;
procedure TPeca.SetImagem(tipo: TTipoObj;Owner:TWinControl;caminho:string);
begin
pImagem := TImage.Create(nil);
pImagem.Parent := Owner;
pImagem.Tag := pCodigo;
pImagem.Visible := True;
pImagem.AutoSize := True;
pImagem.Picture.LoadFromFile(caminho);
pImagem.BringToFront;
case tipo of
toRaposa :pTop := 5;//pq o tamanhho da imagem da raposa não é o mesmo do quadro como com o ganso
toGanso :pTop := 0;
else
begin
pImagem.AutoSize := False;
pTop := -2;
pLeft := -2;
pImagem.Width := 54;
pImagem.Height := 50;
pImagem.Stretch := True;
end;
end;
end;
procedure TPeca.SetTipo(tipo: TTipoObj);
begin
pTipo := tipo;
end;
function TPeca.YToTop(Y: integer):integer;
// 328 = valor mais baixo de y no tabuleiro; y = 0
begin
result := pTop + 328 - (QtdTopMov * (Y-1));
end;
function TPeca.XToLeft(X: integer): integer;
// 9 = valor mais baixo de x no tabuleiro; x = 0
begin
result := pLeft + 9 + (QtdLeftMov * (X-1));
end;
procedure TPeca.SetPosicao(X, Y: integer);
begin
if ((X > 0) and (Y > 0)
and (X < 8) and (Y < 8)) then
begin
pImagem.Left := XToLeft(X);
pImagem.Top := YToTop(Y);
pX := X;
pY := Y;
end;
end;
function TPeca.GetPosX: integer;
begin
result := pX;
end;
function TPeca.GetPosY: integer;
begin
result := pY;
end;
procedure TPeca.SetClick(evento: TNotifyEvent);
begin
pImagem.OnClick := evento;
end;
function TPeca.GetCodigo: integer;
begin
result := pCodigo;
end;
{ TTabuleiro }
constructor TTabuleiro.Create();
var i,j:integer;
begin
for i := 1 to 7 do
begin
for j := 1 to 7 do
begin
case i of
1,2,6,7:
begin
case j of
1,2,6,7:mTabuleiro[i,j] := 99; //conta como "ocupado"
else mTabuleiro[i,j] := 0; //esvazia o tabuleiro
end;
end else mTabuleiro[i,j] := 0;
end;
end;
end;
end;
function TTabuleiro.GetPosXY(posX, posY: integer): integer;
begin
if ((posX > 0) and (posY > 0)
and (posX < 8) and (posY < 8)) then
result := mTabuleiro[posX,posY];
end;
procedure TTabuleiro.SetOcupado(posX, posY, ocupado: integer);
begin
if ((posX > 0) and (posY > 0)
and (posX < 8) and (posY < 8)) then
mTabuleiro[posX,posY] := ocupado;
end;
end.
|
(* _______________________________________________________________________
| |
| CONFIDENTIAL MATERIALS |
| |
| These materials include confidential and valuable trade secrets owned |
| by JP Software Inc. or its suppliers, and are provided to you under |
| the terms of a non-disclosure agreement. These materials may not be |
| transmitted or divulged to others or received, viewed, or used by |
| others in any way. All source code, source code and technical |
| documentation, and related notes, are unpublished materials, except |
| to the extent that they are in part legally available as published |
| works from other suppliers, and use of a copyright notice below does |
| not imply publication of these materials. |
| |
| This notice must remain as part of these materials and must not be |
| removed. |
| |
| Unpublished work, Copyright 1988 - 1999, J.P. Software Inc. All |
| Rights Reserved. Portions Copyright 1987, TurboPower Software. |
|_______________________________________________________________________|
Modifications September and October, 1991 by Scott McGrath:
Base TPHELP file updated to TPro v.5.11, usable with TP 6
Paged Help replaced with scrolling help system.
Added Processing for TTY Output: TTYToggle, TTYOnlyMark
Added new routines for TTY Output processing: ShowHelpTTY,
OutputTTY, IsTTYAvailable
Changed Scrollbar char to ASCII 196
Added HKSPrint processing, which calls PrintTopic with the current topic
Added ButtonBar procedure to display key commands
Added test in HKSPgUp/Dn to stop needlessly redrawing the screen
*)
{$S-,R-,V-,I-,B-}
{ NOTE! Major sections that have been customized are marked with
"(* !!!! *)". Major sections that have been eliminated to save
space have been marked with (* ### ... ### *). }
{$IFDEF Ver40}
{$F-}
{$DEFINE FMinus}
{$ELSE}
{$F+}
{$I OPLUS.INC}
{$I AMINUS.INC}
{$ENDIF}
{Conditional defines that may affect this unit}
{$I TPDEFINE.INC}
{*********************************************************}
{* TPHELP.PAS 5.02, 5.11 *}
{* Copyright (c) TurboPower Software 1987. *}
{* Portions copyright (c) Sunny Hill Software 1985, 1986 *}
{* and used under license to TurboPower Software *}
{* All rights reserved. *}
{*********************************************************}
unit TpHelp;
{-General purpose help facility}
interface
uses
Dos,
TPDos,
TPMemChk,
TPString,
TpCrt,
TPWindow,
{$IFDEF UseMouse}
TpMouse,
{$ENDIF}
TpPick,
TpCmd,
TpEdit;
const
NoHelpAvailable = $FFFFFFFF; {Flag that no help is available for topic}
HelpEquated = $FFFFFFFE; {Flag that this topic is equated to another}
{ *** 4.00 *** }
MaxLinesPerSection = 2000; {Maximum number of lines per topic?}
MaxXrefsPerSection = 512; {Maximum number of topic xrefs per section}
MaxTopics = 1024; {Maximum number of topics in one help file}
MaxHelpStack = 15; {Highest stacked topic}
MaxXrefSearchLen = 16; {Max length of xref search string}
PageDragFirst = 350; {Delay for first page drag, ms}
PageDragRep = 200; {Delay for page drag repeat, ms}
LineDragFirst = 250; {Delay for first line drag, ms}
LineDragRep = 50; {Delay for line drag repeat, ms}
Attr1Toggle = ^A; {Character toggles special attribute 1}
Attr2Toggle = ^B; {Character toggles special attribute 2}
Attr3Toggle = ^C; {Character toggles special attribute 3}
IndexMarker = ^D; {Character marks topic number that follows}
XrefToggle = ^E; {Character toggles xref highlight}
IndentMark = ^F; {Character sets indent width}
IgnoreMark = ^G; {Ignore character for XRef search}
LineBrkMark = ^M; {Denotes end of line of help}
PageBrkMark = ^L; {Denotes end of page of help}
SectEndMark = #0; {Denotes end of help section}
EscapeChar = ^X; {Escape character for input text}
TTYToggle = ^N; {Character toggles TTY output sections}
TTYOnlyMark = #15; {TTY only text at end of topic}
{Command values for help system}
HKSNone = 0; {Not a command}
HKSAlpha = 1; {An alphanumeric character}
HKSUp = 2; {Scroll toward top}
HKSDown = 3; {Scroll toward bottom}
HKSPgUp = 4; {Display previous help page}
HKSPgDn = 5; {Display next help page}
HKSLeft = 6; {Cursor left to previous cross-reference}
HKSRight = 7; {Cursor right to next cross-reference}
HKSExit = 8; {Exit the help system}
HKSSelect = 9; {Select the current cross-reference and display topic}
HKSBack = 10; {Display the most recent help topic}
HKSHome = 11; {Display first help page}
HKSEnd = 12; {Display last help page}
HKSToC = 13; {Display the first help topic}
HKSIndex = 14; {Display the help index}
HKSKeys = 15; {Display a special topic for keys help}
HKSProbe = 16; {Mouse selection}
HksExitSave = 17; {Customized-exit but keep help screen}
HksQuickExit = 18; {Quick-exit}
HksNext = 19; {Customized-show next help}
HksPrevious = 20; {Customized-show previous help}
HKSPrint = 21; {Print TTY Output for Current Topic}
HKSTSearch = 22; {Search within topic}
HKSGSearch = 23; {Global search across topics}
HKSNSearch = 24; {Search for next occurrence}
HKSXUp = 25; {Scroll toward top via XRefs}
HKSXDown = 26; {Scroll toward bottom via XRefs}
HKSExtHelp = 27; {Display external help}
HKSSwapKeys = 28; {Swap button bar keys}
HKSUser0 = 29; {User-defined exit commands}
HKSUser1 = 30;
HKSUser2 = 31;
HKSUser3 = 32;
{.F-}
{Keystroke to command mapping}
HelpKeyMax = 192;
HelpKeySet : array[0..HelpKeyMax] of Byte =
( {Byte offset}
3, $00, $48, HKSUp, {Up} {0}
3, $00, $50, HKSDown, {Down}
3, $00, $49, HKSPgUp, {PgUp}
3, $00, $51, HKSPgDn, {PgDn}
3, $00, $4B, HKSLeft, {Left}
3, $00, $4D, HKSRight, {Right}
3, $00, $47, HKSHome, {Home}
3, $00, $4F, HKSEnd, {End}
3, $00, $3B, HKSIndex, {F1}
3, $00, $3C, HKSToC, {F2}
3, $00, $3D, HKSKeys, {F3}
3, $00, $3E, HKSExtHelp, {F4}
3, $00, $3F, HKSTSearch, {F5}
3, $00, $40, HKSGSearch, {F6}
3, $00, $58, HKSNSearch, {Shift-F5}
3, $00, $59, HKSNSearch, {Shift-F6}
3, $00, $44, HKSSwapKeys, {F10}
2, $1B, HKSExit, {Esc}
2, $0D, HKSSelect, {Enter}
2, $05, HKSUp, {^E} {74}
2, $17, HKSUp, {^W}
2, $18, HKSDown, {^X}
2, $1A, HKSDown, {^Z}
2, $12, HKSPgUp, {^R}
2, $03, HKSPgDn, {^C}
2, $13, HKSLeft, {^S}
2, $04, HKSRight, {^D}
3, $11, $12, HKSHome, {^QR}
3, $11, $03, HKSEnd, {^QC}
{$IFDEF UseMouse}
3, $00, $EF, HKSProbe, {Click left} {106}
3, $00, $EE, HKSExit, {Click right}
3, $00, $ED, HKSIndex, {Click both}
3, $00, $E8, HKSDown, {Wheel down}
3, $00, $E0, HKSUp, {Wheel up}
{$ELSE}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {106}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
{$ENDIF}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {126}
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0
);
{.F+}
{$IFDEF GERMAN}
HelpTitle : string[39] = ' Stichwörter ';
NKeyLists = 1;
NMaxKeys = 6;
StdKeys : array[1..NKeyLists] of string[78] = (
' F1¨Index │ AltX¨ExitSave │ G¨Suche │ W¨Weiter │ D¨Druck │ Z¨Zurück │ '
);
StdKeyCommands : array [1..NKeyLists, 1..NMaxKeys] of byte = (
(HKSIndex, HKSExitSave, HKSTSearch, HKSNSearch, HKSPrint, HKSBack)
);
{ UpAndDown = 'Bd/Bd';}
{$ELSE}
HelpTitle : string[39] = ' Topics '; {Displayed at top of help pick window}
NKeyLists = 2;
NMaxKeys = 6;
StdKeys : array[1..NKeyLists] of string[78] = (
'│ F1¨Index │ F2¨TOC │ F3¨Keys │ F4¨Ext Help │ F9¨Print │ F10¨Search Keys │',
'│ F5¨Topic Search │ F6¨Global Search │ Sh-F5 / Sh-F6¨Next │ F10¨Std Keys │'
);
StdKeyCommands : array [1..NKeyLists, 1..NMaxKeys] of byte = (
(HKSIndex, HKSToC, HKSKeys, HKSExtHelp, HKSPrint, HKSSwapKeys),
(HKSTSearch, HKSGSearch, HKSNSearch, HKSSwapKeys, HKSNone, HKSNone)
);
{$ENDIF}
UseHelpFrame : Boolean = True; {True to draw frame around help window}
HelpMore : Boolean = True; {True to display PgUp/PgDn in help frame}
HideCursor : Boolean = True; {False to leave hardware cursor on screen}
IsTTY : Boolean = False; {True to use TTY Output methods}
UseButtonBar : Boolean = True; {True to display button bar}
{$IFDEF UseMouse}
HelpMouseScroll : Boolean = True; {True to support mouse scrolling}
{$ENDIF}
IndexXrefTopic : Word = 0; {Topic number which brings up index when used as xref}
type
HelpID = string[8]; {Version identifier at start of help file}
HKtype = HKSNone..HKSUser3; {Valid help commands}
SO = record
O : Word;
S : Word;
end;
HelpColorType = (
FrAttr, {Frame}
TeAttr, {Normal text}
HeAttr, {Header and more prompt}
XsAttr, {Selected cross-reference item}
XrAttr, {Unselected cross-reference item}
SpAtt1, {Special attribute #1}
SpAtt2, {Special attribute #2}
SpAtt3, {Special attribute #3}
PWAttr, {Search window attribute}
PIAttr, {Search input attribute}
BBAttr); {Button Bar attribute}
HelpColorArray = array[HelpColorType] of Byte;
HelpToggleArray = array[Attr1Toggle..XrefToggle] of Byte;
{4.0 Mouse Code}
MouseRegionType = (
MouseLineUp, {up arrow at top of scroll bar}
MouseLineDown, {down arrow at bottom}
MousePgUp, {PgUp hot spot}
MousePgDn, {PgDn hot spot}
MouseScrollBar, {in scroll bar}
MouseClose, {close window hot spot}
MouseButtonBar, {button bar hot spots}
MouseOther); {anywhere else}
DragStateType = (
DragNone, {dragging not active}
DragScroll, {repeating line or page up/down}
DragSlider, {dragging slider}
DragHold); {drag hold due to mouse motion}
MouseBarRegion = record
Start : Byte; {Starting Position}
Last : Byte; {Length of String}
end;
BarRegion = array[1..NMaxKeys] of MouseBarRegion;
XlateArray = array[0..29] of Byte; {Most common characters in help text}
SharewareDataRec = {shareware timeout data stored in help file}
record
CheckSum : Word; {shareware data checksum}
LastUsageDate : Word; {last use of 4DOS}
ReleaseNum : Word; {release number on first use}
DaysUsed : Word; {number of days on which 4DOS has been used}
MachineName : array[1..32] of byte; {machine ID bytes}
RestartCount : word; {number of restarts}
ExpireDays : word; {days to expiration (encoded)}
RestrictDays : word; {days to restriction (encoded)}
Signature : word; {shareware signature}
Pad : array [1..72] of byte; {pad to 128 bytes}
end;
HelpHeader = {At start of help file}
record
ID : HelpID; {Marks file as help file}
HighestTopic : Word; {Highest topic number}
NumTopics : Word; {Number of topics}
BiggestTopic : Word; {Size of largest topic in uncompressed bytes}
NamedTopics : Word; {Number of topics in help index}
NameSize : Byte; {Size of largest name, 0 for none}
PickSize : Byte; {Size of each entry in pick table, 0 for none}
Width : Byte; {Width of help window, with frame if any}
FirstTopic : Word; {Topic to show first (0 = index)}
KeysTopic : Word; {Topic to show when keys help needed}
ExtHelpName : String[13]; {Name for external help file}
ExtHelpEnv : String[16]; {Environment variable for alternate
external help file name}
XlateTable : XlateArray; {Table for decompression}
SharewareData : SharewareDataRec; {shareware info for 4DOS.COM}
end;
HelpHeaderPtr = ^HelpHeader;
CharArray = array[0..65520] of Char; {List of names of help entries}
CharArrayPtr = ^CharArray;
HelpIndexRec =
record
Start : LongInt; {File position of topic}
CompLen : Word; {Compressed length of topic}
end; {Index of file positions}
HelpIndex = array[1..MaxTopics] of HelpIndexRec;
HelpIndexPtr = ^HelpIndex;
TopicIndex = array[1..MaxTopics] of Word;
TopicIndexPtr = ^TopicIndex;
Xrefs = 0..MaxXrefsPerSection;
Lines = 0..MaxLinesPerSection;
HelpStackRec =
record
STopic : Word; {Which topic}
SLine : Word; {Starting line count}
SXnum : Xrefs; {Which xref item selected}
end;
HelpStackIndex = 0..MaxHelpStack;
HelpStackArray = array[HelpStackIndex] of HelpStackRec;
HelpPtr = ^HelpDesc; {The user hook to the help system}
HelpDesc = {Holds parameters of help system}
record
BufP : CharArrayPtr; {Points to a buffer that will hold largest section}
Hdr : HelpHeader; {Copy of header for fast reference}
RowH : Byte; {Upper left corner of help window - Row}
ColH : Byte; {Upper left corner of help window - Col}
Height : Byte; {Height of help window, with frame}
A : HelpColorArray; {Attributes used to draw help}
Frame : FrameArray; {Frame characters to use}
ShowFrame : Boolean; {True to display frame}
ShowMore : Boolean; {True to display More prompt in frame}
MouseScroll : Boolean; {True to display mouse scroll bar}
Stack : HelpStackArray; {Topics previously accessed}
St : HelpStackIndex; {Top of help stack}
Sb : HelpStackIndex; {Bottom of help stack}
PickWindow : WindowPtr; {window used for index}
PickCols : integer; {columns in index}
PickRows : integer; {rows in index}
FillPickScreen : boolean; {index fills screen}
PickChoice : Word; {previous index choice}
case InRAM : Boolean of {True if help file is bound into code}
False :
(Fil : file); {Untyped file variable for help}
True :
(HdrP : HelpHeaderPtr; {Points to base of structure in RAM}
NamP : CharArrayPtr; {Points to pick name array in RAM}
IndP : HelpIndexPtr); {Points to help section index in RAM}
end;
const
HelpSystemID : HelpID = '4DH701AA'; {Version identifier}
var
PBuff : CharArrayPtr; {Pointer to pick names buffer}
PBufSize : Word; {Pick names buffer size}
TBuff : TopicIndexPtr; {Pointer to topic index buffer}
TBufSize : Word; {Topic index buffer size}
TBufPtr : Word; {Topic list entry number for current topic}
HelpKeyPtr : Pointer; {Points to Kbd routine like ReadKeyWord}
HelpCmdNum : HKtype; {Last help command entered}
HelpOnScreen : Boolean; {True when help system is displayed}
{$IFDEF UseMouse}
HelpMouseEnabled : Boolean; {True if mouse is enabled}
{$ENDIF}
HelpResize : boolean; {true if windows should be resized for topic}
HelpSaveSrch : boolean; {true if xref search string should be saved
on mismatch}
BarDispCol : Word; {column for BBar start}
BarReg : BarRegion;
Lst : Text;
LstName : string[40];
LstOpen : Boolean;
{-----------------------------------------------------------------}
function OpenHelpFile(HelpFileName : string;
XLow, YLow, YHigh, PickCols : Byte;
FullScreenIndex : boolean;
Colors : HelpColorArray;
var Help : HelpPtr) : Word;
{-Find and open help file, returning 0 or error code, and
an initialized help descriptor if successful}
procedure CloseHelp(var Help : HelpPtr);
{-Close help file and/or deallocate buffer space}
function ShowHelp(Help : HelpPtr; Var Topic : Word;
StartAtMark : boolean) : Boolean;
{-Display help screen for item Topic, returning true if successful}
{ I changed TOPIC to a VAR so that changes can be passed back }
function FindHelp(Help : HelpPtr; Name : string; MatchFunc : Pointer) : Word;
{-Return Topic number of help with specified Name, 0 if not found}
function PickHelp(Help : HelpPtr; var PickW : WindowPtr;
XLow, YLow, YHigh, PickCols : Byte;
OldWindow, SaveWindow : boolean;
var Choice : word) : Word;
{-Display help pick list, returning Topic number, or 0 for none}
function AddHelpCommand(Cmd : HKtype; NumKeys : Byte; Key1, Key2 : Word) : Boolean;
{-Add a new command key assignment or change an existing one}
procedure DisableHelpIndex;
{-Disable the F1 help index inside of a help screen}
procedure EnableHelpIndex;
{-Enable the F1 help index inside of a help screen}
{$IFDEF UseMouse}
procedure EnableHelpMouse;
{-Enable mouse control of help screens}
procedure DisableHelpMouse;
{-Disable mouse control of help screens}
{$ENDIF}
procedure Beep;
{error beep}
procedure PrintTopic(Help : HelpPtr; Topic : word);
{Print the current topic to the standard printer}
function SearchText(Help : HelpPtr; var Topic : word;
GlobalSearch : boolean) : boolean;
{Search the current topic for a string}
function ShowHelpTTY(Help : HelpPtr; Var Topic : Word) : Boolean;
{display topic help to TTY Output}
{=================================================================}
implementation
const
FlexStackSize = 6; {Max number of nested attributes}
MouseUpMark = #24; {Characters in scroll bar}
MouseDnMark = #25;
MouseQuitMark = #4;
ScrollMark = #178;
SBarChar = #176; {scroll bar background char, 4.00}
{blank string used for indents (length may change)}
Blanks : string[80] = ' ';
FrameDelta : array[Boolean] of Byte = (1, 0);
HelpIndexDisabled : Boolean = False; {True when F1 inside of help is disabled}
type
StringPtr = ^string;
{ *** 4.00 *** }
LineIndex = array[Lines] of Word; {offset into text for each line}
{ LineXRS = array[Lines] of Boolean; {start with xref flag for each line}
FlexStack = array[0..FlexStackSize] of Byte; {Stacks current attributes}
LineAttrRec =
record
FlexSP : Byte; {flex stack pointer}
FlexSt : FlexStack; {active attribute indices}
end;
LineAttr = array[Lines] of LineAttrRec;
LineIndent = array[Lines] of byte;
XrefRec =
record
Line : Lines; {which line the xref displays on}
Col : Byte; {Which col of window}
Len : Byte; {Length of highlight}
Bofs : Word; {Offset in uncompressed text buffer}
Topic : Word; {Which topic is cross-referenced}
end;
XrefIndex = array[Xrefs] of XrefRec;
{ *** 4.00 *** }
HelpStateRec =
record
ColMin : Byte; {Min window-relative col where text appears}
ColMax : Byte; {Max window-relative col where text appears}
Xnum : Xrefs; {Currently selected cross-reference}
Xcnt : Xrefs; {Number of cross-references in topic}
X : XrefIndex; {Index of cross-references}
AC : HelpToggleArray; {Attributes for each toggle character}
ShowMoreNow : Boolean; {True to display More prompt in frame}
MouseScrollNow : Boolean; {True to display mouse scroll bar}
L : LineIndex; {buffer offset to start of each line}
LineA : LineAttr; {starting attributes}
LineI : LineIndent; {indents}
{ LineX : LineXRS; {starting XRef flags}
CurrentTopLine : Lines; {active top line}
NewTopLine : Lines; {desired Top line}
LastLine : Lines; {Last active line number}
LineCnt : Lines; {Line Cnt of Current Topic}
Lslid : Byte; {Last slider position}
W : WindowPtr; {Pointer to window in which help appears}
BBWin : WindowPtr; {Pointer to Button Bar Window}
KeyListNum : word; {number of current button bar key list}
NewHeight : byte; {new window height}
OldHeight : byte; {previous window height}
SearchStartPos : word; {Starting position for compare}
SearchGlobal : boolean; {last search type}
SearchString : string[40]; {String to search for}
SearchLen : word; {length of search string}
FoundLine : Lines; {line found in search}
FoundMarkLine : Lines; {found line to be marked}
end;
var
HelpState : HelpStateRec; {Overall help info}
PopWindow : WindowPtr; {global popup window pointer}
SPtr : CharArrayPtr; {Source pointer}
Dptr : CharArrayPtr; {Destination pointer}
SI : Word; {Source index during decompression}
DI : Word; {Destination index during decompression}
BN : Byte; {Buffered nibble}
Nibble : Boolean; {True when partial byte entered during decompress}
NSize : Byte; {Size of array element in pick buffer}
{$IFDEF FMinus}
{$F+}
{$ENDIF}
function SendHelpName(Topic : Word) : string;
{-Pass each help Topic to the pick unit}
var
NamePtr : ^string;
begin
NamePtr := Ptr(SO(PBuff).S, SO(PBuff).O+NSize*(TBuff^[Topic]-1));
if NamePtr^[1] = Chr(24) then {kill escape on topic name}
SendHelpName := ' ' + Copy(NamePtr^, 2, Length(NamePtr^)-1)
else
SendHelpName := ' ' + NamePtr^;
{SendHelpName := ' '+string(Ptr(SO(PBuff).S, SO(PBuff).O+NSize*(TBuff^[Topic]-1))^);}
end;
function Match(S1, S2 : string) : Boolean;
{-Default match function}
begin
Match := (CompUCstring(S1, S2) = Equal);
end;
{$IFDEF FMinus}
{$F-}
{$ENDIF}
function GetBuffer(Help : HelpPtr; var P; SeekOfs : LongInt;
SizeReq : Word; var SizeAlloc : Word) : Boolean;
{-Return pointer to loaded array of help data}
var
Pt : Pointer absolute P;
BytesRead : Word;
begin
GetBuffer := False;
SizeAlloc := 0;
with Help^, Hdr do
if InRAM then
{Already in memory, just compute the pointer}
Pt := Ptr(SO(HdrP).S, SO(HdrP).O+Word(SeekOfs))
else if FileRec(Fil).Mode = fmInOut then begin
{On disk, first allocate space}
if not GetMemCheck(P, SizeReq) then
Exit;
SizeAlloc := SizeReq;
{Read names into buffer}
Seek(Fil, SeekOfs);
if IoResult <> 0 then
Exit;
BlockRead(Fil, Pt^, SizeReq, BytesRead);
if (IoResult <> 0) or (BytesRead <> SizeReq) then
Exit;
end else
{Help file not open}
Exit;
GetBuffer := True;
end;
function IDOK(Help : HelpPtr) : boolean;
begin
with Help^, Hdr do begin
IDOK := (Length(ID) = Length(HelpSystemID)) and
(CompString(Help^.Hdr.ID, HelpSystemID) = Equal)
end;
end;
procedure DecryptTable(Help : HelpPtr);
{-Decrypt the translation table}
var
I : Word;
begin
with Help^, Hdr do begin
for I := 0 to 29 do
XlateTable[I] := XlateTable[I] xor $C3;
end;
end;
function OpenHelpFile(HelpFileName : string;
XLow, YLow, YHigh, PickCols : Byte;
FullScreenIndex : boolean;
Colors : HelpColorArray;
var Help : HelpPtr) : Word;
{-Find and open help file, returning 0 or error code, and
an initialized help descriptor if successful}
label
ErrorExit;
var
IO : Word;
BytesRead : Word;
IsOpen : Boolean;
MaxCols : Byte;
Rows : integer;
begin
{Initialize the result}
Help := nil;
PBuff := nil;
TBuff := nil;
TBufPtr := 0;
IsOpen := False;
{Find the help file}
if not ExistOnPath(HelpFileName, HelpFileName) then begin
OpenHelpFile := 2;
goto ErrorExit;
end;
{Allocate space for help descriptor}
if not GetMemCheck(Help, SizeOf(HelpDesc)) then begin
OpenHelpFile := 203;
goto ErrorExit;
end;
{Initialize the help descriptor}
with Help^ do begin
{Most help information is on disk}
InRAM := False;
{Open the help file}
FileMode := 0; {open in read-only mode}
Assign(Fil, HelpFileName);
Reset(Fil, 1);
IO := IoResult;
if IO <> 0 then begin
OpenHelpFile := IO;
goto ErrorExit;
end;
IsOpen := True;
{Get header from file}
BlockRead(Fil, Hdr, SizeOf(HelpHeader), BytesRead);
IO := IoResult;
if IO <> 0 then begin
OpenHelpFile := IO;
goto ErrorExit;
end;
if BytesRead <> SizeOf(HelpHeader) then begin
OpenHelpFile := 100;
goto ErrorExit;
end;
with Hdr do begin
{Check file ID}
if not IDOK(Help) then begin
{"Invalid numeric format" - used as error code for invalid ID}
OpenHelpFile := 106;
goto ErrorExit;
end;
{Decrypt the translation table}
DecryptTable(Help);
{Read pick name index}
if not GetBuffer(Help, PBuff, SizeOf(HelpHeader),
HighestTopic*NameSize, PBufSize) then begin
OpenHelpFile := 211;
goto ErrorExit;
end;
{Read topic list}
if not GetBuffer(Help, TBuff, SizeOf(HelpHeader) +
LongInt(HighestTopic)*(NameSize+SizeOf(HelpIndexRec)),
HighestTopic*SizeOf(Word), TBufSize) then begin
OpenHelpFile := 212;
goto ErrorExit;
end;
{Get buffer space for reading help sections}
if not GetMemCheck(BufP, BiggestTopic) then begin
OpenHelpFile := 203;
goto ErrorExit;
end;
{Initialize index window data}
Rows := TpCRT.ScreenHeight;
PickWindow := nil;
PickCols := (NamedTopics + Rows - 4) div (Rows - 3);
PickRows := ((NamedTopics + PickCols - 1) div PickCols) + 2;
FillPickScreen := FullScreenIndex;
PickChoice := 1;
PickMouseScroll := false; {disable mouse scroll in TPPICK}
end;
{Initialize remaining fields}
RowH := YLow;
ColH := XLow;
Height := YHigh-YLow+1;
A := Colors;
Frame := FrameChars;
ShowFrame := UseHelpFrame;
ShowMore := UseHelpFrame and HelpMore;
{$IFDEF UseMouse}
MouseScroll := UseHelpFrame and HelpMouseScroll;
{$ENDIF}
{ St := 0;
Sb := 0;}
{Successful initialization}
OpenHelpFile := 0;
Exit;
end;
ErrorExit:
if IsOpen then begin
Close(Help^.Fil);
IO := IoResult;
end;
FreeMemCheck(Help, SizeOf(HelpDesc));
FreeMemCheck(PBuff, PBufSize);
FreeMemCheck(TBuff, TBufSize);
end;
procedure CloseHelp(var Help : HelpPtr);
{-Close help file and/or deallocate buffer space}
var
IO : Word;
begin
with Help^, Hdr do begin
if not IDOK(Help) then
{Not a valid help pointer}
Exit;
if not InRAM then
if FileRec(Fil).Mode = fmInOut then begin
{Close help file}
Close(Fil);
IO := IoResult;
end;
FreeMemCheck(BufP, BiggestTopic);
end;
FreeMemCheck(Help, SizeOf(HelpDesc));
FreeMemCheck(PBuff, PBufSize);
FreeMemCheck(TBuff, TBufSize);
Help := nil;
if LstOpen then begin
Close(Lst);
LstOpen := false;
end;
end;
function GetNameString(Help : HelpPtr; Topic : Word) : string;
{-Return name string for help item, if any}
var
S : string;
begin
GetNameString := '';
with Help^, Hdr do
if NameSize <> 0 then
if InRAM then
GetNameString := string(Ptr(SO(NamP).S, SO(NamP).O+NameSize*(Topic-1))^)
else if FileRec(Fil).Mode = fmInOut then begin
Seek(Fil, LongInt(SizeOf(HelpHeader))+NameSize*(Topic-1));
if IoResult <> 0 then
Exit;
BlockRead(Fil, S, NameSize);
if IoResult <> 0 then
Exit;
if S[1] = Chr(24) then {kill escape on topic name}
GetNameString := Copy(S, 2, Length(S)-1)
else
GetNameString := S;
end;
end;
function MapPointer(Help : HelpPtr; Topic : Word) : Word;
{-Find the topic map entry number for a topic}
var
MPtr : Word;
begin
MPtr := 1;
with Help^.Hdr do begin
while (MPtr < HighestTopic) and (TBuff^[MPtr] <> Topic) do
Inc(MPtr);
if MPtr >= HighestTopic then
MapPointer := 0
else
MapPointer := integer(MPtr);
end;
end;
procedure InitTopic(Help : HelpPtr);
{-Examine topic and find xref points}
var
Bpos : Word;
{Pofs : Word;}
{Prow : Word;}
Pcol : Word;
{Mrow : Word;}
WordP : ^Word;
Done : Boolean;
Ch : Char;
HA : LineAttrRec;
LA : LineAttrRec;
LineOfs : word;
IndentWidth : byte;
SaveIndentWidth : byte;
LineIndent : boolean;
{ InXRef : Boolean;}
procedure NewLine;
begin
with HelpState do begin
if LineCnt >= MaxLinesPerSection then
Done := True
else begin
Inc(LineCnt);
L[LineCnt] := LineOfs;
LineA[LineCnt] := LA;
LineI[LineCnt] := IndentWidth;
if LineIndent then begin
IndentWidth := SaveIndentWidth; {reset to normal after first line}
LineIndent := false;
end;
{ LineX[LineCnt] := InXRef;}
LineOfs := Bpos+1;
L[LineCnt+1] := LineOfs;
LA := HA;
end;
end;
end;
{ *** 4.00 *** }
begin
with Help^, Hdr, HelpState do begin
Xnum := 0;
ColMin := 2;
ColMax := Width-3;
Bpos := 0;
LineOfs := 0;
Pcol := ColMin;
{Mrow := Height-2;}
Xcnt := 0;
NewHeight := 0;
LineCnt := 0; {count of lines}
LastLine := 0;
IndentWidth := 0;
LineIndent := false;
{No special attributes initially active}
FillChar(HA, SizeOf(LineAttrRec), 0);
HA.FlexSt[0] := A[TeAttr];
LA := HA;
{ InXRef := False;}
Done := False;
repeat
Ch := BufP^[Bpos];
case Ch of
EscapeChar : {suppress normal meaning of next character}
Inc(Bpos);
Attr1Toggle..Attr3Toggle : {Modifying video attribute}
with HA do
if (FlexSp > 0) and (FlexSt[FlexSp] = AC[Ch]) then
{Toggling current state off}
Dec(FlexSp)
else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
FlexSt[FlexSp] := AC[Ch];
end;
XrefToggle : {Marking a cross-reference}
with HA do
if (FlexSp > 0) and (FlexSt[FlexSp] = A[XrAttr]) then begin
{Toggling current state off}
Dec(FlexSp);
{Store length of highlight}
with X[Xcnt] do
Len := Bpos-Bofs-1;
{ InXRef := False;}
end else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
FlexSt[FlexSp] := A[XrAttr];
{ InXRef := True;}
end;
IndexMarker : {Indicating cross-reference topic}
begin
if Xcnt < MaxXrefsPerSection then begin
Inc(Xcnt);
with X[Xcnt] do begin
Line := LineCnt+1;
Col := Pcol;
Bofs := Bpos+3;
WordP := @BufP^[Bpos+1];
Topic := WordP^;
end;
end;
Inc(Bpos, 2);
end;
TTYToggle, IgnoreMark:
;
IndentMark :
begin
SaveIndentWidth := IndentWidth;
IndentWidth := Byte(Bufp^[Bpos+1]); {get indent width}
if IndentWidth >= 128 then begin
LineIndent := true; {indent changes for one line only}
IndentWidth := IndentWidth - 128;
end;
Pcol := ColMin + IndentWidth; {force column to left}
Inc(Bpos); {skip it}
end;
PageBrkMark,
LineBrkMark : {End of line}
begin
NewLine;
Pcol := ColMin + IndentWidth;
end;
TTYOnlyMark,
SectEndMark : {End of section}
begin
Done := True;
NewLine;
LastLine := LineCnt;
end;
else
Inc(Pcol);
end;
Inc(Bpos);
until Done;
{use screen height if resize disabled}
if not HelpResize then
NewHeight := Height - 1;
end;
end;
{$IFDEF UseMouse}
procedure HiddenMouse;
begin
if HelpMouseEnabled then
HideMouse;
end;
procedure VisibleMouse;
begin
if HelpMouseEnabled then
ShowMouse;
end;
procedure WaitForMouseRelease;
begin
if HelpMouseEnabled then
while MousePressed do
inline($cd/$28); {let TSRs pop up while we wait for release}
end;
function GetKeyStart(KeyString : String; AllKeys : String) : Byte;
begin
GetKeyStart := Pos(KeyString, AllKeys) + BarDispCol -1;
end;
procedure InitMouseBarKeys(Help : HelpPtr);
const
D : Charset = ['│'];
var
KeyList : String;
KeyStr : String;
Keys : byte;
begin
if HelpMouseEnabled then
with Help^, Hdr, HelpState do begin
KeyList := StdKeys[KeyListNum];
BarDispCol := (((ColH+Width-1) - Length(KeyList)) div 2) + 1;
for Keys := 1 to NMaxKeys do begin
KeyStr := ExtractWord(Keys, KeyList, D);
BarReg[Keys].Start := GetKeyStart(KeyStr, KeyList);
BarReg[Keys].Last := BarReg[Keys].Start + Length(KeyStr)-1;
end;
end;
end;
function GetBBCommand(Help : HelpPtr; XPos : Byte) : HKType;
{return a command based on where on button the cursor is}
var
ButtonClicked : word;
begin
with Help^, HelpState do begin
for ButtonClicked := 1 to NMaxKeys do begin
if (XPos >= BarReg[ButtonClicked].Start) and
(XPos <= BarReg[ButtonClicked].Last) then begin
GetBBCommand := StdKeyCommands[KeyListNum, ButtonClicked];
Exit;
end;
end;
end;
GetBBCommand := HKSNone;
end;
{$ENDIF}
procedure ButtonBar(Help : HelpPtr);
{display a mouse-hot bar with commands}
var
KeyList : String;
begin
HiddenMouse;
with Help^, HelpState, Hdr, WindowP(BBWin)^, Draw do begin
KeyList := StdKeys[KeyListNum];
BarDispCol := (((ColH+Width-1) - Length(KeyList)) div 2) + 1;
FastWrite(KeyList, Height, BarDispCol, A[BBAttr]);
end;
VisibleMouse;
end;
procedure DoIndent(R : byte; var C : byte; IndentWidth, Attr : byte);
{do any indent}
begin
if IndentWidth > 0 then begin
Blanks[0] := Char(IndentWidth);
FastWriteWindow(Blanks, R, C, Attr);
C := C + IndentWidth;
end;
end;
procedure DrawLine(Help : HelpPtr; Start : Word; WriteRow : Byte);
{-Draw one line of help}
var
Bpos : Word;
Attr : Byte;
R : Byte;
C : Byte;
Ch : Char;
AtSt : LineAttrRec;
Indenting : Boolean;
Finished : Boolean;
begin
with Help^, HelpState, AtSt do begin
Bpos := L[Start]; {starting position of top line}
R := WriteRow; {window relative row}
C := ColMin;
Indenting := True;
Finished := False;
AtSt := LineA[Start];
Attr := FlexSt[FlexSp];
DoIndent(R, C, LineI[Start], A[TeAttr]);
if (Attr = A[XrAttr]) and (R = 1) then {don't display partial xref}
Attr := A[TeAttr];
repeat
Ch := BufP^[Bpos];
case Ch of
TTYToggle, IgnoreMark:
;
IndentMark :
Inc(Bpos); {skip indent amount}
LineBrkMark, PageBrkMark :
Finished := True;
Attr1Toggle..Attr3Toggle :
if (FlexSp > 0) and (FlexSt[FlexSp] = AC[Ch]) then begin
{Toggling current state off}
Dec(FlexSp);
Attr := FlexSt[FlexSp];
end else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
Attr := AC[Ch];
FlexSt[FlexSp] := Attr;
end;
XrefToggle :
if (FlexSp > 0) and (FlexSt[FlexSp] = A[XrAttr]) then begin
{Toggling current state off}
Dec(FlexSp);
Attr := FlexSt[FlexSp];
end else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
if Bpos = X[Xnum].Bofs then
{Selected cross-ref}
Attr := A[XsAttr]
else
{Deselected cross-ref}
Attr := A[XrAttr];
FlexSt[FlexSp] := A[XrAttr];
end;
IndexMarker :
{Skip over topic number}
Inc(Bpos, 2);
TTYOnlyMark,
SectEndMark :
Finished := True;
else
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos] {get next character to write it}
end;
if C <= ColMax then begin
if Indenting and (Ch = ' ') then
FastWriteWindow(Ch, R, C, A[TeAttr])
else begin
FastWriteWindow(Ch, R, C, Attr);
Indenting := False;
end;
Inc(C);
end;
end;
Inc(Bpos);
until Finished;
end;
end;
procedure DrawPage(Help : HelpPtr; Start : Word);
{-Draw one page of help}
var
Bpos : Word;
Bend : Word;
Attr : Byte;
R : Byte;
C : Byte;
Ch : Char;
AtSt : LineAttrRec;
PrevMX, PrevMY : Byte;
{LineNum : Word;}
Indenting : Boolean;
begin
HiddenMouse;
with Help^, HelpState, AtSt do begin
Bpos := L[Start]; {starting position of top line}
if LastLine <= Height-3 then
Bend := L[LastLine+1] {LastLine is end of Buffer}
else
Bend := L[Start+Height-3]; {buffer offset of last line on screen }
R := 1; {window relative row}
C := ColMin;
AtSt := LineA[Start];
Attr := FlexSt[FlexSp];
ClrScr;
DoIndent(R, C, LineI[Start], A[TeAttr]);
repeat
Ch := BufP^[Bpos];
case Ch of
TTYToggle, IgnoreMark:
;
IndentMark :
Inc(Bpos); {skip indent width byte}
PageBrkMark,
LineBrkMark :
begin
Inc(R);
Inc(Start);
C := ColMin;
if (R < Height - 2) then
DoIndent(R, C, LineI[Start], A[TeAttr]);
Indenting := True;
end;
Attr1Toggle..Attr3Toggle :
if (FlexSp > 0) and (FlexSt[FlexSp] = AC[Ch]) then begin
{Toggling current state off}
Dec(FlexSp);
Attr := FlexSt[FlexSp];
end else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
Attr := AC[Ch];
FlexSt[FlexSp] := Attr;
end;
XrefToggle :
if (FlexSp > 0) and (FlexSt[FlexSp] = A[XrAttr]) then begin
{Toggling current state off}
Dec(FlexSp);
Attr := FlexSt[FlexSp];
end else if FlexSp < FlexStackSize then begin
{Changing to new attribute}
Inc(FlexSp);
if Bpos = X[Xnum].Bofs then
{Selected cross-ref}
Attr := A[XsAttr]
else
{Deselected cross-ref}
Attr := A[XrAttr];
FlexSt[FlexSp] := A[XrAttr];
end;
IndexMarker :
{Skip over topic number}
Inc(Bpos, 2);
TTYOnlyMark,
SectEndMark :
Bpos := Bend; {force exit}
else
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos] {get next character to write it}
end;
if C <= ColMax then begin
if Indenting and (Ch = ' ') then
FastWriteWindow(Ch, R, C, A[TeAttr])
else begin
FastWriteWindow(Ch, R, C, Attr);
Indenting := False;
end;
Inc(C);
end;
end;
Inc(Bpos);
until (R >= Height-2) or (Bpos >= Bend); { make this screen relative }
end;
VisibleMouse;
end;
procedure DrawXref(Help : HelpPtr; Num : Xrefs);
{-Draw Xref in appropriate attribute}
var
Bpos : Word;
Bend : Word;
Attr : Byte;
R : Byte;
C : Byte;
Ch : Char;
Indenting : Boolean;
begin
with Help^, HelpState, X[Num] do begin
if (Num < 1) or (Num > XCnt) then
exit;
HiddenMouse;
Indenting := False;
Bpos := Bofs+1;
if LastLine <= Height-3 then
Bend := L[LastLine+1]-1 {LastLine is end of Buffer}
else
Bend := L[NewTopLine+Height-3];
R := Line - NewTopLine+1;
C := Col;
if Num = Xnum then
Attr := A[XsAttr]
else
Attr := A[XrAttr];
repeat
Ch := BufP^[Bpos];
case Ch of
PageBrkMark,
LineBrkMark :
begin
Inc(R);
C := ColMin + LineI[R + NewTopLine - 1];
Indenting := True;
if R >= Height-2 then
Bpos := Bend; {force exit}
end;
IndentMark:
Inc(Bpos);
IgnoreMark: {skip xref ignore marks}
;
XrefToggle,
TTYOnlyMark,
SectEndMark :
Bpos := Bend; {force exit}
else
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos] {get next character to write it}
end;
if C <= ColMax then begin
if Indenting and (Ch = ' ') then
FastWriteWindow(Ch, R, C, A[TeAttr])
else begin
FastWriteWindow(Ch, R, C, Attr);
Indenting := False;
end;
Inc(C);
end;
end;
Inc(Bpos);
until Bpos >= Bend;
end;
VisibleMouse;
end;
procedure DrawSearchString(Help : HelpPtr; SearchString : string; Attr : byte);
begin
with Help^ do
FastWrite(SearchString, Height - 1, ColH + 2, Attr);
end;
function GetNibble : Byte;
{-Return next nibble from source}
begin
if Nibble then begin
{Buffered nibble available}
GetNibble := BN shr 4;
Nibble := False;
Inc(SI);
end else begin
{First nibble of byte}
BN := Ord(SPtr^[SI]);
GetNibble := BN and $0F;
Nibble := True;
end;
end;
procedure Decompress(var X : XlateArray; Len : Word; S, D : CharArrayPtr);
{-Decompress text of length Len at S to position D, using X for translation}
var
N : Byte;
C : Char;
begin
Nibble := False;
SI := 0;
DI := 0;
SPtr := S;
Dptr := D;
while SI < Len do begin
N := GetNibble;
case N of
$0F: {three-nibble actual ASCII code}
begin
N := GetNibble;
C := Char((GetNibble shl 4) or N);
end;
$0E: {two-nibble translation code}
C := Char(X[GetNibble + 14]);
else {one-nibble translation code}
C := Char(X[N]);
end;
Dptr^[DI] := C;
Inc(DI);
end;
end;
function LoadHelp(Help : HelpPtr; Topic : Word) : Boolean;
{-Load and decompress one help topic}
var
BytesRead : Word;
Frec : HelpIndexRec;
Comp : CharArrayPtr;
begin
LoadHelp := False;
with Help^, Hdr do begin
if InRAM then begin
{Already in memory, just compute the pointer}
Frec := IndP^[Topic];
{Check for available help}
if Frec.Start = NoHelpAvailable then
Exit;
Comp := Ptr(SO(HdrP).S, SO(HdrP).O+Frec.Start);
end else if FileRec(Fil).Mode = fmInOut then begin
{On disk, first read the index}
Seek(Fil, (SizeOf(HelpHeader)+LongInt(NameSize)*HighestTopic+
SizeOf(HelpIndexRec)*(Topic-1)));
if IoResult <> 0 then
Exit;
BlockRead(Fil, Frec, SizeOf(HelpIndexRec), BytesRead);
if (IoResult <> 0) or (BytesRead <> SizeOf(HelpIndexRec)) then
Exit;
{Check for available help}
if Frec.Start = NoHelpAvailable then
Exit;
{Now read the help section}
Seek(Fil, Frec.Start);
if IoResult <> 0 then
Exit;
{Put compressed version at top of buffer}
Comp := @BufP^[BiggestTopic-Frec.CompLen];
BlockRead(Fil, Comp^, Frec.CompLen, BytesRead);
if (IoResult <> 0) or (BytesRead <> Frec.CompLen) then
Exit;
end else
{Help file not open}
Exit;
{Decompress text into BufP^[0]}
Decompress(XlateTable, Frec.CompLen, Comp, BufP);
{set the map pointer}
if (TBufPtr = 0) or (TBuff^[TbufPtr] <> Topic) then
TBufPtr := MapPointer(Help, Topic);
LoadHelp := True;
end;
end;
function FirstXref(Help : HelpPtr) : Xrefs;
{-Return index of first xref on page, 0 if none}
var
Inum : Xrefs;
begin
with Help^, HelpState do begin
for Inum := 1 to Xcnt do
with X[Inum] do
if (Line >= NewTopLine) and (Line <= (NewTopLine+Height-4))
then begin
FirstXref := Inum;
Exit;
end;
end;
FirstXref := 0;
end;
function LastXref(Help : HelpPtr) : Xrefs;
{-Return index of last xref on page, 0 if none}
var
Inum : Xrefs;
begin
with Help^, HelpState do begin
for Inum := Xcnt downto 1 do
with X[Inum] do
if (Line >= NewTopLine) and (Line <= (NewTopLine+Height-4))
then begin
LastXref := Inum;
Exit;
end;
end;
LastXref := 0;
end;
{$IFDEF UseMouse}
function MatchXref(Help : HelpPtr; Num : Xrefs; MX, MY : Byte) : Boolean;
{-Return true if any portion of xref intersects MX, MY}
var
Bpos : Word;
Bend : Word;
R : Byte;
C : Byte;
begin
MatchXref := False;
with Help^, HelpState, X[Num] do begin
Bpos := Bofs+1;
if LastLine <= Height-3 then
Bend := L[LastLine+1]-1 {LastLine is end of Buffer}
else
Bend := L[CurrentTopLine+Height-3]; {buffer offset of last visible line}
if CurrentTopLine = 1 then {draw xref relative to currenttopline}
R := Line
else
R := Line - CurrentTopLine+1;
C := Col;
repeat
case BufP^[Bpos] of
LineBrkMark :
begin
Inc(R);
C := ColMin;
end;
XrefToggle, PageBrkMark, SectEndMark, TTYOnlyMark, IndentMark :
Exit;
TTYToggle :
;
else
{Check for a match}
if (R = MY) and (C = MX) then begin
MatchXref := True;
Exit;
end;
if Bufp^[Bpos] = EscapeChar then {skip next if escape}
Inc(Bpos);
Inc(C);
end;
Inc(Bpos);
until Bpos >= Bend;
end;
end;
{ *** 4.00 *** }
function IsXRef(Help : HelpPtr; MX, MY : Byte) : Xrefs;
{-Select xref, if any, at position MX,MY}
var
Inum : Xrefs;
ScrnRow : Lines;
begin
with Help^, HelpState do begin
for ScrnRow := CurrentTopLine to (CurrentTopLine+Height-4) do begin
for Inum := 1 to Xcnt do
if X[Inum].Line = ScrnRow then
if MatchXref(Help, Inum, MX, MY) then begin
IsXRef := Inum;
Exit;
end;
IsXRef := 0;
end;
end;
end;
{ *** 4.00 *** }
function SliderPos : Byte;
{-Calculate the slider position in absolute coordinates}
{Basic formula: First pos+(Topline-1)*SBHeight div HeightLastLine}
{Note that the final -1 is necessary}
begin
with HelpState, WindowP(W)^ do
if Lastline-(YH-YL)-1 <> 0 then
SliderPos := YL + longint((NewTopLine-1)*(YH-YL)) div longint(Lastline-(YH-YL)-1)
else
SliderPos := YL;
end;
procedure UpdateMouseFrame(Help : HelpPtr);
{-Set mouse window coordinates and scroll bar}
var
SBar : Byte;
begin
HiddenMouse;
with Help^, HelpState, WindowP(W)^, Draw do begin
MouseScrollNow := MouseScroll and (LastLine-Height+3 > 0);
if MouseScrollNow then begin
{Let mouse move into frame}
MouseWindow(XL1, YL1, XH1, YH1+1);
{Draw scroll marks}
FastWrite(MouseUpMark, YL1, XH1, FAttr);
FastWrite(MouseDnMark, YH1, XH1, FAttr);
{draw scrollbar in bar character}
for SBar := 2 to YH1-1 do
FastWrite(SBarChar, SBar, XH1, FAttr);
{ShowMoreNow := False;}
Lslid := 0;
end; (* else
{Don't let mouse move into frame}
MouseWindow(XL1, YL1, XH, YH1); *)
{Draw previous help mark}
FastWrite(MouseQuitMark, YL1, XL1, FAttr);
end;
VisibleMouse;
end;
{$ENDIF}
procedure IncPrim(Help : HelpPtr; Delta : Integer);
{-Increment or decrement to next valid Xref}
var
Inum : Xrefs;
begin
with Help^, HelpState do
if Xnum <> 0 then begin
Inum := Xnum;
repeat
Inc(Xnum, Delta);
if Xnum < 1 then
XNum := Xcnt
else if Xnum > Xcnt then
XNum := 1;
until (Xnum = Inum) or ((X[Xnum].Line <= CurrentTopLine+Height-4)
and (X[Xnum].Line >= CurrentTopLine));
end;
end;
procedure IncXref(Help : HelpPtr; Delta : Integer);
{-Increment or decrement to next valid Xref and update screen}
var
Inum : Xrefs;
begin
with HelpState do begin
Inum := Xnum;
IncPrim(Help, Delta);
if Inum <> Xnum then begin
{Update highlights}
DrawXref(Help, INum);
DrawXref(Help, XNum);
end;
end;
end;
function NextXref(Help : HelpPtr; Delta : Integer) : boolean;
{-Increment or decrement to next valid Xref, non-circular}
{ returns false if no more XRefs on screen in this direction}
var
Inum : Xrefs;
begin
with Help^, HelpState do begin
Inum := XNum;
Inc(XNum, Delta);
if (XNum >= 1) and (XNum <= Xcnt) and
((X[XNum].Line <= CurrentTopLine+Height-4) and
(X[XNum].Line >= CurrentTopLine)) then begin
DrawXref(Help, INum); {clear old}
DrawXref(Help, XNum); {draw new}
NextXRef := true;
end else begin
XNum := INum; {forget it, stay on old one}
NextXRef := false;
end;
end;
end;
{ *** 4.00 *** }
procedure ScrollUp(Help : HelpPtr);
begin
HiddenMouse;
with Help^, HelpState do begin
ScrollWindow(True, 1);
{remove any partial XRef at top}
DrawLine(Help, CurrentTopLine+1, 1);
{draw new bottom line}
DrawLine(Help, CurrentTopLine+Height-3, Height-3);
DrawXRef(Help, XNum); {highlight any new XRef at bottom}
end;
VisibleMouse;
end;
procedure ScrollDown(Help : HelpPtr);
begin
HiddenMouse;
with Help^, HelpState do begin
ScrollWindow(False, 1);
{Draw new top line}
DrawLine(Help, CurrentTopLine-1, 1);
{Draw second line in case 2-line xref scrolled on}
DrawLine(Help, CurrentTopLine, 2);
{Be sure selected XRef is drawn}
DrawXRef(Help, XNum);
{ DrawLine(Help, CurrentTopLine+Height-5, Height-3);}
end;
VisibleMouse;
end;
{ *** 4.00 *** }
procedure GetHeaderString(Help : HelpPtr; Topic : Word;
var HeaderStr : string);
{-Return string for header of window}
begin
HeaderStr := GetNameString(Help, Topic);
if Length(HeaderStr) > 0 then
HeaderStr := ' '+HeaderStr+' ';
end;
procedure FrameHelp(Help : HelpPtr; Title : string);
{-Draw titled frame around help window}
begin
with Help^, Hdr, HelpState do
if ShowFrame then
FrameWindow(ColH, RowH, ColH+Width-1, Height-1, {changed}
A[FrAttr], A[HeAttr], Title);
end;
function LoadNewTopic(Help : HelpPtr; Topic : Word) : Boolean;
{-Return true if specified topic successfully loaded}
var
HeaderStr : string[80];
Dummy : boolean;
begin
with Help^, Hdr, HelpState do
if LoadHelp(Help, Topic) then begin
InitTopic(Help);
{Dummy := ResizeWindow(0, (NewHeight - OldHeight), ' ');}
{OldHeight := NewHeight;}
GetHeaderString(Help, Topic, HeaderStr);
FrameHelp(Help, HeaderStr);
LoadNewTopic := True;
end else
LoadNewTopic := False;
end;
procedure IncSp(var Sp : HelpStackIndex);
{-Increment and wrap}
begin
if Sp = MaxHelpStack then
Sp := 0
else
Inc(Sp);
end;
procedure DecSp(var Sp : HelpStackIndex);
{-Decrement and wrap}
begin
if Sp = 0 then
Sp := MaxHelpStack
else
Dec(Sp);
end;
procedure PushStack(Help : HelpPtr; Topic : Word; Line : Lines;
Xnum : Xrefs);
{-Push a help topic onto stack}
begin
with Help^ do begin
{ if Topic <> 0 then begin {!!.06}
with Stack[St] do begin
STopic := Topic;
SLine := Line;
SXnum := Xnum;
end;
IncSp(St);
if St = Sb then
IncSp(Sb);
{ end;}
end;
end;
procedure PopStack(Help : HelpPtr; var Topic : Word; var Line : Lines;
var Xnum : Xrefs);
{-Pop help topic from stack}
begin
with Help^ do begin
(*
if St = Sb then {!!.07}
Topic := 0 {!!.07}
else begin {!!.07}
*)
DecSp(St);
with Stack[St] do begin
Topic := STopic;
Line := SLine;
Xnum := SXnum;
end;
{ end; {!!.07}
end;
end;
function NextPrevious(Help : HelpPtr) : Word;
{-move to the next or previous topic in the map}
begin
with Help^.Hdr do begin
If HelpCmdNum = HksPrevious then
Dec(TBufPtr)
else
Inc(TBufPtr);
If TBufPtr > NamedTopics Then TBufPtr := 1;
If TBufPtr < 1 Then TBufPtr := NamedTopics;
NextPrevious := TBuff^[TBufPtr];
end;
end;
procedure ShowExternalHelp(Hdr : HelpHeader);
var
ExtHelpPath : String;
SaveMode : Byte;
WC : WindowCoordinates;
ScreenBufPtr : Pointer;
MSP : MouseStatePtr;
ExtHelpError : Integer;
begin
with Hdr do begin
ExtHelpPath := '';
if ExtHelpEnv <> '' then
ExtHelpPath := GetEnv(ExtHelpEnv);
if ExtHelpPath = '' then
ExtHelpPath := ExtHelpName;
SaveMode := FileMode;
FileMode := 0;
ExtHelpError := -99;
if ExistOnPath(ExtHelpPath, ExtHelpPath) then begin
if SaveWindow(1, 1, ScreenWidth, ScreenHeight, True, ScreenBufPtr) then begin
SaveMouseState(MSP, True);
StoreWindowCoordinates(WC);
Window(1, 1, ScreenWidth, ScreenHeight);
ClrScr;
ExtHelpError := ExecDos(ExtHelpPath, false, Nil);
RestoreWindowCoordinates(WC);
RestoreWindow(1, 1, ScreenWidth, ScreenHeight, True, ScreenBufPtr);
RestoreMouseState(MSP, True);
end;
end;
if ExtHelpError <> 0 then begin
Beep;
Beep;
end;
FileMode := SaveMode;
end;
end;
function ShowHelpIndex(Help : HelpPtr) : Word;
{-Display help index, return topic number if one chosen, or 0}
begin
with Help^ do
ShowHelpIndex := PickHelp(Help, PickWindow, 1, 1, PickRows, PickCols,
false, false, PickChoice);
end;
function ShowHelpPrim(Help : HelpPtr;
Var Topic : Word;
Line : Lines) : Boolean;
{-Display help screen, returning true if successful}
label
ScrollViaXRefs,
DoPopStack,
ExitHelp,
SelectATopic,
SwitchTopics,
ShowIndex, {!!.10}
ReShowIndex,
DoSearch,
ExitPoint;
var
Test : Word;
Done : Boolean;
Choice : Word;
Row : Word;
ChWord : Word;
JumpXRefLine : word;
SavePickMatrix : Word;
Key1 : Word;
Key2 : Word;
SavePickHelp : Pointer; {!! 5.09}
NumKeys : Byte;
ScrollCount : Integer; {for difference of lines}
ScrollDraw : Boolean; {flag to indicate screen redraw}
FoundRow : Word;
OldFoundMarkLine : Word;
XRDelta : integer;
XRDummy : boolean;
JumpToLine : boolean;
JumpToXRef : boolean;
XRefSearchString : string[MaxXrefSearchLen]; {XRef alpha search string}
XRefCompString : string[MaxXrefSearchLen]; {XRef search comparison
string}
XRefSearchLen : byte absolute XRefSearchString;
XRefBufIndex : word; {XRef alpha search position in buffer}
XRefCompLen : word; {length for XRef search comparison}
XRefMatch : boolean; {true if XRef search matches so far}
NewChar : char; {new character in xref search string}
{$IFDEF UseMouse}
MX : Byte; {Mouse absolute X position}
MY : Byte; {Mouse absolute Y position}
SaveMX : Byte; {Saved mouse state}
SaveMY : Byte;
SaveMXL : Byte;
SaveMXH : Byte;
SaveMYL : Byte;
SaveMYH : Byte;
SaveWaitFor : Boolean; {Saved WaitForButtonRelease variable}
SaveMouseOn : Boolean; {Was mouse cursor on at entry}
SavePickMouseEnabled : Boolean; {Was pick enabled for mouse}
Slid : Byte; {Slider position}
OldXnum : Xrefs;
NewXnum : Xrefs;
TmpXnum : Xrefs;
MouseRegion, OldMouseRegion : MouseRegionType; {init to MouseOther}
DragState, DragSave : DragStateType; {init to DragNone}
PageScrollViaBar, CommandWasMouse : boolean; {init to false}
KillDrag : Boolean;
DragDistance : Integer;
DragDelay, DragNewDelay : Word;
NewHelpCommand : HKType; {stuff commands into loop}
{$ENDIF}
PC : PickColorArray;
SaveFrameChars : FrameArray;
HeaderStr : string[80];
begin
ShowHelpPrim := False;
with Help^, Hdr, HelpState do begin
{Validate request}
if not IDOK(Help) then
Exit;
if (Topic = 0) or (Topic > HighestTopic) then
Exit;
{Set colors and frame}
AC[Attr1Toggle] := A[SpAtt1];
AC[Attr2Toggle] := A[SpAtt2];
AC[Attr3Toggle] := A[SpAtt3];
AC[IndexMarker] := 0;
AC[XrefToggle] := A[XsAttr];
PC[WindowAttr] := A[TeAttr];
PC[FrameAttr] := A[FrAttr];
PC[HeaderAttr] := A[HeAttr];
PC[SelectAttr] := A[XsAttr];
PC[AltNormal] := A[TeAttr];
PC[AltHigh] := A[XsAttr];
SaveFrameChars := FrameChars;
{Get help text into memory and initialize pointer to it}
if not LoadHelp(Help, Topic) then
Exit;
{Scan help text to find page boundaries and xref markers}
InitTopic(Help);
(*** 4.00 ***)
if Line > LineCnt then
CurrentTopLine := LineCnt - Height - 3;
(*** 4.00 ***)
ShowMoreNow := ShowMore and (LastLine-Height+4 > 0);
HelpOnScreen := True;
{$IFDEF UseMouse}
SaveMouseOn := MouseCursorOn;
if SaveMouseOn then
HideMouse;
{$ENDIF}
{Display window}
FrameChars := Frame;
GetHeaderString(Help, Topic, HeaderStr);
{create Button Bar Window}
if not MakeWindow(BBWin,
ColH, Height,
ColH+Width-1-2*FrameDelta[ShowFrame], Height,
False, True, True,
A[BBAttr], A[BBAttr], A[BBAttr], '') then
goto ExitPoint;
KeyListNum := 1; {Default to first set of button bar keys}
if HelpMouseEnabled then
InitMouseBarKeys(Help); {added in 4.0}
if not MakeWindow(WindowPtr(W),
ColH, RowH,
ColH+Width-1-2*FrameDelta[ShowFrame], Height-1,{was RowH+NewHeight}
ShowFrame, True, true,
A[TeAttr], A[FrAttr], A[HeAttr],
HeaderStr) then
goto ExitPoint;
OldHeight := NewHeight;
if not DisplayWindow(BBWin) then
goto ExitPoint;
if not DisplayWindow(W) then
goto ExitPoint;
if HideCursor then
HiddenCursor;
if not SetTopTiledWindow(W) then
goto ExitPoint;
{$IFDEF UseMouse}
if HelpMouseEnabled then
with WindowP(W)^, Draw do begin
{Save current mouse parameters}
SaveMX := MouseWhereX;
SaveMY := MouseWhereY;
SaveMXL := MouseXLo+1;
SaveMXH := MouseXHi;
SaveMYL := MouseYLo+1;
SaveMYH := MouseYHi;
SaveWaitFor := WaitForButtonRelease;
{Set new mouse parameters}
WaitForButtonRelease := True;
UpdateMouseFrame(Help);
{Position to top left corner of window}
{MouseGoToXY(Width div 2, Height div 2); {was 1,1}
VisibleMouse;
end;
{$ENDIF}
UpdateMouseFrame(Help);
ButtonBar(Help); {draw text in Button Bar Window}
{Allow user to browse help}
{ *** 4.00 *** Main Loop}
ScrollDraw := True;
ScrollCount := 0;
NewTopLine := 1;
CurrentTopLine := 0;
OldFoundMarkLine := 0;
XRDelta := 0;
XRefSearchLen := 0;
XRefMatch := false;
MouseRegion := MouseOther;
OldMouseRegion := MouseOther;
DragState := DragNone;
DragSave := DragNone;
PageScrollViaBar := False;
CommandWasMouse := False;
NewHelpCommand := HKSNone;
WaitForButtonRelease := False; {newmouse}
with HelpState do begin
Done := False;
repeat
if ((FoundMarkLine > 0) and ((CurrentTopLine = 0) or
(FoundMarkLine < CurrentTopLine) or
(FoundMarkLine > CurrentTopLine+Height-4))) then
NewTopLine := FoundMarkLine;
if (NewTopLine <> CurrentTopLine) then begin
if NewTopLine > LastLine-Height+4 then
NewTopLine := LastLine-Height+4;
if NewTopLine < 1 then
NewTopLine := 1;
ScrollCount := NewTopLine - CurrentTopLine;
OldXnum := Xnum;
{adjust if selected XRef no longer on page}
if (XNum = 0) or (X[XNum].Line < NewTopLine) then
Xnum := FirstXref(Help)
else if (X[XNum].Line > NewTopLine+Height-4) then
XNum := LastXref(Help);
{draw or scroll the page}
if ScrollDraw or (Abs(ScrollCount) > 1) then begin
DrawPage(Help, NewTopLine);
OldFoundMarkLine := 0; {old markers are gone}
end else begin
if ScrollCount = -1 then
ScrollDown(Help)
else if ScrollCount = 1 then
ScrollUp(Help);
end;
CurrentTopLine := NewTopLine;
ScrollDraw := False;
{if we just scrolled 1 line and that changed the current
xref, redraw it so the highlight shows}
if (Abs(ScrollCount) = 1) and (Xnum <> 0) and (Xnum <> OldXNum) then
DrawXref(Help, Xnum);
{move to next xref if scrolling via XRefs}
if (XNum = OldXNum) and (XRDelta <> 0) then begin
XRDummy := NextXRef(Help, XRDelta);
end;
XRDelta := 0;
{$IFDEF UseMouse}
{ if HelpMouseEnabled and MouseScrollNow then begin}
{Draw slider}
with WindowP(W)^.Draw do begin
Slid := SliderPos;
if Slid <> LSlid then begin
HiddenMouse;
if Lslid <> 0 then
FastWrite(SBarChar, Lslid, XH1, FAttr);
FastWrite(ScrollMark, Slid, XH1, FAttr);
Lslid := Slid;
VisibleMouse;
end;
end;
{ end;}
end;
{remove old "found" markers if any}
FoundRow := OldFoundMarkLine - CurrentTopLine + 2;
if ((OldFoundMarkLine > 0) and (FoundRow > 1) and
(FoundRow < Height-1)) then begin
FastWrite(' ', FoundRow, ColMin, A[HeAttr]);
FastWrite(' ', FoundRow, ColMax+2, A[HeAttr]);
OldFoundMarkLine := 0;
end;
{draw "found" markers if necessary}
FoundRow := FoundMarkLine - CurrentTopLine + 2;
if ((FoundMarkLine > 0) and (FoundRow > 1) and
(FoundRow < Height-1)) then begin
FastWrite('', FoundRow, ColMin, A[HeAttr]);
FastWrite('', FoundRow, ColMax+2, A[HeAttr]);
OldFoundMarkLine := FoundMarkLine;
FoundMarkLine := 0;
end;
{Display the search string}
if XRefSearchLen > 0 then
DrawSearchString(Help, ' ' + XRefSearchString + ' ', A[HeAttr]);
HelpCmdNum := HKSNone; {default to no command}
if CommandWasMouse then begin
if DragState = DragNone then
{non-repeatable mouse command, wait for mouse button to be released}
WaitForMouseRelease
else begin
{repeatable command, see if mouse still pressed}
if MousePressed then begin
HelpCmdNum := HKSProbe; {still pressed, fake a probe}
MouseKeyWordX := MouseLastX; {get current coordinates}
MouseKeyWordY := MouseLastY;
end else
DragState := DragNone; {button released, kill drag}
end;
end;
{$ENDIF}
if HelpCmdNum = HKSNone then
if NewHelpCommand = HKSNone then
HelpCmdNum := GetCommand(HelpKeySet, HelpKeyPtr, ChWord)
else begin
HelpCmdNum := NewHelpCommand;
NewHelpCommand := HKSNone; {reset NewHelpCommand}
end;
{Reset the search string and redraw the frame if appropriate}
if (HelpCmdNum <> HKSAlpha) or
((not HelpSaveSrch) and (not XRefMatch)) then begin
XRefSearchLen := 0;
DrawSearchString(Help, CharStr(FrameChars[Horiz],
SizeOf(XRefSearchString)), A[FrAttr]);
end;
JumpToLine := false;
JumpToXRef := false;
case HelpCmdNum of
{Alpha -- search XRefs}
HKSAlpha :
begin
NewChar := UpCase(Char(Lo(ChWord)));
if (NewChar >= #32) and (NewChar <= #127) then begin
{Accumulate search string}
if XRefSearchLen < MaxXRefSearchLen then begin
Inc(XRefSearchLen);
XRefSearchString[XRefSearchLen] := NewChar;
end;
{Search each xref for a match}
OldXNum := XNum;
XRefMatch := false;
repeat
{Check this xref}
XRefBufIndex := X[XNum].Bofs + 1;
XRefCompLen := X[XNum].Len;
{Skip ignore mark and first character if requested}
if BufP^[XRefBufIndex] = IgnoreMark then begin
Inc(XRefBufIndex, 2);
Dec(XRefCompLen);
end;
{Copy the XRef text for comparison}
XRefCompString[0] := Chr(XRefSearchLen);
Move(BufP^[XRefBufIndex], XRefCompString[1], XRefSearchLen);
{Compare search string to xref if string is not too long}
XRefMatch := (XRefSearchLen <= XRefCompLen) and
(CompString(XRefSearchString, StUpCase(XRefCompString))
= Equal);
{Move to next xref}
Inc(XNum, 1);
until XRefMatch or (XNum > XCnt);
if XRefMatch then begin
Inc(XNum, -1);
if (X[XNum].Line < CurrentTopLine) or
(X[XNum].Line > CurrentTopLine+Height-4) then
NewTopLine := X[XNum].Line {not on screen, redraw}
else begin
DrawXref(Help, OldXNum); {on screen, clear old XRef}
DrawXref(Help, XNum); {and draw new}
end;
end else begin
XNum := OldXNum; {restore previous XRef number}
Beep;
Dec(XRefSearchLen); {discard erroneous character}
end;
end;
end;
HKSUp :
NewTopLine := CurrentTopLine-1;
HKSDown :
NewTopLine := CurrentTopLine+1;
{Commands to move xref highlight}
HKSLeft :
IncXRef(Help, -1); {move xref up, circular}
HKSRight :
IncXRef(Help, +1); {move xref down, circular}
{Commands to scroll via XRefs}
HKSXUp :
begin
XRDelta := -1;
goto ScrollViaXRefs
end;
HKSXDown :
begin
XRDelta := 1;
ScrollViaXRefs:
{if no XRef or we can't move the XRef, scroll the display}
if (XNum = 0) or (not NextXRef(Help, XRDelta)) then
NewTopLine := CurrentTopLine + XRDelta
end;
{Commands to select another page of help}
HKSPgUp :
begin
if CurrentTopLine <> 1 then begin
NewTopLine := CurrentTopLine-Height+4;
ScrollDraw := True;
end;
end;
HKSPgDn :
begin
if CurrentTopLine <> LastLine-Height+4 then begin
NewTopLine := CurrentTopLine+Height-4;
ScrollDraw := True;
end;
end;
HKSHome :
begin
NewTopLine := 1;
ScrollDraw := True;
end;
HKSEnd :
begin
NewTopLine := LastLine-Height+4;
ScrollDraw := True;
end;
HKSPrint :
{send the current topic's TTY Output to the std printer}
PrintTopic(Help, Topic);
HKSNSearch :
{search again}
if FoundLine > 0 then
goto DoSearch
else
Beep;
HKSTSearch :
begin
{search for text within this topic}
SearchGlobal := false;
SearchStartPos := 0;
goto DoSearch;
end;
HKSGSearch :
begin
{search for text globally}
SearchGlobal := true;
SearchStartPos := 0;
DoSearch:
if SearchText(Help, Topic, SearchGlobal) then begin
{changed to a new topic}
CurrentTopLine := 0;
ScrollDraw := True;
ScrollCount := 0;
ShowMoreNow := ShowMore and (LastLine-Height+4 > 0);
end;
end;
{$IFDEF UseMouse}
{Mouse probe}
HKSProbe :
begin
if HelpMouseEnabled then
with WindowP(W)^, Draw do begin
{Get absolute mouse coordinate}
MX := MouseXLo+MouseKeyWordX;
MY := MouseYLo+MouseKeyWordY;
if (MX = XL1) and (MY = YL1) then
MouseRegion := MouseClose
else if MouseScrollNow and ((MX = XH1) or (MX = XH1 - 1))
then begin
{In the scroll bar region}
MouseRegion := MouseScrollBar; {assume scroll bar}
{if we aren't in the middle of dragging the slider, see
if the mouse cursor is on a line up or line down arrow}
if ((DragState <> DragSlider) and
((DragState <> DragHold) or (DragSave <> DragSlider)))
then
if MY = YL1 then MouseRegion := MouseLineUp
else if MY = YH1 then MouseRegion := MouseLineDown
else if MY = YH1 + 1 then MouseRegion := MouseOther;
end else if (MY = YH1+1) and (MX < XH1) then
MouseRegion := MouseButtonBar
else {if (MY >= YL) and (MY <= YH) then}
MouseRegion := MouseOther;
{see if we were already dragging}
if DragState <> DragNone then begin
{we were dragging -- is the mouse in the same region?}
if MouseRegion = OldMouseRegion then begin
{yes it's the same region, repeat the action}
if DragState = DragHold then {first remove any hold}
DragState := DragSave;
{for the slider, set a single line scroll with no delay}
if DragState = DragSlider then begin
if DragDistance = 0 then begin
{start dragging if mouse moved}
if MY > Lslid then
DragDistance := 1 {scroll up, no delay}
else if MY < Lslid then
DragDistance := -1; {scroll down, no delay}
{stop dragging if slider moved down to meet us, but
be sure we don't get stuck at bottom of screen}
end else if ((DragDistance > 0) and (MY <= LSlid) and
((LSlid < YH) or (CurrentTopLine = (LastLine - Height
+ 4)))) then begin
DragDistance := 0;
MouseGotoXY(MX, LSlid);
{stop dragging if slider moved up to meet us, but
be sure we don't get stuck at top of screen}
end else if ((DragDistance < 0) and (MY >= LSlid) and
((LSlid > YL) or (CurrentTopLine = 1))) then begin
DragDistance := 0;
MouseGotoXY(MX, LSlid);
end;
{it's not the slider, so we must be scrolling}
end else begin {not moving slider}
if PageScrollViaBar then begin
if (((DragDistance > 0) and (MY <= Lslid)) or
((DragDistance < 0) and (MY >= Lslid)))
then
KillDrag := true; {reached slider, kill drag}
end;
while ((DragDelay > 0) and (not KillDrag)) do begin {do any delay}
Delay(50); {wait for a clock tick}
Dec(DragDelay,50); {adjust remaining delay}
KillDrag := not MousePressed; {quit if button released}
end;
DragDelay := DragNewDelay; {adjust repeat rate after 1st time}
end;
if KillDrag then begin
DragState := DragNone;
DragDistance := 0;
DragDelay := 0;
DragNewDelay := 0;
end;
{we were dragging -- but the mouse moved out of the region}
end else if DragState <> DragHold then begin
DragSave := DragState; {save state}
DragState := DragHold; {hold until something changes}
end;
{we weren't dragging, set up the appropriate event for the probe}
end else begin
DragDelay := 0; {initialize first delay}
DragNewDelay := 0; {initialize repeat delay}
DragDistance := 0; {initialize distance}
KillDrag := False; {initialize kill}
PageScrollViaBar := False; {initialize scroll bar paging}
case MouseRegion of
MousePgUp, MousePgDn: {move a page at a time}
begin
DragState := DragScroll; {start scrolling}
DragDelay := PageDragFirst; {delay for first repeat}
DragNewDelay := PageDragRep; {subsequent repeats}
DragDistance := Height - 4; {scroll distance}
if MouseRegion = MousePgUp then {switch direction for PgUp}
DragDistance := -DragDistance;
end;
MouseLineUp, MouseLineDown: {move a line at a time}
begin
DragState := DragScroll; {start scrolling}
DragDelay := LineDragFirst; {delay for first repeat}
DragNewDelay := LineDragRep; {subsequent repeats}
DragDistance := 1; {scroll distance}
if MouseRegion = MouseLineUp then {switch direction for line up}
DragDistance := -DragDistance;
end;
MouseScrollBar: {in the scroll bar}
begin
if MY = Lslid then
DragState := DragSlider {just set slider state}
else begin
DragState := DragScroll; {start scrolling}
PageScrollViaBar := true; {set scroll bar paging}
DragDelay := PageDragFirst; {delay for first repeat}
DragNewDelay := PageDragRep; {subsequent repeats}
DragDistance := Height - 4; {scroll distance}
if MY < Lslid then {switch direction for PgUp}
DragDistance := -DragDistance;
end;
end;
MouseClose: {close the window}
NewHelpCommand := HKSExit;
MouseButtonBar :
NewHelpCommand := GetBBCommand(Help, MX);
MouseOther:
begin {In active pick region, convert to window relative}
Dec(MX, XL-1);
Dec(MY, YL-1);
{Select another xref if possible}
NewXnum := IsXRef(Help, MX, MY);
if NewXnum <> 0 then
if NewXnum = Xnum then
{Second click on item, select it}
goto SelectATopic
else begin
{Move highlight to item}
TmpXnum := Xnum;
Xnum := NewXnum;
DrawXref(Help, TmpXnum);
DrawXref(Help, Xnum);
end;
end;
end; {case MouseRegion}
{save region for next pass}
if (DragState = DragScroll) or (DragState = DragSlider) then
OldMouseRegion := MouseRegion;
end; {we weren't dragging}
if (DragState = DragScroll) or (DragState = DragSlider) then {adjust top line}
NewTopLine := CurrentTopLine + DragDistance;
CommandWasMouse := True; {show we had a mouse command}
end; {With ...}
end; {HKSProbe}
{$ENDIF}
{Commands to exit help or select another topic}
HKSToC : {show Table of Contents if available}
begin
if FirstTopic = 0 then
goto ShowIndex;
PushStack(Help, Topic, CurrentTopLine, Xnum);
Topic := FirstTopic;
goto SwitchTopics;
end;
HKSIndex :
begin
ShowIndex:
PushStack(Help, Topic, CurrentTopLine, Xnum);
ReShowIndex:
Topic := ShowHelpIndex(Help);
case Topic of
0:
goto DoPopStack;
$FFFF:
begin
ShowExternalHelp(Hdr);
goto ReShowIndex;
{ goto DoPopStack;}
end;
else begin
PushStack(Help, 0, 0, 0); {put index on stack}
goto SwitchTopics;
end;
end;
end;
HKSBack :
DoPopStack:
if St = Sb then begin
HelpCmdNum := HKSExit; {fake an exit}
goto ExitHelp;
end else begin
WaitForMouseRelease;
{Restore previous displayed topic and page}
PopStack(Help, Topic, Line, OldXNum);
if (Topic = 0) then
goto ReShowIndex;
JumpToLine := true;
JumpToXRef := true;
Goto SwitchTopics;
end;
HKSExit, HKSQuickExit, HKSExitSave, HKSUser0..HKSUser3 :
ExitHelp:
begin
WaitForMouseRelease;
Done := True;
ShowHelpPrim := True;
end;
HksPrevious, HksNext :
Begin
PushStack(Help, Topic, CurrentTopLine, Xnum);
Topic := NextPrevious(Help);
Goto SwitchTopics;
End;
HKSKeys :
Begin
PushStack(Help, Topic, CurrentTopLine, Xnum);
Topic := KeysTopic;
Goto SwitchTopics;
End;
HKSSelect :
If Xnum <> 0 then begin
SelectATopic:
{topic 0 is index, FFFF is external help}
case X[Xnum].Topic of
0:
NewHelpCommand := HKSIndex;
$FFFF:
ShowExternalHelp(Hdr);
else begin
{Save current help topic and page}
PushStack(Help, Topic, CurrentTopLine, Xnum);
Topic := X[Xnum].Topic;
SwitchTopics:
Done := not LoadNewTopic(Help, Topic);
if not Done then begin
CurrentTopLine := 0;
if JumpToLine then
NewTopLine := Line
else
NewTopLine := 1;
if JumpToXRef then begin
XNum := OldXNum;
OldXNum := 0;
XRDelta := 0;
end;
ScrollDraw := True;
ScrollCount := 0;
ShowMoreNow := ShowMore and (LastLine-Height+4 > 0);
XRefSearchLen := 0;
{$IFDEF UseMouse}
{ if HelpMouseEnabled then}
UpdateMouseFrame(Help);
ButtonBar(Help);
{$ENDIF}
end;
end;
end;
end;
HKSExtHelp :
ShowExternalHelp(Hdr);
HKSSwapKeys : {swap button bar keys}
begin
Inc(KeyListNum);
if KeyListNum > NKeyLists then
KeyListNum := 1;
if HelpMouseEnabled then
InitMouseBarKeys(Help);
ButtonBar(Help);
end;
end;
until Done;
{Restore the screen}
{========================================================================}
{ CAUTION!! HksExitSave bypasses the normal screen cleanup routine when }
{ it exits. It is provided so that the help screen can be retained when }
{ the program terminates. Using it without terminating the program can }
{ have unknown and undesired side-effects. }
{========================================================================}
HiddenMouse;
if HelpCmdNum = HksExitSave then
DisposeWindow(W)
else
DisposeWindow(EraseTopWindow);
if SetTopTiledWindow(BBWin) then
DisposeWindow(EraseTopWindow);
(*
If HelpCmdNum <> HksExitSave Then
DisposeWindow(EraseTopWindow);
*)
{$IFDEF UseMouse}
if HelpMouseEnabled then begin
{Restore mouse position and window}
MouseWindow(SaveMXL, SaveMYL, SaveMXH, SaveMYH);
MouseGoToXY(SaveMX, SaveMY);
WaitForButtonRelease := SaveWaitFor;
WaitForMouseRelease;
end;
if SaveMouseOn then
ShowMouse
else
HideMouse;
{$ENDIF}
ExitPoint:
FrameChars := SaveFrameChars;
HelpOnScreen := False;
end;
end;
end; { with Helpstate }
function ShowHelp(Help : HelpPtr; Var Topic : Word;
StartAtMark : boolean) : Boolean;
{-Display help screen, returning true if successful}
var
StartLine : Lines;
begin
with Help^ do begin
St := 0;
Sb := 0;
end;
StartLine := 1;
with HelpState do
if StartAtMark and (FoundMarkLine > 0) then
StartLine := FoundMarkLine
else begin
SearchStartPos := 0;
FoundMarkLine := 0;
end;
ShowHelp := ShowHelpPrim(Help, Topic, StartLine)
end;
function FindHelp(Help : HelpPtr; Name : string; MatchFunc : Pointer) : Word;
{-Return topic number of help with specified Name, 0 if not found}
label
ExitPoint;
var
NP : StringPtr;
I : Word;
function CallMatch(S1, S2 : string) : Boolean;
{-Call routine pointed to by MatchFunc}
inline($FF/$5E/<MatchFunc); {Call dword ptr [bp+<MatchFunc]}
begin
FindHelp := 0;
if MatchFunc = nil then
MatchFunc := @Match;
with Help^, Hdr do begin
{Validate help structure}
if not IDOK(Help) then
Exit;
{Match the name}
NP := StringPtr(PBuff);
for I := 1 to HighestTopic do
if CallMatch(NP^, Name) then begin
FindHelp := I;
Exit;
end else
Inc(SO(NP).O, NameSize);
{Clear the topic stack}
end;
end;
function WordChar(Ch : Char) : Boolean;
{-Return true if Ch is a character in a word}
begin
case Upcase(Ch) of
'A'..'Z', '_', '0'..'9' : WordChar := True;
else
WordChar := False;
end;
end;
function PickHelp(Help : HelpPtr; var PickW : WindowPtr;
XLow, YLow, YHigh, PickCols : Byte;
OldWindow, SaveWindow : boolean;
var Choice : word) : Word;
{-Display help pick list, returning Topic number, or 0 for none}
var
XHigh : Byte;
SaveFrameChars : FrameArray;
SavePickMatrix : Byte;
SavePickMouseEnabled : Boolean;
PC : PickColorArray;
PickRow : word;
Topic : word;
begin
PickHelp := 0;
with Help^, Hdr, HelpState do begin
{Validate help structure}
if not IDOK(Help) then
Exit;
{Set colors and frame}
PC[WindowAttr] := A[TeAttr];
PC[FrameAttr] := A[FrAttr];
PC[HeaderAttr] := A[HeAttr];
PC[SelectAttr] := A[XsAttr];
PC[AltNormal] := A[TeAttr];
PC[AltHigh] := A[XsAttr];
SaveFrameChars := FrameChars;
SavePickMatrix := TpPick.PickMatrix;
{Set up global with NameSize}
NSize := NameSize;
FrameChars := Frame;
{Set the pick matrix to the number of columns that fit}
{ if (PickCols * (NameSize + 1)) <= (ScreenWidth - XLow - 2) then}
if (PickCols * (PickSize + 1)) <= (ScreenWidth - XLow - 2) then
TpPick.PickMatrix := PickCols
else
{ TpPick.PickMatrix := (ScreenWidth - XLow - 2) div (NameSize + 1);}
TpPick.PickMatrix := (ScreenWidth - XLow - 2) div (PickSize + 1);
{And set the end of the window based on the pick matrix}
{ XHigh := XLow + (TpPick.PickMatrix * (NameSize + 1)) + 1;}
XHigh := XLow + (TpPick.PickMatrix * (PickSize + 1)) + 1;
if (FillPickScreen) then begin
XHigh := TpCRT.ScreenWidth;
YHigh := TpCRT.ScreenHeight;
end;
{$IFDEF UseMouse}
if HelpMouseEnabled then begin
{Assure mouse is also on in TPPICK}
SavePickMouseEnabled := PickMouseEnabled;
if not PickMouseEnabled then
EnablePickMouse;
end;
{$ENDIF}
{Pick from list}
(* if OldWindow then
OldWindow := DisplayWindow(PickW);*)
if (OldWindow or MakeWindow(PickW, XLow, YLow, XHigh, YHigh,
UseHelpFrame, true, true, PC[WindowAttr], PC[FrameAttr],
PC[HeaderAttr], HelpTitle)) then begin
PickRow := 1;
FillPickWindow(PickW, @SendHelpName, NamedTopics,
PC, Choice, PickRow);
PickBar(PickW, @SendHelpName, NamedTopics, PC, false,
Choice, PickRow);
if PickCmdNum = PKSSelect then
PickHelp := TBuff^[Choice]
else if PickCmdNum = PKSUser0 then begin
Topic := 0; {force search of all topics}
if SearchText(Help, Topic, true) then
PickHelp := Topic;
end;
end; {if OldWindow ...}
{$IFDEF UseMouse}
if HelpMouseEnabled then
if not SavePickMouseEnabled then begin
{Assure mouse is now off in TPPICK}
DisablePickMouse;
{But that it stays on for TPHELP}
EnableHelpMouse;
end;
{$ENDIF}
FrameChars := SaveFrameChars;
TpPick.PickMatrix := SavePickMatrix;
end;
(* PickW := EraseTopWindow;
if not SaveWindow then
DisposeWindow(PickW);*)
if not SaveWindow then
DisposeWindow(EraseTopWindow);
end;
function AddHelpCommand(Cmd : HKtype; NumKeys : Byte; Key1, Key2 : Word) : Boolean;
{-Add a new command key assignment or change an existing one}
begin
AddHelpCommand := AddCommandPrim(HelpKeySet, HelpKeyMax, Cmd, NumKeys, Key1, Key2);
end;
procedure DisableHelpIndex;
{-Disable the F1 help index inside of a help screen}
var
Junk : Boolean;
begin
Junk := AddHelpCommand(HKSNone, 1, $3B00, 0);
{$IFDEF UseMouse}
Junk := AddHelpCommand(HKSNone, 1, $ED00, 0);
{$ENDIF}
HelpIndexDisabled := True;
end;
procedure EnableHelpIndex;
{-Enable the F1 help index inside of a help screen}
var
Junk : Boolean;
begin
Junk := AddHelpCommand(HKSIndex, 1, $3B00, 0);
{$IFDEF UseMouse}
Junk := AddHelpCommand(HKSIndex, 1, $ED00, 0);
{$ENDIF}
HelpIndexDisabled := False;
end;
{$IFDEF UseMouse}
procedure EnableHelpMouse;
{-Enable mouse control of the help system}
begin
if MouseInstalled then begin
HelpKeyPtr := @TpMouse.ReadKeyOrButton;
EnableEventHandling;
HelpMouseEnabled := True;
end;
end;
procedure DisableHelpMouse;
{-Disable mouse control of the help system}
begin
if HelpMouseEnabled then begin
HelpKeyPtr := @ReadKeyWord;
DisableEventHandling;
HelpMouseEnabled := False;
end;
end;
{$ENDIF}
procedure Beep;
{error beep}
begin
Sound(880);
Delay(200);
NoSound;
Delay(100);
end;
procedure OneLineWindow(Help : HelpPtr; LeftIndent, WinWidth,
TopOffset : byte; TitleString : string);
begin
with Help^, Hdr do begin
Shadow := true;
if not MakeWindow(PopWindow, ColH+LeftIndent, RowH+TopOffset,
ColH+LeftIndent+WinWidth, RowH+TopOffset+2, True, True, True,
A[PWAttr], A[PWAttr], A[PWAttr], TitleString) then begin
Shadow := false;
exit;
end;
if not DisplayWindow(PopWindow) then
exit;
Shadow := false;
end;
end;
procedure OneLinePrompt(Help : HelpPtr; InputLength : byte;
PromptString : string; var InputString : string);
var
PWindow : WindowPtr;
Escaped : boolean;
begin
with Help^, Hdr do begin
WindowRelative := true;
ReadString(PromptString, 1, 1, InputLength, A[PIAttr], A[PIAttr],
A[PIAttr], Escaped, InputString);
if Escaped then
InputString := '';
end;
end;
procedure PrintTopic(Help : HelpPtr; Topic : word);
{Print the current topic to the standard printer}
const
PrintColWidth : Byte = 80;
PrintPageLength : Byte = 58;
var
DeviceName : string[40];
Bpos : Word;
R : Byte;
C : Byte;
Ch : Char;
TTYState : Boolean;
Finished : Boolean;
IOTest : Word;
LineOut : String;
IndentWidth : byte;
SaveIndentWidth : byte;
LineIndent : boolean;
begin
if LstOpen then
DeviceName := LstName
else
DeviceName := 'LPT1';
{$IFDEF GERMAN}
OneLineWindow(Help, 10, 58, 5, '');
OneLinePrompt(Help, 40, ' Drucke nach: ', DeviceName);
{$ELSE}
OneLineWindow(Help, 10, 55, 5, '');
OneLinePrompt(Help, 40, ' Print to: ', DeviceName);
{$ENDIF}
DisposeWindow(EraseTopWindow);
if DeviceName = '' then
exit;
if LstOpen and (DeviceName <> LstName) then begin
Close(Lst);
LstOpen := false;
end;
if not LstOpen then begin
Assign(Lst, DeviceName);
Rewrite(Lst);
LstOpen := True;
LstName := DeviceName;
end;
if IOResult <> 0 then begin
Beep; Beep; Beep;
Exit;
end;
with Help^ do begin
Bpos := 0; {starting position of top line}
C := 1;
IndentWidth := 0;
LineIndent := false;
LineOut := '';
Finished := False;
{$IFDEF GERMAN}
WriteLn(Lst, 'Stichwort der 4DOS-Hilfe: ', GetNameString(Help, Topic));
{$ELSE}
WriteLn(Lst, '4DOS Help Topic: ', GetNameString(Help, Topic));
{$ENDIF}
WriteLn(Lst, '');
R := 3;
repeat
Ch := BufP^[Bpos];
case Ch of
Attr1Toggle..Attr3Toggle, XrefToggle, TTYToggle :
;
IndexMarker :
{Skip over topic number}
Inc(Bpos, 2);
IndentMark :
begin
SaveIndentWidth := IndentWidth;
IndentWidth := Byte(Bufp^[Bpos+1]); {get indent width}
if IndentWidth >= 128 then begin
LineIndent := true; {indent changes for one line only}
IndentWidth := IndentWidth - 128;
end;
Inc(Bpos); {skip width}
end;
TTYOnlyMark,
SectEndMark :
begin
if LineOut <> '' then {the last line may contain text}
WriteLn(Lst, LineOut);
Finished := True;
end;
else
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos] {get next character to write it}
end;
if C <= PrintColWidth then {printable character}
case Ch of
LineBrkMark, PageBrkMark :
begin
if R = PrintPageLength then begin
WriteLn(Lst, #12); {print 58 lines per page}
IOTest := IOResult;
if IOTest <> 0 then begin
Beep; Beep;
Exit;
end;
R := 1;
end;
WriteLn(Lst, LineOut);
IOTest := IOResult;
if IOTest <> 0 then begin
Beep; Beep;
Exit;
end;
LineOut := '';
C := 1;
Inc(R);
if LineIndent then begin
IndentWidth := SaveIndentWidth;
LineIndent := false;
end;
end
else begin
if (C = 1) and (IndentWidth > 0) then begin
FillChar(LineOut[1], IndentWidth, ' ');
LineOut[0] := Char(IndentWidth);
Inc(C, IndentWidth);
end;
LineOut := Lineout + Ch;
Inc(C);
end;
end;
end;
Inc(Bpos);
until Finished;
end;
WriteLn(Lst, #12); {insert FF at end of TTY print}
end;
function SearchText(Help : HelpPtr; var Topic : word;
GlobalSearch : boolean) : boolean;
{Search for a string}
var
Ch : char;
Bpos : word;
SearchPos : word;
Finished : boolean;
Found : boolean;
BogusSpace : boolean;
SkipIncr : boolean;
DoingGlobal : boolean;
SaveTopic : word;
HeaderStr : string[80];
SearchTitle : string[40];
WindowUp : boolean;
QuitGlobal : boolean;
SearchAll : boolean;
IndexBuf : HelpIndexPtr;
IndexBufSize : word;
SearchStartLine : Lines;
label
SearchExit;
begin
WindowUp := false;
SearchText := false;
IndexBuf := nil;
with Help^, Hdr, HelpState do begin
{$IFDEF GERMAN}
if GlobalSearch then
SearchTitle := ' Globale Suche (Esc für Abbruch) '
else
SearchTitle := ' Suche im Stichwort ';
{$ELSE}
if GlobalSearch then
SearchTitle := ' Global Search (Esc to stop) '
else
SearchTitle := ' Topic Search ';
{$ENDIF}
SearchAll := (Topic = 0);
if SearchAll then begin
SearchStartPos := 0;
FoundMarkLine := 0;
Topic := HighestTopic; {force wrap to first topic}
BufP^[0] := SectEndMark; {force topic increment}
end;
if SearchStartPos = 0 then begin
SearchString := '';
{$IFDEF GERMAN}
OneLineWindow(Help, 5, 66, 5, SearchTitle);
OneLinePrompt(Help, 40, ' Suchstring: ', SearchString);
{$ELSE}
OneLineWindow(Help, 5, 70, 5, SearchTitle);
OneLinePrompt(Help, 40, ' Enter search string: ', SearchString);
{$ENDIF}
SearchLen := Length(SearchString);
if SearchLen = 0 then begin
DisposeWindow(EraseTopWindow);
exit;
end;
if not GlobalSearch then
DisposeWindow(EraseTopWindow)
else
WindowUp := true; {get rid of window later}
Bpos := 0;
FoundLine := 1;
end else begin
Bpos := SearchStartPos + 1;
if BufP^[Bpos] = EscapeChar then
Inc(Bpos);
if GlobalSearch then begin {window for search progress msg}
OneLineWindow(Help, 5, 70, 5, SearchTitle);
WindowUp := true;
end;
end;
SearchPos := 1;
Finished := false;
Found := false;
BogusSpace := false;
SkipIncr := false;
DoingGlobal := false;
QuitGlobal := false;
repeat
if BogusSpace then begin
Ch := ' ';
BogusSpace := false;
SkipIncr := true;
end else
Ch := BufP^[Bpos];
case Ch of
Attr1Toggle..Attr3Toggle, XrefToggle, TTYToggle :
;
IndexMarker :
{Skip over topic number}
Inc(Bpos, 2);
IndentMark :
Inc(Bpos); {skip indent width}
LineBrkMark, PageBrkMark :
begin
Inc(FoundLine);
BogusSpace := ((Bpos > 1) and (BufP^[Bpos - 1] <> ' '));
end;
TTYOnlyMark,
SectEndMark :
if not GlobalSearch then begin
FoundLine := 0; {didn't find it}
Finished := true;
end else begin
if DoingGlobal then begin {global search in process}
if KeyPressed then
QuitGlobal := (Lo(ReadKeyWord) = $1B) {Esc}
else if MousePressed then
QuitGlobal := (MouseKeyWord = $EE00); {Rt Button}
end else begin {not found in current topic,
start new global search}
SaveTopic := Topic;
ClrScr;
{Read the sequential list so we can move through it quickly}
if not GetBuffer(Help, IndexBuf,
SizeOf(HelpHeader) + LongInt(HighestTopic)*(NameSize),
HighestTopic*SizeOf(HelpIndexRec), IndexBufSize)
then begin
Beep; Beep; Beep;
goto SearchExit;
end;
{$IFDEF GERMAN}
FastWriteWindow('Suche ... ', 1, 1, A[HeAttr]);
{$ELSE}
FastWriteWindow('Searching ... ', 1, 1, A[HeAttr]);
{$ENDIF}
end;
DoingGlobal := true;
repeat {find next valid topic in index}
Inc(Topic);
if Topic > HighestTopic then Topic := 1;
until (IndexBuf^[Topic].Start <> NoHelpAvailable) or
(Topic = SaveTopic);
if QuitGlobal or (Topic = SaveTopic) or
(not LoadHelp(Help, Topic)) then begin
Topic := SaveTopic;
if (not SearchAll) and (not LoadNewTopic(Help, Topic))
then begin
Beep; Beep;
Halt(11);
end;
FoundLine := 0;
Finished := True;
end else begin
BPos := $FFFF; {increments to 0!}
SearchPos := 1;
FoundLine := 1;
{$IFDEF GERMAN}
FastFillWindow(55, ' ', 1, 11, A[TeAttr]);
FastWriteWindow(GetNameString(Help, Topic), 1, 11, A[TeAttr]);
{$ELSE}
FastFillWindow(55, ' ', 1, 15, A[TeAttr]);
FastWriteWindow(GetNameString(Help, Topic), 1, 15, A[TeAttr]);
{$ENDIF}
end;
end;
else begin
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos]; {get next character}
end;
if UpCase(Ch) <> UpCase(SearchString[SearchPos]) then begin
if SearchPos > 1 then begin
Bpos := SearchStartPos; {no match, back up}
FoundLine := SearchStartLine;
SkipIncr := false;
end;
SearchPos := 1; {restart comparison}
BogusSpace := false;
end else begin {character matched}
if SearchPos = 1 then begin
SearchStartPos := Bpos; {save start of matching string}
SearchStartLine := FoundLine;
end;
Inc(SearchPos);
if SearchPos > SearchLen then begin {all matched, found it!}
FoundLine := SearchStartLine;
Finished := True;
end;
end;
end;
end;
if not SkipIncr then
Inc(Bpos);
SkipIncr := false;
until Finished;
if WindowUp then
DisposeWindow(EraseTopWindow);
if FoundLine = 0 then begin
if not QuitGlobal then
Beep
end else begin
if DoingGlobal and (not SearchAll) then begin
InitTopic(Help);
GetHeaderString(Help, Topic, HeaderStr);
FrameHelp(Help, HeaderStr);
{$IFDEF UseMouse}
{ if HelpMouseEnabled then}
UpdateMouseFrame(Help);
ButtonBar(Help);
{$ENDIF}
end;
end;
FoundMarkLine := FoundLine;
end;
if IndexBuf <> nil then
FreeMemCheck(IndexBuf, IndexBufSize);
SearchText := DoingGlobal and (not QuitGlobal);
SearchExit:
end;
function ShowHelpTTY(Help : HelpPtr;
Var Topic : Word) : Boolean;
{-Display help screen, returning true if successful}
var
Done : Boolean;
HeaderStr : string[80];
function IsTTYAvailable(Help : HelpPtr) : Boolean;
{does the topic contain TTY text?}
var
Bpos : Word;
Ch : Char;
Finished : Boolean;
begin
with Help^ do begin
Bpos := 0; {starting position of top line}
Finished := False;
IsTTYAvailable := False;
repeat
Ch := BufP^[Bpos];
case Ch of
SectEndMark :
Finished := True;
IndentMark :
Inc(Bpos);
TTYOnlyMark,
TTYToggle :
begin
IsTTYAvailable := True;
Exit;
end;
end;
Inc(Bpos);
until Finished;
end;
end;
procedure OutputTTY(Help : HelpPtr);
var
Bpos : Word;
R : Byte;
C : Byte;
Ch : Char;
TTYState : Boolean;
Finished : Boolean;
LineOut : String;
IndentWidth : byte;
SaveIndentWidth : byte;
LineIndent : boolean;
begin
with Help^ do begin
Bpos := 0; {starting position of top line}
C := 1;
LineOut := '';
TTYState := False;
Finished := False;
IndentWidth := 0;
LineIndent := false;
repeat
Ch := BufP^[Bpos];
case Ch of
Attr1Toggle..Attr3Toggle, XrefToggle :
;
IndexMarker :
{Skip over topic number}
Inc(Bpos, 2);
SectEndMark :
begin
if LineOut <> '' then {the last line may contain text}
WriteLn(LineOut);
Finished := True;
end;
TTYOnlyMark:
TTYState := True;
TTYToggle :
TTYState := not TTYState;
IndentMark :
begin
SaveIndentWidth := IndentWidth;
IndentWidth := Byte(Bufp^[Bpos+1]); {get indent width}
if IndentWidth >= 128 then begin
LineIndent := true; {indent changes for one line only}
IndentWidth := IndentWidth - 128;
end;
Inc(Bpos); {skip width}
end;
else
if Ch = EscapeChar then begin
Inc(Bpos); {move to next character}
Ch := BufP^[Bpos] {get next character to write it}
end;
if TTYState then
case Ch of
LineBrkMark, PageBrkMark :
begin
WriteLn(LineOut);
LineOut := '';
C := 1;
if LineIndent then begin
IndentWidth := SaveIndentWidth;
LineIndent := false;
end;
end
else begin
if C <= ScreenWidth then begin
if (C = 1) and (IndentWidth > 0) then begin
FillChar(LineOut[1], IndentWidth, ' ');
LineOut[0] := Char(IndentWidth);
Inc(C, IndentWidth);
end;
LineOut := Lineout + Ch;
Inc(C);
end;
end;
end;
end;
Inc(Bpos);
until Finished;
end;
end;
begin
ShowHelpTTY := False;
with Help^, Hdr, HelpState do begin
{Validate request}
if not IDOK(Help) then
Exit;
if (Topic = 0) or (Topic > HighestTopic) then begin
{$IFDEF GERMAN}
WriteLn('Unzulässiges Hilfe-Stichwort gewählt');
{$ELSE}
WriteLn('Invalid Help Topic Chosen.');
{$ENDIF}
Exit;
end;
{Get help text into memory and initialize pointer to it}
if not LoadHelp(Help, Topic) then
Exit;
if IsTTYAvailable(Help) then
OutputTTY(Help)
else
{$IFDEF GERMAN}
WriteLn('Kein "/?" Hilfetext verfügbar.');
{$ELSE}
WriteLn('No "/?" help text available.');
{$ENDIF}
ShowHelpTTY := True;
end;
end;
begin
HelpKeyPtr := @ReadKeyWord;
HelpOnScreen := False;
LstOpen := false;
{$IFDEF UseMouse}
HelpMouseEnabled := False;
{$ENDIF}
HelpResize := false;
with HelpState do begin
FoundMarkLine := 0;
FoundLine := 0;
end;
end.
|
{$include lem_directives.inc}
unit LemAnimationSet;
interface
uses
Classes, GR32,
LemCore,
LemTypes,
LemMetaAnimation,
LemAnimation;
type
{-------------------------------------------------------------------------------
base class animationset
-------------------------------------------------------------------------------}
TBaseAnimationSet = class(TPersistent)
private
procedure SetMetaLemmingAnimations(Value: TMetaLemmingAnimations);
procedure SetMetaMaskAnimations(Value: TMetaAnimations);
protected
fMetaLemmingAnimations : TMetaLemmingAnimations; // meta data lemmings
fMetaMaskAnimations : TMetaAnimations; // meta data masks (for bashing etc.)
fLemmingAnimations : TBitmaps; // the list of lemmings bitmaps
fMaskAnimations : TBitmaps; // the list of masks (for bashing etc.)
fBrickColor : TColor32;
{ new virtuals }
function DoCreateMetaLemmingAnimations: TMetaLemmingAnimations; virtual;
function DoCreateMetaMaskAnimations: TMetaAnimations; virtual;
{ internals }
procedure DoReadMetaData; virtual; abstract;
procedure DoReadData; virtual; abstract;
procedure DoClearData; virtual; abstract;
public
constructor Create; virtual; // watch out, it's virtual!
destructor Destroy; override;
procedure ReadMetaData;
procedure ReadData;
procedure ClearData;
procedure ReplaceLemmingAnimationColor(OldColor, NewColor: TColor32);
property BrickColor: TColor32 read fBrickColor write fBrickColor;
property LemmingAnimations: TBitmaps read fLemmingAnimations;
property MaskAnimations: TBitmaps read fMaskAnimations;
published
property MetaLemmingAnimations: TMetaLemmingAnimations read fMetaLemmingAnimations write SetMetaLemmingAnimations;
property MetaMaskAnimations: TMetaAnimations read fMetaMaskAnimations write SetMetaMaskAnimations;
end;
implementation
{ TBaseAnimationSet }
constructor TBaseAnimationSet.Create;
begin
inherited Create;
//fBrickColor := clMask32;
fMetaLemmingAnimations := DoCreateMetaLemmingAnimations;
fMetaMaskAnimations := DoCreateMetaMaskAnimations;
fLemmingAnimations := TBitmaps.Create;
fMaskAnimations := TBitmaps.Create;
end;
destructor TBaseAnimationSet.Destroy;
begin
fMetaLemmingAnimations.Free;
fMetaMaskAnimations.Free;
fMaskAnimations.Free;
fLemmingAnimations.Free;
inherited Destroy;
end;
procedure TBaseAnimationSet.ReadMetaData;
begin
DoReadMetaData;
end;
procedure TBaseAnimationSet.ReadData;
//var
//i: Integer;
begin
DoReadData;
(*
for i := 0 to fAnimationCache.Count - 1 do
begin
ReplaceColor(TBitmap32(fAnimationCache[i]), clBRICK32, fBrickColor);
end;
*)
end;
procedure TBaseAnimationSet.ClearData;
begin
DoClearData;
end;
procedure TBaseAnimationSet.ReplaceLemmingAnimationColor(OldColor, NewColor: TColor32);
var
i: Integer;
begin
for i := 0 to fLemmingAnimations.Count - 1 do
//ReplaceColor(TBitmap32(fLemmingAnimations[i]), fBrickColor, aColor);
ReplaceColor(fLemmingAnimations[i], OldColor, NewColor);
end;
function TBaseAnimationSet.DoCreateMetaLemmingAnimations: TMetaLemmingAnimations;
begin
Result := TMetaLemmingAnimations.Create(TMetaLemmingAnimation);
end;
function TBaseAnimationSet.DoCreateMetaMaskAnimations: TMetaAnimations;
begin
Result := TMetaAnimations.Create(TMetaAnimation);
end;
procedure TBaseAnimationSet.SetMetaLemmingAnimations(Value: TMetaLemmingAnimations);
begin
fMetaLemmingAnimations.Assign(Value);
end;
procedure TBaseAnimationSet.SetMetaMaskAnimations(Value: TMetaAnimations);
begin
fMetaMaskAnimations.Assign(Value);
end;
end.
|
PROGRAM Split(INPUT, OUTPUT);
{Копирует INPUT в OUTPUT, сначала нечётные, а затем
чётные элементы}
VAR
Ch, Next: CHAR;
Odds, Evens: TEXT;
PROCEDURE CopyOut(VAR F1: TEXT);
VAR
Ch: CHAR;
BEGIN {CopyOut}
RESET(F1);
WHILE NOT EOF(F1)
DO
BEGIN
WHILE NOT EOLN(F1)
DO
BEGIN
READ(F1, Ch);
WRITE(Ch)
END;
READLN(F1)
END
END; {CopyOut}
BEGIN {Split}
WRITELN(Odds, 'abcd');
WRITELN(Evens, '1234');
CopyOut(Odds);
CopyOut(Evens);
WRITELN
END. {Split}
|
{
Steam Utilities
Copyright (C) 2016, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/SteamUtils
License:
- You may use this library as you see fit, including use within commercial applications.
- You may modify this library to suit your needs, without the requirement of distributing
modified versions.
- You may redistribute this library (in part or whole) individually, or as part of any
other works.
- You must NOT charge a fee for the distribution of this library (compiled or in its
source form). It MUST be distributed freely.
- This license and the surrounding comment block MUST remain in place on all copies and
modified versions of this source code.
- Modified versions of this source MUST be clearly marked, including the name of the
person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog"
detailing all additions/deletions/modifications made.
Disclaimer:
- Your use of this source constitutes your understanding and acceptance of this
disclaimer.
- Simon J Stuart, nor any other contributor, may be held liable for your use of this source
code. This includes any losses and/or damages resulting from your use of this source
code, be they physical, financial, or psychological.
- There is no warranty or guarantee (implicit or otherwise) provided with this source
code. It is provided on an "AS-IS" basis.
Donations:
- While not mandatory, contributions are always appreciated. They help keep the coffee
flowing during the long hours invested in this and all other Open Source projects we
produce.
- Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com
^ Garbled to prevent spam! ^
}
unit Steam.App.Manifests.Intf;
interface
{$I ADAPT.inc}
{
NOTES:
StateFlags = 1026 while Downloading...
StateFlags = 4 when Downloaded/No Updates... [CONFIRMED]
Only allow Transfers if (BytesToDownload = 0) AND ((BytesDownloaded > 0) AND (SizeOnDisk > 0)) AND (BytesDownloaded = SizeOnDisk)
Delete "MountedDepots" section entirely to solve the "Invalid Depots" bug (useful feature)
}
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Common.Intf, ADAPT.Common,
ADAPT.Generics.Lists.Intf,
ADAPT.Generics.Maps.Intf,
Steam.Common.Intf;
type
// Forward Declarations
ISteamAppManifest = interface;
ISteamAppManifestConfig = interface;
ISteamAppManifestStagedDepot = interface;
ISteamAppManifestMountedDepot = interface;
// Enums
TSteamAutoUpdateBehavior = (aubAlwaysUpdate, aubUpdateOnLaunch, aubAlwaysUpdatePriority);
TSteamBackgroundDownloadBehavior = (bdbGlobalSetting, bdbAllow, bdbNever);
// Generic Collections/Containers
// ISteamAppManifestStagedDepotDictionary = IADDictionary<Cardinal, ISteamAppManifestStagedDepot>; // Mapped on "Key"
ISteamAppManifest = interface(ISteamJsonFile)
['{C5FA375B-302B-4059-8D55-A61BE93A6B80}']
// Getters
function GetAllowOtherDownloadsWhileRunning: TSteamBackgroundDownloadBehavior;
function GetAppID: Cardinal;
function GetAutoUpdateBehavior: TSteamAutoUpdateBehavior;
function GetBuildId: Cardinal;
function GetBytesDownloaded: Cardinal;
function GetBytesToDownload: Cardinal;
function GetConfig: ISteamAppManifestConfig;
function GetHasBeenUpdated: Boolean;
function GetInstallDir: String;
function GetInstallScripts: ISteamStringList;
function GetLastOwner: Cardinal; //TODO -oDaniel -cManifest Clarification: Should this be a Reference to a Steam User Object?
function GetLastUpdated: TDateTime;
function GetName: String;
function GetSizeOnDisk: Cardinal;
function GetStateFlags: Cardinal; //TODO -oDaniel -cManifest Clarification: Use Set of State Flags (once discovered)
function GetUniverse: Cardinal; //TODO -oDaniel -cManifest Clarification: Should be Enum?
function GetUpdateResult: Cardinal; //TODO -oDaniel -cManifest Clarification: Should be Enum?
// Setters
procedure SetAllowOtherDownloadsWhileRunning(const AValue: TSteamBackgroundDownloadBehavior);
// Properties
property AllowOtherDownloadsWhileRunning: TSteamBackgroundDownloadBehavior read GetAllowOtherDownloadsWhileRunning write SetAllowOtherDownloadsWhileRunning;
property AppID: Cardinal read GetAppID;
property AutoUpdateBehavior: TSteamAutoUpdateBehavior read GetAutoUpdateBehavior;
property BuildId: Cardinal read GetBuildId;
property BytesDownloaded: Cardinal read GetBytesDownloaded;
property BytesToDownload: Cardinal read GetBytesToDownload;
property Config: ISteamAppManifestConfig read GetConfig;
property HasBeenUpdated: Boolean read GetHasBeenUpdated;
property InstallDir: String read GetInstallDir;
property InstallScripts: ISteamStringList read GetInstallScripts;
property LastOwner: Cardinal read GetLastOwner; //TODO -oDaniel -cManifest Clarification: Should this be a Reference to a Steam User Object?
property LastUpdated: TDateTime read GetLastUpdated;
property Name: String read GetName;
property SizeOnDisk: Cardinal read GetSizeOnDisk;
property StateFlags: Cardinal read GetStateFlags; //TODO -oDaniel -cManifest Clarification: Use Set of State Flags (once discovered)
property Universe: Cardinal read GetUniverse; //TODO -oDaniel -cManifest Clarification: Should be Enum?
property UpdateResult: Cardinal read GetUpdateResult;//TODO -oDaniel -cManifest Clarification: Should be Enum?
end;
ISteamAppManifestConfig = interface(IADInterface)
['{FA25981C-A43E-4276-B066-3F7C4D168FA9}']
// Getters
function GetBetaKey: String; //TODO -oDaniel -cManifest Clarification: Is this supposed to be an AppId of some kind?
function GetLanguage: String; //TODO -oDaniel -cManifest Clarification: Use Enumeration of Supported Languages
// Properties
property BetaKey: String read GetBetaKey;
property Language: String read GetLanguage; //TODO -oDaniel -cManifest Clarification: Use Enumeration of Supported Languages
end;
ISteamAppManifestStagedDepot = interface(IADInterface)
['{AFBD6B8B-E0D8-48BB-958A-8D5AEA20D182}']
// Getters
function GetKey: Cardinal; //TODO -oDaniel -cManifest Clarification: Is this supposed to be an AppId of some kind?
function GetManifest: Cardinal;
function GetSize: Cardinal;
// Properties
property Key: Cardinal read GetKey; //TODO -oDaniel -cManifest Clarification: Is this supposed to be an AppId of some kind?;
property Manifest: Cardinal read GetManifest;
property Size: Cardinal read GetSize;
end;
ISteamAppManifestMountedDepot = interface(IADInterface)
['{94347C09-03A2-4CED-8B97-FB629A97AF61}']
// Getters
function GetKey: Cardinal;
function GetValue: Cardinal;
// Properties
property Key: Cardinal read GetKey;
property Value: Cardinal read GetValue;
end;
implementation
end.
|
{
义乌科创计算机有限公司软件部
Dcopyboy
Email:dcopyboy@tom.com
QQ:445235526
添加 Usejis 参数 可在
当 Usejis :=true时 采用 日文(SHIFT JIS) 编码
反之采用机内码编码,成功解决 QRCode 汉字乱码问题。
}
unit QRCode;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Clipbrd;
const
{ 符号化モード }
QR_EM_NUMERIC = 0; // 数字
QR_EM_ALNUM = 1; // 英数字: 0-9 A-Z SP $%*+-./:
QR_EM_8BIT = 2; // 8ビットバイト
QR_EM_KANJI = 3; // 漢字
QR_EM_MAX = 4; // モード総数
{ 誤り訂正レベル }
QR_ECL_L = 0; // レベルL
QR_ECL_M = 1; // レベルM
QR_ECL_Q = 2; // レベルQ
QR_ECL_H = 3; // レベルH
QR_ECL_MAX = 4; // レベル総数
{ モジュール値のマスク }
QR_MM_DATA = $01; // 符号化データの黒モジュール
QR_MM_BLACK = $02; // 印字される黒モジュール
QR_MM_FUNC = $04; // 機能パターン領域(形式/型番情報を含む)
{ 機能パターンの定数 }
QR_DIM_SEP = 4; // 分離パターンの幅
QR_DIM_FINDER = 7; // 位置検出パターンの1辺の長さ
QR_DIM_ALIGN = 5; // 位置合わせパターンの1辺の長さ
QR_DIM_TIMING = 6; // タイミングパターンのオフセット位置
{ サイズ定数 }
QR_SRC_MAX = 7089; // 入力データの最大長
QR_DIM_MAX = 177; // 1辺のモジュール数の最大値
QR_VER_MAX = 40; // 型番の最大値
QR_DWD_MAX = 2956; // データコード語の最大長(型番40/レベルL)
QR_ECW_MAX = 2430; // 誤り訂正コード語の最大長(型番40/レベルH)
QR_CWD_MAX = 3706; // コード語の最大長(型番40)
QR_RSD_MAX = 123; // RSブロックデータコード語の最大長
QR_RSW_MAX = 68; // RSブロック誤り訂正コード語の最大長
QR_RSB_MAX = 2; // RSブロック種別の最大数
QR_MPT_MAX = 8; // マスクパターン種別総数
QR_APL_MAX = 7; // 位置合わせパターン座標の最大数
QR_FIN_MAX = 15; // 形式情報のビット数
QR_VIN_MAX = 18; // 型番情報のビット数
QR_CNN_MAX = 16; // 連結モードでのシンボルの最大表示個数
QR_PLS_MAX = 1024; // プラスモードでのシンボルの最大表示個数
{ その他の定数 }
NAV = 0; // 不使用(not available)
PADWORD1 = $EC; // 埋め草コード語1: 11101100
PADWORD2 = $11; // 埋め草コード語2: 00010001
type
{ RSブロックごとの情報 }
QR_RSBLOCK = record
rsbnum: Integer; // RSブロック数
totalwords: Integer; // RSブロック総コード語数
datawords: Integer; // RSブロックデータコード語数
ecnum: Integer; // RSブロック誤り訂正数(不使用)
end;
{ 誤り訂正レベルごとの情報 }
QR_ECLEVEL = record
datawords: Integer; // データコード語数(全RSブロック)
capacity: array[0..QR_EM_MAX - 1] of Integer; // 符号化モードごとのデータ容量
nrsb: Integer; // RSブロックの種類(1または2)
rsb: array[0..QR_RSB_MAX - 1] of QR_RSBLOCK; // RSブロックごとの情報
end;
{ 型番ごとの情報 }
QR_VERTABLE = record
version: Integer; // 型番
dimension: Integer; // 1辺のモジュール数
totalwords: Integer; // 総コード語数
remainedbits: Integer; // 剰余ビット数
nlen: array[0..QR_EM_MAX - 1] of Integer; // 文字数指示子のビット数
ecl: array[0..QR_ECL_MAX - 1] of QR_ECLEVEL; // 誤り訂正レベルごとの情報
aplnum: Integer; // 位置合わせパターン中心座標数
aploc: array[0..QR_APL_MAX - 1] of Integer; // 位置合わせパターン中心座標
end;
PByte = ^Byte;
const
{ αのべき表現→多項式係数の整数表現 }
exp2fac: array[0..255] of Byte = (
1, 2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19, 38,
76, 152, 45, 90, 180, 117, 234, 201, 143, 3, 6, 12, 24, 48, 96, 192,
157, 39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238, 193, 159, 35,
70, 140, 5, 10, 20, 40, 80, 160, 93, 186, 105, 210, 185, 111, 222, 161,
95, 190, 97, 194, 153, 47, 94, 188, 101, 202, 137, 15, 30, 60, 120, 240,
253, 231, 211, 187, 107, 214, 177, 127, 254, 225, 223, 163, 91, 182, 113, 226,
217, 175, 67, 134, 17, 34, 68, 136, 13, 26, 52, 104, 208, 189, 103, 206,
129, 31, 62, 124, 248, 237, 199, 147, 59, 118, 236, 197, 151, 51, 102, 204,
133, 23, 46, 92, 184, 109, 218, 169, 79, 158, 33, 66, 132, 21, 42, 84,
168, 77, 154, 41, 82, 164, 85, 170, 73, 146, 57, 114, 228, 213, 183, 115,
230, 209, 191, 99, 198, 145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255,
227, 219, 171, 75, 150, 49, 98, 196, 149, 55, 110, 220, 165, 87, 174, 65,
130, 25, 50, 100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166,
81, 162, 89, 178, 121, 242, 249, 239, 195, 155, 43, 86, 172, 69, 138, 9,
18, 36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22,
44, 88, 176, 125, 250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142, 1
);
{ 多項式係数の整数表現→αのべき表現 }
fac2exp: array[0..255] of Byte = (
NAV, 0, 1, 25, 2, 50, 26, 198, 3, 223, 51, 238, 27, 104, 199, 75,
4, 100, 224, 14, 52, 141, 239, 129, 28, 193, 105, 248, 200, 8, 76, 113,
5, 138, 101, 47, 225, 36, 15, 33, 53, 147, 142, 218, 240, 18, 130, 69,
29, 181, 194, 125, 106, 39, 249, 185, 201, 154, 9, 120, 77, 228, 114, 166,
6, 191, 139, 98, 102, 221, 48, 253, 226, 152, 37, 179, 16, 145, 34, 136,
54, 208, 148, 206, 143, 150, 219, 189, 241, 210, 19, 92, 131, 56, 70, 64,
30, 66, 182, 163, 195, 72, 126, 110, 107, 58, 40, 84, 250, 133, 186, 61,
202, 94, 155, 159, 10, 21, 121, 43, 78, 212, 229, 172, 115, 243, 167, 87,
7, 112, 192, 247, 140, 128, 99, 13, 103, 74, 222, 237, 49, 197, 254, 24,
227, 165, 153, 119, 38, 184, 180, 124, 17, 68, 146, 217, 35, 32, 137, 46,
55, 63, 209, 91, 149, 188, 207, 205, 144, 135, 151, 178, 220, 252, 190, 97,
242, 86, 211, 171, 20, 42, 93, 158, 132, 60, 57, 83, 71, 109, 65, 162,
31, 45, 67, 216, 183, 123, 164, 118, 196, 23, 73, 236, 127, 12, 111, 246,
108, 161, 59, 82, 41, 157, 85, 170, 251, 96, 134, 177, 187, 204, 62, 90,
203, 89, 95, 176, 156, 169, 160, 81, 11, 245, 22, 235, 122, 117, 44, 215,
79, 174, 213, 233, 230, 231, 173, 232, 116, 214, 244, 234, 168, 80, 88, 175
);
{ 誤り訂正生成多項式の第2項以降の係数表(べき表現) }
gftable: array[0..QR_RSW_MAX, 0..QR_RSW_MAX - 1] of Byte = (
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(87, 229, 146, 149, 238, 102, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(251, 67, 46, 61, 118, 70, 64, 94, 32, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(74, 152, 176, 100, 86, 100, 106, 104, 130, 218, 206, 140, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(8, 183, 61, 91, 202, 37, 51, 58, 58, 237, 140, 124, 5, 99, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(120, 104, 107, 109, 102, 161, 76, 3, 91, 191, 147, 169, 182, 194, 225, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(43, 139, 206, 78, 43, 239, 123, 206, 214, 147, 24, 99, 150, 39, 243, 163, 136, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(215, 234, 158, 94, 184, 97, 118, 170, 79, 187, 152, 148, 252, 179, 5, 98, 96, 153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(17, 60, 79, 50, 61, 163, 26, 187, 202, 180, 221, 225, 83, 239, 156, 164, 212, 212, 188, 190, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(210, 171, 247, 242, 93, 230, 14, 109, 221, 53, 200, 74, 8, 172, 98, 80, 219, 134, 160, 105, 165, 231, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(229, 121, 135, 48, 211, 117, 251, 126, 159, 180, 169, 152, 192, 226, 228, 218, 111, 0, 117, 232, 87, 96, 227, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(173, 125, 158, 2, 103, 182, 118, 17, 145, 201, 111, 28, 165, 53, 161, 21, 245, 142, 13, 102, 48, 227, 153, 145, 218, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(168, 223, 200, 104, 224, 234, 108, 180, 110, 190, 195, 147, 205, 27, 232, 201, 21, 43, 245, 87, 42, 195, 212, 119, 242, 37, 9, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(41, 173, 145, 152, 216, 31, 179, 182, 50, 48, 110, 86, 239, 96, 222, 125, 42, 173, 226, 193, 224, 130, 156, 37, 251, 216, 238, 40, 192, 180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(10, 6, 106, 190, 249, 167, 4, 67, 209, 138, 138, 32, 242, 123, 89, 27, 120, 185, 80, 156, 38, 69, 171, 60, 28, 222, 80, 52, 254, 185, 220, 241, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(111, 77, 146, 94, 26, 21, 108, 19, 105, 94, 113, 193, 86, 140, 163, 125, 58, 158, 229, 239, 218, 103, 56, 70, 114, 61, 183, 129, 167, 13, 98, 62, 129, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(200, 183, 98, 16, 172, 31, 246, 234, 60, 152, 115, 0, 167, 152, 113, 248, 238, 107, 18, 63, 218, 37, 87, 210, 105, 177, 120, 74, 121, 196, 117, 251, 113, 233, 30, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(159, 34, 38, 228, 230, 59, 243, 95, 49, 218, 176, 164, 20, 65, 45, 111, 39, 81, 49, 118, 113, 222, 193, 250, 242, 168, 217, 41, 164, 247, 177, 30, 238, 18, 120, 153, 60, 193, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(59, 116, 79, 161, 252, 98, 128, 205, 128, 161, 247, 57, 163, 56, 235, 106, 53, 26, 187, 174, 226, 104, 170, 7, 175, 35, 181, 114, 88, 41, 47, 163, 125, 134, 72, 20, 232, 53, 35, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(250, 103, 221, 230, 25, 18, 137, 231, 0, 3, 58, 242, 221, 191, 110, 84, 230, 8, 188, 106, 96, 147, 15, 131, 139, 34, 101, 223, 39, 101, 213, 199, 237, 254, 201, 123, 171, 162, 194, 117, 50, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(190, 7, 61, 121, 71, 246, 69, 55, 168, 188, 89, 243, 191, 25, 72, 123, 9, 145, 14, 247, 1, 238, 44, 78, 143, 62, 224, 126, 118, 114, 68, 163, 52, 194, 217, 147, 204, 169, 37, 130, 113, 102, 73, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(112, 94, 88, 112, 253, 224, 202, 115, 187, 99, 89, 5, 54, 113, 129, 44, 58, 16, 135, 216, 169, 211, 36, 1, 4, 96, 60, 241, 73, 104, 234, 8, 249, 245, 119, 174, 52, 25, 157, 224, 43, 202, 223, 19, 82, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(228, 25, 196, 130, 211, 146, 60, 24, 251, 90, 39, 102, 240, 61, 178, 63, 46, 123, 115, 18, 221, 111, 135, 160, 182, 205, 107, 206, 95, 150, 120, 184, 91, 21, 247, 156, 140, 238, 191, 11, 94, 227, 84, 50, 163, 39, 34, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(232, 125, 157, 161, 164, 9, 118, 46, 209, 99, 203, 193, 35, 3, 209, 111, 195, 242, 203, 225, 46, 13, 32, 160, 126, 209, 130, 160, 242, 215, 242, 75, 77, 42, 189, 32, 113, 65, 124, 69, 228, 114, 235, 175, 124, 170, 215, 232, 133, 205, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(116, 50, 86, 186, 50, 220, 251, 89, 192, 46, 86, 127, 124, 19, 184, 233, 151, 215, 22, 14, 59, 145, 37, 242, 203, 134, 254, 89, 190, 94, 59, 65, 124, 113, 100, 233, 235, 121, 22, 76, 86, 97, 39, 242, 200, 220, 101, 33, 239, 254, 116, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(183, 26, 201, 87, 210, 221, 113, 21, 46, 65, 45, 50, 238, 184, 249, 225, 102, 58, 209, 218, 109, 165, 26, 95, 184, 192, 52, 245, 35, 254, 238, 175, 172, 79, 123, 25, 122, 43, 120, 108, 215, 80, 128, 201, 235, 8, 153, 59, 101, 31, 198, 76, 31, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(106, 120, 107, 157, 164, 216, 112, 116, 2, 91, 248, 163, 36, 201, 202, 229, 6, 144, 254, 155, 135, 208, 170, 209, 12, 139, 127, 142, 182, 249, 177, 174, 190, 28, 10, 85, 239, 184, 101, 124, 152, 206, 96, 23, 163, 61, 27, 196, 247, 151, 154, 202, 207, 20, 61, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(82, 116, 26, 247, 66, 27, 62, 107, 252, 182, 200, 185, 235, 55, 251, 242, 210, 144, 154, 237, 176, 141, 192, 248, 152, 249, 206, 85, 253, 142, 65, 165, 125, 23, 24, 30, 122, 240, 214, 6, 129, 218, 29, 145, 127, 134, 206, 245, 117, 29, 41, 63, 159, 142, 233, 125, 148, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(107, 140, 26, 12, 9, 141, 243, 197, 226, 197, 219, 45, 211, 101, 219, 120, 28, 181, 127, 6, 100, 247, 2, 205, 198, 57, 115, 219, 101, 109, 160, 82, 37, 38, 238, 49, 160, 209, 121, 86, 11, 124, 30, 181, 84, 25, 194, 87, 65, 102, 190, 220, 70, 27, 209, 16, 89, 7, 33, 240, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(65, 202, 113, 98, 71, 223, 248, 118, 214, 94, 0, 122, 37, 23, 2, 228, 58, 121, 7, 105, 135, 78, 243, 118, 70, 76, 223, 89, 72, 50, 70, 111, 194, 17, 212, 126, 181, 35, 221, 117, 235, 11, 229, 149, 147, 123, 213, 40, 115, 6, 200, 100, 26, 246, 182, 218, 127, 215, 36, 186, 110, 106, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(45, 51, 175, 9, 7, 158, 159, 49, 68, 119, 92, 123, 177, 204, 187, 254, 200, 78, 141, 149, 119, 26, 127, 53, 160, 93, 199, 212, 29, 24, 145, 156, 208, 150, 218, 209, 4, 216, 91, 47, 184, 146, 47, 140, 195, 195, 125, 242, 238, 63, 99, 108, 140, 230, 242, 31, 204, 11, 178, 243, 217, 156, 213, 231, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(5, 118, 222, 180, 136, 136, 162, 51, 46, 117, 13, 215, 81, 17, 139, 247, 197, 171, 95, 173, 65, 137, 178, 68, 111, 95, 101, 41, 72, 214, 169, 197, 95, 7, 44, 154, 77, 111, 236, 40, 121, 143, 63, 87, 80, 253, 240, 126, 217, 77, 34, 232, 106, 50, 168, 82, 76, 146, 67, 106, 171, 25, 132, 93, 45, 105, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(247, 159, 223, 33, 224, 93, 77, 70, 90, 160, 32, 254, 43, 150, 84, 101, 190, 205, 133, 52, 60, 202, 165, 220, 203, 151, 93, 84, 15, 84, 253, 173, 160, 89, 227, 52, 199, 97, 95, 231, 52, 177, 41, 125, 137, 241, 166, 225, 118, 2, 54, 32, 82, 215, 175, 198, 43, 238, 235, 27, 101, 184, 127, 3, 5, 8, 163, 238)
);
F0 = QR_MM_FUNC;
F1 = (QR_MM_FUNC or QR_MM_BLACK);
{ 位置検出パターンのデータ }
finderpattern: array[0..QR_DIM_FINDER - 1, 0..QR_DIM_FINDER - 1] of Byte = (
(F1, F1, F1, F1, F1, F1, F1),
(F1, F0, F0, F0, F0, F0, F1),
(F1, F0, F1, F1, F1, F0, F1),
(F1, F0, F1, F1, F1, F0, F1),
(F1, F0, F1, F1, F1, F0, F1),
(F1, F0, F0, F0, F0, F0, F1),
(F1, F1, F1, F1, F1, F1, F1)
);
{ 位置合わせパターンのデータ }
alignpattern: array[0..QR_DIM_ALIGN - 1, 0..QR_DIM_ALIGN - 1] of Byte = (
(F1, F1, F1, F1, F1),
(F1, F0, F0, F0, F1),
(F1, F0, F1, F0, F1),
(F1, F0, F0, F0, F1),
(F1, F1, F1, F1, F1)
);
{ モード指示子(英字, 英数字, 8ビットバイト, 漢字) }
modeid: array[0..QR_EM_MAX - 1] of Word = ($01, $02, $04, $08);
{ 英数字モードの符号化表 }
alnumtable: array[0..127] of Shortint = (
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
);
EN = QR_EM_NUMERIC;
EA = QR_EM_ALNUM;
E8 = QR_EM_8BIT;
EK = QR_EM_KANJI;
{ 文字クラス表 }
charclass: array[0..255] of Shortint = (
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
EA, E8, E8, E8, EA, EA, E8, E8, E8, E8, EA, EA, E8, EA, EA, EA, // !"#$%&'()*+,-./
EN, EN, EN, EN, EN, EN, EN, EN, EN, EN, EA, E8, E8, E8, E8, E8, //0123456789:;<=>?
E8, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, //@ABCDEFGHIJKLMNO
EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, EA, E8, E8, E8, E8, E8, //PQRSTUVWXYZ[\]^_
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, //`abcdefghijklmno
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, //pqrstuvwxyz{|}~
E8, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK,
EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8,
EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, EK, E8, E8, E8, E8,
E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8, E8
);
{
qrcode作为日本人设计的规范,考虑了对于jis的优化。
比如日文(jis)是两个字节,但是实际上不需要两个,第一个字节的一部分是没有使用,
qrcode压缩了这部分,变成了13位,编入kanji mode。这使得qrcode在同样的大小上编入更多的日文字符。
qrcode同样支持utf-8,这部分数据没有任何变动的,写入了byte mode。
那为何又乱码呢?首先utf-8的数据,无论生成,解析都不会错,这是肯定的。问题出在gbk上,
比如用网上流传的qrcode edit(无论中文还是日文版),在windons上生成一个包含中文的qrcode码,
则通常会乱码,因为windoes默认是用gbk,而生成器本身无法识别gbk(中文版,知识汉化界面罢了),
它会把一部分汉子的第一个字节编入kanji mode,一部分编入byte mode。
所以解析器无论怎么做格式转换都无法获取正确的数据。
至于有些工具(爱拍)我用过,确实是可以解析这种情况,我猜测是牺牲了日文,
把编入kanji mode的数据强行跟byte mode的数据整合
思路跳过对EK代码的的检测,即可支持中文 .}
type
{ 座標データ型 }
COORD = record
ypos: Integer;
xpos: Integer;
end;
const
{ 形式情報(2箇所)の座標(下位ビットから) }
{ (負数は下端/右端からのオフセット) }
fmtinfopos: array[0..1, 0..QR_FIN_MAX - 1] of COORD = (
((ypos: 0; xpos: 8), (ypos: 1; xpos: 8), (ypos: 2; xpos: 8),
(ypos: 3; xpos: 8), (ypos: 4; xpos: 8), (ypos: 5; xpos: 8),
(ypos: 7; xpos: 8), (ypos: 8; xpos: 8), (ypos: - 7; xpos: 8),
(ypos: - 6; xpos: 8), (ypos: - 5; xpos: 8), (ypos: - 4; xpos: 8),
(ypos: - 3; xpos: 8), (ypos: - 2; xpos: 8), (ypos: - 1; xpos: 8)),
((ypos: 8; xpos: - 1), (ypos: 8; xpos: - 2), (ypos: 8; xpos: - 3),
(ypos: 8; xpos: - 4), (ypos: 8; xpos: - 5), (ypos: 8; xpos: - 6),
(ypos: 8; xpos: - 7), (ypos: 8; xpos: - 8), (ypos: 8; xpos: 7),
(ypos: 8; xpos: 5), (ypos: 8; xpos: 4), (ypos: 8; xpos: 3),
(ypos: 8; xpos: 2), (ypos: 8; xpos: 1), (ypos: 8; xpos: 0))
);
{ 形式情報の固定黒モジュール }
fmtblackpos: COORD = (ypos: - 8; xpos: 8);
{ 型番情報(2箇所)の座標(下位ビットから) }
{ (負数は下端/右端からのオフセット) }
verinfopos: array[0..1, 0..QR_VIN_MAX - 1] of COORD = (
((ypos: - 11; xpos: 0), (ypos: - 10; xpos: 0), (ypos: - 9; xpos: 0),
(ypos: - 11; xpos: 1), (ypos: - 10; xpos: 1), (ypos: - 9; xpos: 1),
(ypos: - 11; xpos: 2), (ypos: - 10; xpos: 2), (ypos: - 9; xpos: 2),
(ypos: - 11; xpos: 3), (ypos: - 10; xpos: 3), (ypos: - 9; xpos: 3),
(ypos: - 11; xpos: 4), (ypos: - 10; xpos: 4), (ypos: - 9; xpos: 4),
(ypos: - 11; xpos: 5), (ypos: - 10; xpos: 5), (ypos: - 9; xpos: 5)),
((ypos: 0; xpos: - 11), (ypos: 0; xpos: - 10), (ypos: 0; xpos: - 9),
(ypos: 1; xpos: - 11), (ypos: 1; xpos: - 10), (ypos: 1; xpos: - 9),
(ypos: 2; xpos: - 11), (ypos: 2; xpos: - 10), (ypos: 2; xpos: - 9),
(ypos: 3; xpos: - 11), (ypos: 3; xpos: - 10), (ypos: 3; xpos: - 9),
(ypos: 4; xpos: - 11), (ypos: 4; xpos: - 10), (ypos: 4; xpos: - 9),
(ypos: 5; xpos: - 11), (ypos: 5; xpos: - 10), (ypos: 5; xpos: - 9))
);
{ 型番情報(型番7~40について有効) }
verinfo: array[0..QR_VER_MAX] of Longint = (
-1, -1, -1, -1, -1, -1,
-1, $07C94, $085BC, $09A99, $0A4D3, $0BBF6,
$0C762, $0D847, $0E60D, $0F928, $10B78, $1145D,
$12A17, $13532, $149A6, $15683, $168C9, $177EC,
$18EC4, $191E1, $1AFAB, $1B08E, $1CC1A, $1D33F,
$1ED75, $1F250, $209D5, $216F0, $228BA, $2379F,
$24B0B, $2542E, $26A64, $27541, $28C69
);
{ バイナリデータ }
BinaryData: set of Byte = [$00..$08, $0B, $0C, $0E..$1F, $A1..$FF];
{ 漢字データ }
Kanji1Data: set of Byte = [$81..$9F, $E0..$EB]; // 1バイト目
Kanji2Data: set of Byte = [$40..$7E, $80..$FC]; // 2バイト目
type
TPictures = (picBMP, picEMF, picWMF);
TLocation = (locLeft, locCenter, locRight);
TQRMode = (qrSingle, qrConnect, qrPlus);
TNumbering = (nbrNone, nbrHead, nbrTail, nbrIfVoid);
TNotifyWatchEvent = procedure(Sender: TObject; Watch: Boolean) of object;
{ TQRCode クラス }
TQRCode = class(TImage)
private
{ Private 宣言 }
FCode: string;
FMemory: PChar;
FLen: Integer;
FBinary: Boolean;
FBinaryOperation: Boolean;
FMode: TQRMode;
FCount: Integer;
FColumn: Integer;
FParity: Integer; // 連結モードの場合に使用するシンボルデータのパリティ値
FNumbering: TNumbering;
FCommentUp: string;
FCommentUpLoc: TLocation;
FCommentDown: string;
FCommentDownLoc: TLocation;
FSymbolLeft: Integer;
FSymbolTop: Integer;
FSymbolSpaceUp: Integer;
FSymbolSpaceDown: Integer;
FSymbolSpaceLeft: Integer;
FSymbolSpaceRight: Integer;
FVersion: Integer; // 型番
FEmode: Integer; // 符号化モード ,自動判定 字符集 0:数字
FEmodeR: Integer;
FEclevel: Integer; // 誤り訂正レベル = 0 (误差级别0-4)
FMasktype: Integer; // マスクパターン種別 -1; 自動設定
FMasktypeR: Integer;
FPxmag: Integer; // 表示画素倍率
FAngle: Integer; // 回転角度
FReverse: Boolean; // 反転表示
FPBM: TStringList; // Portable Bitmap
FMatch: Boolean;
FComFont: TFont;
FTransparent: Boolean;
FSymbolColor: TColor;
FBackColor: TColor;
FSymbolPicture: TPictures;
FSymbolEnabled: Boolean;
FSymbolDebug: Boolean; // デバッグ用プロパティ
FSymbolDisped: Boolean;
FClearOption: Boolean;
FMfCanvas: TMetafileCanvas; // メタファイル用キャンバス
FWindowHandle: HWND;
FNextWindowHandle: HWND;
FRegistered: Boolean;
FClipWatch: Boolean; // クリップボード監視用のスイッチ
FWatch: Boolean; // Code が自動更新された時に True になる。
FOnChangeCode: TNotifyWatchEvent; // OnChangeCode イベントフィールド
FOnPaintSymbol: TNotifyWatchEvent; // OnPaintSymbol イベントフィールド
FOnPaintedSymbol: TNotifyWatchEvent; // OnPaintedSymbol イベントフィールド
FOnChangedCode: TNotifyWatchEvent; // OnChangedCode イベントフィールド
FOnClipChange: TNotifyEvent; // OnClipChange イベントフィールド
FSkip: Boolean; // 最初の OnClipChange イベントをスキップする為のフラッグ
{ データ領域 }
vertable: array[0..QR_VER_MAX] of QR_VERTABLE; // 型番データ表
source: array[0..QR_SRC_MAX - 1] of Byte; // 入力データ領域
dataword: array[0..QR_DWD_MAX - 1] of Byte; // データコード語領域
ecword: array[0..QR_ECW_MAX - 1] of Byte; // 誤り訂正コード語領域
codeword: array[0..QR_CWD_MAX - 1] of Byte; // シンボル配置用コード語領域
rswork: array[0..QR_RSD_MAX - 1] of Byte; // RS符号計算用作業領域
symbol: array[0..QR_DIM_MAX - 1, 0..QR_DIM_MAX - 1] of Byte; // シンボルデータ領域
offsets: array[0..QR_PLS_MAX] of Integer; // 各シンボルデータオフセット値格納領域
{ その他の大域変数 }
srclen: Integer; // 入力データのバイト長
dwpos: Integer; // データコード語の追加バイト位置
dwbit: Integer; // データコード語の追加ビット位置
xpos, ypos: Integer; // モジュールを配置する座標位置
xdir, ydir: Integer; // モジュール配置の移動方向
icount: Integer; // 表示中のシンボルのカウンタ値(1 ~ QR_PLS_MAX)
FUsejis: boolean; //使用jis优化,dcopyboy
function GetData(Index: Integer): Byte;
function GetOffset(Index: Integer): Integer;
function GetSymbolWidth: Integer;
function GetSymbolWidthS: Integer;
function GetSymbolWidthA: Integer;
function GetSymbolHeight: Integer;
function GetSymbolHeightS: Integer;
function GetSymbolHeightA: Integer;
function GetQuietZone: Integer;
function GetCapacity: Integer;
function GetPBM: TStringList;
procedure SetCode(const Value: string);
procedure SetData(Index: Integer; const Value: Byte);
procedure SetBinaryOperation(const Value: Boolean);
procedure SetMode(const Value: TQRMode);
procedure SetCount(const Value: Integer);
procedure SetColumn(const Value: Integer);
procedure SetNumbering(const Value: TNumbering);
procedure SetCommentUp(const Value: string);
procedure SetCommentUpLoc(const Value: TLocation);
procedure SetCommentDown(const Value: string);
procedure SetCommentDownLoc(const Value: TLocation);
procedure SetSymbolLeft(const Value: Integer);
procedure SetSymbolTop(const Value: Integer);
procedure SetSymbolSpaceUp(const Value: Integer);
procedure SetSymbolSpaceDown(const Value: Integer);
procedure SetSymbolSpaceLeft(const Value: Integer);
procedure SetSymbolSpaceRight(const Value: Integer);
procedure SetVersion(const Value: Integer);
procedure SetEmode(const Value: Integer);
procedure SetEclevel(const Value: Integer);
procedure SetMasktype(const Value: Integer);
procedure SetPxmag(const Value: Integer);
procedure SetAngle(const Value: Integer);
procedure SetReverse(const Value: Boolean);
procedure SetMatch(const Value: Boolean);
procedure SetComFont(const Value: TFont);
procedure SetTransparent(const Value: Boolean);
procedure SetSymbolColor(const Value: TColor);
procedure SetBackColor(const Value: TColor);
procedure SetSymbolPicture(const Value: TPictures);
procedure SetSymbolEnabled(const Value: Boolean);
procedure SetSymbolDebug(const Value: Boolean);
procedure SetClearOption(const Value: Boolean);
procedure SetClipWatch(const Value: Boolean);
procedure SetOnClipChange(const Value: TNotifyEvent);
{ ローカル関数群 }
procedure PaintSymbolCodeB;
procedure PaintSymbolCodeM;
procedure SaveToClipAsWMF(const mf: TMetafile);
procedure WndClipProc(var Message: TMessage);
procedure UpdateClip;
procedure ClipChangeHandler(Sender: TObject);
procedure RotateBitmap(Degree: Integer);
procedure ReverseBitmap;
function CPos(Ch: Char; const Str: string; Index: Integer): Integer;
function Code2Data: Integer;
function Data2Code: Integer;
procedure CheckParity;
procedure CheckOffset;
function isData(i, j: Integer): Boolean;
function isBlack(i, j: Integer): Boolean;
function isFunc(i, j: Integer): Boolean;
function CharClassOf(src: PByte; len: Integer): Shortint;
procedure initvertable;
function qrEncodeDataWordA: Integer;
function qrEncodeDataWordM: Integer;
procedure qrInitDataWord;
function qrGetSourceRegion(src: PByte; len: Integer; var mode: Integer): Integer;
function qrGetEncodedLength(mode: Integer; len: Integer): Integer;
procedure qrAddDataBits(n: Integer; w: Longword);
function qrRemainedDataBits: Integer;
procedure qrComputeECWord;
procedure qrMakeCodeWord;
procedure qrFillFunctionPattern;
procedure qrFillCodeWord;
procedure qrInitPosition;
procedure qrNextPosition;
procedure qrSelectMaskPattern;
procedure qrSetMaskPattern(mask: Integer);
function qrEvaluateMaskPattern: Longint;
procedure qrFillFormatInfo;
procedure qrOutputSymbol;
procedure qrOutputSymbols;
protected
{ Protected 宣言 }
{ イベントメソッド宣言 }
procedure ChangeCode; dynamic;
procedure PaintSymbol; dynamic;
procedure PaintedSymbol; dynamic;
procedure ChangedCode; dynamic;
procedure ClipChange; dynamic;
public
{ Public 宣言 }
procedure PaintSymbolCode; virtual;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ 公開メソッド宣言 }
procedure Clear; virtual;
procedure CopyToClipboard; virtual;
procedure PasteFromClipboard; virtual;
procedure RepaintSymbol; virtual;
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
procedure LoadFromMemory(const Ptr: Pointer; Count: Integer);
{ プロパティ宣言 }
property Data[Index: Integer]: Byte read GetData write SetData; default;
property Memory: PChar read FMemory nodefault;
property Offset[Index: Integer]: Integer read GetOffset;
{ イベント宣言 }
property OnClipChange: TNotifyEvent read FOnClipChange write SetOnClipChange;
published
{ Published 宣言(プロパティ宣言) }
property Code: string read FCode write SetCode;
property Len: Integer read FLen nodefault;
property Binary: Boolean read FBinary nodefault;
property BinaryOperation: Boolean read FBinaryOperation write SetBinaryOperation default False;
property Mode: TQRMode read FMode write SetMode default qrSingle;
property Count: Integer read FCount write SetCount default 1;
property Column: Integer read FColumn write SetColumn default 16;
property Parity: Integer read FParity nodefault;
property Numbering: TNumbering read FNumbering write SetNumbering default nbrIfVoid;
property CommentUp: string read FCommentUp write SetCommentUp nodefault;
property CommentUpLoc: TLocation read FCommentUpLoc write SetCommentUpLoc nodefault;
property CommentDown: string read FCommentDown write SetCommentDown nodefault;
property CommentDownLoc: TLocation read FCommentDownLoc write SetCommentDownLoc nodefault;
property Usejis: Boolean read FUsejis write FUsejis; //使用jis优化,dcopyboy
property SymbolWidth: Integer read GetSymbolWidth;
property SymbolWidthS: Integer read GetSymbolWidthS;
property SymbolWidthA: Integer read GetSymbolWidthA;
property SymbolHeight: Integer read GetSymbolHeight;
property SymbolHeightS: Integer read GetSymbolHeightS;
property SymbolHeightA: Integer read GetSymbolHeightA;
property QuietZone: Integer read GetQuietZone;
property SymbolLeft: Integer read FSymbolLeft write SetSymbolLeft nodefault;
property SymbolTop: Integer read FSymbolTop write SetSymbolTop nodefault;
property SymbolSpaceUp: Integer read FSymbolSpaceUp write SetSymbolSpaceUp nodefault;
property SymbolSpaceDown: Integer read FSymbolSpaceDown write SetSymbolSpaceDown nodefault;
property SymbolSpaceLeft: Integer read FSymbolSpaceLeft write SetSymbolSpaceLeft nodefault;
property SymbolSpaceRight: Integer read FSymbolSpaceRight write SetSymbolSpaceRight nodefault;
property Version: Integer read FVersion write SetVersion default 1;
property Emode: Integer read FEmode write SetEmode default -1;
property EmodeR: Integer read FEmodeR nodefault;
property Eclevel: Integer read FEclevel write SetEclevel default 0;
property Masktype: Integer read FMasktype write SetMasktype default -1;
property MasktypeR: Integer read FMasktypeR nodefault;
property Capacity: Integer read GetCapacity;
property Pxmag: Integer read FPxmag write SetPxmag default 1;
property Angle: Integer read FAngle write SetAngle default 0;
property Reverse: Boolean read FReverse write SetReverse default False;
property PBM: TStringList read GetPBM;
property Match: Boolean read FMatch write SetMatch nodefault;
property ComFont: TFont read FComFont write SetComFont stored True;
property Transparent: Boolean read FTransparent write SetTransparent nodefault;
property SymbolColor: TColor read FSymbolColor write SetSymbolColor default clBlack;
property BackColor: TColor read FBackColor write SetBackColor default clWhite;
property SymbolPicture: TPictures read FSymbolPicture write SetSymbolPicture default picBMP;
property SymbolEnabled: Boolean read FSymbolEnabled write SetSymbolEnabled default True;
property SymbolDebug: Boolean read FSymbolDebug write SetSymbolDebug nodefault;
property SymbolDisped: Boolean read FSymbolDisped nodefault;
property ClearOption: Boolean read FClearOption write SetClearOption default False;
property ClipWatch: Boolean read FClipWatch write SetClipWatch default False;
{ イベント宣言 }
property OnChangeCode: TNotifyWatchEvent read FOnChangeCode write FOnChangeCode;
property OnPaintSymbol: TNotifyWatchEvent read FOnPaintSymbol write FOnPaintSymbol;
property OnPaintedSymbol: TNotifyWatchEvent read FOnPaintedSymbol write FOnPaintedSymbol;
property OnChangedCode: TNotifyWatchEvent read FOnChangedCode write FOnChangedCode;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('slmis', [TQRCode]);
end;
constructor TQRCode.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCode := '';
FMemory := nil;
FLen := 0;
FBinary := true;
FBinaryOperation := true;
FMode := qrSingle;
FCount := 1;
FColumn := 16;
icount := 1; // 表示中のシンボルのカウンタ値(1 ~ QR_PLS_MAX)
ZeroMemory(@offsets, SizeOf(offsets));
FParity := 0; // 連結モードの場合に使用するシンボルデータのパリティ値
FNumbering := nbrIfVoid;
FCommentUp := '';
FCommentUpLoc := locLeft;
FCommentDown := '';
FCommentDownLoc := locLeft;
FSymbolLeft := 0;
FSymbolTop := 0;
FSymbolSpaceUp := 0;
FSymbolSpaceDown := 0;
FSymbolSpaceLeft := 0;
FSymbolSpaceRight := 0;
FVersion := 1;
FEmode := -1; // 自動判定
FEmodeR := FEmode;
FEclevel := QR_ECL_L; // = 0(レベルL)
FMasktype := -1; // 自動設定
FMasktypeR := FMasktype;
FPxmag := 1;
FAngle := 0;
FReverse := False;
FPBM := TStringList.Create; FPBM.Duplicates := dupAccept;
FMatch := True;
FTransparent := False;
FComFont := TFont.Create;
FSymbolColor := clBlack;
FBackColor := clWhite;
FSymbolPicture := picBMP;
FSymbolEnabled := True;
FSymbolDebug := False; // デバッグ用プロパティ
FSymbolDisped := False;
FClearOption := False;
initvertable;
// 2002/10/06 Modify ぜえた From Here
FWindowHandle := AllocateHWnd(WndClipProc);
FClipWatch := False;
FWatch := False;
OnClipChange := ClipChangeHandler; // メソッドをイベントにアタッチする。
FSkip := False; // 最初の OnClipChange イベントをスキップする為のフラッグ
// 2002/10/06 Modify ぜえた Until Here
Usejis := false;//使用jis优化,dcopyboy
end;
destructor TQRCode.Destroy;
begin
// 2002/10/06 Modify ぜえた From Here
SetClipWatch(False);
DeallocateHWnd(FWindowHandle);
// 2002/10/06 Modify ぜえた Until Here
FComFont.Free;
FPBM.Free;
ReallocMem(FMemory, 0);
inherited Destroy;
end;
procedure TQRCode.ChangeCode; // イベントメソッド
begin
if Assigned(FOnChangeCode) and FSymbolEnabled then
FOnChangeCode(Self, FWatch); // イベントハンドラの呼び出し
end;
procedure TQRCode.ChangedCode; // イベントメソッド
begin
if Assigned(FOnChangedCode) and FSymbolEnabled then
FOnChangedCode(Self, FWatch); // イベントハンドラの呼び出し
end;
{ len バイトのサイズを持つバイトデータのポインタ src が与えられた時、先頭の }
{ 1バイト目の実際の文字クラスを返す関数です。1バイト目が、QR_EM_KANJI }
{ すなわち漢字の1バイト目であっても次の2バイト目が、漢字の2バイト目で }
{ ない場合や len が1の場合は、QR_EM_8BIT を返します。}
function TQRCode.CharClassOf(src: PByte; len: Integer): Shortint;
begin
Result := -1;
if (src = nil) or (len < 1) then
Exit; // エラー
// Dcopyboy 修改,不使用Jis优化,完美支持中文
if not Usejis then begin
Result := QR_EM_8BIT;
Exit;
end;
Result := charclass[src^];
if Result = QR_EM_KANJI then
begin
if len = 1 then
Result := QR_EM_8BIT
else
begin
Inc(src);
if not (src^ in Kanji2Data) then
Result := QR_EM_8BIT;
end;
end;
end;
{ Memory 内のシンボルデータを Count 個に分割し、分割後の各データの }
{ Memory 上のオフセット値を内部配列変数 offsets[] に格納する手続きです。}
{ この手続き内では、そのときの Count と Mode の値が適切であるかどうかも }
{ チェックし適切でなければ、適切な値にセットし直します。}
procedure TQRCode.CheckOffset;
var
i, j: Integer;
d: Integer;
begin
if FCount > FLen then // Count は Len よりも大きい値であってはならない。
FCount := FLen;
if FCount < 1 then
FCount := 1
else if FCount > QR_PLS_MAX then
FCount := QR_PLS_MAX;
d := FLen div FCount; // 分割後の各データの平均サイズ
if (d * FCount < FLen) and ((d + 1) * (FCount - 1) < FLen) then
Inc(d);
i := 0; // 配列 offsets[] のインデックス値(0 <= i <= Count)
j := 0; // Memory 上のオフセット値(0 <= j <= Len)
offsets[i] := j; // 先頭の値は、常に 0 である。
Inc(i);
j := j + d;
while (i < FCount) and (j < FLen) do
begin
if (StrByteType(FMemory, j) = mbTrailByte) and
(Byte(FMemory[j]) in Kanji2Data) then // 漢字の2バイト目
begin
if j - 1 > offsets[i - 1] then
Dec(j)
else if j + 1 < FLen then
Inc(j)
else
Break;
end;
offsets[i] := j;
Inc(i);
j := j + d;
end;
offsets[i] := FLen; // 最後尾のオフセット値は、常に Len である。
FCount := i; // 最終的に確定した Count の値
if FCount = 1 then
FMode := qrSingle // シングルモード
else if FCount <= QR_CNN_MAX then
begin
if FMode = qrSingle then // 今までシングルモードであった。
FMode := qrConnect; // 連結モード
end
else
FMode := qrPlus; // プラスモード
end;
{ 連結モードの場合に必要なシンボルデータのパリティ値を計算する手続きです。}
{ この手続きを呼び出す前には CheckOffset を呼んで Count と Mode の値を設定 }
{ しておく必要があります。さらにこの手続き内では、Len, Count, Mode, Column, }
{ offsets[] に格納された値が適正なものであるかどうかのチェックも行ないます。}
procedure TQRCode.CheckParity;
var
i: Integer;
pr: Byte;
err: string;
begin
err := '';
if FLen < 0 then
err := 'Len'
else if (FCount < 1) or (FCount > QR_PLS_MAX) then
err := 'Count'
else if (FMode <> qrSingle) and (FMode <> qrConnect) and (FMode <> qrPlus) then
err := 'Mode'
else if (FColumn < 1) or (FColumn > QR_PLS_MAX) then
err := 'Column'
else if FLen = 0 then
begin
if FCount <> 1 then
err := 'Count'
else if FMode <> qrSingle then
err := 'Mode'
else if offsets[0] <> 0 then
err := '0'
else if offsets[1] <> 0 then
err := '1';
end
else
begin
if FCount > Flen then
err := 'Count'
else if (FMode = qrSingle) and (FCount <> 1) then
err := 'Count'
else if (FMode = qrConnect) and ((FCount < 2) or (FCount > QR_CNN_MAX)) then
err := 'Count'
else if (FMode = qrPlus) and ((FCount < 2) or (FCount > QR_PLS_MAX)) then
err := 'Count'
else if offsets[0] <> 0 then
err := '0'
else if offsets[FCount] <> FLen then
err := IntToStr(FCount)
else
begin
for i := 1 to FCount do
begin
if offsets[i] <= offsets[i - 1] then
begin
err := IntToStr(i);
Break;
end;
end;
end;
end;
if err <> '' then // 何らかのエラーがあった。
begin
if err = 'Len' then
i := FLen
else if err = 'Count' then
i := FCount
else if err = 'Mode' then
i := Integer(FMode)
else if err = 'Column' then
i := FColumn
else
begin
i := StrToInt(err);
i := offsets[i];
err := 'Offset[' + err + ']';
end;
err := 'Illegal ' + err + ' : %d';
raise Exception.CreateFmt(err, [i]);
end;
if (FMode <> qrConnect) or (FLen div FCount > QR_SRC_MAX) then
Exit; // この場合、パリティ値の計算は行なわない。
pr := Byte(FMemory[0]); // 先頭のデータ
for i := 1 to FLen - 1 do
pr := pr xor Byte(FMemory[i]);
FParity := Integer(pr);
end;
{ 現在 Picture が、保持しているグラフイックデータを破棄して Canvas を }
{ クリアーするメソッドです。このとき SymbolDisped プロパティは False }
{ に設定されます。}
procedure TQRCode.Clear;
begin
if FSymbolDisped = True then
FSymbolDisped := False;
Picture := nil; // グラフイックデータを破棄
end;
{ 2002/10/06 Update ぜえた From Here }
procedure TQRCode.ClipChange; // イベントメソッド
begin
if Assigned(FOnClipChange) then
FOnClipChange(Self); // イベントハンドラの呼び出し
end;
procedure TQRCode.ClipChangeHandler(Sender: TObject);
begin
if FSkip = True then // 最初に発生した OnClipChange イベントをスキップする。
begin
FSkip := False;
Exit;
end;
FWatch := True; // クリップボード監視中にテキストデータがコピーされた。
PasteFromClipboard;
FWatch := False;
end;
{ 2002/10/06 Update ぜえた Until Here }
{ Code プロパティの文字列をバイトデータに変換して、シンボルデータ領域である }
{ Memory プロパティに格納する関数。そのときの BinaryOption プロパティの値に }
{ よってデータ変換の結果は異なります。戻り値は、変換されたデータのバイト数 }
{ です。バイナリデータを含む場合、Binary プロパティは True にセットされます。}
{ BinaryOption プロパティが True のときに変換エラーが生じると BinaryOption }
{ プロパティは強制的に False にセットされ全て通常の文字列とみなされます。}
function TQRCode.Code2Data: Integer;
var
i, j: Integer;
p1, p2: Integer;
S: string;
e: Integer;
begin
Result := Length(FCode);
FBinary := False;
ReallocMem(FMemory, Result + 4);
if Result = 0 then
Exit;
i := 1; // コードのインデックス
j := 0; // データのインデックス
S := '$00';
if FBinaryOperation = True then
begin
while i <= Result do
begin
p1 := CPos('~', FCode, i); // 最初に '~' 文字が見つかった位置
if p1 = 0 then // 見つからなかった場合は、以後全て通常の文字と見なす。
begin
while i <= Result do
begin
FMemory[j] := FCode[i];
Inc(j);
Inc(i);
end;
Break;
end;
p2 := CPos('~', FCode, p1 + 1); // 次に '~' 文字が見つかった位置
if (p2 = 0) or ((p2 - p1 - 1) mod 2 <> 0) then // エラー
begin
i := 0; // エラーのサイン
Break;
end;
while i < p1 do
begin
FMemory[j] := FCode[i];
Inc(j);
Inc(i);
end;
if p2 = p1 + 1 then // '~' 文字自身
begin
FMemory[j] := '~';
Inc(j);
end
else begin
i := p1 + 1;
while i <= p2 - 2 do
begin
S[2] := FCode[i];
Inc(i);
S[3] := FCode[i];
Inc(i);
e := StrToIntDef(S, 256);
if e = 256 then // エラー
begin
i := 0; // エラーのサイン
Break;
end;
FMemory[j] := Chr(e);
Inc(j);
if Byte(e) in BinaryData then // バイナリデータを含んでいた。
FBinary := True;
end;
end;
if i = 0 then // エラー
Break;
i := p2 + 1;
end;
if i = 0 then // エラー
begin // エラーがあって変換不能の場合は、通常の文字列と見なす。
FBinaryOperation := False;
FBinary := False;
end
else begin
if Result <> j then
begin
Result := j; // データのサイズ
ReallocMem(FMemory, Result + 4);
FMemory[Result] := Chr($00);
FMemory[Result + 1] := Chr($00);
FMemory[Result + 2] := Chr($00);
FMemory[Result + 3] := Chr($00);
end;
Exit;
end;
end;
{ BinaryOperation = False のとき }
CopyMemory(FMemory, PChar(FCode), Result);
FMemory[Result] := Chr($00);
FMemory[Result + 1] := Chr($00);
FMemory[Result + 2] := Chr($00);
FMemory[Result + 3] := Chr($00);
end;
procedure TQRCode.CopyToClipboard;
begin
{ まだ一度もシンボルを表示していないか、表示に失敗した場合は、Bitmap や }
{ Metafile あるいはそれ以外の形式で画像が表示されている可能性もあるので }
{ 可能な限りコピーを試みます。}
if FSymbolDisped = False then
Clipboard.Assign(Picture)
else if FSymbolPicture = picBMP then // ビットマップ形式でコピー
Clipboard.Assign(Picture.Bitmap)
else if FSymbolPicture = picEMF then // EMF形式でコピー
Clipboard.Assign(Picture.Metafile) // (Win32 エンハンスドメタファイル)
else // WMF形式でコピー
SaveToClipAsWMF(Picture.Metafile); // (Win16 形式メタファイル)
end;
{ 文字列 Str の Index バイト目以降で最初に文字 Ch が見つかった位置を }
{ 返す関数。エラーあるいは見つからなかった場合の戻り値は、0 です。}
function TQRCode.CPos(Ch: Char; const Str: string; Index: Integer): Integer;
var
i: Integer;
begin
Result := 0; // エラーあるいは見つからなかった場合の戻り値
if Index < 1 then
Exit;
for i := Index to Length(Str) do
begin
if Str[i] = Ch then
begin
Result := i;
Break;
end;
end;
end;
{ Memory プロパティに格納されているシンボルデータを文字列に変換して、Code }
{ プロパティに格納する関数。シンボルデータがバイナリデータを含む場合は、}
{ Binary プロパティと BinaryOption プロパティは、True にセットされます。}
{ この関数を呼び出す前には、シンボルデータのサイズを Len プロパティに }
{ セットしておく必要があります。戻り値は形式上、シンボルデータのサイズ }
{ すなわち Len プロパティの値を返す様になっています。}
function TQRCode.Data2Code: Integer;
var
i, j: Integer;
P: PChar;
len: Integer;
S: string;
inBinary: Boolean;
begin
{ この関数を呼び出す前には、FLen の値が確定されている必要があります。}
Result := FLen;
FBinary := False;
if Result = 0 then
begin
FCode := '';
Exit;
end;
for i := 0 to Result - 1 do
begin
if Byte(FMemory[i]) in BinaryData then
begin
FBinary := True;
FBinaryOperation := True;
Break;
end;
end;
if FBinary = False then
begin
FCode := FMemory; // Create String
Exit;
end;
P := nil;
len := Result + 8;
ReallocMem(P, len);
i := 0; // データのインデックス
j := 0; // コードのインデックス
inBinary := False;
while i < Result do
begin
if j + 8 > len then
begin
len := len + 8;
ReallocMem(P, len);
end;
if Byte(FMemory[i]) in BinaryData then
begin
if inBinary = False then
begin
P[j] := '~'; // Start of Binary Data
Inc(j);
inBinary := True;
end;
S := IntToHex(Byte(FMemory[i]), 2);
P[j] := S[1];
Inc(j);
P[j] := S[2];
Inc(j);
end
else
begin
if inBinary = True then
begin
P[j] := '~'; // End of Binary Data
Inc(j);
inBinary := False;
end;
P[j] := FMemory[i];
if P[j] = '~' then
begin
Inc(j);
P[j] := '~';
end;
Inc(j);
end;
Inc(i);
end;
if inBinary = True then
begin
P[j] := '~'; // End of Binary Data
Inc(j);
end;
P[j] := Chr($00); // End of String
P[j + 1] := Chr($00);
P[j + 2] := Chr($00);
P[j + 3] := Chr($00);
FCode := P; // Create String
ReallocMem(P, 0); // Free Memory
end;
function TQRCode.GetCapacity: Integer;
var
em: Integer;
begin
em := FEmodeR;
if em = -1 then
em := QR_EM_ALNUM; // この場合は、暫定的に英数字モードの値を返す。
Result := vertable[FVersion].ecl[FEclevel].capacity[em] * FCount;
end;
function TQRCode.GetData(Index: Integer): Byte;
begin
if (Index < 0) or (Index >= FLen) then
raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d',
[Index, 0, FLen - 1]);
Result := Byte(FMemory[Index]);
end;
function TQRCode.GetOffset(Index: Integer): Integer;
begin
if (Index < 0) or (Index > FCount) then
raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d',
[Index, 0, FCount]);
Result := offsets[Index];
end;
function TQRCode.GetPBM: TStringList;
begin
qrOutputSymbols;
Result := FPBM;
end;
function TQRCode.GetQuietZone: Integer;
begin
Result := QR_DIM_SEP * FPxmag;
end;
function TQRCode.GetSymbolHeight: Integer;
begin
Result := (vertable[FVersion].dimension + QR_DIM_SEP * 2) * FPxmag;
end;
function TQRCode.GetSymbolHeightA: Integer;
var
n: Integer;
begin
n := FCount div FColumn;
if (FCount mod FColumn) <> 0 then
Inc(n);
Result := SymbolHeightS * n
end;
function TQRCode.GetSymbolHeightS: Integer;
begin
Result := FSymbolSpaceUp + SymbolHeight + FSymbolSpaceDown;
end;
function TQRCode.GetSymbolWidth: Integer;
begin
Result := (vertable[FVersion].dimension + QR_DIM_SEP * 2) * FPxmag;
end;
function TQRCode.GetSymbolWidthA: Integer;
var
n: Integer;
begin
if FCount < FColumn then
n := FCount
else
n := FColumn;
Result := SymbolWidthS * n
end;
function TQRCode.GetSymbolWidthS: Integer;
begin
Result := FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight;
end;
procedure TQRCode.initvertable;
const
{ vertable 初期化用データ領域 }
capacities: array[1..40, 0..3, 0..3] of Integer = (
// version 1 (capacities[1][0] ~capacities[1][3])
((41, 25, 17, 10), (34, 20, 14, 8), (27, 16, 11, 7), (17, 10, 7, 4)),
// version 2
((77, 47, 32, 20), (63, 38, 26, 16), (48, 29, 20, 12), (34, 20, 14, 8)),
// version 3
((127, 77, 53, 32), (101, 61, 42, 26), (77, 47, 32, 20), (58, 35, 24, 15)),
// version 4
((187, 114, 78, 48), (149, 90, 62, 38), (111, 67, 46, 28), (82, 50, 34, 21)),
// version 5
((255, 154, 106, 65), (202, 122, 84, 52), (144, 87, 60, 37), (106, 64, 44, 27)),
// version 6
((322, 195, 134, 82), (255, 154, 106, 65), (178, 108, 74, 45), (139, 84, 58, 36)),
// version 7
((370, 224, 154, 95), (293, 178, 122, 75), (207, 125, 86, 53), (154, 93, 64, 39)),
// version 8
((461, 279, 192, 118), (365, 221, 152, 93), (259, 157, 108, 66), (202, 122, 84, 52)),
// version 9
((552, 335, 230, 141), (432, 262, 180, 111), (312, 189, 130, 80), (235, 143, 98, 60)),
// version 10
((652, 395, 271, 167), (513, 311, 213, 131), (364, 221, 151, 93), (288, 174, 119, 74)),
// version 11
((772, 468, 321, 198), (604, 366, 251, 155), (427, 259, 177, 109), (331, 200, 137, 85)),
// version 12
((883, 535, 367, 226), (691, 419, 287, 177), (489, 296, 203, 125), (374, 227, 155, 96)),
// version 13
((1022, 619, 425, 262), (796, 483, 331, 204), (580, 352, 241, 149), (427, 259, 177, 109)),
// version 14
((1101, 667, 458, 282), (871, 528, 362, 223), (621, 376, 258, 159), (468, 283, 194, 120)),
// version 15
((1250, 758, 520, 320), (991, 600, 412, 254), (703, 426, 292, 180), (530, 321, 220, 136)),
// version 16
((1408, 854, 586, 361), (1082, 656, 450, 277), (775, 470, 322, 198), (602, 365, 250, 154)),
// version 17
((1548, 938, 644, 397), (1212, 734, 504, 310), (876, 531, 364, 224), (674, 408, 280, 173)),
// version 18
((1725, 1046, 718, 442), (1346, 816, 560, 345), (948, 574, 394, 243), (746, 452, 310, 191)),
// version 19
((1903, 1153, 792, 488), (1500, 909, 624, 384), (1063, 644, 442, 272), (813, 493, 338, 208)),
// version 20
((2061, 1249, 858, 528), (1600, 970, 666, 410), (1159, 702, 482, 297), (919, 557, 382, 235)),
// version 21
((2232, 1352, 929, 572), (1708, 1035, 711, 438), (1224, 742, 509, 314), (969, 587, 403, 248)),
// version 22
((2409, 1460, 1003, 618), (1872, 1134, 779, 480), (1358, 823, 565, 348), (1056, 640, 439, 270)),
// version 23
((2620, 1588, 1091, 672), (2059, 1248, 857, 528), (1468, 890, 611, 376), (1108, 672, 461, 284)),
// version 24
((2812, 1704, 1171, 721), (2188, 1326, 911, 561), (1588, 963, 661, 407), (1228, 744, 511, 315)),
// version 25
((3057, 1853, 1273, 784), (2395, 1451, 997, 614), (1718, 1041, 715, 440), (1286, 779, 535, 330)),
// version 26
((3283, 1990, 1367, 842), (2544, 1542, 1059, 652), (1804, 1094, 751, 462), (1425, 864, 593, 365)),
// version 27
((3517, 2132, 1465, 902), (2701, 1637, 1125, 692), (1933, 1172, 805, 496), (1501, 910, 625, 385)),
// version 28
((3669, 2223, 1528, 940), (2857, 1732, 1190, 732), (2085, 1263, 868, 534), (1581, 958, 658, 405)),
// version 29
((3909, 2369, 1628, 1002), (3035, 1839, 1264, 778), (2181, 1322, 908, 559), (1677, 1016, 698, 430)),
// version 30
((4158, 2520, 1732, 1066), (3289, 1994, 1370, 843), (2358, 1429, 982, 604), (1782, 1080, 742, 457)),
// version 31
((4417, 2677, 1840, 1132), (3486, 2113, 1452, 894), (2473, 1499, 1030, 634), (1897, 1150, 790, 486)),
// version 32
((4686, 2840, 1952, 1201), (3693, 2238, 1538, 947), (2670, 1618, 1112, 684), (2022, 1226, 842, 518)),
// version 33
((4965, 3009, 2068, 1273), (3909, 2369, 1628, 1002), (2805, 1700, 1168, 719), (2157, 1307, 898, 553)),
// version 34
((5253, 3183, 2188, 1347), (4134, 2506, 1722, 1060), (2949, 1787, 1228, 756), (2301, 1394, 958, 590)),
// version 35
((5529, 3351, 2303, 1417), (4343, 2632, 1809, 1113), (3081, 1867, 1283, 790), (2361, 1431, 983, 605)),
// version 36
((5836, 3537, 2431, 1496), (4588, 2780, 1911, 1176), (3244, 1966, 1351, 832), (2524, 1530, 1051, 647)),
// version 37
((6153, 3729, 2563, 1577), (4775, 2894, 1989, 1224), (3417, 2071, 1423, 876), (2625, 1591, 1093, 673)),
// version 38
((6479, 3927, 2699, 1661), (5039, 3054, 2099, 1292), (3599, 2181, 1499, 923), (2735, 1658, 1139, 701)),
// version 39
((6743, 4087, 2809, 1729), (5313, 3220, 2213, 1362), (3791, 2298, 1579, 972), (2927, 1774, 1219, 750)),
// version 40
((7089, 4296, 2953, 1817), (5596, 3391, 2331, 1435), (3993, 2420, 1663, 1024), (3057, 1852, 1273, 784))
);
rsbs: array[0..287] of QR_RSBLOCK = (
// version 1 (rsbs[0]~rsbs[3])
(rsbnum: 1; totalwords: 26; datawords: 19; ecnum: 2),
(rsbnum: 1; totalwords: 26; datawords: 16; ecnum: 4),
(rsbnum: 1; totalwords: 26; datawords: 13; ecnum: 6),
(rsbnum: 1; totalwords: 26; datawords: 9; ecnum: 8),
// version 2 (rsbs[4]~rsbs[7])
(rsbnum: 1; totalwords: 44; datawords: 34; ecnum: 4),
(rsbnum: 1; totalwords: 44; datawords: 28; ecnum: 8),
(rsbnum: 1; totalwords: 44; datawords: 22; ecnum: 11),
(rsbnum: 1; totalwords: 44; datawords: 16; ecnum: 14),
// version 3 (rsbs[8]~rsbs[11])
(rsbnum: 1; totalwords: 70; datawords: 55; ecnum: 7),
(rsbnum: 1; totalwords: 70; datawords: 44; ecnum: 13),
(rsbnum: 2; totalwords: 35; datawords: 17; ecnum: 9),
(rsbnum: 2; totalwords: 35; datawords: 13; ecnum: 11),
// version 4 (rsbs[12]~rsbs[15])
(rsbnum: 1; totalwords: 100; datawords: 80; ecnum: 10),
(rsbnum: 2; totalwords: 50; datawords: 32; ecnum: 9),
(rsbnum: 2; totalwords: 50; datawords: 24; ecnum: 13),
(rsbnum: 4; totalwords: 25; datawords: 9; ecnum: 8),
// version 5 (rsbs[16]~rsbs[21])
(rsbnum: 1; totalwords: 134; datawords: 108; ecnum: 13),
(rsbnum: 2; totalwords: 67; datawords: 43; ecnum: 12),
(rsbnum: 2; totalwords: 33; datawords: 15; ecnum: 9), (rsbnum: 2; totalwords: 34; datawords: 16; ecnum: 9),
(rsbnum: 2; totalwords: 33; datawords: 11; ecnum: 11), (rsbnum: 2; totalwords: 34; datawords: 12; ecnum: 11),
// version 6 (rsbs[22]~rsbs[25])
(rsbnum: 2; totalwords: 86; datawords: 68; ecnum: 9),
(rsbnum: 4; totalwords: 43; datawords: 27; ecnum: 8),
(rsbnum: 4; totalwords: 43; datawords: 19; ecnum: 12),
(rsbnum: 4; totalwords: 43; datawords: 15; ecnum: 14),
// version 7 (rsbs[26]~rsbs[31])
(rsbnum: 2; totalwords: 98; datawords: 78; ecnum: 10),
(rsbnum: 4; totalwords: 49; datawords: 31; ecnum: 9),
(rsbnum: 2; totalwords: 32; datawords: 14; ecnum: 9), (rsbnum: 4; totalwords: 33; datawords: 15; ecnum: 9),
(rsbnum: 4; totalwords: 39; datawords: 13; ecnum: 13), (rsbnum: 1; totalwords: 40; datawords: 14; ecnum: 13),
// version 8 (rsbs[32]~rsbs[38])
(rsbnum: 2; totalwords: 121; datawords: 97; ecnum: 12),
(rsbnum: 2; totalwords: 60; datawords: 38; ecnum: 11), (rsbnum: 2; totalwords: 61; datawords: 39; ecnum: 11),
(rsbnum: 4; totalwords: 40; datawords: 18; ecnum: 11), (rsbnum: 2; totalwords: 41; datawords: 19; ecnum: 11),
(rsbnum: 4; totalwords: 40; datawords: 14; ecnum: 13), (rsbnum: 2; totalwords: 41; datawords: 15; ecnum: 13),
// version 9 (rsbs[39]~rsbs[45])
(rsbnum: 2; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 3; totalwords: 58; datawords: 36; ecnum: 11), (rsbnum: 2; totalwords: 59; datawords: 37; ecnum: 11),
(rsbnum: 4; totalwords: 36; datawords: 16; ecnum: 10), (rsbnum: 4; totalwords: 37; datawords: 17; ecnum: 10),
(rsbnum: 4; totalwords: 36; datawords: 12; ecnum: 12), (rsbnum: 4; totalwords: 37; datawords: 13; ecnum: 12),
// version 10 (rsbs[46]~rsbs[53])
(rsbnum: 2; totalwords: 86; datawords: 68; ecnum: 9), (rsbnum: 2; totalwords: 87; datawords: 69; ecnum: 9),
(rsbnum: 4; totalwords: 69; datawords: 43; ecnum: 13), (rsbnum: 1; totalwords: 70; datawords: 44; ecnum: 13),
(rsbnum: 6; totalwords: 43; datawords: 19; ecnum: 12), (rsbnum: 2; totalwords: 44; datawords: 20; ecnum: 12),
(rsbnum: 6; totalwords: 43; datawords: 15; ecnum: 14), (rsbnum: 2; totalwords: 44; datawords: 16; ecnum: 14),
// version 11 (rsbs[54]~rsbs[60])
(rsbnum: 4; totalwords: 101; datawords: 81; ecnum: 10),
(rsbnum: 1; totalwords: 80; datawords: 50; ecnum: 15), (rsbnum: 4; totalwords: 81; datawords: 51; ecnum: 15),
(rsbnum: 4; totalwords: 50; datawords: 22; ecnum: 14), (rsbnum: 4; totalwords: 51; datawords: 23; ecnum: 14),
(rsbnum: 3; totalwords: 36; datawords: 12; ecnum: 12), (rsbnum: 8; totalwords: 37; datawords: 13; ecnum: 12),
// version 12 (rsbs[61]~rsbs[68])
(rsbnum: 2; totalwords: 116; datawords: 92; ecnum: 12), (rsbnum: 2; totalwords: 117; datawords: 93; ecnum: 12),
(rsbnum: 6; totalwords: 58; datawords: 36; ecnum: 11), (rsbnum: 2; totalwords: 59; datawords: 37; ecnum: 11),
(rsbnum: 4; totalwords: 46; datawords: 20; ecnum: 13), (rsbnum: 6; totalwords: 47; datawords: 21; ecnum: 13),
(rsbnum: 7; totalwords: 42; datawords: 14; ecnum: 14), (rsbnum: 4; totalwords: 43; datawords: 15; ecnum: 14),
// version 13 (rsbs[69]~rsbs[75])
(rsbnum: 4; totalwords: 133; datawords: 107; ecnum: 13),
(rsbnum: 8; totalwords: 59; datawords: 37; ecnum: 11), (rsbnum: 1; totalwords: 60; datawords: 38; ecnum: 11),
(rsbnum: 8; totalwords: 44; datawords: 20; ecnum: 12), (rsbnum: 4; totalwords: 45; datawords: 21; ecnum: 12),
(rsbnum: 12; totalwords: 33; datawords: 11; ecnum: 11), (rsbnum: 4; totalwords: 34; datawords: 12; ecnum: 11),
// version 14 (rsbs[76]~rsbs[83])
(rsbnum: 3; totalwords: 145; datawords: 115; ecnum: 15), (rsbnum: 1; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 4; totalwords: 64; datawords: 40; ecnum: 12), (rsbnum: 5; totalwords: 65; datawords: 41; ecnum: 12),
(rsbnum: 11; totalwords: 36; datawords: 16; ecnum: 10), (rsbnum: 5; totalwords: 37; datawords: 17; ecnum: 10),
(rsbnum: 11; totalwords: 36; datawords: 12; ecnum: 12), (rsbnum: 5; totalwords: 37; datawords: 13; ecnum: 12),
// version 15 (rsbs[84]~rsbs[91])
(rsbnum: 5; totalwords: 109; datawords: 87; ecnum: 11), (rsbnum: 1; totalwords: 110; datawords: 88; ecnum: 11),
(rsbnum: 5; totalwords: 65; datawords: 41; ecnum: 12), (rsbnum: 5; totalwords: 66; datawords: 42; ecnum: 12),
(rsbnum: 5; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 7; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 11; totalwords: 36; datawords: 12; ecnum: 12), (rsbnum: 7; totalwords: 37; datawords: 13; ecnum: 12),
// version 16 (rsbs[92]~rsbs[99])
(rsbnum: 5; totalwords: 122; datawords: 98; ecnum: 12), (rsbnum: 1; totalwords: 123; datawords: 99; ecnum: 12),
(rsbnum: 7; totalwords: 73; datawords: 45; ecnum: 14), (rsbnum: 3; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 15; totalwords: 43; datawords: 19; ecnum: 12), (rsbnum: 2; totalwords: 44; datawords: 20; ecnum: 12),
(rsbnum: 3; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 13; totalwords: 46; datawords: 16; ecnum: 15),
// version 17 (rsbs[100]~rsbs[107])
(rsbnum: 1; totalwords: 135; datawords: 107; ecnum: 14), (rsbnum: 5; totalwords: 136; datawords: 108; ecnum: 14),
(rsbnum: 10; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 1; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 1; totalwords: 50; datawords: 22; ecnum: 14), (rsbnum: 15; totalwords: 51; datawords: 23; ecnum: 14),
(rsbnum: 2; totalwords: 42; datawords: 14; ecnum: 14), (rsbnum: 17; totalwords: 43; datawords: 15; ecnum: 14),
// version 18 (rsbs[108]~rsbs[115])
(rsbnum: 5; totalwords: 150; datawords: 120; ecnum: 15), (rsbnum: 1; totalwords: 151; datawords: 121; ecnum: 15),
(rsbnum: 9; totalwords: 69; datawords: 43; ecnum: 13), (rsbnum: 4; totalwords: 70; datawords: 44; ecnum: 13),
(rsbnum: 17; totalwords: 50; datawords: 22; ecnum: 14), (rsbnum: 1; totalwords: 51; datawords: 23; ecnum: 14),
(rsbnum: 2; totalwords: 42; datawords: 14; ecnum: 14), (rsbnum: 19; totalwords: 43; datawords: 15; ecnum: 14),
// version 19 (rsbs[116]~rsbs[123])
(rsbnum: 3; totalwords: 141; datawords: 113; ecnum: 14), (rsbnum: 4; totalwords: 142; datawords: 114; ecnum: 14),
(rsbnum: 3; totalwords: 70; datawords: 44; ecnum: 13), (rsbnum: 11; totalwords: 71; datawords: 45; ecnum: 13),
(rsbnum: 17; totalwords: 47; datawords: 21; ecnum: 13), (rsbnum: 4; totalwords: 48; datawords: 22; ecnum: 13),
(rsbnum: 9; totalwords: 39; datawords: 13; ecnum: 13), (rsbnum: 16; totalwords: 40; datawords: 14; ecnum: 13),
// version 20 (rsbs[124]~rsbs[131])
(rsbnum: 3; totalwords: 135; datawords: 107; ecnum: 14), (rsbnum: 5; totalwords: 136; datawords: 108; ecnum: 14),
(rsbnum: 3; totalwords: 67; datawords: 41; ecnum: 13), (rsbnum: 13; totalwords: 68; datawords: 42; ecnum: 13),
(rsbnum: 15; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 5; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 15; totalwords: 43; datawords: 15; ecnum: 14), (rsbnum: 10; totalwords: 44; datawords: 16; ecnum: 14),
// version 21 (rsbs[132]~rsbs[138])
(rsbnum: 4; totalwords: 144; datawords: 116; ecnum: 14), (rsbnum: 4; totalwords: 145; datawords: 117; ecnum: 14),
(rsbnum: 17; totalwords: 68; datawords: 42; ecnum: 13),
(rsbnum: 17; totalwords: 50; datawords: 22; ecnum: 14), (rsbnum: 6; totalwords: 51; datawords: 23; ecnum: 14),
(rsbnum: 19; totalwords: 46; datawords: 16; ecnum: 15), (rsbnum: 6; totalwords: 47; datawords: 17; ecnum: 15),
// version 22 (rsbs[139]~rsbs[144])
(rsbnum: 2; totalwords: 139; datawords: 111; ecnum: 14), (rsbnum: 7; totalwords: 140; datawords: 112; ecnum: 14),
(rsbnum: 17; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 7; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 16; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 34; totalwords: 37; datawords: 13; ecnum: 13),
// version 23 (rsbs[145]~rsbs[152])
(rsbnum: 4; totalwords: 151; datawords: 121; ecnum: 15), (rsbnum: 5; totalwords: 152; datawords: 122; ecnum: 15),
(rsbnum: 4; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 14; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 11; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 14; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 16; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 14; totalwords: 46; datawords: 16; ecnum: 15),
// version 24 (rsbs[153]~rsbs[160])
(rsbnum: 6; totalwords: 147; datawords: 117; ecnum: 15), (rsbnum: 4; totalwords: 148; datawords: 118; ecnum: 15),
(rsbnum: 6; totalwords: 73; datawords: 45; ecnum: 14), (rsbnum: 14; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 11; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 16; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 30; totalwords: 46; datawords: 16; ecnum: 15), (rsbnum: 2; totalwords: 47; datawords: 17; ecnum: 15),
// version 25 (rsbs[161]~rsbs[168])
(rsbnum: 8; totalwords: 132; datawords: 106; ecnum: 13), (rsbnum: 4; totalwords: 133; datawords: 107; ecnum: 13),
(rsbnum: 8; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 13; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 7; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 22; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 22; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 13; totalwords: 46; datawords: 16; ecnum: 15),
// version 26 (rsbs[169]~rsbs[176])
(rsbnum: 10; totalwords: 142; datawords: 114; ecnum: 14), (rsbnum: 2; totalwords: 143; datawords: 115; ecnum: 14),
(rsbnum: 19; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 4; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 28; totalwords: 50; datawords: 22; ecnum: 14), (rsbnum: 6; totalwords: 51; datawords: 23; ecnum: 14),
(rsbnum: 33; totalwords: 46; datawords: 16; ecnum: 15), (rsbnum: 4; totalwords: 47; datawords: 17; ecnum: 15),
// version 27 (rsbs[177]~rsbs[184])
(rsbnum: 8; totalwords: 152; datawords: 122; ecnum: 15), (rsbnum: 4; totalwords: 153; datawords: 123; ecnum: 15),
(rsbnum: 22; totalwords: 73; datawords: 45; ecnum: 14), (rsbnum: 3; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 8; totalwords: 53; datawords: 23; ecnum: 15), (rsbnum: 26; totalwords: 54; datawords: 24; ecnum: 15),
(rsbnum: 12; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 28; totalwords: 46; datawords: 16; ecnum: 15),
// version 28 (rsbs[185]~rsbs[192])
(rsbnum: 3; totalwords: 147; datawords: 117; ecnum: 15), (rsbnum: 10; totalwords: 148; datawords: 118; ecnum: 15),
(rsbnum: 3; totalwords: 73; datawords: 45; ecnum: 14), (rsbnum: 23; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 4; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 31; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 11; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 31; totalwords: 46; datawords: 16; ecnum: 15),
// version 29 (rsbs[193]~rsbs[200])
(rsbnum: 7; totalwords: 146; datawords: 116; ecnum: 15), (rsbnum: 7; totalwords: 147; datawords: 117; ecnum: 15),
(rsbnum: 21; totalwords: 73; datawords: 45; ecnum: 14), (rsbnum: 7; totalwords: 74; datawords: 46; ecnum: 14),
(rsbnum: 1; totalwords: 53; datawords: 23; ecnum: 15), (rsbnum: 37; totalwords: 54; datawords: 24; ecnum: 15),
(rsbnum: 19; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 26; totalwords: 46; datawords: 16; ecnum: 15),
// version 30 (rsbs[201]~rsbs[208])
(rsbnum: 5; totalwords: 145; datawords: 115; ecnum: 15), (rsbnum: 10; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 19; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 10; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 15; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 25; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 23; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 25; totalwords: 46; datawords: 16; ecnum: 15),
// version 31 (rsbs[209]~rsbs[216])
(rsbnum: 13; totalwords: 145; datawords: 115; ecnum: 15), (rsbnum: 3; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 2; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 29; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 42; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 1; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 23; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 28; totalwords: 46; datawords: 16; ecnum: 15),
// version 32 (rsbs[217]~rsbs[223])
(rsbnum: 17; totalwords: 145; datawords: 115; ecnum: 15),
(rsbnum: 10; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 23; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 10; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 35; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 19; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 35; totalwords: 46; datawords: 16; ecnum: 15),
// version 33 (rsbs[224]~rsbs[231])
(rsbnum: 17; totalwords: 145; datawords: 115; ecnum: 15), (rsbnum: 1; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 14; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 21; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 29; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 19; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 11; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 46; totalwords: 46; datawords: 16; ecnum: 15),
// version 34 (rsbs[232]~rsbs[239])
(rsbnum: 13; totalwords: 145; datawords: 115; ecnum: 15), (rsbnum: 6; totalwords: 146; datawords: 116; ecnum: 15),
(rsbnum: 14; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 23; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 44; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 7; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 59; totalwords: 46; datawords: 16; ecnum: 15), (rsbnum: 1; totalwords: 47; datawords: 17; ecnum: 15),
// version 35 (rsbs[240]~rsbs[247])
(rsbnum: 12; totalwords: 151; datawords: 121; ecnum: 15), (rsbnum: 7; totalwords: 152; datawords: 122; ecnum: 15),
(rsbnum: 12; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 26; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 39; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 14; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 22; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 41; totalwords: 46; datawords: 16; ecnum: 15),
// version 36 (rsbs[248]~rsbs[255])
(rsbnum: 6; totalwords: 151; datawords: 121; ecnum: 15), (rsbnum: 14; totalwords: 152; datawords: 122; ecnum: 15),
(rsbnum: 6; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 34; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 46; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 10; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 2; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 64; totalwords: 46; datawords: 16; ecnum: 15),
// version 37 (rsbs[256]~rsbs[263])
(rsbnum: 17; totalwords: 152; datawords: 122; ecnum: 15), (rsbnum: 4; totalwords: 153; datawords: 123; ecnum: 15),
(rsbnum: 29; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 14; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 49; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 10; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 24; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 46; totalwords: 46; datawords: 16; ecnum: 15),
// version 38 (rsbs[264]~rsbs[271])
(rsbnum: 4; totalwords: 152; datawords: 122; ecnum: 15), (rsbnum: 18; totalwords: 153; datawords: 123; ecnum: 15),
(rsbnum: 13; totalwords: 74; datawords: 46; ecnum: 14), (rsbnum: 32; totalwords: 75; datawords: 47; ecnum: 14),
(rsbnum: 48; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 14; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 42; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 32; totalwords: 46; datawords: 16; ecnum: 15),
// version 39 (rsbs[272]~rsbs[279])
(rsbnum: 20; totalwords: 147; datawords: 117; ecnum: 15), (rsbnum: 4; totalwords: 148; datawords: 118; ecnum: 15),
(rsbnum: 40; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 7; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 43; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 22; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 10; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 67; totalwords: 46; datawords: 16; ecnum: 15),
// version 40 (rsbs[280]~rsbs[287])
(rsbnum: 19; totalwords: 148; datawords: 118; ecnum: 15), (rsbnum: 6; totalwords: 149; datawords: 119; ecnum: 15),
(rsbnum: 18; totalwords: 75; datawords: 47; ecnum: 14), (rsbnum: 31; totalwords: 76; datawords: 48; ecnum: 14),
(rsbnum: 34; totalwords: 54; datawords: 24; ecnum: 15), (rsbnum: 34; totalwords: 55; datawords: 25; ecnum: 15),
(rsbnum: 20; totalwords: 45; datawords: 15; ecnum: 15), (rsbnum: 61; totalwords: 46; datawords: 16; ecnum: 15)
);
nlens: array[0..2, 0..3] of Integer = (
(10, 9, 8, 8), (12, 11, 16, 10), (14, 13, 16, 12)
);
aplocs: array[1..40, 0..6] of Integer = (
(0, 0, 0, 0, 0, 0, 0),
(6, 18, 0, 0, 0, 0, 0), (6, 22, 0, 0, 0, 0, 0),
(6, 26, 0, 0, 0, 0, 0), (6, 30, 0, 0, 0, 0, 0),
(6, 34, 0, 0, 0, 0, 0), (6, 22, 38, 0, 0, 0, 0),
(6, 24, 42, 0, 0, 0, 0), (6, 26, 46, 0, 0, 0, 0),
(6, 28, 50, 0, 0, 0, 0), (6, 30, 54, 0, 0, 0, 0),
(6, 32, 58, 0, 0, 0, 0), (6, 34, 62, 0, 0, 0, 0),
(6, 26, 46, 66, 0, 0, 0), (6, 26, 48, 70, 0, 0, 0),
(6, 26, 50, 74, 0, 0, 0), (6, 30, 54, 78, 0, 0, 0),
(6, 30, 56, 82, 0, 0, 0), (6, 30, 58, 86, 0, 0, 0),
(6, 34, 62, 90, 0, 0, 0), (6, 28, 50, 72, 94, 0, 0),
(6, 26, 50, 74, 98, 0, 0), (6, 30, 54, 78, 102, 0, 0),
(6, 28, 54, 80, 106, 0, 0), (6, 32, 58, 84, 110, 0, 0),
(6, 30, 58, 86, 114, 0, 0), (6, 34, 62, 90, 118, 0, 0),
(6, 26, 50, 74, 98, 122, 0), (6, 30, 54, 78, 102, 126, 0),
(6, 26, 52, 78, 104, 130, 0), (6, 30, 56, 82, 108, 134, 0),
(6, 34, 60, 86, 112, 138, 0), (6, 30, 58, 86, 114, 142, 0),
(6, 34, 62, 90, 118, 146, 0), (6, 30, 54, 78, 102, 126, 150),
(6, 24, 50, 76, 102, 128, 154), (6, 28, 54, 80, 106, 132, 158),
(6, 32, 58, 84, 110, 136, 162), (6, 26, 54, 82, 110, 138, 166),
(6, 30, 58, 86, 114, 142, 170)
);
var
i, j, k: Integer;
{ vertable 初期化用データ領域 }
ecls: array[1..QR_VER_MAX, 0..QR_ECL_MAX - 1] of QR_ECLEVEL;
begin
{ ecls: array[1..QR_VER_MAX, 0..QR_ECL_MAX - 1] of QR_ECLEVEL の初期化 }
ZeroMemory(@ecls, SizeOf(ecls));
for i := 1 to QR_VER_MAX do
begin
for j := 0 to (QR_ECL_MAX - 1) do
begin
for k := 0 to (QR_EM_MAX - 1) do
ecls[i][j].capacity[k] := capacities[i][j][k];
end;
end;
// version 1
ecls[1][0].datawords := 19; ecls[1][0].nrsb := 1;
ecls[1][0].rsb[0] := rsbs[0];
ecls[1][1].datawords := 16; ecls[1][1].nrsb := 1;
ecls[1][1].rsb[0] := rsbs[1];
ecls[1][2].datawords := 13; ecls[1][2].nrsb := 1;
ecls[1][2].rsb[0] := rsbs[2];
ecls[1][3].datawords := 9; ecls[1][3].nrsb := 1;
ecls[1][3].rsb[0] := rsbs[3];
// version 2
ecls[2][0].datawords := 34; ecls[2][0].nrsb := 1;
ecls[2][0].rsb[0] := rsbs[4];
ecls[2][1].datawords := 28; ecls[2][1].nrsb := 1;
ecls[2][1].rsb[0] := rsbs[5];
ecls[2][2].datawords := 22; ecls[2][2].nrsb := 1;
ecls[2][2].rsb[0] := rsbs[6];
ecls[2][3].datawords := 16; ecls[2][3].nrsb := 1;
ecls[2][3].rsb[0] := rsbs[7];
// version 3
ecls[3][0].datawords := 55; ecls[3][0].nrsb := 1;
ecls[3][0].rsb[0] := rsbs[8];
ecls[3][1].datawords := 44; ecls[3][1].nrsb := 1;
ecls[3][1].rsb[0] := rsbs[9];
ecls[3][2].datawords := 34; ecls[3][2].nrsb := 1;
ecls[3][2].rsb[0] := rsbs[10];
ecls[3][3].datawords := 26; ecls[3][3].nrsb := 1;
ecls[3][3].rsb[0] := rsbs[11];
// version 4
ecls[4][0].datawords := 80; ecls[4][0].nrsb := 1;
ecls[4][0].rsb[0] := rsbs[12];
ecls[4][1].datawords := 64; ecls[4][1].nrsb := 1;
ecls[4][1].rsb[0] := rsbs[13];
ecls[4][2].datawords := 48; ecls[4][2].nrsb := 1;
ecls[4][2].rsb[0] := rsbs[14];
ecls[4][3].datawords := 36; ecls[4][3].nrsb := 1;
ecls[4][3].rsb[0] := rsbs[15];
// version 5
ecls[5][0].datawords := 108; ecls[5][0].nrsb := 1;
ecls[5][0].rsb[0] := rsbs[16];
ecls[5][1].datawords := 86; ecls[5][1].nrsb := 1;
ecls[5][1].rsb[0] := rsbs[17];
ecls[5][2].datawords := 62; ecls[5][2].nrsb := 2;
ecls[5][2].rsb[0] := rsbs[18]; ecls[5][2].rsb[1] := rsbs[19];
ecls[5][3].datawords := 46; ecls[5][3].nrsb := 2;
ecls[5][3].rsb[0] := rsbs[20]; ecls[5][3].rsb[1] := rsbs[21];
// version 6
ecls[6][0].datawords := 136; ecls[6][0].nrsb := 1;
ecls[6][0].rsb[0] := rsbs[22];
ecls[6][1].datawords := 108; ecls[6][1].nrsb := 1;
ecls[6][1].rsb[0] := rsbs[23];
ecls[6][2].datawords := 76; ecls[6][2].nrsb := 1;
ecls[6][2].rsb[0] := rsbs[24];
ecls[6][3].datawords := 60; ecls[6][3].nrsb := 1;
ecls[6][3].rsb[0] := rsbs[25];
// version 7
ecls[7][0].datawords := 156; ecls[7][0].nrsb := 1;
ecls[7][0].rsb[0] := rsbs[26];
ecls[7][1].datawords := 124; ecls[7][1].nrsb := 1;
ecls[7][1].rsb[0] := rsbs[27];
ecls[7][2].datawords := 88; ecls[7][2].nrsb := 2;
ecls[7][2].rsb[0] := rsbs[28]; ecls[7][2].rsb[1] := rsbs[29];
ecls[7][3].datawords := 66; ecls[7][3].nrsb := 2;
ecls[7][3].rsb[0] := rsbs[30]; ecls[7][3].rsb[1] := rsbs[31];
// version 8
ecls[8][0].datawords := 194; ecls[8][0].nrsb := 1;
ecls[8][0].rsb[0] := rsbs[32];
ecls[8][1].datawords := 154; ecls[8][1].nrsb := 2;
ecls[8][1].rsb[0] := rsbs[33]; ecls[8][1].rsb[1] := rsbs[34];
ecls[8][2].datawords := 110; ecls[8][2].nrsb := 2;
ecls[8][2].rsb[0] := rsbs[35]; ecls[8][2].rsb[1] := rsbs[36];
ecls[8][3].datawords := 86; ecls[8][3].nrsb := 2;
ecls[8][3].rsb[0] := rsbs[37]; ecls[8][3].rsb[1] := rsbs[38];
// version 9
ecls[9][0].datawords := 232; ecls[9][0].nrsb := 1;
ecls[9][0].rsb[0] := rsbs[39];
ecls[9][1].datawords := 182; ecls[9][1].nrsb := 2;
ecls[9][1].rsb[0] := rsbs[40]; ecls[9][1].rsb[1] := rsbs[41];
ecls[9][2].datawords := 132; ecls[9][2].nrsb := 2;
ecls[9][2].rsb[0] := rsbs[42]; ecls[9][2].rsb[1] := rsbs[43];
ecls[9][3].datawords := 100; ecls[9][3].nrsb := 2;
ecls[9][3].rsb[0] := rsbs[44]; ecls[9][3].rsb[1] := rsbs[45];
// version 10
ecls[10][0].datawords := 274; ecls[10][0].nrsb := 2;
ecls[10][0].rsb[0] := rsbs[46]; ecls[10][0].rsb[1] := rsbs[47];
ecls[10][1].datawords := 216; ecls[10][1].nrsb := 2;
ecls[10][1].rsb[0] := rsbs[48]; ecls[10][1].rsb[1] := rsbs[49];
ecls[10][2].datawords := 154; ecls[10][2].nrsb := 2;
ecls[10][2].rsb[0] := rsbs[50]; ecls[10][2].rsb[1] := rsbs[51];
ecls[10][3].datawords := 122; ecls[10][3].nrsb := 2;
ecls[10][3].rsb[0] := rsbs[52]; ecls[10][3].rsb[1] := rsbs[53];
// version 11
ecls[11][0].datawords := 324; ecls[11][0].nrsb := 1;
ecls[11][0].rsb[0] := rsbs[54];
ecls[11][1].datawords := 254; ecls[11][1].nrsb := 2;
ecls[11][1].rsb[0] := rsbs[55]; ecls[11][1].rsb[1] := rsbs[56];
ecls[11][2].datawords := 180; ecls[11][2].nrsb := 2;
ecls[11][2].rsb[0] := rsbs[57]; ecls[11][2].rsb[1] := rsbs[58];
ecls[11][3].datawords := 140; ecls[11][3].nrsb := 2;
ecls[11][3].rsb[0] := rsbs[59]; ecls[11][3].rsb[1] := rsbs[60];
// version 12
ecls[12][0].datawords := 370; ecls[12][0].nrsb := 2;
ecls[12][0].rsb[0] := rsbs[61]; ecls[12][0].rsb[1] := rsbs[62];
ecls[12][1].datawords := 290; ecls[12][1].nrsb := 2;
ecls[12][1].rsb[0] := rsbs[63]; ecls[12][1].rsb[1] := rsbs[64];
ecls[12][2].datawords := 206; ecls[12][2].nrsb := 2;
ecls[12][2].rsb[0] := rsbs[65]; ecls[12][2].rsb[1] := rsbs[66];
ecls[12][3].datawords := 158; ecls[12][3].nrsb := 2;
ecls[12][3].rsb[0] := rsbs[67]; ecls[12][3].rsb[1] := rsbs[68];
// version 13
ecls[13][0].datawords := 428; ecls[13][0].nrsb := 1;
ecls[13][0].rsb[0] := rsbs[69];
ecls[13][1].datawords := 334; ecls[13][1].nrsb := 2;
ecls[13][1].rsb[0] := rsbs[70]; ecls[13][1].rsb[1] := rsbs[71];
ecls[13][2].datawords := 244; ecls[13][2].nrsb := 2;
ecls[13][2].rsb[0] := rsbs[72]; ecls[13][2].rsb[1] := rsbs[73];
ecls[13][3].datawords := 180; ecls[13][3].nrsb := 2;
ecls[13][3].rsb[0] := rsbs[74]; ecls[13][3].rsb[1] := rsbs[75];
// version 14
ecls[14][0].datawords := 461; ecls[14][0].nrsb := 2;
ecls[14][0].rsb[0] := rsbs[76]; ecls[14][0].rsb[1] := rsbs[77];
ecls[14][1].datawords := 365; ecls[14][1].nrsb := 2;
ecls[14][1].rsb[0] := rsbs[78]; ecls[14][1].rsb[1] := rsbs[79];
ecls[14][2].datawords := 261; ecls[14][2].nrsb := 2;
ecls[14][2].rsb[0] := rsbs[80]; ecls[14][2].rsb[1] := rsbs[81];
ecls[14][3].datawords := 197; ecls[14][3].nrsb := 2;
ecls[14][3].rsb[0] := rsbs[82]; ecls[14][3].rsb[1] := rsbs[83];
// version 15
ecls[15][0].datawords := 523; ecls[15][0].nrsb := 2;
ecls[15][0].rsb[0] := rsbs[84]; ecls[15][0].rsb[1] := rsbs[85];
ecls[15][1].datawords := 415; ecls[15][1].nrsb := 2;
ecls[15][1].rsb[0] := rsbs[86]; ecls[15][1].rsb[1] := rsbs[87];
ecls[15][2].datawords := 295; ecls[15][2].nrsb := 2;
ecls[15][2].rsb[0] := rsbs[88]; ecls[15][2].rsb[1] := rsbs[89];
ecls[15][3].datawords := 223; ecls[15][3].nrsb := 2;
ecls[15][3].rsb[0] := rsbs[90]; ecls[15][3].rsb[1] := rsbs[91];
// version 16
ecls[16][0].datawords := 589; ecls[16][0].nrsb := 2;
ecls[16][0].rsb[0] := rsbs[92]; ecls[16][0].rsb[1] := rsbs[93];
ecls[16][1].datawords := 453; ecls[16][1].nrsb := 2;
ecls[16][1].rsb[0] := rsbs[94]; ecls[16][1].rsb[1] := rsbs[95];
ecls[16][2].datawords := 325; ecls[16][2].nrsb := 2;
ecls[16][2].rsb[0] := rsbs[96]; ecls[16][2].rsb[1] := rsbs[97];
ecls[16][3].datawords := 253; ecls[16][3].nrsb := 2;
ecls[16][3].rsb[0] := rsbs[98]; ecls[16][3].rsb[1] := rsbs[99];
// version 17
ecls[17][0].datawords := 647; ecls[17][0].nrsb := 2;
ecls[17][0].rsb[0] := rsbs[100]; ecls[17][0].rsb[1] := rsbs[101];
ecls[17][1].datawords := 507; ecls[17][1].nrsb := 2;
ecls[17][1].rsb[0] := rsbs[102]; ecls[17][1].rsb[1] := rsbs[103];
ecls[17][2].datawords := 367; ecls[17][2].nrsb := 2;
ecls[17][2].rsb[0] := rsbs[104]; ecls[17][2].rsb[1] := rsbs[105];
ecls[17][3].datawords := 283; ecls[17][3].nrsb := 2;
ecls[17][3].rsb[0] := rsbs[106]; ecls[17][3].rsb[1] := rsbs[107];
// version 18
ecls[18][0].datawords := 721; ecls[18][0].nrsb := 2;
ecls[18][0].rsb[0] := rsbs[108]; ecls[18][0].rsb[1] := rsbs[109];
ecls[18][1].datawords := 563; ecls[18][1].nrsb := 2;
ecls[18][1].rsb[0] := rsbs[110]; ecls[18][1].rsb[1] := rsbs[111];
ecls[18][2].datawords := 397; ecls[18][2].nrsb := 2;
ecls[18][2].rsb[0] := rsbs[112]; ecls[18][2].rsb[1] := rsbs[113];
ecls[18][3].datawords := 313; ecls[18][3].nrsb := 2;
ecls[18][3].rsb[0] := rsbs[114]; ecls[18][3].rsb[1] := rsbs[115];
// version 19
ecls[19][0].datawords := 795; ecls[19][0].nrsb := 2;
ecls[19][0].rsb[0] := rsbs[116]; ecls[19][0].rsb[1] := rsbs[117];
ecls[19][1].datawords := 627; ecls[19][1].nrsb := 2;
ecls[19][1].rsb[0] := rsbs[118]; ecls[19][1].rsb[1] := rsbs[119];
ecls[19][2].datawords := 445; ecls[19][2].nrsb := 2;
ecls[19][2].rsb[0] := rsbs[120]; ecls[19][2].rsb[1] := rsbs[121];
ecls[19][3].datawords := 341; ecls[19][3].nrsb := 2;
ecls[19][3].rsb[0] := rsbs[122]; ecls[19][3].rsb[1] := rsbs[123];
// version 20
ecls[20][0].datawords := 861; ecls[20][0].nrsb := 2;
ecls[20][0].rsb[0] := rsbs[124]; ecls[20][0].rsb[1] := rsbs[125];
ecls[20][1].datawords := 669; ecls[20][1].nrsb := 2;
ecls[20][1].rsb[0] := rsbs[126]; ecls[20][1].rsb[1] := rsbs[127];
ecls[20][2].datawords := 485; ecls[20][2].nrsb := 2;
ecls[20][2].rsb[0] := rsbs[128]; ecls[20][2].rsb[1] := rsbs[129];
ecls[20][3].datawords := 385; ecls[20][3].nrsb := 2;
ecls[20][3].rsb[0] := rsbs[130]; ecls[20][3].rsb[1] := rsbs[131];
// version 21
ecls[21][0].datawords := 932; ecls[21][0].nrsb := 2;
ecls[21][0].rsb[0] := rsbs[132]; ecls[21][0].rsb[1] := rsbs[133];
ecls[21][1].datawords := 714; ecls[21][1].nrsb := 1;
ecls[21][1].rsb[0] := rsbs[134];
ecls[21][2].datawords := 512; ecls[21][2].nrsb := 2;
ecls[21][2].rsb[0] := rsbs[135]; ecls[21][2].rsb[1] := rsbs[136];
ecls[21][3].datawords := 406; ecls[21][3].nrsb := 2;
ecls[21][3].rsb[0] := rsbs[137]; ecls[21][3].rsb[1] := rsbs[138];
// version 22
ecls[22][0].datawords := 1006; ecls[22][0].nrsb := 2;
ecls[22][0].rsb[0] := rsbs[139]; ecls[22][0].rsb[1] := rsbs[140];
ecls[22][1].datawords := 782; ecls[22][1].nrsb := 1;
ecls[22][1].rsb[0] := rsbs[141];
ecls[22][2].datawords := 568; ecls[22][2].nrsb := 2;
ecls[22][2].rsb[0] := rsbs[142]; ecls[22][2].rsb[1] := rsbs[143];
ecls[22][3].datawords := 442; ecls[22][3].nrsb := 1;
ecls[22][3].rsb[0] := rsbs[144];
// version 23
ecls[23][0].datawords := 1094; ecls[23][0].nrsb := 2;
ecls[23][0].rsb[0] := rsbs[145]; ecls[23][0].rsb[1] := rsbs[146];
ecls[23][1].datawords := 860; ecls[23][1].nrsb := 2;
ecls[23][1].rsb[0] := rsbs[147]; ecls[23][1].rsb[1] := rsbs[148];
ecls[23][2].datawords := 614; ecls[23][2].nrsb := 2;
ecls[23][2].rsb[0] := rsbs[149]; ecls[23][2].rsb[1] := rsbs[150];
ecls[23][3].datawords := 464; ecls[23][3].nrsb := 2;
ecls[23][3].rsb[0] := rsbs[151]; ecls[23][3].rsb[1] := rsbs[152];
// version 24
ecls[24][0].datawords := 1174; ecls[24][0].nrsb := 2;
ecls[24][0].rsb[0] := rsbs[153]; ecls[24][0].rsb[1] := rsbs[154];
ecls[24][1].datawords := 914; ecls[24][1].nrsb := 2;
ecls[24][1].rsb[0] := rsbs[155]; ecls[24][1].rsb[1] := rsbs[156];
ecls[24][2].datawords := 664; ecls[24][2].nrsb := 2;
ecls[24][2].rsb[0] := rsbs[157]; ecls[24][2].rsb[1] := rsbs[158];
ecls[24][3].datawords := 514; ecls[24][3].nrsb := 2;
ecls[24][3].rsb[0] := rsbs[159]; ecls[24][3].rsb[1] := rsbs[160];
// version 25
ecls[25][0].datawords := 1276; ecls[25][0].nrsb := 2;
ecls[25][0].rsb[0] := rsbs[161]; ecls[25][0].rsb[1] := rsbs[162];
ecls[25][1].datawords := 1000; ecls[25][1].nrsb := 2;
ecls[25][1].rsb[0] := rsbs[163]; ecls[25][1].rsb[1] := rsbs[164];
ecls[25][2].datawords := 718; ecls[25][2].nrsb := 2;
ecls[25][2].rsb[0] := rsbs[165]; ecls[25][2].rsb[1] := rsbs[166];
ecls[25][3].datawords := 538; ecls[25][3].nrsb := 2;
ecls[25][3].rsb[0] := rsbs[167]; ecls[25][3].rsb[1] := rsbs[168];
// version 26
ecls[26][0].datawords := 1370; ecls[26][0].nrsb := 2;
ecls[26][0].rsb[0] := rsbs[169]; ecls[26][0].rsb[1] := rsbs[170];
ecls[26][1].datawords := 1062; ecls[26][1].nrsb := 2;
ecls[26][1].rsb[0] := rsbs[171]; ecls[26][1].rsb[1] := rsbs[172];
ecls[26][2].datawords := 754; ecls[26][2].nrsb := 2;
ecls[26][2].rsb[0] := rsbs[173]; ecls[26][2].rsb[1] := rsbs[174];
ecls[26][3].datawords := 596; ecls[26][3].nrsb := 2;
ecls[26][3].rsb[0] := rsbs[175]; ecls[26][3].rsb[1] := rsbs[176];
// version 27
ecls[27][0].datawords := 1468; ecls[27][0].nrsb := 2;
ecls[27][0].rsb[0] := rsbs[177]; ecls[27][0].rsb[1] := rsbs[178];
ecls[27][1].datawords := 1128; ecls[27][1].nrsb := 2;
ecls[27][1].rsb[0] := rsbs[179]; ecls[27][1].rsb[1] := rsbs[180];
ecls[27][2].datawords := 808; ecls[27][2].nrsb := 2;
ecls[27][2].rsb[0] := rsbs[181]; ecls[27][2].rsb[1] := rsbs[182];
ecls[27][3].datawords := 628; ecls[27][3].nrsb := 2;
ecls[27][3].rsb[0] := rsbs[183]; ecls[27][3].rsb[1] := rsbs[184];
// version 28
ecls[28][0].datawords := 1531; ecls[28][0].nrsb := 2;
ecls[28][0].rsb[0] := rsbs[185]; ecls[28][0].rsb[1] := rsbs[186];
ecls[28][1].datawords := 1193; ecls[28][1].nrsb := 2;
ecls[28][1].rsb[0] := rsbs[187]; ecls[28][1].rsb[1] := rsbs[188];
ecls[28][2].datawords := 871; ecls[28][2].nrsb := 2;
ecls[28][2].rsb[0] := rsbs[189]; ecls[28][2].rsb[1] := rsbs[190];
ecls[28][3].datawords := 661; ecls[28][3].nrsb := 2;
ecls[28][3].rsb[0] := rsbs[191]; ecls[28][3].rsb[1] := rsbs[192];
// version 29
ecls[29][0].datawords := 1631; ecls[29][0].nrsb := 2;
ecls[29][0].rsb[0] := rsbs[193]; ecls[29][0].rsb[1] := rsbs[194];
ecls[29][1].datawords := 1267; ecls[29][1].nrsb := 2;
ecls[29][1].rsb[0] := rsbs[195]; ecls[29][1].rsb[1] := rsbs[196];
ecls[29][2].datawords := 911; ecls[29][2].nrsb := 2;
ecls[29][2].rsb[0] := rsbs[197]; ecls[29][2].rsb[1] := rsbs[198];
ecls[29][3].datawords := 701; ecls[29][3].nrsb := 2;
ecls[29][3].rsb[0] := rsbs[199]; ecls[29][3].rsb[1] := rsbs[200];
// version 30
ecls[30][0].datawords := 1735; ecls[30][0].nrsb := 2;
ecls[30][0].rsb[0] := rsbs[201]; ecls[30][0].rsb[1] := rsbs[202];
ecls[30][1].datawords := 1373; ecls[30][1].nrsb := 2;
ecls[30][1].rsb[0] := rsbs[203]; ecls[30][1].rsb[1] := rsbs[204];
ecls[30][2].datawords := 985; ecls[30][2].nrsb := 2;
ecls[30][2].rsb[0] := rsbs[205]; ecls[30][2].rsb[1] := rsbs[206];
ecls[30][3].datawords := 745; ecls[30][3].nrsb := 2;
ecls[30][3].rsb[0] := rsbs[207]; ecls[30][3].rsb[1] := rsbs[208];
// version 31
ecls[31][0].datawords := 1843; ecls[31][0].nrsb := 2;
ecls[31][0].rsb[0] := rsbs[209]; ecls[31][0].rsb[1] := rsbs[210];
ecls[31][1].datawords := 1455; ecls[31][1].nrsb := 2;
ecls[31][1].rsb[0] := rsbs[211]; ecls[31][1].rsb[1] := rsbs[212];
ecls[31][2].datawords := 1033; ecls[31][2].nrsb := 2;
ecls[31][2].rsb[0] := rsbs[213]; ecls[31][2].rsb[1] := rsbs[214];
ecls[31][3].datawords := 793; ecls[31][3].nrsb := 2;
ecls[31][3].rsb[0] := rsbs[215]; ecls[31][3].rsb[1] := rsbs[216];
// version 32
ecls[32][0].datawords := 1955; ecls[32][0].nrsb := 1;
ecls[32][0].rsb[0] := rsbs[217];
ecls[32][1].datawords := 1541; ecls[32][1].nrsb := 2;
ecls[32][1].rsb[0] := rsbs[218]; ecls[32][1].rsb[1] := rsbs[219];
ecls[32][2].datawords := 1115; ecls[32][2].nrsb := 2;
ecls[32][2].rsb[0] := rsbs[220]; ecls[32][2].rsb[1] := rsbs[221];
ecls[32][3].datawords := 845; ecls[32][3].nrsb := 2;
ecls[32][3].rsb[0] := rsbs[222]; ecls[32][3].rsb[1] := rsbs[223];
// version 33
ecls[33][0].datawords := 2071; ecls[33][0].nrsb := 2;
ecls[33][0].rsb[0] := rsbs[224]; ecls[33][0].rsb[1] := rsbs[225];
ecls[33][1].datawords := 1631; ecls[33][1].nrsb := 2;
ecls[33][1].rsb[0] := rsbs[226]; ecls[33][1].rsb[1] := rsbs[227];
ecls[33][2].datawords := 1171; ecls[33][2].nrsb := 2;
ecls[33][2].rsb[0] := rsbs[228]; ecls[33][2].rsb[1] := rsbs[229];
ecls[33][3].datawords := 901; ecls[33][3].nrsb := 2;
ecls[33][3].rsb[0] := rsbs[230]; ecls[33][3].rsb[1] := rsbs[231];
// version 34
ecls[34][0].datawords := 2191; ecls[34][0].nrsb := 2;
ecls[34][0].rsb[0] := rsbs[232]; ecls[34][0].rsb[1] := rsbs[233];
ecls[34][1].datawords := 1725; ecls[34][1].nrsb := 2;
ecls[34][1].rsb[0] := rsbs[234]; ecls[34][1].rsb[1] := rsbs[235];
ecls[34][2].datawords := 1231; ecls[34][2].nrsb := 2;
ecls[34][2].rsb[0] := rsbs[236]; ecls[34][2].rsb[1] := rsbs[237];
ecls[34][3].datawords := 961; ecls[34][3].nrsb := 2;
ecls[34][3].rsb[0] := rsbs[238]; ecls[34][3].rsb[1] := rsbs[239];
// version 35
ecls[35][0].datawords := 2306; ecls[35][0].nrsb := 2;
ecls[35][0].rsb[0] := rsbs[240]; ecls[35][0].rsb[1] := rsbs[241];
ecls[35][1].datawords := 1812; ecls[35][1].nrsb := 2;
ecls[35][1].rsb[0] := rsbs[242]; ecls[35][1].rsb[1] := rsbs[243];
ecls[35][2].datawords := 1286; ecls[35][2].nrsb := 2;
ecls[35][2].rsb[0] := rsbs[244]; ecls[35][2].rsb[1] := rsbs[245];
ecls[35][3].datawords := 986; ecls[35][3].nrsb := 2;
ecls[35][3].rsb[0] := rsbs[246]; ecls[35][3].rsb[1] := rsbs[247];
// version 36
ecls[36][0].datawords := 2434; ecls[36][0].nrsb := 2;
ecls[36][0].rsb[0] := rsbs[248]; ecls[36][0].rsb[1] := rsbs[249];
ecls[36][1].datawords := 1914; ecls[36][1].nrsb := 2;
ecls[36][1].rsb[0] := rsbs[250]; ecls[36][1].rsb[1] := rsbs[251];
ecls[36][2].datawords := 1354; ecls[36][2].nrsb := 2;
ecls[36][2].rsb[0] := rsbs[252]; ecls[36][2].rsb[1] := rsbs[253];
ecls[36][3].datawords := 1054; ecls[36][3].nrsb := 2;
ecls[36][3].rsb[0] := rsbs[254]; ecls[36][3].rsb[1] := rsbs[255];
// version 37
ecls[37][0].datawords := 2566; ecls[37][0].nrsb := 2;
ecls[37][0].rsb[0] := rsbs[256]; ecls[37][0].rsb[1] := rsbs[257];
ecls[37][1].datawords := 1992; ecls[37][1].nrsb := 2;
ecls[37][1].rsb[0] := rsbs[258]; ecls[37][1].rsb[1] := rsbs[259];
ecls[37][2].datawords := 1426; ecls[37][2].nrsb := 2;
ecls[37][2].rsb[0] := rsbs[260]; ecls[37][2].rsb[1] := rsbs[261];
ecls[37][3].datawords := 1096; ecls[37][3].nrsb := 2;
ecls[37][3].rsb[0] := rsbs[262]; ecls[37][3].rsb[1] := rsbs[263];
// version 38
ecls[38][0].datawords := 2702; ecls[38][0].nrsb := 2;
ecls[38][0].rsb[0] := rsbs[264]; ecls[38][0].rsb[1] := rsbs[265];
ecls[38][1].datawords := 2102; ecls[38][1].nrsb := 2;
ecls[38][1].rsb[0] := rsbs[266]; ecls[38][1].rsb[1] := rsbs[267];
ecls[38][2].datawords := 1502; ecls[38][2].nrsb := 2;
ecls[38][2].rsb[0] := rsbs[268]; ecls[38][2].rsb[1] := rsbs[269];
ecls[38][3].datawords := 1142; ecls[38][3].nrsb := 2;
ecls[38][3].rsb[0] := rsbs[270]; ecls[38][3].rsb[1] := rsbs[271];
// version 39
ecls[39][0].datawords := 2812; ecls[39][0].nrsb := 2;
ecls[39][0].rsb[0] := rsbs[272]; ecls[39][0].rsb[1] := rsbs[273];
ecls[39][1].datawords := 2216; ecls[39][1].nrsb := 2;
ecls[39][1].rsb[0] := rsbs[274]; ecls[39][1].rsb[1] := rsbs[275];
ecls[39][2].datawords := 1582; ecls[39][2].nrsb := 2;
ecls[39][2].rsb[0] := rsbs[276]; ecls[39][2].rsb[1] := rsbs[277];
ecls[39][3].datawords := 1222; ecls[39][3].nrsb := 2;
ecls[39][3].rsb[0] := rsbs[278]; ecls[39][3].rsb[1] := rsbs[279];
// version 40
ecls[40][0].datawords := 2956; ecls[40][0].nrsb := 2;
ecls[40][0].rsb[0] := rsbs[280]; ecls[40][0].rsb[1] := rsbs[281];
ecls[40][1].datawords := 2334; ecls[40][1].nrsb := 2;
ecls[40][1].rsb[0] := rsbs[282]; ecls[40][1].rsb[1] := rsbs[283];
ecls[40][2].datawords := 1666; ecls[40][2].nrsb := 2;
ecls[40][2].rsb[0] := rsbs[284]; ecls[40][2].rsb[1] := rsbs[285];
ecls[40][3].datawords := 1276; ecls[40][3].nrsb := 2;
ecls[40][3].rsb[0] := rsbs[286]; ecls[40][3].rsb[1] := rsbs[287];
{ vertable: array[0..QR_VER_MAX] of QR_VERTABLE 型番データ表の初期化 }
ZeroMemory(@vertable, SizeOf(vertable));
k := 0;
for i := 1 to QR_VER_MAX do
begin
vertable[i].version := i;
if i in [10, 27] then
Inc(k);
for j := 0 to (QR_EM_MAX - 1) do
vertable[i].nlen[j] := nlens[k][j];
for j := 0 to (QR_ECL_MAX - 1) do
vertable[i].ecl[j] := ecls[i][j];
for j := 0 to (QR_APL_MAX - 1) do
vertable[i].aploc[j] := aplocs[i][j];
end;
// version 1
vertable[1].dimension := 21;
vertable[1].totalwords := 26;
vertable[1].remainedbits := 0;
vertable[1].aplnum := 0;
// version 2
vertable[2].dimension := 25;
vertable[2].totalwords := 44;
vertable[2].remainedbits := 7;
vertable[2].aplnum := 2;
// version 3
vertable[3].dimension := 29;
vertable[3].totalwords := 70;
vertable[3].remainedbits := 7;
vertable[3].aplnum := 2;
// version 4
vertable[4].dimension := 33;
vertable[4].totalwords := 100;
vertable[4].remainedbits := 7;
vertable[4].aplnum := 2;
// version 5
vertable[5].dimension := 37;
vertable[5].totalwords := 134;
vertable[5].remainedbits := 7;
vertable[5].aplnum := 2;
// version 6
vertable[6].dimension := 41;
vertable[6].totalwords := 172;
vertable[6].remainedbits := 7;
vertable[6].aplnum := 2;
// version 7
vertable[7].dimension := 45;
vertable[7].totalwords := 196;
vertable[7].remainedbits := 0;
vertable[7].aplnum := 3;
// version 8
vertable[8].dimension := 49;
vertable[8].totalwords := 242;
vertable[8].remainedbits := 0;
vertable[8].aplnum := 3;
// version 9
vertable[9].dimension := 53;
vertable[9].totalwords := 292;
vertable[9].remainedbits := 0;
vertable[9].aplnum := 3;
// version 10
vertable[10].dimension := 57;
vertable[10].totalwords := 346;
vertable[10].remainedbits := 0;
vertable[10].aplnum := 3;
// version 11
vertable[11].dimension := 61;
vertable[11].totalwords := 404;
vertable[11].remainedbits := 0;
vertable[11].aplnum := 3;
// version 12
vertable[12].dimension := 65;
vertable[12].totalwords := 466;
vertable[12].remainedbits := 0;
vertable[12].aplnum := 3;
// version 13
vertable[13].dimension := 69;
vertable[13].totalwords := 532;
vertable[13].remainedbits := 0;
vertable[13].aplnum := 3;
// version 14
vertable[14].dimension := 73;
vertable[14].totalwords := 581;
vertable[14].remainedbits := 3;
vertable[14].aplnum := 4;
// version 15
vertable[15].dimension := 77;
vertable[15].totalwords := 655;
vertable[15].remainedbits := 3;
vertable[15].aplnum := 4;
// version 16
vertable[16].dimension := 81;
vertable[16].totalwords := 733;
vertable[16].remainedbits := 3;
vertable[16].aplnum := 4;
// version 17
vertable[17].dimension := 85;
vertable[17].totalwords := 815;
vertable[17].remainedbits := 3;
vertable[17].aplnum := 4;
// version 18
vertable[18].dimension := 89;
vertable[18].totalwords := 901;
vertable[18].remainedbits := 3;
vertable[18].aplnum := 4;
// version 19
vertable[19].dimension := 93;
vertable[19].totalwords := 991;
vertable[19].remainedbits := 3;
vertable[19].aplnum := 4;
// version 20
vertable[20].dimension := 97;
vertable[20].totalwords := 1085;
vertable[20].remainedbits := 3;
vertable[20].aplnum := 4;
// version 21
vertable[21].dimension := 101;
vertable[21].totalwords := 1156;
vertable[21].remainedbits := 4;
vertable[21].aplnum := 5;
// version 22
vertable[22].dimension := 105;
vertable[22].totalwords := 1258;
vertable[22].remainedbits := 4;
vertable[22].aplnum := 5;
// version 23
vertable[23].dimension := 109;
vertable[23].totalwords := 1364;
vertable[23].remainedbits := 4;
vertable[23].aplnum := 5;
// version 24
vertable[24].dimension := 113;
vertable[24].totalwords := 1474;
vertable[24].remainedbits := 4;
vertable[24].aplnum := 5;
// version 25
vertable[25].dimension := 117;
vertable[25].totalwords := 1588;
vertable[25].remainedbits := 4;
vertable[25].aplnum := 5;
// version 26
vertable[26].dimension := 121;
vertable[26].totalwords := 1706;
vertable[26].remainedbits := 4;
vertable[26].aplnum := 5;
// version 27
vertable[27].dimension := 125;
vertable[27].totalwords := 1828;
vertable[27].remainedbits := 4;
vertable[27].aplnum := 5;
// version 28
vertable[28].dimension := 129;
vertable[28].totalwords := 1921;
vertable[28].remainedbits := 3;
vertable[28].aplnum := 6;
// version 29
vertable[29].dimension := 133;
vertable[29].totalwords := 2051;
vertable[29].remainedbits := 3;
vertable[29].aplnum := 6;
// version 30
vertable[30].dimension := 137;
vertable[30].totalwords := 2185;
vertable[30].remainedbits := 3;
vertable[30].aplnum := 6;
// version 31
vertable[31].dimension := 141;
vertable[31].totalwords := 2323;
vertable[31].remainedbits := 3;
vertable[31].aplnum := 6;
// version 32
vertable[32].dimension := 145;
vertable[32].totalwords := 2465;
vertable[32].remainedbits := 3;
vertable[32].aplnum := 6;
// version 33
vertable[33].dimension := 149;
vertable[33].totalwords := 2611;
vertable[33].remainedbits := 3;
vertable[33].aplnum := 6;
// version 34
vertable[34].dimension := 153;
vertable[34].totalwords := 2761;
vertable[34].remainedbits := 3;
vertable[34].aplnum := 6;
// version 35
vertable[35].dimension := 157;
vertable[35].totalwords := 2876;
vertable[35].remainedbits := 0;
vertable[35].aplnum := 7;
// version 36
vertable[36].dimension := 161;
vertable[36].totalwords := 3034;
vertable[36].remainedbits := 0;
vertable[36].aplnum := 7;
// version 37
vertable[37].dimension := 165;
vertable[37].totalwords := 3196;
vertable[37].remainedbits := 0;
vertable[37].aplnum := 7;
// version 38
vertable[38].dimension := 169;
vertable[38].totalwords := 3362;
vertable[38].remainedbits := 0;
vertable[38].aplnum := 7;
// version 39
vertable[39].dimension := 173;
vertable[39].totalwords := 3532;
vertable[39].remainedbits := 0;
vertable[39].aplnum := 7;
// version 40
vertable[40].dimension := 177;
vertable[40].totalwords := 3706;
vertable[40].remainedbits := 0;
vertable[40].aplnum := 7;
end;
function TQRCode.isBlack(i, j: Integer): Boolean;
begin
Result := ((symbol[i][j] and QR_MM_BLACK) <> 0);
end;
function TQRCode.isData(i, j: Integer): Boolean;
begin
Result := ((symbol[i][j] and QR_MM_DATA) <> 0);
end;
function TQRCode.isFunc(i, j: Integer): Boolean;
begin
Result := ((symbol[i][j] and QR_MM_FUNC) <> 0);
end;
{ ファイルをロードしてその内容をQRコードとして描画するメソッドです。}
{ ファイルのロードに成功しても常にファイルの内容をQRコードとして描画 }
{ 出来るとは限りませんので注意が必要です。}
procedure TQRCode.LoadFromFile(const FileName: string);
var
MS: TMemoryStream;
begin
if not FileExists(FileName) then
Exit;
MS := TMemoryStream.Create;
try
MS.LoadFromFile(FileName);
FLen := MS.Size;
ReallocMem(FMemory, FLen + 4);
CopyMemory(FMemory, MS.Memory, FLen);
FMemory[FLen] := Chr($00);
FMemory[FLen + 1] := Chr($00);
FMemory[FLen + 2] := Chr($00);
FMemory[FLen + 3] := Chr($00);
Data2Code;
PaintSymbolCode; // シンボルを描画する
finally
MS.Free;
end;
end;
{ メモリの内容を Count バイト分シンボルデータ領域へコピーしてQRコード }
{ として描画するメソッドです。メモリの内容を常にQRコードとして描画出来る }
{ とは限りませんので注意が必要です。}
procedure TQRCode.LoadFromMemory(const Ptr: Pointer; Count: Integer);
begin
if (Ptr = nil) or (Count <= 0) then
Exit;
FLen := Count;
ReallocMem(FMemory, FLen + 4);
CopyMemory(FMemory, Ptr, FLen);
FMemory[FLen] := Chr($00);
FMemory[FLen + 1] := Chr($00);
FMemory[FLen + 2] := Chr($00);
FMemory[FLen + 3] := Chr($00);
Data2Code;
PaintSymbolCode; // シンボルを描画する
end;
procedure TQRCode.PaintSymbol; // イベントメソッド
begin
if Assigned(FOnPaintSymbol) then
FOnPaintSymbol(Self, FWatch); // イベントハンドラの呼び出し
end;
procedure TQRCode.PaintedSymbol; // イベントメソッド
begin
if Assigned(FOnPaintedSymbol) then
FOnPaintedSymbol(Self, FWatch); // イベントハンドラの呼び出し
end;
procedure TQRCode.PaintSymbolCode;
var
x, y: Integer;
sl, st: Integer;
sll, stt: Integer;
asz, srh: Boolean;
OrgFont: TFont;
CmtUp: string;
CmtDown: string;
begin
if FSymbolEnabled = False then // 一時的にシンボル表示を停止している状態
Exit;
FSymbolDisped := False;
CheckOffset; // シンボルデータ(Memory の)を Count 個に分割する。
CheckParity; // 連結モード(Mode = qrConnect)ならバリティ値を計算する。
icount := 1; // 現在表示しているシンボルのカウンタ値(1 ~ Count)
PaintSymbol; // OnPaintSymbol イベントをここで発生
Picture.Bitmap.PixelFormat := pf32bit; // どの様な環境でもこの値に固定します。
if Picture.Bitmap.Empty = True then
begin
Picture.Bitmap.Width := Width;
Picture.Bitmap.Height := Height;
end;
sll := FSymbolLeft;
stt := FSymbolTop;
if FMatch = False then
begin
if FAngle = 90 then
begin
FSymbolLeft := stt;
FSymbolTop := Width - 1 - sll - SymbolHeightA + 1;
end
else if FAngle = 180 then
begin
FSymbolLeft := Width - 1 - sll - SymbolWidthA + 1;
FSymbolTop := Height - 1 - stt - SymbolHeightA + 1;
end
else if FAngle = 270 then
begin
FSymbolLeft := Height - 1 - stt - SymbolWidthA + 1;
FSymbolTop := sll;
end;
RotateBitmap(360 - FAngle); // -FAngle 度分回転する。
end;
asz := AutoSize;
srh := Stretch;
AutoSize := False;
Stretch := False;
OrgFont := Canvas.Font;
if FSymbolPicture = picBMP then
Canvas.Font := FComFont;
sl := FSymbolLeft;
st := FSymbolTop;
CmtUp := FCommentUp;
CmtDown := FCommentDown;
while icount <= FCount do
begin
FSymbolDisped := False;
x := (icount - 1) mod FColumn;
y := (icount - 1) div FColumn;
FSymbolLeft := sl + SymbolWidthS * x;
FSymbolTop := st + SymbolHeightS * y;
if (FCount > 1) and (FNumbering in [nbrHead, nbrTail, nbrIfVoid]) then
begin
if FNumbering = nbrHead then
begin
if CmtUp = '' then
FCommentUp := IntToStr(icount)
else
FCommentUp := IntToStr(icount) + ' ' + CmtUp;
if CmtDown = '' then
FCommentDown := IntToStr(icount)
else
FCommentDown := IntToStr(icount) + ' ' + CmtDown;
end
else if FNumbering = nbrTail then
begin
if CmtUp = '' then
FCommentUp := IntToStr(icount)
else
FCommentUp := CmtUp + ' ' + IntToStr(icount);
if CmtDown = '' then
FCommentDown := IntToStr(icount)
else
FCommentDown := CmtDown + ' ' + IntToStr(icount);
end
else if FNumbering = nbrIfVoid then
begin
if CmtUp = '' then
FCommentUp := IntToStr(icount);
if CmtDown = '' then
FCommentDown := IntToStr(icount);
end;
end;
srclen := offsets[icount] - offsets[icount - 1];
if srclen > QR_SRC_MAX then // エラー
Break;
CopyMemory(@source, @FMemory[offsets[icount - 1]], srclen);
if FSymbolPicture = picBMP then
PaintSymbolCodeB // Picture.Bitmap への描画を行なう場合
else
PaintSymbolCodeM; // Picture.Metafile への描画を行なう場合
if FSymbolDisped = False then // シンボルを表示出来なかった。
Break;
Inc(icount);
end;
FCommentDown := CmtDown;
FCommentUp := CmtUp;
FSymbolTop := stt;
FSymbolLeft := sll;
if FSymbolPicture = picBMP then
Canvas.Font := OrgFont;
Stretch := srh;
AutoSize := asz;
if (FMatch = False) or (FSymbolDisped = True) then
RotateBitmap(FAngle); // FAngle 度分回転する。
PaintedSymbol; // OnPaintedSymbol イベントをここで発生
if (FSymbolDisped = False) and (FClearOption = True) then
begin
if FSymbolDebug = False then
Clear; // 画面をクリアーする。
end;
end;
procedure TQRCode.PaintSymbolCodeB;
var
Done: Integer;
lx, ly, rx, ry: Integer;
x, y: Integer;
inBlack: Boolean;
SX, SY: Integer; // シンボルの描画開始位置
dim: Integer; // 一辺のモジュール数
CmtUpWidth, CmtUpHeight: Integer; // 上部のコメント部分の大きさ
CmtDownWidth, CmtDownHeight: Integer; // 下部のコメント部分の大きさ
PositionUp, PositionDown: Integer; // 各コメントの表示開始位置
UpLimit, DownLimit: Integer; // 各コメントの表示開始の限界位置
begin
if FEmode = -1 then
Done := qrEncodeDataWordA // 自動符号化モード
else
Done := qrEncodeDataWordM; // 符号化モードが指定されている
if Done = -1 then // 表示に失敗した
Exit;
qrComputeECWord; // 誤り訂正コード語を計算する
qrMakeCodeWord; // 最終生成コード語を求める
qrFillFunctionPattern; // シンボルに機能パターンを配置する
qrFillCodeWord; // シンボルにコード語を配置する
qrSelectMaskPattern; // シンボルにマスク処理を行う
qrFillFormatInfo; // シンボルに型情報と形式情報を配置する
{ デバッグモードの場合 }
if SymbolDebug = True then
begin
FSymbolDisped := True;
Exit;
end;
{ 各コメント部分の大きさを求める。}
if FCommentUp <> '' then
begin
CmtUpWidth := Canvas.TextWidth(FCommentUp);
CmtUpHeight := Canvas.TextHeight(FCommentUp);
end
else
begin
CmtUpWidth := 0;
CmtUpHeight := 0;
end;
if FCommentDown <> '' then
begin
CmtDownWidth := Canvas.TextWidth(FCommentDown);
CmtDownHeight := Canvas.TextHeight(FCommentDown);
end
else
begin
CmtDownWidth := 0;
CmtDownHeight := 0;
end;
{ コントロールのサイズをシンボルのサイズに合わせる場合 }
if (FMatch = True) and (icount = 1) then
begin
Width := FSymbolLeft + SymbolWidthA;
Height := FSymbolTop + SymbolHeightA;
Picture.Bitmap.Width := Width;
Picture.Bitmap.Height := Height;
end;
{ Canvas の Pen を設定する。}
Canvas.Pen.Color := FSymbolColor;
Canvas.Pen.Style := psSolid;
{ シンボルの背景を描く。}
if (FTransparent = False) and (icount = 1) then
begin
Canvas.Brush.Color := FBackColor;
Canvas.Brush.Style := bsSolid;
if FMatch = True then
Canvas.FillRect(Rect(0, 0,
FSymbolLeft + SymbolWidthA, FSymbolTop + SymbolHeightA))
else
Canvas.FillRect(Rect(FSymbolLeft, FSymbolTop,
FSymbolLeft + SymbolWidthA, FSymbolTop + SymbolHeightA));
end;
{ Canvas の Brush を設定する。}
Canvas.Brush.Color := FSymbolColor;
Canvas.Brush.Style := bsSolid;
{ シンボルを描く。}
// シンボルの描画開始位置(X座標)
SX := FSymbolLeft + FSymbolSpaceLeft + QR_DIM_SEP * FPxmag;
// シンボルの描画開始位置(Y座標)
SY := FSymbolTop + FSymbolSpaceUp + QR_DIM_SEP * FPxmag;
dim := vertable[FVersion].dimension; // 一辺のモジュール数
for y := 0 to dim - 1 do
begin
lx := 0;
ly := y * FPxmag;
ry := ly + FPxmag;
inBlack := False;
for x := 0 to dim - 1 do
begin
if (inBlack = False) and (isBlack(y, x) = True) then
begin
lx := x * FPxmag;
inBlack := True;
end
else if (inBlack = True) and (isBlack(y, x) = False) then
begin
rx := x * FPxmag;
Canvas.FillRect(Rect(SX + lx, SY + ly, SX + rx, SY + ry));
inBlack := False;
end;
end;
if inBlack = True then
begin
rx := dim * FPxmag;
Canvas.FillRect(Rect(SX + lx, SY + ly, SX + rx, SY + ry));
end;
end;
{ シンボルの上下にコメントを描く場合の処理 }
Canvas.Brush.Color := FBackColor;
Canvas.Brush.Style := bsSolid;
if FCommentUp <> '' then
begin
case FCommentUpLoc of
locLeft:
PositionUp := 0;
locCenter:
PositionUp := (FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtUpWidth) div 2;
locRight:
PositionUp := FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtUpWidth;
else
PositionUp := 0;
end;
if PositionUp < 0 then
PositionUp := 0;
UpLimit := FSymbolTop + FSymbolSpaceUp - CmtUpHeight;
y := FSymbolTop;
if y > UpLimit then
y := UpLimit;
Canvas.TextOut(FSymbolLeft + PositionUp, y, FCommentUp);
end;
if FCommentDown <> '' then
begin
case FCommentDownLoc of
locLeft:
PositionDown := 0;
locCenter:
PositionDown := (FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtDownWidth) div 2;
locRight:
PositionDown := FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtDownWidth;
else
PositionDown := 0;
end;
if PositionDown < 0 then
PositionDown := 0;
DownLimit := FSymbolTop + FSymbolSpaceUp + SymbolHeight;
y := FSymbolTop + FSymbolSpaceUp + SymbolHeight + FSymbolSpaceDown
- CmtDownHeight;
if y < DownLimit then
y := DownLimit;
Canvas.TextOut(FSymbolLeft + PositionDown, y, FCommentDown);
end;
FSymbolDisped := True;
end;
procedure TQRCode.PaintSymbolCodeM;
var
Done: Integer;
lx, ly, rx, ry: Integer;
x, y: Integer;
inBlack: Boolean;
SX, SY: Integer; // シンボルの描画開始位置
dim: Integer; // 一辺のモジュール数
CmtUpWidth, CmtUpHeight: Integer; // 上部のコメント部分の大きさ
CmtDownWidth, CmtDownHeight: Integer; // 下部のコメント部分の大きさ
PositionUp, PositionDown: Integer; // 各コメントの表示開始位置
UpLimit, DownLimit: Integer; // 各コメントの表示開始の限界位置
begin
if FEmode = -1 then
Done := qrEncodeDataWordA // 自動符号化モード
else
Done := qrEncodeDataWordM; // 符号化モードが指定されている
if Done = -1 then // 表示に失敗した
begin
if (icount > 1) and (SymbolDebug = False) then
FMfCanvas.Free; // 開放する。
Exit;
end;
qrComputeECWord; // 誤り訂正コード語を計算する
qrMakeCodeWord; // 最終生成コード語を求める
qrFillFunctionPattern; // シンボルに機能パターンを配置する
qrFillCodeWord; // シンボルにコード語を配置する
qrSelectMaskPattern; // シンボルにマスク処理を行う
qrFillFormatInfo; // シンボルに型情報と形式情報を配置する
{ デバッグモードの場合 }
if SymbolDebug = True then
begin
FSymbolDisped := True;
Exit;
end;
if icount = 1 then
begin
{ コントロールのサイズをシンボルのサイズに合わせる。}
Width := FSymbolLeft + SymbolWidthA;
Height := FSymbolTop + SymbolHeightA;
Picture.Metafile.Width := Width;
Picture.Metafile.Height := Height;
{ メタファイルのキャンバスを用意する。 }
FMfCanvas := TMetafileCanvas.Create(Picture.Metafile, GetDC(0));
{ FMfCanvas の Pen と Brush を設定する。 }
FMfCanvas.Pen.Color := FSymbolColor;
FMfCanvas.Pen.Style := psSolid;
FMfCanvas.Brush.Color := FBackColor;
FMfCanvas.Brush.Style := bsSolid;
{ シンボルの背景を描く。 }
FMfCanvas.FillRect(Rect(0, 0, Width, Height));
end;
{ シンボルを描く。}
FMfCanvas.Pen.Color := FSymbolColor;
FMfCanvas.Pen.Style := psSolid;
FMfCanvas.Brush.Color := FSymbolColor;
FMfCanvas.Brush.Style := bsSolid;
// シンボルの描画開始位置(X座標)
SX := FSymbolLeft + FSymbolSpaceLeft + QR_DIM_SEP * FPxmag;
// シンボルの描画開始位置(Y座標)
SY := FSymbolTop + FSymbolSpaceUp + QR_DIM_SEP * FPxmag;
dim := vertable[FVersion].dimension; // 一辺のモジュール数
for y := 0 to dim - 1 do
begin
lx := 0;
ly := y * FPxmag;
ry := ly + FPxmag;
inBlack := False;
for x := 0 to dim - 1 do
begin
if (inBlack = False) and (isBlack(y, x) = True) then
begin
lx := x * FPxmag;
inBlack := True;
end
else if (inBlack = True) and (isBlack(y, x) = False) then
begin
rx := x * FPxmag;
FMfCanvas.FillRect(Rect(SX + lx, SY + ly, SX + rx, SY + ry));
inBlack := False;
end;
end;
if inBlack = True then
begin
rx := dim * FPxmag;
FMfCanvas.FillRect(Rect(SX + lx, SY + ly, SX + rx, SY + ry));
end;
end;
{ シンボルの上下にコメントを描く場合の処理 }
FMfCanvas.Brush.Color := FBackColor;
FMfCanvas.Brush.Style := bsSolid;
FMfCanvas.Font := FComFont;
{ 各コメント部分の大きさを求める。}
if FCommentUp <> '' then
begin
CmtUpWidth := FMfCanvas.TextWidth(FCommentUp);
CmtUpHeight := FMfCanvas.TextHeight(FCommentUp);
end
else
begin
CmtUpWidth := 0;
CmtUpHeight := 0;
end;
if FCommentDown <> '' then
begin
CmtDownWidth := FMfCanvas.TextWidth(FCommentDown);
CmtDownHeight := FMfCanvas.TextHeight(FCommentDown);
end
else
begin
CmtDownWidth := 0;
CmtDownHeight := 0;
end;
if FCommentUp <> '' then
begin
case FCommentUpLoc of
locLeft:
PositionUp := 0;
locCenter:
PositionUp := (FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtUpWidth) div 2;
locRight:
PositionUp := FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtUpWidth;
else
PositionUp := 0;
end;
if PositionUp < 0 then
PositionUp := 0;
UpLimit := FSymbolTop + FSymbolSpaceUp - CmtUpHeight;
y := FSymbolTop;
if y > UpLimit then
y := UpLimit;
FMfCanvas.TextOut(FSymbolLeft + PositionUp, y, FCommentUp);
end;
if FCommentDown <> '' then
begin
case FCommentDownLoc of
locLeft:
PositionDown := 0;
locCenter:
PositionDown := (FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtDownWidth) div 2;
locRight:
PositionDown := FSymbolSpaceLeft + SymbolWidth + FSymbolSpaceRight
- CmtDownWidth;
else
PositionDown := 0;
end;
if PositionDown < 0 then
PositionDown := 0;
DownLimit := FSymbolTop + FSymbolSpaceUp + SymbolHeight;
y := FSymbolTop + FSymbolSpaceUp + SymbolHeight + FSymbolSpaceDown
- CmtDownHeight;
if y < DownLimit then
y := DownLimit;
FMfCanvas.TextOut(FSymbolLeft + PositionDown, y, FCommentDown);
end;
if icount = FCount then
begin
FMfCanvas.Free; // 開放して初めて描画される。
{ なぜか1ピクセル分つぶれる(どこかの線がおかしくなる)ので表示後に }
{ 元にもどす。これは、M&I さんのご指摘により修正した部分です。}
// 2001/08/05 Modify M&I
Picture.Metafile.Width := Picture.Metafile.Width + 1;
Picture.Metafile.Height := Picture.Metafile.Height + 1;
end;
FSymbolDisped := True;
end;
{ 現在クリップボードにあるテキストデータでシンボルを描画するメソッドです。}
procedure TQRCode.PasteFromClipboard;
begin
if Clipboard.HasFormat(CF_TEXT) then
Code := Clipboard.AsText;
end;
{ データコード語にビット列を追加する }
procedure TQRCode.qrAddDataBits(n: Integer; w: Longword);
begin
{ 上位ビットから順に処理(ビット単位で処理するので遅い) }
while n > 0 do
begin
Dec(n);
{ ビット追加位置にデータの下位からnビットめをORする }
dataword[dwpos] := dataword[dwpos] or (((w shr n) and 1) shl dwbit);
{ 次のビット追加位置に進む }
Dec(dwbit);
if dwbit < 0 then
begin
Inc(dwpos);
dwbit := 7;
end;
end;
end;
{ RSブロックごとに誤り訂正コード語を計算する }
procedure TQRCode.qrComputeECWord;
var
i, j, k, m: Integer;
ecwtop, dwtop, nrsb, rsbnum: Integer;
dwlen, ecwlen: Integer;
rsb: QR_RSBLOCK;
e: Integer;
begin
{ データコード語をRSブロックごとに読み出し、}
{ それぞれについて誤り訂正コード語を計算する }
{ RSブロックは長さによってnrsb種類に分かれ、}
{ それぞれの長さについてrsbnum個のブロックがある }
dwtop := 0;
ecwtop := 0;
nrsb := vertable[FVersion].ecl[FEclevel].nrsb;
for i := 0 to nrsb - 1 do
begin
{ この長さのRSブロックの個数(rsbnum)と }
{ RSブロック内のデータコード語の長さ(dwlen)、}
{ 誤り訂正コード語の長さ(ecwlen)を求める }
{ また誤り訂正コード語の長さから、使われる }
{ 誤り訂正生成多項式(gftable[ecwlen])が選ばれる }
rsb := vertable[FVersion].ecl[FEclevel].rsb[i];
rsbnum := rsb.rsbnum;
dwlen := rsb.datawords;
ecwlen := rsb.totalwords - rsb.datawords;
{ それぞれのRSブロックについてデータコード語を }
{ 誤り訂正生成多項式で除算し、結果を誤り訂正 }
{ コード語とする }
for j := 0 to rsbnum - 1 do
begin
{ RS符号計算用作業領域をクリアし、}
{ 当該RSブロックのデータコード語を }
{ 多項式係数とみなして作業領域に入れる }
{ (作業領域の大きさはRSブロックの }
{ データコード語と誤り訂正コード語の }
{ いずれか長いほうと同じだけ必要) }
ZeroMemory(@rswork, SizeOf(rswork));
CopyMemory(@rswork, @dataword[dwtop], dwlen);
{ 多項式の除算を行う }
{ (各次数についてデータコード語の初項係数から }
{ 誤り訂正生成多項式への乗数を求め、多項式 }
{ どうしの減算により剰余を求めることをくり返す) }
for k := 0 to dwlen - 1 do
begin
if rswork[0] = 0 then
begin
{ 初項係数がゼロなので、各項係数を }
{ 左にシフトして次の次数に進む }
for m := 0 to QR_RSD_MAX - 2 do
rswork[m] := rswork[m + 1];
rswork[QR_RSD_MAX - 1] := 0;
Continue;
end;
{ データコード語の初項係数(整数表現)から }
{ 誤り訂正生成多項式への乗数(べき表現)を求め、}
{ 残りの各項について剰余を求めるために }
{ データコード語の各項係数を左にシフトする }
e := fac2exp[rswork[0]];
for m := 0 to QR_RSD_MAX - 2 do
rswork[m] := rswork[m + 1];
rswork[QR_RSD_MAX - 1] := 0;
{ 誤り訂正生成多項式の各項係数に上で求めた }
{ 乗数を掛け(べき表現の加算により求める)、}
{ データコード語の各項から引いて(整数表現の }
{ 排他的論理和により求める)、剰余を求める }
for m := 0 to ecwlen - 1 do
rswork[m] := rswork[m] xor exp2fac[(gftable[ecwlen][m] + e) mod 255];
end;
{ 多項式除算の剰余を当該RSブロックの }
{ 誤り訂正コードとする }
CopyMemory(@ecword[ecwtop], @rswork, ecwlen);
{ データコード語の読み出し位置と }
{ 誤り訂正コード語の書き込み位置を }
{ 次のRSブロック開始位置に移動する }
Inc(dwtop, dwlen);
Inc(ecwtop, ecwlen);
end;
end;
end;
{ 入力データをモードに従って符号化する }
function TQRCode.qrEncodeDataWordA: Integer;
var
p: PByte;
n, m, len, mode: Integer;
w: Longword;
begin
{ エラーの場合の戻り値 }
Result := -1;
mode := -1;
{ データコード語を初期化する }
qrInitDataWord;
{ 入力データを同じ文字クラスの部分に分割して }
{ それぞれの部分について符号化する }
p := @source;
len := qrGetSourceRegion(p, Integer(@source[srclen]) - Integer(p), mode);
while len > 0 do
begin
{ pからのlenバイトを符号化モードmodeで符号化する }
{ 入力データが長すぎる }
if qrGetEncodedLength(mode, len) > qrRemainedDataBits then
Exit;
{ モード指示子(4ビット)を追加する }
qrAddDataBits(4, modeid[mode]);
{ 文字数指示子(8~16ビット)を追加する }
{ ビット数は型番とモードによって異なる }
w := Longword(len);
if mode = QR_EM_KANJI then
w := w shr 1;
qrAddDataBits(vertable[FVersion].nlen[mode], w);
{ データ本体を符号化する }
case mode of
QR_EM_NUMERIC:
begin
{ 数字モード }
{ 3桁ずつ10ビットの2進数に変換する }
{ 余りは1桁なら4ビット、2桁なら7ビットにする }
n := 0;
w := 0;
while len > 0 do
begin
Dec(len);
w := w * 10 + Longword(p^ - $30); // $30 = '0'
Inc(p);
{ 3桁たまったら10ビットで追加する }
Inc(n);
if n >= 3 then
begin
qrAddDataBits(10, w);
n := 0;
w := 0;
end;
end;
{ 余りの桁を追加する }
if n = 1 then
qrAddDataBits(4, w)
else if n = 2 then
qrAddDataBits(7, w);
end;
QR_EM_ALNUM:
begin
{ 英数字モード }
{ 2桁ずつ11ビットの2進数に変換する }
{ 余りは6ビットとして変換する }
n := 0;
w := 0;
while len > 0 do
begin
Dec(len);
w := w * 45 + Longword(Longint(alnumtable[p^]));
Inc(p);
{ 2桁たまったら11ビットで追加する }
Inc(n);
if n >= 2 then
begin
qrAddDataBits(11, w);
n := 0;
w := 0;
end;
end;
{ 余りの桁を追加する }
if n = 1 then
qrAddDataBits(6, w);
end;
QR_EM_8BIT:
begin
{ 8ビットバイトモード }
{ 各バイトを直接8ビット値として追加する }
while len > 0 do
begin
Dec(len);
qrAddDataBits(8, p^);
Inc(p);
end;
end;
QR_EM_KANJI:
begin
{ 漢字モード }
{ 2バイトを13ビットに変換して追加する }
while len >= 2 do
begin
{ 第1バイトの処理 }
{ $81~$9Fなら$81を引いて$C0を掛ける }
{ $E0~$EBなら$C1を引いて$C0を掛ける }
if (p^ >= $81) and (p^ <= $9F) then
w := (p^ - $81) * $C0
else // if (p^ >= $E0) and (p^ <= $EB)
w := (p^ - $C1) * $C0;
Inc(p);
{ 第2バイトの処理 }
{ $40を引いてから第1バイトの結果に加える }
if ((p^ >= $40) and (p^ <= $7E)) or ((p^ >= $80) and (p^ <= $FC)) then
w := w + Longword(p^ - $40)
else
{ JIS X 0208漢字の2バイトめでない }
Exit;
Inc(p);
{ 結果を13ビットの値として追加する }
qrAddDataBits(13, w);
Dec(len, 2);
end;
if len > 0 then
{ 末尾に余分なバイトがある }
Exit;
end;
end;
len := qrGetSourceRegion(p, Integer(@source[srclen]) - Integer(p), mode);
end;
{ 終端パターンを追加する(最大4ビットの0) }
n := qrRemainedDataBits;
if n < 4 then
begin
qrAddDataBits(n, 0);
n := 0;
end
else
begin
qrAddDataBits(4, 0);
Dec(n, 4);
end;
{ 末尾のデータコード語の全ビットが埋まっていなければ }
{ 余りを埋め草ビット(0)で埋める }
m := n mod 8;
if m > 0 then
begin
qrAddDataBits(m, 0);
Dec(n, m);
end;
{ 残りのデータコード語に埋め草コード語1,2を交互に埋める }
w := PADWORD1;
while n >= 8 do
begin
qrAddDataBits(8, w);
if w = PADWORD1 then
w := PADWORD2
else
w := PADWORD1;
Dec(n, 8);
end;
FEmodeR := mode;
Result := 0;
end;
{ 入力データをモードに従って符号化する }
function TQRCode.qrEncodeDataWordM: Integer;
var
i: Integer;
n, m: Integer;
w: Longword;
begin
{ エラーの場合の戻り値 }
Result := -1;
{ データコード語を初期化する }
qrInitDataWord;
{ 先頭からのsrclenバイトを符号化モードFEmodeで符号化する }
{ 入力データが長すぎる }
if qrGetEncodedLength(FEmode, srclen) > qrRemainedDataBits then
Exit;
{ モード指示子(4ビット)を追加する }
qrAddDataBits(4, modeid[FEmode]);
{ 文字数指示子(8~16ビット)を追加する }
{ ビット数は型番とモードによって異なる }
w := Longword(srclen);
if (FEmode = QR_EM_KANJI) then
w := w shr 1;
qrAddDataBits(vertable[version].nlen[FEmode], w);
{ 入力データを符号化する }
if FEmode = QR_EM_NUMERIC then
begin
{ 数字モード }
{ 3桁ずつ10ビットの2進数に変換する }
{ 余りは1桁なら4ビット、2桁なら7ビットにする }
n := 0;
w := 0;
i := 0;
while i < srclen do
begin
if (source[i] < $30) or (source[i] > $39) then // $30 = '0', $39 = '9'
Exit; // 数字でない
w := w * 10 + Longword(source[i] - $30); // $30 = '0'
{ 3桁たまったら10ビットで追加する }
Inc(n);
if n >= 3 then
begin
qrAddDataBits(10, w);
n := 0;
w := 0;
end;
Inc(i);
end;
{ 余りの桁を追加する }
if n = 1 then
qrAddDataBits(4, w)
else if n = 2 then
qrAddDataBits(7, w);
end
else if FEmode = QR_EM_ALNUM then
begin
{ 英数字モード }
{ 2桁ずつ11ビットの2進数に変換する }
{ 余りは6ビットとして変換する }
n := 0;
w := 0;
i := 0;
while i < srclen do
begin
if ((source[i] and $80) <> 0) or (alnumtable[source[i]] = -1) then
Exit; // 符号化可能な英数字でない
w := w * 45 + Longword(Longint(alnumtable[source[i]]));
{ 2桁たまったら11ビットで追加する }
Inc(n);
if n >= 2 then
begin
qrAddDataBits(11, w);
n := 0;
w := 0;
end;
Inc(i);
end;
{ 余りの桁を追加する }
if n = 1 then
qrAddDataBits(6, w);
end
else if FEmode = QR_EM_8BIT then
begin
{ 8ビットバイトモード }
{ 各バイトを直接8ビット値として追加する }
i := 0;
while i < srclen do
begin
qrAddDataBits(8, source[i]);
Inc(i);
end;
end
else if FEmode = QR_EM_KANJI then
begin
{ 漢字モード }
{ 2バイトを13ビットに変換して追加する }
i := 0;
while i < srclen - 1 do
begin
{ 第1バイトの処理 }
{ $81~$9Fなら$81を引いて$C0を掛ける }
{ $E0~$EBなら$C1を引いて$C0を掛ける }
if (source[i] >= $81) and (source[i] <= $9F) then
w := (source[i] - $81) * $C0
else if (source[i] >= $E0) and (source[i] <= $EB) then
w := (source[i] - $C1) * $C0
else
Exit; // JIS X 0208漢字の1バイトめでない
Inc(i);
{ 第2バイトの処理 }
{ 0x40を引いてから第1バイトの結果に加える }
if ((source[i] >= $40) and (source[i] <= $7E)) or
((source[i] >= $80) and (source[i] <= $FC)) then
w := w + source[i] - $40
else
Exit; // JIS X 0208漢字の2バイトめでない
Inc(i);
{ 結果を13ビットの値として追加する }
qrAddDataBits(13, w);
end;
if i < srclen then
Exit; // 末尾に余分なバイトがある
end;
{ 終端パターンを追加する(最大4ビットの0) }
n := qrRemainedDataBits;
if n < 4 then
begin
qrAddDataBits(n, 0);
n := 0;
end
else
begin
qrAddDataBits(4, 0);
Dec(n, 4);
end;
{ 末尾のデータコード語の全ビットが埋まっていなければ }
{ 余りを埋め草ビット(0)で埋める }
m := n mod 8;
if m > 0 then
begin
qrAddDataBits(m, 0);
Dec(n, m);
end;
{ 残りのデータコード語に埋め草コード語1,2を交互に埋める }
w := PADWORD1;
while n >= 8 do
begin
qrAddDataBits(8, w);
if w = PADWORD1 then
w := PADWORD2
else
w := PADWORD1;
Dec(n, 8);
end;
Result := 0;
end;
{ マスクパターンを評価し評価値を返す }
function TQRCode.qrEvaluateMaskPattern: Longint;
var
i, j, m, n, dim: Integer;
penalty: Longint;
begin
{ 評価値をpenaltyに積算する }
{ マスクは符号化領域に対してのみ行うが }
{ 評価はシンボル全体について行われる }
penalty := 0;
dim := vertable[FVersion].dimension;
{ 特徴: 同色の行/列の隣接モジュール }
{ 評価条件: モジュール数 := (5 + i) }
{ 失点: 3 + i }
for i := 0 to dim - 1 do
begin
n := 0;
for j := 0 to dim - 1 do
begin
if (j > 0) and (isBlack(i, j) = isBlack(i, j - 1)) then
Inc(n) // すぐ左と同色のモジュール、同色列の長さを1増やす
else
begin
{ 色が変わった }
{ 直前で終わった同色列の長さを評価する }
if n >= 5 then
penalty := penalty + 3 + (n - 5);
n := 1;
end;
end;
{ 列が尽きた }
{ 直前で終わった同色列の長さを評価する }
if n >= 5 then
penalty := penalty + 3 + (n - 5);
end;
for i := 0 to dim - 1 do
begin
n := 0;
for j := 0 to dim - 1 do
begin
if (j > 0) and (isBlack(j, i) = isBlack(j - 1, i)) then
Inc(n) // すぐ上と同色のモジュール、同色列の長さを1増やす
else
begin
{ 色が変わった }
{ 直前で終わった同色列の長さを評価する }
if n >= 5 then
penalty := penalty + 3 + (n - 5);
n := 1;
end;
end;
{ 列が尽きた }
{ 直前で終わった同色列の長さを評価する }
if n >= 5 then
penalty := penalty + 3 + (n - 5);
end;
{ 特徴: 同色のモジュールブロック }
{ 評価条件: ブロックサイズ := 2×2 }
{ 失点: 3 }
for i := 0 to dim - 2 do
begin
for j := 0 to dim - 2 do
begin
if (
(isBlack(i, j) = isBlack(i, j + 1)) and
(isBlack(i, j) = isBlack(i + 1, j)) and
(isBlack(i, j) = isBlack(i + 1, j + 1))
) then
Inc(penalty, 3); // 2×2の同色のブロックがあった
end;
end;
{ 特徴: 行/列における1:1:3:1:1比率(暗:明:暗:明:暗)のパターン }
{ 失点: 40 }
{ 前後はシンボル境界外か明モジュールである必要がある }
{ 2:2:6:2:2のようなパターンにも失点を与えるべきかは }
{ JIS規格からは読み取れない。ここでは与えていない }
for i := 0 to dim - 1 do
begin
for j := 0 to dim - 7 do
begin
if (
((j = 0) or (isBlack(i, j - 1) = False)) and
(isBlack(i, j + 0) = True) and
(isBlack(i, j + 1) = False) and
(isBlack(i, j + 2) = True) and
(isBlack(i, j + 3) = True) and
(isBlack(i, j + 4) = True) and
(isBlack(i, j + 5) = False) and
(isBlack(i, j + 6) = True) and
((j = dim - 7) or (isBlack(i, j + 7) = False))
) then
Inc(penalty, 40); // パターンがあった
end;
end;
for i := 0 to dim - 1 do
begin
for j := 0 to dim - 7 do
begin
if (
((j = 0) or (isBlack(j - 1, i) = False)) and
(isBlack(j + 0, i) = True) and
(isBlack(j + 1, i) = False) and
(isBlack(j + 2, i) = True) and
(isBlack(j + 3, i) = True) and
(isBlack(j + 4, i) = True) and
(isBlack(j + 5, i) = False) and
(isBlack(j + 6, i) = True) and
((j = dim - 7) or (isBlack(j + 7, i) = False))
) then
Inc(penalty, 40); // パターンがあった
end;
end;
{ 特徴: 全体に対する暗モジュールの占める割合 }
{ 評価条件: 50±(5×k)%~50±(5×(k+1))% }
{ 失点: 10×k }
m := 0;
n := 0;
for i := 0 to dim - 1 do
begin
for j := 0 to dim - 1 do
begin
Inc(m);
if isBlack(i, j) = True then
Inc(n);
end;
end;
penalty := penalty + Abs((n * 100 div m) - 50) div 5 * 10;
Result := penalty;
end;
{ シンボルに符号化されたコード語を配置する }
procedure TQRCode.qrFillCodeWord;
var
i, j: Integer;
begin
{ シンボル右下隅から開始する }
qrInitPosition;
{ コード語領域のすべてのバイトについて... }
for i := 0 to vertable[FVersion].totalwords - 1 do
begin
{ 最上位ビットから順に各ビットを調べ... }
for j := 7 downto 0 do
begin
{ そのビットが1なら黒モジュールを置く }
if (codeword[i] and (1 shl j)) <> 0 then
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_DATA;
{ 次のモジュール配置位置に移動する }
qrNextPosition;
end;
end;
end;
{ シンボルに形式情報と型番情報を配置する }
procedure TQRCode.qrFillFormatInfo;
var
i, j, dim, fmt, modulo, xpos, ypos: Integer;
v: Longint;
begin
dim := vertable[FVersion].dimension;
{ 形式情報を計算する }
{ 誤り訂正レベル2ビット(L:01, M:00, Q:11, H:10)と }
{ マスクパターン参照子3ビットからなる計5ビットに }
{ Bose-Chaudhuri-Hocquenghem(15,5)符号による }
{ 誤り訂正ビット10ビットを付加して15ビットとする }
{ (5ビットをxの次数14~10の多項式係数とみなして }
{ 多項式x^10+x^8+x^5+x^4+x^2+x+1(係数10100110111) }
{ で除算した剰余10ビットを誤り訂正ビットとする) }
{ さらにすべてのビットがゼロにならないように }
{ 101010000010010(0x5412)とXORをとる }
fmt := ((FEclevel xor 1) shl 3) or FMasktypeR;
modulo := fmt shl 10;
for i := 14 downto 10 do
begin
if (modulo and (1 shl i)) = 0 then
continue;
modulo := modulo xor ($0537 shl (i - 10));
end;
fmt := ((fmt shl 10) + modulo) xor $5412;
{ 形式情報をシンボルに配置する }
for i := 0 to 1 do
begin
for j := 0 to QR_FIN_MAX - 1 do
begin
if (fmt and (1 shl j)) = 0 then
continue;
xpos := (fmtinfopos[i][j].xpos + dim) mod dim;
ypos := (fmtinfopos[i][j].ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_BLACK;
end;
end;
xpos := (fmtblackpos.xpos + dim) mod dim;
ypos := (fmtblackpos.ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_BLACK;
{ 型番情報が有効(型番7以上)なら }
{ 型番情報をシンボルに配置する }
v := verinfo[FVersion];
if v <> -1 then
begin
for i := 0 to 1 do
begin
for j := 0 to QR_VIN_MAX - 1 do
begin
if (v and (1 shl j)) = 0 then
continue;
xpos := (verinfopos[i][j].xpos + dim) mod dim;
ypos := (verinfopos[i][j].ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_BLACK;
end;
end;
end;
end;
{ シンボルを初期化し、機能パターンを配置する }
procedure TQRCode.qrFillFunctionPattern;
var
i, j, n, dim, xpos, ypos: Integer;
x, y, x0, y0, xcenter, ycenter: Integer;
begin
{ シンボルの1辺の長さを求める }
dim := vertable[FVersion].dimension;
{ シンボル全体をクリアする }
ZeroMemory(@symbol, SizeOf(symbol));
{ 左上、右上、左下の隅に位置検出パターンを配置する }
for i := 0 to QR_DIM_FINDER - 1 do
begin
for j := 0 to QR_DIM_FINDER - 1 do
begin
symbol[i][j] := finderpattern[i][j];
symbol[i][dim - 1 - j] := finderpattern[i][j];
symbol[dim - 1 - i][j] := finderpattern[i][j];
end;
end;
{ 位置検出パターンの分離パターンを配置する }
for i := 0 to QR_DIM_FINDER do
begin
symbol[i][QR_DIM_FINDER] := QR_MM_FUNC;
symbol[QR_DIM_FINDER][i] := QR_MM_FUNC;
symbol[i][dim - 1 - QR_DIM_FINDER] := QR_MM_FUNC;
symbol[dim - 1 - QR_DIM_FINDER][i] := QR_MM_FUNC;
symbol[dim - 1 - i][QR_DIM_FINDER] := QR_MM_FUNC;
symbol[QR_DIM_FINDER][dim - 1 - i] := QR_MM_FUNC;
end;
{ 位置合わせパターンを配置する }
n := vertable[FVersion].aplnum;
for i := 0 to n - 1 do
begin
for j := 0 to n - 1 do
begin
{ 位置合わせパターンの中心と左上の座標を求める }
ycenter := vertable[FVersion].aploc[i];
xcenter := vertable[FVersion].aploc[j];
y0 := ycenter - QR_DIM_ALIGN div 2;
x0 := xcenter - QR_DIM_ALIGN div 2;
if isFunc(ycenter, xcenter) = True then
Continue; // 位置検出パターンと重なるときは配置しない
for y := 0 to QR_DIM_ALIGN - 1 do
begin
for x := 0 to QR_DIM_ALIGN - 1 do
symbol[y0 + y][x0 + x] := alignpattern[y][x];
end;
end;
end;
{ タイミングパターンを配置する }
for i := QR_DIM_FINDER to dim - 1 - QR_DIM_FINDER - 1 do
begin
symbol[i][QR_DIM_TIMING] := QR_MM_FUNC;
symbol[QR_DIM_TIMING][i] := QR_MM_FUNC;
if (i and 1) = 0 then
begin
symbol[i][QR_DIM_TIMING] := symbol[i][QR_DIM_TIMING] or QR_MM_BLACK;
symbol[QR_DIM_TIMING][i] := symbol[QR_DIM_TIMING][i] or QR_MM_BLACK;
end;
end;
{ 形式情報の領域を予約する }
for i := 0 to 1 do
begin
for j := 0 to QR_FIN_MAX - 1 do
begin
xpos := (fmtinfopos[i][j].xpos + dim) mod dim;
ypos := (fmtinfopos[i][j].ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_FUNC;
end;
end;
xpos := (fmtblackpos.xpos + dim) mod dim;
ypos := (fmtblackpos.ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_FUNC;
{ 型番情報が有効(型番7以上)なら }
{ 型番情報の領域を予約する }
if verinfo[FVersion] <> -1 then
begin
for i := 0 to 1 do
begin
for j := 0 to QR_VIN_MAX - 1 do
begin
xpos := (verinfopos[i][j].xpos + dim) mod dim;
ypos := (verinfopos[i][j].ypos + dim) mod dim;
symbol[ypos][xpos] := symbol[ypos][xpos] or QR_MM_FUNC;
end;
end;
end;
end;
{ 特定のモードでlenバイト符号化したときのビット長を返す }
function TQRCode.qrGetEncodedLength(mode: Integer; len: Integer): Integer;
var
n: Integer;
begin
{ モード指示子と文字数指示子のサイズ }
n := 4 + vertable[FVersion].nlen[mode];
{ 符号化モードごとのデータサイズ }
case mode of
QR_EM_NUMERIC:
begin
{ 数字モード: 3桁ごとに10ビット }
{ (余りは1桁なら4ビット, 2桁なら7ビット) }
n := n + (len div 3) * 10;
case (len mod 3) of
1: Inc(n, 4);
2: Inc(n, 7);
end;
end;
QR_EM_ALNUM:
begin
{ 英数字モード: 2桁ごとに11ビット }
{ (余りは1桁につき6ビット) }
n := n + (len div 2) * 11;
if (len mod 2) = 1 then
Inc(n, 6);
end;
QR_EM_8BIT:
{ 8ビットバイトモード: 1桁ごとに8ビット }
n := n + len * 8;
QR_EM_KANJI:
{ 漢字モード: 1文字(2バイト)ごとに13ビット }
n := n + (len div 2) * 13;
end;
Result := n;
end;
{ どの符号化モードで何バイト符号化すべきか求める }
function TQRCode.qrGetSourceRegion(src: PByte; len: Integer; var mode: Integer): Integer;
var
n, m, cclass, ccnext: Integer;
HasData: Boolean;
begin
Result := 0;
{ 入力データがない }
{ バイト数ゼロを返す }
if len = 0 then
Exit;
{ 残りの入力データの先頭から同じ符号化モードで }
{ 何バイトのデータを符号化すればよいか調べる }
HasData := True;
cclass := CharClassOf(src, len);
n := 0;
while HasData do
begin
{ 同じ文字クラスの文字が何バイト続くか調べる }
while (len > 0) and (CharClassOf(src, len) = cclass) do
begin
if cclass = QR_EM_KANJI then
begin
Inc(src, 2);
Dec(len, 2);
Inc(n, 2);
end
else
begin
Inc(src);
Dec(len);
Inc(n);
end;
end;
if (len = 0) then
begin
{ 入力データが尽きた }
{ 符号化モードとバイト数を返す }
mode := cclass;
Result := n;
Exit;
end;
ccnext := CharClassOf(src, len);
if (cclass = QR_EM_KANJI) or (ccnext = QR_EM_KANJI) then
begin
{ 漢字クラスからそれ以外のクラスへ、または }
{ 漢字以外のクラスから漢字クラスへ変化した }
{ 符号化モードの切り替えが必要になるので }
{ ここまでの符号化モードとバイト数を返す }
mode := cclass;
Result := n;
Exit;
end;
if cclass > ccnext then
begin
{ 下位の文字クラスに変化した(8ビット→英数字, }
{ 8ビット→数字, 英数字→数字) }
{ ここで符号化モードを切り替えたほうが有利か }
{ 切り替えず続けたほうが有利か調べる }
m := 0;
while (len > 0) and (CharClassOf(src, len) = ccnext) do
begin
Inc(src);
Dec(len);
Inc(m);
end;
if (len > 0) and (CharClassOf(src, len) = cclass) then
begin
{ 最初の文字クラスに戻った }
{ 符号化モードを切り替えてまた戻した場合と }
{ 切り替えなかった場合について }
{ 符号化ビット数の合計を比較する }
if (qrGetEncodedLength(cclass, n) + qrGetEncodedLength(ccnext, m) +
qrGetEncodedLength(cclass, 0)) < qrGetEncodedLength(cclass, n + m) then
begin
{ 切り替えたほうが短くなる }
{ 最初の文字クラスの部分について }
{ 符号化モードとバイト数を返す }
mode := cclass;
Result := n;
Exit;
end
else
begin
{ 切り替えないほうが短くなる }
{ 最初の文字クラスが続くとみなして }
{ カウントを続ける }
Inc(n, m);
Continue;
end;
end
else
begin
{ データが尽きたか別の文字クラスに変わった }
{ 符号化モードを切り替えた場合と }
{ 切り替えなかった場合について }
{ 符号化ビット数の合計を比較する }
if (qrGetEncodedLength(cclass, n) + qrGetEncodedLength(ccnext, m))
< qrGetEncodedLength(cclass, n + m) then
begin
{ 切り替えたほうが短くなる }
{ 最初の文字クラスの部分について }
{ 符号化モードとバイト数を返す }
mode := cclass;
Result := n;
Exit;
end
else
begin
{ 切り替えないほうが短くなる }
{ 最初の文字クラスが続くとみなして }
{ カウントを続ける }
Inc(n, m);
Continue;
end;
end;
end
else if cclass < ccnext then
begin
{ より上位の文字クラスに変化した(数字→英数字, }
{ 数字→8ビット, 英数字→8ビット) }
{ ここで符号化モードを切り替えたほうが有利か、}
{ 先に切り替えておいたほうが有利か調べる }
m := 0;
while (len > 0) and (CharClassOf(src, len) = ccnext) do
begin
Inc(src);
Dec(len);
Inc(m);
end;
if (qrGetEncodedLength(cclass, n) + qrGetEncodedLength(ccnext, m))
< qrGetEncodedLength(ccnext, n + m) then
begin
{ ここで切り替えたほうが短くなる }
{ 最初の文字クラスの部分について }
{ 符号化モードとバイト数を返す }
mode := cclass;
Result := n;
Exit;
end
else
begin
{ 先に切り替えておいたほうが短くなる }
{ 全体を後続の文字クラスと見なして }
{ 符号化モードとバイト数を返す }
mode := ccnext;
Result := n + m;
Exit;
end;
end;
end;
end;
{ データコード語を初期化する }
procedure TQRCode.qrInitDataWord;
begin
{ データコード語領域をゼロクリアする }
ZeroMemory(@dataword, SizeOf(dataword));
{ 追加位置をバイト0の最上位ビットにする }
dwpos := 0;
dwbit := 7;
if FMode = qrConnect then
begin
{ 連結モード指示子(4ビット)を追加する }
qrAddDataBits(4, 3); // 0011B = 3
{ シンボル列指示子(4ビット + 4ビット)を追加する }
qrAddDataBits(4, icount - 1); // 表示中のシンボルのカウンタ(1 ~ Count)
qrAddDataBits(4, FCount - 1); // シンボルの表示個数
{ パリティ値(8ビット)を追加する }
qrAddDataBits(8, FParity);
end;
end;
{ モジュール配置の初期位置と配置方向を決める }
procedure TQRCode.qrInitPosition;
begin
{ シンボルの右下隅から配置を始める }
xpos := vertable[FVersion].dimension - 1;
ypos := xpos;
{ 最初の移動方向は左向き、次に上向き }
xdir := -1;
ydir := -1;
end;
{ データコード語と誤り訂正コード語から最終的なコード語を作る }
procedure TQRCode.qrMakeCodeWord;
var
i, j, k, cwtop, pos: Integer;
dwlenmax, ecwlenmax: Integer;
dwlen, ecwlen, nrsb: Integer;
begin
{ RSブロックのサイズ種類数(nrsb)および }
{ 最大RSブロックのデータコード語数(dwlenmax)、}
{ 誤り訂正コード語数(ecwlenmax)を得る }
nrsb := vertable[FVersion].ecl[FEclevel].nrsb;
dwlenmax := vertable[FVersion].ecl[FEclevel].rsb[nrsb - 1].datawords;
ecwlenmax := vertable[FVersion].ecl[FEclevel].rsb[nrsb - 1].totalwords
- vertable[FVersion].ecl[FEclevel].rsb[nrsb - 1].datawords;
{ 各RSブロックから順にデータコード語を取り出し }
{ コード語領域(codeword)に追加する }
cwtop := 0;
for i := 0 to dwlenmax - 1 do
begin
pos := i;
{ RSブロックのサイズごとに処理を行う }
for j := 0 to nrsb - 1 do
begin
dwlen := vertable[FVersion].ecl[FEclevel].rsb[j].datawords;
{ 同じサイズのRSブロックは順に処理する }
for k := 0 to vertable[FVersion].ecl[FEclevel].rsb[j].rsbnum - 1 do
begin
{ 各RSブロックのiバイトめのデータ }
{ コード語をコード語領域に追加する }
{ (すでにすべてのデータコード語を }
{ 取り出したRSブロックは飛ばす) }
if i < dwlen then
begin
codeword[cwtop] := dataword[pos];
Inc(cwtop);
end;
{ 次のRSブロックのiバイトめに進む }
Inc(pos, dwlen);
end;
end;
end;
{ 各RSブロックから順に誤り訂正コード語を取り出し }
{ コード語領域(codeword)に追加する }
for i := 0 to ecwlenmax - 1 do
begin
pos := i;
{ RSブロックのサイズごとに処理を行う }
for j := 0 to nrsb - 1 do
begin
ecwlen := vertable[FVersion].ecl[FEclevel].rsb[j].totalwords
- vertable[FVersion].ecl[FEclevel].rsb[j].datawords;
{ 同じサイズのRSブロックは順に処理する }
for k := 0 to vertable[FVersion].ecl[FEclevel].rsb[j].rsbnum - 1 do
begin
{ 各RSブロックのiバイトめの誤り訂正 }
{ コード語をコード語領域に追加する }
{ (すでにすべての誤り訂正コード語を }
{ 取り出したRSブロックは飛ばす) }
if i < ecwlen then
begin
codeword[cwtop] := ecword[pos];
Inc(cwtop);
end;
{ 次のRSブロックのiバイトめに進む }
Inc(pos, ecwlen);
end;
end;
end;
end;
{ 次のモジュール配置位置を決める }
procedure TQRCode.qrNextPosition;
begin
repeat
{ xdir方向に1モジュール移動して }
{ xdirの向きを逆にする }
{ 右に移動したときはydir方向にも }
{ 1モジュール移動する }
Inc(xpos, xdir);
if xdir > 0 then
Inc(ypos, ydir);
xdir := -xdir;
{ y方向にシンボルをはみ出すようなら }
{ y方向ではなくx方向に2モジュール左に移動し、}
{ かつydirの向きを逆にする }
{ xposが縦のタイミングパターン上なら }
{ さらに1モジュール左に移動する }
if (ypos < 0) or (ypos >= vertable[FVersion].dimension) then
begin
Dec(ypos, ydir);
ydir := -ydir;
Dec(xpos, 2);
if xpos = QR_DIM_TIMING then
Dec(xpos);
end;
{ 新しい位置が機能パターン上なら }
{ それをよけて次の候補位置を探す }
until isFunc(ypos, xpos) = False;
end;
{ 生成されたQRコードシンボルを1個出力する }
procedure TQRCode.qrOutputSymbol;
var
i, j, ix, jx, dim, imgdim: Integer;
p: string;
q: string;
begin
{ 生成されたQRコードシンボルをモノクロ2値の }
{ アスキー形式Portable Bitmap(PBM)として出力する }
{ 縦横ともにFPxmagで指定した倍率で出力する }
dim := vertable[FVersion].dimension;
imgdim := (dim + QR_DIM_SEP * 2) * FPxmag; // シンボルの大きさ(モジュール単位)
{ 分離パターンで囲んでシンボルを書く }
for i := 0 to QR_DIM_SEP * FPxmag - 1 do
begin
p := '';
for j := 0 to imgdim - 1 do
p := p + ' 0';
FPBM.Add(p);
end;
for i := 0 to dim - 1 do
begin
for ix := 0 to FPxmag - 1 do
begin
p := '';
for j := 0 to QR_DIM_SEP * FPxmag - 1 do
p := p + ' 0';
for j := 0 to dim - 1 do
begin
if isBlack(i, j) = True then
q := ' 1'
else
q := ' 0';
for jx := 0 to FPxmag - 1 do
p := p + q;
end;
for j := 0 to QR_DIM_SEP * FPxmag - 1 do
p := p + ' 0';
FPBM.Add(p);
end;
end;
for i := 0 to QR_DIM_SEP * FPxmag - 1 do
begin
p := '';
for j := 0 to imgdim - 1 do
p := p + ' 0';
FPBM.Add(p);
end;
end;
{ QRコードシンボルを Count 個出力する }
procedure TQRCode.qrOutputSymbols;
var
Done: Integer;
dim, imgdim: Integer;
p: string;
begin
{ QRコードシンボルをモノクロ2値のアスキー形式 }
{ Portable Bitmap(PBM)として Count 個出力する }
{ 縦横ともにFPxmagで指定した倍率で出力する }
FPBM.Clear;
dim := vertable[FVersion].dimension;
imgdim := (dim + QR_DIM_SEP * 2) * FPxmag; // シンボルの大きさ(モジュール単位)
p := 'P1'; FPBM.Add(p);
if FMode = qrSingle then
p := 'Single Mode (Count = '
else if FMode = qrConnect then
p := 'Connect Mode (Count = '
else
p := 'Plus Mode (Count = ';
p := p + IntToStr(FCount) + ')';
FPBM.Add(p);
p := IntToStr(imgdim); FPBM.Add(p + ' ' + p);
icount := 1; // 現在符号化しているシンボルのカウンタ値(1 ~ Count)
while icount <= FCount do
begin
srclen := offsets[icount + 1] - offsets[icount];
if srclen > QR_SRC_MAX then // エラー
Break;
CopyMemory(@source, @FMemory[offsets[icount - 1]], srclen);
if FEmode = -1 then
Done := qrEncodeDataWordA // 自動符号化モード
else
Done := qrEncodeDataWordM; // 符号化モードが指定されている
if Done = -1 then // 符号化に失敗した
Break;
qrComputeECWord; // 誤り訂正コード語を計算する
qrMakeCodeWord; // 最終生成コード語を求める
qrFillFunctionPattern; // シンボルに機能パターンを配置する
qrFillCodeWord; // シンボルにコード語を配置する
qrSelectMaskPattern; // シンボルにマスク処理を行う
qrFillFormatInfo; // シンボルに型情報と形式情報を配置する
FPBM.Add(''); // 改行する
FPBM.Add(''); // 改行する
qrOutputSymbol; // 生成されたQRコードシンボルを1個出力する
Inc(icount);
end;
end;
{ データコード語の残りビット数を返す }
function TQRCode.qrRemainedDataBits: Integer;
begin
Result := (vertable[FVersion].ecl[FEclevel].datawords - dwpos) * 8 - (7 - dwbit);
end;
{ シンボルを最適なマスクパターンでマスクする }
procedure TQRCode.qrSelectMaskPattern;
var
mask, xmask: Integer;
penalty, xpenalty: Longint;
begin
if FMasktype >= 0 then
begin
{ マスクパターンが引数で指定されていたので }
{ そのパターンでマスクして終了 }
qrSetMaskPattern(FMasktype);
Exit;
end;
{ すべてのマスクパターンを評価する }
xmask := 0;
xpenalty := -1;
for mask := 0 to QR_MPT_MAX - 1 do
begin
{ 当該マスクパターンでマスクして評価する }
qrSetMaskPattern(mask);
penalty := qrEvaluateMaskPattern;
{ 失点がこれまでより低かったら記録する }
if (xpenalty = -1) or (penalty < xpenalty) then
begin
xmask := mask;
xpenalty := penalty;
end;
end;
{ 失点が最低のパターンでマスクする }
FMasktypeR := xmask;
qrSetMaskPattern(xmask);
end;
{ 指定した参照子のマスクパターンでシンボルをマスクする }
procedure TQRCode.qrSetMaskPattern(mask: Integer);
var
i, j, dim: Integer;
begin
dim := vertable[FVersion].dimension;
{ 以前のマスクパターンをクリアし、}
{ 符号化済みデータを初期パターンとする }
for i := 0 to dim - 1 do
begin
for j := 0 to dim - 1 do
begin
{ 機能パターン領域の印字黒モジュールは残す }
if isFunc(i, j) = True then
Continue;
{ 符号化データ領域は符号化データの }
{ 黒モジュールを印字黒モジュールにする }
if isData(i, j) = True then
symbol[i][j] := symbol[i][j] or QR_MM_BLACK
else
symbol[i][j] := symbol[i][j] and (not QR_MM_BLACK);
end;
end;
{ i行j列のモジュールについて... }
for i := 0 to dim - 1 do
begin
for j := 0 to dim - 1 do
begin
{ 機能パターン領域(および形式情報、}
{ 型番情報)はマスク対象から除外する }
if isFunc(i, j) = True then
Continue;
{ 指定された条件を満たすモジュールを反転する }
if (
((mask = 0) and ((i + j) mod 2 = 0)) or
((mask = 1) and (i mod 2 = 0)) or
((mask = 2) and (j mod 3 = 0)) or
((mask = 3) and ((i + j) mod 3 = 0)) or
((mask = 4) and (((i div 2) + (j div 3)) mod 2 = 0)) or
((mask = 5) and ((i * j) mod 2 + (i * j) mod 3 = 0)) or
((mask = 6) and (((i * j) mod 2 + (i * j) mod 3) mod 2 = 0)) or
((mask = 7) and (((i * j) mod 3 + (i + j) mod 2) mod 2 = 0))
) then
symbol[i][j] := symbol[i][j] xor QR_MM_BLACK;
end;
end;
end;
{ 現在のプロパティの値でシンボルを再描画するメソッドです。}
{ シンボルの上に何か図形を描いた後でシンボルを再描画する }
{ 場合等に使用します。}
procedure TQRCode.RepaintSymbol;
begin
PaintSymbolCode;
end;
procedure TQRCode.ReverseBitmap;
type
TTriple = packed record
B, G, R: Byte;
end;
TTripleArray = array[0..40000000] of TTriple;
PTripleArray = ^TTripleArray;
TDWordArray = array[0..100000000] of DWORD;
PDWordArray = ^TDWordArray;
var
NewBitmap: TBitmap;
x, y, i: Integer;
w, h: Integer;
BitCount: Integer;
DS: TDIBSection;
OldBitmap: TBitmap;
Bits: Byte;
Index: Integer;
SourceScanline, DestScanline: array of Pointer;
begin
if (Picture.Graphic = nil) or (FSymbolPicture <> picBMP) or
(FReverse = False) then
Exit;
OldBitmap := (Picture.Graphic as TBitmap);
OldBitmap.HandleType := bmDIB;
{ 不正なビットマップの可能性がある場合は、強制的に 24bit Color にします。}
{ この様な事は、画面の色数が 16bit Color の場合等によく発生します。}
if OldBitmap.PixelFormat in [pfDevice, pfcustom] then
OldBitmap.PixelFormat := pf24bit;
GetObject(OldBitmap.Handle, SizeOf(TDIBSection), @DS);
BitCount := DS.dsBmih.biBitCount;
if not (BitCount in [1, 4, 8, 16, 24, 32]) then
Exit;
NewBitmap := TBitmap.Create;
try
w := OldBitmap.Width;
h := OldBitmap.Height;
NewBitmap.HandleType := bmDIB;
NewBitmap.PixelFormat := OldBitmap.PixelFormat;
NewBitmap.Width := w;
NewBitmap.Height := h;
NewBitmap.Palette := CopyPalette(OldBitmap.Palette);
SetLength(SourceScanline, h);
SetLength(DestScanline, h);
for i := 0 to h - 1 do
SourceScanline[i] := OldBitmap.Scanline[i];
for i := 0 to h - 1 do
DestScanline[i] := NewBitmap.Scanline[i];
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
case Bitcount of
32: PDWordArray(DestScanline[y])^[x] :=
PDWordArray(SourceScanline[y])^[w - 1 - x];
24: PTripleArray(DestScanline[y])^[x] :=
PTripleArray(SourceScanline[y])^[w - 1 - x];
16: PWordArray(DestScanline[y])^[x] :=
PWordArray(SourceScanline[y])^[w - 1 - x];
8: PByteArray(DestScanline[y])^[x] :=
PByteArray(SourceScanline[y])^[w - 1 - x];
4:
begin
Index := w - 1 - x;
Bits := PByteArray(SourceScanline[y])^[Index div 2];
Bits := (Bits shr (4 * (1 - Index mod 2))) and $0F;
PByteArray(DestScanline[y])^[x div 2] :=
(PByteArray(DestScanline[y])^[x div 2] and
not ($F0 shr (4 * (x mod 2)))) or
(Bits shl (4 * (1 - x mod 2)));
end;
1:
begin
Index := w - 1 - x;
Bits := PByteArray(SourceScanline[y])^[Index div 8];
Bits := (Bits shr (7 - Index mod 8)) and $01;
PByteArray(DestScanline[y])^[x div 8] :=
(PByteArray(DestScanline[y])^[x div 8] and
not ($80 shr (x mod 8))) or
(Bits shl (7 - x mod 8));
end;
end;
end;
end;
//Picture.Graphic := NewBitmap;
Picture.Bitmap.width := NewBitmap.width;
Picture.Bitmap.Height := NewBitmap.Height;
Picture.Bitmap := NewBitmap;
finally
NewBitmap.Free;
end;
end;
procedure TQRCode.RotateBitmap(Degree: Integer);
type
TTriple = packed record
B, G, R: Byte;
end;
TTripleArray = array[0..40000000] of TTriple;
PTripleArray = ^TTripleArray;
TDWordArray = array[0..100000000] of DWORD;
PDWordArray = ^TDWordArray;
var
NewBitmap: TBitmap;
x, y, i: Integer;
w, h: Integer;
ww, hh: Integer;
asz, srh: Boolean;
BitCount: Integer;
DS: TDIBSection;
OldBitmap: TBitmap;
Bits: Byte;
Index: Integer;
SourceScanline, DestScanline: array of Pointer;
begin
if (Picture.Graphic = nil) or (FSymbolPicture <> picBMP) then
Exit;
if ((Degree <> 90) and (Degree <> 180) and (Degree <> 270)) then
begin
ReverseBitmap;
Exit;
end;
asz := AutoSize;
srh := Stretch;
AutoSize := False;
Stretch := False;
ww := Width;
hh := Height;
OldBitmap := (Picture.Graphic as TBitmap);
OldBitmap.HandleType := bmDIB;
{ 不正なビットマップの可能性がある場合は、強制的に 24bit Color にします。}
{ この様な事は、画面の色数が 16bit Color の場合等によく発生します。}
if OldBitmap.PixelFormat in [pfDevice, pfcustom] then
OldBitmap.PixelFormat := pf24bit;
GetObject(OldBitmap.Handle, SizeOf(TDIBSection), @DS);
BitCount := DS.dsBmih.biBitCount;
if not (BitCount in [1, 4, 8, 16, 24, 32]) then
Exit;
NewBitmap := TBitmap.Create;
try
if Degree = 180 then
begin
w := OldBitmap.Width;
h := OldBitmap.Height;
end
else
begin
w := OldBitmap.Height;
h := OldBitmap.Width;
end;
NewBitmap.HandleType := bmDIB;
NewBitmap.PixelFormat := OldBitmap.PixelFormat;
NewBitmap.Width := w;
NewBitmap.Height := h;
NewBitmap.Palette := CopyPalette(OldBitmap.Palette);
if Degree = 90 then
begin
SetLength(SourceScanline, w);
SetLength(DestScanline, h);
for i := 0 to w - 1 do
SourceScanline[i] := OldBitmap.Scanline[i];
for i := 0 to h - 1 do
DestScanline[i] := NewBitmap.Scanline[i];
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
case Bitcount of
32: PDWordArray(DestScanline[y])^[x] :=
PDWordArray(SourceScanline[w - 1 - x])^[y];
24: PTripleArray(DestScanline[y])^[x] :=
PTripleArray(SourceScanline[w - 1 - x])^[y];
16: PWordArray(DestScanline[y])^[x] :=
PWordArray(SourceScanline[w - 1 - x])^[y];
8: PByteArray(DestScanline[y])^[x] :=
PByteArray(SourceScanline[w - 1 - x])^[y];
4:
begin
Index := y;
Bits := PByteArray(SourceScanline[w - 1 - x])^[Index div 2];
Bits := (Bits shr (4 * (1 - Index mod 2))) and $0F;
PByteArray(DestScanline[y])^[x div 2] :=
(PByteArray(DestScanline[y])^[x div 2] and
not ($F0 shr (4 * (x mod 2)))) or
(Bits shl (4 * (1 - x mod 2)));
end;
1:
begin
Index := y;
Bits := PByteArray(SourceScanline[w - 1 - x])^[Index div 8];
Bits := (Bits shr (7 - Index mod 8)) and $01;
PByteArray(DestScanline[y])^[x div 8] :=
(PByteArray(DestScanline[y])^[x div 8] and
not ($80 shr (x mod 8))) or
(Bits shl (7 - x mod 8));
end;
end;
end;
end;
Width := hh;
Height := ww;
end
else if Degree = 180 then
begin
SetLength(SourceScanline, h);
SetLength(DestScanline, h);
for i := 0 to h - 1 do
SourceScanline[i] := OldBitmap.Scanline[i];
for i := 0 to h - 1 do
DestScanline[i] := NewBitmap.Scanline[i];
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
case Bitcount of
32: PDWordArray(DestScanline[y])^[x] :=
PDWordArray(SourceScanline[h - 1 - y])^[w - 1 - x];
24: PTripleArray(DestScanline[y])^[x] :=
PTripleArray(SourceScanline[h - 1 - y])^[w - 1 - x];
16: PWordArray(DestScanline[y])^[x] :=
PWordArray(SourceScanline[h - 1 - y])^[w - 1 - x];
8: PByteArray(DestScanline[y])^[x] :=
PByteArray(SourceScanline[h - 1 - y])^[w - 1 - x];
4:
begin
Index := w - 1 - x;
Bits := PByteArray(SourceScanline[h - 1 - y])^[Index div 2];
Bits := (Bits shr (4 * (1 - Index mod 2))) and $0F;
PByteArray(DestScanline[y])^[x div 2] :=
(PByteArray(DestScanline[y])^[x div 2] and
not ($F0 shr (4 * (x mod 2)))) or
(Bits shl (4 * (1 - x mod 2)));
end;
1:
begin
Index := w - 1 - x;
Bits := PByteArray(SourceScanline[h - 1 - y])^[Index div 8];
Bits := (Bits shr (7 - Index mod 8)) and $01;
PByteArray(DestScanline[y])^[x div 8] :=
(PByteArray(DestScanline[y])^[x div 8] and
not ($80 shr (x mod 8))) or
(Bits shl (7 - x mod 8));
end;
end;
end;
end;
end
else if Degree = 270 then
begin
SetLength(SourceScanline, w);
SetLength(DestScanline, h);
for i := 0 to w - 1 do
SourceScanline[i] := OldBitmap.Scanline[i];
for i := 0 to h - 1 do
DestScanline[i] := NewBitmap.Scanline[i];
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
case Bitcount of
32: PDWordArray(DestScanline[y])^[x] :=
PDWordArray(SourceScanline[x])^[h - 1 - y];
24: PTripleArray(DestScanline[y])^[x] :=
PTripleArray(SourceScanline[x])^[h - 1 - y];
16: PWordArray(DestScanline[y])^[x] :=
PWordArray(SourceScanline[x])^[h - 1 - y];
8: PByteArray(DestScanline[y])^[x] :=
PByteArray(SourceScanline[x])^[h - 1 - y];
4:
begin
Index := h - 1 - y;
Bits := PByteArray(SourceScanline[x])^[Index div 2];
Bits := (Bits shr (4 * (1 - Index mod 2))) and $0F;
PByteArray(DestScanline[y])^[x div 2] :=
(PByteArray(DestScanline[y])^[x div 2] and
not ($F0 shr (4 * (x mod 2)))) or
(Bits shl (4 * (1 - x mod 2)));
end;
1:
begin
Index := h - 1 - y;
Bits := PByteArray(SourceScanline[x])^[Index div 8];
Bits := (Bits shr (7 - Index mod 8)) and $01;
PByteArray(DestScanline[y])^[x div 8] :=
(PByteArray(DestScanline[y])^[x div 8] and
not ($80 shr (x mod 8))) or
(Bits shl (7 - x mod 8));
end;
end;
end;
end;
Width := hh;
Height := ww;
end;
//Picture.Graphic := NewBitmap;
Picture.Bitmap.width := NewBitmap.width;
Picture.Bitmap.Height := NewBitmap.Height;
Picture.Bitmap := NewBitmap;
finally
NewBitmap.Free;
end;
AutoSize := asz;
Stretch := srh;
Invalidate;
ReverseBitmap;
end;
{ 2001/07/29 Created by M&I from here }
//メタファイルコピー手続き
procedure TQRCode.SaveToClipAsWMF(const mf: TMetafile);
var
hMetafilePict: THandle;
pMFPict: PMetafilePict;
DC: THandle;
Length: Integer;
Bits: Pointer;
h: HMETAFILE;
begin
DC := GetDC(0);
try
Length := GetWinMetaFileBits(mf.Handle, 0, nil,
MM_ANISOTROPIC, DC);
//Assertは論理式が成立しない場合に例外を発生させるため
//処理を簡略化出来ることがある。
//代りに条件式でチェックすればOK
//Assert(Length > 0);
if Length > 0 then
begin
GetMem(Bits, Length);
try
GetWinMetaFileBits(mf.Handle, Length, Bits,
MM_ANISOTROPIC, DC);
h := SetMetafileBitsEx(Length, Bits);
//Assert(h <> 0);
if h <> 0 then
begin
try
hMetafilePict := GlobalAlloc(GMEM_MOVEABLE or
GMEM_DDESHARE,
Length);
//Assert(hMetafilePict <> 0);
if hMetafilePict <> 0 then
begin
try
pMFPict := GlobalLock(hMetafilePict);
pMFPict^.mm := MM_ANISOTROPIC;
pMFPict^.xExt := mf.MMWidth;
pMfPict^.yExt := mf.MMHeight;
pMfPict^.hMF := h;
GlobalUnlock(hMetafilePict);
Clipboard.SetAsHandle(CF_METAFILEPICT, hMetafilePict);
except
GlobalFree(hMetafilePict);
raise;
end;
end;
except
DeleteObject(h);
raise;
end;
end;
finally
FreeMem(Bits);
end;
end;
finally
ReleaseDC(0, DC);
end;
end;
{ シンボルデータの内容をファイルとして保存するメソッドです。必ずしも }
{ シンボルデータの内容をQRコードとして表示している場合とは限りません。}
procedure TQRCode.SaveToFile(const FileName: string);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create;
try
MS.SetSize(FLen);
CopyMemory(MS.Memory, FMemory, FLen);
MS.SaveToFile(FileName);
finally
MS.Free;
end;
end;
procedure TQRCode.SetAngle(const Value: Integer);
begin
if (Value = 0) or (Value = 90) or (Value = 180) or (Value = 270) then
begin
FAngle := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetBackColor(const Value: TColor);
begin
FBackColor := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetBinaryOperation(const Value: Boolean);
begin
if csDesigning in ComponentState then // IDE 内
Exit;
FBinaryOperation := Value;
FLen := Code2Data;
PaintSymbolCode; // シンボルを描画する
end;
procedure TQRCode.SetClearOption(const Value: Boolean);
begin
if Value = False then
FClearOption := Value
else
begin
if FClearOption = False then
begin
FClearOption := Value;
if FSymbolDisped = False then
Clear;
end;
end;
end;
{ ClipWatch プロパティを False から True にすると、クリップボードに }
{ 変化がなくとも必ず OnClipChange イベントが一回発生するので、この }
{ 最初のイベントをスキップする必要がある。}
procedure TQRCode.SetClipWatch(const Value: Boolean);
begin
if (FClipWatch = False) and (Value = True) then
FSkip := True
else
FSkip := False;
FClipWatch := Value;
UpdateClip;
end;
procedure TQRCode.SetCode(const Value: string);
begin
if csDesigning in ComponentState then // IDE 内
begin
FCode := Value;
PaintSymbolCode;
Exit;
end;
ChangeCode; // OnChangeCode イベントをここで発生
FCode := Value;
FLen := Code2Data;
PaintSymbolCode; // シンボルを描画する
ChangedCode; // OnChangedCode イベントをここで発生
end;
procedure TQRCode.SetColumn(const Value: Integer);
begin
if (Value >= 1) and (Value <= QR_PLS_MAX) then // 1 ~ 1024
begin
FColumn := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetComFont(const Value: TFont);
begin
if (Value <> nil) and (Value <> FComFont) then
begin
FComFont.Assign(Value);
PaintSymbolCode;
end;
end;
procedure TQRCode.SetCommentDown(const Value: string);
begin
FCommentDown := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetCommentDownLoc(const Value: TLocation);
begin
FCommentDownLoc := Value;
if FCommentDown <> '' then
PaintSymbolCode;
end;
procedure TQRCode.SetCommentUp(const Value: string);
begin
FCommentUp := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetCommentUpLoc(const Value: TLocation);
begin
FCommentUpLoc := Value;
if FCommentUp <> '' then
PaintSymbolCode;
end;
procedure TQRCode.SetCount(const Value: Integer);
begin
if (Value >= 1) and (Value <= QR_PLS_MAX) then // 1 ~ 1024
begin
FCount := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetData(Index: Integer; const Value: Byte);
begin
if (Index < 0) or (Index >= FLen) then
raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d',
[Index, 0, FLen - 1]);
FMemory[Index] := Char(Value);
FLen := Data2Code;
PaintSymbolCode; // シンボルを描画する
end;
procedure TQRCode.SetEclevel(const Value: Integer);
begin
if Value in [0..QR_ECL_MAX - 1] then
begin
FEclevel := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetEmode(const Value: Integer);
begin
if (Value in [0..QR_EM_MAX - 1]) or (Value = -1) then
begin
FEmode := Value;
FEmodeR := FEmode;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetMasktype(const Value: Integer);
begin
if (Value in [0..QR_MPT_MAX - 1]) or (Value = -1) then
begin
FMasktype := Value;
FMasktypeR := FMasktype;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetMatch(const Value: Boolean);
begin
FMatch := Value;
if FMatch = True then
begin
if FTransparent = True then
FTransparent := False;
end
else
FSymbolPicture := picBMP;
PaintSymbolCode;
end;
procedure TQRCode.SetMode(const Value: TQRMode);
begin
if Value = qrSingle then
FCount := 1
else if Value = qrConnect then
begin
if FCount < 2 then
FCount := 2
else if FCount > QR_CNN_MAX then
FCount := QR_CNN_MAX;
end
else if Value = qrPlus then
begin
if FCount < 2 then
FCount := 2
else if FCount > QR_PLS_MAX then
FCount := QR_PLS_MAX;
end
else
Exit;
FMode := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetNumbering(const Value: TNumbering);
begin
if Value in [nbrNone, nbrHead, nbrTail, nbrIfVoid] then
begin
FNumbering := Value;
if FCount > 1 then
PaintSymbolCode;
end;
end;
procedure TQRCode.SetOnClipChange(const Value: TNotifyEvent);
begin
FOnClipChange := Value;
UpdateClip;
end;
procedure TQRCode.SetPxmag(const Value: Integer);
begin
if Value in [1..10] then
begin
FPxmag := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetReverse(const Value: Boolean);
begin
FReverse := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolColor(const Value: TColor);
begin
FSymbolColor := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolDebug(const Value: Boolean);
begin
FSymbolDebug := Value
end;
procedure TQRCode.SetSymbolEnabled(const Value: Boolean);
begin
if FSymbolEnabled <> Value then
begin
FSymbolEnabled := Value;
if FSymbolEnabled = True then
PaintSymbolCode;
end;
end;
procedure TQRCode.SetSymbolLeft(const Value: Integer);
begin
FSymbolLeft := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolPicture(const Value: TPictures);
begin
if FMatch = False then
FSymbolPicture := picBMP
else
begin
FSymbolPicture := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.SetSymbolSpaceDown(const Value: Integer);
begin
FSymbolSpaceDown := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolSpaceLeft(const Value: Integer);
begin
FSymbolSpaceLeft := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolSpaceRight(const Value: Integer);
begin
FSymbolSpaceRight := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolSpaceUp(const Value: Integer);
begin
FSymbolSpaceUp := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetSymbolTop(const Value: Integer);
begin
FSymbolTop := Value;
PaintSymbolCode;
end;
procedure TQRCode.SetTransparent(const Value: Boolean);
begin
FTransparent := Value;
if FTransparent = True then
begin
if FMatch = True then
FMatch := False;
FSymbolPicture := picBMP;
end;
PaintSymbolCode;
end;
procedure TQRCode.SetVersion(const Value: Integer);
begin
if Value in [1..QR_VER_MAX] then
begin
FVersion := Value;
PaintSymbolCode;
end;
end;
procedure TQRCode.UpdateClip;
begin
if FRegistered = FClipWatch and Assigned(FOnClipChange) then
Exit;
FRegistered := not FRegistered;
if FRegistered then
FNextWindowHandle := SetClipboardViewer(FWindowHandle)
else
ChangeClipboardChain(FWindowHandle, FNextWindowHandle);
end;
procedure TQRCode.WndClipProc(var Message: TMessage);
begin
with Message do
case Msg of
WM_CHANGECBCHAIN:
try
with TWMChangeCBChain(Message) do
if Remove = FNextWindowHandle then
FNextWindowHandle := Next
else if FNextWindowHandle <> 0 then
SendMessage(FNextWindowHandle, Msg, wParam, lParam);
except
Application.HandleException(Self);
end;
WM_DRAWCLIPBOARD:
try
ClipChange; // OnClipChange イベントをここで発生
SendMessage(FNextWindowHandle, Msg, wParam, lParam);
except
Application.HandleException(Self);
end;
else
Result := DefWindowProc(FWindowHandle, Msg, wParam, lParam);
end;
end;
end.
|
unit cCadSetores;
interface
uses System.Classes,Vcl.Controls,
Vcl.ExtCtrls,Vcl.Dialogs,FireDAC.Comp.Client,System.SysUtils;//LISTA DE UNITS
type
TSetor = class
private
//VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_setor:Integer;
F_Setor:string;
function getcodigo: integer;
function getDescricao: string;
procedure setcodigo(const Value: integer);
procedure setDescricao(const Value: string);
public
constructor Create(aConexao:TFDConnection); //CONSTRUTOR DA CLASSE
destructor Destroy;override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir:Boolean;
function Atualizar:Boolean;
function Apagar:Boolean;
function Selecionar(id:integer):boolean;
//DE SOBRESCREVER
//VARIÁVEIS PUBLICAS QUE PODE SER TRABALHADA FORA DA CLASSE
published
//VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
//PARA FORNECER INFORMAÇÕESD EM RUMTIME
property codigo:integer read getcodigo write setcodigo;
property descricao:string read getDescricao write setDescricao;
end;
implementation
{ TSetor }
{$region 'Constructor and Destructor'}
constructor TSetor.Create;
begin
ConexaoDB:=aConexao;
end;
destructor TSetor.Destroy;
begin
inherited;
end;
{$endregion}
{$region 'CRUD'}
function TSetor.Apagar: Boolean;
var Qry:TFDQuery;
begin
if MessageDlg('Apagar o Registro: '+#13+#13+
'Código: '+IntToStr(F_cod_setor)+#13+
'Descrição: '+F_Setor,mtConfirmation,[mbYes,mbNo],0)=mrNO then begin
Result:=false;
Abort;
end;
Try
Result:=True;
Qry:=TFDQuery.Create(nil);
Qry.Connection:= ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_setor WHERE cod_setor=:cod_setor; ');
Qry.ParamByName('cod_setor').AsInteger:=F_cod_setor;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TSetor.Atualizar: Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:= ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE igreja.tb_setor ' +
' SET setor=:setor WHERE cod_setor=:cod_setor; ');
Qry.ParamByName('setor').AsString:=F_Setor;
Qry.ParamByName('cod_setor').AsInteger:=F_cod_setor;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TSetor.Inserir: Boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:= ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_setor (setor,cod_igreja) VALUES(:descricao,1);');
Qry.ParamByName('descricao').AsString:=F_Setor;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TSetor.Selecionar(id: integer): boolean;
var Qry:TFDQuery;
begin
try
Result:=true;
Qry:=TFDQuery.Create(nil);
Qry.Connection:= ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_setor, setor, cod_igreja, '+
'cod_congregacao, data_cadastro, usuario_cadastro FROM tb_setor where cod_setor = :cod_setor ');
Qry.ParamByName('cod_setor').AsInteger:=id;
try
Qry.Open;
Self.F_cod_setor:=Qry.FieldByName('cod_setor').AsInteger;
Self.F_Setor:= Qry.FieldByName('setor').AsString;
Except
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$endregion}
function TSetor.getcodigo: integer;
begin
Result:= Self.F_cod_setor;
end;
function TSetor.getDescricao: string;
begin
Result:= Self.F_Setor;
end;
procedure TSetor.setcodigo(const Value: integer);
begin
Self.F_cod_setor:= value;
end;
procedure TSetor.setDescricao(const Value: string);
begin
Self.F_Setor:=value;
end;
end.
|
unit UFrameKP;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons, UTreeItem, IniFiles, UFrameMain;
type
TItemKP = class;
TFrameKP = class(TFrame)
GroupBox1: TGroupBox;
Panel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
GroupBox2: TGroupBox;
edName: TEdit;
edAddress: TEdit;
edPhoneNum: TEdit;
edInterval: TEdit;
cbDialRequest: TCheckBox;
BtnKvit: TButton;
BtnChange: TButton;
Memo: TMemo;
Label5: TLabel;
stLastConnect: TStaticText;
procedure BtnChangeClick(Sender: TObject);
procedure cbDialRequestClick(Sender: TObject);
procedure BtnKvitClick(Sender: TObject);
private
{ Private declarations }
KP:TItemKP;
public
{ Public declarations }
end;
TItemKP = class(TTreeItem)
private
function GetAutoDialRequest: Boolean;
procedure SetManualDialRequest(const Value: Boolean);
procedure SetLastDataTime(const Value: TDateTime);
function GetManualDialRequest: Boolean;
function GetPeriod: TDateTime;
function DataLagBigger(Secs:Cardinal):Boolean;
function GetNeedConnection: Boolean;
protected
Main:TItemMain;
FKP:TFrameKP;
// Persistent variables
FName:String;
FAddress:Byte;
FDialInterval:Integer;
FPhone:String;
FLastDataTime:TDateTime;
Port:Integer;
Analogs:TList;
//
FManualDialRequest:Boolean;
FEvents:String;
DialPause:Integer;
AlarmTimer:Integer;
procedure RefreshFrame;
public
function Enter:TFrame;override;
function Leave:Boolean;override;
function Validate:Boolean;override;
constructor Load(Main:TItemMain; Ini,Cfg:TIniFile; const Section:String);
procedure SaveCfg(Cfg:TIniFile);override;
procedure TimerProc;override;
destructor Destroy;override;
procedure PauseDial;
procedure AddEvent(Time:TDateTime; Event:String);
procedure handleADCService(const DataI:String);
public
Alarm:Boolean;
property ManualDialRequest:Boolean read GetManualDialRequest write SetManualDialRequest;
property AutoDialRequest:Boolean read GetAutoDialRequest;
property LastDataTime:TDateTime read FLastDataTime write SetLastDataTime;
property Phone:String read FPhone;
property Name:String read FName;
property Address:Byte read FAddress;
property Period:TDateTime read GetPeriod;
property NeedConnection:Boolean read GetNeedConnection;
end;
const
ADCSampleSize=2;
implementation
uses UFormMain, UFrameAnalog, Misc, DataTypes, UServices, UTime;
{$R *.DFM}
procedure TFrameKP.BtnChangeClick(Sender: TObject);
begin
KP.ChangeData(BtnChange,Panel);
end;
{ TItemKP }
function TItemKP.Enter: TFrame;
begin
FKP:=TFrameKP.Create(FormMain);
FKP.KP:=Self;
FKP.Name:='';
FKP.edName.Text:=Name;
FKP.edAddress.Text:=IntToStr(Address);
FKP.edPhoneNum.Text:=Phone;
FKP.edInterval.Text:=IntToStr(FDialInterval);
FKP.cbDialRequest.Checked:=FManualDialRequest;
RefreshFrame;
FKP.Memo.Text:=FEvents;
Result:=FKP;
end;
function TItemKP.Leave: Boolean;
begin
FKP.Free; FKP:=nil;
Result:=True;
end;
constructor TItemKP.Load(Main:TItemMain; Ini,Cfg: TIniFile; const Section: String);
var
i,Cnt:Integer;
S:String;
begin
inherited;
Self.Main:=Main;
Self.Section:=Section;
Node:=FormMain.TreeView.Items.AddChildObject(Main.Node,Section,Self);
FName:=Ini.ReadString(Section,'Name',Section);
FAddress:=Ini.ReadInteger(Section,'Address',0);
FPhone:=Ini.ReadString(Section,'Phone','');
Port:=Ini.ReadInteger(Section,'Port',22000+Address);
FDialInterval:=Cfg.ReadInteger(Section,'DialInterval',240);
LastDataTime:=Cfg.ReadDateTime(Section,'LastDataTime',0);
Cnt:=Ini.ReadInteger(Section,'ADCCount',0);
Analogs:=TList.Create;
for i:=1 to Cnt do begin
S:=Ini.ReadString(Section,Format('ADC%.2d',[i]),'');
if S<>''
then Analogs.Add(TItemAnalog.Load(Self,Ini,Cfg,S));
end;
end;
procedure TItemKP.TimerProc;
var
i:Integer;
begin
if DialPause>0 then Dec(DialPause);
for i:=0 to Analogs.Count-1 do TItemAnalog(Analogs[i]).TimerProc;
if Alarm then begin
if AlarmTimer=0 then begin
FormMain.Visible:=True;
SetForegroundWindow(FormMain.Handle);
FormMain.TreeView.Selected:=Node;
if FKP<>nil then FKP.BtnKvit.SetFocus;
MessageBeep(MB_OK);
AlarmTimer:=5;
end
else Dec(AlarmTimer);
end;
end;
function TItemKP.Validate: Boolean;
var
Name_,Phone_:String;
Addr,Interv:Double;
begin
try
Name_:=FKP.edName.Text;
CheckMinMax(Addr,0,255,FKP.edAddress);
Phone_:=FKP.edPhoneNum.Text;
CheckMinMax(Interv,0,240,FKP.edInterval);
FName:=Name_;
FAddress:=Trunc(Addr);
FPhone:=Phone_;
FDialInterval:=Trunc(Interv);
Result:=True;
except
Result:=False;
end;
end;
procedure TItemKP.SaveCfg(Cfg: TIniFile);
var
i:Integer;
begin
// Ini.WriteString(Section,'Name',Name);
// Ini.WriteInteger(Section,'Address',FAddress);
// Ini.WriteString(Section,'Phone',FPhone);
Cfg.WriteInteger(Section,'DialInterval',FDialInterval);
Cfg.WriteDateTime(Section,'LastDataTime',LastDataTime);
for i:=0 to Analogs.Count-1
do TItemAnalog(Analogs[i]).SaveCfg(Cfg);
end;
destructor TItemKP.Destroy;
var
i:Integer;
begin
for i:=0 to Analogs.Count-1 do TItemAnalog(Analogs[i]).Free;
Analogs.Free;
inherited;
end;
function TItemKP.GetAutoDialRequest: Boolean;
begin
Result:=(FDialInterval>0) and (DialPause=0) and DataLagBigger(FDialInterval*60);
end;
procedure TItemKP.SetManualDialRequest(const Value: Boolean);
begin
if FManualDialRequest=Value then exit;
FManualDialRequest := Value;
DialPause:=0;
if FKP<>nil then FKP.cbDialRequest.Checked:=Value;
end;
procedure TFrameKP.cbDialRequestClick(Sender: TObject);
begin
KP.ManualDialRequest:=cbDialRequest.Checked;
end;
procedure TItemKP.SetLastDataTime(const Value: TDateTime);
begin
FLastDataTime := Value;
if FKP<>nil then RefreshFrame;
end;
procedure TItemKP.RefreshFrame;
begin
FKP.stLastConnect.Caption:=DateTimeToStr(LastDataTime);
end;
procedure TItemKP.AddEvent(Time:TDateTime; Event: String);
begin
Event:=LogMsg(Time,Event);
if FKP<>nil then begin
FKP.Memo.SelStart:=0;
FKP.Memo.SelText:=Event;
end;
FEvents:=Event+FEvents;
WriteToLog(Event);
end;
procedure TFrameKP.BtnKvitClick(Sender: TObject);
begin
KP.Alarm:=False;
KP.AddEvent(GetMyTime,'***** ÊÂÈÒÈÐÎÂÀÍÎ');
end;
procedure TItemKP.PauseDial;
begin
DialPause:=Main.RedialInterval;
end;
function TItemKP.GetManualDialRequest: Boolean;
begin
Result:=FManualDialRequest and (DialPause=0);
end;
procedure TItemKP.handleADCService(const DataI: String);
var
ID:^TADCServiceInData;
IA:TItemAnalog;
Cnt,k:Integer;
Time,MaxTime:TDateTime;
ST:TSystemTime;
CharBuf:array[0..15] of Char;
Buf:TSclRec absolute CharBuf;
begin
ID:=@(DataI[1]);
if ID.SensNum>=Analogs.Count then exit;
IA:=TItemAnalog(Analogs[ID.SensNum]);
Buf.Number:=IA.NetNumber;
Cnt:=(Length(DataI)-SizeOf(ID.SensNum)-SizeOf(ID.Time)) div ADCSampleSize;
MaxTime:=GetMyTime;
// Update LastDataTime
Time:=ID.Time*dtLLTickPeriod+(Cnt-1)*Period;
if Time>MaxTime then Time:=MaxTime;
if LastDataTime<Time then LastDataTime:=Time;
// Send data cycle
FormMain.NMUDP.RemotePort:=Port;
for k:=0 to Cnt-1 do begin
Time:=ID.Time*dtLLTickPeriod+k*Period;
if Time>MaxTime then break;
DateTimeToSystemTime(Time,ST);
with Buf.Time do begin
Year:=ST.wYear-1900;
Month:=ST.wMonth;
Day:=ST.wDay;
Hour:=ST.wHour;
Min:=ST.wMinute;
Sec:=ST.wSecond;
Sec100:=Trunc(ST.wMilliseconds*0.1);
end;
IA.GetP(ID.Data[k],Buf.P);
// Îòñûëêà
FormMain.NMUDP.SendBuffer(CharBuf,SizeOf(CharBuf));
end;
end;
function TItemKP.GetPeriod: TDateTime;
begin
Result:=Main.Period;
end;
function TItemKP.DataLagBigger(Secs: Cardinal): Boolean;
const
SecToTimeCoeff = 1/(24*60*60);
begin
Result := LastDataTime+Secs*SecToTimeCoeff < GetMyTime;
end;
function TItemKP.GetNeedConnection: Boolean;
begin
Result := DataLagBigger(10);
end;
end.
|
unit frSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Themes,
ADC.Types, ADC.Common, Vcl.Buttons, Vcl.ExtCtrls;
type
TPanel = class(Vcl.ExtCtrls.TPanel)
private
procedure WMPaint(var Msg: TMessage); message WM_PAINT;
end;
type
TBitBtn = class(Vcl.Buttons.TBitBtn)
private
procedure WMPaint(var Msg: TMessage); message WM_PAINT;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
end;
type
TComboBox = class(Vcl.StdCtrls.TComboBox)
private
procedure CN_DrawItem(var Message : TWMDrawItem); message CN_DRAWITEM;
procedure WMPaint(var Msg: TMessage); message WM_PAINT;
procedure WMNCPaint(var Msg: TMessage); message WM_NCPAINT;
end;
type
TFrame_Search = class(TFrame)
Edit_SearchPattern: TEdit;
ComboBox_SearchOption: TComboBox;
Button_ClearPattern: TBitBtn;
Panel_Search: TPanel;
procedure ComboBox_SearchOptionDropDown(Sender: TObject);
procedure ComboBox_SearchOptionDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure ComboBox_SearchOptionSelect(Sender: TObject);
procedure FrameResize(Sender: TObject);
procedure Button_ClearPatternClick(Sender: TObject);
procedure Edit_SearchPatternChange(Sender: TObject);
private
{ Private declarations }
FComboBoxMargin: Byte;
FComboBoxWndProc: TWndMethod;
procedure ComboBoxWndProc(var Message: TMessage);
procedure SetComboBoxWidth;
procedure SetComboBoxDropDownWidth;
procedure SetFilterOption(Value: Byte);
function GetFilterOption: Byte;
public
{ Public declarations }
procedure InitControls;
property FilterOption: Byte read GetFilterOption write SetFilterOption;
end;
implementation
{$R *.dfm}
{ TComboBox }
procedure TComboBox.CN_DrawItem(var Message: TWMDrawItem);
begin
with Message do
DrawItemStruct.itemState := DrawItemStruct.itemState and not ODS_FOCUS;
inherited;
end;
procedure TComboBox.WMNCPaint(var Msg: TMessage);
var
hC: HDC;
C: TCanvas;
R: TRect;
begin
hC := GetWindowDC(Handle);
SaveDC(hC);
try
C:= TCanvas.Create;
try
C.Handle := hC;
C.Lock;
R := Rect(0, 0, Width, Height);
with C.Brush do
begin
Color := Self.Color;
Style := bsSolid;
end;
C.FrameRect(R);
InflateRect(R, -1, -1);
C.FrameRect(R);
finally
C.Unlock;
C.free;
end;
finally
RestoreDC(hC, -1);
ReleaseDC(Handle, hC);
end;
end;
procedure TComboBox.WMPaint(var Msg: TMessage);
var
C: TControlCanvas;
R: TRect;
begin
inherited;
C := TControlCanvas.Create;
try
C.Control := Self;
with C do
begin
{ Рисуем новую рамку }
Brush.Color := StyleServices.GetStyleColor(scBorder);
R := ClientRect;
FrameRect(R);
{ Левую сторону перерисовываем как разделитель }
Pen.Color := clWindow;
MoveTo(0, 1);
LineTo(0, R.Height - 1);
Pen.Color := clSilver;
MoveTo(0, 3);
LineTo(0, R.Height - 3);
end;
finally
C.Free;
end;
end;
procedure TFrame_Search.Button_ClearPatternClick(Sender: TObject);
begin
Edit_SearchPattern.Clear;
Edit_SearchPattern.SetFocus;
end;
procedure TFrame_Search.ComboBoxWndProc(var Message: TMessage);
var
cbR: TRect;
lbR: TRect;
begin
if Message.Msg = WM_CTLCOLORLISTBOX then
begin
GetWindowRect(ComboBox_SearchOption.Handle, cbR);
GetWindowRect(Message.LParam, lbR);
if cbR.Right <> lbR.Right then MoveWindow(
Message.LParam,
lbR.Left - (lbR.Right - cbR.Right),
lbR.Top,
lbR.Right - lbR.Left,
lbR.Bottom - lbR.Top,
True
);
end
else FComboBoxWndProc(Message);
end;
procedure TFrame_Search.ComboBox_SearchOptionDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
ItemText: string;
C: TCanvas;
DC: HDC;
DrawRect: TRect;
TextWidth: Integer;
begin
ItemText := ComboBox_SearchOption.Items[Index];
DC := ComboBox_SearchOption.Canvas.Handle;
C := ComboBox_SearchOption.Canvas;
C.Font.Color := clGray;
C.FillRect(Rect);
if odSelected in State then
begin
if odComboBoxEdit in State then
begin
C.Brush.Color := StyleServices.GetStyleColor(scComboBox);
C.FillRect(Rect);
{ ВАЖНО: Вызываем C.DrawFocusRect(Rect) дважды с разным }
{ цветом кисти. Иначе цвет FocusRect всегда темный черный }
C.Brush.Color := clBlack;
C.DrawFocusRect(Rect);
C.Brush.Color := StyleServices.GetStyleColor(scComboBox);
C.DrawFocusRect(Rect);
end else
begin
C.Brush.Color := clSilver;
C.Font.Color := clWhite;
C.FillRect(Rect);
end;
end;
{ Выводим текст }
DrawRect := Rect;
OffsetRect(DrawRect, FComboBoxMargin, 1);
DrawRect.Right := Rect.Right - FComboBoxMargin;
C.TextRect(DrawRect, ItemText, [tfLeft, tfEndEllipsis]);
end;
procedure TFrame_Search.ComboBox_SearchOptionDropDown(Sender: TObject);
begin
SetComboBoxDropDownWidth;
end;
procedure TFrame_Search.ComboBox_SearchOptionSelect(Sender: TObject);
begin
SetComboBoxWidth;
Edit_SearchPattern.SetFocus;
end;
procedure TFrame_Search.Edit_SearchPatternChange(Sender: TObject);
begin
Button_ClearPattern.Visible := Edit_SearchPattern.Text <> '';
end;
procedure TFrame_Search.FrameResize(Sender: TObject);
begin
Panel_Search.Top := Round((Self.ClientHeight - Panel_Search.Height) / 2);
end;
function TFrame_Search.GetFilterOption: Byte;
begin
Result := ComboBox_SearchOption.ItemIndex;
end;
procedure TFrame_Search.InitControls;
var
i: Integer;
begin
Button_ClearPattern.Hide;
FComboBoxMargin := 3;
SendMessage(
Edit_SearchPattern.Handle,
EM_SETMARGINS,
EC_LEFTMARGIN or EC_RIGHTMARGIN,
MakeLong(FComboBoxMargin, 0)
);
FComboBoxWndProc := ComboBox_SearchOption.WindowProc;
ComboBox_SearchOption.WindowProc := ComboBoxWndProc;
SetComboBoxWidth;
SetFilterOption(0);
for i := 0 to Self.ControlCount - 1 do
Self.Controls[i].Repaint;
end;
procedure TFrame_Search.SetComboBoxDropDownWidth;
var
ItemText: string;
TextWidth: Integer;
MaxWidth: Integer;
begin
MaxWidth := 0;
for ItemText in ComboBox_SearchOption.Items do
begin
TextWidth := GetTextWidthInPixels(ItemText, ComboBox_SearchOption.Font);
if MaxWidth < TextWidth then MaxWidth := TextWidth;
end;
MaxWidth := MaxWidth + FComboBoxMargin * 2 + 2;
if (MaxWidth > ComboBox_SearchOption.Width) then
begin
if ComboBox_SearchOption.DropDownCount < ComboBox_SearchOption.Items.Count
then MaxWidth := MaxWidth + GetSystemMetrics(SM_CXVSCROLL);
SendMessage(ComboBox_SearchOption.Handle, CB_SETDROPPEDWIDTH, MaxWidth, 0);
end;
end;
procedure TFrame_Search.SetComboBoxWidth;
begin
ComboBox_SearchOption.Width := GetSystemMetrics(SM_CXHTHUMB)
+ GetSystemMetrics(SM_CYFIXEDFRAME) * 2
+ GetTextWidthInPixels(ComboBox_SearchOption.Text, ComboBox_SearchOption.Font)
+ FComboBoxMargin * 2;
end;
procedure TFrame_Search.SetFilterOption(Value: Byte);
begin
if (Value > ComboBox_SearchOption.Items.Count - 1)
then ComboBox_SearchOption.ItemIndex := FILTER_BY_ANY
else ComboBox_SearchOption.ItemIndex := Value;
SetComboBoxWidth;
end;
{ TBitBtn }
procedure TBitBtn.WMPaint(var Msg: TMessage);
var
C: TControlCanvas;
R: TRect;
begin
inherited;
C := TControlCanvas.Create;
try
C.Control := Self;
with C do
begin
{ Закрашиваем стандартную рамку }
Brush.Color := clWindow;
R := ClientRect;
FrameRect(R);
FillRect(R);
InflateRect(R, -1, -1);
FrameRect(R);
{ Рисуем новую рамку }
Brush.Color := StyleServices.GetStyleColor(scBorder);
R := ClientRect;
FrameRect(R);
Brush.Color := clWindow;
InflateRect(R, 0, -1);
FillRect(R);
Draw(
Round((ClipRect.Width - Self.Glyph.Width) / 2),
Round((ClipRect.Height - Self.Glyph.Height) / 2),
Self.Glyph
);
// Pen.Color := StyleServices.GetStyleColor(scBorder);
// MoveTo(0, 0);
// LineTo(ClipRect.Width, 0);
// Pen.Color := StyleServices.GetStyleColor(scBorder);
// MoveTo(0, ClipRect.Height);
// LineTo(ClipRect.Width, ClipRect.Height);
end;
finally
C.Free;
end;
end;
procedure TBitBtn.WMSetFocus(var Message: TWMSetFocus);
var
C: TControlCanvas;
R: TRect;
begin
inherited;
C := TControlCanvas.Create;
try
C.Control := Self;
with C do
begin
{ Закрашиваем стандартную рамку }
Brush.Color := clWindow;
R := ClientRect;
FrameRect(R);
FillRect(R);
InflateRect(R, -1, -1);
FrameRect(R);
{ Рисуем новую рамку }
Brush.Color := StyleServices.GetStyleColor(scBorder);
R := ClientRect;
FrameRect(R);
Brush.Color := clWindow;
InflateRect(R, 0, -1);
FillRect(R);
InflateRect(R, -2, -2);
DrawFocusRect(R);
Draw(
Round((ClipRect.Width - Self.Glyph.Width) / 2),
Round((ClipRect.Height - Self.Glyph.Height) / 2),
Self.Glyph
);
end;
finally
C.Free;
end;
end;
{ TPanel }
procedure TPanel.WMPaint(var Msg: TMessage);
var
C: TControlCanvas;
R: TRect;
begin
inherited;
C := TControlCanvas.Create;
try
C.Control := Self;
with C do
begin
{ Заливаем фон }
Brush.Color := clWindow;
R := ClientRect;
FillRect(R);
{ Рисуем рамку }
Brush.Color := StyleServices.GetStyleColor(scBorder);
R := ClientRect;
FrameRect(R);
end;
finally
C.Free;
end;
end;
end.
|
unit qstring;
//{$I 'qdac.inc'}
interface
{$REGION 'History'}
{
本源码来自QDAC项目,版权归swish(QQ:109867294)所有。
(1)、使用许可及限制
您可以自由复制、分发、修改本源码,但您的修改应该反馈给作者,并允许作者在必要时,
合并到本项目中以供使用,合并后的源码同样遵循QDAC版权声明限制。
您的产品的关于中,应包含以下的版本声明:
本产品使用的JSON解析器来自QDAC项目中的QJSON,版权归作者所有。
(2)、技术支持
有技术问题,您可以加入QDAC官方QQ群250530692共同探讨。
(3)、赞助
您可以自由使用本源码而不需要支付任何费用。如果您觉得本源码对您有帮助,您可以赞
助本项目(非强制),以使作者不为生活所迫,有更多的精力为您呈现更好的作品:
赞助方式:
支付宝: guansonghuan@sina.com 姓名:管耸寰
建设银行:
户名:管耸寰
账号:4367 4209 4324 0179 731
开户行:建设银行长春团风储蓄所
}
{ 修订日志
2018.04.14
===========
+ 增加 DateTimeFromString 函数来转换字符串日期时间值到 TDateTime
2017.1.23
==========
* 修正了 UrlEncode编码时没有对特殊转义字符计算空间的问题
+ 增加 UrlDecode 函数来解析Url的各个组成部分
2016.11.24
==========
* 优化了函数 HTMLUnescape 的效率
2016.11.12
==========
+ DeleteSideCharsW 用于删除两边的特定字符
2016.9.29
==========
- 删除 RightStrCountW 函数
+ 增加 RightPosW 函数,来计算字符串出现在右侧的起始位置(阿木建议)
2016.9.21
==========
* 修正了 HashOf 在计算长度为0的数据时出现AV错误的问题(QQ报告)
2016.8.23
==========
* 修正了DecodeChineseId身份证号中包含小写 x 时检查出错的问题
+ 增加 JavaEscape 和 JavaUnescape 来转义/反转 Java 字符串
+ 增加 IsOctChar 来检查指定的字符是否是8进制允许的字符
2016.7.16
==========
+ 增加 FreeAndNilObject 函数来替代 FreeAndNil
2016.6.13
==========
+ 增加 MemComp 函数用于比较两块内存块的值,不同于 BinaryCmp,它不要求两个内存块等长
2016.6.3
==========
+ 增加 IsHumanName/IsChineseName/IsNoChineseName/IsChineseAddr/IsNoChineseAddr 函数
2016.5.27
==========
* 修正了身份证号检查在移动平台中由于字符串索引调整而引起的问题
2016.5.24
==========
* 修正了TQStringCatHelperW.SetDest 设置地址时未处理结束边界的问题
2016.3.21
==========
* 修正了 StrIStrA 算法错误(阿木报告)
+ 加入了 PosA 函数(阿木建议)
+ QStringA 加入 UpperCase/LowerCase函数
2016.2.26
==========
+ 增加 IsEmailAddr 来检查电子邮箱格式
+ 增加IsChineseMobile 来检查手机号码格式
2016.2.25
==========
+ 增加 IsChineseIdNo 函数来判断身份证号的有效性(规则验证,非联网验证)
+ 增加 DecodeChineseId 来解析身份证号的各个组成部分内容
2015.11.22
==========
* 修正了PosW 函数 AStartPos 返回时没有考虑和一个重载丢失AStartPos参数的问题(阿木报告)
2015.11.18
==========
* 修正了MemScan忘记减小len_s计数的问题(TTT报告)
2015.11.10
==========
+ 新增货币金额汉语大写函数 CapMoney
+ 新增简繁转换函数 SimpleChineseToTraditional 和 TraditionalChineseToSimple
2015.9.26
=========
* 修正了ParseDateTime在解析 "n-nxxx" 这样的内容时错误返回true的问题(马铃薯报告)
2015.9.2
=========
* 修正了 AnsiEncode 在 2007 上由于编译器的Bug而出错的问题(星空报告)
2015.8.28
=========
* 合并 InternalInsert 的代码到 Insert
* 修正了 Clear 后没有收缩时,重新插入元素时页面异常增长的问题(冰晰空气报告)
* 修正了 Pack 函数在 Clear 后收缩时出错的问题(蝈蝈报告)
+ 加入了批量插入模式的 Insert 函数重载
+ 加入批量添加模式的 Add 函数重载
2015.8.27
=========
* 修正了 TQPagedList.Pack 方法收缩结果不正确的问题(冰晰空气报告)
2015.8.26
=========
* 修正了 TQPagedList.Insert 插入位置小于0时出错的问题(冰晰空气报告)
* 优化了 TQPagedList.Add 的代码,改成直接调用InternalInsert(冰晰空气建议)
2015.8.11
=========
* 修正了 HTMLUnescape 反转义特殊字符时出错的问题(不得闲报告)
2015.7.15
=========
* 根据 qsl 的哈希测试结果,将 HashOf 函数算法改为 BKDR 并在Windows平台下使用汇编
以提升效率(感谢qsl)
2015.6.6
=========
* 修正了 Utf8Decode 时对0x10000+范围的字符解码时移位错误(感谢qsl)
2015.5.29
=========
* 修正了 TQPagedStream 在低版本的IDE中无法编译的问题
2015.5.25
=========
+ TQPagedStream 加入,以在写入大内存流数据时替代TMemoryStream
2015.5.22
=========
* 修正了 ParseNumeric 和 ParseInt 时,对溢出表示范围的数值处理方式
2015.5.21
=========
* 修正了 StringReplaceWithW 在 AWithTag 为 True 时结果不正确的问题(麦子仲肥报告)
* 修正了 StringReplaceWithW 在替换的结果字符串为空时,访问无效地址的问题(麦子仲肥报告)
2015.5.20
=========
+ StringReplaceW 函数的一个重载,用于替换字符串中的某一部分为特定字符,一般用于部分敏感内容的隐藏
* 移除一个Hint
2015.5.8
=========
* 修改 TQPtr 的实现,将匿名释放事件和普通的事件使用同一个变量
+ DecodeText 函数从内存中直接检测编码并返回Unicode编码的字符串
2015.4.17
=========
* 优化了UTFEncode是占用内存过多的问题
2015.4.8
=========
* 修正了ParseNumeric 在解析 -0.xx 这样的数字符号出错的问题(感谢YZ报告)
2015.4.1
=========
* 修正了TQStringCatHelper记算需要的缓冲区长度时判断错误的问题(感谢etarelecca报告)
2015.3.9
=========
* 修改 NaturalCompareW 函数,增加是否忽略掉空白字符选项,在忽略时A 10 和 A10 将被视为一致的结果
2015.3.5
=========
+ 新增 PosW(等价于系统的Pos) 和按自然规则排序函数 NaturalCompareW
2015.2.9
=========
+ 新增 FilterCharW 和 FilterNoNumberW 两个函数
2015.1.27
=========
* 修正了TQPtr.Bind 几个函数由于代码没有保存的问题
2015.1.26
==========
+ TQPtr 新增几个 Bind 函数的重载
+ 加入全局变量 IsFMXApp 来检测当前是否是 FMX 类应用程序
2014.11.10
=========
* 修正了XE3编译时TSystemTimes定义无效的问题
2014.11.5
=========
* QStringA的From函数修改返回值类型并加入一个重载
+ QStringA加入Cat函数
+ CharCodeA/CharCodeU/CharCodeW来获得指定位置的字符编码值
2014.9.26
=========
* 将TThreadId类型定义由QWorker移入本单元
2014.9.11
=========
* 修正了LoadTextA/LoadTextW加载带有BOM头的空的Utf8流时出错的问题
2014.8.20
=========
+ StringReplaceWithW函数,用于替换一块标签中的内容(天地弦)
2014.8.15
=========
* 清理并验证了TQBytesCatHelper引起的2007编译无法通过的问题(秋风起逸以凉报告并验证)
+ PQStringA类型定义
2014.8.14
=========
* 修正了TQBytesCatHelper.NeedSize函数在Delphi2007下无法编译的问题(音儿小白报告并提供修改)
2014.8.5
========
* BinToHex加入ALowerCase参数,以支持使用小写的十六进制表示方式
2014.8.1
=========
+ 新增函数SameCharsA/U/W计算相同的字符数,EndWithA/U/W判断是符以指定的字符串结尾
2014.7.17
=========
+ 新增BinaryCmp函数,用于等价于C中的memcmp函数
2014.7.16
=========
+ 新增MemScan函数用于在指定的内存区域中查找指定的字节序列
2014.7.12
=========
* 修正了DecodeLineU中递归调用自己的错误(音儿小白报告)
* 修正了CharCountU检查字符宽度时对双字节Utf8编码的检测错误
2014.7.10
=========
+ 新增以下函数:StringReplicateW,NameOfW,ValueOfW,IndexOfNameW,IndexOfValueW
2014.6.26
=========
* 加入HPPEMIT默认链接本单元(麦子仲肥 建议)
2014.6.21
==========
* 修正了C++ Builder中编译的问题
2014.6.19
==========
* 修正了QuotedStr对于长度为0的字符串编码出错的问题
}
{$ENDREGION 'History'}
uses classes, sysutils, types{$IF RTLVersion>=21},
Rtti{$IFEND >=XE10}{$IFNDEF MSWINDOWS},
syncobjs{$ENDIF}
{$IFDEF MSWINDOWS}
, windows
{$ENDIF}
{$IFDEF POSIX}
, Posix.String_, Posix.Time, Posix.SysTypes
{$ENDIF}
{$IFDEF ANDROID}
, Androidapi.Log
{$ENDIF}
{$IFDEF IOS}
, iOSapi.Foundation, Macapi.Helpers, Macapi.ObjectiveC
{$ENDIF}
;
{$HPPEMIT '#pragma link "qstring"'}
{$HPPEMIT 'template<class T>'}
{$HPPEMIT 'bool __fastcall HasInterface(IUnknown *AIntf, DelphiInterface<T> &AResult)'}
{$HPPEMIT '{'}
{$HPPEMIT 'T *ATemp;'}
{$HPPEMIT 'if (AIntf&&(AIntf->QueryInterface(__uuidof(T), (void **)&ATemp) == S_OK))'}
{$HPPEMIT '{'}
{$HPPEMIT ' AResult = ATemp;'}
{$HPPEMIT ' ATemp->Release();'}
{$HPPEMIT ' return true;'}
(*$HPPEMIT '}'*)
{$HPPEMIT 'return false;'}
(*$HPPEMIT '}'*)
{$HPPEMIT 'template < class T > bool __fastcall HasInterface(TObject * AObject, DelphiInterface<T> &AResult)'}
{$HPPEMIT '{'}
{$HPPEMIT 'T *ATemp = NULL;'}
{$HPPEMIT 'if (AObject&&(AObject->GetInterface(__uuidof(T), &ATemp)))'}
{$HPPEMIT '{'}
{$HPPEMIT ' AResult = ATemp;'}
{$HPPEMIT ' ATemp->Release();'}
{$HPPEMIT ' return true;'}
(*$HPPEMIT '}'*)
{$HPPEMIT 'return false;'}
(*$HPPEMIT '}'*)
{$HPPEMIT 'template<class T>'}
{$HPPEMIT 'DelphiInterface<T> __fastcall ToInterface(TObject *AObject)'}
{$HPPEMIT '{'}
{$HPPEMIT 'DelphiInterface<T> ARetVal;'}
{$HPPEMIT 'HasInterface(AObject, ARetVal);'}
{$HPPEMIT 'return ARetVal;'}
(*$HPPEMIT '}'*)
{$HPPEMIT 'template<class T>'}
{$HPPEMIT 'DelphiInterface<T> __fastcall ToInterface(IUnknown *AIntf)'}
{$HPPEMIT '{'}
{$HPPEMIT 'DelphiInterface<T> ARetVal;'}
{$HPPEMIT 'HasInterface(AIntf, ARetVal);'}
{$HPPEMIT 'return ARetVal;'}
(*$HPPEMIT '}'*)
const
MC_NUM = $01; // 显示数字
MC_UNIT = $02; // 显示单位
MC_HIDE_ZERO = $04; // 隐藏左侧零值
MC_MERGE_ZERO = $08; // 合并中间的零值
MC_END_PATCH = $10; // 仅在不以分结束时加入AEndText指定的值
MC_READ = MC_NUM or MC_UNIT or MC_HIDE_ZERO or MC_MERGE_ZERO or MC_END_PATCH;
// 正常读取形式
MC_PRINT = MC_NUM or MC_HIDE_ZERO; // 正常套打形式
type
{$IFDEF UNICODE}
QStringW = UnicodeString;
{$ELSE}
QStringW = WideString;
{$ENDIF UNICODE}
{$IF RTLVersion<25}
IntPtr = Integer;
IntUPtr = Cardinal;
UIntPtr = Cardinal;
NativeInt = Integer;
{$IFEND IntPtr}
{$IF RTLVersion>=21}
TValueArray = TArray<TValue>;
TIntArray = TArray<Integer>;
TQStringArray = TArray<QStringW>;
{$ELSE}
TIntArray = array of Integer;
TQStringArray = array of QStringW;
{$IFEND >=2010}
// {$IF RTLVersion<=18}
// DWORD_PTR = DWORD;
// ULONGLONG = Int64;
// TBytes = array of Byte;
// PPointer = ^Pointer;
// {$IFEND}
{$IF RTLVersion<22}
TThreadId = Longword;
{$IFEND}
PIntPtr = ^IntPtr;
QCharA = Byte;
QCharW = WideChar;
PQCharA = ^QCharA;
PPQCharA = ^PQCharA;
PQStringA = ^QStringA;
PQCharW = PWideChar;
PPQCharW = ^PQCharW;
PQStringW = ^QStringW;
TTextEncoding = (teUnknown, { 未知的编码 }
teAuto, { 自动检测 }
teAnsi, { Ansi编码 }
teUnicode16LE, { Unicode LE 编码 }
teUnicode16BE, { Unicode BE 编码 }
teUTF8 { UTF8编码 }
);
{$HPPEMIT '#define DELPHI_ANON(AType,Code,AVar) \'}
{$HPPEMIT ' class AType##AVar:public TCppInterfacedObject<AType>\'}
(*$HPPEMIT ' {\'*)
{$HPPEMIT ' public:\'}
{$HPPEMIT ' void __fastcall Invoke##Code\'}
(*$HPPEMIT ' } *AVar=new AType##AVar'*)
TDirection = (FromBeginning, FromEnd);
// 从A结尾的为Ansi编码支持的函数,以U结尾的是Utf8编码支持的函数,以W结尾的为UCS2
QStringA = record
private
FValue: TBytes;
function GetChars(AIndex: Integer): QCharA;
procedure SetChars(AIndex: Integer; const Value: QCharA);
function GetLength: Integer;
procedure SetLength(const Value: Integer);
function GetIsUtf8: Boolean;
function GetData: PByte;
procedure SetIsUtf8(const Value: Boolean);
public
class operator Implicit(const S: QStringW): QStringA;
class operator Implicit(const S: QStringA): PQCharA;
class operator Implicit(const S: QStringA): TBytes;
class operator Implicit(const ABytes: TBytes): QStringA;
class operator Implicit(const S: QStringA): QStringW;
class operator Implicit(const S: PQCharA): QStringA;
{$IFNDEF NEXTGEN}
class operator Implicit(const S: AnsiString): QStringA;
class operator Implicit(const S: QStringA): AnsiString;
{$ENDIF}
class function UpperCase(S: PQCharA): QStringA; overload; static;
class function LowerCase(S: PQCharA): QStringA; overload; static;
class function Create(const p: PQCharA; AIsUtf8: Boolean): QStringA; static;
function UpperCase: QStringA; overload;
function LowerCase: QStringA; overload;
// 字符串比较
function From(p: PQCharA; AOffset, ALen: Integer): PQStringA; overload;
function From(const S: QStringA; AOffset: Integer = 0): PQStringA; overload;
function Cat(p: PQCharA; ALen: Integer): PQStringA; overload;
function Cat(const S: QStringA): PQStringA; overload;
property Chars[AIndex: Integer]: QCharA read GetChars
write SetChars; default;
property Length: Integer read GetLength write SetLength;
property IsUtf8: Boolean read GetIsUtf8 write SetIsUtf8;
property Data: PByte read GetData;
end;
TQSingleton{$IFDEF UNICODE}<T: class>{$ENDIF} = record
InitToNull: {$IFDEF UNICODE}T{$ELSE}Pointer{$ENDIF};
type
{$IFDEF UNICODE}
TGetInstanceCallback = reference to function: T;
{$ELSE}
TGetInstanceCallback = function: Pointer;
{$ENDIF}
function Instance(ACallback: TGetInstanceCallback):
{$IFDEF UNICODE}T{$ELSE}Pointer{$ENDIF};
end;
QException = class(Exception)
end;
// 字符串拼接类
TQStringCatHelperW = class
private
FValue: array of QCharW;
FStart, FDest, FLast: PQCharW;
FBlockSize: Integer;
{$IFDEF DEBUG}
FAllocTimes: Integer;
{$ENDIF}
FSize: Integer;
function GetValue: QStringW;
function GetPosition: Integer; inline;
procedure SetPosition(const Value: Integer);
procedure NeedSize(ASize: Integer);
function GetChars(AIndex: Integer): QCharW;
function GetIsEmpty: Boolean; inline;
procedure SetDest(const Value: PQCharW);
public
constructor Create; overload;
constructor Create(ASize: Integer); overload;
procedure LoadFromFile(const AFileName: QStringW);
procedure LoadFromStream(const AStream: TStream);
procedure IncSize(ADelta: Integer);
function Cat(p: PQCharW; len: Integer; AQuoter: QCharW = #0)
: TQStringCatHelperW; overload;
function Cat(const S: QStringW; AQuoter: QCharW = #0)
: TQStringCatHelperW; overload;
function Cat(c: QCharW): TQStringCatHelperW; overload;
function Cat(const V: Int64): TQStringCatHelperW; overload;
function Cat(const V: Double): TQStringCatHelperW; overload;
function Cat(const V: Boolean): TQStringCatHelperW; overload;
function Cat(const V: Currency): TQStringCatHelperW; overload;
function Cat(const V: TGuid): TQStringCatHelperW; overload;
function Cat(const V: Variant): TQStringCatHelperW; overload;
function Replicate(const S: QStringW; count: Integer): TQStringCatHelperW;
function Back(ALen: Integer): TQStringCatHelperW;
function BackIf(const S: PQCharW): TQStringCatHelperW;
procedure TrimRight;
procedure Reset;
function EndWith(const S: QStringW; AIgnoreCase: Boolean): Boolean;
function ToString: QStringW; {$IFDEF UNICODE}override; {$ENDIF}
property Value: QStringW read GetValue;
property Chars[AIndex: Integer]: QCharW read GetChars;
property Start: PQCharW read FStart;
property Current: PQCharW read FDest write SetDest;
property Last: PQCharW read FLast;
property Position: Integer read GetPosition write SetPosition;
property IsEmpty: Boolean read GetIsEmpty;
end;
TQBytesCatHelper = class
private
FValue: TBytes;
FStart, FDest: PByte;
FBlockSize: Integer;
FSize: Integer;
function GetBytes(AIndex: Integer): Byte;
function GetPosition: Integer;
procedure SetPosition(const Value: Integer);
procedure NeedSize(ASize: Integer);
procedure SetCapacity(const Value: Integer);
function GetValue: TBytes;
public
constructor Create; overload;
constructor Create(ASize: Integer); overload;
function Cat(const V: Byte): TQBytesCatHelper; overload;
function Cat(const V: Shortint): TQBytesCatHelper; overload;
function Cat(const V: Word): TQBytesCatHelper; overload;
function Cat(const V: Smallint): TQBytesCatHelper; overload;
function Cat(const V: Cardinal): TQBytesCatHelper; overload;
function Cat(const V: Integer): TQBytesCatHelper; overload;
function Cat(const V: Int64): TQBytesCatHelper; overload;
{$IFNDEF NEXTGEN}
function Cat(const V: AnsiChar): TQBytesCatHelper; overload;
function Cat(const V: AnsiString): TQBytesCatHelper; overload;
{$ENDIF}
function Cat(const V: QStringA; ACStyle: Boolean = false)
: TQBytesCatHelper; overload;
function Cat(const c: QCharW): TQBytesCatHelper; overload;
function Cat(const S: QStringW): TQBytesCatHelper; overload;
function Cat(const ABytes: TBytes): TQBytesCatHelper; overload;
function Cat(const AData: Pointer; const ALen: Integer)
: TQBytesCatHelper; overload;
function Cat(const V: Single): TQBytesCatHelper; overload;
function Cat(const V: Double): TQBytesCatHelper; overload;
function Cat(const V: Boolean): TQBytesCatHelper; overload;
function Cat(const V: Currency): TQBytesCatHelper; overload;
function Cat(const V: TGuid): TQBytesCatHelper; overload;
function Cat(const V: Variant): TQBytesCatHelper; overload;
function Replicate(const ABytes: TBytes; ACount: Integer): TQBytesCatHelper;
function Back(ALen: Integer): TQBytesCatHelper;
function Insert(AIndex: Cardinal; const AData: Pointer; const ALen: Integer)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Byte): TQBytesCatHelper;
overload;
function Insert(AIndex: Cardinal; const V: Shortint)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Word): TQBytesCatHelper;
overload;
function Insert(AIndex: Cardinal; const V: Smallint)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Cardinal)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Integer)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Int64)
: TQBytesCatHelper; overload;
{$IFNDEF NEXTGEN}
function Insert(AIndex: Cardinal; const V: AnsiChar)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: AnsiString)
: TQBytesCatHelper; overload;
{$ENDIF}
function Insert(AIndex: Cardinal; const V: QStringA;
ACStyle: Boolean = false): TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const c: QCharW)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const S: QStringW)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const ABytes: TBytes)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Single)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Double)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Boolean)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Currency)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: TGuid)
: TQBytesCatHelper; overload;
function Insert(AIndex: Cardinal; const V: Variant)
: TQBytesCatHelper; overload;
function Delete(AStart: Integer; ACount: Cardinal): TQBytesCatHelper;
procedure Reset;
property Value: TBytes read GetValue;
property Bytes[AIndex: Integer]: Byte read GetBytes;
property Start: PByte read FStart;
property Current: PByte read FDest;
property Position: Integer read GetPosition write SetPosition;
property Capacity: Integer read FSize write SetCapacity;
end;
IQPtr = interface(IInterface)
['{E5B28F92-CA81-4C01-8766-59FBF4E95F05}']
function Get: Pointer;
end;
TQPtrFreeEvent = procedure(AData: Pointer) of object;
PQPtrFreeEvent = ^TQPtrFreeEvent;
TQPtrFreeEventG = procedure(AData: Pointer);
{$IFDEF UNICODE}
TQPtrFreeEventA = reference to procedure(AData: Pointer);
PQPtrFreeEventA = ^TQPtrFreeEventA;
{$ENDIF}
TQPtrFreeEvents = record
case Integer of
0:
(Method: TMethod);
1:
(OnFree: {$IFNDEF NEXTGEN}TQPtrFreeEvent{$ELSE}Pointer{$ENDIF});
2:
(OnFreeG: TQPtrFreeEventG);
3:
(OnFreeA: Pointer);
end;
TQPtr = class(TInterfacedObject, IQPtr)
private
FObject: Pointer;
FOnFree: TQPtrFreeEvents;
public
constructor Create(AObject: Pointer); overload;
destructor Destroy; override;
class function Bind(AObject: TObject): IQPtr; overload;
class function Bind(AData: Pointer; AOnFree: TQPtrFreeEvent)
: IQPtr; overload;
class function Bind(AData: Pointer; AOnFree: TQPtrFreeEventG)
: IQPtr; overload;
{$IFDEF UNICODE}
class function Bind(AData: Pointer; AOnFree: TQPtrFreeEventA)
: IQPtr; overload;
{$ENDIF}
function Get: Pointer;
end;
{$IF RTLVersion<=23}
TDirection = (FromBeginning, FromEnd);
TPointerList = array of Pointer;
{$ELSE}
// TDirection = System.Types.TDirection;
{$IFEND}
// TQPagedList - 分页式列表,将来用于记录列表
TQListPage = class
protected
FStartIndex: Integer; // 起始索引
FUsedCount: Integer; // 使用的页面计数
FItems: array of Pointer;
public
constructor Create(APageSize: Integer);
destructor Destroy; override;
end;
TQPagedListSortCompare = procedure(p1, p2: Pointer; var AResult: Integer)
of object;
TQPagedListSortCompareG = procedure(p1, p2: Pointer; var AResult: Integer);
{$IFDEF UNICODE}
TQPagedListSortCompareA = reference to procedure(p1, p2: Pointer;
var AResult: Integer);
PQPagedListSortCompareA = ^TQPagedListSortCompareA;
{$ENDIF}
TQPagedList = class;
TQPagedListEnumerator = class
private
FIndex: Integer;
FList: TQPagedList;
public
constructor Create(AList: TQPagedList);
function GetCurrent: Pointer; inline;
function MoveNext: Boolean;
property Current: Pointer read GetCurrent;
end;
TQPagedList = class
protected
FPages: array of TQListPage; // 页面列表
FPageSize: Integer; // 每页大小
FCount: Integer; // 数量
FLastUsedPage: Integer; // 最后一个正在使用的页面索引(基于0)
FFirstDirtyPage: Integer; // 首个索引脏的页面
FOnCompare: TQPagedListSortCompare; // 内容比较函数
/// <summary> 比较两个指针对应的内容大小 </summary>
/// <param name="p1">第一个指针</param>
/// <param name="p2">第二个指针</param>
/// <returns>返回内容的比较结果,<0代表p1的内容小于p2,相等则为0,反之则>0</returns>
/// <remarks>仅在排序和查找时使用</remarks>
function DoCompare(p1, p2: Pointer): Integer; inline;
/// <summary>获取指定索引的值</summary>
/// <param name="AIndex">要获取的元素索引</param>
/// <returns>返回指到的指针,如果索引越界,则抛出异常</returns>
/// <remarks>属性Items的读函数</remarks>
function GetItems(AIndex: Integer): Pointer; inline;
/// <summary>设置指定索引的值</summary>
/// <param name="AIndex">目标索引位置,如果越界,则抛出异常</param>
/// <remarks>属性Items的写函数</remarks>
procedure SetItems(AIndex: Integer; const Value: Pointer); inline;
/// <summary>删除通知触发函数</summary>
/// <param name="p">要删除的指针</param>
/// <remarks>仅在TQPagedList子类才会触发Notify函数</remarks>
procedure DoDelete(const p: Pointer); inline;
/// <summary>查找指定索引所在的页索引</summary>
/// <param name="p">目标索引位置</param>
/// <returns>返回找到的页号</returns>
function FindPage(AIndex: Integer): Integer;
/// <summary>查找指定索引所在的页</summary>
/// <param name="p">目标索引位置</param>
/// <returns>返回找到的页对象</returns>
function GetPage(AIndex: Integer): TQListPage;
/// <summary>标记从指定的页开始,页头的FStartIndex信息失效</summary>
/// <param name="APage">失效的页面索引</param>
/// <remarks>使用失效的页(脏页)内容时,需要先更新脏页索引信息</remarks>
procedure Dirty(APage: Integer); inline;
/// <summary>通知指定的指针发生变化</summary>
/// <param name="Ptr">发生变化的指针数据</param>
/// <param name="Action">发生的变化类型</param>
procedure Notify(Ptr: Pointer; Action: TListNotification); virtual;
/// <summary>获取当前列表的容量</summary>
/// <returns>返回 PageSize*PageCount 的结果</returns>
/// <remarks>属性Capacity的读函数</remarks>
function GetCapacity: Integer;
/// <summary>不做任何事,仅为兼容TList的形式而提供</summary>
/// <remarks>属性Capacity的写函数</remarks>
procedure SetCapacity(const Value: Integer);
/// <summary>将当前所有内容放到一维的指针数组中</summary>
/// <returns>返回生成的一维动态数组</returns>
/// <remarks>属性List的读函数</remarks>
function GetList: TPointerList;
/// <summary>设置内容大小比较函数</summary>
/// <param name="Value">新的比较函数</summary>
/// <remarks>属性OnCompare的写函数,修改它可能触发重新排序</remarks>
procedure SetOnCompare(const Value: TQPagedListSortCompare);
/// <summary>在删除或移除元素时,检查最后使用的分页索引</summary>
procedure CheckLastPage;
/// <summary>获取当前已经分配的总页数</summary>
function GetPageCount: Integer;
public
/// <summary>
/// 默认构造函数,由于未指定页面大小,使用默认大小512
/// </summary>
constructor Create; overload;
/// <summary>构造函数</summary>
/// <param name="APageSize">每页项数,如果小于等于0则使用默认值</param>
constructor Create(APageSize: Integer); overload;
/// <summary>析构函数</summary>
destructor Destroy; override;
{$IF RTLVersion<26}
/// <summary>拷贝函数,参考TList.Assign</summary>
procedure Assign(ListA: TList; AOperator: TListAssignOp = laCopy;
ListB: TList = nil); overload;
{$IFEND}
/// <summary>拷贝函数,参考TList.Assign</summary>
procedure Assign(ListA: TQPagedList; AOperator: TListAssignOp = laCopy;
ListB: TQPagedList = nil); overload;
/// <summary>添加一个元素</summary>
/// <param name="p">要添加的元素</param>
/// <returns>返回新元素的索引值</returns>
function Add(const p: Pointer): Integer; overload;
/// <summary>一次性添加多个元素</summary>
/// <param name="pp">要添加的元素列表指针</param>
/// <param name="ACount">要添加的元素个数</param>
/// <returns>返回新元素的索引值</returns>
procedure BatchAdd(pp: PPointer; ACount: Integer); overload;
/// <summary>一次性添加多个元素</summary>
/// <param name="AList">要添加的元素动态数组</param>
/// <returns>返回新元素的索引值</returns>
procedure BatchAdd(AList: TPointerList); overload;
/// <summary>在指定的位置插入一个新元素</summary>
/// <param name="AIndex">要插入的位置,如果小于等于0,插入起始位置,如果大于等于Count,则插入末尾</param>
/// <param name="p">要插入的元素</param>
/// <remarks>如果指定的排序规则,则AIndex参数被忽略</remarks>
procedure Insert(AIndex: Integer; const p: Pointer); overload;
/// <summary>在指定的位置批量插入多个新元素</summary>
/// <param name="AIndex">要插入的位置,如果小于等于0,插入起始位置,如果大于等于Count,则插入末尾</param>
/// <param name="pp">要插入的元素</param>
/// <param name="ACount">pp参数指向的元素个数</param>
/// <remarks>如果指定的排序规则,则AIndex参数被忽略</remarks>
procedure BatchInsert(AIndex: Integer; pp: PPointer;
ACount: Integer); overload;
/// <summary>在指定的位置插入一个新元素</summary>
/// <param name="AIndex">要插入的位置,如果小于等于0,插入起始位置,如果大于等于Count,则插入末尾</param>
/// <param name="p">要插入的元素</param>
/// <remarks>如果指定的排序规则,则AIndex参数被忽略</remarks>
procedure BatchInsert(AIndex: Integer; const AList: TPointerList); overload;
/// <summary>交换两个元素的位置</summary>
/// <param name="AIndex1">第一个元素的位置索引</param>
/// <param name="AIndex2">第二个元素的位置索引</param>
procedure Exchange(AIndex1, AIndex2: Integer);
/// <summary>将指定位置的元素移动到新位置</summary>
/// <param name="AFrom">起始位置索引</param>
/// <param name="ATo">目标位置索引</param>
procedure MoveTo(AFrom, ATo: Integer);
/// <summary>实际直接调用MoveTo</summary>
procedure Move(AFrom, ATo: Integer); inline;
/// <summary>删除指定的元素</summary>
procedure Delete(AIndex: Integer);
/// <summary>移除指定的元素</summary>
procedure Remove(AIndex: Integer); overload;
/// <summary>移除指定的元素</summary>
function Remove(Item: Pointer): Integer; overload; inline;
/// <summary>从指定的方向开始查找并移除元素</summary>
function RemoveItem(Item: Pointer; Direction: TDirection): Integer;
/// <summary>查找指定元素的索引</summary>
/// <param name="p">要查找的元素</param>
/// <param name="AIdx">找到的元素索引</param>
/// <returns>如果找到,返回True,否则返回False,AIdx为目标应出现的位置</returns>
function Find(const p: Pointer; var AIdx: Integer): Boolean;
/// <summary>清除所有元素</summary>
/// <remarks>Clear并不收缩页以便后面重用,要收缩页,请调用Pack函数</remarks>
procedure Clear;
/// <summary>收缩列表为最少的页数</summary>
procedure Pack;
/// <summary>按照OnCompare规定的规则排序</summary>
/// <remarks>一旦指定OnCompare规则,则添加元素时会自动排序,Insert时指定的索引位置将会被忽略</remarks>
procedure Sort; overload;
{$IFDEF UNICODE}
/// <summary>按照AOnCompare参数规定的规则排序</summary>
/// <remarks>一旦指定OnCompare规则,则添加元素时会自动排序,Insert时指定的索引位置将会被忽略</remarks>
procedure Sort(AOnCompare: TQPagedListSortCompareA); overload;
{$ENDIF}
/// <summary>按照AOnCompare参数规定的规则排序</summary>
/// <remarks>一旦指定OnCompare规则,则添加元素时会自动排序,Insert时指定的索引位置将会被忽略</remarks>
procedure Sort(AOnCompare: TQPagedListSortCompareG); overload;
/// <summary> for .. in 支持</summary>
function GetEnumerator: TQPagedListEnumerator;
/// <summary>仅为兼容 TList 添加,对 TQPagedList 无意义</summary>
function Expand: TQPagedList;
/// <summary>移除指定的项目</summary>
/// <param name="Item">要移除的值</param>
function Extract(Item: Pointer): Pointer; inline;
/// <summary>移除指定的项目</summary>
/// <param name="Item">要移除的值</param>
/// <param name="Direction">查找方向</param>
function ExtractItem(Item: Pointer; Direction: TDirection): Pointer;
/// <summary>首个元素</summary>
function First: Pointer; inline;
/// <summary>最后一个元素</summary>
function Last: Pointer; inline;
/// <summary>获取指定元素的首次出现位置</summary>
/// <param name="Item">要查找的元素</param>
function IndexOf(Item: Pointer): Integer;
/// <summary>按指定的方向查找元素首次出现的位置</summary>
/// <param name="Item">要查找的元素</param>
/// <param name="Direction">查找方向</param>
function IndexOfItem(Item: Pointer; Direction: TDirection): Integer;
/// <summary>元素个数</summary>
property count: Integer read FCount;
/// <summary>元素列表</summary>
property Items[AIndex: Integer]: Pointer read GetItems
write SetItems; default;
/// <summary>元素比较规则,如果指定,则元素自动排序</summary>
property OnCompare: TQPagedListSortCompare read FOnCompare
write SetOnCompare;
/// <summary>兼容TList设置,对 TQPagedList 无意义</summary>
property Capacity: Integer read GetCapacity write SetCapacity;
/// <summary>获取所有的元素值数组</summary>
property List: TPointerList read GetList;
/// <summary>已经分配的页数</summary>
property PageCount: Integer read GetPageCount;
/// <summary>当前页大小</summary>
property PageSize: Integer read FPageSize;
end;
/// <summary>
/// 分页内存流对象,用于按页来存取数据,以优化内存的分配和释放次数,提高运行效率,使用方式同普通的内存流一样,但不提供Memory
/// 指针(因为它就不是连续的内存块)。不过提供了AsBytes或Bytes[AIndex]的方式来访问指定的内容。
/// </summary>
TQPagedStream = class(TStream)
private
procedure SetCapacity(Value: Int64);
function GetBytes(AIndex: Int64): Byte;
procedure SetBytes(AIndex: Int64; const Value: Byte);
procedure SetAsBytes(const Value: TBytes);
function GetAsBytes: TBytes;
protected
FPages: array of PByte;
FPageSize: Integer;
FSize: Int64;
FPosition: Int64;
FCapacity: Int64;
function ActivePage: Integer; inline;
function ActiveOffset: Integer; inline;
procedure PageNeeded(APageIndex: Integer);
function GetSize: Int64; override;
public
constructor Create; overload;
constructor Create(APageSize: Integer); overload;
destructor Destroy; override;
procedure Clear;
function Read(var Buffer; count: Longint): Longint; overload; override;
function Read(Buffer: TBytes; Offset, count: Longint): Longint;
{$IF RTLVersion>23} override{$ELSE}reintroduce;
overload{$IFEND};
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
procedure SaveToStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: string);
procedure SetSize(const NewSize: Int64); override;
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; count: Longint): Longint; overload; override;
function Write(const Buffer: TBytes; Offset, count: Longint): Longint;
{$IF RTLVersion>23} override{$ELSE}reintroduce;
overload{$IFEND};
property Capacity: Int64 read FCapacity write SetCapacity;
property Bytes[AIndex: Int64]: Byte read GetBytes write SetBytes;
property AsBytes: TBytes read GetAsBytes write SetAsBytes;
end;
/// <summary>
/// TQBits用来简化对标志位的访问,可以设置或获取某一位的状态
/// </summary>
TQBits = record
private
FBits: TBytes;
function GetSize: Integer;
procedure SetSize(const Value: Integer);
function GetIsSet(AIndex: Integer): Boolean;
procedure SetIsSet(AIndex: Integer; const Value: Boolean);
public
property Size: Integer read GetSize write SetSize;
property IsSet[AIndex: Integer]: Boolean read GetIsSet
write SetIsSet; default;
property Bytes: TBytes read FBits write FBits;
end;
TQReadOnlyMemoryStream = class(TCustomMemoryStream)
private
protected
constructor Create(); overload;
public
constructor Create(AData: Pointer; ASize: Integer); overload;
function Write(const Buffer; count: Longint): Longint; override;
end;
TQFilterCharEvent = procedure(const AChar, AIndex: Cardinal;
var Accept: Boolean; ATag: Pointer) of object;
{$IFDEF UNICODE}
TQFilterCharEventA = reference to procedure(const c, AIndex: Cardinal;
var Accept: Boolean; ATag: Pointer);
{$ENDIF}
TQNumberType = (nftFloat, nftHexPrec, nftDelphiHex, nftCHex, nftBasicHex,
nftNegative, nftPositive);
TQNumberTypes = set of TQNumberType;
TPasswordStrongLevel = (pslLowest, pslLower, pslNormal, pslHigher,
pslHighest);
TPasswordRule = (prIncNumber, prIncLowerCase, prIncUpperCase, prIncChart,
prIncUnicode, prRepeat, prSimpleOrder);
TPasswordRules = set of TPasswordRule;
// 舍入方法:mrmNone - 不舍入,mrmSimple - 四舍五入,mrmBank - 银行家舍入法(四舍六入五成双)
TMoneyRoundMethod = (mrmNone, mrmSimple, mrmBank);
/// <summary>
/// 名称字符类型
/// </summary>
TNameCharType = (
/// <summary>
/// 汉字
/// </summary>
nctChinese,
/// <summary>
/// 字母
/// </summary>
nctAlpha,
/// <summary>
/// 数字
/// </summary>
nctNum,
/// <summary>
/// 符号
/// </summary>
nctSymbol,
/// <summary>
/// 空格,注意不包含换行或Tab
/// </summary>
nctSpace,
/// <summary>
/// 姓名分隔符
/// </summary>
nctDot,
/// <summary>
/// 私有字符
/// </summary>
nctCustom,
/// <summary>
/// 其它
/// </summary>
nctOther);
TNameCharSet = set of TNameCharType;
/// <summary>
/// 用于 IsHumanName 判断名称是否有效时,用户可以自定义判定特定字符是否允许的全局回调函数,AChar 为要检查的字符,Accept
/// 为检查结果,AHandled 用于记录用户是否已经判定,如果已经判定,设置为true,默认为false,走默认判定。
/// </summary>
TQCustomNameCharTest = procedure(AChar: Cardinal;
var Accept, AHandled: Boolean);
/// <summary>
/// TRandCharType 用于生成随机字符串时确定字符串包含的字符范围
/// </summary>
TRandCharType = (
/// <summary>汉字</summary>
rctChinese,
/// <summary>大小写英文字母</summary>
rctAlpha,
/// <summary>仅小写英文字母,rctAlpha同时包含</summary>
rctLowerCase,
/// <summary>仅大写英文字母</summary>
rctUpperCase,
/// <summary>数字</summary>
rctNum,
/// <summary>英文符号</summary>
rctSymbol,
/// <summary>空白字符(空格、Tab和换行符)</summary>
rctSpace);
TRandCharTypes = set of TRandCharType;
/// <summary>
/// 人类性别
/// </summary>
TQHumanSex = (
/// <summary>
/// 未知
/// </summary>
hsUnknown,
/// <summary>
/// 女性
/// </summary>
hsFemale,
/// <summary>
/// 男性
/// </summary>
hsMale);
TMemCompFunction = function(p1, p2: Pointer; L1, L2: Integer): Integer;
TCNSpellCallback = function(const p: PQCharW): QCharW;
TUrlBookmarkEncode = (ubeOnlyLast, ubeNone, ubeAll);
TQStringCallback = procedure(var AValue: QStringW);
// UTF8编码与Unicode编码转换函数,使用自己的实现
function Utf8Decode(p: PQCharA; l: Integer): QStringW; overload;
function Utf8Decode(const p: QStringA): QStringW; overload;
function Utf8Encode(p: PQCharW; l: Integer): QStringA; overload;
function Utf8Encode(const p: QStringW): QStringA; overload;
function Utf8Encode(ps: PQCharW; sl: Integer; pd: PQCharA; dl: Integer)
: Integer; overload;
// Ansi编码与Unicode编码转换函数,使用系统的TEncoding实现
function AnsiEncode(p: PQCharW; l: Integer): QStringA; overload;
function AnsiEncode(const p: QStringW): QStringA; overload;
function AnsiDecode(p: PQCharA; l: Integer): QStringW; overload;
function AnsiDecode(const p: QStringA): QStringW; overload;
// 取指定的字符串的中文拼音首字母
function CNSpellChars(S: QStringA; AIgnoreEnChars: Boolean): QStringW; overload;
function CNSpellChars(S: QStringW; AIgnoreEnChars: Boolean): QStringW; overload;
// 计算当前字符的长度
function CharSizeA(c: PQCharA): Integer;
function CharSizeU(c: PQCharA): Integer;
function CharSizeW(c: PQCharW): Integer;
// 计算字符数函数,CharCountW重写以包括UCS2扩展区字符处理
function CharCountA(const source: QStringA): Integer;
function CharCountW(const S: QStringW): Integer;
function CharCountU(const source: QStringA): Integer;
// 计算当前字符的Unicode编码
function CharCodeA(c: PQCharA): Cardinal;
function CharCodeU(c: PQCharA): Cardinal;
function CharCodeW(c: PQCharW): Cardinal;
function CharAdd(const w: WideChar; ADelta: Integer): WideChar; inline;
function CharDelta(const c1, c2: WideChar): Integer; inline;
// 检查字符是否在指定的列表中
function CharInA(const c: PQCharA; const List: array of QCharA;
ACharLen: PInteger = nil): Boolean;
function CharInW(const c: PQCharW; const List: array of QCharW;
ACharLen: PInteger = nil): Boolean; overload;
function CharInW(const c, List: PQCharW; ACharLen: PInteger = nil)
: Boolean; overload;
function CharInU(const c: PQCharA; const List: array of QCharA;
ACharLen: PInteger = nil): Boolean;
function StrInW(const S: QStringW; const Values: array of QStringW;
AIgnoreCase: Boolean = false): Integer; overload;
function StrInW(const S: QStringW; Values: TStrings;
AIgnoreCase: Boolean = false): Integer; overload;
// 检查是否是空白字符
function IsSpaceA(const c: PQCharA; ASpaceSize: PInteger = nil): Boolean;
function IsSpaceW(const c: PQCharW; ASpaceSize: PInteger = nil): Boolean;
function IsSpaceU(const c: PQCharA; ASpaceSize: PInteger = nil): Boolean;
function TrimSpaceW(const S: QStringW): QStringW;
// 全角半角转换
function CNFullToHalf(const S: QStringW): QStringW;
function CNHalfToFull(const S: QStringW): QStringW;
// 引号处理
function QuotedStrA(const S: QStringA; const AQuoter: QCharA = $27): QStringA;
function QuotedStrW(const S: QStringW; const AQuoter: QCharW = #$27): QStringW;
function SQLQuoted(const S: QStringW; ADoEscape: Boolean = True): QStringW;
function DequotedStrA(const S: QStringA; const AQuoter: QCharA = $27): QStringA;
function DequotedStrW(const S: QStringW; const AQuoter: QCharW = #$27)
: QStringW;
// 跳过列表中的字符
function SkipCharA(var p: PQCharA; const List: array of QCharA): Integer;
function SkipCharU(var p: PQCharA; const List: array of QCharA): Integer;
function SkipCharW(var p: PQCharW; const List: array of QCharA)
: Integer; overload;
function SkipCharW(var p: PQCharW; const List: PQCharW): Integer; overload;
// 跳过空白字符,对于 Ansi编码,跳过的是#9#10#13#161#161,对于UCS编码,跳过的是#9#10#13#$A0#$3000
function SkipSpaceA(var p: PQCharA): Integer;
function SkipSpaceU(var p: PQCharA): Integer;
function SkipSpaceW(var p: PQCharW): Integer;
// 跳过一行,以#10为行结尾
function SkipLineA(var p: PQCharA): Integer;
function SkipLineU(var p: PQCharA): Integer;
function SkipLineW(var p: PQCharW): Integer;
// 跳过直接遇到指定的字符
function SkipUntilA(var p: PQCharA; AExpects: array of QCharA;
AQuoter: QCharA = 0): Integer;
function SkipUntilU(var p: PQCharA; AExpects: array of QCharA;
AQuoter: QCharA = 0): Integer;
function SkipUntilW(var p: PQCharW; AExpects: array of QCharW;
AQuoter: QCharW = #0): Integer; overload;
function SkipUntilW(var p: PQCharW; AExpects: PQCharW; AQuoter: QCharW = #0)
: Integer; overload;
function BackUntilW(var p: PQCharW; AExpects, AStartPos: PQCharW): Integer;
// 查找字符所在行列号,返回行的起始地址
function StrPosA(Start, Current: PQCharA; var ACol, ARow: Integer): PQCharA;
function StrPosU(Start, Current: PQCharA; var ACol, ARow: Integer): PQCharA;
function StrPosW(Start, Current: PQCharW; var ACol, ARow: Integer): PQCharW;
// 字符串分解
function DecodeTokenA(var p: PQCharA; ADelimiters: array of QCharA;
AQuoter: QCharA; AIgnoreSpace: Boolean): QStringA;
function DecodeTokenU(var p: PQCharA; ADelimiters: array of QCharA;
AQuoter: QCharA; AIgnoreSpace: Boolean): QStringA;
function DecodeTokenW(var p: PQCharW; ADelimiters: array of QCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean; ASkipDelimiters: Boolean = True)
: QStringW; overload;
function DecodeTokenW(var p: PQCharW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreSpace: Boolean; ASkipDelimiters: Boolean = True): QStringW; overload;
function DecodeTokenW(var S: QStringW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreCase, ARemove: Boolean; ASkipDelimiters: Boolean = True)
: QStringW; overload;
function SplitTokenW(AList: TStrings; p: PQCharW; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean): Integer; overload;
function SplitTokenW(AList: TStrings; const S: QStringW; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean): Integer; overload;
function SplitTokenW(const S: QStringW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreSpace: Boolean): TQStringArray; overload;
function StrBeforeW(var source: PQCharW; const ASpliter: QStringW;
AIgnoreCase, ARemove: Boolean; AMustMatch: Boolean = false)
: QStringW; overload;
function StrBeforeW(var source: QStringW; const ASpliter: QStringW;
AIgnoreCase, ARemove: Boolean; AMustMatch: Boolean = false)
: QStringW; overload;
function SplitByStrW(AList: TStrings; ASource: QStringW;
const ASpliter: QStringW; AIgnoreCase: Boolean): Integer;
function LeftStrW(const S: QStringW; AMaxCount: Integer; ACheckExt: Boolean)
: QStringW; overload;
function LeftStrW(var S: QStringW; const ADelimiters: QStringW;
ARemove: Boolean): QStringW; overload;
function RightStrW(const S: QStringW; AMaxCount: Integer; ACheckExt: Boolean)
: QStringW; overload;
function RightStrW(var S: QStringW; const ADelimiters: QStringW;
ARemove: Boolean): QStringW; overload;
function StrBetween(var S: PQCharW; AStartTag, AEndTag: QStringW;
AIgnoreCase: Boolean): QStringW; overload;
function StrBetweenTimes(const S, ADelimiter: QStringW; AIgnoreCase: Boolean;
AStartTimes: Integer = 0; AStopTimes: Integer = 1): QStringW;
function TokenWithIndex(var S: PQCharW; AIndex: Integer; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSapce: Boolean): QStringW;
// 获取一行
function DecodeLineA(var p: PQCharA; ASkipEmpty: Boolean = True;
AMaxSize: Integer = MaxInt): QStringA;
function DecodeLineU(var p: PQCharA; ASkipEmpty: Boolean = True;
AMaxSize: Integer = MaxInt): QStringA;
function DecodeLineW(var p: PQCharW; ASkipEmpty: Boolean = True;
AMaxSize: Integer = MaxInt; AQuoterChar: QCharW = #0): QStringW; overload;
function DecodeLineW(AStream: TStream; AEncoding: TTextEncoding;
var ALine: QStringW): Boolean; overload;
function ReplaceLineBreak(const S, ALineBreak: QStringW): QStringW;
// 大小写转换
function CharUpperA(c: QCharA): QCharA; inline;
function CharUpperW(c: QCharW): QCharW; inline;
function CharLowerA(c: QCharA): QCharA; inline;
function CharLowerW(c: QCharW): QCharW; inline;
function UpperFirstW(const S: QStringW): QStringW;
// 判断是否是以指定的字符串开始
function StartWithA(S, startby: PQCharA; AIgnoreCase: Boolean): Boolean;
function StartWithU(S, startby: PQCharA; AIgnoreCase: Boolean): Boolean;
function StartWithW(S, startby: PQCharW; AIgnoreCase: Boolean): Boolean;
// 判断是否以指定的字符串结尾
function EndWithA(const S, endby: QStringA; AIgnoreCase: Boolean): Boolean;
function EndWithU(const S, endby: QStringA; AIgnoreCase: Boolean): Boolean;
function EndWithW(const S, endby: QStringW; AIgnoreCase: Boolean): Boolean;
// 检查两个字符串从开始算相同的字符数
function SameCharsA(s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
function SameCharsU(s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
function SameCharsW(s1, s2: PQCharW; AIgnoreCase: Boolean): Integer;
// 加载文本
function LoadTextA(const AFileName: String;
AEncoding: TTextEncoding = teUnknown): QStringA; overload;
function LoadTextA(AStream: TStream; AEncoding: TTextEncoding = teUnknown)
: QStringA; overload;
function LoadTextU(const AFileName: String;
AEncoding: TTextEncoding = teUnknown): QStringA; overload;
function LoadTextU(AStream: TStream; AEncoding: TTextEncoding = teUnknown)
: QStringA; overload;
function LoadTextW(const AFileName: String;
AEncoding: TTextEncoding = teUnknown): QStringW; overload;
function LoadTextW(AStream: TStream; AEncoding: TTextEncoding = teUnknown)
: QStringW; overload;
// 检测文本编码并加载文本内容,注意对于没有BOM的文本的检测不是100%,尤其在没有BOM
// 时难以区分Unicode和Ansi编码的字符
function DecodeText(p: Pointer; ASize: Integer;
AEncoding: TTextEncoding = teUnknown): QStringW;
// 保存文本
procedure SaveTextA(const AFileName: String; const S: QStringA); overload;
procedure SaveTextA(AStream: TStream; const S: QStringA); overload;
procedure SaveTextU(const AFileName: String; const S: QStringA;
AWriteBom: Boolean = True); overload;
procedure SaveTextU(const AFileName: String; const S: QStringW;
AWriteBom: Boolean = True); overload;
procedure SaveTextU(AStream: TStream; const S: QStringA;
AWriteBom: Boolean = True); overload;
procedure SaveTextU(AStream: TStream; const S: QStringW;
AWriteBom: Boolean = True); overload;
procedure SaveTextW(const AFileName: String; const S: QStringW;
AWriteBom: Boolean = True); overload;
procedure SaveTextW(AStream: TStream; const S: QStringW;
AWriteBom: Boolean = True); overload;
procedure SaveTextWBE(AStream: TStream; const S: QStringW;
AWriteBom: Boolean = True); overload;
// 子串查找
function StrStrA(s1, s2: PQCharA): PQCharA;
function StrIStrA(s1, s2: PQCharA): PQCharA;
function StrStrU(s1, s2: PQCharA): PQCharA;
function StrIStrU(s1, s2: PQCharA): PQCharA;
function StrStrW(s1, s2: PQCharW): PQCharW;
function StrIStrW(s1, s2: PQCharW): PQCharW;
// 字符串的 Like 匹配
function StrLikeX(var S: PQCharW; pat: PQCharW; AIgnoreCase: Boolean): PQCharW;
function StrLikeW(S, pat: PQCharW; AIgnoreCase: Boolean): Boolean; overload;
// 计算子串的起始位置
function PosA(sub, S: PQCharA; AIgnoreCase: Boolean; AStartPos: Integer = 1)
: Integer; overload;
function PosA(sub, S: QStringA; AIgnoreCase: Boolean; AStartPos: Integer = 1)
: Integer; overload;
/// <summary>Pos函数的增强版本实现</summary>
/// <param name="sub">要查找的子字符串</param>
/// <param name="S">用来查找的原字符串</param>
/// <param name="AIgnoreCase">是否忽略大小写</param>
/// <param name="AStartPos">起始位置,第一个字符位置为1</param>
/// <returns>找到,返回子串的起始位置,失败,返回0<returns>
function PosW(sub, S: PQCharW; AIgnoreCase: Boolean; AStartPos: Integer = 1)
: Integer; overload;
/// <param name="sub">要查找的子字符串</param>
/// <param name="S">用来查找的原字符串</param>
/// <param name="AIgnoreCase">是否忽略大小写</param>
/// <param name="AStartPos">起始位置,第一个字符位置为1</param>
/// <returns>找到,返回子串的起始位置,失败,返回0<returns>
function PosW(sub, S: QStringW; AIgnoreCase: Boolean; AStartPos: Integer = 1)
: Integer; overload;
// 字符串复制
function StrDupX(const S: PQCharW; ACount: Integer): QStringW;
function StrDupW(const S: PQCharW; AOffset: Integer = 0;
const ACount: Integer = MaxInt): QStringW;
procedure StrCpyW(d: PQCharW; S: PQCharW; ACount: Integer = -1);
// 字符串比较
function StrCmpA(const s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
function StrCmpW(const s1, s2: PQCharW; AIgnoreCase: Boolean): Integer;
function StrNCmpW(const s1, s2: PQCharW; AIgnoreCase: Boolean;
ALength: Integer): Integer;
function NaturalCompareW(s1, s2: PQCharW; AIgnoreCase: Boolean;
AIgnoreSpace: Boolean = True): Integer;
function StrCatW(const S: array of QStringW; AIgnoreZeroLength: Boolean = True;
const AStartOffset: Integer = 0; const ACount: Integer = MaxInt;
const ADelimiter: QCharW = ','): QStringW;
// 十六进制相关函数
function IsHexChar(c: QCharW): Boolean; inline;
function IsOctChar(c: QCharW): Boolean; inline;
function HexValue(c: QCharW): Integer; inline;
function HexChar(V: Byte): QCharW; inline;
// 类型转换函数
function TryStrToGuid(const S: QStringW; var AGuid: TGuid): Boolean;
function TryStrToIPV4(const S: QStringW; var AIPV4:
{$IFDEF MSWINDOWS}Integer{$ELSE}Cardinal{$ENDIF}): Boolean;
/// StringReplace 增强
function StringReplaceW(const S, Old, New: QStringW; AFlags: TReplaceFlags)
: QStringW; overload;
/// <summary>替换指定范围内的字符为指定的字符</summary>
/// <param name="AChar">占位字符</param>
/// <param name="AFrom">开始位置,从0开始</param>
/// <param name="ACount">替换数量</param>
/// <returns>返回替换后的字符串</returns>
function StringReplaceW(const S: QStringW; const AChar: QCharW;
AFrom, ACount: Integer): QStringW; overload;
/// <summary>使用指定的内容替换AStartTag和EndTag之间的内容</summary>
/// <params>
/// <param name="S">要查找替换的字符串</param>
/// <param name="AStartTag">开始的标签名称</param>
/// <param name="AEndTag">结束的标签名称</param>
/// <param name="AReplaced">替换的结果</param>
/// <param name="AWithTag">是否连同AStartTag和AEndTag标签一起替换掉</param>
/// <param name="AIgnoreCase">比较标签名称时是否忽略大小</param>
/// <param name="AMaxTimes">最大替换次数,默认为1</param>
/// </params>
/// <returns>返回替换后的内容</returns>
function StringReplaceWithW(const S, AStartTag, AEndTag, AReplaced: QStringW;
AWithTag, AIgnoreCase: Boolean; AMaxTimes: Cardinal = 1): QStringW;
/// 重复指定的字符N次
function StringReplicateW(const S: QStringW; ACount: Integer)
: QStringW; overload;
function StringReplicateW(const S, AChar: QStringW; AExpectLength: Integer)
: QStringW; overload;
/// <summary>将字符串中间的字符替换为指定的掩码</summary>
/// <param name="S">原始字符串</param>
/// <param name="AMaskChar">掩码字符</param>
/// <param name="ALeft">工侧保留原始字符数</param>
/// <param name="ARight">右侧保留原始字符数</param>
///
function MaskText(const S: QStringW; ALeft, ARight: Integer;
AMaskChar: QCharW = '*'): QStringW;
/// <summary>
/// 将字符串中指定的字符按其在第二个参数中出现的位置替换为第三个参数同样位置的字符
/// </summary>
/// <param name="S">
/// 要查找的字符串
/// </param>
/// <param name="AToReplace">
/// 要替换的字符序列
/// </param>
/// <param name="AReplacement">
/// 同位置替换的字符序列
/// </param>
/// <returns>
/// 返回替换完成的结果
/// </returns>
/// <remarks>
/// AToReplace 和 AReplacement 的字符串长度要求必需保持一致,否则抛出异常。
/// </remarks>
/// <example>
/// translate('Techonthenet.com', 'met', 'ABC') 执行的结果为 TBchonChBnBC.coA
/// </example>
function Translate(const S, AToReplace, AReplacement: QStringW): QStringW;
/// <summary>过滤掉字符串内容中不需要的字符</summary>
/// <param name="S">要过滤的字符串</param>
/// <param name="AcceptChars">允许的字符列表</param>
/// <returns>返回过滤后的结果</returns>
function FilterCharW(const S: QStringW; AcceptChars: QStringW)
: QStringW; overload;
/// <summary>过滤掉字符串内容中不需要的字符</summary>
/// <param name="S">要过滤的字符串</param>
/// <param name="AOnValidate">用于过滤的回调函数</param>
/// <param name="ATag">用户自定义的附加参数,会传递给AOnValidate事件</param>
/// <returns>返回过滤后的结果</returns>
function FilterCharW(const S: QStringW; AOnValidate: TQFilterCharEvent;
ATag: Pointer = nil): QStringW; overload;
{$IFDEF UNICODE}
/// <summary>过滤掉字符串内容中不需要的字符</summary>
/// <param name="S">要过滤的字符串</param>
/// <param name="AOnValidate">用于过滤的回调函数</param>
/// <param name="ATag">用户自定义的附加参数,会传递给AOnValidate事件</param>
/// <returns>返回过滤后的结果</returns>
function FilterCharW(const S: QStringW; AOnValidate: TQFilterCharEventA;
ATag: Pointer = nil): QStringW; overload;
{$ENDIF}
/// <summary>过滤掉所有非数值类型的字符,从而将其格式化一个相对标准的浮点数</summary>
/// <param name="S">要过滤的字符串</param>
/// <param name="Accepts">过滤条件组件</param>
/// <returns>返回过滤后的结果</returns>
/// <remarks>
/// FilterNoNumberW 过滤后的结果可以使用 ParseNumeric 解析为数组,大部分情况下也
/// 可以被StrToFloat解析(但StrToFloat不支持有些特殊格式)
function FilterNoNumberW(const S: QStringW; Accepts: TQNumberTypes): QStringW;
/// <summary>简体中文转换为繁体中文</summary>
/// <param name="S">要转换的字符串</param>
/// <returns>返回转换后的结果</returns>
function SimpleChineseToTraditional(S: QStringW): QStringW;
/// <summary>繁体中文转换为简体中文</summary>
/// <param name="S">要转换的字符串</param>
/// <returns>返回转换后的结果</returns>
function TraditionalChineseToSimple(S: QStringW): QStringW;
/// <summary> 将货币值转换为汉字大写</summary>
/// <param name="AVal">货币值</param>
/// <param name="AFlags">标志位组合,以决定输出结果的格式</param>
/// <param name="ANegText">当货币值为负数时,显示的前缀</param>
/// <param name="AStartText">前导字符串,如“人民币:”</param>
/// <param name="AEndText">后置字符串,如“整”</param>
/// <param name="AGroupNum">组数,每个数字与其单位构成一个数组,AGroupNum指出要求的组数量,不为0时,会忽略标志位中的MC_HIDE_ZERO和MC_MERGE_ZERO</param>
/// <param name="ARoundMethod">金额舍入到分时的算法</param>
/// <param name="AEndDigts">小数点后的位数,-16~4 之间</param>
/// <returns>返回格式化后的字符串</returns>
function CapMoney(AVal: Currency; AFlags: Integer;
ANegText, AStartText, AEndText: QStringW; AGroupNum: Integer;
ARoundMethod: TMoneyRoundMethod; AEndDigits: Integer = 2): QStringW;
/// <summary>
/// 判断指定的字符串是否是一个有效的名称
/// </summary>
/// <param name="S">
/// 要判断的字符串
/// </param>
/// <param name="AllowChars">
/// 允许的字符类型
/// </param>
/// <param name="AMinLen">
/// 最小允许的字符数
/// </param>
/// <param name="AMaxLen">
/// 最大允许的字符数
/// </param>
/// <param name="AOnTest">
/// 用户自定义测试规则回调
/// </param>
function IsHumanName(S: QStringW; AllowChars: TNameCharSet;
AMinLen: Integer = 2; AMaxLen: Integer = 15;
AOnTest: TQCustomNameCharTest = nil): Boolean;
/// <summary>
/// 判断指定的字符串是否是一个中国人姓名
/// </summary>
function IsChineseName(S: QStringW): Boolean;
/// <summary>
/// 判断指定的字符串是否是一个有效的外国人名
/// </summary>
function IsNoChineseName(S: QStringW): Boolean;
/// <summary>
/// 判断指定的字符串是否是有效的中国地址
/// </summary>
function IsChineseAddr(S: QStringW; AMinLength: Integer = 3): Boolean;
/// <summary>
/// 判断指定的字符串是否是有效的外国地址
/// </summary>
function IsNoChineseAddr(S: QStringW; AMinLength: Integer = 3): Boolean;
/// 查找指定的二进制内容出现的起始位置
function MemScan(S: Pointer; len_s: Integer; sub: Pointer;
len_sub: Integer): Pointer;
function BinaryCmp(const p1, p2: Pointer; len: Integer): Integer;
{$IFNDEF WIN64}inline; {$ENDIF}
// 下面的函数只能Unicode版本,没有Ansi和UTF-8版本,如果需要,再加入
// 分解名称-值对
function NameOfW(const S: QStringW; ASpliter: QCharW;
AEmptyIfMissed: Boolean = false): QStringW;
function ValueOfW(const S: QStringW; ASpliter: QCharW;
AEmptyIfMissed: Boolean = false): QStringW;
function IndexOfNameW(AList: TStrings; const AName: QStringW;
ASpliter: QCharW): Integer;
function IndexOfValueW(AList: TStrings; const AValue: QStringW;
ASpliter: QCharW): Integer;
function DeleteCharW(const ASource, ADeletes: QStringW): QStringW;
function DeleteSideCharsW(const ASource: QStringW; ADeletes: QStringW;
AIgnoreCase: Boolean = false): QStringW;
function DeleteRightW(const S, ADelete: QStringW; AIgnoreCase: Boolean = false;
ACount: Integer = MaxInt): QStringW;
function DeleteLeftW(const S, ADelete: QStringW; AIgnoreCase: Boolean = false;
ACount: Integer = MaxInt): QStringW;
function ContainsCharW(const S, ACharList: QStringW): Boolean;
function HtmlEscape(const S: QStringW): QStringW;
function HtmlUnescape(const S: QStringW): QStringW;
function JavaEscape(const S: QStringW; ADoEscape: Boolean): QStringW;
function JavaUnescape(const S: QStringW; AStrictEscape: Boolean): QStringW;
function HtmlTrimText(const S: QStringW): QStringW;
function IsUrl(const S: QStringW): Boolean;
function UrlEncode(const ABytes: PByte; l: Integer; ASpacesAsPlus: Boolean;
AEncodePercent: Boolean = false;
ABookmarkEncode: TUrlBookmarkEncode = ubeOnlyLast): QStringW; overload;
function UrlEncode(const ABytes: TBytes; ASpacesAsPlus: Boolean;
AEncodePercent: Boolean = false;
ABookmarkEncode: TUrlBookmarkEncode = ubeOnlyLast): QStringW; overload;
function UrlEncodeString(const S: QStringW): QStringW;
function UrlEncode(const S: QStringW; ASpacesAsPlus: Boolean;
AUtf8Encode: Boolean = True; AEncodePercent: Boolean = false;
ABookmarkEncode: TUrlBookmarkEncode = ubeOnlyLast): QStringW; overload;
function UrlDecode(const AUrl: QStringW;
var AScheme, AHost, ADocument: QStringW; var APort: Word; AParams: TStrings;
AUtf8Encode: Boolean = True): Boolean; overload;
function UrlDecode(const AValue: QStringW; var AResult: QStringW;
AUtf8Encode: Boolean = True): Boolean; overload;
function LeftStrCount(const S: QStringW; const sub: QStringW;
AIgnoreCase: Boolean): Integer;
function RightPosW(const S: QStringW; const sub: QStringW;
AIgnoreCase: Boolean): Integer;
// 下面是一些辅助函数
function ParseInt(var S: PQCharW; var ANum: Int64): Integer;
function ParseHex(var p: PQCharW; var Value: Int64): Integer;
function ParseNumeric(var S: PQCharW; var ANum: Extended): Boolean;
overload; inline;
function ParseNumeric(var S: PQCharW; var ANum: Extended; var AIsFloat: Boolean)
: Boolean; overload;
function ParseDateTime(S: PWideChar; var AResult: TDateTime): Boolean;
function ParseWebTime(p: PWideChar; var AResult: TDateTime): Boolean;
function DateTimeFromString(AStr: QStringW; var AResult: TDateTime;
AFormat: String = ''): Boolean; overload;
function DateTimeFromString(Str: QStringW; AFormat: QStringW = '';
ADef: TDateTime = 0): TDateTime; overload;
// 获取当前时区偏移,单位为分钟,如中国为东8区,值为480
function GetTimeZone: Integer;
// 获取当前时区偏移文本表示,如中国为东8区,值为+0800
function GetTimezoneText: QStringW;
function EncodeWebTime(ATime: TDateTime): QStringW;
function RollupSize(ASize: Int64): QStringW;
function RollupTime(ASeconds: Int64; AHideZero: Boolean = True): QStringW;
function DetectTextEncoding(const p: Pointer; l: Integer; var b: Boolean)
: TTextEncoding;
procedure ExchangeByteOrder(p: PQCharA; l: Integer); overload;
function ExchangeByteOrder(V: Smallint): Smallint; overload; inline;
function ExchangeByteOrder(V: Word): Word; overload; inline;
function ExchangeByteOrder(V: Integer): Integer; overload; inline;
function ExchangeByteOrder(V: Cardinal): Cardinal; overload; inline;
function ExchangeByteOrder(V: Int64): Int64; overload; inline;
function ExchangeByteOrder(V: Single): Single; overload; inline;
function ExchangeByteOrder(V: Double): Double; overload; // inline;
procedure FreeObject(AObject: TObject); inline;
procedure FreeAndNilObject(var AObject); inline;
// 原子操作函数
function AtomicAnd(var Dest: Integer; const AMask: Integer): Integer;
function AtomicOr(var Dest: Integer; const AMask: Integer): Integer;
{$IF RTLVersion<24}
// 为与XE6兼容,InterlockedCompareExchange等价
function AtomicCmpExchange(var Target: Integer; Value: Integer;
Comparand: Integer): Integer; inline; overload;
function AtomicCmpExchange(var Target: Pointer; Value: Pointer;
Comparand: Pointer): Pointer; inline; overload;
// 等价于InterlockedExchanged
function AtomicExchange(var Target: Integer; Value: Integer): Integer;
inline; overload;
function AtomicExchange(var Target: Pointer; Value: Pointer): Pointer;
inline; overload;
function AtomicIncrement(var Target: Integer; const Value: Integer = 1)
: Integer; inline;
function AtomicDecrement(var Target: Integer): Integer; inline;
{$IFEND <XE5}
//
function BinToHex(p: Pointer; l: Integer; ALowerCase: Boolean = false)
: QStringW; overload;
function BinToHex(const ABytes: TBytes; ALowerCase: Boolean = false)
: QStringW; overload;
function HexToBin(const S: QStringW): TBytes; overload;
procedure HexToBin(const S: QStringW; var AResult: TBytes); overload;
// 计算指定内容的哈希值
function HashOf(p: Pointer; l: Integer): Cardinal;
function NewId: TGuid;
function SameId(const V1, V2: TGuid): Boolean;
/// <summary>计算指定内容的密码强度</summary>
/// <param name="S">密码</param>
/// <returns>返回一个>=0的密码强度值</returns>
function PasswordScale(const S: QStringW): Integer; overload;
/// <summary>计算指定内容的密码强度</summary>
/// <param name="S">密码</param>
/// <param name="ARules">检测到的密码规则项目</param>
/// <returns>返回一个>=0的密码强度值</returns>
function PasswordScale(const S: QStringW; var ARules: TPasswordRules)
: Integer; overload;
/// <summary>将指定的密码强度系数转换为强度等级</summary>
/// <param name="AScale">通过PasswordScale得到的强度等级</param>
/// <returns>返回转换后的强度等级</returns>
function CheckPassword(const AScale: Integer): TPasswordStrongLevel; overload;
/// <summary>计算指定内容的密码的强度等级</summary>
/// <param name="S">密码</param>
/// <returns>返回计算得到的强度等级</returns>
function CheckPassword(const S: QStringW): TPasswordStrongLevel; overload;
/// <summary>计算密码中包含的字符类型</summary>
/// <param name="S">字符串</param>
/// <returns>返回包含的字符类型集合</returns>
function PasswordCharTypes(const S: QStringW): TRandCharTypes;
/// <summary>计算密码匹配的规则类型</summary>
/// <param name="S">字符串</param>
/// <returns>返回匹配的规则类型集合</returns>
function PasswordRules(const S: QStringW): TPasswordRules;
/// <summary>检查指定的中国身份证号的有效性</summary>
/// <param name="CardNo">身份证号</param>
/// <returns>号码符合规则,返回true,否则,返回false</returns>
function IsChineseIdNo(CardNo: QStringW): Boolean;
/// <summary>解析指定的中国大陆身份证号的组成部分</summary>
/// <param name="CardNo">身份证号</param>
/// <param name="AreaCode">行政区划代码</param>
/// <param name="Birthday">出生日期</param>
/// <param name="IsFemale">性别,男为true,女为false</param>
/// <returns>身份证号有效,返回true,并通过参数返回各个部分,否则,返回false</returns>
function DecodeChineseId(CardNo: QStringW; var AreaCode: QStringW;
var Birthday: TDateTime; var IsFemale: Boolean): Boolean;
function AreaCodeOfChineseId(CardNo: QStringW): QStringW;
function AgeOfChineseId(CardNo: QStringW; ACalcDate: TDateTime = 0): Integer;
function BirthdayOfChineseId(CardNo: QStringW): TDateTime;
function SexOfChineseId(CardNo: QStringW): TQHumanSex;
/// <summary>检查指定的字符串是否符合电子邮箱格式</summary>
/// <param name="S">要检查的电子邮箱地址</param>
/// <returns>如果是x@y.z格式,则返回true,否则,返回false</returns>
function IsEmailAddr(S: QStringW): Boolean;
/// <summary>检查是否是中国电话号码格式</summary>
/// <param name="S">要检查的电话号码</param>
/// <returns>格式类型于[+86-]nnnn[-, ]nnnn[-]nnnn,则返回true,否则返回false</returns>
function IsChinesePhone(S: QStringW): Boolean;
/// <summary>检查是否是中国手机号码格式</summary>
/// <param name="S">要检查的手机号码</param>
/// <returns>格式类型[+86]nnnn[-, ]...且n共11位数字,且是以1打头,则返回true,否则false</returns>
function IsChineseMobile(S: QStringW): Boolean;
/// <summary>获取指定的文件的大小</summary>
/// <param name="S">要查询的文件名</param>
/// <returns>成功,返回实际的文件大小,失败,返回-1</returns>
function SizeOfFile(const S: QStringW): Int64;
/// <summary>判断两个事件响应函数是否相等</summary>
/// <param name="Left">第一个事件响应函数</param>
/// <param name="Right">第二个事件响应函数</param>
/// <returns>相等,返回true,不相等,返回False</param>
function MethodEqual(const Left, Right: TMethod): Boolean; inline;
/// <summary>合并两个URL,相当于TURI里的相对路径转换为绝对路径的函数</summary>
/// <param name="ABase">基准路径</param>
/// <param name="ARel">相对路径</param>
/// <returns>
/// 1.如果ARel是一个绝对路径,则直接返回该路径.
/// 2.如果ARel是一个以//开始的绝对路径,则拷贝ABase的协议类型,加上ARel形成新路径
/// 3.如果ARel是一个相对路径,则以ABase的路径为基准,加上ARel形成新路径
/// </returns>
function UrlMerge(const ABase, ARel: QStringW): QStringW;
/// <summary>输出调试信息</summary>
/// <param name="AMsg">要输出的字符串内容</param>
/// <remark>输出的日志在调试时会输出到Events窗口中</remark>
procedure Debugout(const AMsg: QStringW); overload;
/// <summary>输出调试信息</summary>
/// <param name="AMsg">要输出的字符串内容</param>
/// <remark>输出的日志在调试时会输出到Events窗口中</remark>
procedure Debugout(const AFmt: QStringW;
const AParams: array of const); overload;
function RandomString(ALen: Cardinal; ACharTypes: TRandCharTypes = [];
AllTypesNeeded: Boolean = false): QStringW;
function FindSwitchValue(ASwitch: QStringW; ANameValueSperator: QCharW;
AIgnoreCase: Boolean; var ASwitchChar: QCharW): QStringW; overload;
function FindSwitchValue(ASwitch: QStringW; ANameValueSperator: QCharW = ':')
: QStringW; overload;
function MonthFirstDay(ADate: TDateTime): TDateTime;
function MergeAddr(const AProv, ACity, ACounty, ATownship, AVillage,
ADetail: QStringW; AIgnoreCityIfSameEnding: Boolean): QStringW;
var
JavaFormatUtf8: Boolean;
IsFMXApp: Boolean;
MemComp: TMemCompFunction;
OnFetchCNSpell: TCNSpellCallback;
const
SLineBreak: PQCharW = {$IFDEF MSWINDOWS}#13#10{$ELSE}#10{$ENDIF};
DefaultNumberSet = [nftFloat, nftDelphiHex, nftCHex, nftBasicHex, nftHexPrec,
nftNegative, nftPositive];
HexChars: array [0 .. 15] of QCharW = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
LowerHexChars: array [0 .. 15] of QCharW = ('0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
implementation
uses dateutils, math, sysconst, variants
{$IF (RTLVersion>=25) and (not Defined(NEXTGEN))}
, AnsiStrings
{$IFEND >=XE4}
;
resourcestring
SBadUnicodeChar = '无效的Unicode字符:%d';
SBadUtf8Char = '无效的UTF8字符:%d';
SOutOfIndex = '索引越界,值 %d 不在[%d..%d]的范围内。';
SDayName = '天';
SHourName = '小时';
SMinuteName = '分钟';
SSecondName = '秒';
SCharNeeded = '当前位置应该是 "%s" ,而不是 "%s"。';
SRangeEndNeeded = '字符范围边界结束字符未指定。';
STooSmallCapMoneyGroup = '给定的分组数 %d 小于实际需要的最小货币分组数 %d。';
SUnsupportNow = '指定的函数 %s 目前不受支持';
SBadJavaEscape = '无效的 Java 转义序列:%s';
SBadHexChar = '无效的十六进制字符 %s';
SStreamReadOnly = '不能在一个只读的数据流上写入数据';
SMismatchReplacement = '%s 与 %s 的长度不一致';
type
TGBKCharSpell = record
SpellChar: QCharW;
StartChar, EndChar: Word;
end;
TStrStrFunction = function(s1, s2: PQCharW): PQCharW;
{$IFDEF MSWINDOWS}
TMSVCStrStr = function(s1, s2: PQCharA): PQCharA; cdecl;
TMSVCStrStrW = function(s1, s2: PQCharW): PQCharW; cdecl;
TMSVCMemCmp = function(s1, s2: Pointer; len: Integer): Integer; cdecl;
{$ENDIF}
var
// GBK汉字拼音首字母表
GBKSpells: array [0 .. 22] of TGBKCharSpell = (
(
SpellChar: 'A'; StartChar: $B0A1; EndChar: $B0C4;
), (SpellChar: 'B'; StartChar: $B0C5; EndChar: $B2C0;
), (SpellChar: 'C'; StartChar: $B2C1; EndChar: $B4ED;
), (SpellChar: 'D'; StartChar: $B4EE; EndChar: $B6E9;
), (SpellChar: 'E'; StartChar: $B6EA; EndChar: $B7A1;
), (SpellChar: 'F'; StartChar: $B7A2; EndChar: $B8C0;
), (SpellChar: 'G'; StartChar: $B8C1; EndChar: $B9FD;
), (SpellChar: 'H'; StartChar: $B9FE; EndChar: $BBF6;
), (SpellChar: 'J'; StartChar: $BBF7; EndChar: $BFA5;
), (SpellChar: 'K'; StartChar: $BFA6; EndChar: $C0AB;
), (SpellChar: 'L'; StartChar: $C0AC; EndChar: $C2E7;
), (SpellChar: 'M'; StartChar: $C2E8; EndChar: $C4C2;
), (SpellChar: 'N'; StartChar: $C4C3; EndChar: $C5B5;
), (SpellChar: 'O'; StartChar: $C5B6; EndChar: $C5BD;
), (SpellChar: 'P'; StartChar: $C5BE; EndChar: $C6D9;
), (SpellChar: 'Q'; StartChar: $C6DA; EndChar: $C8BA;
), (SpellChar: 'R'; StartChar: $C8BB; EndChar: $C8F5;
), (SpellChar: 'S'; StartChar: $C8F6; EndChar: $CBF0;
), (SpellChar: 'T'; StartChar: $CBFA; EndChar: $CDD9;
), (SpellChar: 'W'; StartChar: $CDDA; EndChar: $CEF3;
), (SpellChar: 'X'; StartChar: $CEF4; EndChar: $D188;
), (SpellChar: 'Y'; StartChar: $D1B9; EndChar: $D4D0;
), (SpellChar: 'Z'; StartChar: $D4D1; EndChar: $D7F9;));
{$IFDEF MSWINDOWS}
hMsvcrtl: HMODULE;
VCStrStr: TMSVCStrStr;
VCStrStrW: TMSVCStrStrW;
{$IFDEF WIN64}
VCMemCmp: TMSVCMemCmp;
{$ENDIF}
{$ENDIF}
const
// HTML转义表
HtmlEscapeChars: array [32 .. 255] of QStringW = (' ', #33, '"',
#35, #36, #37, '&', ''', #40, #41,
//
#42, #43, #44, #45, #46, #47, #48, #49, #50, #51, //
#52, #53, #54, #55, #56, #57, #58, #59, '<', #61, //
'>', #63, #64, #65, #66, #67, #68, #69, #70, #71, //
#72, #73, #74, #75, #76, #77, #78, #79, #80, #81, //
#82, #83, #84, #85, #86, #87, #88, #89, #90, #91, //
#92, #93, #94, #95, #96, #97, #98, #99, #100, #101, //
#102, #103, #104, #105, #106, #107, #108, #109, #110, #111, //
#112, #113, #114, #115, #116, #117, #118, #119, #120, #121, //
#122, #123, #124, #125, #126, #127, WideChar(128), WideChar(129),
WideChar(130), WideChar(131), //
WideChar(132), WideChar(133), WideChar(134), WideChar(135), WideChar(136),
WideChar(137), WideChar(138), WideChar(139), WideChar(140), WideChar(141),
//
WideChar(142), WideChar(143), WideChar(144), WideChar(145), WideChar(146),
WideChar(147), WideChar(148), WideChar(149), WideChar(150), WideChar(151),
//
WideChar(152), WideChar(153), WideChar(154), WideChar(155), WideChar(156),
WideChar(157), WideChar(158), WideChar(159), WideChar(160), '¡', //
'¢', '£', '¤', '¥', '¦', '§', '¨',
'©', 'ª', '«', //
'¬', '­', '®', '¯', '°', '±', WideChar(178),
WideChar(179), '´', 'µ', //
'¶', '·', '¸', WideChar(185), 'º', '»',
WideChar(188), WideChar(189), WideChar(190), '¿', //
'À', 'Á', 'ˆ', 'Ã', WideChar(196), '˚',
'Æ', 'Ç', 'È', 'É', //
'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð',
'Ñ', 'Ò', 'Ó', //
'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù',
'Ú', 'Û', 'Ü', 'Ý', //
'Þ', 'ß', 'à', 'á', WideChar(226), 'ã',
'ä', 'å', 'æ', 'ç',
//
'è', 'é', 'ê', 'ë', 'ì', 'í',
'î', 'ï', '&ieth;', 'ñ', 'ò', 'ó',
'ô', 'õ', 'ö', '÷', 'ø', 'ù',
'ú', 'û',
//
'ü', 'ý', 'þ', 'ÿ');
// QString函数
function Utf8Decode(const p: QStringA): QStringW;
begin
if p.IsUtf8 then
Result := Utf8Decode(PQCharA(p), p.Length)
else if p.Length > 0 then
Result := AnsiDecode(p)
else
SetLength(Result, 0);
end;
function Utf8Encode(const p: QStringW): QStringA;
var
l: NativeInt;
begin
l := Length(p);
if l > 0 then
Result := Utf8Encode(PQCharW(p), l)
else
begin
Result.Length := 0;
Result.FValue[0] := 1;
end;
end;
function Utf8Decode(p: PQCharA; l: Integer; var AResult: QStringW;
var ABadAt: PQCharA): Boolean; overload;
var
ps, pe: PByte;
pd, pds: PWord;
c: Cardinal;
procedure _Utf8Decode;
begin
ps := PByte(p);
pe := ps;
Inc(pe, l);
System.SetLength(AResult, l);
pd := PWord(PQCharW(AResult));
pds := pd;
Result := True;
while IntPtr(ps) < IntPtr(pe) do
begin
if (ps^ and $80) <> 0 then
begin
if (ps^ and $FC) = $FC then // 4000000+
begin
c := (ps^ and $03) shl 30;
Inc(ps);
c := c or ((ps^ and $3F) shl 24);
Inc(ps);
c := c or ((ps^ and $3F) shl 18);
Inc(ps);
c := c or ((ps^ and $3F) shl 12);
Inc(ps);
c := c or ((ps^ and $3F) shl 6);
Inc(ps);
c := c or (ps^ and $3F);
Inc(ps);
c := c - $10000;
pd^ := $D800 + ((c shr 10) and $3FF);
Inc(pd);
pd^ := $DC00 + (c and $3FF);
Inc(pd);
end
else if (ps^ and $F8) = $F8 then // 200000-3FFFFFF
begin
c := (ps^ and $07) shl 24;
Inc(ps);
c := c or ((ps^ and $3F) shl 18);
Inc(ps);
c := c or ((ps^ and $3F) shl 12);
Inc(ps);
c := c or ((ps^ and $3F) shl 6);
Inc(ps);
c := c or (ps^ and $3F);
Inc(ps);
c := c - $10000;
pd^ := $D800 + ((c shr 10) and $3FF);
Inc(pd);
pd^ := $DC00 + (c and $3FF);
Inc(pd);
end
else if (ps^ and $F0) = $F0 then // 10000-1FFFFF
begin
c := (ps^ and $0F) shl 18;
Inc(ps);
c := c or ((ps^ and $3F) shl 12);
Inc(ps);
c := c or ((ps^ and $3F) shl 6);
Inc(ps);
c := c or (ps^ and $3F);
Inc(ps);
c := c - $10000;
pd^ := $D800 + ((c shr 10) and $3FF);
Inc(pd);
pd^ := $DC00 + (c and $3FF);
Inc(pd);
end
else if (ps^ and $E0) = $E0 then // 800-FFFF
begin
c := (ps^ and $1F) shl 12;
Inc(ps);
c := c or ((ps^ and $3F) shl 6);
Inc(ps);
c := c or (ps^ and $3F);
Inc(ps);
pd^ := c;
Inc(pd);
end
else if (ps^ and $C0) = $C0 then // 80-7FF
begin
pd^ := (ps^ and $3F) shl 6;
Inc(ps);
pd^ := pd^ or (ps^ and $3F);
Inc(pd);
Inc(ps);
end
else
begin
ABadAt := PQCharA(ps);
Result := false;
Exit;
end;
end
else
begin
pd^ := ps^;
Inc(ps);
Inc(pd);
end;
end;
System.SetLength(AResult, (IntPtr(pd) - IntPtr(pds)) shr 1);
end;
begin
if l <= 0 then
begin
ps := PByte(p);
while ps^ <> 0 do
Inc(ps);
l := IntPtr(ps) - IntPtr(p);
end;
{$IFDEF MSWINDOWS}
SetLength(AResult, l);
SetLength(AResult, MultiByteToWideChar(CP_UTF8, 8, PAnsiChar(p), l,
PQCharW(AResult), l)); // 8==>MB_ERR_INVALID_CHARS
Result := Length(AResult) <> 0;
if not Result then
_Utf8Decode;
{$ELSE}
_Utf8Decode
{$ENDIF}
end;
function Utf8Decode(p: PQCharA; l: Integer): QStringW;
var
ABadChar: PQCharA;
begin
if not Utf8Decode(p, l, Result, ABadChar) then
raise Exception.Create(Format(SBadUtf8Char, [ABadChar^]));
end;
function WideCharUtf8Size(c: Integer): Integer;
begin
if c < $7F then
Result := 1
else if c < $7FF then
Result := 2
else if c < $FFFF then
Result := 3
else if c < $1FFFFF then
Result := 4
else if c < $3FFFFFF then
Result := 5
else
Result := 6;
end;
function Utf8BufferSize(p: PQCharW; var l: Integer): Integer;
var
c: Cardinal;
T: Integer;
begin
Result := 0;
if l < 0 then
begin
l := 0;
while p^ <> #0 do
begin
if (p^ >= #$D800) and (p^ <= #$DFFF) then // Unicode 扩展区字符
begin
c := (Word(p^) - $D800);
Inc(p);
if (p^ >= #$DC00) and (p^ <= #$DFFF) then
begin
c := $10000 + (c shl 10) + Word(p^) - $DC00;
Inc(p);
end;
Inc(Result, WideCharUtf8Size(c));
end
else
Inc(Result, WideCharUtf8Size(Word(p^)));
Inc(p);
Inc(l);
end;
end
else
begin
T := l;
while T > 0 do
begin
if (p^ >= #$D800) and (p^ <= #$DFFF) then // Unicode 扩展区字符
begin
c := (Word(p^) - $D800);
Inc(p);
if (p^ >= #$DC00) and (p^ <= #$DFFF) then
begin
c := $10000 + (c shl 10) + Word(p^) - $DC00;
Inc(p);
end;
Inc(Result, WideCharUtf8Size(c));
end
else
Inc(Result, WideCharUtf8Size(Word(p^)));
Inc(p);
Dec(T);
end;
end;
end;
function Utf8Encode(ps: PQCharW; sl: Integer; pd: PQCharA; dl: Integer)
: Integer;
{$IFNDEF MSWINDOWS}
var
pds: PQCharA;
c: Cardinal;
{$ENDIF}
begin
if (ps = nil) or (sl = 0) then
Result := 0
else
begin
{$IFDEF MSWINDOWS}
// Windows下直接调用操作系统的API
Result := WideCharToMultiByte(CP_UTF8, 0, ps, sl, PAnsiChar(pd), dl,
nil, nil);
{$ELSE}
pds := pd;
while sl > 0 do
begin
c := Cardinal(ps^);
Inc(ps);
if (c >= $D800) and (c <= $DFFF) then // Unicode 扩展区字符
begin
c := (c - $D800);
if (ps^ >= #$DC00) and (ps^ <= #$DFFF) then
begin
c := $10000 + ((c shl 10) + (Cardinal(ps^) - $DC00));
Inc(ps);
Dec(sl);
end
else
raise Exception.Create(Format(SBadUnicodeChar, [IntPtr(ps^)]));
end;
Dec(sl);
if c = $0 then
begin
if JavaFormatUtf8 then // 按照Java格式编码,将#$0字符编码为#$C080
begin
pd^ := $C0;
Inc(pd);
pd^ := $80;
Inc(pd);
end
else
begin
pd^ := c;
Inc(pd);
end;
end
else if c <= $7F then // 1B
begin
pd^ := c;
Inc(pd);
end
else if c <= $7FF then // $80-$7FF,2B
begin
pd^ := $C0 or (c shr 6);
Inc(pd);
pd^ := $80 or (c and $3F);
Inc(pd);
end
else if c <= $FFFF then // $8000 - $FFFF,3B
begin
pd^ := $E0 or (c shr 12);
Inc(pd);
pd^ := $80 or ((c shr 6) and $3F);
Inc(pd);
pd^ := $80 or (c and $3F);
Inc(pd);
end
else if c <= $1FFFFF then // $01 0000-$1F FFFF,4B
begin
pd^ := $F0 or (c shr 18); // 1111 0xxx
Inc(pd);
pd^ := $80 or ((c shr 12) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or ((c shr 6) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or (c and $3F); // 10 xxxxxx
Inc(pd);
end
else if c <= $3FFFFFF then // $20 0000 - $3FF FFFF,5B
begin
pd^ := $F8 or (c shr 24); // 1111 10xx
Inc(pd);
pd^ := $F0 or ((c shr 18) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or ((c shr 12) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or ((c shr 6) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or (c and $3F); // 10 xxxxxx
Inc(pd);
end
else if c <= $7FFFFFFF then // $0400 0000-$7FFF FFFF,6B
begin
pd^ := $FC or (c shr 30); // 1111 11xx
Inc(pd);
pd^ := $F8 or ((c shr 24) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $F0 or ((c shr 18) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or ((c shr 12) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or ((c shr 6) and $3F); // 10 xxxxxx
Inc(pd);
pd^ := $80 or (c and $3F); // 10 xxxxxx
Inc(pd);
end;
end;
pd^ := 0;
Result := IntPtr(pd) - IntPtr(pds);
{$ENDIF}
end;
end;
function CalcUtf8Length(p: PQCharW; l: Integer): Integer;
var
c: Cardinal;
begin
Result := 0;
while l > 0 do
begin
c := Cardinal(p^);
Inc(p);
if (c >= $D800) and (c <= $DFFF) then // Unicode 扩展区字符
begin
c := (c - $D800);
if (p^ >= #$DC00) and (p^ <= #$DFFF) then
begin
c := $10000 + ((c shl 10) + (Cardinal(p^) - $DC00));
Inc(p);
Dec(l);
end
else
raise Exception.Create(Format(SBadUnicodeChar, [IntPtr(p^)]));
end;
Dec(l);
if c = $0 then
begin
if JavaFormatUtf8 then // 按照Java格式编码,将#$0字符编码为#$C080
Inc(Result, 2)
else
Inc(Result);
end
else if c <= $7F then // 1B
Inc(Result)
else if c <= $7FF then // $80-$7FF,2B
Inc(Result, 2)
else if c <= $FFFF then // $8000 - $FFFF,3B
Inc(Result, 3)
else if c <= $1FFFFF then // $01 0000-$1F FFFF,4B
Inc(Result, 4)
else if c <= $3FFFFFF then // $20 0000 - $3FF FFFF,5B
Inc(Result, 5)
else if c <= $7FFFFFFF then // $0400 0000-$7FFF FFFF,6B
Inc(Result, 6);
end;
end;
function Utf8Encode(p: PQCharW; l: Integer): QStringA;
var
ps: PQCharW;
begin
if l <= 0 then
begin
ps := p;
while ps^ <> #0 do
Inc(ps);
l := ps - p;
end;
if l > (MaxInt div 3) then
Result.Length := CalcUtf8Length(p, l)
else
Result.Length := l * 3;
Result.IsUtf8 := True;
if l > 0 then
Result.Length := Utf8Encode(p, l, PQCharA(Result), Result.Length);
end;
function AnsiEncode(p: PQCharW; l: Integer): QStringA;
var
ps: PQCharW;
begin
if l <= 0 then
begin
ps := p;
while ps^ <> #0 do
Inc(ps);
l := ps - p;
end;
if l > 0 then
begin
{$IFDEF MSWINDOWS}
Result.Length := WideCharToMultiByte(CP_ACP, 0, p, l, nil, 0, nil, nil);
WideCharToMultiByte(CP_ACP, 0, p, l, LPSTR(Result.Data), Result.Length,
nil, nil);
{$ELSE}
Result.Length := l shl 1;
Result.FValue[0] := 0;
Move(p^, PQCharA(Result)^, l shl 1);
Result := TEncoding.Convert(TEncoding.Unicode, TEncoding.ANSI,
Result.FValue, 1, l shl 1);
{$ENDIF}
end
else
Result.Length := 0;
end;
function AnsiEncode(const p: QStringW): QStringA;
var
l: NativeInt;
begin
l := Length(p);
if l > 0 then
Result := AnsiEncode(PQCharW(p), l)
else
Result.Length := 0;
end;
function AnsiDecode(p: PQCharA; l: Integer): QStringW;
var
ps: PQCharA;
{$IFNDEF MSWINDOWS}
ABytes: TBytes;
{$ENDIF}
begin
if l <= 0 then
begin
ps := p;
while ps^ <> 0 do
Inc(ps);
l := IntPtr(ps) - IntPtr(p);
end;
if l > 0 then
begin
{$IFDEF MSWINDOWS}
System.SetLength(Result, MultiByteToWideChar(CP_ACP, 0, PAnsiChar(p),
l, nil, 0));
MultiByteToWideChar(CP_ACP, 0, PAnsiChar(p), l, PWideChar(Result),
Length(Result));
{$ELSE}
System.SetLength(ABytes, l);
Move(p^, PByte(@ABytes[0])^, l);
Result := TEncoding.ANSI.GetString(ABytes);
{$ENDIF}
end
else
System.SetLength(Result, 0);
end;
function AnsiDecode(const p: QStringA): QStringW;
begin
if p.IsUtf8 then
Result := Utf8Decode(p)
else if p.Length > 0 then
begin
{$IFDEF MSWINDOWS}
Result := AnsiDecode(PQCharA(p), p.Length);
{$ELSE}
Result := TEncoding.ANSI.GetString(p.FValue, 1, p.Length);
{$ENDIF}
end
else
SetLength(Result, 0);
end;
function SpellOfChar(w: Word): QCharW;
var
I, l, H: Integer;
begin
Result := #0;
l := 0;
H := 22;
repeat
I := (l + H) div 2;
if w >= GBKSpells[I].StartChar then
begin
if w <= GBKSpells[I].EndChar then
begin
Result := GBKSpells[I].SpellChar;
Break;
end
else
l := I + 1;
end
else
H := I - 1;
until l > H;
end;
function CNSpellChars(S: QStringA; AIgnoreEnChars: Boolean): QStringW;
var
p: PQCharA;
pd, pds: PQCharW;
begin
if S.Length > 0 then
begin
p := PQCharA(S);
System.SetLength(Result, S.Length);
pd := PQCharW(Result);
pds := pd;
while p^ <> 0 do
begin
if p^ in [1 .. 127] then
begin
if not AIgnoreEnChars then
begin
pd^ := QCharW(CharUpperA(p^));
Inc(pd);
end;
Inc(p);
end
else
begin
pd^ := SpellOfChar(ExchangeByteOrder(PWord(p)^));
Inc(p, 2);
if pd^ <> #0 then
Inc(pd);
end;
end;
System.SetLength(Result, pd - pds);
end
else
System.SetLength(Result, 0);
end;
function CNSpellChars(S: QStringW; AIgnoreEnChars: Boolean): QStringW;
var
pw, pd: PQCharW;
T: QStringA;
begin
pw := PWideChar(S);
System.SetLength(Result, Length(S));
pd := PQCharW(Result);
while pw^ <> #0 do
begin
if pw^ < #127 then
begin
if not AIgnoreEnChars then
begin
pd^ := CharUpperW(pw^);
Inc(pd);
end;
end
else if (pw^ > #$4E00) and (pw^ <= #$9FA5) then // 汉字区间
begin
if Assigned(OnFetchCNSpell) then
begin
pd^ := OnFetchCNSpell(pw);
if pd^ <> #0 then
begin
Inc(pd);
Inc(pw);
continue;
end;
end;
T := AnsiEncode(pw, 1);
if T.Length = 2 then
pd^ := SpellOfChar(ExchangeByteOrder(PWord(PQCharA(T))^));
if pd^ <> #0 then
Inc(pd);
end;
Inc(pw);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(PQCharW(Result))) shr 1);
end;
function CharSizeA(c: PQCharA): Integer;
begin
{ GB18030,兼容GBK和GB2312
单字节,其值从0到0x7F。
双字节,第一个字节的值从0x81到0xFE,第二个字节的值从0x40到0xFE(不包括0x7F)。
四字节,第一个字节的值从0x81到0xFE,第二个字节的值从0x30到0x39,第三个字节从0x81到0xFE,第四个字节从0x30到0x39。
}
{$IFDEF MSWINDOWS}
if GetACP = 936 then
{$ELSE}
if TEncoding.ANSI.CodePage = 936 then
{$ENDIF}
begin
Result := 1;
if (c^ >= $81) and (c^ <= $FE) then
begin
Inc(c);
if (c^ >= $40) and (c^ <= $FE) and (c^ <> $7F) then
Result := 2
else if (c^ >= $30) and (c^ <= $39) then
begin
Inc(c);
if (c^ >= $81) and (c^ <= $FE) then
begin
Inc(c);
if (c^ >= $30) and (c^ <= $39) then
Result := 4;
end;
end;
end;
end
else
{$IFDEF QDAC_ANSISTRINGS}
Result := AnsiStrings.StrCharLength(PAnsiChar(c));
{$ELSE}
{$IFDEF NEXTGEN}
if TEncoding.ANSI.CodePage = CP_UTF8 then
Result := CharSizeU(c)
else if (c^ < 128) or (TEncoding.ANSI.CodePage = 437) then
Result := 1
else
Result := 2;
{$ELSE}
{$IF RTLVersion>=25}
Result := AnsiStrings.StrCharLength(PAnsiChar(c));
{$ELSE}
Result := sysutils.StrCharLength(PAnsiChar(c));
{$IFEND}
{$ENDIF}
{$ENDIF !QDAC_ANSISTRINGS}
end;
function CharSizeU(c: PQCharA): Integer;
begin
if (c^ and $80) = 0 then
Result := 1
else
begin
if (c^ and $FC) = $FC then // 4000000+
Result := 6
else if (c^ and $F8) = $F8 then // 200000-3FFFFFF
Result := 5
else if (c^ and $F0) = $F0 then // 10000-1FFFFF
Result := 4
else if (c^ and $E0) = $E0 then // 800-FFFF
Result := 3
else if (c^ and $C0) = $C0 then // 80-7FF
Result := 2
else
Result := 1;
end
end;
function CharSizeW(c: PQCharW): Integer;
begin
if (c[0] >= #$D800) and (c[0] <= #$DBFF) and (c[1] >= #$DC00) and
(c[1] <= #$DFFF) then
Result := 2
else
Result := 1;
end;
function CharCodeA(c: PQCharA): Cardinal;
var
T: QStringA;
begin
T := AnsiDecode(c, CharSizeA(c));
Result := CharCodeW(PQCharW(T));
end;
function CharCodeU(c: PQCharA): Cardinal;
begin
if (c^ and $80) <> 0 then
begin
if (c^ and $FC) = $FC then // 4000000+
begin
Result := (c^ and $03) shl 30;
Inc(c);
Result := Result or ((c^ and $3F) shl 24);
Inc(c);
Result := Result or ((c^ and $3F) shl 18);
Inc(c);
Result := Result or ((c^ and $3F) shl 12);
Inc(c);
Result := Result or ((c^ and $3F) shl 6);
Inc(c);
Result := Result or (c^ and $3F);
end
else if (c^ and $F8) = $F8 then // 200000-3FFFFFF
begin
Result := (c^ and $07) shl 24;
Inc(c);
Result := Result or ((c^ and $3F) shl 18);
Inc(c);
Result := Result or ((c^ and $3F) shl 12);
Inc(c);
Result := Result or ((c^ and $3F) shl 6);
Inc(c);
Result := Result or (c^ and $3F);
end
else if (c^ and $F0) = $F0 then // 10000-1FFFFF
begin
Result := (c^ and $0F) shr 18;
Inc(c);
Result := Result or ((c^ and $3F) shl 12);
Inc(c);
Result := Result or ((c^ and $3F) shl 6);
Inc(c);
Result := Result or (c^ and $3F);
end
else if (c^ and $E0) = $E0 then // 800-FFFF
begin
Result := (c^ and $1F) shl 12;
Inc(c);
Result := Result or ((c^ and $3F) shl 6);
Inc(c);
Result := Result or (c^ and $3F);
end
else if (c^ and $C0) = $C0 then // 80-7FF
begin
Result := (c^ and $3F) shl 6;
Inc(c);
Result := Result or (c^ and $3F);
end
else
raise Exception.Create(Format(SBadUtf8Char, [IntPtr(c^)]));
end
else
Result := c^;
end;
function CharCodeW(c: PQCharW): Cardinal;
begin
if (c^ >= #$D800) and (c^ <= #$DFFF) then // Unicode 扩展区字符
begin
Result := (Ord(c^) - $D800);
Inc(c);
if (c^ >= #$DC00) and (c^ <= #$DFFF) then
begin
Result := $10000 + ((Result shl 10) + (Cardinal(Ord(c^)) - $DC00));
end
else
Result := 0
end
else
Result := Ord(c^);
end;
function CharAdd(const w: WideChar; ADelta: Integer): WideChar;
begin
Result := WideChar(Ord(w) + ADelta);
end;
function CharDelta(const c1, c2: WideChar): Integer;
begin
Result := Ord(c1) - Ord(c2);
end;
function CharCountA(const source: QStringA): Integer;
var
p: PQCharA;
l, ASize: Integer;
begin
p := PQCharA(source);
l := source.Length;
Result := 0;
while l > 0 do
begin
ASize := CharSizeA(p);
Dec(l, ASize);
Inc(p, ASize);
Inc(Result);
end;
// Result:=TEncoding.ANSI.GetCharCount(source);
end;
function CharCountW(const S: QStringW): Integer;
var
p, pe: PWord;
ALen: Integer;
procedure CountChar;
begin
if (p^ > $D800) and (p^ < $DFFF) then
begin
Inc(p);
if (p^ >= $DC00) and (p^ < $DFFF) then
begin
Inc(p);
Inc(Result);
end
else
Result := -1;
end
else
begin
Inc(Result);
Inc(p);
end;
end;
begin
Result := 0;
p := PWord(S);
ALen := Length(S);
pe := PWord(IntPtr(p) + (ALen shl 1));
while IntPtr(p) < IntPtr(pe) do
CountChar;
end;
function CharCountU(const source: QStringA): Integer;
var
p, pe: PQCharA;
procedure CountChar;
begin
if (p^ and $80) = 0 then
begin
Inc(Result);
Inc(p);
end
else if (p^ and $FC) = $FC then
begin
Inc(Result);
Inc(p, 6);
end
else if (p^ and $F8) = $F8 then
begin
Inc(Result);
Inc(p, 5);
end
else if (p^ and $F0) = $F0 then
begin
Inc(Result);
Inc(p, 4);
end
else if (p^ and $E0) = $E0 then
begin
Inc(Result);
Inc(p, 3);
end
else if (p^ and $C0) = $C0 then
begin
Inc(Result);
Inc(p, 2);
end
else
Result := -1;
end;
begin
Result := 0;
p := PQCharA(source);
pe := PQCharA(IntPtr(p) + source.Length);
while (IntPtr(p) < IntPtr(pe)) and (Result >= 0) do
CountChar;
end;
procedure CalcCharLengthA(var Lens: TIntArray; const List: array of QCharA);
var
I, l: Integer;
begin
I := Low(List);
System.SetLength(Lens, Length(List));
while I <= High(List) do
begin
l := CharSizeA(@List[I]);
Lens[I] := l;
Inc(I, l);
end;
end;
function CharInA(const c: PQCharA; const List: array of QCharA;
ACharLen: PInteger): Boolean;
var
I, count: Integer;
Lens: TIntArray;
begin
count := High(List) + 1;
Result := false;
CalcCharLengthA(Lens, List);
I := Low(List);
while I < count do
begin
if CompareMem(c, @List[I], Lens[I]) then
begin
if ACharLen <> nil then
ACharLen^ := Lens[I];
Result := True;
Break;
end
else
Inc(I, Lens[I]);
end;
end;
procedure CalcCharLengthW(var Lens: TIntArray; const List: array of QCharW);
var
I, l: Integer;
begin
I := Low(List);
System.SetLength(Lens, Length(List));
while I <= High(List) do
begin
l := CharSizeW(@List[I]);
Lens[I] := l;
Inc(I, l);
end;
end;
function CharInW(const c: PQCharW; const List: array of QCharW;
ACharLen: PInteger): Boolean;
var
I, count: Integer;
Lens: TIntArray;
begin
count := High(List) + 1;
Result := false;
CalcCharLengthW(Lens, List);
I := Low(List);
while I < count do
begin
if c^ = List[I] then
begin
if Lens[I] = 2 then
begin
Result := c[1] = List[I + 1];
if Assigned(ACharLen) and Result then
ACharLen^ := 2;
if Result then
Break;
end
else
begin
Result := True;
if Assigned(ACharLen) then
ACharLen^ := 1;
Break;
end;
end;
Inc(I, Lens[I]);
end;
end;
function CharInW(const c, List: PQCharW; ACharLen: PInteger): Boolean;
var
p: PQCharW;
begin
Result := false;
p := List;
while p^ <> #0 do
begin
if p^ = c^ then
begin
if (p[0] >= #$D800) and (p[0] <= #$DBFF) then
begin
// (p[1] >= #$DC00) and (p[1] <= #$DFFF)
if p[1] = c[1] then
begin
Result := True;
if ACharLen <> nil then
ACharLen^ := 2;
Break;
end;
end
else
begin
Result := True;
if ACharLen <> nil then
ACharLen^ := 1;
Break;
end;
end;
Inc(p);
end;
end;
procedure CalcCharLengthU(var Lens: TIntArray; const List: array of QCharA);
var
I, l: Integer;
begin
I := Low(List);
System.SetLength(Lens, Length(List));
while I <= High(List) do
begin
l := CharSizeU(@List[I]);
Lens[I] := l;
Inc(I, l);
end;
end;
function CharInU(const c: PQCharA; const List: array of QCharA;
ACharLen: PInteger): Boolean;
var
I, count: Integer;
Lens: TIntArray;
begin
count := High(List) + 1;
Result := false;
CalcCharLengthU(Lens, List);
I := Low(List);
while I < count do
begin
if CompareMem(c, @List[I], Lens[I]) then
begin
if ACharLen <> nil then
ACharLen^ := Lens[I];
Result := True;
Break;
end
else
Inc(I, Lens[I]);
end;
end;
function StrInW(const S: QStringW; const Values: array of QStringW;
AIgnoreCase: Boolean): Integer;
var
I: Integer;
begin
Result := -1;
for I := Low(Values) to High(Values) do
begin
if (Values[I] = S) or (AIgnoreCase and (CompareText(Values[I], S) = 0)) then
begin
Result := I;
Break;
end;
end
end;
function StrInW(const S: QStringW; Values: TStrings;
AIgnoreCase: Boolean = false): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Values.count - 1 do
begin
if (Values[I] = S) or (AIgnoreCase and (CompareText(Values[I], S) = 0)) then
begin
Result := I;
Break;
end;
end;
end;
function IsSpaceA(const c: PQCharA; ASpaceSize: PInteger): Boolean;
begin
if c^ in [9, 10, 13, 32, $A0] then
begin
Result := True;
if Assigned(ASpaceSize) then
ASpaceSize^ := 1;
end
else if (c^ = 161) and (PQCharA(IntPtr(c) + 1)^ = 161) then
begin
Result := True;
if Assigned(ASpaceSize) then
ASpaceSize^ := 2;
end
else
Result := false;
end;
function IsSpaceW(const c: PQCharW; ASpaceSize: PInteger): Boolean;
begin
Result := (c^ = #9) or (c^ = #10) or (c^ = #13) or (c^ = #32) or
(c^ = WideChar($A0)) or (c^ = #$3000);
if Result and Assigned(ASpaceSize) then
ASpaceSize^ := 1;
end;
function IsSpaceU(const c: PQCharA; ASpaceSize: PInteger): Boolean;
begin
// 全角空格$3000的UTF-8编码是227,128,128
if c^ in [9, 10, 13, 32, $A0] then
begin
Result := True;
if Assigned(ASpaceSize) then
ASpaceSize^ := 1;
end
else if (c^ = 227) and (PQCharA(IntPtr(c) + 1)^ = 128) and
(PQCharA(IntPtr(c) + 2)^ = 128) then
begin
Result := True;
if Assigned(ASpaceSize) then
ASpaceSize^ := 3;
end
else
Result := false;
end;
function TrimSpaceW(const S: QStringW): QStringW;
var
ps, pd: PQCharW;
ASize: Integer;
begin
ps := PQCharW(S);
SetLength(Result, Length(S));
pd := PQCharW(Result);
while ps^ <> #0 do
begin
if IsSpaceW(ps, @ASize) then
Inc(ps, ASize)
else
begin
pd^ := ps^;
Inc(ps);
Inc(pd);
end;
end;
SetLength(Result, pd - PQCharW(Result));
end;
function CNFullToHalf(const S: QStringW): QStringW;
var
p, pd: PWord;
l: Integer;
begin
l := Length(S);
if l > 0 then
begin
System.SetLength(Result, l);
p := PWord(PQCharW(S));
pd := PWord(PQCharW(Result));
while l > 0 do
begin
if (p^ = $3000) then // 全角空格' '
pd^ := $20
else if (p^ >= $FF01) and (p^ <= $FF5E) then
pd^ := $21 + (p^ - $FF01)
else
pd^ := p^;
Dec(l);
Inc(p);
Inc(pd);
end;
end
else
System.SetLength(Result, 0);
end;
function CNHalfToFull(const S: QStringW): QStringW;
var
p, pd: PWord;
l: Integer;
begin
l := Length(S);
if l > 0 then
begin
System.SetLength(Result, l);
p := PWord(PQCharW(S));
pd := PWord(PQCharW(Result));
while l > 0 do
begin
if p^ = $20 then // 全角空格' '
pd^ := $3000
else if (p^ >= $21) and (p^ <= $7E) then
pd^ := $FF01 + (p^ - $21)
else
pd^ := p^;
Dec(l);
Inc(p);
Inc(pd);
end;
end
else
System.SetLength(Result, 0);
end;
function QuotedStrA(const S: QStringA; const AQuoter: QCharA): QStringA;
var
p, pe, pd, pds: PQCharA;
begin
p := PQCharA(S);
Result.Length := S.Length shl 1;
pe := p;
Inc(pe, S.Length);
pd := PQCharA(Result);
pds := pd;
pd^ := AQuoter;
Inc(pd);
while IntPtr(p) < IntPtr(pe) do
begin
if p^ = AQuoter then
begin
pd^ := AQuoter;
Inc(pd);
pd^ := AQuoter;
end
else
pd^ := p^;
Inc(pd);
Inc(p);
end;
pd^ := AQuoter;
Result.Length := IntPtr(pd) - IntPtr(pds) + 1;
end;
function QuotedStrW(const S: QStringW; const AQuoter: QCharW): QStringW;
var
p, pe, pd, pds: PQCharW;
l: Integer;
begin
if AQuoter <> #0 then
begin
l := System.Length(S);
p := PQCharW(S);
SetLength(Result, (l + 1) shl 1);
pe := p;
Inc(pe, l);
pd := PQCharW(Result);
pds := pd;
pd^ := AQuoter;
Inc(pd);
while IntPtr(p) < IntPtr(pe) do
begin
if p^ = AQuoter then
begin
pd^ := AQuoter;
Inc(pd);
pd^ := AQuoter;
end
else
pd^ := p^;
Inc(pd);
Inc(p);
end;
pd^ := AQuoter;
SetLength(Result, ((IntPtr(pd) - IntPtr(pds)) shr 1) + 1);
end
else
Result := S;
end;
function SQLQuoted(const S: QStringW; ADoEscape: Boolean): QStringW;
begin
if ADoEscape then
Result := QuotedStrW(StringReplaceW(S, '\', '\\', [rfReplaceAll]))
else
Result := QuotedStrW(S);
end;
function DequotedStrA(const S: QStringA; const AQuoter: QCharA): QStringA;
var
p, pe, pd, pds: PQCharA;
begin
if (S.Length > 0) and (S[0] = AQuoter) and (S[S.Length - 1] = AQuoter) then
begin
p := PQCharA(S);
pe := p;
Inc(pe, S.Length);
Inc(p);
Result.Length := S.Length;
pd := PQCharA(Result);
pds := pd;
while IntPtr(p) < IntPtr(pe) do
begin
if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
begin
pd^ := AQuoter;
end
else if IntPtr(p) < IntPtr(pe) then // 后面不是单引号,错误的字符串,直接拷贝内容
begin
pd^ := AQuoter;
Inc(pd);
pd^ := p^;
end
else
Break;
end
else
pd^ := p^;
Inc(p);
Inc(pd);
end;
Result.Length := IntPtr(pd) - IntPtr(pds);
end
else
Result := S;
end;
function DequotedStrW(const S: QStringW; const AQuoter: QCharW): QStringW;
var
p, pe, pd, pds: PQCharW;
begin
if (Length(S) > 0) and (PQCharW(S)[0] = AQuoter) and
(PQCharW(S)[Length(S) - 1] = AQuoter) then
begin
p := PQCharW(S);
pe := p;
Inc(pe, Length(S));
Inc(p);
SetLength(Result, Length(S));
pd := PQCharW(Result);
pds := pd;
while IntPtr(p) < IntPtr(pe) do
begin
if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
begin
pd^ := AQuoter;
end
else if IntPtr(p) < IntPtr(pe) then // 后面不是单引号,错误的字符串,直接拷贝内容
begin
pd^ := AQuoter;
Inc(pd);
pd^ := p^;
end
else
Break;
end
else
pd^ := p^;
Inc(p);
Inc(pd);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(pds)) shr 1);
end
else
Result := S;
end;
function SkipCharA(var p: PQCharA; const List: array of QCharA): Integer;
var
I, count: Integer;
Lens: TIntArray;
AFound: Boolean;
ps: PQCharA;
begin
count := High(List) + 1;
Result := 0;
if count > 0 then
begin
CalcCharLengthA(Lens, List);
ps := p;
while p^ <> 0 do
begin
I := Low(List);
AFound := false;
while I < count do
begin
if CompareMem(p, @List[I], Lens[I]) then
begin
AFound := True;
Inc(p, Lens[I]);
Break;
end
else
Inc(I, Lens[I]);
end;
if not AFound then
begin
Result := IntPtr(p) - IntPtr(ps);
Break;
end;
end;
end;
end;
function SkipCharU(var p: PQCharA; const List: array of QCharA): Integer;
var
I, count: Integer;
Lens: TIntArray;
AFound: Boolean;
ps: PQCharA;
begin
count := High(List) + 1;
Result := 0;
if count > 0 then
begin
CalcCharLengthU(Lens, List);
ps := p;
while p^ <> 0 do
begin
I := Low(List);
AFound := false;
while I < count do
begin
if CompareMem(p, @List[I], Lens[I]) then
begin
AFound := True;
Inc(p, Lens[I]);
Break;
end
else
Inc(I, Lens[I]);
end;
if not AFound then
begin
Result := IntPtr(p) - IntPtr(ps);
Break;
end;
end;
end;
end;
function SkipCharW(var p: PQCharW; const List: array of QCharA): Integer;
var
I, count: Integer;
Lens: TIntArray;
AFound: Boolean;
ps: PQCharW;
begin
count := High(List) + 1;
Result := 0;
if count > 0 then
begin
CalcCharLengthA(Lens, List);
ps := p;
while p^ <> #0 do
begin
I := Low(List);
AFound := false;
while I < count do
begin
if CompareMem(p, @List[I], Lens[I] shl 1) then
begin
AFound := True;
Break;
end
else
Inc(I, Lens[I]);
end;
if AFound then
Inc(p)
else
begin
Result := IntPtr(p) - IntPtr(ps);
Break;
end;
end;
end;
end;
function SkipCharW(var p: PQCharW; const List: PQCharW): Integer;
var
l: Integer;
ps: PQCharW;
begin
Result := 0;
if (List <> nil) and (List^ <> #0) then
begin
ps := p;
while p^ <> #0 do
begin
if CharInW(p, List, @l) then
Inc(p, l)
else
begin
Result := IntPtr(p) - IntPtr(ps);
Break;
end;
end;
end;
end;
function SkipSpaceA(var p: PQCharA): Integer;
var
ps: PQCharA;
l: Integer;
begin
ps := p;
while p^ <> 0 do
begin
if IsSpaceA(p, @l) then
Inc(p, l)
else
Break;
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipSpaceU(var p: PQCharA): Integer;
var
ps: PQCharA;
l: Integer;
begin
ps := p;
while p^ <> 0 do
begin
if IsSpaceU(p, @l) then
Inc(p, l)
else
Break;
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipSpaceW(var p: PQCharW): Integer;
var
ps: PQCharW;
l: Integer;
begin
ps := p;
while p^ <> #0 do
begin
if IsSpaceW(p, @l) then
Inc(p, l)
else
Break;
end;
Result := IntPtr(p) - IntPtr(ps);
end;
// 跳过一行,以#10为行结尾
function SkipLineA(var p: PQCharA): Integer;
var
ps: PQCharA;
begin
ps := p;
while p^ <> 0 do
begin
if p^ = 10 then
begin
Inc(p);
Break;
end
else
Inc(p);
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipLineU(var p: PQCharA): Integer;
begin
Result := SkipLineA(p);
end;
function SkipLineW(var p: PQCharW): Integer;
var
ps: PQCharW;
begin
ps := p;
while p^ <> #0 do
begin
if p^ = #10 then
begin
Inc(p);
Break;
end
else
Inc(p);
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function StrPosA(Start, Current: PQCharA; var ACol, ARow: Integer): PQCharA;
begin
ACol := 1;
ARow := 1;
Result := Start;
while IntPtr(Start) < IntPtr(Current) do
begin
if Start^ = 10 then
begin
Inc(ARow);
ACol := 1;
Inc(Start);
Result := Start;
end
else
begin
Inc(Start, CharSizeA(Start));
Inc(ACol);
end;
end;
end;
function StrPosU(Start, Current: PQCharA; var ACol, ARow: Integer): PQCharA;
begin
ACol := 1;
ARow := 1;
Result := Start;
while IntPtr(Start) < IntPtr(Current) do
begin
if Start^ = 10 then
begin
Inc(ARow);
ACol := 1;
Inc(Start);
Result := Start;
end
else
begin
Inc(Start, CharSizeU(Start));
Inc(ACol);
end;
end;
end;
function StrPosW(Start, Current: PQCharW; var ACol, ARow: Integer): PQCharW;
begin
ACol := 1;
ARow := 1;
Result := Start;
while Start < Current do
begin
if Start^ = #10 then
begin
Inc(ARow);
ACol := 1;
Inc(Start);
Result := Start;
end
else
begin
Inc(Start, CharSizeW(Start));
Inc(ACol);
end;
end;
end;
function DecodeTokenA(var p: PQCharA; ADelimiters: array of QCharA;
AQuoter: QCharA; AIgnoreSpace: Boolean): QStringA;
var
S: PQCharA;
l: Integer;
begin
if AIgnoreSpace then
SkipSpaceA(p);
S := p;
while p^ <> 0 do
begin
if p^ = AQuoter then // 引用的内容不拆分
begin
Inc(p);
while p^ <> 0 do
begin
if p^ = $5C then
begin
Inc(p);
if p^ <> 0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInA(p, ADelimiters, @l) then
Break
else // \",\',"",''分别解析转义
Inc(p);
end;
l := IntPtr(p) - IntPtr(S);
Result.Length := l;
Move(S^, PQCharA(Result)^, l);
while CharInA(p, ADelimiters, @l) do
Inc(p, l);
end;
function DecodeTokenU(var p: PQCharA; ADelimiters: array of QCharA;
AQuoter: QCharA; AIgnoreSpace: Boolean): QStringA;
var
S: PQCharA;
l: Integer;
begin
if AIgnoreSpace then
SkipSpaceU(p);
S := p;
while p^ <> 0 do
begin
if p^ = AQuoter then // 引用的内容不拆分
begin
Inc(p);
while p^ <> 0 do
begin
if p^ = $5C then
begin
Inc(p);
if p^ <> 0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInU(p, ADelimiters, @l) then
Break
else // \",\',"",''分别解析转义
Inc(p);
end;
l := IntPtr(p) - IntPtr(S);
Result.Length := l;
Move(S^, PQCharA(Result)^, l);
while CharInU(p, ADelimiters, @l) do
Inc(p, l);
end;
function DecodeTokenW(var p: PQCharW; ADelimiters: array of QCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean; ASkipDelimiters: Boolean): QStringW;
var
S: PQCharW;
l: Integer;
begin
if AIgnoreSpace then
SkipSpaceW(p);
S := p;
while p^ <> #0 do
begin
if p^ = AQuoter then // 引用的内容不拆分
begin
Inc(p);
while p^ <> #0 do
begin
if p^ = #$5C then
begin
Inc(p);
if p^ <> #0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInW(p, ADelimiters, @l) then
Break
else // \",\',"",''分别解析转义
Inc(p);
end;
l := p - S;
SetLength(Result, l);
Move(S^, PQCharW(Result)^, l shl 1);
if ASkipDelimiters then
begin
while CharInW(p, ADelimiters, @l) do
Inc(p, l);
end;
if AIgnoreSpace then
SkipSpaceW(p);
end;
function DecodeTokenW(var p: PQCharW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreSpace: Boolean; ASkipDelimiters: Boolean): QStringW;
var
S: PQCharW;
l: Integer;
begin
if AIgnoreSpace then
SkipSpaceW(p);
S := p;
while p^ <> #0 do
begin
if p^ = AQuoter then // 引用的内容不拆分
begin
Inc(p);
while p^ <> #0 do
begin
if p^ = #$5C then
begin
Inc(p);
if p^ <> #0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInW(p, ADelimiters, @l) then
Break
else // \",\',"",''分别解析转义
Inc(p);
end;
l := p - S;
SetLength(Result, l);
Move(S^, PQCharW(Result)^, l shl 1);
if ASkipDelimiters then
begin
while CharInW(p, ADelimiters, @l) do
Inc(p, l);
end;
if AIgnoreSpace then
SkipSpaceW(p);
end;
function DecodeTokenW(var S: QStringW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreCase, ARemove, ASkipDelimiters: Boolean): QStringW;
var
p: PQCharW;
begin
p := PQCharW(S);
Result := DecodeTokenW(p, ADelimiters, AQuoter, AIgnoreCase, ASkipDelimiters);
if ARemove then
S := StrDupX(p, Length(S) - (p - PQCharW(S)));
end;
function SplitTokenW(AList: TStrings; p: PQCharW; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean): Integer;
begin
Result := 0;
AList.BeginUpdate;
try
while p^ <> #0 do
begin
AList.Add(DecodeTokenW(p, ADelimiters, AQuoter, AIgnoreSpace, True));
Inc(Result);
end;
finally
AList.EndUpdate;
end;
end;
function SplitTokenW(AList: TStrings; const S: QStringW; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSpace: Boolean): Integer;
begin
Result := SplitTokenW(AList, PQCharW(S), ADelimiters, AQuoter, AIgnoreSpace);
end;
function SplitTokenW(const S: QStringW; ADelimiters: PQCharW; AQuoter: QCharW;
AIgnoreSpace: Boolean): TQStringArray;
var
l: Integer;
p: PQCharW;
begin
SetLength(Result, 4);
l := 0;
p := PQCharW(S);
repeat
Result[l] := DecodeTokenW(p, ADelimiters, AQuoter, AIgnoreSpace);
Inc(l);
if (l = Length(Result)) and (p^ <> #0) then
SetLength(Result, l + 4);
until p^ = #0;
SetLength(Result, l);
end;
function StrBeforeW(var source: PQCharW; const ASpliter: QStringW;
AIgnoreCase, ARemove: Boolean; AMustMatch: Boolean = false): QStringW;
var
pe: PQCharW;
len: Integer;
begin
if Assigned(source) then
begin
if AIgnoreCase then
pe := StrIStrW(source, PQCharW(ASpliter))
else
pe := StrStrW(source, PQCharW(ASpliter));
if Assigned(pe) then
begin
len := (IntPtr(pe) - IntPtr(source)) shr 1;
Result := StrDupX(source, len);
if ARemove then
begin
Inc(pe, Length(ASpliter));
source := pe;
end;
end
else if not AMustMatch then
begin
Result := source;
if ARemove then
source := nil;
end
else
SetLength(Result, 0);
end
else
SetLength(Result, 0);
end;
function StrBeforeW(var source: QStringW; const ASpliter: QStringW;
AIgnoreCase, ARemove: Boolean; AMustMatch: Boolean): QStringW;
var
p, pe: PQCharW;
len: Integer;
begin
p := PQCharW(source);
if AIgnoreCase then
pe := StrIStrW(p, PQCharW(ASpliter))
else
pe := StrStrW(p, PQCharW(ASpliter));
if Assigned(pe) then
begin
len := (IntPtr(pe) - IntPtr(p)) shr 1;
Result := StrDupX(p, len);
if ARemove then
begin
Inc(pe, Length(ASpliter));
len := Length(source) - len - Length(ASpliter);
Move(pe^, p^, len shl 1);
SetLength(source, len);
end;
end
else if not AMustMatch then
begin
Result := source;
if ARemove then
SetLength(source, 0);
end
else
SetLength(Result, 0);
end;
function SplitByStrW(AList: TStrings; ASource: QStringW;
const ASpliter: QStringW; AIgnoreCase: Boolean): Integer;
var
p: PQCharW;
begin
if Length(ASource) > 0 then
begin
p := PQCharW(ASource);
Result := 0;
AList.BeginUpdate;
try
while Assigned(p) do
begin
AList.Add(StrBeforeW(p, ASpliter, AIgnoreCase, True, false));
Inc(Result);
end;
finally
AList.EndUpdate;
end;
end
else
Result := 0;
end;
function UpperFirstW(const S: QStringW): QStringW;
var
p, pd: PQCharW;
begin
if Length(S) > 0 then
begin
p := PQCharW(S);
SetLength(Result, Length(S));
pd := PQCharW(Result);
pd^ := CharUpperW(p^);
Inc(p);
Inc(pd);
while p^ <> #0 do
begin
pd^ := CharLowerW(p^);
Inc(p);
Inc(pd);
end;
end
else
Result := S;
end;
function DecodeLineA(var p: PQCharA; ASkipEmpty: Boolean; AMaxSize: Integer)
: QStringA;
var
ps: PQCharA;
begin
ps := p;
while p^ <> 0 do
begin
if ((p^ = 13) and (PQCharA(IntPtr(p) + 1)^ = 10)) or (p^ = 10) then
begin
if ps = p then
begin
if ASkipEmpty then
begin
if p^ = 13 then
Inc(p, 2)
else
Inc(p);
ps := p;
end
else
begin
Result.Length := 0;
Exit;
end;
end
else
begin
Result.Length := IntPtr(p) - IntPtr(ps);
Move(ps^, PQCharA(Result)^, IntPtr(p) - IntPtr(ps));
if p^ = 13 then
Inc(p, 2)
else
Inc(p);
Exit;
end;
end
else
Inc(p);
end;
if ps = p then
Result.Length := 0
else
begin
Result.Length := IntPtr(p) - IntPtr(ps);
Move(ps^, PQCharA(Result)^, IntPtr(p) - IntPtr(ps));
end;
if Result.Length > AMaxSize then
begin
Move(Result.FValue[Result.Length - AMaxSize + 3], Result.FValue[4],
AMaxSize - 3);
Result.FValue[1] := $2E;
// ...
Result.FValue[2] := $2E;
Result.FValue[3] := $2E;
end;
end;
function DecodeLineU(var p: PQCharA; ASkipEmpty: Boolean; AMaxSize: Integer)
: QStringA;
begin
Result := DecodeLineA(p, ASkipEmpty, MaxInt);
if Result.Length > 0 then
begin
Result.FValue[0] := 1;
if Result.Length > AMaxSize then
begin
Move(Result.FValue[Result.Length - AMaxSize + 3], Result.FValue[4],
AMaxSize - 3);
Result.FValue[1] := $2E;
// ...
Result.FValue[2] := $2E;
Result.FValue[3] := $2E;
end;
end;
end;
function DecodeLineW(var p: PQCharW; ASkipEmpty: Boolean; AMaxSize: Integer;
AQuoterChar: QCharW): QStringW;
var
ps: PQCharW;
begin
ps := p;
while p^ <> #0 do
begin
if p^ = AQuoterChar then
begin
Inc(p);
while p^ <> #0 do
begin
if p^ = #$5C then
begin
Inc(p);
if p^ <> #0 then
Inc(p);
end
else if p^ = AQuoterChar then
begin
Inc(p);
if p^ = AQuoterChar then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end;
if ((p[0] = #13) and (p[1] = #10)) or (p[0] = #10) then
begin
if ps = p then
begin
if ASkipEmpty then
begin
if p^ = #13 then
Inc(p, 2)
else
Inc(p);
ps := p;
end
else
begin
SetLength(Result, 0);
Exit;
end;
end
else
begin
SetLength(Result, p - ps);
Move(ps^, PQCharW(Result)^, IntPtr(p) - IntPtr(ps));
if p^ = #13 then
Inc(p, 2)
else
Inc(p);
Exit;
end;
end
else
Inc(p);
end;
if ps = p then
SetLength(Result, 0)
else
begin
SetLength(Result, p - ps);
Move(ps^, PQCharW(Result)^, IntPtr(p) - IntPtr(ps));
end;
if Length(Result) > AMaxSize then
Result := '...' + RightStrW(Result, AMaxSize - 3, True);
end;
function DecodeLineW(AStream: TStream; AEncoding: TTextEncoding;
var ALine: QStringW): Boolean;
var
ABuf: array [0 .. 4095] of Byte;
AReaded, I, ACount: Integer;
pd: PQCharW;
procedure NeedSize(ADelta: Integer);
begin
if Length(ALine) < (ACount + (ADelta shr 1)) then
begin
SetLength(ALine, Length(ALine) + 4096);
pd := PQCharW(ALine);
Inc(pd, ACount);
end;
end;
procedure Append(ADelta: Integer);
begin
NeedSize(ADelta);
Move(ABuf[0], pd^, ADelta);
pd := PQCharW(IntPtr(pd) + ADelta);
Inc(ACount, ADelta shr 1);
end;
begin
ACount := 0;
Result := false;
SetLength(ALine, 4096);
pd := PQCharW(ALine);
repeat
AReaded := AStream.Read(ABuf[0], 4096);
for I := 0 to AReaded - 1 do
begin
if ABuf[I] = 10 then
begin
Append(I);
if AEncoding = teUnicode16LE then
AStream.Seek(I - AReaded + 2, soCurrent)
else
AStream.Seek(I - AReaded + 1, soCurrent);
Result := True;
Break;
end;
end;
if not Result then
Append(AReaded);
until Result or (AStream.Position = AStream.Size);
Result := ACount > 0;
if AEncoding <> teUnicode16LE then
ALine := DecodeText(PQCharW(ALine), Length(ALine) shl 1, AEncoding)
else
begin
pd := PQCharW(ALine);
if PQCharW(IntPtr(pd) + (ACount shl 1) - 2)^ = #13 then
Dec(ACount, 1);
SetLength(ALine, ACount);
end;
end;
function LeftStrW(const S: QStringW; AMaxCount: Integer; ACheckExt: Boolean)
: QStringW;
var
ps, p: PQCharW;
l: Integer;
begin
l := Length(S);
if AMaxCount > l then
Result := S
else if AMaxCount > 0 then
begin
ps := PQCharW(S);
if ACheckExt then
begin
p := ps;
while (p^ <> #0) and (AMaxCount > 0) do
begin
if (p^ >= #$D800) and (p^ <= #$DBFF) then
begin
Inc(p);
if (p^ >= #$DC00) and (p^ <= #$DFFF) then
Inc(p);
// else 无效的扩展区字符,仍然循环保留
end
else
Inc(p);
Dec(AMaxCount);
end;
l := p - ps;
SetLength(Result, l);
Move(ps^, PQCharW(Result)^, l shl 1);
end
else
begin
SetLength(Result, AMaxCount);
Move(ps^, PQCharW(Result)^, AMaxCount shl 1);
end;
end
else
SetLength(Result, 0);
end;
function LeftStrW(var S: QStringW; const ADelimiters: QStringW;
ARemove: Boolean): QStringW;
begin
Result := DecodeTokenW(S, PQCharW(ADelimiters), QCharW(#0), false, ARemove);
end;
function RightStrW(const S: QStringW; AMaxCount: Integer; ACheckExt: Boolean)
: QStringW;
var
ps, p: PQCharW;
l: Integer;
begin
l := Length(S);
if AMaxCount > l then
Result := S
else if AMaxCount > 0 then
begin
ps := PQCharW(S);
if ACheckExt then
begin
p := ps + l - 1;
while (p > ps) and (AMaxCount > 0) do
begin
if (p^ >= #$DC00) and (p^ <= #$DFFF) then
begin
Dec(p);
if (p^ >= #$D800) and (p^ <= #$DBFF) then
Dec(p)
// else 无效的扩展区字符,仍然循环保留
end
else
Dec(p);
Dec(AMaxCount);
end;
Inc(p);
l := l - (p - ps);
SetLength(Result, l);
Move(p^, PQCharW(Result)^, l shl 1);
end
else
begin
Inc(ps, l - AMaxCount);
SetLength(Result, AMaxCount);
Move(ps^, PQCharW(Result)^, AMaxCount shl 1);
end;
end
else
SetLength(Result, 0);
end;
function RightStrW(var S: QStringW; const ADelimiters: QStringW;
ARemove: Boolean): QStringW;
var
ps, pe, pd: PQCharW;
begin
ps := PQCharW(S);
pe := PQCharW(IntPtr(ps) + (Length(S) shl 1));
pd := PQCharW(ADelimiters);
while pe > ps do
begin
Dec(pe);
if CharInW(pe, pd) then
begin
Inc(pe);
Result := StrDupX(pe, (IntPtr(ps) + (Length(S) shl 1) -
IntPtr(pe)) shr 1);
if ARemove then
S := StrDupX(ps, (IntPtr(pe) - IntPtr(ps) - 1) shr 1);
Exit;
end;
end;
Result := S;
if ARemove then
SetLength(S, 0);
end;
function StrBetween(var S: PQCharW; AStartTag, AEndTag: QStringW;
AIgnoreCase: Boolean): QStringW;
var
ps, pe: PQCharW;
l: Integer;
begin
if AIgnoreCase then
begin
ps := StrIStrW(S, PQCharW(AStartTag));
if ps <> nil then
begin
Inc(ps, Length(AStartTag));
pe := StrIStrW(ps, PQCharW(AEndTag));
if pe <> nil then
begin
l := pe - ps;
SetLength(Result, l);
Move(ps^, PQCharW(Result)^, l shl 1);
Inc(pe, Length(AEndTag));
S := pe;
end
else
begin
SetLength(Result, 0);
while S^ <> #0 do
Inc(S);
end;
end
else
begin
SetLength(Result, 0);
while S^ <> #0 do
Inc(S);
end;
end
else
begin
ps := StrStrW(S, PQCharW(AStartTag));
if ps <> nil then
begin
Inc(ps, Length(AStartTag));
pe := StrStrW(ps, PQCharW(AEndTag));
if pe <> nil then
begin
l := pe - ps;
SetLength(Result, l);
Move(ps^, PQCharW(Result)^, l shl 1);
Inc(pe, Length(AEndTag));
S := pe;
end
else
begin
SetLength(Result, 0);
while S^ <> #0 do
Inc(S);
end
end
else
begin
SetLength(Result, 0);
while S^ <> #0 do
Inc(S);
end;
end;
end;
function StrStrX(s1, s2: PQCharW; L1, L2: Integer;
AIgnoreCase: Boolean): PQCharW;
var
p1, p2: PQCharW;
begin
Result := nil;
while (s1^ <> #0) and (L1 >= L2) do
begin
if (s1^ = s2^) or
(AIgnoreCase and (qstring.CharUpperW(s1^) = qstring.CharUpperW(s2^))) then
begin
p1 := s1;
p2 := s2;
repeat
Inc(p1);
Inc(p2);
if p2^ = #0 then
begin
Result := s1;
Exit;
end
else if (p1^ = p2^) or
(AIgnoreCase and (qstring.CharUpperW(p1^) = qstring.CharUpperW(p2^)))
then
continue
else
Break;
until 1 > 2;
end;
Inc(s1);
end;
end;
function StrStrRX(s1, s2: PQCharW; L1, L2: Integer;
AIgnoreCase: Boolean): PQCharW;
var
ps1, ps2, p1, p2: PQCharW;
begin
Result := nil;
ps1 := s1 - 1;
ps2 := s2 - 1;
s1 := s1 - L1;
s2 := s2 - L2;
while (ps1 >= s1) and (L1 >= L2) do
begin
if (ps1^ = ps2^) or
(AIgnoreCase and (qstring.CharUpperW(ps1^) = qstring.CharUpperW(ps2^)))
then
begin
p1 := ps1;
p2 := ps2;
while (p2 > s2) do
begin
Dec(p1);
Dec(p2);
if (p1^ = p2^) or
(AIgnoreCase and (qstring.CharUpperW(p1^) = qstring.CharUpperW(p2^)))
then
continue
else
Break;
end;
if p2 = s2 then
begin
Result := ps1;
Exit;
end;
end;
Dec(ps1);
end;
end;
function StrBetweenTimes(const S, ADelimiter: QStringW; AIgnoreCase: Boolean;
AStartTimes: Integer = 0; AStopTimes: Integer = 1): QStringW;
var
p, ps, pl, pd: PQCharW;
L1, L2, ATimes: Integer;
begin
ps := PQCharW(S);
pd := PQCharW(ADelimiter);
L1 := Length(S);
L2 := Length(ADelimiter);
ATimes := 0;
if AStopTimes > 0 then
begin
// 查找起始位置
p := ps;
while ATimes < AStartTimes do
begin
pl := p;
p := StrStrX(p, pd, L1, L2, AIgnoreCase);
if Assigned(p) then
begin
Inc(p, L2);
Dec(L1, (IntPtr(p) - IntPtr(pl)) shr 1);
Inc(ATimes);
end
else
Break;
end;
// 查找结束位置
ps := p;
while ATimes < AStopTimes do
begin
pl := p;
p := StrStrX(p, pd, L1, L2, AIgnoreCase);
if Assigned(p) then
begin
Inc(p, Length(ADelimiter));
Dec(L1, (IntPtr(p) - IntPtr(pl)) shr 1);
Inc(ATimes);
end
else
Break;
end;
if Assigned(p) then
Result := StrDupX(ps, (IntPtr(p) - IntPtr(ps)) shr 1 - L2)
else
Result := S;
end
else if AStopTimes < 0 then // 从右向左找
begin
p := ps + L1;
while ATimes > AStartTimes do
begin
pl := p;
p := StrStrRX(p, pd + L2, L1, L2, AIgnoreCase);
if Assigned(p) then
begin
Dec(L1, (IntPtr(pl) - IntPtr(p)) shr 1);
Dec(ATimes);
end
else
Break;
end;
ps := p;
while ATimes > AStopTimes do
begin
pl := p;
p := StrStrRX(p, pd + L2, L1, L2, AIgnoreCase);
if Assigned(p) then
begin
Dec(L1, (IntPtr(pl) - IntPtr(p)) shr 1);
Dec(ATimes);
end
else
Break;
end;
if Assigned(p) then
Result := StrDupX(p + L2, (IntPtr(ps) - IntPtr(p)) shr 1 - L2)
else
Result := S;
end;
end;
function TokenWithIndex(var S: PQCharW; AIndex: Integer; ADelimiters: PQCharW;
AQuoter: QCharW; AIgnoreSapce: Boolean): QStringW;
begin
SetLength(Result, 0);
while (AIndex >= 0) and (S^ <> #0) do
begin
if AIndex <> 0 then
DecodeTokenW(S, ADelimiters, AQuoter, AIgnoreSapce)
else
begin
Result := DecodeTokenW(S, ADelimiters, AQuoter, AIgnoreSapce);
Break;
end;
Dec(AIndex);
end;
end;
function SkipUntilA(var p: PQCharA; AExpects: array of QCharA;
AQuoter: QCharA): Integer;
var
ps: PQCharA;
begin
ps := p;
while p^ <> 0 do
begin
if (p^ = AQuoter) then
begin
Inc(p);
while p^ <> 0 do
begin
if p^ = $5C then
begin
Inc(p);
if p^ <> 0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInA(p, AExpects) then
Break
else
Inc(p, CharSizeA(p));
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipUntilU(var p: PQCharA; AExpects: array of QCharA;
AQuoter: QCharA): Integer;
var
ps: PQCharA;
begin
ps := p;
while p^ <> 0 do
begin
if (p^ = AQuoter) then
begin
Inc(p);
while p^ <> 0 do
begin
if p^ = $5C then
begin
Inc(p);
if p^ <> 0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInU(p, AExpects) then
Break
else
Inc(p, CharSizeU(p));
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipUntilW(var p: PQCharW; AExpects: array of QCharW;
AQuoter: QCharW): Integer;
var
ps: PQCharW;
begin
ps := p;
while p^ <> #0 do
begin
if (p^ = AQuoter) then
begin
Inc(p);
while p^ <> #0 do
begin
if p^ = #$5C then
begin
Inc(p);
if p^ <> #0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInW(p, AExpects) then
Break
else
Inc(p, CharSizeW(p));
end;
Result := IntPtr(p) - IntPtr(ps);
end;
function SkipUntilW(var p: PQCharW; AExpects: PQCharW; AQuoter: QCharW)
: Integer;
var
ps: PQCharW;
begin
ps := p;
while p^ <> #0 do
begin
if (p^ = AQuoter) then
begin
Inc(p);
while p^ <> #0 do
begin
if p^ = #$5C then
begin
Inc(p);
if p^ <> #0 then
Inc(p);
end
else if p^ = AQuoter then
begin
Inc(p);
if p^ = AQuoter then
Inc(p)
else
Break;
end
else
Inc(p);
end;
end
else if CharInW(p, AExpects) then
Break
else
Inc(p, CharSizeW(p));
end;
Result := (IntPtr(p) - IntPtr(ps)) shr 1;
end;
function BackUntilW(var p: PQCharW; AExpects, AStartPos: PQCharW): Integer;
begin
Result := 0;
while p > AStartPos do
begin
if CharInW(p, AExpects) then
Break;
Dec(p);
Inc(Result);
end;
end;
function CharUpperA(c: QCharA): QCharA;
begin
if (c >= $61) and (c <= $7A) then
Result := c xor $20
else
Result := c;
end;
function CharUpperW(c: QCharW): QCharW;
begin
if (c >= #$61) and (c <= #$7A) then
Result := QCharW(PWord(@c)^ xor $20)
else
Result := c;
end;
function CharLowerA(c: QCharA): QCharA;
begin
if (c >= Ord('A')) and (c <= Ord('Z')) then
Result := Ord('a') + Ord(c) - Ord('A')
else
Result := c;
end;
function CharLowerW(c: QCharW): QCharW;
begin
if (c >= 'A') and (c <= 'Z') then
Result := QCharW(Ord('a') + Ord(c) - Ord('A'))
else
Result := c;
end;
function StartWithA(S, startby: PQCharA; AIgnoreCase: Boolean): Boolean;
begin
while (S^ <> 0) and (startby^ <> 0) do
begin
if AIgnoreCase then
begin
if CharUpperA(S^) <> CharUpperA(startby^) then
Break;
end
else if S^ <> startby^ then
Break;
Inc(S);
Inc(startby);
end;
Result := (startby^ = 0);
end;
function StartWithU(S, startby: PQCharA; AIgnoreCase: Boolean): Boolean;
begin
Result := StartWithA(S, startby, AIgnoreCase);
end;
function StartWithW(S, startby: PQCharW; AIgnoreCase: Boolean): Boolean;
begin
if AIgnoreCase then
begin
while (S^ <> #0) and (startby^ <> #0) do
begin
if CharUpperW(S^) <> CharUpperW(startby^) then
Break;
Inc(S);
Inc(startby);
end;
end
else
begin
while (S^ <> #0) and (S^ = startby^) do
begin
Inc(S);
Inc(startby);
end;
end;
Result := (startby^ = #0);
end;
function EndWithA(const S, endby: QStringA; AIgnoreCase: Boolean): Boolean;
var
p: PQCharA;
begin
if S.Length < endby.Length then
Result := false
else
begin
p := PQCharA(S);
Inc(p, S.Length - endby.Length);
if AIgnoreCase then
Result := (StrIStrA(p, PQCharA(endby)) = p)
else
Result := (StrStrA(p, PQCharA(endby)) = p);
end;
end;
function EndWithU(const S, endby: QStringA; AIgnoreCase: Boolean): Boolean;
begin
Result := EndWithA(S, endby, AIgnoreCase);
end;
function EndWithW(const S, endby: QStringW; AIgnoreCase: Boolean): Boolean;
var
p: PQCharW;
begin
if System.Length(S) < System.Length(endby) then
Result := false
else
begin
p := PQCharW(S);
Inc(p, System.Length(S) - System.Length(endby));
if AIgnoreCase then
Result := (StrIStrW(p, PQCharW(endby)) = p)
else
Result := (StrStrW(p, PQCharW(endby)) = p);
end;
end;
function SameCharsA(s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
begin
Result := 0;
if (s1 <> nil) and (s2 <> nil) then
begin
if AIgnoreCase then
begin
while (s1^ <> 0) and (s2^ <> 0) and
((s1^ = s2^) or (CharUpperA(s1^) = CharUpperA(s2^))) do
begin
Inc(Result);
Inc(s1);
Inc(s2);
end;
end
else
begin
while (s1^ <> 0) and (s2^ <> 0) and (s1^ = s2^) do
begin
Inc(Result);
Inc(s1);
Inc(s2);
end;
end;
end;
end;
function SameCharsU(s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
function CompareSubSeq: Integer;
var
ACharSize1, ACharSize2: Integer;
begin
ACharSize1 := CharSizeU(s1) - 1;
ACharSize2 := CharSizeU(s2) - 1;
Result := 0;
if ACharSize1 = ACharSize2 then
begin
Inc(s1);
Inc(s2);
while (ACharSize1 > 0) and (s1^ = s2^) do
begin
Inc(s1);
Inc(s2);
end;
if ACharSize1 = 0 then
Result := ACharSize2 + 1;
end;
end;
var
ACharSize: Integer;
begin
Result := 0;
if (s1 <> nil) and (s2 <> nil) then
begin
if AIgnoreCase then
begin
while (s1^ <> 0) and (s2^ <> 0) and
((s1^ = s2^) or (CharUpperA(s1^) = CharUpperA(s2^))) do
begin
ACharSize := CompareSubSeq;
if ACharSize <> 0 then
begin
Inc(Result);
Inc(s1, ACharSize);
Inc(s2, ACharSize);
end
else
Break;
end;
end
else
begin
while (s1^ <> 0) and (s2^ <> 0) and (s1^ = s2^) do
begin
ACharSize := CompareSubSeq;
if ACharSize <> 0 then
begin
Inc(Result);
Inc(s1, ACharSize);
Inc(s2, ACharSize);
end
else
Break;
end;
end;
end;
end;
function SameCharsW(s1, s2: PQCharW; AIgnoreCase: Boolean): Integer;
begin
Result := 0;
if (s1 <> nil) and (s2 <> nil) then
begin
if AIgnoreCase then
begin
while (s1^ <> #0) and (s2^ <> #0) and
((s1^ = s2^) or (CharUpperW(s1^) = CharUpperW(s2^))) do
begin
Inc(Result);
Inc(s1);
Inc(s2);
end;
end
else
begin
while (s1^ <> #0) and (s2^ <> #0) and (s1^ = s2^) do
begin
Inc(Result);
Inc(s1);
Inc(s2);
end;
end;
end;
end;
function DetectTextEncoding(const p: Pointer; l: Integer; var b: Boolean)
: TTextEncoding;
var
pAnsi: PByte;
pWide: PWideChar;
I, AUtf8CharSize: Integer;
const
NoUtf8Char: array [0 .. 3] of Byte = ($C1, $AA, $CD, $A8); // ANSI编码的联通
function IsUtf8Order(var ACharSize: Integer): Boolean;
var
I: Integer;
ps: PByte;
const
Utf8Masks: array [0 .. 4] of Byte = ($C0, $E0, $F0, $F8, $FC);
begin
ps := pAnsi;
ACharSize := CharSizeU(PQCharA(ps));
Result := false;
if ACharSize > 1 then
begin
I := ACharSize - 2;
if ((Utf8Masks[I] and ps^) = Utf8Masks[I]) then
begin
Inc(ps);
Result := True;
for I := 1 to ACharSize - 1 do
begin
if (ps^ and $80) <> $80 then
begin
Result := false;
Break;
end;
Inc(ps);
end;
end;
end;
end;
begin
Result := teAnsi;
b := false;
if l >= 2 then
begin
pAnsi := PByte(p);
pWide := PWideChar(p);
b := True;
if pWide^ = #$FEFF then
Result := teUnicode16LE
else if pWide^ = #$FFFE then
Result := teUnicode16BE
else if l >= 3 then
begin
if (pAnsi^ = $EF) and (PByte(IntPtr(pAnsi) + 1)^ = $BB) and
(PByte(IntPtr(pAnsi) + 2)^ = $BF) then // UTF-8编码
Result := teUTF8
else // 检测字符中是否有符合UFT-8编码规则的字符,11...
begin
b := false;
Result := teUnknown; // 假设为UTF8编码,然后检测是否有不符合UTF-8编码的序列
I := 0;
Dec(l, 2);
while I <= l do
begin
if (pAnsi^ and $80) <> 0 then
// 高位为1
begin
if (l - I >= 4) then
begin
if CompareMem(pAnsi, @NoUtf8Char[0], 4) then
// 联通?是则忽略掉,不做UTF-8编码的判断依据
begin
Inc(pAnsi, 4);
Inc(I, 4);
Result := teAnsi;
continue;
end;
end;
if IsUtf8Order(AUtf8CharSize) then
begin
Inc(pAnsi, AUtf8CharSize);
Result := teUTF8;
Break;
end
else
begin
Result := teAnsi;
Break;
end;
end
else
begin
if pAnsi^ = 0 then // 00 xx (xx<128) 高位在前,是BE编码
begin
if PByte(IntPtr(pAnsi) + 1)^ < 128 then
begin
Result := teUnicode16BE;
Break;
end;
end
else if PByte(IntPtr(pAnsi) + 1)^ = 0 then
// xx 00 低位在前,是LE编码
begin
Result := teUnicode16LE;
Break;
end;
Inc(pAnsi);
Inc(I);
end;
if Result = teUnknown then
Result := teAnsi;
end;
end;
end;
end;
end;
function LoadTextA(const AFileName: String; AEncoding: TTextEncoding): QStringA;
var
AStream: TStream;
begin
AStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadTextA(AStream, AEncoding);
finally
AStream.Free;
end;
end;
procedure ExchangeByteOrder(p: PQCharA; l: Integer);
var
pe: PQCharA;
c: QCharA;
begin
pe := p;
Inc(pe, l);
while IntPtr(p) < IntPtr(pe) do
begin
c := p^;
p^ := PQCharA(IntPtr(p) + 1)^;
PQCharA(IntPtr(p) + 1)^ := c;
Inc(p, 2);
end;
end;
function ExchangeByteOrder(V: Smallint): Smallint;
var
pv: array [0 .. 1] of Byte absolute V;
pd: array [0 .. 1] of Byte absolute Result;
begin
pd[0] := pv[1];
pd[1] := pv[0];
end;
function ExchangeByteOrder(V: Word): Word;
var
pv: array [0 .. 1] of Byte absolute V;
pd: array [0 .. 1] of Byte absolute Result;
begin
pd[0] := pv[1];
pd[1] := pv[0];
end;
function ExchangeByteOrder(V: Integer): Integer;
var
pv: array [0 .. 3] of Byte absolute V;
pd: array [0 .. 3] of Byte absolute Result;
begin
pd[0] := pv[3];
pd[1] := pv[2];
pd[2] := pv[1];
pd[3] := pv[0];
end;
function ExchangeByteOrder(V: Cardinal): Cardinal;
var
pv: array [0 .. 3] of Byte absolute V;
pd: array [0 .. 3] of Byte absolute Result;
begin
pd[0] := pv[3];
pd[1] := pv[2];
pd[2] := pv[1];
pd[3] := pv[0];
end;
function ExchangeByteOrder(V: Int64): Int64;
var
pv: array [0 .. 7] of Byte absolute V;
pd: array [0 .. 7] of Byte absolute Result;
begin
pd[0] := pv[7];
pd[1] := pv[6];
pd[2] := pv[5];
pd[3] := pv[4];
pd[4] := pv[3];
pd[5] := pv[2];
pd[6] := pv[1];
pd[7] := pv[0];
end;
function ExchangeByteOrder(V: Single): Single;
var
pv: array [0 .. 3] of Byte absolute V;
pd: array [0 .. 3] of Byte absolute Result;
begin
pd[0] := pv[3];
pd[1] := pv[2];
pd[2] := pv[1];
pd[3] := pv[0];
end;
function ExchangeByteOrder(V: Double): Double;
var
pv: array [0 .. 7] of Byte absolute V;
pd: array [0 .. 7] of Byte absolute Result;
begin
pd[0] := pv[7];
pd[1] := pv[6];
pd[2] := pv[5];
pd[3] := pv[4];
pd[4] := pv[3];
pd[5] := pv[2];
pd[6] := pv[1];
pd[7] := pv[0];
end;
function LoadTextA(AStream: TStream; AEncoding: TTextEncoding): QStringA;
var
ASize: Integer;
ABuffer: TBytes;
ABomExists: Boolean;
begin
ASize := AStream.Size - AStream.Position;
if ASize > 0 then
begin
SetLength(ABuffer, ASize);
AStream.ReadBuffer((@ABuffer[0])^, ASize);
if AEncoding in [teUnknown, teAuto] then
AEncoding := DetectTextEncoding(@ABuffer[0], ASize, ABomExists)
else if ASize >= 2 then
begin
case AEncoding of
teUnicode16LE:
ABomExists := (ABuffer[0] = $FF) and (ABuffer[1] = $FE);
teUnicode16BE:
ABomExists := (ABuffer[1] = $FE) and (ABuffer[1] = $FF);
teUTF8:
begin
if ASize >= 3 then
ABomExists := (ABuffer[0] = $EF) and (ABuffer[1] = $BB) and
(ABuffer[2] = $BF)
else
ABomExists := false;
end;
end;
end
else
ABomExists := false;
if AEncoding = teAnsi then
Result := ABuffer
else if AEncoding = teUTF8 then
begin
if ABomExists then
begin
if ASize > 3 then
Result := AnsiEncode(Utf8Decode(@ABuffer[3], ASize - 3))
else
Result.Length := 0;
end
else
Result := AnsiEncode(Utf8Decode(@ABuffer[0], ASize));
end
else
begin
if AEncoding = teUnicode16BE then
ExchangeByteOrder(@ABuffer[0], ASize);
if ABomExists then
Result := AnsiEncode(PQCharW(@ABuffer[2]), (ASize - 2) shr 1)
else
Result := AnsiEncode(PQCharW(@ABuffer[0]), ASize shr 1);
end;
end
else
Result.Length := 0;
end;
function LoadTextU(const AFileName: String; AEncoding: TTextEncoding): QStringA;
var
AStream: TStream;
begin
AStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadTextU(AStream, AEncoding);
finally
AStream.Free;
end;
end;
function LoadTextU(AStream: TStream; AEncoding: TTextEncoding): QStringA;
var
ASize: Integer;
ABuffer: TBytes;
ABomExists: Boolean;
begin
ASize := AStream.Size - AStream.Position;
if ASize > 0 then
begin
SetLength(ABuffer, ASize);
AStream.ReadBuffer((@ABuffer[0])^, ASize);
if AEncoding in [teUnknown, teAuto] then
AEncoding := DetectTextEncoding(@ABuffer[0], ASize, ABomExists)
else if ASize >= 2 then
begin
case AEncoding of
teUnicode16LE:
ABomExists := (ABuffer[0] = $FF) and (ABuffer[1] = $FE);
teUnicode16BE:
ABomExists := (ABuffer[1] = $FE) and (ABuffer[1] = $FF);
teUTF8:
begin
if ASize > 3 then
ABomExists := (ABuffer[0] = $EF) and (ABuffer[1] = $BB) and
(ABuffer[2] = $BF)
else
ABomExists := false;
end;
end;
end
else
ABomExists := false;
if AEncoding = teAnsi then
Result := qstring.Utf8Encode(AnsiDecode(@ABuffer[0], ASize))
else if AEncoding = teUTF8 then
begin
if ABomExists then
begin
Dec(ASize, 3);
Result.From(@ABuffer[0], 3, ASize);
end
else
Result := ABuffer;
if ASize > 0 then
Result.FValue[0] := 1; // UTF-8
end
else
begin
if AEncoding = teUnicode16BE then
ExchangeByteOrder(@ABuffer[0], ASize);
if ABomExists then
Result := qstring.Utf8Encode(PQCharW(@ABuffer[2]), (ASize - 2) shr 1)
else
Result := qstring.Utf8Encode(PQCharW(@ABuffer[0]), ASize shr 1);
end;
end
else
begin
Result.Length := 0;
Result.FValue[0] := 1;
end;
end;
function LoadTextW(const AFileName: String; AEncoding: TTextEncoding): QStringW;
var
AStream: TStream;
begin
AStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadTextW(AStream, AEncoding);
finally
AStream.Free;
end;
end;
function DecodeText(p: Pointer; ASize: Integer; AEncoding: TTextEncoding)
: QStringW;
var
ABomExists: Boolean;
pb: PByte;
pe: PQCharA;
function ByteOf(AOffset: Integer): Byte;
begin
Result := PByte(IntPtr(pb) + AOffset)^;
end;
begin
pb := p;
if ASize >= 2 then
begin
// 不管是否指定编码,强制检测BOM头,避免由于编码指定不符造成问题
if (ByteOf(0) = $FF) and (ByteOf(1) = $FE) then
begin
AEncoding := teUnicode16LE;
Inc(pb, 2);
Dec(ASize, 2);
end
else if (ByteOf(0) = $FE) and (ByteOf(1) = $FF) then
begin
AEncoding := teUnicode16BE;
Inc(pb, 2);
Dec(ASize, 2);
end
else if (ASize > 2) and (ByteOf(0) = $EF) and (ByteOf(1) = $BB) and
(ByteOf(2) = $BF) then
begin
AEncoding := teUTF8;
Inc(pb, 3);
Dec(ASize, 3);
end
else if AEncoding in [teUnknown, teAuto] then // No BOM
AEncoding := DetectTextEncoding(pb, ASize, ABomExists);
if ASize > 0 then
begin
if AEncoding = teAnsi then
Result := AnsiDecode(PQCharA(pb), ASize)
else if AEncoding = teUTF8 then
begin
if not Utf8Decode(PQCharA(pb), ASize, Result, pe) then
Result := AnsiDecode(PQCharA(pb), ASize);
end
else
begin
if AEncoding = teUnicode16BE then
ExchangeByteOrder(PQCharA(pb), ASize);
SetLength(Result, ASize shr 1);
Move(pb^, PQCharW(Result)^, ASize);
end;
end
else
SetLength(Result, 0);
end
else if ASize > 0 then
Result := WideChar(pb^)
else
SetLength(Result, 0);
end;
function LoadTextW(AStream: TStream; AEncoding: TTextEncoding)
: QStringW; overload;
var
AReaded, ASize: Int64;
ANeedRead: Integer;
ABuffer: TBytes;
begin
ASize := AStream.Size - AStream.Position;
if ASize > 0 then
begin
SetLength(ABuffer, ASize);
AReaded := 0;
repeat
if ASize - AReaded > MaxInt then
ANeedRead := MaxInt
else
ANeedRead := ASize - AReaded;
AStream.ReadBuffer((@ABuffer[AReaded])^, ANeedRead);
Inc(AReaded, ANeedRead);
until AReaded = ASize;
Result := DecodeText(@ABuffer[0], ASize, AEncoding);
end
else
SetLength(Result, 0);
end;
procedure SaveTextA(const AFileName: String; const S: QStringA);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(AFileName, fmCreate);
try
SaveTextA(AStream, S);
finally
AStream.Free;
end;
end;
procedure SaveTextA(AStream: TStream; const S: QStringA);
procedure Utf8Save;
var
T: QStringA;
begin
T := AnsiEncode(Utf8Decode(S));
AStream.WriteBuffer(PQCharA(T)^, T.Length);
end;
begin
if not S.IsUtf8 then
AStream.WriteBuffer(PQCharA(S)^, S.Length)
else
Utf8Save;
end;
procedure SaveTextU(const AFileName: String; const S: QStringA;
AWriteBom: Boolean);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(AFileName, fmCreate);
try
SaveTextU(AStream, S, AWriteBom);
finally
AStream.Free;
end;
end;
procedure SaveTextU(const AFileName: String; const S: QStringW;
AWriteBom: Boolean); overload;
begin
SaveTextU(AFileName, qstring.Utf8Encode(S), AWriteBom);
end;
procedure SaveTextU(AStream: TStream; const S: QStringA; AWriteBom: Boolean);
procedure WriteBom;
var
ABom: TBytes;
begin
SetLength(ABom, 3);
ABom[0] := $EF;
ABom[1] := $BB;
ABom[2] := $BF;
AStream.WriteBuffer(ABom[0], 3);
end;
procedure SaveAnsi;
var
T: QStringA;
begin
T := qstring.Utf8Encode(AnsiDecode(S));
AStream.WriteBuffer(PQCharA(T)^, T.Length);
end;
begin
if AWriteBom then
WriteBom;
if S.IsUtf8 then
AStream.WriteBuffer(PQCharA(S)^, S.Length)
else
SaveAnsi;
end;
procedure SaveTextU(AStream: TStream; const S: QStringW;
AWriteBom: Boolean); overload;
begin
SaveTextU(AStream, qstring.Utf8Encode(S), AWriteBom);
end;
procedure SaveTextW(const AFileName: String; const S: QStringW;
AWriteBom: Boolean);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(AFileName, fmCreate);
try
SaveTextW(AStream, S, AWriteBom);
finally
AStream.Free;
end;
end;
procedure SaveTextW(AStream: TStream; const S: QStringW; AWriteBom: Boolean);
procedure WriteBom;
var
bom: Word;
begin
bom := $FEFF;
AStream.WriteBuffer(bom, 2);
end;
begin
if AWriteBom then
WriteBom;
AStream.WriteBuffer(PQCharW(S)^, System.Length(S) shl 1);
end;
procedure SaveTextWBE(AStream: TStream; const S: QStringW; AWriteBom: Boolean);
var
pw, pe: PWord;
w: Word;
ABuilder: TQStringCatHelperW;
begin
pw := PWord(PQCharW(S));
pe := pw;
Inc(pe, Length(S));
ABuilder := TQStringCatHelperW.Create(IntPtr(pe) - IntPtr(pw));
try
while IntPtr(pw) < IntPtr(pe) do
begin
w := (pw^ shr 8) or (pw^ shl 8);
ABuilder.Cat(@w, 1);
Inc(pw);
end;
if AWriteBom then
AStream.WriteBuffer(#$FE#$FF, 2);
AStream.WriteBuffer(ABuilder.FStart^, Length(S) shl 1);
finally
FreeObject(ABuilder);
end;
end;
function StrStrA(s1, s2: PQCharA): PQCharA;
function DoSearch: PQCharA;
var
ps1, ps2: PQCharA;
begin
ps1 := s1;
ps2 := s2;
Inc(ps1);
Inc(ps2);
while ps2^ <> 0 do
begin
if ps1^ = ps2^ then
begin
Inc(ps1);
Inc(ps2);
end
else
Break;
end;
if ps2^ = 0 then
Result := s1
else
Result := nil;
end;
begin
{$IFDEF MSWINDOWS}
if Assigned(VCStrStr) then
begin
Result := VCStrStr(s1, s2);
Exit;
end;
{$ENDIF}
Result := nil;
if (s1 <> nil) and (s2 <> nil) then
begin
while s1^ <> 0 do
begin
if s1^ = s2^ then
begin
Result := DoSearch;
if Result <> nil then
Exit;
end;
Inc(s1);
end;
end;
end;
function StrIStrA(s1, s2: PQCharA): PQCharA;
var
ws2: QStringA;
function DoSearch: PQCharA;
var
ps1, ps2: PQCharA;
begin
ps1 := s1;
ps2 := PQCharA(ws2);
Inc(ps1);
Inc(ps2);
while ps2^ <> 0 do
begin
if CharUpperA(ps1^) = ps2^ then
begin
Inc(ps1);
Inc(ps2);
end
else
Break;
end;
if ps2^ = 0 then
Result := s1
else
Result := nil;
end;
begin
Result := nil;
if (s1 <> nil) and (s2 <> nil) then
begin
ws2 := QStringA.UpperCase(s2);
while s1^ <> 0 do
begin
if s1^ = s2^ then
begin
Result := DoSearch;
if Result <> nil then
Exit;
end;
Inc(s1);
end;
end;
end;
function StrStrU(s1, s2: PQCharA): PQCharA;
begin
Result := StrStrA(s1, s2);
end;
function StrIStrU(s1, s2: PQCharA): PQCharA;
begin
Result := StrIStrA(s1, s2);
end;
function StrStrW(s1, s2: PQCharW): PQCharW;
var
I: Integer;
begin
{$IFDEF MSWINDOWS}
if Assigned(VCStrStrW) then
begin
Result := VCStrStrW(s1, s2);
Exit;
end;
{$ENDIF}
if (s2 = nil) or (s2^ = #0) then
Result := s1
else
begin
Result := nil;
while s1^ <> #0 do
begin
if s1^ = s2^ then
begin
I := 1;
while s2[I] <> #0 do
begin
if s1[I] = s2[I] then
Inc(I)
else
Break;
end;
if s2[I] = #0 then
begin
Result := s1;
Break;
end;
end;
Inc(s1);
end;
end;
end;
function StrIStrW(s1, s2: PQCharW): PQCharW;
var
I: Integer;
ws2: QStringW;
begin
Result := nil;
if (s1 = nil) or (s2 = nil) then
Exit;
ws2 := UpperCase(s2);
s2 := PWideChar(ws2);
while s1^ <> #0 do
begin
if CharUpperW(s1^) = s2^ then
begin
I := 1;
while s2[I] <> #0 do
begin
if CharUpperW(s1[I]) = s2[I] then
Inc(I)
else
Break;
end;
if s2[I] = #0 then
begin
Result := s1;
Break;
end;
end;
Inc(s1);
end;
end;
function PosA(sub, S: PQCharA; AIgnoreCase: Boolean;
AStartPos: Integer): Integer;
begin
if AStartPos > 0 then
Inc(S, AStartPos - 1);
if AIgnoreCase then
sub := StrIStrA(S, sub)
else
sub := StrStrA(S, sub);
if Assigned(sub) then
Result := (IntPtr(sub) - IntPtr(S)) + AStartPos
else
Result := 0;
end;
function PosA(sub, S: QStringA; AIgnoreCase: Boolean;
AStartPos: Integer): Integer;
begin
Result := PosA(PQCharA(sub), PQCharA(S), AIgnoreCase, AStartPos);
end;
function PosW(sub, S: PQCharW; AIgnoreCase: Boolean;
AStartPos: Integer): Integer;
begin
if AStartPos > 0 then
Inc(S, AStartPos - 1);
if AIgnoreCase then
sub := StrIStrW(S, sub)
else
sub := StrStrW(S, sub);
if Assigned(sub) then
Result := ((IntPtr(sub) - IntPtr(S)) shr 1) + AStartPos
else
Result := 0;
end;
function PosW(sub, S: QStringW; AIgnoreCase: Boolean; AStartPos: Integer)
: Integer; overload;
begin
Result := PosW(PQCharW(sub), PQCharW(S), AIgnoreCase, AStartPos);
end;
function StrDupX(const S: PQCharW; ACount: Integer): QStringW;
begin
SetLength(Result, ACount);
Move(S^, PQCharW(Result)^, ACount shl 1);
end;
function StrDupW(const S: PQCharW; AOffset: Integer; const ACount: Integer)
: QStringW;
var
c, ACharSize: Integer;
p, pds, pd: PQCharW;
begin
c := 0;
p := S + AOffset;
SetLength(Result, 16384);
pd := PQCharW(Result);
pds := pd;
while (p^ <> #0) and (c < ACount) do
begin
ACharSize := CharSizeW(p);
AOffset := pd - pds;
if AOffset + ACharSize = Length(Result) then
begin
SetLength(Result, Length(Result) shl 1);
pds := PQCharW(Result);
pd := pds + AOffset;
end;
Inc(c);
pd^ := p^;
if ACharSize = 2 then
pd[1] := p[1];
Inc(pd, ACharSize);
Inc(p, ACharSize);
end;
SetLength(Result, pd - pds);
end;
function StrCmpA(const s1, s2: PQCharA; AIgnoreCase: Boolean): Integer;
var
p1, p2: PQCharA;
c1, c2: QCharA;
begin
p1 := s1;
p2 := s2;
if AIgnoreCase then
begin
while (p1^ <> 0) and (p2^ <> 0) do
begin
if p1^ <> p2^ then
begin
if (p1^ >= Ord('a')) and (p1^ <= Ord('z')) then
c1 := p1^ xor $20
else
c1 := p1^;
if (p2^ >= Ord('a')) and (p2^ <= Ord('z')) then
c2 := p2^ xor $20
else
c2 := p2^;
Result := Ord(c1) - Ord(c2);
if Result <> 0 then
Exit;
end;
Inc(p1);
Inc(p2);
end;
Result := Ord(p1^) - Ord(p2^);
end
else
begin
while (p1^ <> 0) and (p2^ <> 0) do
begin
Result := p1^ - p2^;
if Result <> 0 then
Exit;
Inc(p1);
Inc(p2);
end;
Result := Ord(p1^) - Ord(p2^);
end;
end;
function StrCmpW(const s1, s2: PQCharW; AIgnoreCase: Boolean): Integer;
var
p1, p2: PQCharW;
c1, c2: QCharW;
begin
p1 := s1;
p2 := s2;
if AIgnoreCase then
begin
while (p1^ <> #0) and (p2^ <> #0) do
begin
if p1^ <> p2^ then
begin
if (p1^ >= 'a') and (p1^ <= 'z') then
c1 := WideChar(Word(p1^) xor $20)
else
c1 := p1^;
if (p2^ >= 'a') and (p2^ <= 'z') then
c2 := WideChar(Word(p2^) xor $20)
else
c2 := p2^;
Result := Ord(c1) - Ord(c2);
if Result <> 0 then
Exit;
end;
Inc(p1);
Inc(p2);
end;
Result := Ord(p1^) - Ord(p2^);
end
else
begin
while (p1^ <> #0) and (p2^ <> #0) do
begin
if p1^ <> p2^ then
begin
Result := Ord(p1^) - Ord(p2^);
if Result <> 0 then
Exit;
end;
Inc(p1);
Inc(p2);
end;
Result := Ord(p1^) - Ord(p2^);
end;
end;
function StrNCmpW(const s1, s2: PQCharW; AIgnoreCase: Boolean;
ALength: Integer): Integer;
var
p1, p2: PQCharW;
c1, c2: QCharW;
begin
p1 := s1;
p2 := s2;
if AIgnoreCase then
begin
while ALength > 0 do
begin
if p1^ <> p2^ then
begin
if (p1^ >= 'a') and (p1^ <= 'z') then
c1 := WideChar(Word(p1^) xor $20)
else
c1 := p1^;
if (p2^ >= 'a') and (p2^ <= 'z') then
c2 := WideChar(Word(p2^) xor $20)
else
c2 := p2^;
Result := Ord(c1) - Ord(c2);
if Result <> 0 then
Exit;
end;
Inc(p1);
Inc(p2);
Dec(ALength);
end;
end
else
begin
while ALength > 0 do
begin
if p1^ <> p2^ then
begin
Result := Ord(p1^) - Ord(p2^);
if Result <> 0 then
Exit;
end;
Inc(p1);
Inc(p2);
Dec(ALength);
end;
end;
if ALength = 0 then
Result := 0
else
Result := Ord(p1^) - Ord(p2^);
end;
/// <summary>使用自然语言规则比较字符串</summary>
/// <param name="s1">第一个要比较的字符串</param>
/// <param name="s2">第二个要比较的字符串</param>
/// <param name="AIgnoreCase">比较时是否忽略大小写</param>
/// <param name="AIgnoreSpace">比较时是否忽略空白字符</param>
/// <remarks>本比较考虑中文全角的情况,认为中文全角符号和对应的半角符号是相等的值</remarks>
function NaturalCompareW(s1, s2: PQCharW;
AIgnoreCase, AIgnoreSpace: Boolean): Integer;
var
N1, N2: Int64;
L1, L2: Integer;
c1, c2: QCharW;
function FetchNumeric(p: PQCharW; var AResult: Int64;
var ALen: Integer): Boolean;
var
ps: PQCharW;
const
Full0: WideChar = #65296; // 全角0
Full9: WideChar = #65305; // 全角9
begin
AResult := 0;
ps := p;
while p^ <> #0 do
begin
while IsSpaceW(p) do
Inc(p);
if (p^ >= '0') and (p^ <= '9') then // 半角数字
AResult := AResult * 10 + Ord(p^) - Ord('0')
else if (p^ >= Full0) and (p^ <= Full9) then // 全角数字
AResult := AResult * 10 + Ord(p^) - Ord(Full0)
else
Break;
Inc(p);
end;
Result := ps <> p;
ALen := (IntPtr(p) - IntPtr(ps)) shr 1;
end;
function FullToHalfChar(c: Word): QCharW;
begin
if (c = $3000) then
// 全角空格' '
Result := QCharW($20)
else if (c >= $FF01) and (c <= $FF5E) then
Result := QCharW($21 + (c - $FF01))
else
Result := QCharW(c);
end;
function CompareChar: Integer;
begin
if AIgnoreCase then
begin
c1 := CharUpperW(FullToHalfChar(Ord(s1^)));
c2 := CharUpperW(FullToHalfChar(Ord(s2^)));
end
else
begin
c1 := FullToHalfChar(Ord(s1^));
c2 := FullToHalfChar(Ord(s2^));
end;
Result := Ord(c1) - Ord(c2);
end;
begin
if Assigned(s1) then
begin
if not Assigned(s2) then
begin
Result := 1;
Exit;
end;
while (s1^ <> #0) and (s2^ <> #0) do
begin
if s1^ <> s2^ then
begin
while IsSpaceW(s1) do
Inc(s1);
while IsSpaceW(s1) do
Inc(s2);
// 检查是否是数字
L1 := 0;
L2 := 0;
if FetchNumeric(s1, N1, L1) and FetchNumeric(s2, N2, L2) then
begin
Result := N1 - N2;
if Result <> 0 then
Exit
else
begin
Inc(s1, L1);
Inc(s2, L2);
end;
end
else
begin
Result := CompareChar;
if Result = 0 then
begin
Inc(s1);
Inc(s2);
end
else
Exit;
end;
end
else // 如果想等,即使是数字,肯定也是相等的
begin
Inc(s1);
Inc(s2);
end;
end;
Result := CompareChar;
end
else if Assigned(s2) then
Result := -1
else
Result := 0;
end;
function IsHexChar(c: QCharW): Boolean; inline;
begin
Result := ((c >= '0') and (c <= '9')) or ((c >= 'a') and (c <= 'f')) or
((c >= 'A') and (c <= 'F'));
end;
function IsOctChar(c: WideChar): Boolean; inline;
begin
Result := (c >= '0') and (c <= '7');
end;
function HexValue(c: QCharW): Integer;
begin
if (c >= '0') and (c <= '9') then
Result := Ord(c) - Ord('0')
else if (c >= 'a') and (c <= 'f') then
Result := 10 + Ord(c) - Ord('a')
else if (c >= 'A') and (c <= 'F') then
Result := 10 + Ord(c) - Ord('A')
else
Result := -1;
end;
function HexChar(V: Byte): QCharW;
begin
Result := HexChars[V];
end;
function TryStrToGuid(const S: QStringW; var AGuid: TGuid): Boolean;
var
p, ps: PQCharW;
l: Int64;
begin
l := Length(S);
p := PWideChar(S);
if (l = 38) or (l = 36) then
begin
// {0BCBAAFF-15E6-451D-A8E8-0D98AC48C364}
ps := p;
if p^ = '{' then
Inc(p);
if (ParseHex(p, l) <> 8) or (p^ <> '-') then
begin
Result := false;
Exit;
end;
AGuid.D1 := l;
Inc(p);
if (ParseHex(p, l) <> 4) or (p^ <> '-') then
begin
Result := false;
Exit;
end;
AGuid.D2 := l;
Inc(p);
if (ParseHex(p, l) <> 4) or (p^ <> '-') then
begin
Result := false;
Exit;
end;
AGuid.D3 := l;
Inc(p);
// 0102-030405060708
// 剩下的16个字符
l := 0;
while IsHexChar(p[0]) do
begin
if IsHexChar(p[1]) then
begin
AGuid.D4[l] := (HexValue(p[0]) shl 4) + HexValue(p[1]);
Inc(l);
Inc(p, 2);
end
else
begin
Result := false;
Exit;
end;
end;
if (l <> 2) or (p^ <> '-') then
begin
Result := false;
Exit;
end;
Inc(p);
while IsHexChar(p[0]) do
begin
if IsHexChar(p[1]) then
begin
AGuid.D4[l] := (HexValue(p[0]) shl 4) + HexValue(p[1]);
Inc(l);
Inc(p, 2);
end
else
begin
Result := false;
Exit;
end;
end;
if (l = 8) then
begin
if ps^ = '{' then
Result := (p[0] = '}') and (p[1] = #0)
else
Result := (p[0] = #0);
end
else
Result := false;
end
else
Result := false;
end;
function TryStrToIPV4(const S: QStringW; var AIPV4:
{$IFDEF MSWINDOWS}Integer{$ELSE}Cardinal{$ENDIF}): Boolean;
var
p: PQCharW;
dc: Integer;
pd: PByte;
begin
dc := 0;
AIPV4 := 0;
p := PQCharW(S);
pd := PByte(@AIPV4);
while p^ <> #0 do
begin
if (p^ >= '0') and (p^ <= '9') then
pd^ := pd^ * 10 + Ord(p^) - Ord('0')
else if p^ = '.' then
begin
Inc(dc);
if dc > 3 then
Break;
Inc(pd);
end
else
Break;
Inc(p);
end;
Result := (dc = 3) and (p^ = #0);
end;
procedure InlineMove(var d, S: Pointer; l: Integer); inline;
begin
if l >= 16 then
begin
Move(S^, d^, l);
Inc(PByte(d), l);
Inc(PByte(S), l);
end
else
begin
if l >= 8 then
begin
PInt64(d)^ := PInt64(S)^;
Inc(PInt64(d));
Inc(PInt64(S));
Dec(l, 8);
end;
if l >= 4 then
begin
PInteger(d)^ := PInteger(S)^;
Inc(PInteger(d));
Inc(PInteger(S));
Dec(l, 4);
end;
if l >= 2 then
begin
PSmallint(d)^ := PSmallint(S)^;
Inc(PSmallint(d));
Inc(PSmallint(S));
Dec(l, 2);
end;
if l = 1 then
begin
PByte(d)^ := PByte(S)^;
Inc(PByte(d));
Inc(PByte(S));
end;
end;
end;
function StringReplaceWX(const S, Old, New: QStringW; AFlags: TReplaceFlags)
: QStringW;
var
ps, pse, pr, pd, po, pn, pns: PQCharW;
LO, LN, LS, I, ACount: Integer;
SS, SOld: QStringW;
AFounds: array of Integer;
AReplaceOnce: Boolean;
begin
LO := Length(Old);
LS := Length(S);
if (LO = 0) or (LS = 0) or (Old = New) then
begin
Result := S;
Exit;
end;
LN := Length(New);
if rfIgnoreCase in AFlags then
begin
SOld := UpperCase(Old);
if SOld = Old then // 大小写一致,不需要额外进行大写转换
SS := S
else
begin
SS := UpperCase(S);
LS := Length(SS);
end;
end
else
begin
SOld := Old;
SS := S;
end;
ps := Pointer(SS);
pn := ps;
po := Pointer(SOld);
ACount := 0;
AReplaceOnce := not(rfReplaceAll in AFlags);
repeat
pr := StrStrW(pn, po);
if Assigned(pr) then
begin
if ACount = 0 then
SetLength(AFounds, 32)
else
SetLength(AFounds, ACount shl 1);
AFounds[ACount] := IntPtr(pr) - IntPtr(pn);
Inc(ACount);
pn := pr;
Inc(pn, LO);
end
else
Break;
until AReplaceOnce or (pn^ = #0);
if ACount = 0 then // 没有找到需要替换的内容,直接返回原始字符串
Result := S
else
begin
// 计算需要分配的目标内存
SetLength(Result, LS + (LN - LO) * ACount);
pd := Pointer(Result);
pn := Pointer(New);
pns := pn;
ps := Pointer(S);
pse := ps;
Inc(pse, LS);
LN := LN shl 1;
for I := 0 to ACount - 1 do
begin
InlineMove(Pointer(pd), Pointer(ps), AFounds[I]);
InlineMove(Pointer(pd), Pointer(pn), LN);
Inc(ps, LO);
pn := pns;
end;
InlineMove(Pointer(pd), Pointer(ps), IntPtr(pse) - IntPtr(ps));
end;
end;
function StringReplaceW(const S, Old, New: QStringW; AFlags: TReplaceFlags)
: QStringW;
{$IF RTLVersion>30}// Berlin 开始直接使用系统自带的替换函数
begin
Result := StringReplace(S, Old, New, AFlags);
end;
{$ELSE}
var
ps, pse, pds, pr, pd, po, pn: PQCharW;
l, LO, LN, LS, LR: Integer;
AReplaceOnce: Boolean;
begin
LO := Length(Old);
LN := Length(New);
if LO = LN then
begin
if Old = New then
begin
Result := S;
Exit;
end;
end;
LS := Length(S);
if (LO > 0) and (LS >= LO) then
begin
AReplaceOnce := not(rfReplaceAll in AFlags);
// LO=LN,则不变LR=LS,假设全替换,也不过是原长度
// LO<LN,则LR=LS+(LS*LN)/LO,假设全替换的长度
// LO>LN,则LR=LS,假设一次都不替换,也不过是原长度
if LO >= LN then
LR := LS
else if AReplaceOnce then
LR := LS + (LN - LO)
else
LR := LS + 1 + LS * LN div LO;
SetLength(Result, LR);
ps := PQCharW(S);
pse := ps + LS;
pd := PQCharW(Result);
pds := pd;
po := PQCharW(Old);
pn := PQCharW(New);
repeat
if rfIgnoreCase in AFlags then
pr := StrIStrW(ps, po)
else
pr := StrStrW(ps, po);
if pr <> nil then
begin
l := IntPtr(pr) - IntPtr(ps);
Move(ps^, pd^, l);
Inc(pd, l shr 1);
Inc(pr, LO);
Move(pn^, pd^, LN shl 1);
Inc(pd, LN);
ps := pr;
end;
until (pr = nil) or AReplaceOnce;
// 将剩余部分合并到目标
l := IntPtr(pse) - IntPtr(ps);
Move(ps^, pd^, l);
Inc(pd, l shr 1);
SetLength(Result, pd - pds);
end
else
Result := S;
end;
{$IFEND}
function StringReplaceW(const S: QStringW; const AChar: QCharW;
AFrom, ACount: Integer): QStringW;
var
p, pd: PQCharW;
l: Integer;
begin
l := Length(S);
SetLength(Result, l);
if (l > 0) and (l > AFrom + 1) then
begin
p := PQCharW(S);
pd := PQCharW(Result);
while (p^ <> #0) and (AFrom > 0) do
begin
pd^ := p^;
if (p^ > #$D800) and (p^ <= #$DFFF) then
begin
Inc(pd);
Inc(p);
pd^ := p^;
end;
Inc(p);
Inc(pd);
Dec(AFrom);
end;
while (p^ <> #0) and (ACount > 0) do
begin
pd^ := AChar;
if (p^ > #$D800) and (p^ <= #$DFFF) then
Inc(p);
Inc(p);
Inc(pd);
Dec(ACount);
end;
while p^ <> #0 do
begin
pd^ := p^;
Inc(p);
Inc(pd);
end;
end;
end;
function StringReplaceWithW(const S, AStartTag, AEndTag, AReplaced: QStringW;
AWithTag, AIgnoreCase: Boolean; AMaxTimes: Cardinal): QStringW;
var
po, pe, pws, pwe, pd, pStart, pEnd, pReplaced: PQCharW;
l, dl, LS, LE, LR: Integer;
StrStrFunc: TStrStrFunction;
begin
l := Length(S);
LS := Length(AStartTag);
LE := Length(AEndTag);
if (l >= LS + LE) and (AMaxTimes > 0) then
begin
LR := Length(AReplaced);
po := PQCharW(S);
pe := po + l;
pStart := PQCharW(AStartTag);
pEnd := PQCharW(AEndTag);
pReplaced := PQCharW(AReplaced);
if LR > l then
SetLength(Result, l * LR) // 最糟糕的情况,每个都被替换为目标,当然这不可能
else
SetLength(Result, l);
pd := PQCharW(Result);
if AIgnoreCase then
StrStrFunc := StrIStrW
else
StrStrFunc := StrStrW;
repeat
pws := StrStrFunc(po, pStart);
if pws = nil then
begin
dl := (pe - po);
Move(po^, pd^, dl shl 1);
SetLength(Result, pd - PQCharW(Result) + dl);
Exit;
end
else
begin
pwe := StrStrFunc(pws + LS, pEnd);
if pwe = nil then
// 没找到结尾
begin
dl := pe - po;
Move(po^, pd^, dl shl 1);
SetLength(Result, pd - PQCharW(Result) + dl);
Exit;
end
else
begin
dl := pws - po;
if AWithTag then
begin
Move(po^, pd^, (LS + dl) shl 1);
Inc(pd, LS + dl);
Move(pReplaced^, pd^, LR shl 1);
Inc(pd, LR);
Move(pwe^, pd^, LE shl 1);
Inc(pd, LE);
end
else
begin
Move(po^, pd^, dl shl 1);
Inc(pd, dl);
Move(pReplaced^, pd^, LR shl 1);
Inc(pd, LR);
end;
po := pwe + LE;
Dec(AMaxTimes);
end;
end;
until (AMaxTimes = 0) and (IntPtr(po) < IntPtr(pe));
if IntPtr(po) < IntPtr(pe) then
begin
dl := pe - po;
Move(po^, pd^, dl shl 1);
Inc(pd, dl);
SetLength(Result, pd - PQCharW(Result));
end;
end
else
Result := S;
end;
function StringReplicateW(const S: QStringW; ACount: Integer): QStringW;
var
l: Integer;
p, ps, pd: PQCharW;
begin
l := Length(S);
if (l > 0) and (ACount > 0) then
begin
SetLength(Result, ACount * l);
ps := PQCharW(S);
pd := PQCharW(Result);
for l := 0 to ACount - 1 do
begin
p := ps;
while p^ <> #0 do
begin
pd^ := p^;
Inc(pd);
Inc(p);
end;
end;
end
else
SetLength(Result, 0);
end;
function StringReplicateW(const S, AChar: QStringW; AExpectLength: Integer)
: QStringW;
begin
if Length(S) < AExpectLength then
Result := S + StringReplicateW(AChar, AExpectLength - Length(S))
else
Result := S;
end;
function Translate(const S, AToReplace, AReplacement: QStringW): QStringW;
var
I: Integer;
pd, pp, pr, ps: PQCharW;
function CharIndex(c: QCharW): Integer;
var
pt: PQCharW;
begin
pt := pp;
Result := -1;
while pt^ <> #0 do
begin
if pt^ <> c then
Inc(pt)
else
begin
Result := (IntPtr(pt) - IntPtr(pp));
Break;
end;
end;
end;
begin
if Length(AToReplace) <> Length(AReplacement) then
raise Exception.CreateFmt(SMismatchReplacement, [AToReplace, AReplacement]);
SetLength(Result, Length(S));
pd := PQCharW(Result);
ps := PQCharW(S);
pp := PQCharW(AToReplace);
pr := PQCharW(AReplacement);
while ps^ <> #0 do
begin
I := CharIndex(ps^);
if I <> -1 then
pd^ := PQCharW(IntPtr(pr) + I)^
else
pd^ := ps^;
Inc(ps);
Inc(pd);
end;
end;
function FilterCharW(const S: QStringW; AcceptChars: QStringW)
: QStringW; overload;
var
ps, pd, pc, pds: PQCharW;
l: Integer;
begin
SetLength(Result, Length(S));
if Length(S) > 0 then
begin
ps := PQCharW(S);
pd := PQCharW(Result);
pds := pd;
pc := PQCharW(AcceptChars);
while ps^ <> #0 do
begin
if CharInW(ps, pc, @l) then
begin
pd^ := ps^;
Inc(ps);
Inc(pd);
if l > 1 then
begin
pd^ := ps^;
Inc(ps);
Inc(pd);
end;
end
else
Inc(ps);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(pds)) shr 1);
end;
end;
function FilterCharW(const S: QStringW; AOnValidate: TQFilterCharEvent;
ATag: Pointer): QStringW; overload;
var
ps, pd, pds: PQCharW;
l, I: Integer;
Accept: Boolean;
begin
if (Length(S) > 0) and Assigned(AOnValidate) then
begin
SetLength(Result, Length(S));
ps := PQCharW(S);
pd := PQCharW(Result);
pds := pd;
I := 0;
while ps^ <> #0 do
begin
Accept := True;
if CharSizeW(ps) = 2 then
begin
l := Ord(ps^);
Inc(ps);
l := (l shl 16) or Ord(ps^);
AOnValidate(l, I, Accept, ATag);
end
else
AOnValidate(Ord(ps^), I, Accept, ATag);
if Accept then
begin
pd^ := ps^;
Inc(pd);
end;
Inc(ps);
Inc(I);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(pds)) shr 1);
end
else
SetLength(Result, 0);
end;
{$IFDEF UNICODE}
function FilterCharW(const S: QStringW; AOnValidate: TQFilterCharEventA;
ATag: Pointer): QStringW; overload;
var
ps, pd, pds: PQCharW;
l, I: Integer;
Accept: Boolean;
begin
if (Length(S) > 0) and Assigned(AOnValidate) then
begin
SetLength(Result, Length(S));
ps := PQCharW(S);
pd := PQCharW(Result);
pds := pd;
I := 0;
while ps^ <> #0 do
begin
Accept := True;
if CharSizeW(ps) = 2 then
begin
l := Ord(ps^);
Inc(ps);
l := (l shl 16) or Ord(ps^);
AOnValidate(l, I, Accept, ATag);
end
else
AOnValidate(Ord(ps^), I, Accept, ATag);
Inc(I);
if Accept then
begin
pd^ := ps^;
Inc(pd);
end;
Inc(ps);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(pds)) shr 1);
end
else
SetLength(Result, 0);
end;
{$ENDIF}
function FilterNoNumberW(const S: QStringW; Accepts: TQNumberTypes): QStringW;
var
p, pd, pds: PQCharW;
d, e: Integer;
AIsHex: Boolean;
procedure NegPosCheck;
begin
if ((p^ = '+') and (nftPositive in Accepts)) or
((p^ = '-') and (nftNegative in Accepts)) then
begin
pd^ := p^;
Inc(p);
Inc(pd);
end;
end;
begin
SetLength(Result, Length(S));
p := PQCharW(S);
pd := PQCharW(Result);
pds := pd;
AIsHex := false;
NegPosCheck;
if nftHexPrec in Accepts then
// Check Hex prec
begin
if (p^ = '0') and (nftCHex in Accepts) then // C Style
begin
Inc(p);
if (p^ = 'x') or (p^ = 'X') then
begin
pd^ := '0';
Inc(pd);
pd^ := p^;
Inc(pd);
Inc(p);
AIsHex := True;
end
else
Dec(p);
end
else if (p^ = '$') and (nftDelphiHex in Accepts) then
begin
pd^ := p^;
Inc(p);
Inc(pd);
AIsHex := True;
end
else if (p^ = '&') and (nftBasicHex in Accepts) then
begin
Inc(p);
if Ord(p^) in [Ord('h'), Ord('H')] then
begin
pd^ := '&';
Inc(pd);
pd^ := p^;
Inc(pd);
Inc(p);
AIsHex := True;
end
else
Dec(p);
end;
end;
d := 0;
e := 0;
while p^ <> #0 do
begin
if Ord(p^) in [Ord('0') .. Ord('9')] then
begin
pd^ := p^;
Inc(pd);
end
else if (p^ = '.') and (not AIsHex) then
begin
Inc(d);
if (d = 1) and (nftFloat in Accepts) then
begin
pd^ := p^;
Inc(pd);
end;
end
else if (Ord(p^) in [Ord('e'), Ord('E')]) and (not AIsHex) then
begin
Inc(e);
if (e = 1) and (nftFloat in Accepts) then
begin
if d <= 1 then
begin
pd^ := p^;
Inc(pd);
d := 0;
NegPosCheck;
end;
end;
end
else if AIsHex and ((Ord(p^) in [Ord('a') .. Ord('f')]) or
(Ord(p^) in [Ord('A') .. Ord('F')])) then
begin
pd^ := p^;
Inc(pd);
end;
Inc(p);
end;
SetLength(Result, (IntPtr(pd) - IntPtr(pds)) shr 1);
end;
function MemScan(S: Pointer; len_s: Integer; sub: Pointer;
len_sub: Integer): Pointer;
var
pb_s, pb_sub, pc_sub, pc_s: PByte;
remain: Integer;
begin
if len_s > len_sub then
begin
pb_s := S;
pb_sub := sub;
Result := nil;
while len_s >= len_sub do
begin
if pb_s^ = pb_sub^ then
begin
remain := len_sub - 1;
pc_sub := pb_sub;
pc_s := pb_s;
Inc(pc_s);
Inc(pc_sub);
if BinaryCmp(pc_s, pc_sub, remain) = 0 then
begin
Result := pb_s;
Break;
end;
end;
Inc(pb_s);
Dec(len_s);
end;
end
else if len_s = len_sub then
begin
if CompareMem(S, sub, len_s) then
Result := S
else
Result := nil;
end
else
Result := nil;
end;
function MemCompPascal(p1, p2: Pointer; L1, L2: Integer): Integer;
var
l: Integer;
ps1: PByte absolute p1;
ps2: PByte absolute p2;
begin
if L1 > L2 then
l := L2
else
l := L1;
while l > 4 do
begin
if PInteger(ps1)^ = PInteger(ps2)^ then
begin
Inc(ps1, 4);
Inc(ps2, 4);
end
else
Break;
end;
if l > 0 then
begin
Result := ps1^ - ps2^;
if (Result = 0) and (l > 1) then
begin
Inc(ps1);
Inc(ps2);
Result := ps1^ - ps2^;
if (Result = 0) and (L1 > 2) then
begin
Inc(ps1);
Inc(ps2);
Result := ps1^ - ps2^;
if (Result = 0) and (L1 > 3) then
begin
Inc(ps1);
Inc(ps2);
Result := ps1^ - ps2^;
end;
end;
end;
end
else // ==0
Result := L1 - L2;
end;
{$IFDEF WIN32}
function MemCompAsm(p1, p2: Pointer; L1, L2: Integer): Integer;
label AssignL1, AdjustEnd, DoComp, ByBytes, ByLen, PopReg, C4, C3, c2, c1;
// EAX Temp 1
// EBX Temp 2
// ECX Min(L1,L2)
// EDX EndOf(P1)
// ESI P1
// EDI P2
begin
asm
push esi
push edi
push ebx
mov esi,P1
mov edi,p2
mov eax,L1
mov ebx,L2
cmp eax,ebx
jle AssignL1
mov ecx,ebx
jmp AdjustEnd
AssignL1:// L1<=L2
mov ecx,eax
jmp AdjustEnd
// 调整edx的值为需要比较的结束位置
AdjustEnd:
mov edx,esi
add edx,ecx
and edx,$FFFFFFFC
and ecx,3
DoComp:
cmp esi,edx
jge ByBytes
mov eax,[esi]
mov ebx,[edi]
cmp eax,ebx
jnz C4
add esi,4
add edi,4
jmp DoComp
C4: // 剩下>=4个字节时,直接减最近的4个字节
bswap eax
bswap ebx
sub eax,ebx
jmp PopReg
ByBytes:
cmp ecx,0// 没有可比的内容了,谁长就是谁大
je ByLen
cmp ecx,1// 剩下1个字节
je C1
cmp ecx,2// 剩下2个字节
je C2
// 剩下3个字节
C3:
xor eax,eax// eax清零
xor ebx,ebx// ebx清零
mov ax,WORD PTR [esi]
mov bx,WORD PTR [edi]
add esi,2
add edi,2
cmp eax,ebx
je C1// 剩下一个需要比较的字节,跳到C1
bswap eax
bswap ebx
sub eax,ebx
jmp PopReg
// 剩下两个字节
C2:
xor eax,eax// eax清零
xor ebx,ebx// ebx清零
mov ax,WORD PTR [esi]
mov bx,WORD PTR [edi]
cmp eax,ebx
je ByLen// 能比较的都相等,看长度了
bswap eax
bswap ebx
shr eax,16
shr ebx,16
sub eax,ebx
jmp PopReg
// 剩下一个字节
C1:
xor eax,eax// eax清零
xor ebx,ebx// ebx清零
mov al, BYTE PTR [esi]
mov bl, BYTE PTR [edi]
cmp eax,ebx
je ByLen// 能比较的都相等,看长度了
sub eax,ebx
jmp PopReg;
// 按长度比较
ByLen:
mov eax,L1
sub eax,L2
// 恢复保存的edi和esi值
PopReg:
pop ebx
pop edi
pop esi
mov Result,eax
// lea ebx,[ebp-10]
end;
end;
{$ENDIF}
function BinaryCmp(const p1, p2: Pointer; len: Integer): Integer;
begin
{$IFDEF MSWINDOWS}
{$IFDEF WIN32}
Result := MemComp(p1, p2, len, len);
{$ELSE}
if Assigned(VCMemCmp) then
Result := VCMemCmp(p1, p2, len)
else
Result := MemComp(p1, p2, len, len)
{$ENDIF}
{$ELSE}
Result := memcmp(p1, p2, len);
{$ENDIF}
end;
procedure SkipHex(var S: PQCharW);
begin
while ((S^ >= '0') and (S^ <= '9')) or ((S^ >= 'a') and (S^ <= 'f')) or
((S^ >= 'A') and (S^ <= 'F')) do
Inc(S);
end;
procedure SkipDec(var S: PQCharW);
begin
while (S^ >= '0') and (S^ <= '9') do
Inc(S);
end;
function ParseHex(var p: PQCharW; var Value: Int64): Integer;
var
ps: PQCharW;
begin
Value := 0;
ps := p;
while IsHexChar(p^) do
begin
Value := (Value shl 4) + HexValue(p^);
Inc(p);
end;
Result := p - ps;
end;
function LeftStrCount(const S: QStringW; const sub: QStringW;
AIgnoreCase: Boolean): Integer;
var
ps, psub: PQCharW;
l: Integer;
begin
l := Length(sub);
Result := 0;
if (l > 0) and (Length(S) >= l) then
begin
ps := PQCharW(S);
psub := PQCharW(sub);
if AIgnoreCase then
begin
repeat
ps := StrIStrW(ps, psub);
if ps <> nil then
begin
Inc(Result);
Inc(ps, l);
end;
until ps = nil;
end
else
begin
repeat
ps := StrStrW(ps, psub);
if ps <> nil then
begin
Inc(Result);
Inc(ps, l);
end;
until ps = nil;
end;
end;
end;
function RightPosW(const S: QStringW; const sub: QStringW;
AIgnoreCase: Boolean): Integer;
var
ps, pe, psub, psube, pc, pt: PQCharW;
LS, lsub: Integer;
begin
lsub := Length(sub);
LS := Length(S);
Result := 0;
if LS >= lsub then
begin
ps := Pointer(S);
pe := ps + LS - 1;
psub := Pointer(sub);
psube := psub + lsub - 1;
if AIgnoreCase then
begin
while pe - ps >= lsub - 1 do
begin
if (pe^ = psube^) or (CharUpperW(pe^) = CharUpperW(psube^)) then
begin
pt := psube - 1;
pc := pe - 1;
while (pt >= psub) and
((pc^ = pt^) or (CharUpperW(pc^) = CharUpperW(pt^))) do
begin
Dec(pt);
Dec(pc);
end;
if pt < psub then
begin
Dec(pe, lsub);
Result := pe - ps + 2;
Exit;
end;
end;
Dec(pe);
end;
end
else
begin
while pe - ps >= lsub - 1 do
begin
if pe^ = psube^ then
begin
pt := psube - 1;
pc := pe - 1;
while (pt >= psub) and (pc^ = pt^) do
begin
Dec(pt);
Dec(pc);
end;
if pt < psub then
begin
Dec(pe, lsub);
Result := pe - ps + 2;
Exit;
end;
end;
Dec(pe);
end;
end;
end;
end;
function ParseInt(var S: PQCharW; var ANum: Int64): Integer;
var
ps: PQCharW;
ANeg: Boolean;
ALastVal: Int64;
begin
ps := S;
// 跳过16进制开始字符
if S[0] = '$' then
begin
Inc(S);
Result := ParseHex(S, ANum);
end
else if (S[0] = '0') and ((S[1] = 'x') or (S[1] = 'X')) then
begin
Inc(S, 2);
Result := ParseHex(S, ANum);
end
else
begin
if (S^ = '-') then
begin
ANeg := True;
Inc(S);
end
else
begin
ANeg := false;
if S^ = '+' then
begin
Inc(S);
if (S^ < '0') or (S^ > '9') then // +后必需跟数字
begin
Result := 0;
Exit;
end;
end;
end;
ANum := 0;
ALastVal := 0;
while (S^ >= '0') and (S^ <= '9') do
begin
ANum := ANum * 10 + Ord(S^) - Ord('0');
if (ANum div 10) <> ALastVal then // 溢出?
begin
Result := 0;
S := ps;
Exit;
end;
ALastVal := ANum;
Inc(S);
end;
if ANeg then
ANum := -ANum;
Result := S - ps;
end;
end;
function ParseNumeric(var S: PQCharW; var ANum: Extended;
var AIsFloat: Boolean): Boolean;
var
ps: PQCharW;
function ParseHexInt: Boolean;
var
iVal: Int64;
begin
iVal := 0;
while IsHexChar(S^) do
begin
iVal := (iVal shl 4) + HexValue(S^);
Inc(S);
end;
Result := (S <> ps);
ANum := iVal;
end;
function ParseDec: Boolean;
var
ACount: Integer;
iVal: Int64;
APow: Extended;
ANeg: Boolean;
begin
try
ANeg := S^ = '-';
if ANeg then
Inc(S);
Result := ParseInt(S, iVal) > 0;
if not Result then
Exit;
if ANeg then
ANum := -iVal
else
ANum := iVal;
if S^ = '.' then // 小数部分
begin
AIsFloat := True;
Inc(S);
ACount := ParseInt(S, iVal);
if ACount > 0 then
begin
if (ANum < 0) or ANeg then
ANum := ANum - iVal / IntPower(10, ACount)
else
ANum := ANum + iVal / IntPower(10, ACount);
end;
end;
if (S^ = 'e') or (S^ = 'E') then
begin
AIsFloat := True;
Inc(S);
if ParseNumeric(S, APow) then
ANum := ANum * Power(10, APow)
else
S := ps;
end;
Result := (S <> ps);
except
on e: EOverflow do
Result := false;
end;
end;
begin
ps := S;
AIsFloat := false;
if (S^ = '$') or (S^ = '&') then
begin
Inc(S);
Result := ParseHexInt;
Exit;
end
else if (S[0] = '0') and ((S[1] = 'x') or (S[1] = 'X')) then
begin
Inc(S, 2);
Result := ParseHexInt;
Exit;
end
else
Result := ParseDec;
if not Result then
S := ps;
end;
function ParseNumeric(var S: PQCharW; var ANum: Extended): Boolean;
var
AIsFloat: Boolean;
begin
Result := ParseNumeric(S, ANum, AIsFloat);
end;
function NameOfW(const S: QStringW; ASpliter: QCharW; AEmptyIfMissed: Boolean)
: QStringW;
var
p: PQCharW;
begin
if Length(S) > 0 then
begin
p := PQCharW(S);
Result := DecodeTokenW(p, [ASpliter], WideChar(0), false, false);
if (p^ = #0) and AEmptyIfMissed then
Result := '';
end
else
Result := S;
end;
function ValueOfW(const S: QStringW; ASpliter: QCharW; AEmptyIfMissed: Boolean)
: QStringW;
var
p: PQCharW;
l: Integer;
begin
if Length(S) > 0 then
begin
p := PQCharW(S);
if p^ = ASpliter then
begin
l := Length(S);
Dec(l);
SetLength(Result, l);
Inc(p);
Move(p^, PQCharW(Result)^, l shl 1);
end
else
begin
DecodeTokenW(p, [ASpliter], WideChar(0), false);
if p^ <> #0 then
Result := p
else if AEmptyIfMissed then
SetLength(Result, 0)
else
Result := S;
end;
end
else
Result := S;
end;
function IndexOfNameW(AList: TStrings; const AName: QStringW;
ASpliter: QCharW): Integer;
var
I: Integer;
function DoCompareName(const AValue: String): Boolean;
begin
if TStringList(AList).CaseSensitive then
Result := CompareStr(AName, AValue) = 0
else
Result := CompareText(AName, AValue) = 0;
end;
begin
if (AList is TStringList) and TStringList(AList).Sorted then
begin
// 如果是已经排序的TStringList实例,则用二分法查找
if not TStringList(AList).Find(AName, Result) then
begin
if Result < AList.count then
begin
if DoCompareName(AList.Names[Result]) then
Exit
else if (Result > 0) and DoCompareName(AList.Names[Result - 1]) then
Dec(Result)
else
Result := -1;
end;
end
end
else
begin
Result := -1;
for I := 0 to AList.count - 1 do
begin
if NameOfW(AList[I], ASpliter) = AName then
begin
Result := I;
Break;
end;
end;
end;
end;
function IndexOfValueW(AList: TStrings; const AValue: QStringW;
ASpliter: QCharW): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to AList.count - 1 do
begin
if ValueOfW(AList[I], ASpliter) = AValue then
begin
Result := I;
Break;
end;
end;
end;
function DeleteCharW(const ASource, ADeletes: QStringW): QStringW;
var
ps, pd: PQCharW;
l, ACharLen: Integer;
begin
l := Length(ASource);
if (l > 0) and (Length(ADeletes) > 0) then
begin
SetLength(Result, l);
ps := PQCharW(ASource);
pd := PQCharW(Result);
while l > 0 do
begin
if not CharInW(ps, PQCharW(ADeletes), @ACharLen) then
begin
pd^ := ps^;
Inc(pd);
ACharLen := CharSizeW(ps);
end;
Inc(ps, ACharLen);
Dec(l, ACharLen);
end;
SetLength(Result, pd - PQCharW(Result));
end
else
Result := ASource;
end;
function DeleteSideCharsW(const ASource: QStringW; ADeletes: QStringW;
AIgnoreCase: Boolean): QStringW;
var
ps, pd, pe: PQCharW;
ATemp: QStringW;
begin
if Length(ADeletes) = 0 then
Result := ASource
else
begin
if AIgnoreCase then
begin
ATemp := UpperCase(ASource);
ADeletes := UpperCase(ADeletes);
ps := PQCharW(ATemp);
pe := ps + Length(ATemp);
end
else
begin
ps := PQCharW(ASource);
pe := ps + Length(ASource);
end;
pd := PQCharW(ADeletes);
while ps < pe do
begin
if CharInW(ps, pd) then
Inc(ps, CharSizeW(ps))
else
Break;
end;
while pe > ps do
begin
Dec(pe);
if (pe^ >= #$DB00) and (pe^ <= #$DFFF) then
Dec(pe);
if not CharInW(pe, pd) then
begin
Inc(pe, CharSizeW(pe));
Break;
end;
end;
Result := StrDupX(ps, pe - ps);
end;
end;
function DeleteRightW(const S, ADelete: QStringW; AIgnoreCase: Boolean = false;
ACount: Integer = MaxInt): QStringW;
var
ps, pd, pe: PQCharW;
LS, LD: Integer;
begin
LS := Length(S);
LD := Length(ADelete);
if LS < LD then
Result := S
else if LD > 0 then
begin
pe := PQCharW(S) + Length(S);
pd := PQCharW(ADelete);
if AIgnoreCase then
begin
while LS >= LD do
begin
ps := pe - LD;
if StrIStrW(ps, pd) = ps then
begin
pe := ps;
Dec(LS, LD);
end
else
Break;
end;
end
else
begin
while LS >= LD do
begin
ps := pe - LD;
if CompareMem(ps, pd, LD shl 1) then
begin
pe := ps;
Dec(LS, LD);
end
else
Break;
end;
end;
SetLength(Result, LS);
if LS > 0 then
Move(PWideChar(S)^, PQCharW(Result)^, LS shl 1);
end
else
Result := S;
end;
function DeleteLeftW(const S, ADelete: QStringW; AIgnoreCase: Boolean = false;
ACount: Integer = MaxInt): QStringW;
var
ps, pd: PQCharW;
LS, LD: Integer;
begin
LS := Length(S);
LD := Length(ADelete);
if LS < LD then
Result := S
else if LD > 0 then
begin
ps := PQCharW(S);
pd := PQCharW(ADelete);
if AIgnoreCase then
begin
while LS >= LD do
begin
if StartWithW(ps, pd, True) then
begin
Inc(ps, LD);
Dec(LS, LD);
end
else
Break;
end;
end
else
begin
while LS >= LD do
begin
if CompareMem(ps, pd, LD shl 1) then
begin
Inc(ps, LD);
Dec(LS, LD);
end
else
Break;
end;
end;
SetLength(Result, LS);
if LS > 0 then
Move(ps^, PQCharW(Result)^, LS shl 1);
end
else
Result := S;
end;
function ContainsCharW(const S, ACharList: QStringW): Boolean;
var
ps: PQCharW;
l: Integer;
begin
l := Length(S);
Result := false;
if (l > 0) then
begin
if Length(ACharList) > 0 then
begin
ps := PQCharW(S);
while l > 0 do
begin
if CharInW(ps, PQCharW(ACharList)) then
begin
Result := True;
Break;
end;
Inc(ps);
Dec(l);
end;
end;
end;
end;
procedure StrCpyW(d: PQCharW; S: PQCharW; ACount: Integer);
begin
while (S^ <> #0) and (ACount <> 0) do
begin
d^ := S^;
Inc(d);
Inc(S);
Dec(ACount);
end;
end;
function JavaEscape(const S: QStringW; ADoEscape: Boolean): QStringW;
var
ASize: Integer;
p, ps, pd: PWideChar;
begin
ASize := Length(S);
if ASize > 0 then
begin
p := Pointer(S);
ps := p;
while p^ <> #0 do
begin
if p^ < ' ' then // 控制字符
begin
if (p^ >= #7) and (p^ <= #13) then
Inc(ASize)
else
Inc(ASize, 5);
end
else if p^ >= '~' then // 非可打印字符,转义的话使用 \uxxxx
begin
if ADoEscape then
Inc(ASize, 5);
end
else
begin
if (p^ = '\') or (p^ = '''') or (p^ = '"') then // \->\\
Inc(ASize);
end;
Inc(p);
end;
if ASize = Length(S) then
Result := S
else
begin
SetLength(Result, ASize);
pd := Pointer(Result);
p := ps;
while p^ <> #0 do
begin
if p^ < ' ' then // 控制字符
begin
case p^ of
#7:
begin
PInteger(pd)^ := $0061005C; // \a
Inc(pd, 2);
end;
#8:
begin
PInteger(pd)^ := $0062005C; // \b
Inc(pd, 2);
end;
#9:
begin
PInteger(pd)^ := $0074005C; // \t
Inc(pd, 2);
end;
#10:
begin
PInteger(pd)^ := $006E005C; // \n
Inc(pd, 2);
end;
#11:
begin
PInteger(pd)^ := $0076005C; // \v
Inc(pd, 2);
end;
#12:
begin
PInteger(pd)^ := $0066005C; // \f
Inc(pd, 2);
end;
#13:
begin
PInteger(pd)^ := $0072005C; // \r
Inc(pd, 2);
end
else
begin
PInteger(pd)^ := $0075005C; // \u
Inc(pd, 2);
pd^ := '0';
Inc(pd);
pd^ := '0';
Inc(pd);
pd^ := '0';
Inc(pd);
pd^ := p^;
Inc(pd);
end;
end;
end
else if p^ >= '~' then // 非可打印字符,转义的话使用 \uxxxx
begin
if ADoEscape then // \uxxxx
begin
PInteger(pd)^ := $0075005C; // \u
Inc(pd, 2);
pd^ := LowerHexChars[(Ord(p^) shr 12) and $0F];
Inc(pd);
pd^ := LowerHexChars[(Ord(p^) shr 8) and $0F];
Inc(pd);
pd^ := LowerHexChars[(Ord(p^) shr 4) and $0F];
Inc(pd);
pd^ := LowerHexChars[Ord(p^) and $0F];
Inc(pd);
end
else
begin
pd^ := p^;
Inc(pd);
end;
end
else
begin
case p^ of
'\':
begin
PInteger(pd)^ := $005C005C; // \\
Inc(pd, 2);
end;
'''':
begin
PInteger(pd)^ := $0027005C; // \'
Inc(pd, 2);
end;
'"':
begin
PInteger(pd)^ := $0022005C; // \"
Inc(pd, 2);
end
else
begin
pd^ := p^;
Inc(pd);
end;
end;
end;
Inc(p);
end;
end;
end
else
SetLength(Result, 0);
end;
function JavaUnescape(const S: QStringW; AStrictEscape: Boolean): QStringW;
var
ps, p, pd: PWideChar;
ASize: Integer;
begin
ASize := Length(S);
Result := S;
if ASize > 0 then
begin
p := Pointer(S);
ps := p;
while p^ <> #0 do
begin
if p^ = '\' then
begin
Inc(p);
case p^ of
'a', 'b', 'f', 'n', 'r', 't', 'v', '''', '"', '\', '?':
begin
Dec(ASize);
Inc(p);
end;
'x': // \xNN
begin
Dec(ASize, 2);
Inc(p, 3);
end;
'u': // \uxxxx
begin
if IsHexChar(p[1]) and IsHexChar(p[2]) and IsHexChar(p[3]) and
IsHexChar(p[4]) then
begin
Dec(ASize, 5);
Inc(p, 5);
end
else
raise Exception.CreateFmt(SBadJavaEscape, [Copy(p, 0, 6)]);
end;
'U': // \Uxxxxxxxx
begin
if IsHexChar(p[1]) and IsHexChar(p[2]) and IsHexChar(p[3]) and
IsHexChar(p[4]) and IsHexChar(p[5]) and IsHexChar(p[6]) and
IsHexChar(p[7]) and IsHexChar(p[8]) then
begin
Dec(ASize, 9);
Inc(p, 9);
end
else
raise Exception.CreateFmt(SBadJavaEscape, [Copy(p, 0, 10)]);
end
else
begin
if IsOctChar(p[0]) then
begin
if IsOctChar(p[1]) then
begin
if IsOctChar(p[2]) then
begin
Dec(ASize, 3);
Inc(p, 3);
end
else
begin
Dec(ASize, 2);
Inc(p, 2);
end;
end
else
begin
Dec(ASize, 1);
Inc(p, 1);
end;
end
else if AStrictEscape then
begin
raise Exception.CreateFmt(SBadJavaEscape, [Copy(p, 0, 6)]);
end;
end;
end;
end
else
Inc(p);
end;
if Length(S) <> ASize then // 尺寸相等,没有需要处理的转义
begin
SetLength(Result, ASize);
pd := Pointer(Result);
p := ps;
while p^ <> #0 do
begin
if p^ = '\' then
begin
Inc(p);
case p^ of
'a':
pd^ := #7;
'b':
pd^ := #8;
'f':
pd^ := #12;
'n':
pd^ := #10;
'r':
pd^ := #13;
't':
pd^ := #9;
'v':
pd^ := #11;
'''':
pd^ := '''';
'"':
pd^ := '"';
'\':
pd^ := '\';
'?':
pd^ := '?';
'x': // \xNN
begin
pd^ := WideChar((HexValue(p[1]) shl 4) or HexValue(p[2]));
Inc(p, 2);
end;
'u': // \uxxxx
begin
pd^ := WideChar((HexValue(p[1]) shl 12) or
(HexValue(p[2]) shl 8) or (HexValue(p[3]) shl 4) or
HexValue(p[4]));
Inc(p, 4);
end;
'U':
// \Uxxxxxxxx
begin
pd^ := WideChar((HexValue(p[1]) shl 12) or
(HexValue(p[2]) shl 8) or (HexValue(p[3]) shl 4) or
HexValue(p[4]));
Inc(pd);
pd^ := WideChar((HexValue(p[5]) shl 12) or
(HexValue(p[6]) shl 8) or (HexValue(p[7]) shl 4) or
HexValue(p[8]));
Inc(p, 8);
end
else
begin
if IsOctChar(p[0]) then
begin
ASize := HexValue(p[0]);
if IsOctChar(p[1]) then
begin
ASize := (ASize shl 3) + HexValue(p[1]);
if IsOctChar(p[2]) then
begin
pd^ := WideChar((ASize shl 3) + HexValue(p[2]));
Inc(p, 2);
end
else
begin
pd^ := WideChar(ASize);
Inc(p);
end;
end
else
pd^ := WideChar(ASize);
end
else
pd^ := p^;
end;
end;
Inc(pd);
end
else
begin
pd^ := p^;
Inc(pd);
end;
Inc(p);
end;
end;
end;
end;
function HtmlEscape(const S: QStringW): QStringW;
var
p, pd: PQCharW;
AFound: Boolean;
pw: PWord absolute p;
begin
if Length(S) > 0 then
begin
System.SetLength(Result, Length(S) shl 3);
// 转义串最长不超过8个字符,长度*8肯定够了
p := PWideChar(S);
pd := PWideChar(Result);
while p^ <> #0 do
begin
AFound := false;
if (pw^ >= 32) and (pw^ <= 255) then
begin
AFound := True;
StrCpyW(pd, PQCharW(HtmlEscapeChars[pw^]));
Inc(pd, Length(HtmlEscapeChars[pw^]));
end;
if not AFound then
begin
pd^ := p^;
Inc(pd);
end; // end if
Inc(p);
end; // end while
SetLength(Result, pd - PQCharW(Result));
end // end if
else
Result := '';
end;
type
THTMLEscapeHashItem = record
Hash: Integer;
Char: Word;
Next: Byte;
end;
function UnescapeHtmlChar(var p: PQCharW): QCharW;
const
HtmlUnescapeTable: array [0 .. 94] of THTMLEscapeHashItem =
((Hash: 1667591796; Char: 162; Next: 255), // 0:0:¢
(Hash: 1768257635; Char: 161; Next: 10), // 1:15:¡
(Hash: 1886352750; Char: 163; Next: 34), // 2:55:£
(Hash: 1869900140; Char: 245; Next: 255), // 3:3:õ
(Hash: 1853122924; Char: 241; Next: 255), // 4:4:ñ
(Hash: 1936226560; Char: 173; Next: 66), // 5:54:­
(Hash: 1684367104; Char: 176; Next: 64), // 6:31:°
(Hash: 1769043301; Char: 191; Next: 255), // 7:78:¿
(Hash: 1096901493; Char: 193; Next: 255), // 8:79:Á
(Hash: 1095068777; Char: 198; Next: 12), // 9:81:Æ
(Hash: 1130587492; Char: 199; Next: 84), // 10:15:Ç
(Hash: 1651668578; Char: 166; Next: 89), // 11:11:¦
(Hash: 1164142962; Char: 202; Next: 255), // 12:81:Ê
(Hash: 1634562048; Char: 38; Next: 18), // 13:13:&
(Hash: 1231516257; Char: 204; Next: 255), // 14:86:Ì
(Hash: 1851945840; Char: 32; Next: 1), // 15:15:
(Hash: 1231119221; Char: 205; Next: 24), // 16:71:Í
(Hash: 1919248128; Char: 174; Next: 40), // 17:17:®
(Hash: 1163151360; Char: 208; Next: 255), // 18:13:Ð
(Hash: 1316252012; Char: 209; Next: 255), // 19:36:Ñ
(Hash: 1869835361; Char: 248; Next: 255), // 20:20:ø
(Hash: 1869966700; Char: 246; Next: 255), // 21:21:ö
(Hash: 1919512167; Char: 197; Next: 255), // 22:22:˚
(Hash: 1633908084; Char: 180; Next: 85), // 23:23:´
(Hash: 1331915122; Char: 212; Next: 255), // 24:71:Ô
(Hash: 1918988661; Char: 187; Next: 255), // 25:25:»
(Hash: 1333029228; Char: 213; Next: 41), // 26:35:Õ
(Hash: 1769303404; Char: 239; Next: 76), // 27:27:ï
(Hash: 1953066341; Char: 215; Next: 255), // 28:53:×
(Hash: 1432445813; Char: 218; Next: 255), // 29:59:Ú
(Hash: 1432578418; Char: 219; Next: 255), // 30:65:Û
(Hash: 1818325365; Char: 171; Next: 6), // 31:31:«
(Hash: 1835098994; Char: 175; Next: 88), // 32:32:¯
(Hash: 1868653429; Char: 243; Next: 82), // 33:33:ó
(Hash: 1499554677; Char: 221; Next: 255), // 34:55:Ý
(Hash: 1835623282; Char: 181; Next: 26), // 35:35:µ
(Hash: 1970105344; Char: 168; Next: 19), // 36:36:¨
(Hash: 1937402985; Char: 223; Next: 67), // 37:63:ß
(Hash: 1633772405; Char: 225; Next: 255), // 38:47:á
(Hash: 1767990133; Char: 237; Next: 70), // 39:39:í
(Hash: 1635019116; Char: 227; Next: 255), // 40:17:ã
(Hash: 1635085676; Char: 228; Next: 255), // 41:35:ä
(Hash: 1969713761; Char: 249; Next: 255), // 42:42:ù
(Hash: 1700881269; Char: 233; Next: 255), // 43:43:é
(Hash: 1667458404; Char: 231; Next: 255), // 44:80:ç
(Hash: 1768122738; Char: 238; Next: 255), // 45:45:î
(Hash: 1701278305; Char: 232; Next: 255), // 46:58:è
(Hash: 1433759084; Char: 220; Next: 38), // 47:47:Ü
(Hash: 1667589225; Char: 184; Next: 68), // 48:48:¸
(Hash: 1098148204; Char: 195; Next: 51), // 49:49:Ã
(Hash: 1869767782; Char: 170; Next: 255), // 50:50:ª
(Hash: 1701013874; Char: 234; Next: 72), // 51:49:ê
(Hash: 1332964449; Char: 216; Next: 255), // 52:52:Ø
(Hash: 1333095788; Char: 214; Next: 28), // 53:53:Ö
(Hash: 1903521652; Char: 34; Next: 5), // 54:54:"
(Hash: 1634758515; Char: 39; Next: 2), // 55:55:'
(Hash: 2036690432; Char: 165; Next: 255), // 56:56:¥
(Hash: 1869767789; Char: 186; Next: 255), // 57:57:º
(Hash: 1668641394; Char: 164; Next: 46), // 58:58:¤
(Hash: 1232432492; Char: 207; Next: 29), // 59:59:Ï
(Hash: 1668247673; Char: 169; Next: 255), // 60:60:©
(Hash: 1634036841; Char: 230; Next: 255), // 61:61:æ
(Hash: 1634169441; Char: 224; Next: 255), // 62:62:à
(Hash: 1165323628; Char: 203; Next: 37), // 63:63:Ë
(Hash: 1702194540; Char: 235; Next: 255), // 64:31:ë
(Hash: 1331782517; Char: 211; Next: 30), // 65:65:Ó
(Hash: 1768387169; Char: 236; Next: 255), // 66:54:ì
(Hash: 1768256616; Char: 240; Next: 255), // 67:63:&ieth;
(Hash: 1869050465; Char: 242; Next: 255), // 68:48:ò
(Hash: 1885434465; Char: 182; Next: 255), // 69:69:¶
(Hash: 1868786034; Char: 244; Next: 255), // 70:39:ô
(Hash: 1886156147; Char: 177; Next: 16), // 71:71:±
(Hash: 1684633193; Char: 247; Next: 255), // 72:49:÷
(Hash: 1414025042; Char: 222; Next: 255), // 73:73:Þ
(Hash: 1432842849; Char: 217; Next: 255), // 74:74:Ù
(Hash: 1164010357; Char: 201; Next: 255), // 75:75:É
(Hash: 1969316725; Char: 250; Next: 255), // 76:27:ú
(Hash: 1231251826; Char: 206; Next: 255), // 77:77:Î
(Hash: 1936024436; Char: 167; Next: 7), // 78:78:§
(Hash: 1852797952; Char: 172; Next: 8), // 79:79:¬
(Hash: 1332179553; Char: 210; Next: 44), // 80:80:Ò
(Hash: 1819541504; Char: 60; Next: 9), // 81:81:<
(Hash: 1969449330; Char: 251; Next: 255), // 82:33:û
(Hash: 1835623524; Char: 183; Next: 255), // 83:83:·
(Hash: 1970629996; Char: 252; Next: 255), // 84:15:ü
(Hash: 2036425589; Char: 253; Next: 255), // 85:23:ý
(Hash: 1735655424; Char: 62; Next: 14), // 86:86:>
(Hash: 1667854947; Char: 194; Next: 255), // 87:87:ˆ
(Hash: 1953001330; Char: 254; Next: 255), // 88:32:þ
(Hash: 2037738860; Char: 255; Next: 255), // 89:11:ÿ
(Hash: 1164407393; Char: 200; Next: 255), // 90:90:È
(Hash: 1634888046; Char: 229; Next: 255), // 91:91:å
(Hash: 0; Char: 0; Next: 255), // 92:Not Used
(Hash: 0; Char: 0; Next: 255), // 93:Not Used
(Hash: 1097298529; Char: 192; Next: 255) // 94:94:À
);
function HashOfEscape: Integer;
var
c: Integer;
R: array [0 .. 3] of Byte absolute Result;
begin
Inc(p); // Skip #
c := 3;
Result := 0;
while (p^ <> #0) and (c >= 0) do
begin
if p^ = ';' then
Exit;
R[c] := Ord(p^);
Inc(p);
Dec(c);
end;
while p^ <> #0 do
begin
if p^ = ';' then
Exit
else
Inc(p);
end;
Result := 0;
end;
var
AHash, ANext: Integer;
begin
AHash := HashOfEscape;
Result := #0;
if AHash <> 0 then
begin
ANext := AHash mod 97;
while ANext <> 255 do
begin
if HtmlUnescapeTable[ANext].Hash = AHash then
begin
Result := QCharW(HtmlUnescapeTable[ANext].Char);
Break;
end
else
ANext := HtmlUnescapeTable[ANext].Next;
end;
end;
end;
function HtmlUnescape(const S: QStringW): QStringW;
var
p, pd, ps: PQCharW;
l: Integer;
begin
if Length(S) > 0 then
begin
System.SetLength(Result, Length(S));
p := PQCharW(S);
pd := PQCharW(Result);
while p^ <> #0 do
begin
if p^ = '&' then
begin
if p[1] = '#' then
begin
ps := p;
Inc(p, 2);
l := 0;
if (p^ = 'x') or (p^ = 'X') then
begin
Inc(p);
while IsHexChar(p^) do
begin
l := l shl 4 + HexValue(p^);
Inc(p);
end;
end
else
begin
while (p^ >= '0') and (p^ <= '9') do
begin
l := l * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
end;
if p^ = ';' then
begin
pd^ := QCharW(l);
Inc(pd);
end
else
begin
pd^ := ps^;
Inc(pd);
p := ps;
end;
end
else
begin
pd^ := UnescapeHtmlChar(p);
if pd^ = #0 then
pd^ := p^;
Inc(pd);
end; // end else
end // end else
else
begin
pd^ := p^;
Inc(pd);
end;
Inc(p);
end; // end while
SetLength(Result, pd - PWideChar(Result));
end // end if
else
Result := '';
end;
function HtmlTrimText(const S: QStringW): QStringW;
var
ps, pe: PQCharW;
l: Integer;
begin
if Length(S) > 0 then
begin
ps := PQCharW(S);
pe := ps + System.Length(S) - 1;
while IsSpaceW(ps) do
Inc(ps);
while IsSpaceW(pe) do
Dec(pe);
l := pe - ps + 1;
SetLength(Result, l);
Move(ps^, PQCharW(Result)^, l shl 1);
end
else
Result := '';
end;
function IsUrl(const S: QStringW): Boolean;
begin
Result := StrIStrW(PWideChar(S), '://') <> nil;
end;
function UrlEncode(const ABytes: PByte; l: Integer;
ASpacesAsPlus, AEncodePercent: Boolean; ABookmarkEncode: TUrlBookmarkEncode)
: QStringW; overload;
const
SafeChars: array [33 .. 127] of Byte = ( //
0, 0, 0, 0, 0, 0, 0, 0, //
0, 0, 0, 0, 1, 1, 0, 1, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 0, 0, 0, 0, 0, 0, 0, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 0, 0, 0, 0, 1, 0, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 1, 1, 1, 1, 1, 1, //
1, 1, 0, 0, 0, 1, 0);
HexChars: array [0 .. 15] of QCharW = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
c: Integer;
ABookmarkCount: Integer;
ps, pe: PByte;
pd: PQCharW;
begin
// 计算实际的长度
ps := PByte(ABytes);
pe := PByte(IntPtr(ps) + l);
{ c := 0;
ABookmarkCount := 0;
while IntPtr(ps) < IntPtr(pe) do
begin
if (not AEncodePercent) and (ps^ = Ord('%')) and
(IntPtr(pe) - IntPtr(ps) > 2) and
(PByte(IntPtr(ps) + 1)^ in [Ord('a') .. Ord('f'), Ord('A') .. Ord('F'),
Ord('0') .. Ord('9')]) and
(PByte(IntPtr(ps) + 2)^ in [Ord('a') .. Ord('f'), Ord('A') .. Ord('F'),
Ord('0') .. Ord('9')]) then
// 原来就是%xx? %09%32
Inc(ps, 3)
else
begin
if (ps^ = Ord('%')) and (not AEncodePercent) then
// 有非%xx这种,说明未编码过%,需要强制编码
begin
Result := UrlEncode(ABytes, l, ASpacesAsPlus, True, ABookmarkEncode);
Exit;
end;
if (ps^ = 32) and ASpacesAsPlus then
Inc(ps)
else if ps^ = Ord('#') then
begin
Inc(ps);
Inc(ABookmarkCount);
end
else
begin
if (ps^ <= 32) or (ps^ > 127) or (SafeChars[ps^] = 0) then
Inc(c,2);
Inc(ps);
end;
end;
end;
if ABookmarkCount > 0 then
begin
if ABookmarkEncode = ubeAll then
Inc(c, ABookmarkCount)
else if ABookmarkEncode = ubeOnlyLast then
Inc(c);
end;
SetLength(Result, l + c); }
SetLength(Result, l * 3);
pd := PQCharW(Result);
ps := ABytes;
while IntPtr(ps) < IntPtr(pe) do
begin
if (not AEncodePercent) and (ps^ = Ord('%')) and
(IntPtr(pe) - IntPtr(ps) > 2) and
(PByte(IntPtr(ps) + 1)^ in [Ord('a') .. Ord('f'), Ord('A') .. Ord('F'),
Ord('0') .. Ord('9')]) and
(PByte(IntPtr(ps) + 2)^ in [Ord('a') .. Ord('f'), Ord('A') .. Ord('F'),
Ord('0') .. Ord('9')]) then // 原来就是%xx?
begin
pd^ := '%';
Inc(pd);
Inc(ps);
pd^ := QCharW(ps^);
Inc(pd);
Inc(ps);
pd^ := QCharW(ps^);
Inc(pd);
Inc(ps);
end
else
begin
if (ABookmarkEncode <> ubeNone) and (ps^ = Ord('#')) then
begin
if (ABookmarkCount = 1) or (ABookmarkEncode = ubeAll) then
begin
pd^ := '%';
Inc(pd);
pd^ := HexChars[(ps^ shr 4) and $0F];
Inc(pd);
pd^ := HexChars[ps^ and $0F];
end;
Dec(ABookmarkCount);
end
else if (ps^ in [33 .. 127]) and (SafeChars[ps^] <> 0) then
pd^ := QCharW(ps^)
else if (ps^ = 32) and ASpacesAsPlus then
pd^ := '+'
else
begin
pd^ := '%';
Inc(pd);
pd^ := HexChars[(ps^ shr 4) and $0F];
Inc(pd);
pd^ := HexChars[ps^ and $0F];
end;
Inc(pd);
Inc(ps);
end;
end;
SetLength(Result, pd - PQCharW(Result));
end;
function UrlEncode(const ABytes: TBytes; ASpacesAsPlus, AEncodePercent: Boolean;
ABookmarkEncode: TUrlBookmarkEncode): QStringW; overload;
begin
if Length(ABytes) > 0 then
Result := UrlEncode(@ABytes[0], Length(ABytes), ASpacesAsPlus,
AEncodePercent, ABookmarkEncode)
else
SetLength(Result, 0);
end;
function UrlEncode(const S: QStringW; ASpacesAsPlus, AUtf8Encode,
AEncodePercent: Boolean; ABookmarkEncode: TUrlBookmarkEncode)
: QStringW; overload;
var
ABytes: QStringA;
begin
if Length(S) > 0 then
begin
if AUtf8Encode then
ABytes := qstring.Utf8Encode(S)
else
ABytes := AnsiEncode(S);
Result := UrlEncode(PByte(PQCharA(ABytes)), ABytes.Length, ASpacesAsPlus,
AEncodePercent, ABookmarkEncode);
end
else
Result := S;
end;
function UrlEncodeString(const S: QStringW): QStringW;
begin
Result := UrlEncode(S, false, True, True, ubeAll);
end;
function UrlDecode(const AValue: QStringW; var AResult: QStringW;
AUtf8Encode: Boolean = True): Boolean;
var
pd, pds, pb: PQCharA;
ps: PQCharW;
ADoUnescape: Boolean;
ABuf: TBytes;
begin
Result := True;
ps := PQCharW(AValue);
ADoUnescape := false;
while ps^ <> #0 do
begin
if (ps^ = '%') or (ps^ = '+') then
begin
ADoUnescape := True;
Break;
end
else
Inc(ps);
end;
if ADoUnescape then
begin
SetLength(ABuf, Length(AValue));
pd := PQCharA(@ABuf[0]);
ps := PQCharW(AValue);
pds := pd;
while ps^ <> #0 do
begin
if ps^ = '%' then
begin
Inc(ps);
if IsHexChar(ps^) then
begin
pd^ := HexValue(ps^) shl 4;
Inc(ps);
if IsHexChar(ps^) then
begin
pd^ := pd^ or HexValue(ps^);
Inc(ps);
end
else
begin
Result := false;
Break;
end;
end
else
begin
pd^ := QCharA('%');
Inc(pd);
pd^ := QCharA(ps^);
Inc(ps);
end;
end
else if ps^ = '+' then
begin
pd^ := 32;
Inc(ps);
end
else
begin
pd^ := QCharA(ps^);
Inc(ps);
end;
Inc(pd);
end;
if AUtf8Encode then
begin
if not Utf8Decode(pds, IntPtr(pd) - IntPtr(pds), AResult, pb) then
AResult := AnsiDecode(pds, IntPtr(pd) - IntPtr(pds));
end
else
AResult := AnsiDecode(pds, IntPtr(pd) - IntPtr(pds));
end
else
AResult := AValue;
end;
function UrlDecode(const AUrl: QStringW;
var AScheme, AHost, ADocument: QStringW; var APort: Word; AParams: TStrings;
AUtf8Encode: Boolean): Boolean;
var
p, ps: PQCharW;
V, N: QStringW;
iV: Int64;
procedure DecodePort;
var
ph, pp, pl: PQCharW;
begin
// 从Host里解析出端口号
ph := PQCharW(AHost);
pp := ph + Length(AHost);
APort := 0;
while pp > ph do
begin
if pp^ = ':' then
begin
pl := pp;
Inc(pp);
if ParseInt(pp, iV) <> 0 then
begin
APort := Word(iV);
SetLength(AHost, pl - ph);
Break;
end
else
Break;
end
else
APort := 0;
Dec(pp);
end
end;
const
HostEnd: PQCharW = '/';
DocEnd: PQCharW = '?';
ParamDelimiter: PQCharW = '&';
begin
Result := True;
p := PQCharW(AUrl);
SkipSpaceW(p);
ps := p;
p := StrStrW(ps, '://');
if p <> nil then
begin
AScheme := StrDupX(ps, p - ps);
Inc(p, 3);
ps := p;
end
else
AScheme := '';
p := ps;
SkipUntilW(p, HostEnd);
AHost := StrDupX(ps, p - ps);
DecodePort;
if Assigned(AParams) then
begin
ps := p;
SkipUntilW(p, DocEnd);
if p^ = '?' then
begin
if not UrlDecode(StrDupX(ps, p - ps), ADocument, AUtf8Encode) then
ADocument := StrDupX(ps, p - ps);
Inc(p);
AParams.BeginUpdate;
try
while p^ <> #0 do
begin
V := DecodeTokenW(p, ParamDelimiter, QCharW(0), false, True);
if UrlDecode(NameOfW(V, '='), N, AUtf8Encode) and
UrlDecode(ValueOfW(V, '=', True), V, AUtf8Encode) then
begin
if Length(N) > 0 then
AParams.Add(N + '=' + V)
end
else
begin
Result := false;
Break;
end;
end;
finally
AParams.EndUpdate;
end;
end
else
begin
if not UrlDecode(ps, ADocument, AUtf8Encode) then
ADocument := ps;
AParams.Clear;
end;
end;
end;
function DateTimeFromString(AStr: QStringW; var AResult: TDateTime;
AFormat: String): Boolean; overload;
// 日期时间格式
function DecodeTagValue(var pf, ps: PWideChar; cl, cu: WideChar;
var AValue, ACount: Integer; AMaxOnOne: Integer): Boolean;
begin
AValue := 0;
ACount := 0;
Result := True;
while (pf^ = cl) or (pf^ = cu) do
begin
if (ps^ >= '0') and (ps^ <= '9') then
begin
AValue := AValue * 10 + Ord(ps^) - Ord('0');
Inc(ps);
Inc(pf);
Inc(ACount);
end
else
begin
Result := false;
Exit;
end;
end;
if (ACount = 1) and (ACount < AMaxOnOne) then
begin
while (ACount < AMaxOnOne) and (ps^ >= '0') and (ps^ <= '9') do
begin
AValue := AValue * 10 + Ord(ps^) - Ord('0');
Inc(ACount);
Inc(ps);
end;
end;
end;
function DecodeAsFormat(fmt: QStringW): Boolean;
var
pf, ps, pl: PWideChar;
c, Y, M, d, H, N, S, MS: Integer;
ADate, ATime: TDateTime;
begin
pf := PWideChar(fmt);
ps := PWideChar(AStr);
c := 0;
Y := 0;
M := 0;
d := 0;
H := 0;
N := 0;
S := 0;
MS := 0;
Result := True;
while (pf^ <> #0) and Result do
begin
if (pf^ = 'y') or (pf^ = 'Y') then
// 到了年份的部分
begin
Result := DecodeTagValue(pf, ps, 'y', 'Y', Y, c, 4) and (c <> 3);
if Result then
begin
if c = 2 then // 两位年时
begin
if Y < 50 then
Y := 2000 + Y
else
Y := 1900 + Y;
end
end;
end
else if (pf^ = 'm') or (pf^ = 'M') then
Result := DecodeTagValue(pf, ps, 'm', 'M', M, c, 2)
else if (pf^ = 'd') or (pf^ = 'D') then
Result := DecodeTagValue(pf, ps, 'd', 'D', d, c, 2)
else if (pf^ = 'h') or (pf^ = 'H') then
Result := DecodeTagValue(pf, ps, 'h', 'H', H, c, 2)
else if (pf^ = 'n') or (pf^ = 'N') then
Result := DecodeTagValue(pf, ps, 'n', 'N', N, c, 2)
else if (pf^ = 's') or (pf^ = 'S') then
Result := DecodeTagValue(pf, ps, 's', 'S', S, c, 2)
else if (pf^ = 'z') or (pf^ = 'Z') then
Result := DecodeTagValue(pf, ps, 'z', 'Z', MS, c, 3)
else if (pf^ = '"') or (pf^ = '''') then
begin
pl := pf;
Inc(pf);
while ps^ = pf^ do
begin
Inc(pf);
Inc(ps);
end;
if pf^ = pl^ then
Inc(pf);
end
else if pf^ = ' ' then
begin
Inc(pf);
while ps^ = ' ' do
Inc(ps);
end
else if pf^ = ps^ then
begin
Inc(pf);
Inc(ps);
end
else
Result := false;
end;
Result := Result and ((ps^ = #0) or (ps^ = '+'));
if Result then
begin
if M = 0 then
M := 1;
if d = 0 then
d := 1;
Result := TryEncodeDate(Y, M, d, ADate);
Result := Result and TryEncodeTime(H, N, S, MS, ATime);
if Result then
AResult := ADate + ATime;
end;
end;
procedure SmartDetect;
var
V: Int64;
l: Integer;
ps, p, tz: PWideChar;
I, AOffset: Integer;
const
KnownFormats: array [0 .. 15] of String = ('y-m-d h:n:s.z', 'y-m-d h:n:s',
'y-m-d', 'h:n:s.z', 'h:n:s', 'y-m-d"T"h:n:s.z', 'y-m-d"T"h:n:s',
'd/m/y h:n:s.z', 'd/m/y h:n:s', 'd/m/y', 'm/d/y h:n:s.z', 'm/d/y h:n:s',
'm/d/y', 'y/m/d h:n:s.z', 'y/m/d h:n:s', 'y/m/d');
begin
ps := PWideChar(AStr);
tz := StrStrW(ps, '+'); // +xxyy
AOffset := 0;
if tz <> nil then
begin
l := (IntPtr(tz) - IntPtr(ps)) shr 1;
Inc(tz);
while tz^ <> #0 do
begin
AOffset := AOffset * 10 + Ord(tz^) - Ord('0');
Inc(tz);
end;
// Todo:Timezone将来处理下
end
else
l := Length(AStr);
Result := True;
if (l = 5) and DecodeAsFormat('h:n:s') then
Exit
else if l = 6 then
begin
if TryStrToInt64(AStr, V) then
begin
if V > 235959 then
// 大于这个的肯定不是时间,那么可能是yymmdd
begin
if not DecodeAsFormat('yymmdd') then
Result := false;
end
else if ((V mod 10000) > 1231) or ((V mod 100) > 31) then
// 月份+日期组合不可能大于1231
begin
if not DecodeAsFormat('hhnnss') then
Result := false;
end
else if not DecodeAsFormat('yymmdd') then
Result := false;
end;
end
// 检测连续的数字格式
else if (l = 8) and (DecodeAsFormat('hh:nn:ss') or
DecodeAsFormat('yy-mm-dd') or DecodeAsFormat('yyyymmdd')) then
Exit
else if (l = 9) and DecodeAsFormat('hhnnsszzz') then
Exit
else if l = 10 then
// yyyy-mm-dd yyyy/mm/dd mm/dd/yyyy dd.mm.yyyy dd/mm/yy
begin
p := ps;
Inc(p, 2);
if (p^ < '0') or (p^ > '9') then
// mm?dd?yyyy or dd?mm?yyyy
begin
// dd mm yyyy 的国家居多,优先识别为这种
if DecodeAsFormat('dd' + p^ + 'mm' + p^ + 'yyyy') or
DecodeAsFormat('mm' + p^ + 'dd' + p^ + 'yyyy') then
Exit;
end
else if DecodeAsFormat('yyyy-mm-dd') then // 其它格式都是100移动卡
Exit;
end
else if (l = 12) and (DecodeAsFormat('yymmddhhnnss') or
DecodeAsFormat('hh:nn:ss.zzz')) then
Exit
else if (l = 14) and DecodeAsFormat('yyyymmddhhnnss') then
Exit
else if (l = 17) and DecodeAsFormat('yyyymmddhhnnsszzz') then
Exit
else if (l = 20) and (DecodeAsFormat('yyyy-mm-dd hh:nn:ss') or
DecodeAsFormat('yyyy-mm-dd"T"hh:nn:ss')) then
Exit
else if (l = 23) and (DecodeAsFormat('yyyy-mm-dd hh:nn:ss.zzz') or
DecodeAsFormat('yyyy-mm-dd"T"hh:nn:ss.zzz')) then
Exit;
for I := Low(KnownFormats) to High(KnownFormats) do
begin
if DecodeAsFormat(KnownFormats[I]) then
Exit;
end;
if not ParseWebTime(ps, AResult) then
Result := false;
end;
begin
if Length(AFormat) > 0 then
Result := DecodeAsFormat(AFormat)
else
// 检测日期时间类型格式
SmartDetect;
end;
function DateTimeFromString(Str: QStringW; AFormat: QStringW; ADef: TDateTime)
: TDateTime; overload;
begin
if not DateTimeFromString(Str, Result, AFormat) then
Result := ADef;
end;
function ParseDateTime(S: PWideChar; var AResult: TDateTime): Boolean;
var
Y, M, d, H, N, Sec, MS: Cardinal;
AQuoter: WideChar;
ADate: TDateTime;
function ParseNum(var N: Cardinal): Boolean;
var
neg: Boolean;
ps: PQCharW;
begin
N := 0;
ps := S;
if S^ = '-' then
begin
neg := True;
Inc(S);
end
else
neg := false;
while S^ <> #0 do
begin
if (S^ >= '0') and (S^ <= '9') then
begin
N := N * 10 + Ord(S^) - 48;
if N >= 10000 then
begin
Result := false;
Exit;
end;
Inc(S);
end
else
Break;
end;
if neg then
N := -N;
Result := ps <> S;
end;
begin
if (S^ = '"') or (S^ = '''') then
begin
AQuoter := S^;
Inc(S);
end
else
AQuoter := #0;
Result := ParseNum(Y);
if not Result then
Exit;
if (S^ = '-') or (S^ = '/') then
begin
Inc(S);
Result := ParseNum(M);
if (not Result) or ((S^ <> '-') and (S^ <> '/')) then
begin
Result := false;
Exit;
end;
Inc(S);
Result := ParseNum(d);
if (not Result) or ((S^ <> 'T') and (S^ <> ' ') and (S^ <> #0)) then
begin
Result := false;
Exit;
end;
if S^ <> #0 then
Inc(S);
if d > 31 then // D -> Y
begin
if M > 12 then // M/D/Y M -> D, D->Y, Y->M
Result := TryEncodeDate(d, Y, M, ADate)
else // D/M/Y
Result := TryEncodeDate(d, M, Y, ADate);
end
else
Result := TryEncodeDate(Y, M, d, ADate);
if not Result then
Exit;
SkipSpaceW(S);
if S^ <> #0 then
begin
if not ParseNum(H) then // 没跟时间值
begin
AResult := ADate;
Exit;
end;
if S^ <> ':' then
begin
if H in [0 .. 23] then
AResult := ADate + EncodeTime(H, 0, 0, 0)
else
Result := false;
Exit;
end;
Inc(S);
end
else
begin
AResult := ADate;
Exit;
end;
end
else if S^ = ':' then
begin
ADate := 0;
H := Y;
Inc(S);
end
else
begin
Result := false;
Exit;
end;
if H > 23 then
begin
Result := false;
Exit;
end;
if not ParseNum(N) then
begin
if AQuoter <> #0 then
begin
if S^ = AQuoter then
AResult := ADate + EncodeTime(H, 0, 0, 0)
else
Result := false;
end
else
AResult := ADate + EncodeTime(H, 0, 0, 0);
Exit;
end
else if N > 59 then
begin
Result := false;
Exit;
end;
Sec := 0;
MS := 0;
if S^ = ':' then
begin
Inc(S);
if not ParseNum(Sec) then
begin
if AQuoter <> #0 then
begin
if S^ = AQuoter then
AResult := ADate + EncodeTime(H, N, 0, 0)
else
Result := false;
end
else
AResult := ADate + EncodeTime(H, N, 0, 0);
Exit;
end
else if Sec > 59 then
begin
Result := false;
Exit;
end;
if S^ = '.' then
begin
Inc(S);
if not ParseNum(MS) then
begin
if AQuoter <> #0 then
begin
if AQuoter = S^ then
AResult := ADate + EncodeTime(H, N, Sec, 0)
else
Result := false;
end
else
AResult := ADate + EncodeTime(H, N, Sec, 0);
Exit;
end
else if MS >= 1000 then // 超过1000是以微秒为单位计时的,转换为毫秒
begin
while MS >= 1000 do
MS := MS div 10;
end;
if AQuoter <> #0 then
begin
if AQuoter = S^ then
AResult := ADate + EncodeTime(H, N, Sec, MS)
else
Result := false;
Exit;
end
else
AResult := ADate + EncodeTime(H, N, Sec, MS);
end
else
begin
if AQuoter <> #0 then
begin
if AQuoter = S^ then
AResult := ADate + EncodeTime(H, N, Sec, 0)
else
Result := false;
end
else
AResult := ADate + EncodeTime(H, N, Sec, 0)
end;
end
else
begin
if AQuoter <> #0 then
begin
if AQuoter = S^ then
AResult := ADate + EncodeTime(H, N, 0, 0)
else
Result := false;
end
else
AResult := ADate + EncodeTime(H, N, 0, 0);
end;
end;
function ParseWebTime(p: PWideChar; var AResult: TDateTime): Boolean;
var
I: Integer;
Y, M, d, H, N, S, tz: Integer;
const
MonthNames: array [0 .. 11] of QStringW = ('Jan', 'Feb', 'Mar', 'Apr', 'May',
'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
WeekNames: array [0 .. 6] of QStringW = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri',
'Sat', 'Sun');
Comma: WideChar = ',';
Digits: PWideChar = '0123456789';
// Web 日期格式:星期, 日 月 年 时:分:秒 GMT
begin
// 跳过星期,这个可以直接通过日期计算出来,不需要
SkipSpaceW(p);
for I := 0 to High(WeekNames) do
begin
if StartWithW(p, PQCharW(WeekNames[I]), True) then
begin
Inc(p, Length(WeekNames[I]));
SkipSpaceW(p);
Break;
end;
end;
if p^ = Comma then
Inc(p);
SkipSpaceW(p);
d := 0;
// 日期
while (p^ >= '0') and (p^ <= '9') do
begin
d := d * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
if (not(IsSpaceW(p) or (p^ = '-'))) or (d < 1) or (d > 31) then
begin
Result := false;
Exit;
end;
if p^ = '-' then
Inc(p);
SkipSpaceW(p);
M := 0;
for I := 0 to 11 do
begin
if StartWithW(p, PWideChar(MonthNames[I]), True) then
begin
M := I + 1;
Inc(p, Length(MonthNames[I]));
Break;
end;
end;
if (not(IsSpaceW(p) or (p^ = '-'))) or (M < 1) or (M > 12) then
begin
Result := false;
Exit;
end;
if p^ = '-' then
Inc(p);
SkipSpaceW(p);
Y := 0;
while (p^ >= '0') and (p^ <= '9') do
begin
Y := Y * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
if not(IsSpaceW(p) or (p^ = '-')) then
begin
Result := false;
Exit;
end;
SkipSpaceW(p);
if p^ <> #0 then
begin
H := 0;
while (p^ >= '0') and (p^ <= '9') do
begin
H := H * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
if p^ <> ':' then
begin
Result := false;
Exit;
end;
Inc(p);
N := 0;
while (p^ >= '0') and (p^ <= '9') do
begin
N := N * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
if p^ <> ':' then
begin
Result := false;
Exit;
end;
Inc(p);
S := 0;
while (p^ >= '0') and (p^ <= '9') do
begin
S := S * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
SkipSpaceW(p);
tz := 0;
if StartWithW(p, 'GMT', True) then
begin
Inc(p, 3);
if p^ = '-' then
begin
Inc(p);
I := -1;
end
else
begin
if p^ = '+' then
Inc(p);
I := 1;
end;
SkipSpaceW(p);
while (p^ >= '0') and (p^ <= '9') do
begin
tz := tz * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
tz := tz * 60;
if p^ = ':' then
Inc(p);
while (p^ >= '0') and (p^ <= '9') do
begin
tz := tz * 10 + Ord(p^) - Ord('0');
Inc(p);
end;
tz := tz * I;
end;
end
else
begin
H := 0;
N := 0;
S := 0;
tz := 0;
end;
Result := TryEncodeDateTime(Y, M, d, H, N, S, 0, AResult);
if Result and (tz <> 0) then
AResult := IncMinute(AResult, -tz);
end;
function GetTimeZone: Integer;
var
{$IFDEF MSWindows}
TimeZone: TTimeZoneInformation;
{$ELSE}
tmLocal: TM;
t1: time_t;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
GetTimeZoneInformation(TimeZone);
Result := -TimeZone.Bias;
{$ELSE}
t1 := 0;
localtime_r(t1, tmLocal);
Result := tmLocal.tm_gmtoff div 60;
{$ENDIF}
end;
function GetTimezoneText: QStringW;
var
ATz: Integer;
begin
ATz := GetTimeZone;
if ATz > 0 then
Result := Format('+%.2d%.2d', [ATz div 60, ATz mod 60])
else
begin
ATz := -ATz;
Result := Format('-%.2d%.2d', [ATz div 60, ATz mod 60]);
end;
end;
function EncodeWebTime(ATime: TDateTime): QStringW;
var
Y, M, d, H, N, S, MS: Word;
ATimeZone: QStringW;
const
DefShortMonthNames: array [1 .. 12] of String = ('Jan', 'Feb', 'Mar', 'Apr',
'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
DefShortDayNames: array [1 .. 7] of String = ('Sun', 'Mon', 'Tue', 'Wed',
'Thu', 'Fri', 'Sat');
begin
if (ATime < MinDateTime) or (ATime > MaxDateTime) then
Result := ''
else
begin
DecodeDateTime(ATime, Y, M, d, H, N, S, MS);
Result := DefShortDayNames[DayOfWeek(ATime)] + ',' + IntToStr(d) + ' ' +
DefShortMonthNames[M] + ' ' + IntToStr(Y) + ' ' + IntToStr(H) + ':' +
IntToStr(N) + ':' + IntToStr(S);
ATimeZone := GetTimezoneText;
if Length(ATimeZone) > 0 then
Result := Result + ' GMT ' + ATimeZone;
end;
end;
function RollupSize(ASize: Int64): QStringW;
var
AIdx, R1, s1: Int64;
AIsNeg: Boolean;
const
Units: array [0 .. 5] of QStringW = ('EB', 'TB', 'GB', 'MB', 'KB', 'B');
begin
AIsNeg := (ASize < 0);
AIdx := High(Units);
R1 := 0;
if AIsNeg then
ASize := -ASize;
Result := '';
while (AIdx >= 0) do
begin
s1 := ASize mod 1024;
ASize := ASize shr 10;
if (ASize = 0) or (AIdx = 0) then
begin
R1 := R1 * 100 div 1024;
if R1 > 0 then
begin
if R1 >= 10 then
Result := IntToStr(s1) + '.' + IntToStr(R1) + Units[AIdx]
else
Result := IntToStr(s1) + '.' + '0' + IntToStr(R1) + Units[AIdx];
end
else
Result := IntToStr(s1) + Units[AIdx];
Break;
end;
R1 := s1;
Dec(AIdx);
end;
if AIsNeg then
Result := '-' + Result;
end;
function RollupTime(ASeconds: Int64; AHideZero: Boolean): QStringW;
var
H, N, d: Integer;
begin
if ASeconds = 0 then
begin
if AHideZero then
Result := ''
else
Result := '0' + SSecondName;
end
else
begin
Result := '';
d := ASeconds div 86400;
ASeconds := ASeconds mod 86400;
H := ASeconds div 3600;
ASeconds := ASeconds mod 3600;
N := ASeconds div 60;
ASeconds := ASeconds mod 60;
if d > 0 then
Result := IntToStr(d) + SDayName
else
Result := '';
if H > 0 then
Result := Result + IntToStr(H) + SHourName;
if N > 0 then
Result := Result + IntToStr(N) + SMinuteName;
if ASeconds > 0 then
Result := Result + IntToStr(ASeconds) + SSecondName;
end;
end;
{ QStringA }
function QStringA.From(p: PQCharA; AOffset, ALen: Integer): PQStringA;
begin
SetLength(ALen);
Inc(p, AOffset);
Move(p^, PQCharA(@FValue[1])^, ALen);
Result := @Self;
end;
function QStringA.From(const S: QStringA; AOffset: Integer): PQStringA;
begin
Result := From(PQCharA(S), AOffset, S.Length);
end;
function QStringA.GetChars(AIndex: Integer): QCharA;
begin
if (AIndex < 0) or (AIndex >= Length) then
raise Exception.CreateFmt(SOutOfIndex, [AIndex, 0, Length - 1]);
Result := FValue[AIndex + 1];
end;
function QStringA.GetData: PByte;
begin
Result := @FValue[1];
end;
class operator QStringA.Implicit(const S: QStringW): QStringA;
begin
Result := qstring.AnsiEncode(S);
end;
class operator QStringA.Implicit(const S: QStringA): PQCharA;
begin
Result := PQCharA(@S.FValue[1]);
end;
function QStringA.GetIsUtf8: Boolean;
begin
if System.Length(FValue) > 0 then
Result := (FValue[0] = 1)
else
Result := false;
end;
function QStringA.GetLength: Integer;
begin
// QStringA.FValue[0]存贮编码类型,0-ANSI,1-UTF8,末尾存贮字符串的\0结束符
Result := System.Length(FValue);
if Result >= 2 then
Dec(Result, 2)
else
Result := 0;
end;
class operator QStringA.Implicit(const S: QStringA): TBytes;
var
l: Integer;
begin
l := System.Length(S.FValue) - 1;
System.SetLength(Result, l);
if l > 0 then
Move(S.FValue[1], Result[0], l);
end;
procedure QStringA.SetChars(AIndex: Integer; const Value: QCharA);
begin
if (AIndex < 0) or (AIndex >= Length) then
raise Exception.CreateFmt(SOutOfIndex, [AIndex, 0, Length - 1]);
FValue[AIndex + 1] := Value;
end;
procedure QStringA.SetIsUtf8(const Value: Boolean);
begin
if System.Length(FValue) = 0 then
System.SetLength(FValue, 1);
FValue[0] := Byte(Value);
end;
procedure QStringA.SetLength(const Value: Integer);
begin
if Value < 0 then
begin
if System.Length(FValue) > 0 then
System.SetLength(FValue, 1)
else
begin
System.SetLength(FValue, 1);
FValue[0] := 0; // ANSI
end;
end
else
begin
System.SetLength(FValue, Value + 2);
FValue[Value + 1] := 0;
end;
end;
class function QStringA.UpperCase(S: PQCharA): QStringA;
var
l: Integer;
ps: PQCharA;
begin
if Assigned(S) then
begin
ps := S;
while S^ <> 0 do
begin
Inc(S)
end;
l := IntPtr(S) - IntPtr(ps);
Result.SetLength(l);
S := ps;
ps := PQCharA(Result);
while S^ <> 0 do
begin
ps^ := CharUpperA(S^);
Inc(ps);
Inc(S);
end;
end
else
Result.SetLength(0);
end;
function QStringA.UpperCase: QStringA;
var
l: Integer;
pd, ps: PQCharA;
begin
l := System.Length(FValue);
System.SetLength(Result.FValue, l);
if l > 0 then
begin
Result.FValue[0] := FValue[0];
Dec(l);
pd := PQCharA(Result);
ps := PQCharA(Self);
while l > 0 do
begin
pd^ := CharUpperA(ps^);
Inc(pd);
Inc(ps);
Dec(l);
end;
end;
end;
class operator QStringA.Implicit(const ABytes: TBytes): QStringA;
var
l: Integer;
begin
l := System.Length(ABytes);
Result.Length := l;
if l > 0 then
Move(ABytes[0], Result.FValue[1], l);
end;
class operator QStringA.Implicit(const S: QStringA): QStringW;
begin
Result := AnsiDecode(S);
end;
function BinToHex(p: Pointer; l: Integer; ALowerCase: Boolean): QStringW;
const
B2HConvert: array [0 .. 15] of QCharW = ('0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
B2HConvertL: array [0 .. 15] of QCharW = ('0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
var
pd: PQCharW;
pb: PByte;
begin
SetLength(Result, l shl 1);
pd := PQCharW(Result);
pb := p;
if ALowerCase then
begin
while l > 0 do
begin
pd^ := B2HConvertL[pb^ shr 4];
Inc(pd);
pd^ := B2HConvertL[pb^ and $0F];
Inc(pd);
Inc(pb);
Dec(l);
end;
end
else
begin
while l > 0 do
begin
pd^ := B2HConvert[pb^ shr 4];
Inc(pd);
pd^ := B2HConvert[pb^ and $0F];
Inc(pd);
Inc(pb);
Dec(l);
end;
end;
end;
function BinToHex(const ABytes: TBytes; ALowerCase: Boolean): QStringW;
begin
Result := BinToHex(@ABytes[0], Length(ABytes), ALowerCase);
end;
procedure HexToBin(const S: QStringW; var AResult: TBytes);
var
l: Integer;
p, ps: PQCharW;
pd: PByte;
begin
l := System.Length(S);
SetLength(AResult, l shr 1);
p := PQCharW(S);
ps := p;
pd := @AResult[0];
while p - ps < l do
begin
if IsHexChar(p[0]) and IsHexChar(p[1]) then
begin
pd^ := (HexValue(p[0]) shl 4) + HexValue(p[1]);
Inc(pd);
Inc(p, 2);
end
else
begin
SetLength(AResult, 0);
Exit;
end;
end;
end;
function HexToBin(const S: QStringW): TBytes;
begin
HexToBin(S, Result);
end;
procedure FreeObject(AObject: TObject);
begin
{$IFDEF AUTOREFCOUNT}
AObject.DisposeOf;
{$ELSE}
AObject.Free;
{$ENDIF}
end;
procedure FreeAndNilObject(var AObject);
var
ATemp: TObject;
begin
ATemp := TObject(AObject);
Pointer(AObject) := nil;
FreeObject(ATemp);
end;
function HashOf(p: Pointer; l: Integer): Cardinal;
{$IFDEF WIN32}
label A00, A01;
begin
asm
push ebx
mov eax,l
mov ebx,0
cmp eax,ebx
jz A01
xor eax, eax
mov edx, p
mov ebx,edx
add ebx,l
A00:
imul eax,131
movzx ecx, BYTE ptr [edx]
inc edx
add eax, ecx
cmp ebx, edx
jne A00
A01:
pop ebx
mov Result,eax
end;
{$ELSE}
var
pe: PByte;
ps: PByte absolute p;
const
seed = 131;
// 31 131 1313 13131 131313 etc..
begin
pe := p;
Inc(pe, l);
Result := 0;
while IntPtr(ps) < IntPtr(pe) do
begin
Result := Result * seed + ps^;
Inc(ps);
end;
Result := Result and $7FFFFFFF;
{$ENDIF}
end;
class operator QStringA.Implicit(const S: PQCharA): QStringA;
var
p: PQCharA;
begin
if S <> nil then
begin
p := S;
while p^ <> 0 do
Inc(p);
Result.Length := IntPtr(p) - IntPtr(S);
Move(S^, PQCharA(Result)^, Result.Length);
end
else
Result.Length := 0;
end;
{$IFNDEF NEXTGEN}
class operator QStringA.Implicit(const S: AnsiString): QStringA;
begin
Result.From(PQCharA(S), 0, System.Length(S));
end;
class operator QStringA.Implicit(const S: QStringA): AnsiString;
begin
System.SetLength(Result, S.Length);
if S.Length > 0 then
Move(PQCharA(S)^, PAnsiChar(Result)^, S.Length);
end;
{$ENDIF}
class function QStringA.LowerCase(S: PQCharA): QStringA;
var
l: Integer;
ps: PQCharA;
begin
if Assigned(S) then
begin
ps := S;
while S^ <> 0 do
begin
Inc(S)
end;
l := IntPtr(S) - IntPtr(ps);
Result.SetLength(l);
S := ps;
ps := PQCharA(Result);
while S^ <> 0 do
begin
ps^ := CharLowerA(S^);
Inc(ps);
Inc(S);
end;
end
else
Result.SetLength(0);
end;
function QStringA.LowerCase: QStringA;
var
l: Integer;
pd, ps: PQCharA;
begin
l := System.Length(FValue);
System.SetLength(Result.FValue, l);
if l > 0 then
begin
Result.FValue[0] := FValue[0];
Dec(l);
pd := PQCharA(Result);
ps := PQCharA(Self);
while l > 0 do
begin
pd^ := CharLowerA(ps^);
Inc(pd);
Inc(ps);
Dec(l);
end;
end;
end;
function QStringA.Cat(p: PQCharA; ALen: Integer): PQStringA;
var
l: Integer;
begin
l := Length;
SetLength(l + ALen);
Move(p^, FValue[1 + l], ALen);
Result := @Self;
end;
function QStringA.Cat(const S: QStringA): PQStringA;
begin
Result := Cat(PQCharA(S), S.Length);
end;
class function QStringA.Create(const p: PQCharA; AIsUtf8: Boolean): QStringA;
var
pe: PQCharA;
begin
pe := p;
while pe^ <> 0 do
Inc(pe);
Result.Cat(p, IntPtr(pe) - IntPtr(p));
Result.SetIsUtf8(AIsUtf8);
end;
{ TQStringCatHelperW }
function TQStringCatHelperW.Back(ALen: Integer): TQStringCatHelperW;
begin
Result := Self;
Dec(FDest, ALen);
if FDest < FStart then
FDest := FStart;
end;
function TQStringCatHelperW.BackIf(const S: PQCharW): TQStringCatHelperW;
var
ps: PQCharW;
begin
Result := Self;
ps := FStart;
while FDest > ps do
begin
if (FDest[-1] >= #$DC00) and (FDest[-1] <= #$DFFF) then
begin
if CharInW(FDest - 2, S) then
Dec(FDest, 2)
else
Break;
end
else if CharInW(FDest - 1, S) then
Dec(FDest)
else
Break;
end;
end;
function TQStringCatHelperW.Cat(const S: QStringW; AQuoter: QCharW)
: TQStringCatHelperW;
begin
Result := Cat(PQCharW(S), Length(S), AQuoter);
end;
function TQStringCatHelperW.Cat(p: PQCharW; len: Integer; AQuoter: QCharW)
: TQStringCatHelperW;
var
ps: PQCharW;
ACount: Integer;
procedure DirectMove;
begin
Move(p^, FDest^, len shl 1);
Inc(FDest, len);
end;
begin
Result := Self;
if (len < 0) or (AQuoter <> #0) then
begin
ps := p;
len := 0;
ACount := 0;
// 先计算长度,一次分配内存
while ps^ <> #0 do
begin
if ps^ = AQuoter then
Inc(ACount);
Inc(len);
Inc(ps);
end;
if AQuoter <> #0 then
NeedSize(-len - ACount - 2)
else
NeedSize(-len);
if AQuoter <> #0 then
begin
begin
FDest^ := AQuoter;
Inc(FDest);
// 如果引号数量为0,直接复制,不用循环
if ACount = 0 then
DirectMove
else
begin
while p^ <> #0 do
begin
FDest^ := p^;
Inc(FDest);
if p^ = AQuoter then
begin
FDest^ := p^;
Inc(FDest);
end;
Inc(p);
end;
end;
FDest^ := AQuoter;
Inc(FDest);
end;
end
else
DirectMove;
end
else
begin
NeedSize(-len);
DirectMove;
end;
end;
function TQStringCatHelperW.Cat(c: QCharW): TQStringCatHelperW;
begin
if Position >= FSize then
NeedSize(-1);
FDest^ := c;
Inc(FDest);
Result := Self;
end;
function TQStringCatHelperW.Cat(const V: Double): TQStringCatHelperW;
begin
Result := Cat(FloatToStr(V));
end;
function TQStringCatHelperW.Cat(const V: Int64): TQStringCatHelperW;
begin
Result := Cat(IntToStr(V));
end;
function TQStringCatHelperW.Cat(const V: Boolean): TQStringCatHelperW;
begin
Result := Cat(BoolToStr(V, True));
end;
function TQStringCatHelperW.Cat(const V: TGuid): TQStringCatHelperW;
begin
Result := Cat(GuidToString(V));
end;
function TQStringCatHelperW.Cat(const V: Currency): TQStringCatHelperW;
begin
Result := Cat(CurrToStr(V));
end;
constructor TQStringCatHelperW.Create(ASize: Integer);
begin
inherited Create;
if ASize < 8192 then
ASize := 8192
else if (ASize and $3FF) <> 0 then
ASize := ((ASize shr 10) + 1) shr 1;
FBlockSize := ASize;
NeedSize(FBlockSize);
end;
function TQStringCatHelperW.EndWith(const S: QStringW;
AIgnoreCase: Boolean): Boolean;
var
p: PQCharW;
begin
p := FDest;
Dec(p, Length(S));
if p >= FStart then
Result := StrNCmpW(p, PQCharW(S), AIgnoreCase, Length(S)) = 0
else
Result := false;
end;
constructor TQStringCatHelperW.Create;
begin
inherited Create;
FBlockSize := 8192;
NeedSize(FBlockSize);
end;
function TQStringCatHelperW.GetChars(AIndex: Integer): QCharW;
begin
Result := FStart[AIndex];
end;
function TQStringCatHelperW.GetIsEmpty: Boolean;
begin
Result := FDest <> FStart;
end;
function TQStringCatHelperW.GetPosition: Integer;
begin
Result := FDest - FStart;
end;
function TQStringCatHelperW.GetValue: QStringW;
var
l: Integer;
begin
l := Position;
SetLength(Result, l);
Move(FStart^, PQCharW(Result)^, l shl 1);
end;
procedure TQStringCatHelperW.IncSize(ADelta: Integer);
begin
NeedSize(-ADelta);
end;
procedure TQStringCatHelperW.LoadFromFile(const AFileName: QStringW);
begin
Reset;
Cat(LoadTextW(AFileName));
end;
procedure TQStringCatHelperW.LoadFromStream(const AStream: TStream);
begin
Reset;
Cat(LoadTextW(AStream));
end;
procedure TQStringCatHelperW.NeedSize(ASize: Integer);
var
Offset: Integer;
begin
Offset := FDest - FStart;
if ASize < 0 then
ASize := Offset - ASize;
if ASize > FSize then
begin
{$IFDEF DEBUG}
Inc(FAllocTimes);
{$ENDIF}
FSize := ((ASize + FBlockSize) div FBlockSize) * FBlockSize;
SetLength(FValue, FSize);
FStart := PQCharW(@FValue[0]);
FDest := FStart + Offset;
FLast := FStart + FSize;
end;
end;
function TQStringCatHelperW.Replicate(const S: QStringW; count: Integer)
: TQStringCatHelperW;
var
ps: PQCharW;
l: Integer;
begin
Result := Self;
if count > 0 then
begin
ps := PQCharW(S);
l := Length(S);
while count > 0 do
begin
Cat(ps, l);
Dec(count);
end;
end;
end;
procedure TQStringCatHelperW.Reset;
begin
FDest := FStart;
end;
procedure TQStringCatHelperW.SetDest(const Value: PQCharW);
begin
if Value < FStart then
FDest := FStart
else if Value > FLast then
FDest := FLast
else
FDest := Value;
end;
procedure TQStringCatHelperW.SetPosition(const Value: Integer);
begin
if Value <= 0 then
FDest := FStart
else if Value > Length(FValue) then
begin
NeedSize(Value);
FDest := FStart + Value;
end
else
FDest := FStart + Value;
end;
function TQStringCatHelperW.ToString: QStringW;
begin
Result := Value;
end;
procedure TQStringCatHelperW.TrimRight;
var
pd: PQCharW;
begin
pd := FDest;
Dec(pd);
while FStart < pd do
begin
if IsSpaceW(pd) then
Dec(pd)
else
Break;
end;
Inc(pd);
FDest := pd;
end;
function TQStringCatHelperW.Cat(const V: Variant): TQStringCatHelperW;
begin
Result := Cat(VarToStr(V));
end;
{ TQPtr }
class function TQPtr.Bind(AObject: TObject): IQPtr;
begin
Result := TQPtr.Create(AObject);
end;
class function TQPtr.Bind(AData: Pointer; AOnFree: TQPtrFreeEventG): IQPtr;
var
ATemp: TQPtr;
begin
ATemp := TQPtr.Create(AData);
ATemp.FOnFree.Method.Data := nil;
ATemp.FOnFree.OnFreeG := AOnFree;
Result := ATemp;
end;
class function TQPtr.Bind(AData: Pointer; AOnFree: TQPtrFreeEvent): IQPtr;
var
ATemp: TQPtr;
begin
ATemp := TQPtr.Create(AData);
{$IFDEF NEXTGEN}
PQPtrFreeEvent(@ATemp.FOnFree.OnFree)^ := AOnFree;
{$ELSE}
ATemp.FOnFree.OnFree := AOnFree;
{$ENDIF}
Result := ATemp;
end;
{$IFDEF UNICODE}
class function TQPtr.Bind(AData: Pointer; AOnFree: TQPtrFreeEventA): IQPtr;
var
ATemp: TQPtr;
begin
ATemp := TQPtr.Create(AData);
ATemp.FOnFree.Method.Data := Pointer(-1);
PQPtrFreeEventA(@ATemp.FOnFree.OnFreeA)^ := AOnFree;
Result := ATemp;
end;
{$ENDIF}
constructor TQPtr.Create(AObject: Pointer);
begin
inherited Create;
FObject := AObject;
end;
destructor TQPtr.Destroy;
begin
if Assigned(FObject) then
begin
if FOnFree.Method.Code <> nil then
begin
if FOnFree.Method.Data = nil then
FOnFree.OnFreeG(FObject)
{$IFDEF UNICODE}
else if FOnFree.Method.Data = Pointer(-1) then
TQPtrFreeEventA(FOnFree.OnFreeA)(FObject)
{$ENDIF}
else
{$IFDEF NEXTGEN}
begin
PQPtrFreeEvent(FOnFree.OnFree)^(FObject);
PQPtrFreeEvent(FOnFree.OnFree)^ := nil;
end;
{$ELSE}
FOnFree.OnFree(FObject);
{$ENDIF}
end
else
FreeAndNil(FObject);
end;
inherited;
end;
function TQPtr.Get: Pointer;
begin
Result := FObject;
end;
// 兼容2007版的原子操作接口
{$IF RTLVersion<24}
function AtomicCmpExchange(var Target: Integer; Value: Integer;
Comparand: Integer): Integer; inline;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedCompareExchange(Target, Value, Comparand);
{$ELSE}
Result := TInterlocked.CompareExchange(Target, Value, Comparand);
{$ENDIF}
end;
function AtomicCmpExchange(var Target: Pointer; Value: Pointer;
Comparand: Pointer): Pointer; inline;
begin
{$IFDEF MSWINDOWS}
Result := Pointer(InterlockedCompareExchange(PInteger(@Target)^,
Integer(Value), Integer(Comparand)));
{$ELSE}
Result := TInterlocked.CompareExchange(Target, Value, Comparand);
{$ENDIF}
end;
function AtomicIncrement(var Target: Integer; const Value: Integer)
: Integer; inline;
begin
{$IFDEF MSWINDOWS}
if Value = 1 then
Result := InterlockedIncrement(Target)
else if Value = -1 then
Result := InterlockedDecrement(Target)
else
Result := InterlockedExchangeAdd(Target, Value);
{$ELSE}
if Value = 1 then
Result := TInterlocked.Increment(Target)
else if Value = -1 then
Result := TInterlocked.Decrement(Target)
else
Result := TInterlocked.Add(Target, Value);
{$ENDIF}
end;
function AtomicDecrement(var Target: Integer): Integer; inline;
begin
// Result := InterlockedDecrement(Target);
Result := AtomicIncrement(Target, -1);
end;
function AtomicExchange(var Target: Integer; Value: Integer): Integer;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedExchange(Target, Value);
{$ELSE}
Result := TInterlocked.Exchange(Target, Value);
{$ENDIF}
end;
function AtomicExchange(var Target: Pointer; Value: Pointer): Pointer;
begin
{$IFDEF MSWINDOWS}
{$IF RTLVersion>19}
Result := InterlockedExchangePointer(Target, Value);
{$ELSE}
Result := Pointer(IntPtr(InterlockedExchange(IntPtr(Target), IntPtr(Value))));
{$IFEND}
{$ELSE}
Result := TInterlocked.Exchange(Target, Value);
{$ENDIF}
end;
{$IFEND <XE5}
// 位与,返回原值
function AtomicAnd(var Dest: Integer; const AMask: Integer): Integer; inline;
var
I: Integer;
begin
repeat
Result := Dest;
I := Result and AMask;
until AtomicCmpExchange(Dest, I, Result) = Result;
end;
// 位或,返回原值
function AtomicOr(var Dest: Integer; const AMask: Integer): Integer; inline;
var
I: Integer;
begin
repeat
Result := Dest;
I := Result or AMask;
until AtomicCmpExchange(Dest, I, Result) = Result;
end;
{ TQBytesCatHelper }
function TQBytesCatHelper.Back(ALen: Integer): TQBytesCatHelper;
begin
Result := Self;
Dec(FDest, ALen);
if IntPtr(FDest) < IntPtr(FStart) then
FDest := FStart;
end;
function TQBytesCatHelper.Cat(const V: Double): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Double));
end;
function TQBytesCatHelper.Cat(const V: Currency): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Currency));
end;
function TQBytesCatHelper.Cat(const V: Boolean): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Boolean));
end;
function TQBytesCatHelper.Cat(const S: QStringW): TQBytesCatHelper;
begin
Result := Cat(PQCharW(S), System.Length(S) shl 1);
end;
function TQBytesCatHelper.Cat(const V: Byte): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Byte));
end;
function TQBytesCatHelper.Cat(const V: Int64): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Int64));
end;
function TQBytesCatHelper.Cat(const c: QCharW): TQBytesCatHelper;
begin
Result := Cat(@c, SizeOf(QCharW));
end;
function TQBytesCatHelper.Cat(const V: Variant): TQBytesCatHelper;
begin
// ??这是一个有问题的实现,临时先这样,回头抽空改
Result := Cat(@V, SizeOf(Variant));
end;
function TQBytesCatHelper.Cat(const V: QStringA; ACStyle: Boolean)
: TQBytesCatHelper;
begin
if ACStyle then
Result := Cat(PQCharA(V), V.Length + 1)
else
Result := Cat(PQCharA(V), V.Length);
end;
{$IFNDEF NEXTGEN}
function TQBytesCatHelper.Cat(const V: AnsiChar): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(AnsiChar));
end;
function TQBytesCatHelper.Cat(const V: AnsiString): TQBytesCatHelper;
begin
Result := Cat(PAnsiChar(V), System.Length(V));
end;
{$ENDIF}
function TQBytesCatHelper.Cat(const V: Single): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Single));
end;
function TQBytesCatHelper.Cat(const V: Cardinal): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Cardinal));
end;
function TQBytesCatHelper.Cat(const V: Smallint): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Smallint));
end;
function TQBytesCatHelper.Cat(const V: Word): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Word));
end;
function TQBytesCatHelper.Cat(const V: Shortint): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Shortint));
end;
function TQBytesCatHelper.Cat(const V: Integer): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(Integer));
end;
function TQBytesCatHelper.Cat(const ABytes: TBytes): TQBytesCatHelper;
begin
if Length(ABytes) > 0 then
Result := Cat(@ABytes[0], Length(ABytes))
else
Result := Self;
end;
function TQBytesCatHelper.Cat(const AData: Pointer; const ALen: Integer)
: TQBytesCatHelper;
begin
Result := Self;
NeedSize(-ALen);
Move(AData^, FDest^, ALen);
Inc(FDest, ALen);
end;
function TQBytesCatHelper.Cat(const V: TGuid): TQBytesCatHelper;
begin
Result := Cat(@V, SizeOf(TGuid));
end;
constructor TQBytesCatHelper.Create(ASize: Integer);
begin
inherited Create;
FBlockSize := ASize;
NeedSize(FBlockSize);
end;
function TQBytesCatHelper.Delete(AStart: Integer; ACount: Cardinal)
: TQBytesCatHelper;
var
ATotal: Integer;
pDeleteStart, pDeleteEnd: PByte;
begin
Result := Self;
if AStart < 0 then // 从右删除指定的个数
begin
pDeleteStart := FDest;
Inc(pDeleteStart, AStart);
if IntPtr(pDeleteStart) < IntPtr(FStart) then
begin
Dec(ACount, IntPtr(FStart) - IntPtr(pDeleteStart));
pDeleteStart := FStart;
end;
end
else
begin
pDeleteStart := FStart;
Inc(pDeleteStart, AStart);
if IntPtr(pDeleteStart) >= IntPtr(FDest) then // 没有可以删除的内容
Exit;
end;
pDeleteEnd := pDeleteStart;
Inc(pDeleteEnd, ACount);
if (IntPtr(pDeleteEnd) >= IntPtr(FDest)) or
(IntPtr(pDeleteEnd) <= IntPtr(FStart)) then
FDest := pDeleteStart
else
begin
ATotal := IntPtr(FDest) - IntPtr(pDeleteEnd);
Move(pDeleteEnd^, pDeleteStart^, ATotal);
FDest := pDeleteStart;
Inc(FDest, ATotal);
end;
end;
constructor TQBytesCatHelper.Create;
begin
inherited Create;
FBlockSize := 8192;
NeedSize(FBlockSize);
end;
function TQBytesCatHelper.GetBytes(AIndex: Integer): Byte;
begin
Result := FValue[AIndex];
end;
function TQBytesCatHelper.GetPosition: Integer;
begin
Result := IntPtr(FDest) - IntPtr(FStart);
end;
function TQBytesCatHelper.GetValue: TBytes;
var
ALen: Integer;
begin
ALen := Position;
SetLength(Result, ALen);
if ALen > 0 then
Move(FValue[0], Result[0], ALen);
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Int64)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Int64));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Integer)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Integer));
end;
{$IFNDEF NEXTGEN}
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: AnsiString)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, PAnsiChar(V), Length(V));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: AnsiChar)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, 1);
end;
{$ENDIF}
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Cardinal)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Cardinal));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Shortint)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Shortint));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Byte)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, 1);
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Smallint)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Smallint));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Word)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Word));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: QStringA;
ACStyle: Boolean): TQBytesCatHelper;
begin
if ACStyle then
Result := Insert(AIndex, PQCharA(V), V.Length + 1)
else
Result := Insert(AIndex, PQCharA(V), V.Length);
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Currency)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Currency));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Boolean)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(Boolean));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Variant)
: TQBytesCatHelper;
begin
// ??这是一个有问题的实现,临时先这样,回头抽空改
Result := Insert(AIndex, @V, SizeOf(Variant));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: TGuid)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(V));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Double)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(V));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const S: QStringW)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, PQCharW(S), Length(S) shl 1);
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const c: QCharW)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @c, SizeOf(c));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const V: Single)
: TQBytesCatHelper;
begin
Result := Insert(AIndex, @V, SizeOf(V));
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const ABytes: TBytes)
: TQBytesCatHelper;
begin
if Length(ABytes) > 0 then
Result := Insert(AIndex, @ABytes[0], Length(ABytes))
else
Result := Self;
end;
function TQBytesCatHelper.Insert(AIndex: Cardinal; const AData: Pointer;
const ALen: Integer): TQBytesCatHelper;
begin
if AIndex >= Cardinal(Position) then
Result := Cat(AData, ALen)
else
begin
NeedSize(-ALen);
Move(PByte(UIntPtr(FStart) + AIndex)^,
PByte(IntPtr(FStart) + ALen + Integer(AIndex))^, ALen);
Move(AData^, PByte(UIntPtr(FStart) + AIndex)^, ALen);
Inc(FDest, ALen);
Result := Self;
end;
end;
procedure TQBytesCatHelper.NeedSize(ASize: Integer);
var
Offset: Integer;
begin
Offset := IntPtr(FDest) - IntPtr(FStart);
if ASize < 0 then
ASize := Offset - ASize;
if ASize > FSize then
begin
FSize := ((ASize + FBlockSize) div FBlockSize) * FBlockSize;
SetLength(FValue, FSize);
FStart := @FValue[0];
FDest := PByte(IntPtr(FStart) + Offset);
end;
end;
function TQBytesCatHelper.Replicate(const ABytes: TBytes; ACount: Integer)
: TQBytesCatHelper;
var
l: Integer;
begin
Result := Self;
l := Length(ABytes);
if l > 0 then
begin
NeedSize(-l * ACount);
while ACount > 0 do
begin
Move(ABytes[0], FDest^, l);
Inc(FDest, l);
Dec(ACount);
end;
end;
end;
procedure TQBytesCatHelper.Reset;
begin
FDest := FStart;
end;
procedure TQBytesCatHelper.SetCapacity(const Value: Integer);
begin
if FSize <> Value then
NeedSize(Value);
end;
procedure TQBytesCatHelper.SetPosition(const Value: Integer);
begin
if Value <= 0 then
FDest := FStart
else if Value > Length(FValue) then
begin
NeedSize(Value);
FDest := Pointer(IntPtr(FStart) + Value);
end
else
FDest := Pointer(IntPtr(FStart) + Value);
end;
function NewId: TGuid;
begin
CreateGUID(Result);
end;
function SameId(const V1, V2: TGuid): Boolean;
var
I1: array [0 .. 1] of Int64 absolute V1;
I2: array [0 .. 1] of Int64 absolute V2;
begin
Result := (I1[0] = I2[0]) and (I1[1] = I2[1]);
end;
function StrLikeX(var S: PQCharW; pat: PQCharW; AIgnoreCase: Boolean): PQCharW;
const
CHAR_DIGITS = -1;
CHAR_NODIGITS = -2;
CHAR_SPACES = -3;
CHAR_NOSPACES = -4;
var
Accept: Boolean;
ACharCode, AEndCode: Integer;
AToken: QStringW;
ps, pt, os: PQCharW;
// >0 正常的字符编码
// <0 特殊范围
function Unescape(var T: PQCharW): Integer;
begin
if T^ = '\' then
begin
Inc(T);
case T^ of
'b':
begin
Inc(T);
Result := 7;
end;
'd':
begin
Inc(T);
Result := CHAR_DIGITS;
end;
'D':
begin
Inc(T);
Result := CHAR_NODIGITS;
end;
'r':
begin
Inc(T);
Result := 13;
end;
'n':
begin
Inc(T);
Result := 10;
end;
't':
begin
Inc(T);
Result := 9;
end;
'f': // \f
begin
Inc(T);
Result := 12;
end;
'v': // \v
begin
Inc(T);
Result := 11;
end;
's': // 空白字符
begin
Inc(T);
Result := CHAR_SPACES;
end;
'S': // 非空白
begin
Inc(T);
Result := CHAR_NOSPACES;
end;
'u': // Unicode字符
begin
if IsHexChar(T[1]) and IsHexChar(T[2]) and IsHexChar(T[3]) and
IsHexChar(T[4]) then
begin
Result := (HexValue(T[1]) shl 12) or (HexValue(T[2]) shl 8) or
(HexValue(T[3]) shl 4) or HexValue(T[4]);
Inc(T, 5);
end
else
raise Exception.CreateFmt(SCharNeeded,
['0-9A-Fa-f', StrDupW(T, 0, 4)]);
end
else
begin
Inc(T);
Result := Ord(S^);
end;
end;
end
else
begin
Result := Ord(T^);
end
end;
function IsDigit: Boolean;
begin
Result := ((S^ >= '0') and (S^ <= '9')) or
((S^ >= #65296) and (S^ <= #65305));
end;
function IsMatch(AStart, AEnd: Integer): Boolean;
var
ACode: Integer;
begin
case AStart of
CHAR_DIGITS:
Result := IsDigit;
CHAR_NODIGITS:
Result := not IsDigit;
CHAR_SPACES:
Result := IsSpaceW(S);
CHAR_NOSPACES:
Result := not IsSpaceW(S)
else
begin
ACode := Ord(S^);
Result := (ACode >= AStart) and (ACode <= AEnd);
if (not Result) and AIgnoreCase then
begin
ACode := Ord(CharUpperW(S^));
AStart := Ord(CharUpperW(QCharW(AStart)));
AEnd := Ord(CharUpperW(QCharW(AEnd)));
Result := (ACode >= AStart) and (ACode <= AEnd);
end;
// 如果是扩展区字符,需要两个连续的转义
if Result and ((ACode >= $D800) and (ACode <= $DFFF)) then
begin
Inc(S);
if pat^ = '\' then
begin
ACode := Unescape(pat);
Result := Ord(S^) = ACode;
end
else
Result := false;
end;
end;
end;
end;
function IsIn: Boolean;
const
SetEndChar: PQCharW = ']';
begin
Result := false;
while (pat^ <> #0) and (pat^ <> ']') do
begin
ACharCode := Unescape(pat);
if pat^ = '-' then // a-z这种范围
begin
Inc(pat);
if pat^ <> ']' then
AEndCode := Unescape(pat)
else
begin
raise Exception.Create(SRangeEndNeeded);
end;
end
else
AEndCode := ACharCode;
Result := IsMatch(ACharCode, AEndCode);
if Result then // 在其中的话,忽略掉后面的判定
begin
Inc(S);
SkipUntilW(pat, SetEndChar);
if pat^ <> ']' then
raise Exception.CreateFmt(SCharNeeded, [']']);
end
else
Inc(pat);
end;
end;
begin
// SQL Like 语法:
// _ 代表一个字符
// % * 代表任意字符
// [字符列表] 列表中任意字符
// [^字符列表]/[!字符列表] 非列表中任意字符
// 以下为QDAC扩展
// \ 转义
// \d 数字(全角和半角)
// \D 非数字(含全角)
// \s 空白字符
// \S 非空白字符
os := S;
Result := nil;
while (pat^ <> #0) and (S^ <> #0) do
begin
case pat^ of
'_':
begin
Inc(S, CharSizeW(S));
Inc(pat);
end;
'[': // 字符列表
begin
Inc(pat);
if (pat^ = '!') or (pat^ = '^') then
begin
Inc(pat);
Accept := not IsIn;
end
else
Accept := IsIn;
if pat^ = ']' then
begin
Inc(pat);
end;
if not Accept then
Exit;
end;
'\':
begin
ACharCode := Unescape(pat);
if not IsMatch(ACharCode, ACharCode) then
Exit
else
Inc(S);
end;
'*', '%':
begin
Inc(pat);
// 匹配任意长度的任意字符
if pat^ = #0 then
begin
Result := os;
while S^ <> #0 do
Inc(S);
Exit;
end
else
begin
// 多个连续的*或%号视为
while (pat^ = '%') or (pat^ = '*') do
Inc(pat);
ps := pat;
// 找到下一个任意匹配规则边界
while (pat^ <> #0) and (pat^ <> '*') do
Inc(pat);
// 匹配子串及剩余部分
AToken := StrDupX(ps, (IntPtr(pat) - IntPtr(ps)) shr 1);
repeat
pt := S;
ps := StrLikeX(S, PQCharW(AToken), AIgnoreCase);
if ps <> nil then
begin
if (pat^ <> #0) and (StrLikeX(S, pat, AIgnoreCase) = nil) then
begin
Inc(pt);
S := pt;
end
else
begin
Result := os;
while S^ <> #0 do
Inc(S);
Exit;
end;
end
else
begin
Inc(pt);
S := pt;
end;
until (S^ = #0);
// 如果上面没有匹配到,说明失败了
Exit;
end;
end
else // 普通字符的比较
begin
if not IsMatch(Ord(pat^), Ord(pat^)) then
Exit;
Inc(S);
Inc(pat);
end;
end;
end;
if (pat^ = '%') or (pat^ = '*') then // 模式匹配
Inc(pat);
if pat^ = #0 then
Result := os;
end;
function StrLikeW(S, pat: PQCharW; AIgnoreCase: Boolean): Boolean;
var
ps: PQCharW;
begin
ps := S;
Result := (StrLikeX(S, pat, AIgnoreCase) = ps) and (S^ = #0);
end;
{ TQPagedList }
function TQPagedList.Add(const p: Pointer): Integer;
begin
Result := FCount;
Insert(Result, p);
end;
{$IF RTLVersion<26}
procedure TQPagedList.Assign(ListA: TList; AOperator: TListAssignOp;
ListB: TList);
var
I: Integer;
LTemp: TQPagedList;
LSource: TList;
begin
// ListB given?
if ListB <> nil then
begin
LSource := ListB;
Assign(ListA);
end
else
LSource := ListA;
// on with the show
case AOperator of
// 12345, 346 = 346 : only those in the new list
laCopy:
begin
Clear;
for I := 0 to LSource.count - 1 do
Add(LSource[I]);
end;
// 12345, 346 = 34 : intersection of the two lists
laAnd:
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) = -1 then
Delete(I);
// 12345, 346 = 123456 : union of the two lists
laOr:
for I := 0 to LSource.count - 1 do
if IndexOf(LSource[I]) = -1 then
Add(LSource[I]);
// 12345, 346 = 1256 : only those not in both lists
laXor:
begin
LTemp := TQPagedList.Create; // Temp holder of 4 byte values
try
for I := 0 to LSource.count - 1 do
if IndexOf(LSource[I]) = -1 then
LTemp.Add(LSource[I]);
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) <> -1 then
Delete(I);
I := count + LTemp.count;
if Capacity < I then
Capacity := I;
for I := 0 to LTemp.count - 1 do
Add(LTemp[I]);
finally
LTemp.Free;
end;
end;
// 12345, 346 = 125 : only those unique to source
laSrcUnique:
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) <> -1 then
Delete(I);
// 12345, 346 = 6 : only those unique to dest
laDestUnique:
begin
LTemp := TQPagedList.Create;
try
for I := LSource.count - 1 downto 0 do
if IndexOf(LSource[I]) = -1 then
LTemp.Add(LSource[I]);
Assign(LTemp);
finally
LTemp.Free;
end;
end;
end;
end;
{$IFEND}
procedure TQPagedList.BatchAdd(pp: PPointer; ACount: Integer);
begin
BatchInsert(FCount, pp, ACount);
end;
procedure TQPagedList.BatchAdd(AList: TPointerList);
begin
if Length(AList) > 0 then
BatchInsert(FCount, @AList[0], Length(AList));
end;
procedure TQPagedList.Assign(ListA: TQPagedList; AOperator: TListAssignOp;
ListB: TQPagedList);
var
I: Integer;
LTemp, LSource: TQPagedList;
begin
// ListB given?
if ListB <> nil then
begin
LSource := ListB;
Assign(ListA);
end
else
LSource := ListA;
case AOperator of
// 12345, 346 = 346 : only those in the new list
laCopy:
begin
Clear;
for I := 0 to LSource.count - 1 do
Add(LSource[I]);
end;
// 12345, 346 = 34 : intersection of the two lists
laAnd:
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) = -1 then
Delete(I);
// 12345, 346 = 123456 : union of the two lists
laOr:
for I := 0 to LSource.count - 1 do
if IndexOf(LSource[I]) = -1 then
Add(LSource[I]);
// 12345, 346 = 1256 : only those not in both lists
laXor:
begin
LTemp := TQPagedList.Create; // Temp holder of 4 byte values
try
for I := 0 to LSource.count - 1 do
if IndexOf(LSource[I]) = -1 then
LTemp.Add(LSource[I]);
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) <> -1 then
Delete(I);
I := count + LTemp.count;
if Capacity < I then
Capacity := I;
for I := 0 to LTemp.count - 1 do
Add(LTemp[I]);
finally
LTemp.Free;
end;
end;
// 12345, 346 = 125 : only those unique to source
laSrcUnique:
for I := count - 1 downto 0 do
if LSource.IndexOf(Items[I]) <> -1 then
Delete(I);
// 12345, 346 = 6 : only those unique to dest
laDestUnique:
begin
LTemp := TQPagedList.Create;
try
for I := LSource.count - 1 downto 0 do
if IndexOf(LSource[I]) = -1 then
LTemp.Add(LSource[I]);
Assign(LTemp);
finally
LTemp.Free;
end;
end;
end;
end;
procedure TQPagedList.CheckLastPage;
begin
while (FLastUsedPage > 0) and (FPages[FLastUsedPage].FUsedCount = 0) do
Dec(FLastUsedPage);
end;
procedure TQPagedList.Clear;
var
I: Integer;
J: Integer;
begin
for I := 0 to High(FPages) do
begin
for J := 0 to FPages[I].FUsedCount - 1 do
DoDelete(FPages[I].FItems[J]);
FPages[I].FUsedCount := 0;
end;
FFirstDirtyPage := 1;
if Length(FPages) > 0 then
begin
FLastUsedPage := 0;
FPages[0].FUsedCount := 0;
end
else
FLastUsedPage := -1;
FCount := 0;
end;
procedure TQPagedList.Pack;
var
ASource, ADest, AStartMove, AToMove, APageCount: Integer;
ADestPage, ASourcePage: TQListPage;
procedure PackPages(AStartPage: Integer);
var
I: Integer;
begin
if AStartPage < APageCount then
begin
I := AStartPage;
while I < APageCount do
begin
FreeAndNil(FPages[I]);
Inc(I);
end;
SetLength(FPages, AStartPage);
FLastUsedPage := AStartPage - 1;
FFirstDirtyPage := AStartPage + 1;
end;
end;
procedure NextDest;
var
APriorPage: TQListPage;
ANewDest: Integer;
begin
ANewDest := ADest;
repeat
ADestPage := FPages[ANewDest];
if ADestPage.FUsedCount = FPageSize then
Inc(ANewDest)
else
begin
if (ADest <> ANewDest) then
begin
ADest := ANewDest;
if ASource <> ADest then
begin
APriorPage := FPages[ADest - 1];
ADestPage.FStartIndex := APriorPage.FStartIndex +
APriorPage.FUsedCount;
end;
end;
Break;
end;
until ADest = ASource;
end;
function NextSource: Boolean;
begin
Inc(ASource);
Result := false;
while ASource <= FLastUsedPage do
begin
ASourcePage := FPages[ASource];
if (ASourcePage.FUsedCount > 0) then
begin
Result := True;
Break;
end
else
Inc(ASource);
end;
end;
procedure CleanPages;
var
I: Integer;
begin
I := FFirstDirtyPage;
while I < APageCount do
begin
FPages[I].FStartIndex := FPages[I - 1].FStartIndex + FPages[I - 1]
.FUsedCount;
Inc(I);
end;
end;
begin
APageCount := Length(FPages);
if count > 0 then
begin
ADest := 0;
ASource := 0;
CleanPages;
while NextSource do
begin
AStartMove := 0;
NextDest;
if ADestPage <> ASourcePage then
begin
while (ADestPage <> ASourcePage) do
begin
AToMove := ASourcePage.FUsedCount - AStartMove;
if AToMove > FPageSize - ADestPage.FUsedCount then
AToMove := FPageSize - ADestPage.FUsedCount;
System.Move(ASourcePage.FItems[AStartMove],
ADestPage.FItems[ADestPage.FUsedCount], AToMove * SizeOf(Pointer));
Inc(AStartMove, AToMove);
Inc(ADestPage.FUsedCount, AToMove);
if ASourcePage.FUsedCount = AStartMove then
begin
ASourcePage.FStartIndex := ADestPage.FStartIndex +
ADestPage.FUsedCount;
ASourcePage.FUsedCount := 0;
Break;
end;
if ADestPage.FUsedCount = FPageSize then
begin
System.Move(ASourcePage.FItems[AStartMove], ASourcePage.FItems[0],
(ASourcePage.FUsedCount - AStartMove) * SizeOf(Pointer));
Dec(ASourcePage.FUsedCount, AStartMove);
Inc(ASourcePage.FStartIndex, AStartMove);
AStartMove := 0;
NextDest;
end;
end;
end;
end;
if ADestPage.FUsedCount = 0 then
PackPages(ADest)
else
PackPages(ADest + 1);
end
else
PackPages(0);
end;
constructor TQPagedList.Create(APageSize: Integer);
begin
inherited Create;
if APageSize <= 0 then
APageSize := 512;
FPageSize := APageSize;
FLastUsedPage := -1;
FFirstDirtyPage := 1;
end;
constructor TQPagedList.Create;
begin
Create(512);
end;
procedure TQPagedList.Delete(AIndex: Integer);
var
APage: Integer;
ATemp: TQListPage;
begin
APage := FindPage(AIndex);
if APage >= 0 then
begin
ATemp := FPages[APage];
Dec(AIndex, ATemp.FStartIndex);
DoDelete(ATemp.FItems[AIndex]);
System.Move(ATemp.FItems[AIndex + 1], ATemp.FItems[AIndex],
SizeOf(Pointer) * (ATemp.FUsedCount - AIndex - 1));
Dec(ATemp.FUsedCount);
CheckLastPage;
Dec(FCount);
Dirty(APage + 1);
end;
end;
destructor TQPagedList.Destroy;
var
I: Integer;
begin
Clear;
for I := 0 to High(FPages) do
FreeObject(FPages[I]);
{$IFDEF UNICODE}
if (TMethod(FOnCompare).Code <> nil) and
(TMethod(FOnCompare).Data = Pointer(-1)) then
TQPagedListSortCompareA(TMethod(FOnCompare).Code) := nil;
{$ENDIF}
inherited;
end;
procedure TQPagedList.Dirty(APage: Integer);
begin
if APage < FFirstDirtyPage then
FFirstDirtyPage := APage;
end;
function TQPagedList.DoCompare(p1, p2: Pointer): Integer;
begin
case IntPtr(TMethod(FOnCompare).Data) of
0: // 全局函数
TQPagedListSortCompareG(TMethod(FOnCompare).Code)(p1, p2, Result);
{$IFDEF UNICODE}
-1: // 匿名函数
TQPagedListSortCompareA(TMethod(FOnCompare).Code)(p1, p2, Result)
{$ENDIF}
else
FOnCompare(p1, p2, Result);
end;
end;
procedure TQPagedList.DoDelete(const p: Pointer);
begin
if (p <> nil) and (ClassType <> TQPagedList) then
Notify(p, lnDeleted);
end;
procedure TQPagedList.Exchange(AIndex1, AIndex2: Integer);
var
p1, p2: TQListPage;
T: Pointer;
begin
p1 := GetPage(AIndex1);
p2 := GetPage(AIndex2);
if (p1 <> nil) and (p2 <> nil) then
begin
Dec(AIndex1, p1.FStartIndex);
Dec(AIndex2, p2.FStartIndex);
T := p1.FItems[AIndex1];
p1.FItems[AIndex1] := p2.FItems[AIndex2];
p2.FItems[AIndex2] := T;
end;
end;
function TQPagedList.Expand: TQPagedList;
begin
// 这个函数只是为兼容TList接口保留,TQPagedList不需要
Result := Self;
end;
function TQPagedList.Extract(Item: Pointer): Pointer;
begin
Result := ExtractItem(Item, FromBeginning);
end;
function TQPagedList.ExtractItem(Item: Pointer; Direction: TDirection): Pointer;
var
I: Integer;
begin
Result := nil;
I := IndexOfItem(Item, Direction);
if I >= 0 then
begin
Result := Item;
Remove(I);
if ClassType <> TQPagedList then
Notify(Result, lnExtracted);
end;
end;
function TQPagedList.Find(const p: Pointer; var AIdx: Integer): Boolean;
var
l, H, I, c: Integer;
begin
Result := false;
l := 0;
H := FCount - 1;
while l <= H do
begin
I := (l + H) shr 1;
c := DoCompare(Items[I], p);
if c < 0 then
l := I + 1
else
begin
H := I - 1;
if c = 0 then
Result := True;
end;
end;
AIdx := l;
end;
function TQPagedList.FindPage(AIndex: Integer): Integer;
var
l, H, I, AMax, c: Integer;
ATemp: TQListPage;
begin
c := Length(FPages);
ATemp := FPages[FFirstDirtyPage - 1];
if (FFirstDirtyPage < c) and (AIndex >= ATemp.FStartIndex + ATemp.FUsedCount)
then
begin
I := FFirstDirtyPage;
while I < c do
begin
ATemp := FPages[I - 1];
FPages[I].FStartIndex := ATemp.FStartIndex + ATemp.FUsedCount;
if FPages[I].FStartIndex > AIndex then
begin
Result := I - 1;
FFirstDirtyPage := I + 1;
Exit;
end
else if FPages[I].FStartIndex = AIndex then
begin
Result := I;
FFirstDirtyPage := I + 1;
Exit;
end;
Inc(I);
end;
H := c - 1;
end
else
H := FFirstDirtyPage - 1;
l := AIndex div FPageSize;
while l <= H do
begin
I := (l + H) shr 1;
ATemp := FPages[I];
AMax := ATemp.FStartIndex + ATemp.FUsedCount - 1; // 最大的索引号
if AIndex > AMax then
l := I + 1
else
begin
H := I - 1;
if (AIndex >= ATemp.FStartIndex) and (AIndex <= AMax) then
begin
Result := I;
Exit;
end;
end;
end;
Result := -1;
end;
function TQPagedList.First: Pointer;
begin
Result := Items[0];
end;
function TQPagedList.GetCapacity: Integer;
begin
Result := Length(FPages) * FPageSize;
end;
function TQPagedList.GetEnumerator: TQPagedListEnumerator;
begin
Result := TQPagedListEnumerator.Create(Self);
end;
function TQPagedList.GetItems(AIndex: Integer): Pointer;
var
APage: TQListPage;
begin
APage := GetPage(AIndex);
if APage <> nil then
begin
Dec(AIndex, APage.FStartIndex);
Result := APage.FItems[AIndex];
end
else
raise Exception.Create('索引越界:' + IntToStr(AIndex));
end;
function TQPagedList.GetList: TPointerList;
var
I, K: Integer;
APage: TQListPage;
begin
SetLength(Result, count);
K := 0;
for I := 0 to High(FPages) do
begin
APage := FPages[I];
if APage.FUsedCount > 0 then
begin
System.Move(APage.FItems[0], Result[K],
APage.FUsedCount * SizeOf(Pointer));
Inc(K, APage.FUsedCount);
end;
end;
end;
function TQPagedList.GetPage(AIndex: Integer): TQListPage;
var
l, H, I, AMax, c: Integer;
ATemp: TQListPage;
begin
Result := nil;
c := Length(FPages);
ATemp := FPages[FFirstDirtyPage - 1];
if (FFirstDirtyPage < c) and (AIndex >= ATemp.FStartIndex + ATemp.FUsedCount)
then
begin
I := FFirstDirtyPage;
while I < c do
begin
ATemp := FPages[I - 1];
FPages[I].FStartIndex := ATemp.FStartIndex + ATemp.FUsedCount;
if FPages[I].FStartIndex > AIndex then
begin
Result := ATemp;
FFirstDirtyPage := I + 1;
Exit;
end
else if FPages[I].FStartIndex = AIndex then
begin
Result := FPages[I];
FFirstDirtyPage := I + 1;
Exit;
end;
Inc(I);
end;
H := c - 1;
end
else
H := FFirstDirtyPage - 1;
// 最坏的情况来说,假设每页都填满,最低索引位置为AIndex div Page
l := AIndex div FPageSize;
while l <= H do
begin
I := (l + H) shr 1;
ATemp := FPages[I];
AMax := ATemp.FStartIndex + ATemp.FUsedCount - 1;
// 最大的索引号
if AIndex > AMax then
l := I + 1
else
begin
H := I - 1;
if (AIndex >= ATemp.FStartIndex) and (AIndex <= AMax) then
begin
Result := ATemp;
Exit;
end;
end;
end;
end;
function TQPagedList.GetPageCount: Integer;
begin
Result := Length(FPages);
end;
function TQPagedList.IndexOf(Item: Pointer): Integer;
var
I, J: Integer;
begin
if TMethod(FOnCompare).Code <> nil then
begin
if not Find(Item, Result) then
Result := -1;
end
else
begin
Result := -1;
for I := 0 to High(FPages) do
begin
for J := 0 to FPages[I].FUsedCount do
begin
if FPages[I].FItems[J] = Item then
begin
Result := FPages[I].FStartIndex + J;
Exit;
end;
end;
end;
end;
end;
function TQPagedList.IndexOfItem(Item: Pointer; Direction: TDirection): Integer;
var
I, J: Integer;
begin
if Direction = FromBeginning then
Result := IndexOf(Item)
else
begin
Result := -1;
for I := High(FPages) downto 0 do
begin
for J := FPages[I].FUsedCount - 1 downto 0 do
begin
if FPages[I].FItems[J] = Item then
begin
Result := FPages[I].FStartIndex + J;
Exit;
end;
end;
end;
end;
end;
procedure TQPagedList.BatchInsert(AIndex: Integer; pp: PPointer;
ACount: Integer);
var
APage, ANeedPages, APageCount, AOffset, ARemain, AToMove: Integer;
ASourcePage, ADestPage: TQListPage;
ASplitNeeded: Boolean;
procedure SplitPage;
begin
ADestPage := FPages[APage];
ADestPage.FStartIndex := ASourcePage.FStartIndex;
ADestPage.FUsedCount := AIndex - ASourcePage.FStartIndex;
System.Move(ASourcePage.FItems[0], ADestPage.FItems[0],
ADestPage.FUsedCount * SizeOf(Pointer));
Dec(ASourcePage.FUsedCount, ADestPage.FUsedCount);
System.Move(ASourcePage.FItems[ADestPage.FUsedCount], ASourcePage.FItems[0],
ASourcePage.FUsedCount * SizeOf(Pointer));
Inc(APage);
Dec(ANeedPages);
end;
procedure NewPages;
var
ATempList: TPointerList;
AEmptyPages: Integer;
begin
APageCount := Length(FPages);
// 计算需要的页数
ANeedPages := ACount div FPageSize;
if (ACount mod FPageSize) <> 0 then
Inc(ANeedPages);
AEmptyPages := APageCount;
if FLastUsedPage >= 0 then
begin
if FPages[FLastUsedPage].FUsedCount = 0 then
Dec(FLastUsedPage);
Dec(AEmptyPages, FLastUsedPage + 1);
end;
if AIndex = 0 then
APage := 0
else if AIndex = FCount then
APage := FLastUsedPage + 1
else
begin
APage := FindPage(AIndex);
ASourcePage := FPages[APage];
ASplitNeeded := AIndex > ASourcePage.FStartIndex;
if ASplitNeeded then
// 如果插入的位置是页中间,需要额外一页来存贮前面的元素
Inc(ANeedPages);
end;
if AEmptyPages >= ANeedPages then // 空闲的页足够的话
begin
if FCount = 0 then // 没有任何记录,此时AIndex=0,直接预留页就可以了
begin
FLastUsedPage := ANeedPages - 1;
FFirstDirtyPage := ANeedPages;
end
else
begin
SetLength(ATempList, ANeedPages);
System.Move(ATempList[0], FPages[APage], ANeedPages * SizeOf(Pointer));
System.Move(FPages[APage], FPages[APage + ANeedPages],
(FLastUsedPage - APage + 1) * SizeOf(Pointer));
System.Move(ATempList[0], FPages[APage], ANeedPages * SizeOf(Pointer));
if ASplitNeeded then
SplitPage;
Inc(FLastUsedPage, ANeedPages);
end;
Exit;
end
else // 空闲页不足
begin
SetLength(FPages, APageCount + ANeedPages - AEmptyPages);
if FLastUsedPage >= APage then
begin
SetLength(ATempList, AEmptyPages);
if AEmptyPages > 0 then
System.Move(FPages[FLastUsedPage + 1], ATempList[0],
AEmptyPages * SizeOf(Pointer));
System.Move(FPages[APage], FPages[APage + ANeedPages],
(FLastUsedPage - APage + 1) * SizeOf(Pointer));
if AEmptyPages > 0 then
System.Move(ATempList[0], FPages[APage],
AEmptyPages * SizeOf(Pointer));
end;
AOffset := APage + AEmptyPages;
AToMove := ANeedPages - AEmptyPages;
while AToMove > 0 do
begin
FPages[AOffset] := TQListPage.Create(FPageSize);
Inc(AOffset);
Dec(AToMove);
end;
if ASplitNeeded then
SplitPage;
FLastUsedPage := High(FPages);
end;
end;
begin
if AIndex < 0 then
AIndex := 0
else if AIndex > FCount then
AIndex := FCount;
NewPages;
ARemain := ACount;
while ARemain > 0 do
begin
ADestPage := FPages[APage];
ADestPage.FStartIndex := AIndex;
AToMove := ARemain;
if AToMove >= FPageSize then
AToMove := FPageSize;
System.Move(pp^, ADestPage.FItems[0], AToMove * SizeOf(Pointer));
ADestPage.FUsedCount := AToMove;
Inc(pp, AToMove);
Inc(AIndex, AToMove);
Dec(ARemain, AToMove);
Inc(APage);
end;
Inc(FCount, ACount);
Dirty(APage + ANeedPages);
end;
procedure TQPagedList.BatchInsert(AIndex: Integer; const AList: TPointerList);
begin
if Length(AList) > 0 then
BatchInsert(AIndex, @AList[0], Length(AList));
end;
procedure TQPagedList.Insert(AIndex: Integer; const p: Pointer);
var
APage, ANewPage, AMoved: Integer;
ADestPage, ATemp: TQListPage;
begin
if AIndex < 0 then
AIndex := 0;
if TMethod(FOnCompare).Code <> nil then
Find(p, AIndex);
if AIndex >= count then // 插入末尾
begin
APage := FLastUsedPage;
if (APage < 0) or (FPages[APage].FUsedCount = FPageSize) then
begin
Inc(APage);
if APage >= Length(FPages) then
begin
SetLength(FPages, Length(FPages) + 1);
ADestPage := TQListPage.Create(FPageSize);
ADestPage.FStartIndex := count;
FPages[APage] := ADestPage;
end
else
ADestPage := FPages[APage];
Inc(FLastUsedPage);
if APage = 0 then
FFirstDirtyPage := 1;
end
else
ADestPage := FPages[APage];
ADestPage.FItems[ADestPage.FUsedCount] := p;
Inc(ADestPage.FUsedCount);
end
else if AIndex <= 0 then // 插入最前面
begin
ADestPage := FPages[0];
if ADestPage.FUsedCount < FPageSize then
begin
System.Move(ADestPage.FItems[0], ADestPage.FItems[1],
ADestPage.FUsedCount * SizeOf(Pointer));
ADestPage.FItems[0] := p;
Inc(ADestPage.FUsedCount);
end
else // 当前页满了,需要分配新页
begin
if FLastUsedPage < High(FPages) then
begin
Inc(FLastUsedPage);
ADestPage := FPages[FLastUsedPage];
System.Move(FPages[0], FPages[1], SizeOf(TQListPage) * FLastUsedPage);
FPages[0] := ADestPage;
ADestPage.FStartIndex := 0;
end
else
begin
ANewPage := Length(FPages);
SetLength(FPages, ANewPage + 1);
FLastUsedPage := ANewPage;
System.Move(FPages[0], FPages[1], SizeOf(TQListPage) * FLastUsedPage);
FPages[0] := TQListPage.Create(FPageSize);
ADestPage := FPages[0];
end;
ADestPage.FUsedCount := 1;
ADestPage.FItems[0] := p;
end;
Dirty(1);
end
else
// 插入中间
begin
APage := FindPage(AIndex);
ADestPage := FPages[APage];
if (ADestPage.FUsedCount = FPageSize) then // 目标页已满
begin
ANewPage := APage + 1;
if (FLastUsedPage = APage) or (FPages[ANewPage].FUsedCount = FPageSize)
then
// 下一页也满了
begin
Inc(FLastUsedPage);
if FLastUsedPage = Length(FPages) then
begin
SetLength(FPages, FLastUsedPage + 1);
System.Move(FPages[ANewPage], FPages[ANewPage + 1],
SizeOf(TQListPage) * (FLastUsedPage - ANewPage));
ATemp := TQListPage.Create(FPageSize);;
FPages[ANewPage] := ATemp;
end
else if ANewPage = FLastUsedPage then
ATemp := FPages[ANewPage]
else
begin
ATemp := FPages[FLastUsedPage];
System.Move(FPages[ANewPage], FPages[ANewPage + 1],
SizeOf(TQListPage) * (FLastUsedPage - ANewPage));
FPages[ANewPage] := ATemp;
end;
ATemp.FStartIndex := AIndex + 1;
Dec(AIndex, ADestPage.FStartIndex);
AMoved := ADestPage.FUsedCount - AIndex;
System.Move(ADestPage.FItems[AIndex], ATemp.FItems[0],
AMoved * SizeOf(Pointer));
Dec(ADestPage.FUsedCount, AMoved - 1);
ATemp.FUsedCount := AMoved;
ADestPage.FItems[AIndex] := p;
Dirty(ANewPage + 1);
end
else // 将当前页的内容移入下一页
begin
ATemp := FPages[ANewPage];
System.Move(ATemp.FItems[0], ATemp.FItems[1],
ATemp.FUsedCount * SizeOf(Pointer));
ATemp.FItems[0] := ADestPage.FItems[FPageSize - 1];
Inc(ATemp.FUsedCount);
Dirty(ANewPage);
Dec(AIndex, ADestPage.FStartIndex);
AMoved := ADestPage.FUsedCount - AIndex - 1;
System.Move(ADestPage.FItems[AIndex], ADestPage.FItems[AIndex + 1],
AMoved * SizeOf(Pointer));
ADestPage.FItems[AIndex] := p;
end;
end
else
begin
Dec(AIndex, ADestPage.FStartIndex);
if AIndex < ADestPage.FUsedCount then
begin
AMoved := (ADestPage.FUsedCount - AIndex);
System.Move(ADestPage.FItems[AIndex], ADestPage.FItems[AIndex + 1],
AMoved * SizeOf(TQListPage));
end;
ADestPage.FItems[AIndex] := p;
Inc(ADestPage.FUsedCount);
Dirty(APage + 1);
end;
end;
Inc(FCount);
if (p <> nil) and (ClassType <> TQPagedList) then
Notify(p, lnAdded);
end;
function TQPagedList.Last: Pointer;
begin
Result := Items[count - 1];
end;
procedure TQPagedList.Move(AFrom, ATo: Integer);
begin
MoveTo(AFrom, ATo);
end;
procedure TQPagedList.MoveTo(AFrom, ATo: Integer);
var
ATemp: Pointer;
begin
if AFrom <> ATo then
begin
ATemp := Items[AFrom];
Remove(AFrom);
Insert(ATo, ATemp);
end;
end;
procedure TQPagedList.Notify(Ptr: Pointer; Action: TListNotification);
begin
end;
function TQPagedList.Remove(Item: Pointer): Integer;
begin
Result := RemoveItem(Item, FromBeginning);
end;
procedure TQPagedList.Remove(AIndex: Integer);
var
APage: Integer;
begin
APage := FindPage(AIndex);
if APage >= 0 then
begin
Dec(AIndex, FPages[APage].FStartIndex);
System.Move(FPages[APage].FItems[AIndex + 1], FPages[APage].FItems[AIndex],
SizeOf(Pointer) * (FPages[APage].FUsedCount - AIndex - 1));
Dec(FPages[APage].FUsedCount);
CheckLastPage;
Assert(FPages[APage].FUsedCount >= 0);
Dirty(APage + 1);
end;
end;
{$IFDEF UNICODE}
procedure TQPagedList.Sort(AOnCompare: TQPagedListSortCompareA);
begin
TMethod(FOnCompare).Code := nil;
PQPagedListSortCompareA(@TMethod(FOnCompare).Code)^ := AOnCompare;
TMethod(FOnCompare).Data := Pointer(-1);
Sort;
end;
{$ENDIF}
procedure TQPagedList.SetCapacity(const Value: Integer);
begin
// 仅为兼容保留,实际不做任何事情
end;
procedure TQPagedList.SetItems(AIndex: Integer; const Value: Pointer);
var
APage: TQListPage;
begin
APage := GetPage(AIndex);
if APage <> nil then
begin
Dec(AIndex, APage.FStartIndex);
APage.FItems[AIndex] := Value;
end
else
raise Exception.Create('索引越界:' + IntToStr(AIndex));
end;
procedure TQPagedList.SetOnCompare(const Value: TQPagedListSortCompare);
begin
if (TMethod(FOnCompare).Code <> TMethod(Value).Code) or
(TMethod(FOnCompare).Data <> TMethod(Value).Data) then
begin
FOnCompare := Value;
if Assigned(Value) then
Sort;
end;
end;
procedure TQPagedList.Sort(AOnCompare: TQPagedListSortCompareG);
begin
TMethod(FOnCompare).Code := @AOnCompare;
TMethod(FOnCompare).Data := nil;
Sort;
end;
procedure TQPagedList.Sort;
procedure QuickSort(l, R: Integer);
var
I, J, p: Integer;
begin
repeat
I := l;
J := R;
p := (l + R) shr 1;
repeat
while DoCompare(Items[I], Items[p]) < 0 do
Inc(I);
while DoCompare(Items[J], Items[p]) > 0 do
Dec(J);
if I <= J then
begin
if I <> J then
Exchange(I, J);
if p = I then
p := J
else if p = J then
p := I;
Inc(I);
Dec(J);
end;
until I > J;
if l < J then
QuickSort(l, J);
l := I;
until I >= R;
end;
begin
if TMethod(FOnCompare).Code = nil then
raise Exception.Create('未指定排序规则');
if count > 0 then
QuickSort(0, count - 1);
end;
function TQPagedList.RemoveItem(Item: Pointer; Direction: TDirection): Integer;
begin
Result := IndexOfItem(Item, Direction);
if Result > 0 then
Remove(Result);
end;
{ TQListPage }
constructor TQListPage.Create(APageSize: Integer);
begin
SetLength(FItems, APageSize);
// OutputDebugString(PChar(IntToHex(IntPtr(Self), 8) + ' Created'));
end;
destructor TQListPage.Destroy;
begin
// OutputDebugString(PChar(IntToHex(IntPtr(Self), 8) + ' Freed'));
inherited;
end;
{ TQPagedListEnumerator }
constructor TQPagedListEnumerator.Create(AList: TQPagedList);
begin
inherited Create;
FList := AList;
FIndex := -1;
end;
function TQPagedListEnumerator.GetCurrent: Pointer;
begin
Result := FList[FIndex];
end;
function TQPagedListEnumerator.MoveNext: Boolean;
begin
Result := FIndex < FList.count - 1;
if Result then
Inc(FIndex);
end;
{ TQPagedStream }
constructor TQPagedStream.Create;
begin
Create(8192);
end;
function TQPagedStream.ActiveOffset: Integer;
begin
Result := FPosition mod FPageSize;
end;
function TQPagedStream.ActivePage: Integer;
begin
Result := FPosition div FPageSize;
end;
procedure TQPagedStream.Clear;
var
I: Integer;
begin
for I := 0 to High(FPages) do
FreeMem(FPages[I]);
SetLength(FPages, 0);
FSize := 0;
FPosition := 0;
end;
constructor TQPagedStream.Create(APageSize: Integer);
begin
inherited Create;
if APageSize <= 0 then
APageSize := 8192;
FPageSize := APageSize;
end;
destructor TQPagedStream.Destroy;
begin
Clear;
inherited;
end;
function TQPagedStream.GetAsBytes: TBytes;
begin
if Size > 0 then
begin
SetLength(Result, FSize);
FPosition := 0;
Read(Result[0], FSize);
end
else
SetLength(Result, 0);
end;
function TQPagedStream.GetBytes(AIndex: Int64): Byte;
begin
if AIndex + 1 > FSize then
Result := 0
else
Result := PByte(IntPtr(FPages[AIndex div FPageSize]) +
(AIndex mod FPageSize))^;
end;
function TQPagedStream.GetSize: Int64;
begin
Result := FSize;
end;
procedure TQPagedStream.LoadFromFile(const FileName: string);
var
AStream: TStream;
begin
AStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(AStream);
finally
FreeAndNil(AStream);
end;
end;
procedure TQPagedStream.LoadFromStream(Stream: TStream);
var
ACount: Int64;
begin
ACount := Stream.Size - Stream.Position;
Capacity := ACount;
CopyFrom(Stream, ACount);
end;
procedure TQPagedStream.PageNeeded(APageIndex: Integer);
begin
if High(FPages) < APageIndex then
Capacity := (APageIndex + 1) * FPageSize - 1;
end;
function TQPagedStream.Read(var Buffer; count: Longint): Longint;
var
ACanRead: Int64;
pBuf: PByte;
APage, APageSpace, APageOffset, AToRead: Integer;
begin
ACanRead := FSize - FPosition;
Result := 0;
if ACanRead >= count then
begin
if ACanRead < count then
count := ACanRead;
pBuf := @Buffer;
while count > 0 do
begin
APage := ActivePage;
APageOffset := ActiveOffset;
APageSpace := FPageSize - ActiveOffset;
if count > APageSpace then
AToRead := APageSpace
else
AToRead := count;
Dec(count, AToRead);
Move(PByte(IntPtr(FPages[APage]) + APageOffset)^, pBuf^, AToRead);
Inc(pBuf, AToRead);
Inc(Result, AToRead);
Inc(FPosition, AToRead);
end;
end;
end;
function TQPagedStream.Read(Buffer: TBytes; Offset, count: Longint): Longint;
begin
if count > 0 then
Result := Read(Buffer[Offset], count)
else
Result := 0;
end;
procedure TQPagedStream.SaveToFile(const FileName: string);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(AStream);
finally
FreeAndNil(AStream);
end;
end;
procedure TQPagedStream.SaveToStream(Stream: TStream);
begin
Stream.CopyFrom(Self, 0);
end;
function TQPagedStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
case Origin of
soBeginning:
Result := Offset;
soCurrent:
Result := FPosition + Offset;
soEnd:
Result := FSize - Offset
else
Result := 0;
end;
if Result > FSize then
Result := FSize
else if Result < 0 then
Result := 0;
FPosition := Result;
end;
procedure TQPagedStream.SetSize(const NewSize: Int64);
begin
Capacity := NewSize;
end;
procedure TQPagedStream.SetAsBytes(const Value: TBytes);
begin
Size := Length(Value);
if Size > 0 then
WriteBuffer(Value[0], Size);
end;
procedure TQPagedStream.SetBytes(AIndex: Int64; const Value: Byte);
begin
if FSize < AIndex + 1 then
Size := AIndex + 1;
PByte(IntPtr(FPages[AIndex div FPageSize]) + (AIndex mod FPageSize))^
:= Value;
end;
procedure TQPagedStream.SetCapacity(Value: Int64);
var
APageNum: Int64;
I: Integer;
begin
if Value < 0 then
Value := 0;
APageNum := (Value div FPageSize);
if (Value mod FPageSize) <> 0 then
Inc(APageNum);
if FCapacity <> APageNum * FPageSize then
begin
FCapacity := APageNum * FPageSize;
if Length(FPages) > APageNum then
begin
I := High(FPages);
while I >= APageNum do
begin
FreeMem(FPages[I]);
Dec(I);
end;
SetLength(FPages, APageNum);
end
else
begin
I := Length(FPages);
SetLength(FPages, APageNum);
while I < APageNum do
begin
GetMem(FPages[I], FPageSize);
Inc(I);
end;
end;
end;
end;
procedure TQPagedStream.SetSize(NewSize: Longint);
begin
Capacity := NewSize;
end;
function TQPagedStream.Write(const Buffer: TBytes;
Offset, count: Longint): Longint;
begin
if count > 0 then
Result := Write(Buffer[Offset], count)
else
Result := 0;
end;
function TQPagedStream.Write(const Buffer; count: Longint): Longint;
var
ADest: PByte;
APageIndex, APageOffset, APageSpace: Integer;
AOffset: Int64;
pBuf: PByte;
begin
Result := 0;
if count > 0 then
begin
AOffset := FPosition + count;
PageNeeded(AOffset div FPageSize);
APageIndex := ActivePage;
APageOffset := ActiveOffset;
APageSpace := FPageSize - APageOffset;
pBuf := @Buffer;
while count > 0 do
begin
ADest := PByte(IntPtr(FPages[APageIndex]) + APageOffset);
if APageSpace < count then
begin
Move(pBuf^, ADest^, APageSpace);
Inc(APageIndex);
Dec(count, APageSpace);
Inc(Result, APageSpace);
Inc(pBuf, APageSpace);
APageOffset := 0;
APageSpace := FPageSize;
end
else
begin
Move(pBuf^, ADest^, count);
Inc(Result, count);
Break;
end;
end;
Inc(FPosition, Result);
if FSize < FPosition then
FSize := FPosition;
end;
end;
const
PR_ORDERED = 9; // 如果存在顺序数列时,如12345,此时每个重复字符减小的权值
PR_REPEAT = 5; // 如果存在重复的数列时,如aaaa,此时每次重复减少的权值
PR_CHARTYPE = 20; // 每增加一个不同类型的字符时,增加的权值
PR_LENGTH = 10; // 每增加一个字符时,增加的权值
PR_CHART = 20; // 包含非数字和字母的控制字符时,额外增加的权值
PR_UNICODE = 40; // 包含Unicode字符时,额外增加的权值
function PasswordScale(const S: QStringW; var ARules: TPasswordRules): Integer;
var
p: PQCharW;
AMaxOrder, AMaxRepeat, ACharTypes: Integer;
function RepeatCount: Integer;
var
T: PQCharW;
begin
T := p;
Inc(T);
Result := 0;
while T^ = p^ do
begin
Inc(Result);
Inc(T);
end;
if Result > AMaxRepeat then
AMaxRepeat := Result;
end;
function OrderCount: Integer;
var
T, tl: PQCharW;
AStep: Integer;
begin
T := p;
tl := p;
Inc(T);
AStep := Ord(T^) - Ord(p^);
Result := 0;
while Ord(T^) - Ord(tl^) = AStep do
begin
Inc(Result);
tl := T;
Inc(T);
end;
if Result > AMaxOrder then
AMaxOrder := Result;
end;
begin
if LowerCase(S) = 'password' then
Result := 0
else
begin
Result := Length(S) * PR_LENGTH;
p := PQCharW(S);
ARules := [];
AMaxOrder := 0;
AMaxRepeat := 0;
while p^ <> #0 do
begin
if (p^ >= '0') and (p^ <= '9') then
ARules := ARules + [prIncNumber]
else if (p^ >= 'a') and (p^ <= 'z') then
ARules := ARules + [prIncLowerCase]
else if (p^ >= 'A') and (p^ <= 'Z') then
ARules := ARules + [prIncUpperCase]
else if p^ > #$7F then
ARules := ARules + [prIncUnicode]
else
ARules := ARules + [prIncChart];
if RepeatCount > 2 then
ARules := ARules + [prRepeat];
if OrderCount > 2 then
ARules := ARules + [prSimpleOrder];
Inc(p);
end;
if prSimpleOrder in ARules then
Result := Result - AMaxOrder * PR_ORDERED;
if prRepeat in ARules then
Result := Result - AMaxRepeat * PR_REPEAT;
ACharTypes := 0;
if prIncNumber in ARules then
Inc(ACharTypes);
if prIncLowerCase in ARules then
Inc(ACharTypes);
if prIncUpperCase in ARules then
Inc(ACharTypes);
if prIncChart in ARules then
begin
Inc(ACharTypes);
Result := Result + PR_CHART;
end;
if prIncUnicode in ARules then
begin
Inc(ACharTypes);
Result := Result + PR_UNICODE;
end;
Result := Result + (ACharTypes - 1) * PR_CHARTYPE;
// 密码强度的取值范围:<0
if Result < 0 then
Result := 0;
end;
end;
function PasswordScale(const S: QStringW): Integer;
var
ARules: TPasswordRules;
begin
Result := PasswordScale(S, ARules);
end;
function CheckPassword(const AScale: Integer): TPasswordStrongLevel; overload;
begin
if AScale < 60 then
Result := pslLowest
else if AScale < 100 then
Result := pslLower
else if AScale < 150 then
Result := pslNormal
else if AScale < 200 then
Result := pslHigher
else
Result := pslHighest;
end;
function CheckPassword(const S: QStringW): TPasswordStrongLevel; overload;
begin
Result := CheckPassword(PasswordScale(S));
end;
function PasswordCharTypes(const S: QStringW): TRandCharTypes;
var
p: PQCharW;
begin
Result := [];
p := PQCharW(S);
while p^ <> #0 do
begin
if ((p^ >= '0') and (p^ <= '9')) or ((p^ >= '0') and (p^ <= '9')) then
Result := Result + [rctNum]
else if ((p^ >= 'a') and (p^ <= 'z')) or ((p^ >= 'a') and (p^ <= 'z')) then
Result := Result + [rctAlpha, rctLowerCase]
else if ((p^ >= 'A') and (p^ <= 'Z')) or ((p^ >= 'A') and (p^ <= 'Z')) then
Result := Result + [rctAlpha, rctUpperCase]
else if (p^ >= #$4E00) and (p^ <= #$9FA5) then
Result := Result + [rctChinese]
else if (p^ = ' ') or (p^ = #9) or (p^ = #10) or (p^ = #13) or (p^ = #$00A0)
or (p^ = #$3000) then
Result := Result + [rctSpace]
else
Result := Result + [rctSymbol];
if Result = [rctChinese, rctAlpha, rctLowerCase, rctUpperCase, rctNum,
rctSymbol, rctSpace] then
Break;
Inc(p);
end;
end;
function PasswordRules(const S: QStringW): TPasswordRules;
begin
Result := [];
PasswordScale(S, Result);
end;
function SimpleChineseToTraditional(S: QStringW): QStringW;
begin
{$IFDEF MSWINDOWS}
SetLength(Result, Length(S) shl 1);
SetLength(Result, LCMapStringW(2052, LCMAP_TRADITIONAL_CHINESE, PWideChar(S),
Length(S), PWideChar(Result), Length(Result)));
{$ELSE}
raise Exception.CreateFmt(SUnsupportNow, ['SimpleChineseToTraditional']);
{$ENDIF}
end;
function TraditionalChineseToSimple(S: QStringW): QStringW;
begin
{$IFDEF MSWINDOWS}
SetLength(Result, Length(S) shl 1);
SetLength(Result, LCMapStringW(2052, LCMAP_SIMPLIFIED_CHINESE, PWideChar(S),
Length(S), PWideChar(Result), Length(Result)));
{$ELSE}
raise Exception.CreateFmt(SUnsupportNow, ['TraditionalChineseToSimple']);
{$ENDIF}
end;
function MoneyRound(const AVal: Currency; ARoundMethod: TMoneyRoundMethod)
: Currency;
var
V, R: Int64;
begin
if ARoundMethod = mrmNone then
begin
Result := AVal;
Exit;
end;
V := PInt64(@AVal)^;
R := V mod 100;
if ARoundMethod = mrmSimple then
begin
if R >= 50 then
PInt64(@Result)^ := ((V div 100) + 1) * 100
else
PInt64(@Result)^ := (V div 100) * 100;
end
else
begin
{
四舍六入五考虑,
五后非零就进一,
五后皆零看奇偶,
五前为偶应舍去,
五前为奇要进一。 }
if R > 50 then // 六入
PInt64(@Result)^ := ((V div 100) + 1) * 100
else if R = 50 then //
begin
if (((V div 100)) and $1) <> 0 then // 奇数
PInt64(@Result)^ := ((V div 100) + 1) * 100
else
PInt64(@Result)^ := (V div 100) * 100;
end
else
PInt64(@Result)^ := (V div 100) * 100;
end;
end;
{
将货币值转换为汉字大写
Parameters
AVal : 货币值
AFlags : 标志位组合,以决定输出结果的格式
ANegText : 当货币值为负数时,显示的前缀
AStartText : 前导字符串,如“人民币:”
AEndText : 后置字符串,如“整”
AGroupNum : 组数,每个数字与其单位构成一个数组,AGroupNum指出要求的组数量,
不为0时,会忽略标志位中的MC_HIDE_ZERO和MC_MERGE_ZERO
ARoundMethod : 金额舍入到分时的算法
AEndDigts : 小数点后的位数,-16~4 之间
Returns
返回格式化后的字符串
Examples
CapMoney(1.235,MC_READ,L"",L"",L"",0)=壹元贰角肆分
CapMoney(1.235,MC_READ,L"",L"",L"",4)=零拾壹元贰角肆分
CapMoney(100.24,MC_READ,L"",L"",L"",4)=壹佰元零贰角肆分
CapMoney(-10012.235,MC_READ,L"负",L"¥",L"",0)=¥负壹万零壹拾贰元贰角肆分
CapMoney(101005,MC_READ,L"负",L"",L"",0)=壹拾万壹仟零伍元
}
function CapMoney(AVal: Currency; AFlags: Integer;
ANegText, AStartText, AEndText: QStringW; AGroupNum: Integer;
ARoundMethod: TMoneyRoundMethod; AEndDigits: Integer = 2): QStringW;
const
Nums: array [0 .. 9] of WideChar = (#$96F6 { 零 } , #$58F9 { 壹 } ,
#$8D30 { 贰 } , #$53C1 { 叁 } , #$8086 { 肆 } , #$4F0D { 伍 } , #$9646 { 陆 } ,
#$67D2 { 柒 } , #$634C { 捌 } , #$7396 { 玖 } );
Units: array [0 .. 19] of WideChar = (#$94B1 { 钱 } , #$5398 { 厘 } ,
#$5206 { 分 } , #$89D2 { 角 } , #$5706 { 圆 } , #$62FE { 拾 } , #$4F70 { 佰 } ,
#$4EDF { 仟 } , #$4E07 { 万 } , #$62FE { 拾 } , #$4F70 { 佰 } , #$4EDF { 仟 } ,
#$4EBF { 亿 } , #$62FE { 拾 } , #$4F70 { 佰 } , #$4EDF { 仟 } , #$4E07 { 万 } ,
#$5146 { 兆 } , #$62FE { 拾 } , #$4F70 { 佰 } );
Levels: array [0 .. 5] of WideChar = (#$62FE { 拾 } , #$4F70 { 佰 } ,
#$4EDF { 仟 } , #$4E07 { 万 } , #$4EBF { 亿 } , #$5146 { 兆 } );
function UnitLevel(const AUnit: WideChar): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to High(Levels) do
begin
if Levels[I] = AUnit then
begin
Result := I;
Break;
end;
end;
end;
var
R, V: Int64;
I: Integer;
ATemp: QStringW;
pd, pe, p, pu: PWideChar;
APreLevel, ALevel: Integer;
begin
AVal := MoneyRound(AVal, ARoundMethod);
{ -922,337,203,685,477.5808 ~ 922,337,203,685,477.5807 }
V := PInt64(@AVal)^; // 精确到分
if V < 0 then
V := -V
else
SetLength(ANegText, 0);
if (AFlags and MC_END_PATCH) <> 0 then // 如果要包含AEndText,则必需包含单位
AFlags := AFlags or MC_UNIT;
if AGroupNum > 0 then // 如果要分组
begin
AFlags := AFlags and (not(MC_MERGE_ZERO or MC_HIDE_ZERO));
if AGroupNum > 20 then
AGroupNum := 20;
end;
if AEndDigits < -16 then
AEndDigits := -16
else if AEndDigits > 4 then
AEndDigits := 4;
SetLength(ATemp, 40); // 最大长度为40
pd := PWideChar(ATemp) + 39;
// 计算实际的分组数量,注意此时包含钱和厘,最后会根据实际的显示需要截断
I := 0;
while V > 0 do
begin
R := V mod 10;
V := V div 10;
pd^ := Units[I];
Dec(pd);
pd^ := Nums[R];
Dec(pd);
Inc(I);
end;
if AGroupNum > 0 then
begin
if I > AGroupNum then
raise Exception.CreateFmt(STooSmallCapMoneyGroup, [AGroupNum, I]);
while AGroupNum > I do
// 要求的分组数多
begin
pd^ := Units[I];
Dec(pd);
pd^ := Nums[0];
Dec(pd);
Inc(I);
end;
end;
Inc(pd);
if (AFlags and MC_HIDE_ZERO) <> 0 then // 如果隐藏左侧的零值,则跳过
begin
while pd^ <> #0 do
begin
if pd^ = Nums[0] then
Inc(pd, 2)
else
Break;
end;
end;
SetLength(Result, PWideChar(ATemp) + 40 - pd);
p := PWideChar(Result);
pe := PWideChar(ATemp) + 32 + AEndDigits * 2;
APreLevel := -1;
while pd < pe do
begin
if (AFlags and MC_NUM) <> 0 then
begin
p^ := pd^;
Inc(p);
if ((AFlags and MC_MERGE_ZERO) <> 0) and (pd^ = Nums[0]) then
begin
pu := pd;
Inc(pu);
while pd^ = Nums[0] do
begin
Inc(pd);
ALevel := UnitLevel(pd^);
if ALevel > APreLevel then // 万
begin
APreLevel := ALevel;
Dec(p);
p^ := pd^;
Inc(p);
Inc(pd);
Break;
end
else
Inc(pd);
end;
if pd^ = #0 then
begin
Dec(p);
if (AFlags and MC_UNIT) <> 0 then
begin
if pu^ = Units[4] then
begin
p^ := Units[4];
Inc(p);
end;
end;
end;
continue;
end;
end;
Inc(pd);
if (AFlags and MC_UNIT) <> 0 then
begin
APreLevel := UnitLevel(pd^);
p^ := pd^;
Inc(p);
end;
Inc(pd);
end;
SetLength(Result, p - PWideChar(Result));
if (AFlags and MC_UNIT) <> 0 then
begin
if Length(Result) = 0 then
Result := '零圆';
if (AFlags and MC_END_PATCH) <> 0 then
begin
if PWideChar(Result)[Length(Result) - 1] = Units[2] then // 分
Result := AStartText + ANegText + Result
else
Result := AStartText + ANegText + Result + AEndText;
end
else
Result := AStartText + ANegText + Result;
end
else
begin
if Length(Result) = 0 then
Result := '零';
Result := AStartText + ANegText + Result;
end;
end;
function IsHumanName(S: QStringW; AllowChars: TNameCharSet; AMinLen: Integer;
AMaxLen: Integer; AOnTest: TQCustomNameCharTest): Boolean;
var
p: PWideChar;
c: Integer;
AHandled: Boolean;
begin
S := Trim(CNFullToHalf(S)); // 将全角转换为半角
c := CharCountW(S);
Result := (c >= AMinLen) and (c <= AMaxLen);
// 姓名的字符数(注意不是字节数)应在最小和最大长度之间
if not Result then
Exit;
p := PWideChar(S);
while Result and (p^ <> #0) do
begin
if Assigned(AOnTest) then
begin
AHandled := false;
AOnTest(qstring.CharCodeW(p), Result, AHandled);
if AHandled then
begin
if (p^ >= #$D800) and (p^ <= #$DBFF) then
Inc(p, 2)
else
Inc(p);
continue;
end;
end;
if (p^ >= '0') and (p^ <= '9') then
// 全角或半角数字
Result := nctNum in AllowChars
else if ((p^ >= 'a') and (p^ <= 'z')) or ((p^ >= 'A') and (p^ <= 'Z')) then
// 全角或半角英文
Result := nctAlpha in AllowChars
else if p^ = ' ' then // 空格
Result := nctSpace in AllowChars
else if p^ = '·' then // 少数民族或外国人姓名分隔符
Result := nctDot in AllowChars
else if p^ < #$80 then // 0-127 之间
Result := nctSymbol in AllowChars
else // 剩下的是找汉字的区间了
begin
// 2400-4DBF CJK统一表意符号扩展
// 4DC0-4DFF 易经六十四卦符号
if (p^ >= #$2400) and (p^ <= #$4DFF) then
Result := nctSymbol in AllowChars
else if (p^ >= #$4E00) and (p^ <= #$9FA5) then
// CJK 统一表意符号
Result := nctChinese in AllowChars
else if (p^ >= #$E000) and (p^ <= #$F8FF) then // 自定义字符区
Result := nctCustom in AllowChars
else if (p^ >= #$D800) and (p^ <= #$DBFF) then // CJK 扩展字符区
begin
Result := nctChinese in AllowChars;
Inc(p);
end
else if (p^ >= #$F900) and (p^ <= #$FAFF) then // CJK兼容象形文字
Result := nctChinese in AllowChars
else
Result := nctOther in AllowChars;
end;
Inc(p);
end;
end;
function IsChineseName(S: QStringW): Boolean;
begin
Result := IsHumanName(S, [nctChinese, nctDot], 2, 50);
end;
function IsNoChineseName(S: QStringW): Boolean;
begin
Result := IsHumanName(S, [nctAlpha, nctDot, nctSpace, nctOther], 2, 50);
end;
procedure AddrCharTest(AChar: Cardinal; var Accept, AHandled: Boolean);
begin
if AChar = Ord('-') then
begin
Accept := True;
AHandled := True;
end;
end;
function IsChineseAddr(S: QStringW; AMinLength: Integer): Boolean;
begin
Result := IsHumanName(S, [nctChinese, nctAlpha, nctSymbol, nctDot, nctSpace,
nctNum], AMinLength, 128, AddrCharTest);
end;
function IsNoChineseAddr(S: QStringW; AMinLength: Integer): Boolean;
begin
Result := IsHumanName(S, [nctAlpha, nctDot, nctSymbol, nctSpace, nctNum],
AMinLength, 128, AddrCharTest);
end;
{ TQBits }
function TQBits.GetIsSet(AIndex: Integer): Boolean;
begin
if (AIndex < 0) or (AIndex >= Size) then
Result := false
else
Result := (FBits[AIndex shr 3] and ($80 shr (AIndex and $7))) <> 0;
end;
function TQBits.GetSize: Integer;
begin
Result := Length(FBits) shl 3;
end;
procedure TQBits.SetIsSet(AIndex: Integer; const Value: Boolean);
var
AByteIdx: Integer;
begin
if (AIndex < 0) or (AIndex >= Size) then
raise QException.CreateFmt(SOutOfIndex, [AIndex, 0, Size - 1]);
AByteIdx := AIndex shr 3;
if Value then
FBits[AByteIdx] := FBits[AByteIdx] or ($80 shr (AIndex and $7))
else
FBits[AByteIdx] := FBits[AByteIdx] and (not($80 shr (AIndex and $7)));
end;
procedure TQBits.SetSize(const Value: Integer);
begin
if (Value and $7) <> 0 then
SetLength(FBits, (Value shr 3) + 1)
else
SetLength(FBits, Value shr 3);
end;
function CheckChineseId18(CardNo: QStringW): QCharW;
var
Sum, Idx: Integer;
const
Weight: array [1 .. 17] of Integer = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10,
5, 8, 4, 2);
Checksums: array [0 .. 10] of WideChar = ('1', '0', 'X', '9', '8', '7', '6',
'5', '4', '3', '2');
begin
if (Length(CardNo) >= 17) then
begin
Sum := 0;
for Idx := 1 to 17 do
Sum := Sum + (Ord(CardNo[Idx{$IFDEF NEXTGEN} - 1{$ENDIF}]) - Ord('0')) *
Weight[Idx];
Result := Checksums[Sum mod 11];
end
else
Result := #0;
end;
function ChineseId15To18(CardNo: QStringW): QStringW;
begin
if (Length(CardNo) <> 15) then
raise Exception.Create('15位转18位过程要求身份证号必需为15位。');
CardNo := LeftStrW(CardNo, 6, false) + '19' + RightStrW(CardNo, 9, false);
Result := CardNo + CheckChineseId18(CardNo);
end;
function DecodeChineseId(CardNo: QStringW; var AreaCode: QStringW;
var Birthday: TDateTime; var IsFemale: Boolean): Boolean;
var
len: Integer;
Y, M, d: Integer;
p: PQCharW;
begin
len := Length(CardNo);
Result := false;
if (len in [15, 18]) then
// 长度检查
begin
if (Length(CardNo) = 15) then
CardNo := ChineseId15To18(CardNo);
if CheckChineseId18(CardNo) <>
CharUpperW(CardNo[{$IFDEF NEXTGEN}17{$ELSE}18{$ENDIF}]) then // 身份证号校验码检查
Exit;
p := PQCharW(CardNo);
AreaCode := StrDupX(p, 6);
Inc(p, 6);
if not TryStrToInt(StrDupX(p, 4), Y) then // 年
Exit;
Inc(p, 4);
if not TryStrToInt(StrDupX(p, 2), M) then // 月
Exit;
Inc(p, 2);
if not TryStrToInt(StrDupX(p, 2), d) then // 日
Exit;
Inc(p, 2);
if not TryEncodeDate(Y, M, d, Birthday) then
Exit;
if Birthday > Now then
Exit;
if TryStrToInt(StrDupX(p, 3), Y) then
begin
Result := True;
if (Y mod 2) = 0 then
IsFemale := True
else
IsFemale := false;
end
end
else
Result := false;
end;
function AreaCodeOfChineseId(CardNo: QStringW): QStringW;
var
ABirthday: TDateTime;
AIsFemale: Boolean;
begin
if not DecodeChineseId(CardNo, Result, ABirthday, AIsFemale) then
SetLength(Result, 0);
end;
function AgeOfChineseId(CardNo: QStringW; ACalcDate: TDateTime): Integer;
var
ACode: QStringW;
AIsFemale: Boolean;
ABirthday: TDateTime;
begin
if DecodeChineseId(CardNo, ACode, ABirthday, AIsFemale) then
begin
if IsZero(ACalcDate) then
Result := YearsBetween(Now, ABirthday)
else
Result := YearsBetween(ACalcDate, ABirthday);
end
else
Result := -1;
end;
function BirthdayOfChineseId(CardNo: QStringW): TDateTime;
var
ACode: QStringW;
AIsFemale: Boolean;
begin
if not DecodeChineseId(CardNo, ACode, Result, AIsFemale) then
Result := 0;
end;
function SexOfChineseId(CardNo: QStringW): TQHumanSex;
var
ACode: QStringW;
AIsFemale: Boolean;
ABirthday: TDateTime;
begin
if DecodeChineseId(CardNo, ACode, ABirthday, AIsFemale) then
begin
if AIsFemale then
Result := hsFemale
else
Result := hsMale;
end
else
Result := hsUnknown;
end;
function IsChineseIdNo(CardNo: QStringW): Boolean;
var
AreaCode: QStringW;
Birthday: TDateTime;
IsFemale: Boolean;
begin
Result := DecodeChineseId(CardNo, AreaCode, Birthday, IsFemale);
end;
function IsEmailAddr(S: QStringW): Boolean;
var
p: PQCharW;
At: Integer;
Dot: Integer;
begin
p := PQCharW(S);
At := 0;
Dot := 0;
while p^ <> #0 do
begin
if p^ = '@' then
Inc(At)
else if p^ = '.' then
Inc(Dot);
Inc(p);
end;
Result := (At = 1) and (Dot > 0);
end;
function IsChinesePhone(S: QStringW): Boolean;
var
p: PQCharW;
begin
p := PQCharW(S);
if p^ = '+' then
begin
Inc(p);
while (p^ >= '0') and (p^ <= '9') do
Inc(p);
// 跳过国别
end;
while ((p^ >= '0') and (p^ <= '9')) or (p^ = '-') or (p^ = ' ') do
Inc(p);
Result := (p^ = #0);
if Result then
begin
Dec(p);
Result := p^ <> '-';
end;
end;
function IsChineseMobile(S: QStringW): Boolean;
var
p: PQCharW;
ACount: Integer;
const
Delimiters: PWideChar = ' -';
begin
ACount := Length(S);
Result := false;
if ACount >= 11 then
begin
p := PQCharW(S);
if p^ = '+' then // +86
begin
Inc(p);
if p^ <> '8' then
Exit;
Inc(p);
if p^ <> '6' then
Exit;
Inc(p);
SkipCharW(p, Delimiters);
end;
if p^ = '1' then // 中国手机号以1打头,
begin
ACount := 0;
while p^ <> #0 do
begin
if (p^ >= '0') and (p^ <= '9') then
begin
Inc(p);
Inc(ACount);
end
else if (p^ = '-') or (p^ = ' ') then
Inc(p)
else
Exit;
end;
Result := (ACount = 11);
end;
end;
end;
function SizeOfFile(const S: QStringW): Int64;
var
sr: TSearchRec;
begin
if FindFirst(S, 0, sr) = 0 then
begin
Result := sr.Size;
sysutils.FindClose(sr);
end
else
Result := -1;
end;
function MethodEqual(const Left, Right: TMethod): Boolean;
begin
Result := (Left.Data = Right.Data) and (Left.Code = Right.Code);
end;
function MethodAssigned(var AMethod): Boolean;
begin
Result := Assigned(TMethod(AMethod).Code);
end;
function UrlMerge(const ABase, ARel: QStringW): QStringW;
var
p, pBase, pRel: PQCharW;
ASchema: QStringW;
function BasePath: String;
var
LP, sp: PQCharW;
begin
p := pBase;
if StartWithW(p, 'http://', True) then
ASchema := StrDupX(p, 7)
else if StartWithW(p, 'https://', True) then
ASchema := StrDupX(p, 8);
Inc(p, Length(ASchema));
LP := p;
sp := p;
while p^ <> #0 do
begin
if p^ = '/' then
LP := p;
Inc(p);
end;
if LP = sp then
Result := ABase + '/'
else
Result := StrDupX(pBase, ((IntPtr(LP) - IntPtr(pBase)) shr 1) + 1);
end;
function RootPath: String;
begin
p := pBase;
if StartWithW(p, 'http://', True) then
ASchema := StrDupX(p, 7)
else if StartWithW(p, 'https://', True) then
ASchema := StrDupX(p, 8);
Inc(p, Length(ASchema));
while p^ <> #0 do
begin
if p^ = '/' then
begin
Result := StrDupX(pBase, ((IntPtr(p) - IntPtr(pBase)) shr 1) + 1);
Exit;
end;
Inc(p);
end;
Result := ABase + '/'
end;
begin
pRel := PQCharW(ARel);
pBase := PQCharW(ABase);
if StartWithW(pRel, 'http', True) then // 绝对路径?
begin
p := pRel;
Inc(pRel, 4);
if (pRel^ = 's') or (pRel^ = 'S') then
// https?
Inc(pRel);
if StartWithW(pRel, '://', false) then // 使用的绝对路径,直接返回
begin
Result := ARel;
Exit;
end;
end
else if StartWithW(pRel, '//', True) then // 基于ABase相同的协议的绝对路径
begin
if StartWithW(pBase, 'https', True) then
Result := 'https:' + ARel
else
Result := 'http:' + ARel;
end
else
begin
if pRel^ = '/' then
Result := RootPath + StrDupW(pRel, 1)
else
Result := BasePath + ARel;
end;
end;
procedure Debugout(const AMsg: QStringW);
begin
{$IFDEF MSWINDOWS}
OutputDebugStringW(PQCharW(AMsg));
{$ENDIF}
{$IFDEF ANDROID}
__android_log_write(ANDROID_LOG_DEBUG, 'debug',
Pointer(PQCharA(qstring.Utf8Encode(AMsg))));
{$ENDIF}
{$IFDEF IOS}
NSLog(((StrToNSStr(AMsg)) as ILocalObject).GetObjectID);
{$ENDIF}
{$IFDEF OSX}
WriteLn(ErrOutput, AMsg);
{$ENDIF}
end;
procedure Debugout(const AFmt: QStringW; const AParams: array of const);
begin
Debugout(Format(AFmt, AParams));
end;
function RandomString(ALen: Cardinal; ACharTypes: TRandCharTypes;
AllTypesNeeded: Boolean): QStringW;
var
p: PQCharW;
K, M: Integer;
V: TRandCharType;
ARemainTypes: TRandCharTypes;
const
SpaceChars: array [0 .. 3] of QCharW = (#9, #10, #13, #32);
begin
if ACharTypes = [] then // 如果未设置,则默认为大小写字母
ACharTypes := [rctAlpha];
SetLength(Result, ALen);
p := PQCharW(Result);
ARemainTypes := ACharTypes;
M := Ord(High(TRandCharType)) + 1;
while ALen > 0 do
begin
V := TRandCharType(random(M));
if AllTypesNeeded and (ARemainTypes <> []) then
begin
while not(V in ARemainTypes) do
V := TRandCharType(random(M));
ARemainTypes := ARemainTypes - [V];
end;
if V in ACharTypes then
begin
case V of
rctChinese:
p^ := QCharW($4E00 + random($9FA5 - $4E00));
rctAlpha:
begin
K := random(52);
if K < 26 then
p^ := QCharW(Ord('A') + K)
else
p^ := QCharW(Ord('a') + K - 26);
end;
rctLowerCase:
p^ := QCharW(Ord('a') + random(26));
rctUpperCase:
p^ := QCharW(Ord('A') + random(26));
rctNum:
p^ := QCharW(Ord('0') + random(10));
rctSymbol: // 只管英文符号
begin
// $21~$2F,$3A~$40,$5B-$60,$7B~$7E
case random(4) of
0: // !->/
p^ := QCharW($21 + random(16));
1: // :->@
p^ := QCharW($3A + random(7));
2: // [->`
p^ := QCharW($5B + random(6));
3: // {->~
p^ := QCharW($7B + random(4));
end;
end;
rctSpace:
p^ := SpaceChars[random(4)];
end;
Dec(ALen);
Inc(p);
end;
end;
end;
function FindSwitchValue(ASwitch: QStringW; ANameValueSperator: QCharW;
AIgnoreCase: Boolean; var ASwitchChar: QCharW): QStringW;
var
I: Integer;
S, SW: QStringW;
ps, p: PQCharW;
const
SwitchChars: PWideChar = '+-/';
begin
SW := ASwitch + ANameValueSperator;
for I := 1 to ParamCount do
begin
S := ParamStr(I);
ps := PQCharW(S);
p := ps;
SkipCharW(p, SwitchChars);
if StartWithW(PQCharW(p), PQCharW(SW), AIgnoreCase) then
begin
if p <> ps then
ASwitchChar := ps^
else
ASwitchChar := #0;
Result := ValueOfW(S, ANameValueSperator);
Exit;
end
end;
Result := '';
end;
function FindSwitchValue(ASwitch: QStringW; ANameValueSperator: QCharW)
: QStringW;
var
c: QCharW;
begin
Result := FindSwitchValue(ASwitch, ANameValueSperator, True, c);
end;
{ TQSingleton<T> }
function TQSingleton{$IFDEF UNICODE}<T>{$ENDIF}.Instance
(ACallback: TGetInstanceCallback):
{$IFDEF UNICODE}T{$ELSE}Pointer{$ENDIF};
begin
if not Assigned(InitToNull) then
begin
GlobalNameSpace.BeginWrite;
try
if not Assigned(InitToNull) then
InitToNull := ACallback;
finally
GlobalNameSpace.EndWrite;
end;
end;
Result := InitToNull;
end;
{ TQReadOnlyMemoryStream }
constructor TQReadOnlyMemoryStream.Create(AData: Pointer; ASize: Integer);
begin
inherited Create;
SetPointer(AData, ASize);
end;
constructor TQReadOnlyMemoryStream.Create;
begin
inherited;
// 这个构造函数变成保护的,以避免外部访问
end;
function TQReadOnlyMemoryStream.Write(const Buffer; count: Longint): Longint;
begin
raise EStreamError.Create(SStreamReadOnly);
end;
function MonthFirstDay(ADate: TDateTime): TDateTime;
var
Y, M, d: Word;
begin
DecodeDate(ADate, Y, M, d);
Result := EncodeDate(Y, M, 1);
end;
function MergeAddr(const AProv, ACity, ACounty, ATownship, AVillage,
ADetail: QStringW; AIgnoreCityIfSameEnding: Boolean): QStringW;
var
p: PWideChar;
procedure Cat(S: QStringW);
begin
if (Length(S) > 0) and (not EndWithW(PWideChar(Result), PWideChar(S), false))
then
begin
Result := Result + S;
if StartWithW(p, PWideChar(S), false) then
Inc(p, Length(S));
end;
end;
begin
Result := '';
p := PWideChar(ADetail);
Cat(AProv);
if ACity <> '市辖区' then
begin
if (Length(ACity) > 0) and (Length(ACounty) > 0) then
begin
if RightStrW(ACity, 1, false) = RightStrW(ACounty, 1, false) then
begin
if not AIgnoreCityIfSameEnding then
Cat(LeftStrW(ACity, Length(ACity) - 1, false))
else if StartWithW(p, PWideChar(ACity), false) then
Inc(p, Length(ACity));
end
else
Cat(ACity);
end;
end;
Cat(ACounty);
Cat(ATownship);
Cat(AVillage);
Result := Result + p;
end;
function MaskText(const S: QStringW; ALeft, ARight: Integer; AMaskChar: QCharW)
: QStringW;
var
l: Integer;
begin
l := Length(S);
if l > 0 then
begin
if ALeft + ARight >= l then
begin
ARight := 0;
if ALeft > l then
ALeft := l - 1;
end;
Result := LeftStrW(S, ALeft, false) + StringReplicateW(AMaskChar,
l - ALeft - ARight) + RightStrW(S, ARight, false);
end
else
Result := S;
end;
function StrCatW(const S: array of QStringW; AIgnoreZeroLength: Boolean;
const AStartOffset, ACount: Integer; const ADelimiter: QCharW): QStringW;
var
I, l, ASize, ADelimSize, ARealStart, ARealStop: Integer;
pd: PQCharW;
begin
ASize := 0;
if ADelimiter <> #0 then
ADelimSize := 1
else
ADelimSize := 0;
if AStartOffset > 0 then
ARealStart := AStartOffset
else
ARealStart := Length(S) - ACount;
if ARealStart < 0 then
ARealStart := 0;
if ARealStart + ACount > Length(S) then
ARealStop := High(S)
else
ARealStop := ARealStart + ACount;
if ARealStart < ARealStop then
begin
for I := ARealStart to ARealStop do
begin
l := Length(S[I]);
if l = 0 then
begin
if AIgnoreZeroLength then
continue;
end
else
Inc(ASize, l);
Inc(ADelimSize, ADelimSize);
end;
Dec(ASize);
if ASize > 0 then
begin
SetLength(Result, ASize);
pd := PQCharW(Result);
for I := ARealStart to ARealStop do
begin
l := Length(S[I]);
if l = 0 then
begin
if AIgnoreZeroLength then
continue;
end
else
begin
Move(PQCharW(S[I])^, pd^, l * SizeOf(QCharW));
Inc(pd, l);
end;
if I <> ARealStop then
begin
pd^ := ADelimiter;
Inc(pd);
end;
end;
end;
end
else
SetLength(Result, 0);
end;
function ReplaceLineBreak(const S, ALineBreak: QStringW): QStringW;
var
ps, pd: PQCharW;
ALen, ADelta: Integer;
begin
if Length(S) > 0 then
begin
ps := PQCharW(S);
ALen := Length(ALineBreak);
ADelta := 0;
while ps^ <> #0 do
begin
if ps^ = #13 then
begin
Inc(ps);
if ps^ = #10 then
begin
Inc(ps);
Inc(ADelta, ALen - 2);
end;
end
else if ps^ = #10 then
begin
Inc(ps);
Inc(ADelta, ALen - 1);
end
else
Inc(ps);
end;
if ADelta = 0 then
Result := S
else
begin
SetLength(Result, Length(S) + ADelta);
ps := PQCharW(S);
pd := PQCharW(Result);
ALen := ALen * SizeOf(QCharW);
while ps^ <> #0 do
begin
if ps^ = #13 then
begin
Inc(ps);
if ps^ = #10 then
begin
Inc(ps);
Move(PQCharW(ALineBreak)^, pd^, ALen);
Inc(pd, Length(ALineBreak));
end;
end
else if ps^ = #10 then
begin
Inc(ps);
Move(PQCharW(ALineBreak)^, pd^, ALen);
Inc(pd, Length(ALineBreak));
end
else
begin
pd^ := ps^;
Inc(ps);
Inc(pd);
end;
end;
end;
end
else
Result := S;
end;
initialization
{$IFDEF WIN32}
MemComp := MemCompAsm;
{$ELSE}
MemComp := MemCompPascal;
{$ENDIF}
{$IFDEF MSWINDOWS}
hMsvcrtl := LoadLibrary('msvcrt.dll');
if hMsvcrtl <> 0 then
begin
VCStrStr := TMSVCStrStr(GetProcAddress(hMsvcrtl, 'strstr'));
VCStrStrW := TMSVCStrStrW(GetProcAddress(hMsvcrtl, 'wcsstr'));
{$IFDEF WIN64}
VCMemCmp := TMSVCMemCmp(GetProcAddress(hMsvcrtl, 'memcmp'));
{$ENDIF}
end
else
begin
VCStrStr := nil;
VCStrStrW := nil;
{$IFDEF WIN64}
VCMemCmp := nil;
{$ENDIF}
end;
{$ENDIF}
IsFMXApp := GetClass('TFmxObject') <> nil;
finalization
{$IFDEF MSWINDOWS}
if hMsvcrtl <> 0 then
FreeLibrary(hMsvcrtl);
{$ENDIF}
end.
|
unit evUnicodeFormulasToUnicodeConverter;
// Модуль: "w:\common\components\gui\Garant\Everest\evUnicodeFormulasToUnicodeConverter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevUnicodeFormulasToUnicodeConverter" MUID: (561E7E4B0034)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evdLeafParaFilter
, k2Base
, l3Variant
;
type
TevUnicodeFormulasToUnicodeConverter = class(TevdLeafParaFilter)
protected
function ParaTypeForFiltering: Tk2Type; override;
{* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация }
procedure DoWritePara(aLeaf: Tl3Variant); override;
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
end;//TevUnicodeFormulasToUnicodeConverter
implementation
uses
l3ImplUses
, TextPara_Const
, k2Tags
, Formula_Const
, evdTypes
, l3_String
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, l3Base
, l3String
, ObjectSegment_Const
, SysUtils
, StrUtils
//#UC START# *561E7E4B0034impl_uses*
//#UC END# *561E7E4B0034impl_uses*
;
function TevUnicodeFormulasToUnicodeConverter.ParaTypeForFiltering: Tk2Type;
{* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация }
//#UC START# *49E488070386_561E7E4B0034_var*
//#UC END# *49E488070386_561E7E4B0034_var*
begin
//#UC START# *49E488070386_561E7E4B0034_impl*
Result := k2_typTextPara;
//#UC END# *49E488070386_561E7E4B0034_impl*
end;//TevUnicodeFormulasToUnicodeConverter.ParaTypeForFiltering
procedure TevUnicodeFormulasToUnicodeConverter.DoWritePara(aLeaf: Tl3Variant);
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
//#UC START# *49E4883E0176_561E7E4B0034_var*
const
cSig = 'String(#@';
var
l_Objects : Tl3Variant;
l_S : Tl3_String;
l_Index : Integer;
l_O : Tl3Variant;
l_F : Tl3Variant;
l_FS : AnsiString;
l_Pos : Integer;
l_Code : Integer;
l_WideChar : WideChar;
//#UC END# *49E4883E0176_561E7E4B0034_var*
begin
//#UC START# *49E4883E0176_561E7E4B0034_impl*
if evHasText(aLeaf) then
begin
l_Objects := aLeaf.rAtomEx([k2_tiSegments, k2_tiChildren, k2_tiHandle, Ord(ev_slObjects)]);
if l_Objects.IsValid AND (l_Objects.ChildrenCount > 0) then
begin
l_S := aLeaf.Attr[k2_tiText].AsObject As Tl3_String;
l_Index := 0;
while (l_Index < l_Objects.ChildrenCount) do
begin
l_O := l_Objects.Child[l_Index];
if l_O.IsKindOf(k2_typObjectSegment) AND (l_O.ChildrenCount = 1) then
begin
l_F := l_O.Child[0];
if l_F.IsKindOf(k2_typFormula) then
begin
l_Pos := l_O.IntA[k2_tiStart];
l_FS := (l_F.Attr[k2_tiText].AsObject As Tl3CustomString).AsString;
if AnsiStartsStr(cSig, l_FS) then
if AnsiEndsStr(')', l_FS) then
begin
Delete(l_FS, 1, Length(cSig));
Delete(l_FS, Length(l_FS), 1);
if TryStrToInt(l_FS, l_Code) then
begin
l_WideChar := WideChar(l_Code);
Dec(l_Pos);
l_S.Delete(l_Pos, 1);
l_S.Insert(l3PCharLen(PWideChar(@l_WideChar), 1), l_Pos);
l_Objects.DeleteChild(l_Index);
continue;
end;//TryStrToInt(l_FS, l_Code)
end;//AnsiStartStr('String(#@', l_FS)
end;//l_F.IsKindOf(k2_typFormula)
end;//l_O.ChildrenCount = 1
Inc(l_Index);
end;//while l_Index
end;//l_Objects.IsValid
end;//evParaTools(aLeaf)
inherited;
//#UC END# *49E4883E0176_561E7E4B0034_impl*
end;//TevUnicodeFormulasToUnicodeConverter.DoWritePara
end.
|
unit Model.Acessos;
interface
uses Common.ENum, FireDAC.Comp.Client, Vcl.ActnList;
type
TAcessos = class
private
FAcao: TAcao;
FMenu: Integer;
FSistema: Integer;
FUsuario: Integer;
FModulo: Integer;
FAdministrador: String;
public
property Sistema: Integer read FSistema write FSistema;
property Modulo: Integer read FModulo write FModulo;
property Menu: Integer read FMenu write FMenu;
property Usuario: Integer read FUsuario write FUsuario;
property Administrador: String read FAdministrador write FAdministrador;
property Acao: TAcao read FAcao write FAcao;
function Localizar(aParam: array of variant): TFDQuery;
function AcessoExiste(aParam: array of variant): Boolean;
function Gravar(): Boolean;
function VerificaLogin(iMenu: Integer; iUsuario: Integer): Boolean;
function VerificaModulo(iModulo: Integer; iUsuario: Integer): Boolean;
function VerificaSistema(iSistema: Integer; iUsuario: Integer): Boolean;
end;
implementation
{ TAcessos }
uses DAO.Acessos;
function TAcessos.AcessoExiste(aParam: array of variant): Boolean;
var
acessosDAO : TAcessosDAO;
begin
try
acessosDAO := TAcessosDAO.Create;
Result := acessosDAO.AcessoExiste(aParam);
finally
acessosDAO.Free;
end;
end;
function TAcessos.Gravar: Boolean;
var
acessosDAO : TAcessosDAO;
begin
try
Result := False;
acessosDAO := TAcessosDAO.Create;
case FAcao of
Common.ENum.tacIncluir: Result := acessosDAO.Inserir(Self);
Common.ENum.tacExcluir: Result := acessosDAO.Excluir(Self);
end;
finally
acessosDAO.Free;
end;
end;
function TAcessos.Localizar(aParam: array of variant): TFDQuery;
var
acessosDAO : TAcessosDAO;
begin
try
acessosDAO := TAcessosDAO.Create;
Result := acessosDAO.Pesquisar(aParam);
finally
acessosDAO.Free;
end;
end;
function TAcessos.VerificaLogin(iMenu, iUsuario: Integer): Boolean;
var
acessosDAO : TAcessosDAO;
begin
try
acessosDAO := TAcessosDAO.Create;
if Self.Administrador = 'S' then
begin
Result := True;
end
else if iMenu = 0 then
begin
Result := True;
end
else
begin
Result := acessosDAO.VerificaAcesso(iMenu, iUsuario);
end;
finally
acessosDAO.Free;
end;
end;
function TAcessos.VerificaModulo(iModulo, iUsuario: Integer): Boolean;
var
acessosDAO : TAcessosDAO;
begin
try
acessosDAO := TAcessosDAO.Create;
Result := acessosDAO.VerificaModulo(iModulo, iUsuario);
finally
acessosDAO.Free;
end;
end;
function TAcessos.VerificaSistema(iSistema, iUsuario: Integer): Boolean;
var
acessosDAO : TAcessosDAO;
begin
try
acessosDAO := TAcessosDAO.Create;
Result := acessosDAO.VerificaSistema(iSistema, iUsuario);
finally
acessosDAO.Free;
end;
end;
end.
|
unit uListaCompra;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uModeloRel, StdCtrls, Buttons, Mask, JvExMask, JvToolEdit, DB,
ZAbstractRODataset, ZDataset, frxClass, frxDBSet, ExtCtrls, JvExControls,
JvNavigationPane, JvComponentBase, JvFormPlacement, JvExStdCtrls,
JvCombobox, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxImageComboBox, ZAbstractDataset;
type
TfrmListaCompra = class(TfrmModeloRel)
JvNavPanelHeader1: TJvNavPanelHeader;
Bevel1: TBevel;
frxDBRelatorio: TfrxDBDataset;
frxRelatorio: TfrxReport;
qrRelatorio: TZReadOnlyQuery;
Bevel2: TBevel;
Label3: TLabel;
Label1: TLabel;
Label2: TLabel;
d02: TJvDateEdit;
d01: TJvDateEdit;
qrEstoque: TZReadOnlyQuery;
qrRelatorionome_empresa: TStringField;
qrRelatoriosite_empresa: TStringField;
qrRelatoriotelefone_empresa: TStringField;
qrRelatorioendereco_empresa: TStringField;
qrRelatoriocomplemento_empresa: TStringField;
qrRelatoriocidade_empresa: TStringField;
qrRelatoriouf_empresa: TStringField;
qrRelatoriocep_empresa: TStringField;
qrRelatoriotipo: TStringField;
qrRelatorioproduto: TStringField;
qrRelatorionome: TStringField;
qrRelatoriounidade: TStringField;
qrRelatorioquantidade: TFloatField;
qrRelatoriounitario: TFloatField;
Label4: TLabel;
cbOrdenacao: TJvComboBox;
JvFormStorage1: TJvFormStorage;
Label5: TLabel;
edtProduto: TJvComboEdit;
Label7: TLabel;
cbFamilia: TcxImageComboBox;
qrProdutos: TZQuery;
frxProdutos: TfrxReport;
frxDBProdutos: TfrxDBDataset;
qrProdutosnome_empresa: TStringField;
qrProdutossite_empresa: TStringField;
qrProdutostelefone_empresa: TStringField;
qrProdutosendereco_empresa: TStringField;
qrProdutoscomplemento_empresa: TStringField;
qrProdutoscidade_empresa: TStringField;
qrProdutosuf_empresa: TStringField;
qrProdutoscep_empresa: TStringField;
qrProdutostipo: TStringField;
qrProdutosproduto: TStringField;
qrProdutosnome: TStringField;
qrProdutosunidade: TStringField;
qrProdutosquantidade: TFloatField;
qrProdutosunitario: TFloatField;
qrProdutoscategoria: TStringField;
qrProdutosid_venda: TLargeintField;
qrProdutosfantasia: TStringField;
qrProdutosdata: TDateField;
qrProdutosnumero: TIntegerField;
qrProdutosvalor_pedido: TFloatField;
qrProdutosqtde_pedido: TFloatField;
qrProdutostotal: TFloatField;
procedure btnImprimirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure d01Change(Sender: TObject);
procedure frxRelatorioGetValue(const VarName: string;
var Value: Variant);
procedure edtProdutoButtonClick(Sender: TObject);
procedure frxRelatorioClickObject(Sender: TfrxView;
Button: TMouseButton; Shift: TShiftState; var Modified: Boolean);
private
{ Private declarations }
produto: string;
procedure Relatorio;
public
{ Public declarations }
end;
var
frmListaCompra: TfrmListaCompra;
implementation
uses udmPrincipal, funcoes, uConsulta_Padrao;
{$R *.dfm}
procedure TfrmListaCompra.Relatorio;
begin
try
if (d01.Date = 0) or (d02.Date = 0) then
begin
Application.MessageBox('Você deve selecionar algum filtro primeiro!', 'Atenção', MB_ICONERROR);
Exit;
end;
with qrEstoque do
begin
Close;
SQL.Clear;
SQL.Add('select estoque_fisico(:pEmpresa, :data1, :data2, "%")');
ParamByName('pEmpresa').value := dmPrincipal.empresa_login;
ParamByName('data1').AsDate := d01.Date;
ParamByName('data2').AsDate := d02.Date;
Open;
end;
qrRelatorio.Close;
qrRelatorio.SQL.Clear;
qrRelatorio.SQL.Add('select');
qrRelatorio.SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, format_fone(e.telefone) as telefone_empresa,');
qrRelatorio.SQL.Add(' concat(e.logradouro,", ",e.numero) as endereco_empresa,');
qrRelatorio.SQL.Add(' e.complemento as complemento_empresa,');
qrRelatorio.SQL.Add(' e.cidade as cidade_empresa, e.uf as uf_empresa, e.cep as cep_empresa,');
qrRelatorio.SQL.Add(' ef.tipo, ef.produto, p.nome, p.unidade, ef.quantidade, ef.unitario, gp.nome as categoria');
qrRelatorio.SQL.Add(' from estoque_fisico ef');
qrRelatorio.SQL.Add(' left join empresas e on e.codigo=ef.empresa_codigo');
qrRelatorio.SQL.Add(' left join produtos p on p.codigo=ef.produto');
qrRelatorio.SQL.Add(' left join grupo_produto gp on gp.codigo=p.codigo_familia');
qrRelatorio.SQL.Add(' where ef.empresa_codigo=:pEmpresa and ef.tipo="SD"');
qrRelatorio.ParamByName('pEmpresa').value := dmPrincipal.empresa_login;
if edtProduto.Text <> EmptyStr then
begin
qrRelatorio.SQL.add('and ef.produto=:pProduto');
qrRelatorio.ParamByName('pProduto').AsString := produto; ;
end;
if cbFamilia.ItemIndex <> -1 then
begin
qrRelatorio.SQL.add('and p.codigo_familia=:pFamilia');
qrRelatorio.ParamByName('pFamilia').AsInteger := cbFamilia.Properties.Items.Items[cbFamilia.ItemIndex].Value;
end;
case cbOrdenacao.ItemIndex of
0: qrRelatorio.SQL.Add('order by p.produto'); //Data
1: qrRelatorio.SQL.Add('order by p.nome'); //Tipo
2: qrRelatorio.SQL.Add('order by gp.nome,p.nome'); //Categoria
end;
qrRelatorio.Open;
if qrRelatorio.IsEmpty then
begin
Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR);
Exit;
end
else
begin
frxRelatorio.ShowReport;
end;
finally
qrRelatorio.Close;
qrEstoque.Close;
end;
end;
procedure TfrmListaCompra.btnImprimirClick(Sender: TObject);
begin
inherited;
Relatorio;
end;
procedure TfrmListaCompra.FormCreate(Sender: TObject);
begin
inherited;
//Padrão data de hoje
d01.Date := dmPrincipal.SoData;
d02.Date := dmPrincipal.SoData;
CarregaCombo(cbFamilia, 'select codigo, nome from grupo_produto where ativo="S" order by 2');
end;
procedure TfrmListaCompra.d01Change(Sender: TObject);
begin
inherited;
d02.date := d01.date;
end;
procedure TfrmListaCompra.frxRelatorioGetValue(const VarName: string;
var Value: Variant);
var
s, b: string;
begin
inherited;
if (d01.Date <> 0) and (d02.Date = 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date))
else if (d01.Date > 0) and (d02.Date > 0) then
s := concat('Emissão de ', formatdatetime('dd/mm/yyyy', d01.Date), ' Até ', formatdatetime('dd/mm/yyyy', d02.Date));
if CompareText(VarName, 'periodo') = 0 then
Value := s;
end;
procedure TfrmListaCompra.edtProdutoButtonClick(Sender: TObject);
begin
inherited;
with TfrmConsulta_Padrao.Create(self) do
begin
with Query.SQL do
begin
Clear;
Add('select codigo, nome from produtos');
Add('where nome like :pFantasia and ativo="S"');
Add('order by nome');
end;
CampoLocate := 'nome';
Parametro := 'pFantasia';
ColunasGrid := 2;
ShowModal;
if Tag = 1 then
begin
produto := Query.Fields[0].Value;
edtProduto.Text := Query.Fields[1].Value;
end;
Free;
end;
end;
procedure TfrmListaCompra.frxRelatorioClickObject(Sender: TfrxView;
Button: TMouseButton; Shift: TShiftState; var Modified: Boolean);
begin
inherited;
if (Sender.TagStr <> EmptyStr) then
begin
try
with qrProdutos do
begin
with qrEstoque do
begin
Close;
SQL.Clear;
SQL.Add('select estoque_fisico(:pEmpresa, :data1, :data2, "%")');
ParamByName('pEmpresa').value := dmPrincipal.empresa_login;
ParamByName('data1').AsDate := d01.Date;
ParamByName('data2').AsDate := d02.Date;
Open;
end;
Close;
SQL.clear;
SQL.Add('select');
SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, format_fone(e.telefone) as telefone_empresa,');
SQL.Add(' concat(e.logradouro,", ",e.numero) as endereco_empresa,');
SQL.Add(' e.complemento as complemento_empresa,');
SQL.Add(' e.cidade as cidade_empresa, e.uf as uf_empresa, e.cep as cep_empresa,');
SQL.Add(' ef.tipo, ef.produto, p.nome, p.unidade, ef.quantidade, ef.unitario, gp.nome as categoria,');
SQL.Add(' vi.id_venda, cf.fantasia, v.data, v.numero, v.valor_pedido, vi.quantidade qtde_pedido, vi.valor_total total');
SQL.Add(' from estoque_fisico ef');
SQL.Add(' left join empresas e on e.codigo=ef.empresa_codigo');
SQL.Add(' left join produtos p on p.codigo=ef.produto');
SQL.Add(' left join grupo_produto gp on gp.codigo=p.codigo_familia');
SQL.Add(' left join vendas_itens vi on vi.produto_codigo=ef.produto');
SQL.Add(' left join vendas v on v.id=vi.id_venda');
SQL.Add(' left join clientes_fornecedores cf on cf.codigo=v.cliente_codigo and cf.filial=v.cliente_filial');
SQL.Add(' where ef.empresa_codigo=:pEmpresa and ef.tipo="SD" and');
SQL.Add(' isnull(v.data_exc) and isnull(vi.data_exc) and vi.produto_codigo=:pProduto');
ParamByName('pProduto').AsString := Sender.TagStr;
ParamByName('pEmpresa').AsInteger := dmPrincipal.empresa_login;
if (d01.Date <> 0) and (d02.Date = 0) then
begin
SQL.add('and v.data=:data1');
ParamByName('data1').AsDate := d01.Date;
end
else if (d01.Date > 0) and (d02.Date > 0) then
begin
SQL.add('and v.data between :data1 and :data2');
ParamByName('data1').AsDate := d01.Date;
ParamByName('data2').AsDate := d02.Date;
end;
if cbFamilia.ItemIndex <> -1 then
begin
SQL.add('and p.codigo_familia=:pFamilia');
ParamByName('pFamilia').AsInteger := cbFamilia.Properties.Items.Items[cbFamilia.ItemIndex].Value;
end;
Open;
if IsEmpty then
begin
Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR);
Exit;
end
else
begin
frxProdutos.ShowReport;
end;
end;
finally
qrProdutos.Close;
qrEstoque.Close;
end;
end;
end;
end.
|
unit alcuDetachedExecutor;
// Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuDetachedExecutor.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TalcuDetachedExecutor" MUID: (54BE24CC00D4)
{$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc}
interface
{$If Defined(ServerTasks)}
uses
l3IntfUses
, l3ProtoObject
{$If NOT Defined(Nemesis)}
, ncsMessageInterfaces
{$IfEnd} // NOT Defined(Nemesis)
, alcuDetachedExecutorPool
, l3Base
{$If NOT Defined(Nemesis)}
, ncsMessage
{$IfEnd} // NOT Defined(Nemesis)
;
type
TalcuDetachedExecutorThread = {final} class(Tl3ThreadContainer)
private
f_Executor: IncsExecutor;
f_Message: TncsMessage;
f_Transporter: IncsTransporter;
private
procedure Prepare(const anExecutor: IncsExecutor;
const aContext: TncsExecuteContext); virtual;
protected
procedure DoExecute; override;
{* основная процедура нити. Для перекрытия в потомках }
procedure Cleanup; override;
{* Функция очистки полей объекта. }
end;//TalcuDetachedExecutorThread
TalcuDetachedExecutor = class(Tl3ProtoObject{$If NOT Defined(Nemesis)}
, IncsExecutor
{$IfEnd} // NOT Defined(Nemesis)
)
private
f_Executor: IncsExecutor;
f_Pool: TalcuDetachedExecutorPool;
f_Thread: TalcuDetachedExecutorThread;
protected
{$If NOT Defined(Nemesis)}
procedure Execute(const aContext: TncsExecuteContext);
{$IfEnd} // NOT Defined(Nemesis)
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aPool: TalcuDetachedExecutorPool;
const anExecutor: IncsExecutor); reintroduce;
class function Make(aPool: TalcuDetachedExecutorPool;
const anExecutor: IncsExecutor): IncsExecutor; reintroduce;
end;//TalcuDetachedExecutor
{$IfEnd} // Defined(ServerTasks)
implementation
{$If Defined(ServerTasks)}
uses
l3ImplUses
, SysUtils
//#UC START# *54BE24CC00D4impl_uses*
//#UC END# *54BE24CC00D4impl_uses*
;
procedure TalcuDetachedExecutorThread.Prepare(const anExecutor: IncsExecutor;
const aContext: TncsExecuteContext);
//#UC START# *54BF6414034B_54BE65DF001D_var*
//#UC END# *54BF6414034B_54BE65DF001D_var*
begin
//#UC START# *54BF6414034B_54BE65DF001D_impl*
f_Executor := anExecutor;
aContext.rMessage.SetRefTo(f_Message);
f_Transporter := aContext.rTransporter;
//#UC END# *54BF6414034B_54BE65DF001D_impl*
end;//TalcuDetachedExecutorThread.Prepare
procedure TalcuDetachedExecutorThread.DoExecute;
{* основная процедура нити. Для перекрытия в потомках }
//#UC START# *4911B69E037D_54BE65DF001D_var*
//#UC END# *4911B69E037D_54BE65DF001D_var*
begin
//#UC START# *4911B69E037D_54BE65DF001D_impl*
f_Executor.Execute(TncsExecuteContext_C(f_Message, f_Transporter));
//#UC END# *4911B69E037D_54BE65DF001D_impl*
end;//TalcuDetachedExecutorThread.DoExecute
procedure TalcuDetachedExecutorThread.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_54BE65DF001D_var*
//#UC END# *479731C50290_54BE65DF001D_var*
begin
//#UC START# *479731C50290_54BE65DF001D_impl*
f_Executor := nil;
FreeAndNil(f_Message);
f_Transporter := nil;
inherited;
//#UC END# *479731C50290_54BE65DF001D_impl*
end;//TalcuDetachedExecutorThread.Cleanup
constructor TalcuDetachedExecutor.Create(aPool: TalcuDetachedExecutorPool;
const anExecutor: IncsExecutor);
//#UC START# *54BE25E40316_54BE24CC00D4_var*
//#UC END# *54BE25E40316_54BE24CC00D4_var*
begin
//#UC START# *54BE25E40316_54BE24CC00D4_impl*
inherited Create;
f_Pool := aPool; // Weak;
f_Executor := anExecutor;
f_Thread := TalcuDetachedExecutorThread.Create;
//#UC END# *54BE25E40316_54BE24CC00D4_impl*
end;//TalcuDetachedExecutor.Create
class function TalcuDetachedExecutor.Make(aPool: TalcuDetachedExecutorPool;
const anExecutor: IncsExecutor): IncsExecutor;
var
l_Inst : TalcuDetachedExecutor;
begin
l_Inst := Create(aPool, anExecutor);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TalcuDetachedExecutor.Make
{$If NOT Defined(Nemesis)}
procedure TalcuDetachedExecutor.Execute(const aContext: TncsExecuteContext);
//#UC START# *54607DDC0159_54BE24CC00D4_var*
//#UC END# *54607DDC0159_54BE24CC00D4_var*
begin
//#UC START# *54607DDC0159_54BE24CC00D4_impl*
f_Thread.Prepare(f_Executor, aCOntext);
f_Pool.Launch(f_Thread);
//#UC END# *54607DDC0159_54BE24CC00D4_impl*
end;//TalcuDetachedExecutor.Execute
{$IfEnd} // NOT Defined(Nemesis)
procedure TalcuDetachedExecutor.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_54BE24CC00D4_var*
//#UC END# *479731C50290_54BE24CC00D4_var*
begin
//#UC START# *479731C50290_54BE24CC00D4_impl*
f_Executor := nil;
f_Pool := nil;
FreeAndNil(f_Thread);
inherited;
//#UC END# *479731C50290_54BE24CC00D4_impl*
end;//TalcuDetachedExecutor.Cleanup
{$IfEnd} // Defined(ServerTasks)
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.