text stringlengths 14 6.51M |
|---|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Micron.New;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TNewMicronSMARTSupport = class(TSMARTSupport)
private
function CheckMU014Characteristics(
const SMARTList: TSMARTValueList): Boolean;
function CheckMU02Characteristics(
const SMARTList: TSMARTValueList): Boolean;
function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite;
const
EntryID = $CA;
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
protected
function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer;
override;
function InnerIsErrorAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsCautionAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult;
override;
function InnerIsCaution(const SMARTList: TSMARTValueList):
TSMARTErrorResult; override;
end;
implementation
{ TNewMicronSMARTSupport }
function TNewMicronSMARTSupport.GetTypeName: String;
begin
result := 'SmartMicronMU02';
end;
function TNewMicronSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TNewMicronSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TNewMicronSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
CheckMU02Characteristics(SMARTList) or
CheckMU014Characteristics(SMARTList);
end;
function TNewMicronSMARTSupport.CheckMU02Characteristics(
const SMARTList: TSMARTValueList): Boolean;
begin
// Crucial BX100 MU02 2015/11/26
result :=
(SMARTList.Count >= 11) and
(SMARTList[0].Id = $01) and
(SMARTList[1].Id = $05) and
(SMARTList[2].Id = $09) and
(SMARTList[3].Id = $0C) and
(SMARTList[4].Id = $A0) and
(SMARTList[5].Id = $A1) and
(SMARTList[6].Id = $A3) and
(SMARTList[7].Id = $A4) and
(SMARTList[8].Id = $A5) and
(SMARTList[9].Id = $A6) and
(SMARTList[10].Id = $A7);
end;
function TNewMicronSMARTSupport.CheckMU014Characteristics(
const SMARTList: TSMARTValueList): Boolean;
begin
// Crucial BX200 MU01.4 2015/11/26
result :=
(SMARTList.Count >= 11) and
(SMARTList[0].Id = $01) and
(SMARTList[1].Id = $05) and
(SMARTList[2].Id = $09) and
(SMARTList[3].Id = $0C) and
(SMARTList[4].Id = $A0) and
(SMARTList[5].Id = $A1) and
(SMARTList[6].Id = $A3) and
(SMARTList[7].Id = $94) and
(SMARTList[8].Id = $95) and
(SMARTList[9].Id = $96) and
(SMARTList[10].Id = $97);
end;
function TNewMicronSMARTSupport.ErrorCheckedGetLife(
const SMARTList: TSMARTValueList): Integer;
begin
result := SMARTList[SMARTList.GetIndexByID($A9)].Current;
end;
function TNewMicronSMARTSupport.InnerIsErrorAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := true;
end;
function TNewMicronSMARTSupport.InnerIsCautionAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := IsEntryAvailable(EntryID, SMARTList);
end;
function TNewMicronSMARTSupport.InnerIsError(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result.Override := false;
result.Status :=
InnerCommonIsError(EntryID, SMARTList).Status;
end;
function TNewMicronSMARTSupport.InnerIsCaution(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold);
end;
function TNewMicronSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
const
WriteID1 = $F1;
WriteID2 = $F5;
begin
try
SMARTList.GetIndexByID(WriteID1);
result := true;
except
result := false;
end;
if not result then
begin
try
SMARTList.GetIndexByID(WriteID2);
result := true;
except
result := false;
end;
end;
end;
function TNewMicronSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $01;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
result.TotalWrite := GetTotalWrite(SMARTList);
end;
function TNewMicronSMARTSupport.GetTotalWrite(
const SMARTList: TSMARTValueList): TTotalWrite;
function LBAToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shr 1;
end;
function GBToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shl 10;
end;
const
HostWrite = true;
NANDWrite = false;
WriteID1 = $F1;
WriteID2 = $F5;
begin
result.InValue.TrueHostWriteFalseNANDWrite :=
HostWrite;
try
result.InValue.ValueInMiB :=
LBAToMB(SMARTList.GetRAWByID(WriteID1));
except
try
result.InValue.ValueInMiB :=
LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID2));
except
result.InValue.ValueInMiB := 0;
end;
end;
end;
end.
|
unit ncTempo;
interface
uses
SysUtils,
DB,
MD5,
Classes,
Windows,
ClasseCS,
ncClassesBase;
type
TncTempo = class
private
function GetString: String;
procedure SetString(const Value: String);
public
teID : Integer;
teDataHora : TDateTime;
teFunc : String;
teTipo : Byte;
teMinutos : Double;
teIDPacPass : Integer;
teTotal : Currency;
teDesconto : Currency;
tePago : Currency;
teCliente : Integer;
teMaq : Word;
teSessao : Integer;
teCancelado : Boolean;
teTran : Integer;
teCaixa : Integer;
_Operacao : Byte;
constructor Create;
procedure Limpa;
procedure AssignFrom(T: TncTempo);
function Igual(T: TncTempo): Boolean;
function Debito: Currency;
procedure SaveToDataset(D: TDataset);
procedure SaveToITranDataset(D: TDataset);
procedure SaveToTran(D: TDataset);
procedure SaveToStream(S: TStream);
procedure LoadFromDataset(D: TDataset);
procedure LoadFromStream(S: TStream);
property AsString: String
read GetString write SetString;
end;
TncTempos = class
private
FItens : TList;
function GetItem(I: Integer): TncTempo;
function GetString: String;
procedure SetString(Value: String);
public
constructor Create;
destructor Destroy; override;
procedure AjustaOperacao(B: TncTempos);
procedure Limpa;
function Count: Integer;
function NewItem: TncTempo;
function GetItemByID(aID: Integer): TncTempo;
property Itens[I: Integer]: TncTempo
read GetItem; Default;
property AsString: String
read GetString write SetString;
end;
implementation
{ TncTempo }
procedure TncTempo.AssignFrom(T: TncTempo);
begin
teID := T.teID;
teDataHora := T.teDataHora;
teFunc := T.teFunc;
teTipo := T.teTipo;
teMinutos := T.teMinutos;
teIDPacPass := T.teIDPacPass;
teTotal := T.teTotal;
teDesconto := T.teDesconto;
tePago := T.tePago;
teCliente := T.teCliente;
teMaq := T.teMaq;
teSessao := T.teSessao;
teCancelado := T.teCancelado;
teTran := T.teTran ;
teCaixa := T.teCaixa;
_Operacao := T._Operacao;
end;
constructor TncTempo.Create;
begin
Limpa;
end;
function TncTempo.Debito: Currency;
begin
Result := teTotal - teDesconto - tePago;
end;
function TncTempo.GetString: String;
begin
Result :=
IntToStr(teID) + sFldDelim(classid_TncTempo) +
GetDTStr(teDataHora) + sFldDelim(classid_TncTempo) +
teFunc + sFldDelim(classid_TncTempo) +
IntToStr(teTipo) + sFldDelim(classid_TncTempo) +
FloatParaStr(teMinutos) + sFldDelim(classid_TncTempo) +
IntToStr(teIDPacPass) + sFldDelim(classid_TncTempo) +
FloatParaStr(teTotal) + sFldDelim(classid_TncTempo) +
FloatParaStr(teDesconto) + sFldDelim(classid_TncTempo) +
FloatParaStr(tePago) + sFldDelim(classid_TncTempo) +
IntToStr(teCliente) + sFldDelim(classid_TncTempo) +
IntToStr(teMaq) + sFldDelim(classid_TncTempo) +
IntToStr(teSessao) + sFldDelim(classid_TncTempo) +
BoolStr[teCancelado] + sFldDelim(classid_TncTempo) +
IntToStr(teTran) + sFldDelim(classid_TncTempo) +
IntToStr(teCaixa) + sFldDelim(classid_TncTempo) +
IntToStr(_Operacao) + sFldDelim(classid_TncTempo);
end;
function TncTempo.Igual(T: TncTempo): Boolean;
begin
Result := False;
if teID <> T.teID then Exit;
if teDataHora <> T.teDataHora then Exit;
if teFunc <> T.teFunc then Exit;
if teTipo <> T.teTipo then Exit;
if teMinutos <> T.teMinutos then Exit;
if teIDPacPass <> T.teIDPacPass then Exit;
if teTotal <> T.teTotal then Exit;
if teDesconto <> T.teDesconto then Exit;
if tePago <> T.tePago then Exit;
if teCliente <> T.teCliente then Exit;
if teMaq <> T.teMaq then Exit;
if teSessao <> T.teSessao then Exit;
if teCancelado <> T.teCancelado then Exit;
if teTran <> T.teTran then Exit;
if teCaixa <> T.teCaixa then Exit;
if _Operacao <> T._Operacao then Exit;
Result := True;
end;
procedure TncTempo.Limpa;
begin
teID := -1;
teDataHora := 0;
teFunc := '';
teTipo := tctPrevisao;
teMinutos := 0;
teIDPacPass := 0;
teTotal := 0;
teDesconto := 0;
tePago := 0;
teCliente := 0;
teMaq := 0;
teSessao := 0;
teCancelado := False;
teTran := -1;
teCaixa := 0;
_Operacao := osNenhuma;
end;
procedure TncTempo.LoadFromDataset(D: TDataset);
begin
teID := D.FieldByName('ID').AsInteger;
teDataHora := D.FieldByName('DataHora').AsDateTime;
teFunc := D.FieldByName('Func').AsString;
teTipo := D.FieldByName('Tipo').AsInteger;
teMinutos := D.FieldByName('Minutos').AsFloat;
teIDPacPass := D.FieldByName('IDPacPass').AsInteger;
teTotal := D.FieldByName('Total').AsCurrency;
teDesconto := D.FieldByName('Desconto').AsCurrency;
tePago := D.FieldByName('Pago').AsCurrency;
teCliente := D.FieldByName('Cliente').AsInteger;
teMaq := D.FieldByName('Maq').AsInteger;
teSessao := D.FieldByName('Sessao').AsInteger;
teCancelado := D.FieldByName('Cancelado').AsBoolean;
teTran := D.FieldByName('Tran').AsInteger;
teCaixa := D.FieldByName('Caixa').AsInteger;
_Operacao := osNenhuma;
end;
procedure TncTempo.LoadFromStream(S: TStream);
var
Str: String;
I: Integer;
begin
S.Read(I, SizeOf(I));
if I>0 then begin
SetLength(Str, I);
S.Read(Str[1], I);
AsString := Str;
end else
Limpa;
end;
procedure TncTempo.SaveToDataset(D: TDataset);
begin
if teID<>-1 then
D.FieldByName('ID').AsInteger := teID else
D.FieldByName('ID').Clear;
D.FieldByName('DataHora').AsDateTime := teDataHora;
D.FieldByName('Func').AsString := teFunc;
D.FieldByName('Tipo').AsInteger := teTipo;
D.FieldByName('Minutos').AsFloat := teMinutos;
D.FieldByName('IDPacPass').AsInteger := teIDPacPass;
D.FieldByName('Total').AsCurrency := teTotal;
D.FieldByName('Desconto').AsCurrency := teDesconto;
D.FieldByName('Pago').AsCurrency := tePago;
D.FieldByName('Cliente').AsInteger := teCliente;
D.FieldByName('Maq').AsInteger := teMaq;
D.FieldByName('Sessao').AsInteger := teSessao;
D.FieldByName('Cancelado').AsBoolean := teCancelado;
D.FieldByName('Tran').AsInteger := teTran;
D.FieldByName('Caixa').AsInteger := teCaixa;
end;
procedure TncTempo.SaveToITranDataset(D: TDataset);
begin
D.FieldByName('Tran').AsInteger := teTran;
D.FieldByName('Caixa').AsInteger := teCaixa;
D.FieldByName('DataHora').AsDateTime := teDataHora;
D.FieldByName('Caixa').AsInteger := teCaixa;
D.FieldByName('TipoItem').AsInteger := itMovEst;
D.FieldByName('ItemID').AsInteger := teID;
D.FieldByname('ItemPos').AsInteger := 1;
D.FieldByName('Total').AsCurrency := teTotal;
D.FieldByName('Desconto').AsCurrency := teDesconto;
D.FieldByName('Pago').AsCurrency := tePago;
D.FieldByName('Cancelado').AsBoolean := teCancelado;
D.FieldByName('Sessao').AsInteger := teSessao;
end;
procedure TncTempo.SaveToStream(S: TStream);
var
Str: String;
I: Integer;
begin
Str := AsString;
I := Length(Str);
S.Write(I, SizeOf(I));
if I>0 then
S.Write(Str[1], I);
end;
procedure TncTempo.SaveToTran(D: TDataset);
begin
D.FieldByName('Caixa').AsInteger := teCaixa;
D.FieldByName('DataHora').AsDateTime := teDataHora;
D.FieldByName('Caixa').AsInteger := teCaixa;
D.FieldByName('Total').AsCurrency := teTotal;
D.FieldByName('Desconto').AsCurrency := teDesconto;
D.FieldByName('Pago').AsCurrency := tePago;
D.FieldByName('Cancelado').AsBoolean := teCancelado;
D.FieldByName('Sessao').AsInteger := teSessao;
end;
procedure TncTempo.SetString(const Value: String);
var S: String;
function _NextField: String;
begin
Result := GetNextStrDelim(S, classid_TncTempo);
end;
begin
Limpa;
teID := StrToIntDef(_NextField, -1);
teDataHora := DTFromStr(_NextField);
teFunc := _NextField;
teTipo := StrToIntDef(_NextField, 0);
teMinutos := StrParaFloat(_NextField);
teIDPacPass := StrToIntDef(_NextField, 0);
teTotal := StrParaFloat(_NextField);
teDesconto := StrParaFloat(_NextField);
tePago := StrParaFloat(_NextField);
teCliente := StrToIntDef(_NextField, 0);
teMaq := StrToIntDef(_NextField, 0);
teSessao := StrToIntDef(_NextField, 0);
teCancelado := (BoolStr[True]=_NextField);
teTran := StrToIntDef(_NextField, -1);
teCaixa := StrToIntDef(_NextField, 0);
_Operacao := osNenhuma;
end;
{ TncTempos }
procedure TncTempos.AjustaOperacao(B: TncTempos);
var
I, N : Integer;
T : TncTempo;
begin
N := 0;
for I := 0 to B.Count - 1 do
if not B[I]._Operacao<>osExcluir then begin
Inc(N);
B[I].teID := N;
end;
for I := 0 to Count - 1 do with Itens[I] do
if (teID<>-1) and (B.GetItemByID(teID)=nil) then
_Operacao := osExcluir;
for I := 0 to B.Count - 1 do
if (B[I].teID=-1) then begin
B[I]._Operacao := osIncluir;
NewItem.AssignFrom(B[I]);
end
else begin
T := GetItemByID(B[I].teID);
if T<>nil then begin
if T.Igual(B[I]) then
B[I]._Operacao := osNenhuma else
B[I]._Operacao := osAlterar;
T.AssignFrom(B[I]);
end;
end;
for I := Count-1 downto 0 do
if Itens[I]._Operacao=osNenhuma then begin
Itens[I].Free;
FItens.Delete(I);
end;
end;
function TncTempos.Count: Integer;
begin
Result := FItens.Count;
end;
constructor TncTempos.Create;
begin
FItens := TList.Create;
end;
destructor TncTempos.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TncTempos.GetItem(I: Integer): TncTempo;
begin
Result := TncTempo(FItens[I]);
end;
function TncTempos.GetItemByID(aID: Integer): TncTempo;
var I : Integer;
begin
for I := 0 to FItens.Count - 1 do with Itens[I] do
if teID=aID then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncTempos.GetString: String;
var I : Integer;
begin
Result := '';
for I := 0 to Count - 1 do
Result := Result + Itens[I].AsString + sListaDelim(classid_TncTempos);
end;
procedure TncTempos.Limpa;
begin
while Count>0 do begin
Itens[0].Free;
FItens.Delete(0);
end;
end;
function TncTempos.NewItem: TncTempo;
begin
Result := TncTempo.Create;
FItens.Add(Result);
end;
procedure TncTempos.SetString(Value: String);
var S: String;
begin
Limpa;
while GetNextListItem(Value, S, classid_TncTempos) do
NewItem.AsString := S;
end;
end.
|
unit uIShorten;
interface
type
IShorten = interface
function Shorten(LongURL: String): String;
end;
IFactoryMethod = interface
function ShortURL(Token: String): IShorten;
end;
implementation
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
type
TMainForm = class(TForm)
ListBtn: TBitBtn;
ClearBtn: TBitBtn;
DelBtn: TBitBtn;
SortBtn: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ListBtnClick(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
procedure DelBtnClick(Sender: TObject);
procedure SortBtnClick(Sender: TObject);
private
PixList: TList;
PixNum: Integer;
public
{ Public declarations }
end;
TMyPixel = class(TObject)
FX: Integer;
FY: Integer;
FText: Integer;
constructor Create(X, Y, Num: Integer);
procedure SetPixel;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
const PixColor = clRed;
var CurPixel: TMyPixel;
constructor TMyPixel.Create(X, Y, Num: Integer);
begin
inherited Create;
FX := X;
FY := Y;
FText := Num;
SetPixel;
end;
procedure TMyPixel.SetPixel;
begin
MainForm.Canvas.PolyLine([Point(FX, FY), Point(FX, FY)]);
MainForm.Canvas.TextOut(FX + 1, FY + 1, IntToStr(FText));
end;
function PixCompare(Item1, Item2: Pointer): Integer;
var Pix1, Pix2: TMyPixel;
begin
Pix1 := Item1;
Pix2 := Item2;
Result := Pix1.FX - Pix2.FX;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
PixList := TList.Create;
PixNum := 1; {Счетчик точек}
Canvas.Pen.Color := PixColor; {Цвет точки}
Canvas.Pen.Width := 3; {Размер точки}
Canvas.Brush.Color := Color; {Цвет фора текста равен цвету формы}
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
PixList.Free;
end;
procedure TMainForm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
PixList.Add(TMyPixel.Create(X, Y, PixNum));
Inc(PixNum);
end;
procedure TMainForm.ListBtnClick(Sender: TObject);
var i: Integer;
begin
with PixList do
for i := 0 to Count - 1 do
begin
CurPixel := Items[i];
CurPixel.SetPixel;
end;
end;
procedure TMainForm.ClearBtnClick(Sender: TObject);
begin
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
procedure TMainForm.DelBtnClick(Sender: TObject);
begin
PixList.Clear;
PixNum := 1;
end;
procedure TMainForm.SortBtnClick(Sender: TObject);
var i: Integer;
begin
PixList.Sort(PixCompare);
with PixList do
for i := 0 to Count - 1 do TMyPixel(Items[i]).FText := i + 1;
end;
end.
|
unit UFrmGoodsInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmGrid, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB,
cxDBData, dxSkinsdxBarPainter, ImgList, ActnList, dxBar, DBClient, cxClasses,
ExtCtrls, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxTextEdit, cxDBLookupComboBox,
cxCheckBox, cxSpinEdit, cxCurrencyEdit;
type
TFrmGoodsInfo = class(TFrmGrid)
ClmnDataGoodsID: TcxGridDBColumn;
ClmnDataGoodsName: TcxGridDBColumn;
ClmnDataGoodsPYM: TcxGridDBColumn;
ClmnDataGoodsType: TcxGridDBColumn;
ClmnDataGoodsUnit: TcxGridDBColumn;
ClmnDataGoodsPrice: TcxGridDBColumn;
ClmnDataClassGuid: TcxGridDBColumn;
ClmnDataRemark: TcxGridDBColumn;
CdsGoodsClass: TClientDataSet;
dsGoodsClass: TDataSource;
ClmnDataGoodsBarCode: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure actNewExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure grdbtblvwDataDblClick(Sender: TObject);
procedure grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
procedure QueryData;
public
end;
var
FrmGoodsInfo: TFrmGoodsInfo;
implementation
uses dxForms, UDBAccess, UFrmGoodsInfoEdit, UMsgBox, UDmGoodsInfo;
{$R *.dfm}
procedure TFrmGoodsInfo.actDeleteExecute(Sender: TObject);
begin
inherited;
if not ShowConfirm('您确定要删除当前选择的商品信息吗?') then Exit;
if CdsData.Active and not CdsData.IsEmpty then
begin
CdsData.Delete;
if not DBAccess.ApplyUpdates('GoodsInfo', CdsData) then
begin
CdsData.CancelUpdates;
ShowMsg('删除商品信息失败!');
Exit;
end;
CdsData.MergeChangeLog;
end;
end;
procedure TFrmGoodsInfo.actEditExecute(Sender: TObject);
begin
inherited;
if CdsData.Active and not CdsData.IsEmpty then
TFrmGoodsInfoEdit.ShowGoodsInfoEdit(CdsData, 'Edit');
end;
procedure TFrmGoodsInfo.actNewExecute(Sender: TObject);
begin
inherited;
if CdsData.Active then
TFrmGoodsInfoEdit.ShowGoodsInfoEdit(CdsData, 'Append');
end;
procedure TFrmGoodsInfo.actRefreshExecute(Sender: TObject);
begin
inherited;
QueryData;
end;
procedure TFrmGoodsInfo.FormCreate(Sender: TObject);
begin
inherited;
DmGoodsInfo := TDmGoodsInfo.Create(nil);
QueryData;
end;
procedure TFrmGoodsInfo.FormDestroy(Sender: TObject);
begin
FreeAndNil(DmGoodsInfo);
inherited;
end;
procedure TFrmGoodsInfo.FormShow(Sender: TObject);
begin
inherited;
grdData.SetFocus;
end;
procedure TFrmGoodsInfo.grdbtblvwDataDblClick(Sender: TObject);
begin
inherited;
actEditExecute(nil);
end;
procedure TFrmGoodsInfo.grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
actEditExecute(nil);
end;
procedure TFrmGoodsInfo.QueryData;
var
lStrSql: string;
begin
lStrSql := 'select * from GoodsInfo order by GoodsID';
DBAccess.ReadDataSet(lStrSql, CdsData);
end;
initialization
dxFormManager.RegisterForm(TFrmGoodsInfo);
end.
|
{**********************************************}
{ TDonutSeries }
{ Copyright (c) 1999-2004 by David Berneda }
{**********************************************}
unit TeeDonut;
{$I TeeDefs.inc}
interface
Uses {$IFDEF CLR}
Classes,
{$ELSE}
{$IFNDEF LINUX}
Windows,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics,
{$ELSE}
Graphics,
{$ENDIF}
{$ENDIF}
TeEngine, Chart, TeCanvas, Series;
{ TDonutSeries -> Pie Series with a hole in the center. }
Const TeeDefaultDonutPercent = 50;
Type
TDonutSeries=class(TPieSeries)
protected
class Function GetEditorClass:String; override;
public
Constructor Create(AOwner: TComponent); override;
Procedure Assign(Source: TPersistent); override; { 5.02 }
published
property DonutPercent default TeeDefaultDonutPercent;
end;
implementation
Uses TeeConst, TeeProCo;
{ TDonutSeries }
Constructor TDonutSeries.Create(AOwner: TComponent);
begin
inherited;
SetDonutPercent(TeeDefaultDonutPercent);
end;
procedure TDonutSeries.Assign(Source: TPersistent);
begin
if Source is TDonutSeries then
With TDonutSeries(Source) do
begin
Self.DonutPercent:=DonutPercent; { 5.02 }
end;
inherited;
if Self.DonutPercent<=0 then
SetDonutPercent(TeeDefaultDonutPercent);
end;
class Function TDonutSeries.GetEditorClass:String;
begin
result:='TDonutSeriesEditor';
end;
initialization
RegisterTeeSeries(TDonutSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryDonut,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended,1);
finalization
UnRegisterTeeSeries([TDonutSeries]);
end.
|
unit uGeometryClasses;
interface
uses
System.Types;
{
增加初始长宽和现在的长宽到这个记录里面来,这样便于数据的统一记录....
这样在计算缩放的时候,所有的参数都齐全了....
}
Type
T2DPosition = record
InitX,InitY : Single;
X,Y : Single;
InitWidth, InitHeight : Single;
Width, Height : Single;
Rotate : Single;
ScaleX,ScaleY : Single;
function Zero : T2DPosition;
end;
implementation
{T2DPosition}
function T2DPosition.Zero;
begin
InitX := 0;
InitY := 0;
X := 0;
Y := 0;
Rotate := 0;
ScaleX := 1;
ScaleY := 1;
InitWidth := 50;
InitHeight := 50;
Width := 50;
Height := 50;
end;
end.
|
unit Test.Devices.Mercury.Parser;
interface
uses TestFrameWork, GMGlobals, Classes, SysUtils, Devices.Mercury, Windows, Test.Devices.Base.ReqParser,
GmSqlQuery, UsefulQueries, Threads.ResponceParser, GMConst, Math;
type
TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest);
TMercuryParserForTest = class(TMercuryParser);
TMercury230ParserTest = class(TDeviceReqParserTestBase)
private
FParser: TMercuryParserForTest;
thr: TLocalSQLWriteThreadForTest;
procedure SetThreadIds;
function Examples_MeterInfo: ArrayOfByte;
function Examples_Readings: ArrayOfByte;
function Examples_LastArchAddr: ArrayOfByte;
function Examples_ArchiveRecord: ArrayOfByte;
protected
procedure SetUp; override;
procedure TearDown; override;
function GetDevType(): int; override;
function GetThreadClass(): TSQLWriteThreadForTestClass; override;
published
procedure CRC();
procedure ParseReadings;
procedure ParseMeterInfo;
procedure ParseLastArchAddr();
procedure ParseArchiveRecord();
procedure Bin2Dec();
procedure ArchDT();
procedure Thread_MeterInfo;
procedure Thread_Readings;
procedure Thread_LastArchAddr;
procedure Thread_ArchiveRecord;
end;
implementation
procedure TMercury230ParserTest.ArchDT;
var buf: ArrayOfByte;
begin
buf := TextNumbersStringToArray('31 FD 20 09 19 30 15 11 14 1E 7F BD');
Check(FParser.SetLastArchAddrBuffer(buf, Length(buf)), 'buf');
Check(FParser.ReadArchUDT(4) = EncodeDateTimeUTC(2014, 11, 15, 19, 00));
end;
procedure TMercury230ParserTest.Bin2Dec;
begin
Check(FParser.BinToDec($01) = 1);
Check(FParser.BinToDec($11) = 11);
Check(FParser.BinToDec($59) = 59);
end;
procedure TMercury230ParserTest.CRC;
var buf: ArrayOfByte;
begin
buf := TextNumbersStringToArray('31 00 20 00 40 00 27 00 57 00 38 00 38 00 38 00 38 18 A9');
Check(Mercury_CheckCRC(buf, Length(buf)));
buf := TextNumbersStringToArray('31 00 20 00 40 00 27 00 57 00 38 00 38 00 38 00 38 18 A9 01');
Check(not Mercury_CheckCRC(buf, Length(buf)));
buf := TextNumbersStringToArray('31 01 01 01 01 01 01 01 01 2E 10');
Check(Mercury_CheckCRC(buf, Length(buf)));
buf := TextNumbersStringToArray('49 5 212 35', false);
Check(Mercury_CheckCRC(buf, Length(buf)));
end;
function TMercury230ParserTest.GetDevType: int;
begin
Result := DEVTYPE_MERCURY_230;
end;
function TMercury230ParserTest.GetThreadClass: TSQLWriteThreadForTestClass;
begin
Result := TLocalSQLWriteThreadForTest;
end;
function TMercury230ParserTest.Examples_MeterInfo(): ArrayOfByte;
begin
Result := TextNumbersStringToArray('31 B4 E4 C2 91 07 00 3E 04');
end;
function TMercury230ParserTest.Examples_Readings(): ArrayOfByte;
begin
Result := TextNumbersStringToArray('31 00 00 79 BD FF FF FF FF 00 00 61 02 FF FF FF FF 84 0A');
end;
function TMercury230ParserTest.Examples_LastArchAddr(): ArrayOfByte;
begin
Result := TextNumbersStringToArray('31 FD 20 09 19 30 15 11 14 1E 7F BD');
end;
function TMercury230ParserTest.Examples_ArchiveRecord(): ArrayOfByte;
begin
Result := TextNumbersStringToArray('31 01 21 00 09 11 14 1E 3E 00 FF FF 00 00 FF FF 85 A6');
end;
procedure TMercury230ParserTest.ParseArchiveRecord;
var buf: ArrayOfByte;
begin
buf := Examples_ArchiveRecord();
Check(FParser.SetArchiveRecordBuffer(buf, Length(buf)), 'buf');
Check(FParser.ReadArchiveRecordUDT() = EncodeDateTimeUTC(2014, 11, 09, 20, 30));
Check(CompareValue(FParser.ReadArchiveRecordChannelImpulses(TMercuryReadingsChannel.mrcAin), 62) = 0);
Check(CompareValue(FParser.ReadArchiveRecordChannelImpulses(TMercuryReadingsChannel.mrcQin), 0) = 0);
end;
procedure TMercury230ParserTest.ParseLastArchAddr;
var buf: ArrayOfByte;
begin
buf := Examples_LastArchAddr();
Check(FParser.SetLastArchAddrBuffer(buf, Length(buf)), 'buf');
Check(FParser.ReadLastArchAddr() = $FD20, 'ReadLastArchAddr');
Check(FParser.ReadLastArchUDT() = EncodeDateTimeUTC(2014, 11, 15, 19, 00, 00));
end;
procedure TMercury230ParserTest.ParseMeterInfo;
var buf: ArrayOfByte;
begin
buf := Examples_MeterInfo();
Check(FParser.SetMeterInfoBuffer(buf, Length(buf)));
Check(FParser.ReadImpulsePerKWt() = 1000);
end;
procedure TMercury230ParserTest.ParseReadings;
var buf: ArrayOfByte;
begin
buf := Examples_Readings();
Check(FParser.SetReadingsBuffer(buf, Length(buf)));
Check(FParser.CheckReadingChannel(TMercuryReadingsChannel.mrcAin));
Check(not FParser.CheckReadingChannel(TMercuryReadingsChannel.mrcAout));
Check(FParser.CheckReadingChannel(TMercuryReadingsChannel.mrcQin));
Check(not FParser.CheckReadingChannel(TMercuryReadingsChannel.mrcQout));
Check(CompareValue(FParser.ReadingsChannelImpulses(TMercuryReadingsChannel.mrcAin), 48505) = 0);
Check(CompareValue(FParser.ReadingsChannelImpulses(TMercuryReadingsChannel.mrcQin), 609) = 0);
end;
procedure TMercury230ParserTest.SetUp;
begin
inherited;
FParser := TMercuryParserForTest.Create();
ExecSQL('delete from DevStates');
thr := TLocalSQLWriteThreadForTest(thread);
end;
procedure TMercury230ParserTest.TearDown;
begin
FParser.Free();
inherited;
end;
procedure TMercury230ParserTest.SetThreadIds();
begin
thr.ChannelIds.ID_DevType := DEVTYPE_MERCURY_230;
thr.ChannelIds.ID_Src := SRC_CNT_MTR;
thr.ChannelIds.N_Src := 1;
thr.ChannelIds.ID_Device := 1;
thr.ChannelIds.NDevNumber := 49;
end;
procedure TMercury230ParserTest.Thread_ArchiveRecord;
begin
gbv.SetBufRec(Examples_ArchiveRecord());
gbv.ReqDetails.rqtp := rqtMercury230_Archive;
SetThreadIds();
SQLReq_SetDevState(thr.ChannelIds.ID_Device, DEV_STATE_NAMES_IMP_PER_KWT, '1000'); // потом надо бы не корежить БД, а вынести в ...ForTest
thr.ChannelIds.N_Src := 1;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(thr.Values) = 1);
Check(CompareValue(thr.Values[0].Val, 0.031) = 0);
Check(thr.Values[0].UTime = EncodeDateTimeUTC(2014, 11, 09, 20, 30));
thr.ChannelIds.N_Src := 2;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresUnknown);
thr.ChannelIds.N_Src := 3;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(thr.Values) = 1);
Check(CompareValue(thr.Values[0].Val, 0) = 0);
Check(thr.Values[0].UTime = EncodeDateTimeUTC(2014, 11, 09, 20, 30));
thr.ChannelIds.N_Src := 4;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresUnknown);
end;
procedure TMercury230ParserTest.Thread_LastArchAddr;
var s: string;
begin
gbv.ReqDetails.rqtp := rqtMercury230_LastArchAddr;
gbv.SetBufRec(Examples_LastArchAddr());
SetThreadIds();
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresSupport); // вспомогательный запрос не несет в себе данных
s := SQLReq_GetDevState(thr.ChannelIds.ID_Device, DEV_STATE_NAMES_LAST_ARCH_ADDR);
Check(StrToInt(s) = $FD20);
s := SQLReq_GetDevState(thr.ChannelIds.ID_Device, DEV_STATE_NAMES_LAST_ARCH_UDT);
Check(StrToInt(s) = int64(EncodedateTimeUTC(2014, 11, 15, 19, 00)));
end;
procedure TMercury230ParserTest.Thread_MeterInfo;
begin
gbv.ReqDetails.rqtp := rqtMercury230_MeterInfo;
gbv.SetBufRec(Examples_MeterInfo());
SetThreadIds();
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresSupport); // вспомогательный запрос не несет в себе данных
Check(SQLReq_GetDevState(thr.ChannelIds.ID_Device, DEV_STATE_NAMES_IMP_PER_KWT) = '1000');
end;
procedure TMercury230ParserTest.Thread_Readings;
begin
gbv.SetBufRec(Examples_Readings());
gbv.ReqDetails.rqtp := rqtMercury230_Currents;
SetThreadIds();
SQLReq_SetDevState(thr.ChannelIds.ID_Device, DEV_STATE_NAMES_IMP_PER_KWT, '1000'); // потом надо бы не корежить БД, а вынести в ...ForTest
thr.ChannelIds.N_Src := 1;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(thr.Values) = 1);
Check(CompareValue(thr.Values[0].Val, 48.505) = 0);
Check(thr.Values[0].UTime = gbv.gmTime);
thr.ChannelIds.N_Src := 2;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresUnknown);
thr.ChannelIds.N_Src := 3;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresData);
Check(Length(thr.Values) = 1);
Check(CompareValue(thr.Values[0].Val, 0.609) = 0);
Check(thr.Values[0].UTime = gbv.gmTime);
thr.ChannelIds.N_Src := 4;
Check(thr.RecognizeAndCheckChannel(gbv) = recchnresUnknown);
end;
initialization
RegisterTest('GMIOPSrv/Devices/Mercury230', TMercury230ParserTest.Suite);
end.
|
unit UFrmWorkerRight;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmBar, dxSkinsCore, dxSkinsdxBarPainter, dxSkinsDefaultPainters,
cxClasses, dxBar, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, ComCtrls, cxSplitter, cxListView, cxContainer,
cxTreeView, DB, DBClient, cxGraphics;
type
PNodeData = ^TNodeData;
TNodeData = record
State: Integer; // 0: 不选 1: 不确定 2: 选择
aDefault: Boolean;
ID: Integer;
end;
TFrmWorkerRight = class(TFrmBar)
tvWorkerRight: TcxTreeView;
lvWorkerClass: TcxListView;
CdsWorkerClass: TClientDataSet;
CdsWorkerRight: TClientDataSet;
BtnSave1: TdxBarButton;
procedure FormShow(Sender: TObject);
procedure tvWorkerRightDeletion(Sender: TObject; Node: TTreeNode);
procedure tvWorkerRightGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure tvWorkerRightGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure tvWorkerRightMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lvWorkerClassInfoTip(Sender: TObject; Item: TListItem;
var InfoTip: string);
procedure lvWorkerClassDeletion(Sender: TObject; Item: TListItem);
procedure lvWorkerClassSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure BtnSave1Click(Sender: TObject);
private
FModified: Boolean; // 记录权限树是否修改
FCurClassGuid: string; // 当前选中的角色Guid
FCurClassID: string; // 当前选中的角色ID
function QueryWorkerClassInfo: Boolean;
procedure DisplayWorkerClassInLv;
procedure InitRightTv;
procedure LoadAuthority(const AClassGuid: string);
procedure CheckToSave;
procedure SaveWorkerRight;
procedure UpdateParentState(PNode: TTreeNode);
function GetRightTvNode(const RightID: Integer): TTreeNode;
procedure SetChildState(Node: TTreeNode; State: Integer);
public
{ Public declarations }
end;
var
FrmWorkerRight: TFrmWorkerRight;
implementation
uses dxForms, UDBAccess, uDataRecord, UMsgBox, UPubFunLib, UDmImage;
{$R *.dfm}
const
RightSql = 'select * from RightInfo order by pid, serialid';
WorkerClassSQL = 'select * from WorkerClass';
WorkerRightSql = 'select * from WorkerRight where ClassGuid=''%s''';
function TFrmWorkerRight.QueryWorkerClassInfo: Boolean;
begin
Result := DBAccess.ReadDataSet(WorkerClassSQL, CdsWorkerClass);
end;
procedure TFrmWorkerRight.DisplayWorkerClassInLv;
var
lItem: TListItem;
lRec: TDataRecord;
begin
lvWorkerClass.Items.BeginUpdate;
try
lvWorkerClass.Clear;
CdsWorkerClass.First;
while not CdsWorkerClass.Eof do
begin
lItem := lvWorkerClass.Items.Add;
lItem.Caption := CdsWorkerClass.Fieldbyname('ClassName').AsString;
lItem.ImageIndex := 0;
lRec := TDataRecord.Create;
lRec.LoadFromDataSet(CdsWorkerClass);
lItem.Data := Pointer(lRec);
CdsWorkerClass.Next;
end;
finally
lvWorkerClass.Items.EndUpdate;
end;
end;
procedure TFrmWorkerRight.FormShow(Sender: TObject);
begin
inherited;
if QueryWorkerClassInfo then
DisplayWorkerClassInLv;
InitRightTv;
if lvWorkerClass.Items.Count > 0 then
lvWorkerClass.Items[0].Selected := True;
end;
procedure TFrmWorkerRight.lvWorkerClassDeletion(Sender: TObject;
Item: TListItem);
begin
if Assigned(Item.Data) then
begin
TDataRecord(Item.Data).Free;
Item.Data := nil;
end;
end;
procedure TFrmWorkerRight.lvWorkerClassInfoTip(Sender: TObject;
Item: TListItem; var InfoTip: string);
begin
if Assigned(Item.Data) then
InfoTip := TDataRecord(Item.Data).FieldValueAsString('Remark');
end;
procedure TFrmWorkerRight.lvWorkerClassSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var
lDataRecord: TDataRecord;
begin
tvWorkerRight.Enabled := False;
FCurClassGuid := '';
FCurClassID := '';
if Selected then
if Assigned(Item.Data) then
begin
lDataRecord := TDataRecord(Item.Data);
LoadAuthority(lDataRecord.FieldValueAsString('Guid'));
FCurClassID := lDataRecord.FieldValueAsString('ClassID');
if FCurClassID <> 'admin' then
tvWorkerRight.Enabled := True;
end;
end;
procedure TFrmWorkerRight.tvWorkerRightDeletion(Sender: TObject;
Node: TTreeNode);
begin
if Assigned(Node.Data) then
DisPose(PNodeData(Node.Data));
end;
procedure TFrmWorkerRight.tvWorkerRightGetImageIndex(Sender: TObject;
Node: TTreeNode);
begin
if Assigned(Node.Data) then
Node.ImageIndex := PNodeData(Node.Data)^.State;
end;
procedure TFrmWorkerRight.tvWorkerRightGetSelectedIndex(Sender: TObject;
Node: TTreeNode);
begin
Node.SelectedIndex := Node.ImageIndex;
end;
procedure TFrmWorkerRight.tvWorkerRightMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
ht: THitTests;
Node: TTreeNode;
NodeData: PNodeData;
begin
if not Assigned(lvWorkerClass.Selected) then
Exit;
ht := tvWorkerRight.GetHitTestInfoAt(X, Y);
Node := tvWorkerRight.GetNodeAt(X, Y);
if htOnIcon in ht then
begin
if Assigned(Node) then
begin
if Assigned(Node.Data) then
begin
NodeData := PNodeData(Node.Data);
Case NodeData^.State of
0:
NodeData^.State := 2;
1, 2:
NodeData^.State := 0;
end;
SetChildState(Node, NodeData^.State);
UpdateParentState(Node.Parent);
FModified := True;
end;
end;
end;
tvWorkerRight.Refresh;
end;
function TFrmWorkerRight.GetRightTvNode(const RightID: Integer): TTreeNode;
var
I: Integer;
NodeData: PNodeData;
begin
Result := nil;
for I := 0 to tvWorkerRight.Items.Count - 1 do
begin
NodeData := PNodeData(tvWorkerRight.Items[I].Data);
if NodeData <> nil then
begin
if NodeData.ID = RightID then
begin
Result := tvWorkerRight.Items[I];
Exit;
end;
end;
end;
end;
procedure TFrmWorkerRight.InitRightTv;
var
tmpCds: TClientDataSet;
PNode, NewNode: TTreeNode;
lPID: Integer;
NodeData: PNodeData;
begin
tmpCds := TClientDataSet.Create(nil);
try
if not DBAccess.ReadDataSet(RightSql, tmpCds) then
Exit;
tvWorkerRight.Items.BeginUpdate;
try
tvWorkerRight.Items.Clear;
tmpCds.First;
while not tmpCds.Eof do
begin
lPID := tmpCds.FindField('PID').AsInteger;
PNode := GetRightTvNode(lPID);
NewNode := tvWorkerRight.Items.AddChild(PNode,
tmpCds.FindField('RightName').AsString);
New(NodeData);
NodeData^.State := 0;
NodeData^.ID := tmpCds.FindField('ID').AsInteger;
NewNode.Data := NodeData;
tmpCds.Next;
end;
tvWorkerRight.FullExpand;
finally
tvWorkerRight.Items.EndUpdate;
end;
finally
tmpCds.Free;
end;
end;
procedure TFrmWorkerRight.SaveWorkerRight;
var
I: Integer;
NodeData: PNodeData;
tmpCds: TClientDataSet;
begin
if not FModified then Exit;
tmpCds := TClientDataSet.Create(nil);
try
if not DBAccess.ReadDataSet(Format(WorkerRightSql, [FCurClassGuid]), tmpCds) then
Exit;
for I := 0 to tvWorkerRight.Items.Count - 1 do
begin
if Assigned(tvWorkerRight.Items[I].Data) then
begin
NodeData := PNodeData(tvWorkerRight.Items[I].Data);
if NodeData.State = 0 then
begin
if tmpCds.Locate('RightID', NodeData^.ID, []) then
tmpCds.Delete;
end
else
begin
if tmpCds.Locate('RightID', NodeData^.ID, []) then
tmpCds.Edit
else
begin
tmpCds.Append;
tmpCds.Fieldbyname('Guid').AsString := CreateGuid;
end;
tmpCds.Fieldbyname('ClassGuid').AsString := Self.FCurClassGuid;
tmpCds.Fieldbyname('RightID').AsInteger := NodeData^.ID;
tmpCds.Post;
end;
end;
end;
if not DBAccess.ApplyUpdates('WorkerRight', tmpCds) then
begin
ShowMsg('角色权限保存失败!');
Exit;
end;
ShowMsg('角色权限保存成功!');
FModified := False;
finally
tmpCds.Free;
end;
end;
procedure TFrmWorkerRight.SetChildState(Node: TTreeNode; State: Integer);
var
I: Integer;
begin
for I := 0 to Node.Count - 1 do
begin
if Assigned(Node.Item[I].Data) then
PNodeData(Node.Item[I].Data)^.State := State;
if Node.HasChildren then
SetChildState(Node.Item[I], State);
end;
end;
procedure TFrmWorkerRight.UpdateParentState(PNode: TTreeNode);
var
I: Integer;
NodeData: PNodeData;
State: Integer;
begin
if not Assigned(PNode) then Exit;
State := -1;
for I := 0 to PNode.Count - 1 do
begin
if Assigned(PNode.Item[I].Data) then
begin
NodeData := PNodeData(PNode.Item[I].Data);
if State = -1 then
State := NodeData^.State
else
begin
if State <> NodeData^.State then
begin
State := 1;
Break;
end;
end;
end;
end;
if Assigned(PNode.Data) then
PNodeData(PNode.Data)^.State := State;
UpdateParentState(PNode.Parent);
end;
procedure TFrmWorkerRight.BtnSave1Click(Sender: TObject);
begin
inherited;
if lvWorkerClass.Selected = nil then
begin
ShowMsg('请先选择需要保存权限的角色!');
Exit;
end;
if FCurClassID = 'admin' then
begin
ShowMsg('“系统管理员”的权限不能修改!');
Exit;
end;
SaveWorkerRight;
end;
procedure TFrmWorkerRight.CheckToSave;
begin
if FModified then
if ShowConfirm('权限已经改变,是否保存?', '权限管理') then
SaveWorkerRight;
end;
procedure TFrmWorkerRight.LoadAuthority(const AClassGuid: string);
var
I: Integer;
NodeData: PNodeData;
begin
CheckToSave;
FCurClassGuid := AClassGuid;
DBAccess.ReadDataSet(Format(WorkerRightSql, [AClassGuid]), CdsWorkerRight);
tvWorkerRight.Items.BeginUpdate;
try
for I := 0 to tvWorkerRight.Items.Count - 1 do
begin
if Assigned(tvWorkerRight.Items[I].Data) then
begin
NodeData := PNodeData(tvWorkerRight.Items[I].Data);
if CdsWorkerRight.Locate('RightID', NodeData^.ID, []) then
NodeData^.State := 2
else
NodeData^.State := 0;
UpdateParentState(tvWorkerRight.Items[I].Parent);
end;
end;
FModified := False;
finally
tvWorkerRight.Items.EndUpdate;
end;
end;
initialization
dxFormManager.RegisterForm(TFrmWorkerRight);
end.
|
unit cPagamento;
interface
uses
SysUtils;
type
Pagamento = class (TObject)
protected
codPag : integer;
valPag : real;
statusPag : string;
dataPag : TDateTime;
tipoPag : string;
public
Constructor Create(codPag:integer; valPag : real; statusPag : string; dataPag : TDateTime; tipoPag : string);
Procedure setcodPag(codPag:integer);
Procedure setvalpag(valPag:real);
Procedure setstatusPag(statusPag:string);
Procedure setdataPag(dataPag:TDateTime);
Procedure setTipoPag(tipoPag : string);
Function getcodPag:integer;
Function getvalpag:real;
Function getstatusPag:string;
Function getdataPag:TDateTime;
Function getTipoPag:string;
end;
implementation
Constructor Pagamento.Create(codPag : integer; valPag : real; statusPag : string; dataPag : TDateTime; tipoPag:string);
begin
self.codPag := codPag;
self.valPag := valPag;
self.statusPag := statusPag;
self.dataPag := dataPag;
self.tipoPag := tipoPag;
end;
Procedure Pagamento.setcodPag(codPag:integer);
begin
self.codPag := codPag;
end;
Function Pagamento.getcodPag:integer;
begin
result := codPag;
end;
Procedure Pagamento.setvalpag(valPag:real);
begin
self.valPag := valPag;
end;
Function Pagamento.getvalpag:real;
begin
result := valPag;
end;
Procedure Pagamento.setstatusPag(statusPag:string);
begin
self.statusPag := statusPag;
end;
Function Pagamento.getstatusPag:string;
begin
result := statusPag;
end;
Procedure Pagamento.setdataPag(dataPag:TDateTime);
begin
self.dataPag := dataPag;
end;
Function Pagamento.getdataPag:TDateTime;
begin
result := dataPag;
end;
Procedure Pagamento.setTipoPag(tipopag:string);
begin
self.tipoPag := tipopag;
end;
Function Pagamento.getTipoPag:string;
begin
result := tipopag;
end;
end.
|
unit mopmaterial;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, complexes, moptype, math;
type
{ TNKPoint }
TNKPoint = class
public
eps: complex; // квадрат показателя преломления
wln: real; // волны
constructor Create;
end;
TNKPoints = specialize TFPGList<TNKPoint>;
{ TMOPMaterial }
TMOPMaterial = class // матриал
public
MaterialName: string;
Comment: string;
Points: TNKPoints;
constructor Create;
destructor Destroy; override;
end;
TMOPMaterialArray = specialize TFPGList<TMOPMaterial>;
{ TMOPMaterials }
TMOPMaterials = class (TMOPMaterialArray)
private
function EpsToWave(Material: Integer; Wvlng: real): Complex;
public
function FindByName(MaterialName: string): integer;
function MinRange(Materials: TIntegerPoints): real;
function MaxRange(Materials: TIntegerPoints): real;
function GetEpsToWave(Materials: TIntegerPoints; WaveLength: real): TComplexPoints;
end;
implementation
{ TMOPMaterials }
function TMOPMaterials.EpsToWave(Material: Integer; Wvlng: real): Complex;
var j: integer;
part: real;
begin
for j:=0 to Items[Material].Points.Count - 2 do
if (Wvlng >= Items[Material].Points.Items[j].wln) and
(Wvlng <= Items[Material].Points.Items[j+1].wln) then
begin
part:=(Wvlng - Items[Material].Points.Items[j].wln)/
(Items[Material].Points.Items[j+1].wln -
Items[Material].Points.Items[j].wln);
result:=Items[Material].Points.Items[j].eps +
part*(Items[Material].Points.Items[j+1].eps -
Items[Material].Points.Items[j].eps);
break;
end;
end;
function TMOPMaterials.FindByName(MaterialName: string): integer;
var j: integer;
begin
Result:=-1;
for j:=0 to Count-1 do
if Items[j].MaterialName = MaterialName then
begin
Result:=j;
Break;
end;
end;
function TMOPMaterials.MinRange(Materials: TIntegerPoints): real;
var j: integer;
begin
Result:=-1;
for j:=0 to Materials.Count-1 do
if j = 0 then
Result:= Items[Materials.Items[j]].Points.Items[0].wln
else
Result:= Min(Result,Items[Materials.Items[j]].Points.Items[0].wln);
end;
function TMOPMaterials.MaxRange(Materials: TIntegerPoints): real;
var j: integer;
begin
Result:=-1;
for j:=0 to Materials.Count-1 do
if j = 0 then
Result:= Items[Materials.Items[j]].Points.Items[0].wln
else
Result:= Max(Result,Items[Materials.Items[j]].Points.Items[0].wln);
end;
function TMOPMaterials.GetEpsToWave(Materials: TIntegerPoints; WaveLength: real
): TComplexPoints;
var j: integer;
begin
Result:=TComplexPoints.Create;
for j:=0 to Materials.Count-1 do
Result.Add( EpsToWave(Materials.Items[j],WaveLength) );
end;
{ TNKPoint }
constructor TNKPoint.Create;
begin
eps:=0;
wln:=0;
end;
{ TMOPMaterial }
constructor TMOPMaterial.Create;
begin
MaterialName:='';
Comment:='';
Points:=TNKPoints.Create;
end;
destructor TMOPMaterial.Destroy;
begin
Points.Free;
inherited Destroy;
end;
end.
|
unit CSCTimerList;
{$B-} {Complete Boolean Evaluation}
{$I+} {Input/Output-Checking}
{$P+} {Open Parameters}
{$T-} {Typed @ Operator}
{$W-} {Windows Stack Frame}
{$X+} {Extended Syntax}
interface
uses
Windows,
Classes,
Forms,
Messages,
SysUtils,
CSCTimer;
type
TTriggerEvent =
procedure(Sender : TObject; Handle : Integer) of object;
PEventRec = ^TEventRec;
TEventRec = packed record {!!.05}
erHandle : Integer;
erOnTrigger : TTriggerEvent;
erRecurring : Boolean;
erTimer : TCSCTimer;
erInterval : Integer;
end;
TCSCTimerList = class(TComponent)
protected
FOnAllTriggers : TTriggerEvent;
{internal variables}
FList : TList; {list of event TEventRec records}
FHandle : hWnd; {our window handle}
FInterval : Cardinal; {the actual Window's timer interval}
{internal methods}
procedure CalcNewInterval;
{-calculates the needed interval for the window's timer}
function EventIndex(Handle : Integer) : Integer;
{-returns the internal list index corresponding to the trigger handle}
procedure SortTriggers;
{-sorts the internal list of timer trigger event records}
procedure TimerWndProc(var Msg : TMessage);
{-window procedure to catch timer messages}
procedure UpdateTimer;
{-re-create the windows timer with a new timer interval}
procedure RemoveER(ER: PEventRec);
protected
procedure DoTriggerNotification;
virtual;
{-conditionally sends notification of all events}
function GetTimersCount: Integer;
function CreateTriggerHandle: Integer;
public
constructor Create(AOwner: TComponent);
override;
destructor Destroy;
override;
function AddTimer(OnTrigger : TTriggerEvent; Interval : Cardinal) : Integer;
procedure Remove(Handle : Integer);
procedure RemoveAll;
{public properties}
property Count : Integer
read GetTimersCount;
published
end;
implementation
const
DefMinInterval = 55; {smallest timer interval allowed}
DefHalfMinInterval = DefMinInterval div 2;
{*** internal routines ***}
function NewEventRec : PEventRec;
begin
GetMem(Result, SizeOf(TEventRec));
FillChar(Result^, SizeOf(TEventRec), #0);
end;
procedure FreeEventRec(ER : PEventRec);
begin
if (ER <> nil) then
FreeMem(ER, SizeOf(TEventRec));
end;
{*** TCSCTimerList ***}
constructor TCSCTimerList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{create internal list for trigger event records}
FList := TList.Create;
{allocate a window handle for the timer}
FHandle := AllocateHWnd(TimerWndProc);
end;
destructor TCSCTimerList.Destroy;
var
I : Integer;
begin
{force windows timer to be destroyed}
FInterval := 0;
UpdateTimer;
{free contents of list}
for I := 0 to FList.Count-1 do
FreeEventRec(FList[I]);
{destroy the internal list}
FList.Free;
FList := nil;
{deallocate our window handle}
DeallocateHWnd(FHandle);
inherited Destroy;
end;
function TCSCTimerList.AddTimer(OnTrigger : TTriggerEvent; Interval : Cardinal) : Integer;
var
ER : PEventRec;
begin
Result := -1; {assume error}
{create new event record}
ER := NewEventRec;
if (ER = nil) then
Exit;
{force interval to be at least the minimum}
if Interval < DefMinInterval then
Interval := DefMinInterval;
{fill event record}
with ER^ do begin
CSCTimer.SetTimer(erTimer, Interval);
erInterval := Interval;
erOnTrigger := OnTrigger;
erRecurring := False;
end;
ER^.erHandle := CreateTriggerHandle;
FList.Add(ER);
{return the trigger event handle}
Result := ER^.erHandle;
{calculate new interval for the windows timer}
CalcNewInterval;
SortTriggers;
UpdateTimer;
end;
procedure TCSCTimerList.DoTriggerNotification;
var
ER : PEventRec;
I : Integer;
begin
I := 0;
while I < FList.Count do begin
ER := PEventRec(FList[I]);
if HasTimerExpired(ER^.erTimer) then begin
try
if Assigned(ER^.erOnTrigger) then
ER^.erOnTrigger(Self, ER^.erHandle);
finally
RemoveER(ER);
end;
end else
Inc(I);
end;
end;
function TCSCTimerList.GetTimersCount : Integer;
{-returns the number of maintained timer triggers}
begin
Result := FList.Count;
end;
procedure TCSCTimerList.RemoveER(ER: PEventRec);
begin
FList.Remove(ER);
FreeEventRec(ER);
CalcNewInterval;
UpdateTimer;
end;
procedure TCSCTimerList.Remove(Handle : Integer);
var I : Integer;
begin
I := EventIndex(Handle);
if (I > -1) and (I < Count) then
RemoveER(PEventRec(FList[I]));
end;
procedure TCSCTimerList.RemoveAll;
begin
while Count > 0 do RemoveER(PEventRec(FList[0]));
FInterval := 0;
UpdateTimer;
end;
procedure TCSCTimerList.CalcNewInterval;
{-calculates the needed interval for the window's timer}
var
I : Integer;
TTE : Integer;
N, V : LongInt;
ER : PEventRec;
TC : LongInt;
Done : Boolean;
begin
{find shortest trigger interval}
TC := GetTickCount;
FInterval := High(Cardinal);
for I := 0 to FList.Count-1 do begin
ER := PEventRec(FList[I]);
TTE := TimeToExpireTC(ER^.erTimer, TC);
if (TTE < FInterval) then
FInterval := TTE;
end;
{limit to smallest allowable interval}
if FInterval < DefMinInterval then
FInterval := DefMinInterval;
if FInterval = High(Cardinal) then
FInterval := 0
else begin
{find interval that evenly divides into all trigger intervals}
V := FInterval; {use LongInt so it is possible for it to become (-)}
repeat
Done := True;
for I := 0 to FList.Count-1 do begin
N := PEventRec(FList[I])^.erInterval;
if (N mod V) <> 0 then begin
Dec(V, N mod V);
Done := False;
Break;
end;
end;
until Done or (V <= DefMinInterval);
{limit to smallest allowable interval}
if V < DefMinInterval then
V := DefMinInterval;
FInterval := V;
end;
end;
function TCSCTimerList.CreateTriggerHandle : Integer;
var
I : Integer;
H : Integer;
begin
Result := 0;
for I := 0 to FList.Count-1 do begin
H := PEventRec(FList[I])^.erHandle;
if H >= Result then
Result := H + 1;
end;
end;
function TCSCTimerList.EventIndex(Handle : Integer) : Integer;
{-returns the internal list index corresponding to Handle}
var
I : Integer;
begin
Result := -1;
for I := 0 to FList.Count-1 do
if PEventRec(FList[I])^.erHandle = Handle then begin
Result := I;
Break;
end;
end;
procedure TCSCTimerList.SortTriggers;
{-sorts the internal list of timer trigger event records}
var
I : Integer;
Done : Boolean;
begin
repeat
Done := True;
for I := 0 to FList.Count-2 do begin
if (PEventRec(FList[I])^.erInterval >
PEventRec(FList[I+1])^.erInterval) then begin
FList.Exchange(I, I+1);
Done := False;
end;
end;
until Done;
end;
procedure TCSCTimerList.TimerWndProc(var Msg : TMessage);
{-window procedure to catch timer messages}
begin
with Msg do
if Msg = WM_TIMER then
try
DoTriggerNotification;
except
Application.HandleException(Self);
end
else
Result := DefWindowProc(FHandle, Msg, wParam, lParam);
end;
procedure TCSCTimerList.UpdateTimer;
begin
KillTimer(FHandle, 1);
if (FInterval <> 0) then
Windows.SetTimer(FHandle, 1, FInterval, nil);
end;
end.
|
unit AverageLogger.Write;
interface
uses AverageLogger;
type
TAverageWriteLogger = class(TAverageLogger)
protected
function GetUnit: Double; override;
end;
implementation
function TAverageWriteLogger.GetUnit: Double;
begin
result := 0.064;
end;
end.
|
{$A-,B-,E-,F-,G+,I-,N-,O-,P-,Q-,R-,S-,T-,V-,X-}
{$D-,L-,Y-}
const
screen : word = $a000;
var
what : pointer;
x,y,i : integer;
j,k : integer;
{----------------------------- Procedures --------------------------------}
{--------------------------
Wait for a key
------------------------}
procedure wait_key; assembler;
asm
@wai: mov dl,0ffh {-- Read keyboard }
mov ah,06 {-- using func 06 Int 21 }
int 21h
or al,al
jz @wai
end;
{--------------------------
read for a key
------------------------}
function read_key : byte; assembler;
asm
mov dl,0ffh {-- Read keyboard }
mov ah,06 {-- using func 06 Int 21 }
int 21h
end;
{-------------------------------
Wait for the vertical retrace
--------------------------------}
procedure vwait; assembler;
asm
mov dx,03DAh { status register }
mov ah,8
@w_wait: in al,dx
test al,ah
jz @w_wait
end;
{------------------------
Select graphics mode
-------------------------}
procedure mode(num:integer); assembler;
asm
mov ax,num
int 10h
end;
{--------------------------
Change the color palette
---------------------------}
procedure palette(color,red,green,blue:integer); assembler;
asm
mov dx,03C8h
mov ax,color
out dx,al
inc dx
mov ax,red
out dx,al
mov ax,green
out dx,al
mov ax,blue
out dx,al
end;
{---------------------
Get a 10x10 block
---------------------}
procedure get10(x,y:word;image:pointer); assembler;
asm
mov bx,320
mov ax,y {-- calculate SI screen position }
mul bx {-- DS:SI = scren source }
mov si,ax
add si,x
les di,image {-- ES:DI = sprite (dest.) }
push ds
mov ds,screen {-- DS:SI = screen (source) }
mov ax,314 {-- vertical adder }
{6} movsw; movsw; movsw; add si,ax
{7} movsw; movsw; movsw; add si,ax
{8} movsw; movsw; movsw; add si,ax
{9} movsw; movsw; movsw; add si,ax
{10} movsw; movsw; movsw
pop ds
end;
{---------------------
Puts a 10x10 block
---------------------}
procedure put10(x,y:word; image:pointer); assembler;
asm
mov es,screen {-- ES:DI = screen }
mov bx,320
mov ax,y {-- calculate DI screen position }
mul bx
mov di,ax
add di,x
push ds
lds si,image
mov ax,314 {-- vertical adder }
{1} movsw; movsw; movsw; add di,ax
{2} movsw; movsw; movsw; add di,ax
{3} movsw; movsw; movsw; add di,ax
{4} movsw; movsw; movsw; add di,ax
{5} movsw; movsw; movsw
pop ds
end;
{-------------------------------------------------------------------------
read_pcx(where:pointer; palette:word) || Reads a PCX graphic
-------------------------------------------------------------------------
where : Address of buffer where the PCX file is located. In C++ it would
be "char far *where". There is a Pascal command to read buffers
BlockRead. Or, you can use BINOBJ.EXE to convert a .PCX file to
a .OBJ file. The file MUST be 320x200 and it must not exceed 64K.
(If it is >64K you are an idiot because the screen uses 60K...)
palette: If it is zero, the palette won't be displayed.
--------------------------------------------------------------------------}
procedure read_pcx(where:pointer; palette:word); assembler;
asm
push ds
mov es,screen {-- es:di = screen }
xor di,di
lds si,where {-- ds:si = graph }
mov bx,64000 { constants }
mov dl,0c0h
mov dh,03fh
add si,128 { skip header }
@pcx: lodsb { get color or run-length }
mov ah,al
and ah,dl
cmp ah,dl { $C0 }
jne @norle
and al,dh { $3f }
xor ch,ch
mov cl,al { CL=run length }
lodsb { Get color }
mov ah,al
shr cx,1 { cx/2, we'll draw in words }
rep stosw { -- store all words }
adc cx,cx { -- Add carry (1 if cx was odd) }
rep stosb { -- store a byte IF present }
cmp di,bx { Got past end?? }
jb @pcx
jmp @bye
@norle: stosb { Store one pixel }
cmp di,bx
jbe @pcx
@bye: mov bx,ds
pop ds
mov ax,palette
or ax,ax
jz @byebye
push ds
mov ds,bx
xor cl,cl
mov dx,03C8h
@coloriz: mov al,cl
out dx,al
inc dx
lodsb
shr al,2
out dx,al
lodsb
shr al,2
out dx,al
lodsb
shr al,2
out dx,al
dec dx
inc cl
jnz @coloriz
pop ds
@byebye:
end;
procedure shak2; external; {$L c:\mmedia\graph\shak2.obj}
begin
getmem(what,16384);
mode($13);
for x:=0 to 255 do
palette(x,0,0,0);
read_pcx(@shak2,0);
for y:=0 to 63 do
begin
vwait;
for x:=0 to 255 do
if (y shl 2)<x then palette(x,y,y,y);
end;
wait_key;
{ repeat
x:=random(309);
y:=random(189);
get10(x,y,what);
put10(x,y+1,what);
x:=random(309);
y:=random(189);
get10(x,y,what);
put10(x+1,y,what);
x:=random(309)+2;
y:=random(189)+2;
get10(x,y,what);
put10(x,y-1,what);
x:=random(309)+2;
y:=random(189)+2;
get10(x,y,what);
put10(x-1,y,what);
until (read_key<>0); }
for y:=63 downto 0 do
begin
vwait;
for x:=0 to 255 do
if (y shl 2)<x then palette(x,y,y,y);
end;
mode($3);
freemem(what,16384);
end. |
unit UnCaixaMenuView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
{ Fluente }
DataUtil, UnModelo, UnCaixaModelo, Componentes, UnAplicacao, CaixaAplicacao,
JvExControls, JvButton, JvTransparentButton;
type
TCaixaMenuView = class(TForm, ITela)
pnlDesktop: TPanel;
btnAbertura: TPanel;
btnTroco: TPanel;
btnSaida: TPanel;
btnSuprimento: TPanel;
btnSangria: TPanel;
btnFechamento: TPanel;
pnlTitle: TPanel;
btnFechar: TJvTransparentButton;
btnExtrato: TPanel;
procedure btnAberturaClick(Sender: TObject);
procedure btnTrocoClick(Sender: TObject);
procedure btnSaidaClick(Sender: TObject);
procedure btnSuprimentoClick(Sender: TObject);
procedure btnSangriaClick(Sender: TObject);
procedure btnFechamentoClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure btnExtratoClick(Sender: TObject);
private
FCaixaModelo: TCaixaModelo;
FControlador: IResposta;
public
function Controlador(const Controlador: IResposta): ITela;
function Descarregar: ITela;
function ExibirTela: Integer;
function ExecutarAcao(const Acao: AcaoDeRegistro;
const Modelo: TModelo): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
end;
implementation
{$R *.dfm}
uses Util;
{ TCaixaMenuView }
function TCaixaMenuView.Controlador(const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TCaixaMenuView.Descarregar: ITela;
begin
Self.FCaixaModelo := nil;
Self.FControlador := nil;
Result := Self;
end;
function TCaixaMenuView.ExecutarAcao(const Acao: AcaoDeRegistro;
const Modelo: TModelo): ITela;
begin
Result := Self;
end;
function TCaixaMenuView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TCaixaMenuView.Modelo(const Modelo: TModelo): ITela;
begin
Self.FCaixaModelo := (Modelo as TCaixaModelo);
Result := Self;
end;
function TCaixaMenuView.Preparar: ITela;
begin
Result := Self;
end;
procedure TCaixaMenuView.btnAberturaClick(Sender: TObject);
var
_parametros: TMap;
_chamada: TChamada;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcAbertura));
_chamada := TChamada.Create
.Parametros(_parametros);
try
Self.FControlador.Responder(_chamada);
finally
FreeAndNil(_chamada);
end;
end;
procedure TCaixaMenuView.btnTrocoClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcTroco));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TCaixaMenuView.btnSaidaClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcSaida));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TCaixaMenuView.btnSuprimentoClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcSuprimento));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TCaixaMenuView.btnSangriaClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcSangria));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TCaixaMenuView.btnFechamentoClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcFechamento));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TCaixaMenuView.btnFecharClick(Sender: TObject);
begin
Self.Close;
end;
procedure TCaixaMenuView.btnExtratoClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FCaixaModelo.Parametros
.Gravar('operacao', Ord(odcExtrato));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
end.
|
unit fPtSel;
{ Allows patient selection using various pt lists. Allows display & processing of alerts. }
{$OPTIMIZATION OFF} // REMOVE AFTER UNIT IS DEBUGGED
{$define VAA}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ORCtrls,
ExtCtrls,
ORFn,
ORNet,
ORDtTmRng,
Gauges,
Menus,
ComCtrls,
CommCtrl,
fBase508Form,
VA508AccessibilityManager,
uConst,
System.UITypes,
uInfoBoxWithBtnControls,
ClipBrd,
DateUtils;
type
TfrmPtSel = class(TfrmBase508Form)
pnlPtSel: TORAutoPanel;
cboPatient: TORComboBox;
lblPatient: TLabel;
cmdOK: TButton;
cmdCancel: TButton;
pnlNotifications: TORAutoPanel;
cmdProcessInfo: TButton;
cmdProcessAll: TButton;
cmdProcess: TButton;
cmdForward: TButton;
sptVert: TSplitter;
cmdSaveList: TButton;
pnlDivide: TORAutoPanel;
lblNotifications: TLabel;
ggeInfo: TGauge;
cmdRemove: TButton;
popNotifications: TPopupMenu;
mnuProcess: TMenuItem;
mnuRemove: TMenuItem;
mnuForward: TMenuItem;
lstvAlerts: TCaptionListView;
N1: TMenuItem;
cmdComments: TButton;
txtCmdComments: TVA508StaticText;
txtCmdRemove: TVA508StaticText;
txtCmdForward: TVA508StaticText;
txtCmdProcess: TVA508StaticText;
lblPtDemo: TLabel;
cmdDefer: TButton;
txtCmdDefer: TVA508StaticText;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cboPatientChange(Sender: TObject);
procedure cboPatientKeyPause(Sender: TObject);
procedure cboPatientMouseClick(Sender: TObject);
procedure cboPatientEnter(Sender: TObject);
procedure cboPatientExit(Sender: TObject);
procedure cboPatientNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cboPatientDblClick(Sender: TObject);
procedure cmdProcessClick(Sender: TObject);
procedure cmdSaveListClick(Sender: TObject);
procedure cmdProcessInfoClick(Sender: TObject);
procedure cmdProcessAllClick(Sender: TObject);
procedure lstvAlertsDblClick(Sender: TObject);
procedure cmdForwardClick(Sender: TObject);
procedure cmdRemoveClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure pnlPtSelResize(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cboPatientKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstvAlertsColumnClick(Sender: TObject; Column: TListColumn);
function DupLastSSN(const DFN: string): Boolean;
procedure lstFlagsClick(Sender: TObject);
procedure lstFlagsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstvAlertsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure ShowButts(ShowButts: Boolean);
procedure lstvAlertsInfoTip(Sender: TObject; Item: TListItem;
var InfoTip: string);
procedure lstvAlertsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure cmdCommentsClick(Sender: TObject);
procedure lstvAlertsMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cboPatientKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cmdDeferClick(Sender: TObject);
procedure lstvAlertsData(Sender: TObject; Item: TListItem);
procedure lstvAlertsDataStateChange(Sender: TObject; StartIndex,
EndIndex: Integer; OldState, NewState: TItemStates);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
FsortCol: Integer;
FsortAscending: Boolean;
FLastPt: string;
FsortDirection: string;
FUserCancelled: Boolean;
FOKClicked: Boolean;
FExpectedClose: Boolean;
FNotificationBtnsAdjusted: Boolean;
FAlertsNotReady: Boolean;
FMouseUpPos: TPoint;
FAlertData: TStringList;
procedure WMReadyAlert(var Message: TMessage); message UM_MISC;
procedure ReadyAlert;
procedure AdjustFormSize(ShowNotif: Boolean; FontSize: Integer);
procedure ClearIDInfo;
procedure ShowIDInfo;
procedure ShowFlagInfo;
procedure SetCaptionTop;
procedure SetPtListTop(IEN: Int64);
procedure RPLDisplay;
procedure AlertList;
// procedure ReformatAlertDateTime;
procedure AdjustButtonSize(pButton: TButton);
procedure AdjustNotificationButtons;
procedure SetupDemographicsForm;
procedure SetupDemographicsLabel;
procedure ShowDisabledButtonTexts;
public
procedure Loaded; override;
end;
procedure SelectPatient(ShowNotif: Boolean; FontSize: Integer; var UserCancelled: Boolean);
var
frmPtSel: TfrmPtSel;
FDfltSrc, FDfltSrcType: string;
IsRPL, RPLJob, DupDFN: string; // RPLJob stores server $J job number of RPL pt. list.
RPLProblem: Boolean; // Allows close of form if there's an RPL problem.
PtStrs: TStringList;
implementation
{$R *.DFM}
uses
rCore,
uCore,
fDupPts,
fPtSens,
fPtSelDemog,
fPtSelOptns,
fPatientFlagMulti,
uOrPtf,
fAlertForward,
rMisc,
fFrame,
fRptBox,
VA508AccessibilityRouter,
VAUtils,
System.Types,
fDeferDialog,
fNotificationProcessor;
const
LAST_DISPLAYED_PIECE = 11;
SORT_DATE_PIECE = 12;
ITEM_STATE_PIECE = 13;
const
AliasString = ' -- ALIAS';
SortDirection: array[boolean] of tSortDir = (DIR_BKWRD, DIR_FRWRD);
procedure SelectPatient(ShowNotif: Boolean; FontSize: Integer; var UserCancelled: Boolean);
{ displays patient selection dialog (with optional notifications), updates Patient object }
var
frmPtSel: TfrmPtSel;
begin
frmPtSel := TfrmPtSel.Create(Application);
RPLProblem := False;
try
with frmPtSel do
begin
AdjustFormSize(ShowNotif, FontSize); // Set initial form size
FDfltSrc := DfltPtList;
FDfltSrcType := Piece(FDfltSrc, U, 2);
FDfltSrc := Piece(FDfltSrc, U, 1);
if (IsRPL = '1') then // Deal with restricted patient list users.
FDfltSrc := '';
frmPtSelOptns.SetDefaultPtList(FDfltSrc);
if RPLProblem then
begin
frmPtSel.Release;
Exit;
end;
Notifications.Clear;
FsortCol := -1;
AlertList;
ClearIDInfo;
if (IsRPL = '1') then // Deal with restricted patient list users.
RPLDisplay; // Removes unnecessary components from view.
FUserCancelled := False;
ShowModal;
UserCancelled := FUserCancelled;
end;
finally
frmPtSel.Release;
end;
end;
procedure TfrmPtSel.AdjustFormSize(ShowNotif: Boolean; FontSize: Integer);
{ Adjusts the initial size of the form based on the font used & if notifications should show. }
var
Rect: TRect;
SplitterTop, t1, t2, t3: Integer;
begin
SetFormPosition(self);
ResizeAnchoredFormToFont(self);
if ShowNotif then
begin
pnlDivide.Visible := True;
lstvAlerts.Visible := True;
pnlNotifications.Visible := True;
pnlPtSel.BevelOuter := bvRaised;
end
else
begin
pnlDivide.Visible := False;
lstvAlerts.Visible := False;
pnlNotifications.Visible := False;
end;
// SetFormPosition(self);
Rect := BoundsRect;
ForceInsideWorkArea(Rect);
BoundsRect := Rect;
if frmFrame.EnduringPtSelSplitterPos <> 0 then
SplitterTop := frmFrame.EnduringPtSelSplitterPos
else
SetUserBounds2(Name + '.' + sptVert.Name, SplitterTop, t1, t2, t3);
if SplitterTop <> 0 then
pnlPtSel.Height := SplitterTop;
FNotificationBtnsAdjusted := False;
AdjustButtonSize(cmdSaveList);
AdjustButtonSize(cmdProcessInfo);
AdjustButtonSize(cmdProcessAll);
AdjustButtonSize(cmdProcess);
AdjustButtonSize(cmdForward);
AdjustButtonSize(cmdRemove);
AdjustButtonSize(cmdComments);
AdjustButtonSize(cmdDefer); // DRP
AdjustNotificationButtons;
end;
procedure TfrmPtSel.SetCaptionTop;
{ Show patient list name, set top list to 'Select ...' if appropriate. }
var
X: string;
begin
X := '';
lblPatient.Caption := 'Patients';
if (not User.IsReportsOnly) then
begin
case frmPtSelOptns.SrcType of
TAG_SRC_DFLT:
lblPatient.Caption := 'Patients (' + FDfltSrc + ')';
TAG_SRC_PROV:
X := 'Provider';
TAG_SRC_TEAM:
X := 'Team';
TAG_SRC_SPEC:
X := 'Specialty';
TAG_SRC_CLIN:
X := 'Clinic';
TAG_SRC_WARD:
X := 'Ward';
TAG_SRC_PCMM:
X := 'PCMM Team'; // TDP - Added 5/27/2014 to handle PCMM team addition
TAG_SRC_ALL: { Nothing }
;
end; // case stmt
end; // begin
if Length(X) > 0 then
with cboPatient do
begin
RedrawSuspend(Handle);
ClearIDInfo;
ClearTop;
Text := '';
Items.Add('^Select a ' + X + '...');
Items.Add(LLS_LINE);
Items.Add(LLS_SPACE);
cboPatient.InitLongList('');
RedrawActivate(cboPatient.Handle);
end;
end;
{ List Source events: }
procedure TfrmPtSel.SetPtListTop(IEN: Int64);
{ Sets top items in patient list according to list source type and optional list source IEN. }
var
NewTopList, updateDate: string;
FirstDate, LastDate: string;
begin
// NOTE: Some pieces in RPC returned arrays are rearranged by ListPtByDflt call in rCore!
IsRPL := User.IsRPL;
if (IsRPL = '') then // First piece in ^VA(200,.101) should always be set (to 1 or 0).
begin
InfoBox('Patient selection list flag not set.', 'Incomplete User Information', MB_OK);
RPLProblem := True;
Exit;
end;
// FirstDate := 0; LastDate := 0; // Not req'd, but eliminates hint.
// Assign list box TabPosition, Pieces properties according to type of list to be displayed.
// (Always use Piece "2" as the first in the list to assure display of patient's name.)
cboPatient.pieces := '2,3'; // This line and next: defaults set - exceptions modifield next.
cboPatient.tabPositions := '20,28';
if ((frmPtSelOptns.SrcType = TAG_SRC_DFLT) and (FDfltSrc = 'Combination')) then
begin
cboPatient.pieces := '2,3,4,5,9';
cboPatient.tabPositions := '20,28,35,45';
end;
if ((frmPtSelOptns.SrcType = TAG_SRC_DFLT) and
(FDfltSrcType = 'Ward')) or (frmPtSelOptns.SrcType = TAG_SRC_WARD) then
cboPatient.tabPositions := '35';
if ((frmPtSelOptns.SrcType = TAG_SRC_DFLT) and
(AnsiStrPos(pChar(FDfltSrcType), 'Clinic') <> nil)) or (frmPtSelOptns.SrcType = TAG_SRC_CLIN) then
begin
cboPatient.pieces := '2,3,9';
cboPatient.tabPositions := '24,45';
end;
NewTopList := IntToStr(frmPtSelOptns.SrcType) + U + IntToStr(IEN); // Default setting.
if (frmPtSelOptns.SrcType = TAG_SRC_CLIN) then
with frmPtSelOptns.cboDateRange do
begin
if ItemID = '' then
Exit; // Need both clinic & date range.
FirstDate := Piece(ItemID, ';', 1);
LastDate := Piece(ItemID, ';', 2);
NewTopList := IntToStr(frmPtSelOptns.SrcType) + U + IntToStr(IEN) + U + ItemID; // Modified for clinics.
end;
if NewTopList = frmPtSelOptns.LastTopList then
Exit; // Only continue if new top list.
frmPtSelOptns.LastTopList := NewTopList;
RedrawSuspend(cboPatient.Handle);
ClearIDInfo;
cboPatient.ClearTop;
cboPatient.Text := '';
if (IsRPL = '1') then // Deal with restricted patient list users.
begin
RPLJob := MakeRPLPtList(User.RPLList); // MakeRPLPtList is in rCore, writes global "B" x-ref list.
if (RPLJob = '') then
begin
InfoBox('Assignment of valid OE/RR Team List Needed.', 'Unable to build Patient List', MB_OK);
RPLProblem := True;
Exit;
end;
end
else
begin
case frmPtSelOptns.SrcType of
TAG_SRC_DFLT:
ListPtByDflt(cboPatient.Items);
TAG_SRC_PROV:
ListPtByProvider(cboPatient.Items, IEN);
TAG_SRC_TEAM:
ListPtByTeam(cboPatient.Items, IEN);
TAG_SRC_SPEC:
ListPtBySpecialty(cboPatient.Items, IEN);
TAG_SRC_CLIN:
ListPtByClinic(cboPatient.Items, frmPtSelOptns.cboList.ItemIEN, FirstDate, LastDate);
TAG_SRC_WARD:
ListPtByWard(cboPatient.Items, IEN);
// TDP - Added 5/27/2014 to handle PCMM team addition
TAG_SRC_PCMM:
ListPtByPcmmTeam(cboPatient.Items, IEN);
TAG_SRC_ALL:
ListPtTop(cboPatient.Items);
end;
end;
with frmPtSelOptns.cboList do
begin
if Visible then
begin
updateDate := '';
if (frmPtSelOptns.SrcType <> TAG_SRC_PROV) and
(Piece(Items[ItemIndex], U, 3) <> '') then
updateDate := ' last updated on ' + Piece(Items[ItemIndex], U, 3);
lblPatient.Caption := 'Patients (' + Text + updateDate + ')';
end;
end;
if frmPtSelOptns.SrcType = TAG_SRC_ALL then
lblPatient.Caption := 'Patients (All Patients)';
with cboPatient do
if ShortCount > 0 then
begin
Items.Add(LLS_LINE);
Items.Add(LLS_SPACE);
end;
cboPatient.Caption := lblPatient.Caption;
cboPatient.InitLongList('');
RedrawActivate(cboPatient.Handle);
end;
{ Patient Select events: }
procedure TfrmPtSel.cboPatientEnter(Sender: TObject);
begin
cmdOK.Default := True;
if cboPatient.ItemIndex >= 0 then
begin
ShowIDInfo;
ShowFlagInfo;
end;
end;
procedure TfrmPtSel.cboPatientExit(Sender: TObject);
begin
cmdOK.Default := False;
end;
procedure TfrmPtSel.cboPatientChange(Sender: TObject);
procedure ShowMatchingPatients;
begin
with cboPatient do
begin
ClearIDInfo;
if ShortCount > 0 then
begin
if ShortCount = 1 then
begin
ItemIndex := 0;
ShowIDInfo;
ShowFlagInfo;
end;
Items.Add(LLS_LINE);
Items.Add(LLS_SPACE);
end;
InitLongList('');
end;
end;
begin
with cboPatient do
if frmPtSelOptns.IsLast5(Text) then
begin
if (IsRPL = '1') then
ListPtByRPLLast5(Items, Text)
else
ListPtByLast5(Items, Text);
ShowMatchingPatients;
end
else if frmPtSelOptns.IsFullSSN(Text) then
begin
if (IsRPL = '1') then
ListPtByRPLFullSSN(Items, Text)
else
ListPtByFullSSN(Items, Text);
ShowMatchingPatients;
end;
end;
procedure TfrmPtSel.cboPatientKeyPause(Sender: TObject);
begin
if Length(cboPatient.ItemID) > 0 then // *DFN*
begin
ShowIDInfo;
ShowFlagInfo;
end
else
begin
ClearIDInfo;
end;
end;
procedure TfrmPtSel.cboPatientKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_BACK) and (cboPatient.Text = '') then
cboPatient.ItemIndex := -1;
end;
procedure TfrmPtSel.cboPatientMouseClick(Sender: TObject);
begin
if Length(cboPatient.ItemID) > 0 then // *DFN*
begin
ShowIDInfo;
ShowFlagInfo;
end
else
begin
ClearIDInfo;
end;
end;
procedure TfrmPtSel.cboPatientDblClick(Sender: TObject);
begin
if Length(cboPatient.ItemID) > 0 then
cmdOKClick(self); // *DFN*
end;
procedure TfrmPtSel.cboPatientNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
var
i: Integer;
NoAlias, Patient: string;
PatientList: TStringList;
begin
NoAlias := StartFrom;
with Sender as TORComboBox do
if Items.Count > ShortCount then
begin
NoAlias := Piece(Items[Items.Count - 1], U, 1) + U + NoAlias;
if Direction < 0 then
NoAlias := Copy(NoAlias, 1, Length(NoAlias) - 1);
end;
if pos(AliasString, NoAlias) > 0 then
NoAlias := Copy(NoAlias, 1, pos(AliasString, NoAlias) - 1);
PatientList := TStringList.Create;
try
begin
if (IsRPL = '1') then // Restricted patient lists uses different feed for long list box:
FastAssign(ReadRPLPtList(RPLJob, NoAlias, Direction), PatientList)
else
begin
FastAssign(SubSetOfPatients(NoAlias, Direction), PatientList);
for i := 0 to PatientList.Count - 1 do // Add " - Alias" to alias names:
begin
Patient := PatientList[i];
// Piece 6 avoids display problems when mixed with "RPL" lists:
if (Uppercase(Piece(Patient, U, 2)) <> Uppercase(Piece(Patient, U, 6))) then
begin
SetPiece(Patient, U, 2, Piece(Patient, U, 2) + AliasString);
PatientList[i] := Patient;
end;
end;
end;
cboPatient.ForDataUse(PatientList);
end;
finally
PatientList.Free;
end;
end;
procedure TfrmPtSel.ClearIDInfo;
begin
frmPtSelDemog.ClearIDInfo;
end;
procedure TfrmPtSel.ShowIDInfo;
begin
frmPtSelDemog.ShowDemog(cboPatient.ItemID);
end;
procedure TfrmPtSel.WMReadyAlert(var Message: TMessage);
begin
ReadyAlert;
message.Result := 0;
end;
{ Command Button events: }
procedure TfrmPtSel.cmdOKClick(Sender: TObject);
{ Checks for restrictions on the selected patient and sets up the Patient object. }
const
DLG_CANCEL = False;
var
NewDFN: string; // *DFN*
DateDied: TFMDateTime;
AccessStatus: Integer;
begin
if not(Length(cboPatient.ItemID) > 0) then // *DFN*
begin
InfoBox('A patient has not been selected.', 'No Patient Selected', MB_OK);
Exit;
end;
NewDFN := cboPatient.ItemID; // *DFN*
if FLastPt <> cboPatient.ItemID then
begin
HasActiveFlg(FlagList, HasFlag, cboPatient.ItemID);
FLastPt := cboPatient.ItemID;
end;
if DupLastSSN(NewDFN) then // Check for, deal with duplicate patient data.
if (DupDFN = 'Cancel') then
Exit
else
NewDFN := DupDFN;
if not AllowAccessToSensitivePatient(NewDFN, AccessStatus) then
Exit;
DateDied := DateOfDeath(NewDFN);
if (DateDied > 0) and (InfoBox('This patient died ' + FormatFMDateTime('mmm dd,yyyy hh:nn', DateDied) + CRLF +
'Do you wish to continue?', 'Deceased Patient', MB_YESNO or MB_DEFBUTTON2) = ID_NO) then
Exit;
// 9/23/2002: Code used to check for changed pt. DFN here, but since same patient could be
// selected twice in diff. Encounter locations, check was removed and following code runs
// no matter; in fFrame code then updates Encounter display if Encounter.Location has changed.
// NOTE: Some pieces in RPC returned arrays are modified/rearranged by ListPtByDflt call in rCore!
Patient.DFN := NewDFN; // The patient object in uCore must have been created already!
Encounter.Clear;
Changes.Clear; // An earlier call to ReviewChanges should have cleared this.
if (frmPtSelOptns.SrcType = TAG_SRC_CLIN) and (frmPtSelOptns.cboList.ItemIEN > 0) and
IsFMDateTime(Piece(cboPatient.Items[cboPatient.ItemIndex], U, 4)) then // Clinics, not by default.
begin
Encounter.Location := frmPtSelOptns.cboList.ItemIEN;
with cboPatient do
Encounter.DateTime := MakeFMDateTime(Piece(Items[ItemIndex], U, 4));
end
else if (frmPtSelOptns.SrcType = TAG_SRC_DFLT) and (DfltPtListSrc = 'C') and
IsFMDateTime(Piece(cboPatient.Items[cboPatient.ItemIndex], U, 4)) then
with cboPatient do // "Default" is a clinic.
begin
Encounter.Location := StrToIntDef(Piece(Items[ItemIndex], U, 10), 0); // Piece 10 is ^SC( location IEN in this case.
Encounter.DateTime := MakeFMDateTime(Piece(Items[ItemIndex], U, 4));
end
else if ((frmPtSelOptns.SrcType = TAG_SRC_DFLT) and (FDfltSrc = 'Combination') and
(Copy(Piece(cboPatient.Items[cboPatient.ItemIndex], U, 3), 1, 2) = 'Cl')) and
(IsFMDateTime(Piece(cboPatient.Items[cboPatient.ItemIndex], U, 8))) then
with cboPatient do // "Default" combination, clinic pt.
begin
Encounter.Location := StrToIntDef(Piece(Items[ItemIndex], U, 7), 0); // Piece 7 is ^SC( location IEN in this case.
Encounter.DateTime := MakeFMDateTime(Piece(Items[ItemIndex], U, 8));
end
else if Patient.Inpatient then // Everything else:
begin
Encounter.Inpatient := True;
Encounter.Location := Patient.Location;
Encounter.DateTime := Patient.AdmitTime;
Encounter.VisitCategory := 'H';
end;
if User.IsProvider then
Encounter.Provider := User.DUZ;
FUserCancelled := False;
FOKClicked := True;
FExpectedClose := True;
Close;
end;
procedure TfrmPtSel.cmdCancelClick(Sender: TObject);
begin
// Leave Patient object unchanged
FUserCancelled := True;
FExpectedClose := True;
Close;
end;
procedure TfrmPtSel.cmdCommentsClick(Sender: TObject);
var
tmpCmt: TStringList;
begin
if FAlertsNotReady then
Exit;
inherited;
tmpCmt := TStringList.Create;
try
tmpCmt.Text := lstvAlerts.Selected.SubItems[8];
LimitStringLength(tmpCmt, 74);
tmpCmt.Insert(0, StringOfChar('-', 74));
tmpCmt.Insert(0, lstvAlerts.Selected.SubItems[4]);
tmpCmt.Insert(0, lstvAlerts.Selected.SubItems[3]);
tmpCmt.Insert(0, lstvAlerts.Selected.SubItems[0]);
ReportBox(tmpCmt, 'Forwarded by: ' + lstvAlerts.Selected.SubItems[5], True);
lstvAlerts.SetFocus;
finally
tmpCmt.Free;
end;
end;
procedure TfrmPtSel.cmdDeferClick(Sender: TObject);
var
aResult: string;
item: TListItem;
begin
if FAlertsNotReady then
Exit;
with TfrmDeferDialog.Create(self) do
try
Title := 'Defer Patient Notification';
with TStringList.Create do
try
Text := lstvAlerts.Selected.SubItems.Text;
while Count > 6 do
Delete(Count - 1);
Description := Text;
finally
Free;
end;
{
Set more/better properties on the dialog here depending on SMART requirements
}
if Execute then
begin
aResult := sCallV('ORB3UTL DEFER', [User.DUZ, lstvAlerts.Selected.SubItems[6], DeferUntilFM]);
if aResult = '1' then
begin
MessageDlg('Notification successfully deferred.', mtInformation, [mbOk], 0);
item := lstvAlerts.Selected;
FAlertData.Delete(item.Index);
item.Selected := False;
lstvAlerts.Invalidate;
end
else
begin
MessageDlg(Copy(aResult, pos(aResult, '^') + 1, Length(aResult)), mtError, [mbOk], 0);
end
end;
finally
Free;
end;
end;
procedure TfrmPtSel.cmdProcessClick(Sender: TObject);
var
AFollowUp, i, infocount, LongTextResult: Integer;
enableclose: Boolean;
ADFN, X, RecordID, XQAID, LongText, AlertMsg: string; // *DFN*
LongTextBtns: TStringList;
aSmartParams, aEmptyParams: TStringList;
aSMARTAction: TNotificationAction;
lastUpdate: TDateTime;
procedure IncProgressBar;
begin
ggeInfo.Progress := ggeInfo.Progress + 1;
if MilliSecondsBetween(Now, lastUpdate) > 250 then
begin
Application.ProcessMessages;
LastUpdate := Now;
end;
end;
begin
Application.ProcessMessages;
if FAlertsNotReady then
Exit;
enableclose := False;
with lstvAlerts do
begin
if SelCount <= 0 then
Exit;
// Count information-only selections for gauge
infocount := 0;
for i := 0 to Items.Count - 1 do
if Items[i].Selected then
begin
X := Items[i].Caption;
if (X = 'I') or (X = 'L') then
Inc(infocount);
end;
if infocount > 0 then
begin
ggeInfo.Visible := True; (* BOB *)
ggeInfo.MaxValue := infocount;
ggeInfo.Progress := 0;
Application.ProcessMessages; // display the progress bar
lastUpdate := Now;
end;
for i := 0 to Items.Count - 1 do
if Items[i].Selected then
{ Items[i].Selected = Boolean TRUE if item is selected
" .Caption = Info flag ('I')
" .SubItems[0] = Patient ('ABC,PATIE (A4321)')
" . " [1] = Patient location ('[2B]')
" . " [2] = Alert urgency level ('HIGH, Moderate, low')
" . " [3] = Alert date/time ('2002/12/31@12:10')
" . " [4] = Alert message ('New order(s) placed.')
" . " [5] = Forwarded by/when
" . " [6] = XQAID ('OR,66,50;1416;3021231.121024')
'TIU6028;1423;3021203.09')
" . " [7] = Remove without processing flag ('YES')
" . " [8] = Forwarding comments (if applicable) }
begin
XQAID := Items[i].SubItems[6];
AlertMsg := Items[i].SubItems[4];
RecordID := Items[i].SubItems[0] + ': ' + Items[i].SubItems[4] +
'^' + XQAID;
// RecordID := patient: alert message^XQAID ('ABC,PATIE (A4321): New order(s) placed.^OR,66,50;1416;3021231.121024')
if Items[i].Caption = 'I' then
// If Caption is 'I' delete the information only alert.
begin
IncProgressBar;
DeleteAlert(XQAID);
end
else if Items[i].Caption = 'L' then
begin
IncProgressBar;
LongText := LoadNotificationLongText(XQAID);
LongTextBtns := TStringList.Create();
LongTextBtns.Add('Copy to Clipboard');
LongTextBtns.Add('Dismiss Alert');
LongTextBtns.Add('Keep Alert^true');
if Piece(XQAID, ',', 1) = 'OR' then
begin
LongTextBtns.Add('Open Patient Chart');
end;
LongTextResult := 0;
while (LongTextResult=0) do
begin
LongTextResult := uInfoBoxWithBtnControls.DefMessageDlg(LongText,
mtConfirmation, LongTextBtns, Alertmsg, false);
if (LongTextResult = 0) then ClipBoard.astext := LongText
end;
if (LongTextResult = 1) then DeleteAlert(XQAID)
else if (LongTextResult = 3) then
begin
DeleteAlert(XQAID);
ADFN := Piece(XQAID, ',', 2); // *DFN*
cboPatient.Items.Add(ADFN+'^');
cboPatient.SelectByID(ADFN);
cmdOKClick(self);
enableClose := True;
break;
end;
end
else if Piece(XQAID, ',', 1) = 'OR' then
// OR,16,50;1311;2980626.100756
begin
//check if smart alert and if so show notificationprocessor dialog
try
aSmartParams := TStringList.Create;
CallVistA('ORB3UTL GET NOTIFICATION', [Piece(RecordID, '^', 2)],
aSmartParams);
If (aSmartParams.Values['PROCESS AS SMART NOTIFICATION'] = '1') then
begin
{ removing code to roll back changes introduced by v31.261 - begin}
// if aSmartParams.Values['CAN_PROCESS'] <> 'D' then
// begin
{ removing code to roll back changes introduced by v31.261 - end}
aSMARTAction := TfrmNotificationProcessor.Execute(aSmartParams,
lstvAlerts.Selected.SubItems.Text);
if aSMARTAction = naNewNote then
begin
aSmartParams.Add('MAKE ADDENDUM=0');
ADFN := Piece(XQAID, ',', 2); // *DFN*
AFollowUp := StrToIntDef(Piece(Piece(XQAID, ';', 1),
',', 3), 0);
Notifications.Add(ADFN, AFollowUp, RecordID,
Items[i].SubItems[3], aSmartParams);
enableclose := True;
end
else if aSMARTAction = naAddendum then
begin
aSmartParams.Add('MAKE ADDENDUM=1');
ADFN := Piece(XQAID, ',', 2); // *DFN*
AFollowUp := StrToIntDef(Piece(Piece(XQAID, ';', 1),
',', 3), 0);
Notifications.Add(ADFN, AFollowUp, RecordID,
Items[i].SubItems[3], aSmartParams);
enableclose := True;
end;
{ removing code to roll back changes introduced by v31.261 - begin}
// end
// else
// begin
// InfoBox('Processing of this type of alert is currently disabled.', 'Unable to Process Alert', MB_OK);
// end;
{ removing code to roll back changes introduced by v31.261 - end}
end
else
begin
ADFN := Piece(XQAID, ',', 2); // *DFN*
AFollowUp := StrToIntDef(Piece(Piece(XQAID, ';', 1), ',', 3), 0);
Notifications.Add(ADFN, AFollowUp, RecordID, Items[i].SubItems[3],
aSmartParams);
// CB
enableclose := True;
end;
finally
FreeAndNil(aSmartParams);
end;
end
else if Copy(XQAID, 1, 6) = 'TIUERR' then
InfoBox(Piece(RecordID, U, 1) + sLineBreak + sLineBreak +
'The CPRS GUI cannot yet process this type of alert. Please use List Manager.',
'Unable to Process Alert', MB_OK)
else if Copy(XQAID, 1, 3) = 'TIU' then
// TIU6028;1423;3021203.09
begin
X := GetTIUAlertInfo(XQAID);
if Piece(X, U, 2) <> '' then
begin
try
aEmptyParams := TStringList.Create();
ADFN := Piece(X, U, 2); // *DFN*
AFollowUp := StrToIntDef(Piece(Piece(X, U, 3), ';', 1), 0);
Notifications.Add(ADFN, AFollowUp,
RecordID + '^^' + Piece(X, U, 3), '', aEmptyParams);
enableclose := True;
finally
FreeAndNil(aEmptyParams);
end;
end
else
DeleteAlert(XQAID);
end
else // other alerts cannot be processed
InfoBox('This alert cannot be processed by the CPRS GUI.' + sLineBreak +
'Please use VistA to process this alert.',
Items[i].SubItems[0] + ': ' + Items[i].SubItems[4], MB_OK);
end;
// blj 21 Jun 2016: moved outside of if statement to prevent A/V.
if enableclose then
begin
FExpectedClose := True;
Close;
end
else
begin
ggeInfo.Visible := False;
// Update notification list:
AlertList;
// display alerts sorted according to parameter settings:
FsortCol := -1; // CA - display alerts in correct sort
FormShow(Sender);
end;
if Items.Count = 0 then
ShowButts(False);
if SelCount <= 0 then
ShowButts(False);
end;
end;
procedure TfrmPtSel.cmdSaveListClick(Sender: TObject);
begin
frmPtSelOptns.cmdSaveListClick(Sender);
end;
procedure TfrmPtSel.cmdProcessInfoClick(Sender: TObject);
// Select and process all items that are information only in the lstvAlerts list box.
var
i: Integer;
begin
if FAlertsNotReady then
Exit;
if lstvAlerts.Items.Count = 0 then
Exit;
if InfoBox('You are about to process all your INFORMATION alerts.' + CRLF
+ 'These alerts will not be presented to you for individual' + CRLF
+ 'review and they will be permanently removed from your' + CRLF
+ 'alert list. Do you wish to continue?',
'Warning', MB_YESNO or MB_ICONWARNING) = IDYES then
begin
lstvAlerts.ClearSelection;
// for i := 0 to lstvAlerts.Items.Count - 1 do
// lstvAlerts.Items[i].Selected := False; // clear any selected alerts so they aren't processed
for i := 0 to lstvAlerts.Items.Count - 1 do
if lstvAlerts.Items[i].Caption = 'I' then
lstvAlerts.Items[i].Selected := True;
cmdProcessClick(self);
ShowButts(False);
end;
end;
procedure TfrmPtSel.cmdProcessAllClick(Sender: TObject);
begin
if FAlertsNotReady then
Exit;
lstvAlerts.SelectAll;
cmdProcessClick(self);
ShowButts(False);
end;
procedure TfrmPtSel.lstvAlertsData(Sender: TObject; Item: TListItem);
var
j: Integer;
s: string;
begin
inherited;
if assigned(Item) and (Item.Index < FAlertData.Count) then
begin
s := FAlertData[Item.Index];
Item.Caption := Piece(s, U, 1);
for j := 2 to LAST_DISPLAYED_PIECE do
if Item.SubItems.Count > (j-2) then
Item.SubItems[j-2] := Piece(s, U, j)
else
Item.SubItems.Add(Piece(s, U, j));
end;
end;
procedure TfrmPtSel.lstvAlertsDataStateChange(Sender: TObject; StartIndex,
EndIndex: Integer; OldState, NewState: TItemStates);
begin
FAlertsNotReady := True;
PostMessage(Handle, UM_MISC, 0, 0);
end;
procedure TfrmPtSel.lstvAlertsDblClick(Sender: TObject);
begin
cmdProcessClick(self);
end;
procedure TfrmPtSel.cmdForwardClick(Sender: TObject);
var
i: Integer;
Alert: string;
begin
if FAlertsNotReady then
Exit;
try
with lstvAlerts do
begin
if SelCount <= 0 then
Exit;
for i := 0 to Items.Count - 1 do
if Items[i].Selected then
begin
try
Alert := Items[i].SubItems[6] + '^' + Items[i].SubItems[0] + ': ' +
Items[i].SubItems[4];
ForwardAlertTo(Alert);
finally
Items[i].Selected := False;
end;
end;
end;
finally
if lstvAlerts.SelCount <= 0 then
ShowButts(False);
end;
end;
procedure TfrmPtSel.cmdRemoveClick(Sender: TObject);
var
i: Integer;
begin
if FAlertsNotReady then
Exit;
with lstvAlerts do
begin
if SelCount <= 0 then
Exit;
for i := 0 to Items.Count - 1 do
if Items[i].Selected then
begin
if Items[i].SubItems[7] = '1' then // remove flag enabled
DeleteAlertforUser(Items[i].SubItems[6])
else
InfoBox('This alert cannot be removed.', Items[i].SubItems[0] + ': ' + Items[i].SubItems[4], MB_OK);
end;
end;
AlertList;
FsortCol := -1; // CA - display alerts in correct sort
FormShow(Sender); // CA - display alerts in correct sort
if (lstvAlerts.Items.Count = 0) or (lstvAlerts.SelCount <= 0) then
ShowButts(False);
end;
procedure TfrmPtSel.FormDestroy(Sender: TObject);
var
i: Integer;
aString: string;
begin
SaveUserBounds(self);
frmFrame.EnduringPtSelSplitterPos := pnlPtSel.Height;
aString := '';
for i := 0 to 6 do
begin
aString := aString + IntToStr(lstvAlerts.Column[i].Width);
if i < 6 then
aString := aString + ',';
end;
frmFrame.EnduringPtSelColumns := aString;
FreeAndNil(FAlertData);
end;
procedure TfrmPtSel.FormResize(Sender: TObject);
begin
inherited;
FNotificationBtnsAdjusted := False;
AdjustButtonSize(cmdSaveList);
AdjustButtonSize(cmdProcessInfo);
AdjustButtonSize(cmdProcessAll);
AdjustButtonSize(cmdProcess);
AdjustButtonSize(cmdForward);
AdjustButtonSize(cmdComments);
AdjustButtonSize(cmdRemove);
AdjustButtonSize(cmdDefer);
AdjustNotificationButtons;
end;
procedure TfrmPtSel.pnlPtSelResize(Sender: TObject);
begin
frmPtSelDemog.Left := cboPatient.Left + cboPatient.Width + 9;
frmPtSelDemog.Width := pnlPtSel.Width - frmPtSelDemog.Left - 2;
frmPtSelOptns.Width := cboPatient.Left - 8;
SetupDemographicsLabel;
end;
procedure TfrmPtSel.Loaded;
begin
inherited;
SetupDemographicsForm;
SetupDemographicsLabel;
frmPtSelOptns := TfrmPtSelOptns.Create(self); // Was application - kcm
with frmPtSelOptns do
begin
parent := pnlPtSel;
Top := 4;
Left := 4;
Width := cboPatient.Left - 8;
SetCaptionTopProc := SetCaptionTop;
SetPtListTopProc := SetPtListTop;
if RPLProblem then
Exit;
TabOrder := cmdSaveList.TabOrder; // Put just before save default list button
Show;
end;
FLastPt := '';
// Begin at alert list, or patient listbox if no alerts
if lstvAlerts.Items.Count = 0 then
ActiveControl := cboPatient;
end;
procedure TfrmPtSel.ShowDisabledButtonTexts;
begin
if ScreenReaderActive then
begin
txtCmdProcess.Visible := not cmdProcess.Enabled;
txtCmdRemove.Visible := not cmdRemove.Enabled;
txtCmdForward.Visible := not cmdForward.Enabled;
txtCmdComments.Visible := not cmdComments.Enabled;
txtCmdDefer.Visible := not cmdDefer.Enabled;
end;
end;
procedure TfrmPtSel.SetupDemographicsForm;
begin
// This needs to be in Loaded rather than FormCreate or the TORAutoPanel resize logic breaks.
frmPtSelDemog := TfrmPtSelDemog.Create(self);
// Was application - kcm
with frmPtSelDemog do
begin
parent := pnlPtSel;
Top := cmdCancel.Top + cmdCancel.Height + 2;
Left := cboPatient.Left + cboPatient.Width + 9;
Width := pnlPtSel.Width - Left - 2;
TabOrder := cmdCancel.TabOrder + 1;
// Place after cancel button
Show;
end;
if ScreenReaderActive then
begin
frmPtSelDemog.Memo.Show;
frmPtSelDemog.Memo.BringToFront;
end;
end;
procedure TfrmPtSel.SetupDemographicsLabel;
var
intAdjust: Integer;
begin
intAdjust := Round(PixelsPerInch * MainFontSize / 96);
lblPtDemo.Top := frmPtSelDemog.Top - Round(lblPtDemo.Height * PixelsPerInch / 96 + intAdjust);
lblPtDemo.Left := frmPtSelDemog.Left
end;
procedure TfrmPtSel.RPLDisplay;
begin
// Make unneeded components invisible:
cmdSaveList.Visible := False;
frmPtSelOptns.Visible := False;
end;
procedure TfrmPtSel.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if (IsRPL = '1') then // Deal with restricted patient list users.
KillRPLPtList(RPLJob); // Kills server global data each time.
// (Global created by MakeRPLPtList in rCore.)
end;
procedure TfrmPtSel.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
inherited;
if not FExpectedClose then
begin
// For Alt-F4 or the X (Close) in the upper right hand corner of the dialog
FExpectedClose := True;
cmdCancelClick(Sender);
end;
end;
procedure TfrmPtSel.FormCreate(Sender: TObject);
begin
inherited;
DefaultButton := cmdOK;
FAlertsNotReady := False;
FExpectedClose := False;
ShowDisabledButtonTexts;
FAlertData := TStringList.Create;
end;
procedure TfrmPtSel.cboPatientKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = Ord('D')) and (ssCtrl in Shift) then
begin
Key := 0;
frmPtSelDemog.ToggleMemo;
end;
end;
function ConvertDate(
var
thisList: TStringList;
listIndex: Integer): string;
{
Convert date portion from yyyy/mm/dd to mm/dd/yyyy
}
var
// thisListItem: TListItem;
thisDateTime: string[16];
tempDt: string;
tempYr: string;
tempTime: string;
newDtTime: string;
k: byte;
piece1: string;
piece2: string;
piece3: string;
piece4: string;
piece5: string;
piece6: string;
piece7: string;
piece8: string;
piece9: string;
piece10: string;
piece11: string;
begin
piece1 := '';
piece2 := '';
piece3 := '';
piece4 := '';
piece5 := '';
piece6 := '';
piece7 := '';
piece8 := '';
piece9 := '';
piece10 := '';
piece11 := '';
piece1 := Piece(thisList[listIndex], U, 1);
piece2 := Piece(thisList[listIndex], U, 2);
piece3 := Piece(thisList[listIndex], U, 3);
piece4 := Piece(thisList[listIndex], U, 4);
// piece5 := Piece(thisList[listIndex],U,5);
piece6 := Piece(thisList[listIndex], U, 6);
piece7 := Piece(thisList[listIndex], U, 7);
piece8 := Piece(thisList[listIndex], U, 8);
piece9 := Piece(thisList[listIndex], U, 9);
piece10 := Piece(thisList[listIndex], U, 1);
thisDateTime := ShortString(Piece(thisList[listIndex], U, 5));
tempYr := '';
for k := 1 to 4 do
tempYr := tempYr + string(thisDateTime[k]);
tempDt := '';
for k := 6 to 10 do
tempDt := tempDt + string(thisDateTime[k]);
tempTime := '';
// Use 'Length' to prevent stuffing the control chars into the date when a trailing zero is missing
for k := 11 to Length(thisDateTime) do // 16 do
tempTime := tempTime + string(thisDateTime[k]);
newDtTime := '';
newDtTime := newDtTime + tempDt + '/' + tempYr + tempTime;
piece5 := newDtTime;
Result := piece1 + U + piece2 + U + piece3 + U + piece4 + U + piece5 + U + piece6 + U + piece7 + U + piece8 + U + piece9 + U + piece10 + U + piece11;
end;
procedure TfrmPtSel.AlertList;
var
i: Integer;
cur: TCursor;
s, inDateStr, srtDate, comment: string;
const
FORWARD_BY_TXT = 'Forwarded by: ';
FORWARD_BY_LEN = Length(FORWARD_BY_TXT);
FORWARD_COMMENT = 'Fwd Comment: ';
begin
cur := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
FAlertData.Clear;
LoadNotifications(FAlertData);
i := 0;
while (i < FAlertData.Count) do
begin
if (i > 0) and (Copy(FAlertData[i], 1, FORWARD_BY_LEN) = FORWARD_BY_TXT) then // faster than Piece
begin
s := FAlertData[i - 1];
SetPiece(s, U, 7, Piece(FAlertData[i], U, 2));
comment := Piece(FAlertData[i], U, 3);
if Length(comment) > 0 then
SetPiece(s, U, 10, FORWARD_COMMENT + comment);
FAlertData[i - 1] := s;
FAlertData.Delete(i);
end
else
begin
s := FAlertData[i];
inDateStr := Piece(s, U, 5);
srtDate := ((Piece(Piece(inDateStr, '/', 3), '@', 1)) + '/' + Piece(inDateStr, '/', 1) +
'/' + Piece(inDateStr, '/', 2) + '@' + Piece(inDateStr, '@', 2));
SetPiece(s, U, SORT_DATE_PIECE, srtDate);
FAlertData[i] := s;
Inc(i);
end;
end;
lstvAlerts.Items.Count := FAlertData.Count;
lstvAlerts.ClearSelection;
if FAlertData.Count > 0 then
lstvAlerts.Items[0].MakeVisible(FALSE);
lstvAlerts.Invalidate;
finally
Screen.Cursor := cur;
end;
with lstvAlerts do
begin
Columns[0].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 1), 40); // Info Caption
Columns[1].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 2), 195); // Patient SubItems[0]
Columns[2].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 3), 75); // Location SubItems[1]
Columns[3].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 4), 95); // Urgency SubItems[2]
Columns[4].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 5), 150); // Alert Date/Time SubItems[3]
Columns[5].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 6), 310); // Message Text SubItems[4]
Columns[6].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 7), 290); // Forwarded By/When SubItems[5]
Columns[10].Width := StrToIntDef(Piece(frmFrame.EnduringPtSelColumns, ',', 11), 195); // Ordering Provider SubItems[5]
// Items not displayed in Columns: XQAID SubItems[6]
// Remove w/o process SubItems[7]
// Forwarding comments SubItems[8]
end;
end;
procedure TfrmPtSel.lstvAlertsColumnClick(Sender: TObject; Column: TListColumn);
const
Mask = LVIS_FOCUSED or LVIS_SELECTED;
var
i, max, State, NewState: integer;
s, code: string;
begin
max := lstvAlerts.Items.Count - 1;
if max > (FAlertData.Count - 1) then
max := FAlertData.Count - 1;
for i := 0 to max do
begin
State := ListView_GetItemState(lstvAlerts.Handle, i, Mask);
if (State and Mask) = Mask then
code := 'B' // Both
else if (State and LVIS_SELECTED) = LVIS_SELECTED then
code := 'S' // Selected
else if (State and LVIS_FOCUSED) = LVIS_FOCUSED then
code := 'F' // Focused
else
code := '';
s := FAlertData[i];
if Piece(s, U, ITEM_STATE_PIECE) <> code then
begin
SetPiece(s, U, ITEM_STATE_PIECE, code);
FAlertData[i] := s;
end;
end;
if (FsortCol = Column.Index) then
FsortAscending := not FsortAscending;
if FsortAscending then
FsortDirection := 'F'
else
FsortDirection := 'R';
FsortCol := Column.Index;
if FsortCol = 4 then
SortByPiece(FAlertData, U, SORT_DATE_PIECE, SortDirection[FsortAscending])
// ReformatAlertDateTime // hds7397- ge 2/6/6 sort and display date/time column correctly - as requested
else
SortByPiece(FAlertData, U, FsortCol + 1, SortDirection[FsortAscending]);
for i := 0 to max do
begin
code := Piece(FAlertData[i], U, ITEM_STATE_PIECE) + ' ';
case code[1] of
'B': NewState := Mask;
'S': NewState := LVIS_SELECTED;
'F': NewState := LVIS_FOCUSED
else NewState := 0;
end;
State := ListView_GetItemState(lstvAlerts.Handle, i, Mask);
if State <> NewState then
ListView_SetItemState(lstvAlerts.Handle, i, NewState, Mask);
end;
lstvAlerts.Invalidate;
// Set the Notifications sort method to last-used sort-type
// ie., user clicked on which column header last use of CPRS?
case Column.Index of
0:
rCore.SetSortMethod('I', FsortDirection);
1:
rCore.SetSortMethod('P', FsortDirection);
2:
rCore.SetSortMethod('L', FsortDirection);
3:
rCore.SetSortMethod('U', FsortDirection);
4:
rCore.SetSortMethod('D', FsortDirection);
5:
rCore.SetSortMethod('M', FsortDirection);
6:
rCore.SetSortMethod('F', FsortDirection);
end;
end;
function TfrmPtSel.DupLastSSN(const DFN: string): Boolean;
var
i: Integer;
frmPtDupSel: tForm;
begin
Result := False;
// Check data on server for duplicates:
CallV('DG CHK BS5 XREF ARRAY', [DFN]);
if (RPCBrokerV.Results[0] <> '1') then // No duplicates found.
Exit;
Result := True;
PtStrs := TStringList.Create;
with RPCBrokerV do
if Results.Count > 0 then
begin
for i := 1 to Results.Count - 1 do
begin
if Piece(Results[i], U, 1) = '1' then
PtStrs.Add(Piece(Results[i], U, 2) + U + Piece(Results[i], U, 3) + U +
FormatFMDateTimeStr('mmm dd,yyyy', Piece(Results[i], U, 4)) + U +
Piece(Results[i], U, 5));
end;
end;
// Call form to get user's selection from expanded duplicate pt. list (resets DupDFN variable if applicable):
DupDFN := DFN;
frmPtDupSel := TfrmDupPts.Create(Application);
with frmPtDupSel do
begin
try
ShowModal;
finally
frmPtDupSel.Release;
end;
end;
end;
procedure TfrmPtSel.ShowFlagInfo;
begin
if (pos('*SENSITIVE*', frmPtSelDemog.lblPtSSN.Caption) > 0) then
begin
// pnlPrf.Visible := False;
Exit;
end;
if (FLastPt <> cboPatient.ItemID) then
begin
HasActiveFlg(FlagList, HasFlag, cboPatient.ItemID);
FLastPt := cboPatient.ItemID;
end;
if HasFlag then
begin
// FastAssign(FlagList, lstFlags.Items);
// pnlPrf.Visible := True;
end
// else pnlPrf.Visible := False;
end;
procedure TfrmPtSel.lstFlagsClick(Sender: TObject);
begin
{ if lstFlags.ItemIndex >= 0 then
ShowFlags(lstFlags.ItemID); }
end;
procedure TfrmPtSel.lstFlagsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
lstFlagsClick(self);
end;
procedure TfrmPtSel.lstvAlertsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
// SelCount is not accurate in this event because lstvAlerts is now OwnerData
FAlertsNotReady := True;
PostMessage(Handle, UM_MISC, 0, 0);
end;
procedure TfrmPtSel.ShowButts(ShowButts: Boolean);
begin
cmdProcess.Enabled := ShowButts;
cmdRemove.Enabled := ShowButts;
cmdForward.Enabled := ShowButts;
cmdComments.Enabled := ShowButts and (lstvAlerts.SelCount = 1) and (lstvAlerts.Selected.SubItems[8] <> '');
cmdDefer.Enabled := ShowButts and (lstvAlerts.SelCount = 1);
ShowDisabledButtonTexts;
end;
procedure TfrmPtSel.lstvAlertsInfoTip(Sender: TObject; Item: TListItem;
var InfoTip: string);
begin
InfoTip := Item.SubItems[8];
end;
procedure TfrmPtSel.lstvAlertsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
{
//KW
508: Allow non-sighted users to sort Notifications using Ctrl + <key>
Numbers in case stmnt are ASCII values for character keys.
}
begin
if FAlertsNotReady then
Exit;
if lstvAlerts.Focused then
begin
case Key of
VK_RETURN:
cmdProcessClick(Sender); // Process all selected alerts
73, 105:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[0]); // I,i
80, 113:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[1]); // P,p
76, 108:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[2]); // L,l
85, 117:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[3]); // U,u
68, 100:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[4]); // D,d
77, 109:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[5]); // M,m
70, 102:
if (ssCtrl in Shift) then
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[6]); // F,f
end;
end;
end;
procedure TfrmPtSel.lstvAlertsMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited;
FMouseUpPos := Point(X, Y);
end;
procedure TfrmPtSel.FormShow(Sender: TObject);
{
//KW
Sort Alerts by last-used method for current user
}
var
sortResult: string;
sortMethod: string;
begin
sortResult := rCore.GetSortMethod;
sortMethod := Piece(sortResult, U, 1);
if sortMethod = '' then
sortMethod := 'D';
FsortDirection := Piece(sortResult, U, 2);
if FsortDirection = 'F' then
FsortAscending := True
else
FsortAscending := False;
case sortMethod[1] of
'I', 'i':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[0]);
'P', 'p':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[1]);
'L', 'l':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[2]);
'U', 'u':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[3]);
'D', 'd':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[4]);
'M', 'm':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[5]);
'F', 'f':
lstvAlertsColumnClick(Sender, lstvAlerts.Columns[6]);
end;
end;
// hds7397- ge 2/6/6 sort and display date/time column correctly - as requested
procedure TfrmPtSel.ReadyAlert;
begin
if lstvAlerts.SelCount <= 0 then
ShowButts(False)
else
ShowButts(True);
FAlertsNotReady := False;
end;
{
procedure TfrmPtSel.ReformatAlertDateTime;
var
i: Integer;
inDateStr, holdDayTime, srtDate, s: string;
begin
// convert date to yyyy/mm/dd prior to sort.
for i := 0 to FAlertData.Count - 1 do
begin
s := FAlertData[i];
inDateStr := Piece(s, U, 5);
srtDate := ((Piece(Piece(inDateStr, '/', 3), '@', 1)) + '/' + Piece(inDateStr, '/', 1) +
'/' + Piece(inDateStr, '/', 2) + '@' + Piece(inDateStr, '@', 2));
SetPiece(s, U, 5, srtDate);
FAlertData[i] := s;
end;
// sort the listview records by date
SortByPiece(FAlertData, U, FsortCol + 1, SortDirection[FsortAscending]);
// loop thru lstvAlerts change date to yyyy/mm/dd
// sort list
// change alert date/time back to mm/dd/yyyy@time for display
for i := 0 to FAlertData.Count - 1 do
begin
s := FAlertData[i];
inDateStr := Piece(s, U, 5);
holdDayTime := Piece(inDateStr, '/', 3); // dd@time
srtDate := (Piece(inDateStr, '/', 2) + '/' + Piece(holdDayTime, '@', 1) + '/'
+ Piece(inDateStr, '/', 1) + '@' + Piece(holdDayTime, '@', 2));
SetPiece(s, U, 5, srtDate);
FAlertData[i] := s;
end;
end;
}
procedure TfrmPtSel.AdjustButtonSize(pButton: TButton);
var
thisButton: TButton;
const
Gap = 5;
begin
thisButton := pButton;
if thisButton.Width < frmFrame.Canvas.TextWidth(thisButton.Caption) then // CQ2737 GE
begin
FNotificationBtnsAdjusted := (thisButton.Width < frmFrame.Canvas.TextWidth(thisButton.Caption));
thisButton.Width := (frmFrame.Canvas.TextWidth(thisButton.Caption) + Gap + Gap); // CQ2737 GE
end;
if thisButton.Height < frmFrame.Canvas.TextHeight(thisButton.Caption) then // CQ2737 GE
thisButton.Height := (frmFrame.Canvas.TextHeight(thisButton.Caption) + Gap); // CQ2737 GE
end;
procedure TfrmPtSel.AdjustNotificationButtons;
const
Gap = 10;
BigGap = 40;
// reposition buttons after resizing eliminate overlap.
begin
if FNotificationBtnsAdjusted then
begin
cmdProcessAll.Left := (cmdProcessInfo.Left + cmdProcessInfo.Width + Gap);
cmdProcess.Left := (cmdProcessAll.Left + cmdProcessAll.Width + Gap);
cmdForward.Left := (cmdProcess.Left + cmdProcess.Width + Gap);
cmdComments.Left := (cmdForward.Left + cmdForward.Width + Gap);
cmdRemove.Left := (cmdComments.Left + cmdComments.Width + BigGap);
cmdDefer.Left := (cmdRemove.Left + cmdRemove.Width + Gap);
end;
end;
end.
|
unit IdBlockCipherIntercept;
{-----------------------------------------------------------------------------
UnitName: IdBlockCipherIntercept
Author: Andrew P.Rybin [magicode@mail.ru]
Creation: 27.02.2002
Version: 0.9.0b
Purpose: Secure communications
History:
-----------------------------------------------------------------------------}
{$I IdCompilerDefines.inc}
interface
uses
Classes,
IdIntercept, IdException;
const
IdBlockCipherBlockSizeDefault = 16;
IdBlockCipherBlockSizeMax = 256;
type
TIdBlockCipherIntercept = class;
//OneBlock event
TIdBlockCipherInterceptDataEvent = procedure (ASender: TIdBlockCipherIntercept; ASrcData, ADstData: Pointer) of object;
TIdBlockCipherIntercept = class(TIdConnectionIntercept)
protected
FBlockSize: Integer;
FData: TObject; //commonly password
FRecvStream: TMemoryStream;
FSendStream: TMemoryStream;
//
procedure Decrypt (const ASrcData; var ADstData); virtual;
procedure Encrypt (const ASrcData; var ADstData); virtual;
function GetOnReceive: TIdBlockCipherInterceptDataEvent;
function GetOnSend: TIdBlockCipherInterceptDataEvent;
procedure SetOnReceive(const Value: TIdBlockCipherInterceptDataEvent);
procedure SetOnSend(const Value: TIdBlockCipherInterceptDataEvent);
procedure SetBlockSize(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Receive(ABuffer: TStream); override; //Decrypt
procedure Send(ABuffer: TStream); override; //Encrypt
procedure CopySettingsFrom (ASrcBlockCipherIntercept: TIdBlockCipherIntercept);
//
property Data: TObject read FData write FData;
published
property BlockSize: Integer read FBlockSize write SetBlockSize default IdBlockCipherBlockSizeDefault;
// events
property OnReceive: TIdBlockCipherInterceptDataEvent read GetOnReceive write SetOnReceive;
property OnSend: TIdBlockCipherInterceptDataEvent read GetOnSend write SetOnSend;
End;//TIdBlockCipherIntercept
EIdBlockCipherInterceptException = EIdException; {block length}
IMPLEMENTATION
Uses
IdGlobal,
IdResourceStrings,
SysUtils;
{ TIdBlockCipherIntercept }
const
bitLongTail = $80; //future: for IdBlockCipherBlockSizeMax>256
constructor TIdBlockCipherIntercept.Create(AOwner: TComponent);
Begin
inherited Create(AOwner);
FBlockSize := IdBlockCipherBlockSizeDefault;
FRecvStream:= TMemoryStream.Create;
FSendStream:= TMemoryStream.Create;
End;//Create
destructor TIdBlockCipherIntercept.Destroy;
Begin
FreeAndNIL(FSendStream);
FreeAndNIL(FRecvStream);
inherited Destroy;
End;//Destroy
procedure TIdBlockCipherIntercept.Encrypt(const ASrcData; var ADstData);
Begin
if Assigned(FOnSend) then begin
TIdBlockCipherInterceptDataEvent(FOnSend)(SELF, @ASrcData, @ADstData);
end;//ex: EncryptAES(LTempIn, ExpandedKey, LTempOut);
End;//Encrypt
procedure TIdBlockCipherIntercept.Decrypt(const ASrcData; var ADstData);
Begin
if Assigned(FOnReceive) then begin
TIdBlockCipherInterceptDataEvent(FOnReceive)(SELF, @ASrcData, @ADstData);
end;//ex: DecryptAES(LTempIn, ExpandedKey, LTempOut);
End;//Decrypt
procedure TIdBlockCipherIntercept.Send(ABuffer: TStream);
var
LTempIn, LTempOut: array [0..IdBlockCipherBlockSizeMax] of Byte;
LCount: Integer;
LBS: Integer; //block size-1
Begin
FSendStream.LoadFromStream(ABuffer);
LCount := FSendStream.Seek(0,soFromEnd);//size
ABuffer.Seek(0,0); //bof
FSendStream.Seek(0,0);
if LCount <= 0 then begin
EXIT;
end;
LBS := FBlockSize-1;
while LCount >= LBS do begin
FSendStream.Read(LTempIn, LBS); //?ReadBuffer
LTempIn[LBS]:= LBS;
Encrypt(LTempIn,LTempOut);
ABuffer.Write(LTempOut, FBlockSize);//? WriteBuffer
Dec(LCount, LBS);
end;//while
if LCount > 0 then begin
FSendStream.Read(LTempIn, LCount);//? ReadBuffer
FillChar(LTempIn[LCount], FBlockSize - LCount, 0); //SizeOf(LTempIn)-Cnt
LTempIn[LBS]:= LCount;
Encrypt(LTempIn, LTempOut);
ABuffer.Write(LTempOut, FBlockSize); //?WriteBuffer
end;//if
End;//Send
procedure TIdBlockCipherIntercept.Receive(ABuffer: TStream);
var
LTempIn, LTempOut: array [0..IdBlockCipherBlockSizeMax] of Byte;
LCount: Integer;
LBS: Integer;
LRcvBlkSize: Integer; //received block data length
Begin
FRecvStream.CopyFrom(ABuffer,0);//append
LCount := FRecvStream.Seek(0,soFromEnd);//size
ABuffer.Seek(0,0); //bof
FRecvStream.Seek(0,0);
if LCount <= 0 then begin
exit;
end;
LBS := FBlockSize-1;
while LCount >= FBlockSize do begin
FRecvStream.Read(LTempIn, FBlockSize); //?ReadBuffer
Decrypt(LTempIn, LTempOut);
LRcvBlkSize := LTempOut[LBS]; //real data_in_block length
if LRcvBlkSize > 0 then begin
if LRcvBlkSize < FBlockSize then begin
ABuffer.Write(LTempOut, LRcvBlkSize);
end else begin
raise EIdBlockCipherInterceptException.Create(RSBlockIncorrectLength);
end;
end;//if block with data
Dec(LCount, FBlockSize);
end;//while
// cache for round block
if LCount >0 then begin
FRecvStream.Read(LTempIn, LCount);
FRecvStream.Seek(0,0);//bof
FRecvStream.Write(LTempIn, LCount);
FRecvStream.SetSize(LCount);
end else begin
FRecvStream.Clear;
end;
ABuffer.Size := ABuffer.Position;//truncate
End;//Receive
function TIdBlockCipherIntercept.GetOnReceive: TIdBlockCipherInterceptDataEvent;
Begin
Result := TIdBlockCipherInterceptDataEvent(FOnReceive);
End;
function TIdBlockCipherIntercept.GetOnSend: TIdBlockCipherInterceptDataEvent;
Begin
Result := TIdBlockCipherInterceptDataEvent(FOnSend);
End;
procedure TIdBlockCipherIntercept.SetOnReceive(const Value: TIdBlockCipherInterceptDataEvent);
Begin
TIdBlockCipherInterceptDataEvent(FOnReceive):= Value;
End;
procedure TIdBlockCipherIntercept.SetOnSend(const Value: TIdBlockCipherInterceptDataEvent);
Begin
TIdBlockCipherInterceptDataEvent(FOnSend):= Value;
End;
procedure TIdBlockCipherIntercept.CopySettingsFrom(
ASrcBlockCipherIntercept: TIdBlockCipherIntercept);
Begin
with ASrcBlockCipherIntercept do begin
SELF.FBlockSize := FBlockSize;
SELF.FData:= FData;
SELF.FOnConnect := FOnConnect;
SELF.FOnDisconnect:= FOnDisconnect;
SELF.FOnReceive := FOnReceive;
SELF.FOnSend := FOnSend;
end;
End;//
procedure TIdBlockCipherIntercept.SetBlockSize(const Value: Integer);
Begin
if (Value>0) and (Value<=IdBlockCipherBlockSizeMax) then begin
FBlockSize := Value;
end;
End;//
END.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLAsyncTimer - asynchronous timer component (actual 1 ms resolution).<p>
This component is based on ThreadedTimer by Carlos Barbosa.<p>
<b>History : </b><font size=-1><ul>
<li>17/11/14 - PW - Refactored TAsyncTimer to TGLAsyncTimer
<li>15/11/14 - PW - Renamed AsynchTimer.pas unit to GLAsyncTimer.pas
<li>06/05/09 - DanB - removed TThreadPriority, was needed for Kylix, but not FPC
<li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585)
<li>28/06/04 - LR - Added TThreadPriority for Linux
<li>24/09/02 - EG - Fixed ThreadPriority default value (Nelson Chu)
<li>20/01/02 - EG - Simplifications, dropped Win32 dependencies
<li>05/04/00 - GrC - Enabled checks to prevent events after destroy
<li>01/04/00 - EG - Re-Creation, minor changes over Carlos's code
</ul></font>
}
unit GLAsyncTimer;
interface
{$I GLScene.inc}
uses
Classes, SysUtils, SyncObjs,
GLCrossPlatform;
const
cDEFAULT_TIMER_INTERVAL = 1000;
type
// TGLAsyncTimer
//
{ : Asynchronous timer component (actual 1 ms resolution, if CPU fast enough).<p>
Keep in mind timer resolution is obtained <i>in-between</i> events, but
events are not triggered every x ms. For instance if you set the interval to
5 ms, and your Timer event takes 1 ms to complete, Timer events will actually
be triggered every 5+1=6 ms (that's why it's "asynchronous").<p>
This component is based on ThreadedTimer by Carlos Barbosa. }
TGLAsyncTimer = class(TComponent)
private
FEnabled: Boolean;
FOnTimer: TNotifyEvent;
FTimerThread: TThread;
FMutex: TCriticalSection;
protected
procedure SetEnabled(Value: Boolean);
function GetInterval: Word;
procedure SetInterval(Value: Word);
function GetThreadPriority: TThreadPriority;
procedure SetThreadPriority(Value: TThreadPriority);
procedure DoTimer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Enabled: Boolean read FEnabled write SetEnabled default False;
property Interval: Word read GetInterval write SetInterval
default cDEFAULT_TIMER_INTERVAL;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
property ThreadPriority: TThreadPriority read GetThreadPriority
write SetThreadPriority default tpTimeCritical;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
type
// TTimerThread
//
TTimerThread = class(TThread)
private
FOwner: TGLAsyncTimer;
FInterval: Word;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean); virtual;
end;
// Create
//
constructor TTimerThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
end;
// Execute
//
procedure TTimerThread.Execute;
var
lastTick, nextTick, curTick, perfFreq: Int64;
begin
QueryPerformanceFrequency(perfFreq);
QueryPerformanceCounter(lastTick);
nextTick := lastTick + (FInterval * perfFreq) div 1000;
while not Terminated do
begin
FOwner.FMutex.Acquire;
FOwner.FMutex.Release;
while not Terminated do
begin
QueryPerformanceCounter(lastTick);
if lastTick >= nextTick then
break;
Sleep(1);
end;
if not Terminated then
begin
// if time elapsed run user-event
Synchronize(FOwner.DoTimer);
QueryPerformanceCounter(curTick);
nextTick := lastTick + (FInterval * perfFreq) div 1000;
if nextTick <= curTick then
begin
// CPU too slow... delay to avoid monopolizing what's left
nextTick := curTick + (FInterval * perfFreq) div 1000;
end;
end;
end;
end;
{ TGLAsyncTimer }
// Create
//
constructor TGLAsyncTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// create timer thread
FMutex := TCriticalSection.Create;
FMutex.Acquire;
FTimerThread := TTimerThread.Create(False);
with TTimerThread(FTimerThread) do
begin
FOwner := Self;
FreeOnTerminate := False;
Priority := tpTimeCritical;
FInterval := cDEFAULT_TIMER_INTERVAL;
end;
end;
// Destroy
//
destructor TGLAsyncTimer.Destroy;
begin
Enabled := False;
FTimerThread.Terminate;
FMutex.Release;
CheckSynchronize;
// wait & free
FTimerThread.WaitFor;
FTimerThread.Free;
FMutex.Free;
inherited Destroy;
end;
// DoTimer
//
procedure TGLAsyncTimer.DoTimer;
begin
if Enabled and Assigned(FOnTimer) then
FOnTimer(Self);
end;
// SetEnabled
//
procedure TGLAsyncTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
if FEnabled then
begin
// When enabled resume thread
if TTimerThread(FTimerThread).FInterval > 0 then
FMutex.Release;
end
else
FMutex.Acquire;
end;
end;
function TGLAsyncTimer.GetInterval: Word;
begin
Result := TTimerThread(FTimerThread).FInterval;
end;
procedure TGLAsyncTimer.SetInterval(Value: Word);
begin
if Value <> TTimerThread(FTimerThread).FInterval then
begin
TTimerThread(FTimerThread).FInterval := Value;
end;
end;
function TGLAsyncTimer.GetThreadPriority: TThreadPriority;
begin
Result := FTimerThread.Priority;
end;
procedure TGLAsyncTimer.SetThreadPriority(Value: TThreadPriority);
begin
FTimerThread.Priority := Value;
end;
initialization
RegisterClass(TGLAsyncTimer);
end.
|
unit user_handler;
interface
uses
tipe_data;
{ KONSTANTA }
const
nmax = 1000; // Asumsi bahwa size terbesar dari database adalah 1000
{ DEKLARASI TIPE }
type
user = record
Nama, Alamat, Username, Password, Role : string;
end;
tabel_user = record
t: array [0..nmax] of user;
sz: integer; // effective size
end;
{ DEKLARASI FUNGSI DAN PROSEDUR }
function tambah(s: arr_str): tabel_user;
procedure print(data_tempuser: tabel_user);
function konversi_csv(data_tempuser: tabel_user): arr_str;
{ IMPLEMENTASI FUNGSI DAN PROSEDUR }
implementation
function tambah(s: arr_str): tabel_user;
{ DESKRIPSI : Memasukkan data dari array of string kedalam tabel_user }
{ PARAMETER : array of string }
{ RETURN : data user }
{ KAMUS LOKAL }
var
row: integer;
temp: string;
c: char;
data_tempuser : tabel_user;
countcomma, amountcomma : integer;
{ ALGORITMA }
begin
data_tempuser.sz := 0;
for row:=0 to s.sz-1 do
begin
temp := '';
countcomma := 0;
for c in s.st[row] do
begin
if (c=',') then countcomma := countcomma + 1;
end;
amountcomma := countcomma;
for c in s.st[row] do
begin
if (c=',') then
begin
if (amountcomma = countcomma) then
begin
data_tempuser.t[data_tempuser.sz].Nama := temp;
countcomma := countcomma - 1;
temp := '';
end else
if (countcomma > 3) then
begin
temp := temp+c;
countcomma := countcomma - 1;
end else
if (countcomma = 3) then
begin
data_tempuser.t[data_tempuser.sz].Alamat := temp;
countcomma := countcomma - 1;
temp := '';
end else
if (countcomma = 2) then
begin
data_tempuser.t[data_tempuser.sz].Username := temp;
countcomma := countcomma - 1;
temp := '';
end else
if (countcomma = 1) then
begin
data_tempuser.t[data_tempuser.sz].Password := temp;
countcomma := countcomma - 1;
temp := '';
end else
end else temp := temp+c;
end;
data_tempuser.t[data_tempuser.sz].Role := temp;
data_tempuser.sz := data_tempuser.sz+1;
end;
tambah := data_tempuser;
end;
function konversi_csv(data_tempuser: tabel_user): arr_str;
{ DESKRIPSI : Fungsi untuk mengubah data user menjadi array of string }
{ PARAMETER : data user }
{ RETURN : array of string }
{ KAMUS LOKAL }
var
i : integer;
ret : arr_str;
{ ALGORITMA }
begin
ret.sz := data_tempuser.sz;
for i:=0 to data_tempuser.sz do
begin
ret.st[i] := data_tempuser.t[i].Nama + ',' +
data_tempuser.t[i].Alamat + ',' +
data_tempuser.t[i].Username + ',' +
data_tempuser.t[i].Password + ','+
data_tempuser.t[i].Role;
end;
konversi_csv := ret;
end;
procedure print(data_tempuser: tabel_user);
{ DESKRIPSI : Prosedur sederhana yang digunakan pada proses pembuatan program untuk debugging, prosedur ini mencetak data ke layar }
{ PARAMETER : Data yang akan dicetak }
{ KAMUS LOKAL }
var
i: integer;
{ ALGORITMA }
begin
for i:=0 to data_tempuser.sz-1 do
begin
writeln(data_tempuser.t[i].Nama, ' | ', data_tempuser.t[i].Alamat, ' | ', data_tempuser.t[i].Username, ' | ', data_tempuser.t[i].Password, ' | ', data_tempuser.t[i].Role);
end;
end;
end.
|
unit utexture;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SDL2;
type TTexture = record
RawTexture : PSDL_Texture;
Width, Height : Int32;
Transparent, Solid : boolean;
RenderTarget : PSDL_Renderer;
end;
type PTexture = ^TTexture;
function LoadTexture(_RenderTarget : PSDL_Renderer; FileName: string; _Transparent, _Solid: boolean) : TTexture;
procedure DestroyTexture(TextureToDestroy : PTexture);
function TextureExists(Target : PTexture) : boolean; inline;
var
TexturePath: string;
implementation
//LoadTexture(RenderTarget, FileName, Transparent, Solid);
//RenderTarget - use 'renderer' variable;
//FileName - I think you got it;
//Transparent - shows if texture supports transparency or not;
//Solid - shows ability to walk through walls with this texture.
function LoadTexture(_RenderTarget : PSDL_Renderer; FileName: string; _Transparent, _Solid: boolean) : TTexture;
var
bmp : PSDL_Surface;
begin
Result.Width:=0;
Result.Height:=0;
bmp := SDL_LoadBMP(PAnsiChar(TexturePath + FileName));
if bmp = nil then
exit;
if _Transparent then
begin
SDL_SetColorKey(bmp, 1, SDL_MapRGB(bmp^.format, 255, 0, 255)); //magenta is transparent
end;
Result.Transparent := _Transparent;
Result.RawTexture := SDL_CreateTextureFromSurface(_RenderTarget, bmp);
if Result.RawTexture = nil then
exit;
SDL_FreeSurface(bmp);
SDL_QueryTexture(Result.RawTexture, nil, nil, @Result.Width, @Result.Height);
Result.RenderTarget := _RenderTarget;
Result.Solid := _Solid;
end;
procedure DestroyTexture(TextureToDestroy : PTexture);
begin
with TextureToDestroy^ do
begin
RenderTarget := nil;
SDL_DestroyTexture(RawTexture);
RawTexture := nil;
Width := 0; Height := 0;
end;
end;
function TextureExists(Target : PTexture) : boolean; inline;
begin
Result := (Target^.Height <> 0) and (Target^.Width <> 0);
end;
initialization
TexturePath := './res/textures/';
end.
|
unit fGMV_SelectColor;
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ComCtrls,
ImgList,
StdCtrls,
ExtCtrls, System.ImageList;
type
TfrmGMV_SelectColor = class(TForm)
ilColors: TImageList;
Panel1: TPanel;
lvColors: TListView;
procedure FormCreate(Sender: TObject);
procedure lvColorsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure lvColorsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lvColorsDblClick(Sender: TObject);
private
FSelectedColor: Integer;
{ Private declarations }
public
{ Public declarations }
end;
var
frmGMV_SelectColor: TfrmGMV_SelectColor;
ilSelectColors: TImageList;
function SelectColor(Ctrl: TControl; var iColor: Integer): Boolean;
implementation
uses uGMV_Const, system.Types;
{$R *.DFM}
function SelectColor(Ctrl: TControl; var iColor: Integer): Boolean;
var
pt: TPoint;
begin
Result := False;
if not Assigned(frmGMV_SelectColor) then
Application.CreateForm(TfrmGMV_SelectColor, frmGMV_SelectColor);
with frmGMV_SelectColor do
begin
pt := Ctrl.Parent.ClientToScreen(Point(Ctrl.Left, Ctrl.Top));
Left := pt.x;
Top := pt.y + Ctrl.Height;
FSelectedColor := iColor;
if (iColor > -1) and (iColor < lvColors.Items.Count) then
begin
lvColors.Items[iColor].Selected := True;
lvColors.Selected := lvColors.Items[iColor];
end;
ShowModal;
if ModalResult = mrOk then
begin
iColor := FSelectedColor;
Result := True;
end;
end;
end;
procedure TfrmGMV_SelectColor.FormCreate(Sender: TObject);
var
i: integer;
begin
lvColors.SmallImages := ilColors;
for i := 0 to ilColors.Count - 1 do
with lvColors.Items.Add do
begin
Caption := DISPLAYNAMES[i];
ImageIndex := i;
end;
end;
procedure TfrmGMV_SelectColor.lvColorsSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
FSelectedColor := Item.ImageIndex;
end;
procedure TfrmGMV_SelectColor.lvColorsKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
ModalResult := mrCancel;
if Key = VK_RETURN then
ModalResult := mrOk;
end;
procedure TfrmGMV_SelectColor.lvColorsDblClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
end.
|
unit uConexaoBanco;
interface
uses
SqlExpr, inifiles, SysUtils,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Comp.Client,
FireDAC.Comp.UI,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.DataSet,
Data.DB;
type
TConexaoBanco = class
private
FConexaoBanco : TFDConnection;
public
constructor Create;
destructor Destroy; override;
function GetConexao : TFDConnection;
property ConexaoBanco : TFDConnection read GetConexao;
end;
implementation
{ TConexaoBanco }
constructor TConexaoBanco.Create;
var
ArquivoINI,
Servidor,
Porta,
DriverName,
UserName,
PassWord,
Database : String;
LocalServer : Integer;
Configuracoes : TIniFile;
begin
// ArquivoINI := ExtractFilePath(Application.ExeName) + '\config.ini';
if not FileExists(ArquivoINI) then
begin
// MsgErro('Arquivo de Configuração não encontrado'+#13+
// 'Entre em contato com o suporte técnico');
Exit;
end;
// Carregando as informações do arquivo de configurações
Configuracoes := TIniFile.Create(ArquivoINI);
Try
Servidor := Configuracoes.ReadString('Dados', 'Servidor', Servidor);
Porta := Configuracoes.ReadString('Dados', 'Porta', Porta);
DriverName := Configuracoes.ReadString('Dados', 'DriverName', DriverName);
UserName := Configuracoes.ReadString('Dados', 'UserName', UserName);
PassWord := Configuracoes.ReadString('Dados', 'PassWord', PassWord);
Database := Configuracoes.ReadString('Dados', 'Database', Database);
Finally
Configuracoes.Free;
end;
// Descriptografando as informações carregadas
{
Servidor := Crypt('D',Servidor);
UserName := Crypt('D',UserName);
PassWord := Crypt('D',PassWord);
Database := Crypt('D',Database);
}
try
FConexaoBanco := TFDConnection.Create(nil);
FConexaoBanco.LoginPrompt := False;
FConexaoBanco.Params.Add('HostName='+Servidor);
FConexaoBanco.Params.Add('User_Name='+UserName);
FConexaoBanco.Params.Add('Password='+PassWord);
FConexaoBanco.Params.Add('Database='+Database);
FConexaoBanco.Params.Add('DriverID='+DriverName);
// FConexaoBanco.Params.Add('Port='+Porta);
FConexaoBanco.Connected := True;
except
On E : Exception Do
Begin
// MsgErro('Erro ao conectar ao Banco de Dados.'+#13+E.Message);
Exit;
End;
end;
end;
destructor TConexaoBanco.Destroy;
begin
FConexaoBanco.Connected := False;
inherited;
end;
function TConexaoBanco.GetConexao: TFDConnection;
begin
Result := FConexaoBanco;
end;
end.
|
// ##################################
// # TPLVisor - Michel Kunkler 2013 #
// ##################################
(*
Parser
*)
unit TPLParser;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Menus, StrUtils, TPLErrors, TPLBefehle;
type
TParser = class
private
FehlerMemo : TMemo;
procedure KommentarZeilenEntferner(zeile : pstring);
function Tokenizieren(zeile : pstring) : TStringList;
function GetZustand(Zustand : string; Fehler : pstring) : integer;
function GetBefehl(Befehl : string; Fehler : pstring) : CBefehl;
function BefehlsZeilenParser(token : TStringList; Start : integer; Ende : integer) : string;
public
Befehle : array of TBefehl;
constructor Create(FehlerMemo : TMemo);
function Parse(Code : TStrings) : boolean;
end;
implementation
{TParse}
constructor TParser.Create(FehlerMemo : TMemo);
begin
self.FehlerMemo := FehlerMemo;
end;
// Entfernt Kommentare
procedure TParser.KommentarZeilenEntferner(zeile : pstring);
var
i : integer;
LetztesZeichenSlash : boolean;
begin
LetztesZeichenSlash := False;
for i:=1 to Length(zeile^)-1 do
begin
if (Zeile^[i] = '/') and (LetztesZeichenSlash = False) then
LetztesZeichenSlash := True
else if (Zeile^[i] = '/') and (LetztesZeichenSlash = True) then
begin
zeile^ := LeftStr(zeile^,i-2);
break;
end;
end;
end;
function TParser.Tokenizieren(Zeile : pstring) : TStringList;
var
Token : TStringList;
begin
Token := TStringList.Create;
Token.Delimiter := ' ';
Token.DelimitedText := Zeile^;
Result := Token;
end;
function TParser.GetZustand(Zustand : string; Fehler : pstring) : integer;
begin
Try
Result := strtoint(Zustand);
Except
Fehler^ := Format(ParserError.UngZustand, [Zustand]);
Result := -1;
End;
end;
(*
Findet für den jeweiligen Befehlsnamen die passende Befehlsklasse.
Sollte kein Befehl gefunden werden wird die Klasse "TBefehl"
als dummy verwendet.
Befehl : Befehlsnamen
Fehler : Zeiger auf Fehlerstring
*)
function TParser.GetBefehl(Befehl : string; Fehler : pstring) : CBefehl;
var
i : integer;
begin
Result := TBefehl;
for i:=0 to High(BefehlsListe) do
begin
if LowerCase(BefehlsListe[i].Name) = Befehl then
begin
Result := BefehlsListe[i].Befehl;
break;
end;
end;
if Result = TBefehl then
Fehler^ := Format(ParserError.UngBefehl, [Befehl])
end;
(*
Parst eine Befehlszeile.
Arbeitet nach der Idee einer endlichen Maschine.
Token : Tokenisierte Form der Zeile.
Start : Startposition im Code.
Ende : Endposition im Code.
*)
function TParser.BefehlsZeilenParser(Token : TStringList; Start : integer; Ende : integer) : string;
type
TStatus = (SNull, SZustand);
var
Status : TStatus;
Zustand : integer;
Befehl : CBefehl;
i : integer;
Fehler : pstring;
begin
New(Fehler);
Status := SNull;
Zustand := 0;
while Token.Count > 0 do
begin
case Status of
SNull :
begin
Zustand := self.GetZustand(Token[0], Fehler);
Token.Delete(0);
if Zustand < 0 then
break;
Status := SZustand;
end;
SZustand :
begin
Befehl := self.GetBefehl(Token[0], Fehler);
Token.Delete(0);
i := Length(self.Befehle)+1;
SetLength(self.Befehle, i);
self.Befehle[i-1] := Befehl.Create;
self.Befehle[i-1].Zustand := Zustand;
self.Befehle[i-1].Parameter := Token;
self.Befehle[i-1].Fehler := Fehler;
self.Befehle[i-1].Start := Start; // Fuer spaetere markierungen
self.Befehle[i-1].Ende := Ende; // -||-
self.Befehle[i-1].Parsen();
break;
end;
end;
end;
if Status = SNull then
Fehler^ := ParserError.KeinBefehl;
Result := Fehler^;
Dispose(Fehler);
end;
(*
Parst eine Codeingabe.
code : Zeilen eines Codememos.
*)
function TParser.Parse(code : TStrings) : boolean;
var
i : integer;
Position : integer;
Ende : integer;
Zeile : pstring;
Token : TStringList;
Fehler : string;
begin
position := 0;
new(Zeile);
Result := True;
Fehler := '';
for i:=0 to code.Count-1 do
begin
Ende := Position+Length(code[i]);
Zeile^ := code[i];
self.KommentarZeilenEntferner(Zeile); // Kommentare entfernen
if Length(Zeile^) = 0 then
begin
position := Ende+2;
Continue;
end;
Token := self.Tokenizieren(Zeile); // Tokenisieren
Fehler := self.BefehlsZeilenParser(Token,Position,Ende); // Befehle parsen
if Length(Fehler) > 0 then
begin
self.FehlerMemo.Lines.add(Format(ParserError.InZeile+Fehler, [i+1]));
Result := False;
end;
position := Ende+2;
end;
Dispose(Zeile);
end;
end.
|
unit XMLBuilderReg;
interface
uses
Windows, Messages, SysUtils, Classes, WebComp, XMLBuilderComp;
procedure Register;
implementation
uses inetreg, SiteComp, DesignIntf, SItemEdt, WCompReg, WCmpEdit, XMLAdapterBuilder;
type
TWebSiteItemsPropertyEditor = class(TWebPageItemsPropertyEditor)
protected
function GetEditorClass: TPageItemsEditorClass; override;
end;
TAdapterComponentProperty = class(TInterfaceComponentProperty)
protected
function GetGuid: TGuid; override;
end;
TXMLTypeGroupProperty = class(TInterfaceComponentProperty)
protected
function GetGuid: TGuid; override;
end;
{ TAdapterComponentProperty }
function TAdapterComponentProperty.GetGuid: TGuid;
begin
Result := IIdentifyAdapter;
end;
procedure Register;
begin
RegisterComponents('WebSnap', [TXMLBuilder]);
RegisterComponentEditor(TCustomXMLBuilder, TSimpleWebItemsComponentEditor);
RegisterPropertyEditor(TypeInfo(TWebComponentList), TCustomXMLBuilder,
'', TSimpleWebItemsPropertyEditor);
RegisterWebComponents([TXMLForm, TXMLFieldGroup, TXMLGrid, TXMLCommandGroup, TXMLCommandColumn,
TXMLAdapterActionItem, TXMLAdapterFieldItem, TXMLAdapterColumnItem, TXMLAdapterErrors, TXMLApplicationInfo]);
RegisterPropertyEditor(TypeInfo(TComponent), TAbstractXMLAdapterTypeGroup, 'Adapter', TAdapterComponentProperty); { do not localize }
RegisterPropertyEditor(TypeInfo(TComponent), TAbstractXMLAdapterReferenceGroup, 'XMLComponent', TXMLTypeGroupProperty); { do not localize }
end;
{ TWebSiteItemsPropertyEditor }
function TWebSiteItemsPropertyEditor.GetEditorClass: TPageItemsEditorClass;
begin
Result := TSiteItemsEditor;
end;
{ TXMLComponentProperty }
function TXMLTypeGroupProperty.GetGuid: TGuid;
begin
Result := IXMLAdapterTypeGroup;
end;
initialization
finalization
UnregisterWebComponents([TXMLForm, TXMLFieldGroup, TXMLGrid, TXMLCommandGroup, TXMLCommandColumn,
TXMLAdapterActionItem,
TXMLAdapterFieldItem, TXMLAdapterColumnItem, TXMLAdapterErrors, TXMLApplicationInfo]);
end.
|
unit xQuestionInfo;
interface
uses System.SysUtils, System.Classes;
type
TQuestionInfo = class
private
FQid : Integer ;
FQtype : Integer ;
FQname : String ;
FQCode : string ;
FQdescribe : String ;
FQanswer : String ;
FQexplain : String ;
FQremark1 : String ;
FQremark2 : String ;
FSortID: Integer;
public
constructor Create;
/// <summary>
/// 复制对象
/// </summary>
procedure Assign(Source : TQuestionInfo);
/// <summary>
/// 题库ID
/// </summary>
property SortID : Integer read FSortID write FSortID;
/// <summary>
/// 考题编号
/// </summary>
property QID : Integer read FQid write FQid ;
/// <summary>
/// 考题类型
/// </summary>
property QType : Integer read FQtype write FQtype ;
/// <summary>
/// 类型名称
/// </summary>
function QTypeString : string; virtual;
/// <summary>
/// 考题名称
/// </summary>
property QName : String read FQname write FQname ;
/// <summary>
/// 考题编码
/// </summary>
property QCode : String read FQCode write FQCode;
/// <summary>
/// 考题描述
/// </summary>
property QDescribe : String read FQdescribe write FQdescribe;
/// <summary>
/// 考题答案
/// </summary>
property QAnswer : String read FQanswer write FQanswer ;
/// <summary>
/// 考题详解
/// </summary>
property QExplain : String read FQexplain write FQexplain ;
/// <summary>
/// 考题备注1
/// </summary>
property QRemark1 : String read FQremark1 write FQremark1 ;
/// <summary>
/// 考题备注2
/// </summary>
property QRemark2 : String read FQremark2 write FQremark2 ;
end;
implementation
{ TQuestionInfo }
procedure TQuestionInfo.Assign(Source: TQuestionInfo);
begin
FSortID := Source.SortID ;
FQid := Source.Qid ;
FQtype := Source.Qtype ;
FQname := Source.Qname ;
FQCode := Source.FQCode ;
FQdescribe := Source.Qdescribe;
FQanswer := Source.Qanswer ;
FQexplain := Source.Qexplain ;
FQremark1 := Source.Qremark1 ;
FQremark2 := Source.Qremark2 ;
end;
constructor TQuestionInfo.Create;
begin
FQid := -1;
FQtype := -1;
FQname := '';
FQCode := '';
FQdescribe := '';
FQanswer := '';
FQexplain := '';
FQremark1 := '';
FQremark2 := '';
end;
function TQuestionInfo.QTypeString: string;
begin
Result := '类型' + IntToStr(FQtype);
end;
end.
|
unit UNewPedidoAWBDetail;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
DBGridEh,
Data.DB,
MemDS,
DBAccess,
Uni,
Vcl.StdCtrls,
Vcl.Mask,
DBCtrlsEh,
DBLookupEh,
UFrameSave;
type
TFNewPedidoAWBDetail = class(TForm)
QueryMarking: TUniQuery;
dsMarking: TDataSource;
lblMarking: TLabel;
edtMarking: TDBLookupComboboxEh;
edtTrack: TDBLookupComboboxEh;
lblTrack: TLabel;
dsTrack: TDataSource;
QueryTrack: TUniQuery;
FrameSave1: TFrameSave;
edtПорядок: TDBNumberEditEh;
edtType: TEdit;
edtFITO: TDBLookupComboboxEh;
lblFITO: TLabel;
QueryFITO: TUniQuery;
dsFITO: TDataSource;
edtPrikul: TDBLookupComboboxEh;
lblPricul: TLabel;
QueryPricul: TUniQuery;
dsPricul: TDataSource;
procedure edtMarkingKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtПорядокChange(Sender: TObject);
procedure FrameSave1btnSaveClick(Sender: TObject);
private
{ Private declarations }
public
s_date_pedido_awb_new: TDate;
procedure ShowFITO(id_locate: Integer = 0);
procedure ShowMarking(id_locate: Integer = 0);
procedure ShowPricul(id_locate: Integer = 0);
procedure ShowTrack(id_locate: Integer = 0);
{ Public declarations }
end;
var
FNewPedidoAWBDetail: TFNewPedidoAWBDetail;
implementation
{$R *.dfm}
procedure TFNewPedidoAWBDetail.edtMarkingKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
edtTrack.SetFocus;
end;
end;
procedure TFNewPedidoAWBDetail.edtПорядокChange(Sender: TObject);
begin
edtType.Text := 'guia hija' + edtПорядок.Text;
end;
procedure TFNewPedidoAWBDetail.FrameSave1btnSaveClick(Sender: TObject);
begin
FrameSave1.btnSaveClick(Sender);
Close;
end;
procedure TFNewPedidoAWBDetail.ShowFITO(id_locate: Integer = 0);
begin
with QueryFITO do
begin
SQL.Clear;
SQL.Add(' SELECT * from "документы"."фито" ');
Open;
edtFITO.KeyValue := id_locate;
end;
end;
procedure TFNewPedidoAWBDetail.ShowMarking(id_locate: Integer = 0);
begin
with QueryMarking do
begin
SQL.Clear;
SQL.Add(' SELECT dz."код_маркировки",');
SQL.Add(' m.uni_name');
SQL.Add(' FROM "документы"."заказы" dz');
SQL.Add(' INNER JOIN "маркировки"."маркировки" m ON (dz."код_маркировки" = m.id)');
SQL.Add(' where dz."дата_вылета" = :d');
ParamByName('d').Value := s_date_pedido_awb_new;
Open;
edtMarking.KeyValue := id_locate;
end;
end;
procedure TFNewPedidoAWBDetail.ShowPricul(id_locate: Integer = 0);
begin
with QueryPricul do
begin
SQL.Clear;
SQL.Add(' SELECT * from "прикулинг"."агенства" ');
Open;
edtPrikul.KeyValue := id_locate;
end;
end;
procedure TFNewPedidoAWBDetail.ShowTrack(id_locate: Integer = 0);
begin
with QueryTrack do
begin
SQL.Clear;
SQL.Add(' SELECT * from траки.траки ');
Open;
edtTrack.KeyValue := id_locate;
end;
end;
end.
|
unit uMenu;
interface
uses
SysUtils;
type TMenu = class
private
programmeNumber : integer;
starters, mains, dessert, details, fullText : string;
public
constructor Create(progNo: integer);
function getStarters : string;
function getMains : string;
function getDessert : string;
function getMeetingDetails : string;
procedure setAllDetails;
end;
implementation
uses
programmesScreen;
{ TMenu }
{The programme number is provided by the programmeScreen and fed in to allow
the menu class to be instantiated. Upon creation, the code checks if a text
file already exists in the programmes folder within the project folder. If it
does, then the contents is read out using file I/O and appended to a single
long string. If the file does not exist, then the contents of of the programme
screen's relevant components are read into one long single string.}
constructor TMenu.Create(progNo: integer);
var
inFile : textfile;
line : string;
begin
programmeNumber := progNo;
fullText := '';
if FileExists('Programmes\programme_'
+ intToStr(programmeNumber) + '.txt') then
begin
AssignFile(inFile, 'Programmes\programme_'
+ intToStr(programmeNumber) + '.txt');
Reset(inFile);
While not EOF(inFile) do
begin
ReadLn(inFile,line);
fullText := fullText + line + #10;
end;
CloseFile(inFile);
end
else
begin
fullText := '1.' + programmesScreen.frmProgrammes.rchStarters.Text
+ '2.' + programmesScreen.frmProgrammes.rchMains.Text + '3.'
+ programmesScreen.frmProgrammes.rchDessert.Text + '4.'
+ programmesScreen.frmProgrammes.rchCoverDetails.Text;
end;
end;
{A function which locates the position of dessert in the string based on its
marker number and then extracts the text describing it. The string extracted
is returned as a result.}
function TMenu.getDessert: string;
var
dessert : string;
i : integer;
begin
dessert := '';
for i := (Pos('3.', fullText)+2) to (Pos('4.',fullText)-1) do
begin
dessert := dessert + fullText[i];
end;
Result := dessert;
end;
{A function which locates the position of mains in the string based on its
marker number and then extracts the text describing it. The string extracted
is returned as a result.}
function TMenu.getMains: string;
var
mains : string;
i : integer;
begin
mains := '';
for i := (Pos('2.', fullText)+2) to (Pos('3.',fullText)-1) do
begin
mains := mains + fullText[i];
end;
Result := mains;
end;
{A function which locates the position of menu details in the string based on
its marker number and then extracts the text describing it. The string
extracted is returned as a result.}
function TMenu.getMeetingDetails: string;
var
details : string;
i : integer;
begin
details := '';
for i := (Pos('4.', fullText)+2) to length(fullText) do
begin
details := details + fullText[i];
end;
Result := details;
end;
{A function which locates the position of starters in the string based on its
marker number and then extracts the text describing it. The string extracted
is returned as a result.}
function TMenu.getStarters: string;
var
starters : string;
i : integer;
begin
starters := '';
for i := (Pos('1.', fullText)+2) to (Pos('2.',fullText)-1) do
begin
starters := starters + fullText[i];
end;
Result := starters;
end;
{This procedure copies the data that has been entered into the richedit boxes
on the programme screen and concatenates it into a single long string.
The string is then written to an existing text file designated to that
programme. If one does not exist then it is created and written to.}
procedure TMenu.setAllDetails;
var
inFile : textFile;
line : string;
begin
fullText := '1.' + programmesScreen.frmProgrammes.rchStarters.Text +
'2.' + programmesScreen.frmProgrammes.rchMains.Text + '3.' +
programmesScreen.frmProgrammes.rchDessert.Text + '4.' +
programmesScreen.frmProgrammes.rchCoverDetails.Text;
Assign(inFile, 'Programmes/programme_' + intToStr(programmeNumber) +
'.txt');
Rewrite(inFile);
WriteLn(inFile, fullText);
CloseFile(inFile);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ NSAPI to ISAPI server application components }
{ }
{ Copyright (c) 1997-2001, Borland Software Corporation }
{ }
{*******************************************************}
unit NSToIS;
interface
uses SysUtils, Windows, Classes, Isapi2, Nsapi,
SyncObjs;
type
TISAPIApplicationList = class;
TISAPIApplication = class
private
FModule: THandle;
FFileName: string;
FVersionInfo: THSE_VERSION_INFO;
FOwner: TISAPIApplicationList;
public
GetExtensionVersion: TGetExtensionVersion;
HTTPExtensionProc: THTTPExtensionProc;
TerminateExtension: TTerminateExtension;
constructor Create(AOWner: TISAPIApplicationList; const AFileName: string);
destructor Destroy; override;
procedure Load;
procedure Unload(Ask: Boolean);
property VersionInfo: THSE_VERSION_INFO read FVersionInfo;
end;
EISAPIException = class(Exception);
TISAPISession = class
private
{ ISAPI Interface }
FECB: TEXTENSION_CONTROL_BLOCK;
FISAPIApplication: TISAPIApplication;
FPathTranslated: string;
{ NSAPI Interface }
Fpb: PPblock;
Fsn: PSession;
Frq: PRequest;
Fenv: PPCharArray;
{ HSE_REQ_DONE_WITH_SESSION event }
FEvent: TEvent;
{ ISAPI Service functions }
function GetServerVariable(VariableName: PChar; Buffer: Pointer; var Size: DWORD): Boolean;
function WriteClient(Buffer: Pointer; var Bytes: DWORD): Boolean;
function ReadClient(Buffer: Pointer; var Size: DWORD): Boolean;
function ServerSupportFunction(HSERequest: DWORD; Buffer: Pointer;
Size: LPDWORD; DataType: LPDWORD): Boolean;
public
constructor Create(pb: PPblock; sn: PSession; rq: PRequest;
ISAPIApplication: TISAPIApplication);
destructor Destroy; override;
procedure ProcessExtension;
end;
TISAPIApplicationList = class
private
FList: TList;
FCriticalSection: TCriticalSection;
FLogfd: SYS_FILE;
procedure AddApplication(ISAPIApplication: TISAPIApplication);
procedure ClearApplications;
function FindApplication(const AFileName: string): TISAPIApplication;
procedure RemoveApplication(ISAPIApplication: TISAPIApplication);
public
constructor Create;
destructor Destroy; override;
function LoadApplication(const AFileName: string): TISAPIApplication;
function InitLog(pb: PPblock; sn: PSession; rq: Prequest): Integer;
procedure LogMessage(const Fmt: string; const Params: array of const);
{ function NewSession(ISAPIApplication: TISAPIApplication; pb: PPBlock;
sn: PSession; rq: PRequest): TISAPISession;}
end;
var
ISAPIApplicationList: TISAPIApplicationList = nil;
procedure LogMessage(const Fmt: string; const Params: array of const);
function UnixPathToDosPath(const Path: string): string;
function DosPathToUnixPath(const Path: string): string;
procedure InitISAPIApplicationList;
procedure DoneISAPIAPplicationList;
implementation
resourcestring
sInvalidISAPIApp = 'Invalid ISAPI application: %s';
sUnSupportedISAPIApp = 'Unsupported ISAPI Application version: %.8x';
sGEVFailed = 'Call to GetExtensionVersion FAILED. Error Code: %d';
sErrorLoadingISAPIApp = 'Error loading ISAPI Application: %s';
sInvalidRedirectParam = 'Invalid Redirect parameter';
sISAPIAppError = 'ISAPI Application Error';
function TranslateChar(const Str: string; FromChar, ToChar: Char): string;
var
I: Integer;
begin
Result := Str;
for I := 1 to Length(Result) do
if Result[I] = FromChar then
Result[I] := ToChar
else if Result[I] = '?' then Break;
end;
function UnixPathToDosPath(const Path: string): string;
begin
Result := TranslateChar(Path, '/', '\');
end;
function DosPathToUnixPath(const Path: string): string;
begin
Result := TranslateChar(Path, '\', '/');
end;
procedure LogMessage(const Fmt: string; const Params: array of const);
begin
ISAPIApplicationList.LogMessage(Fmt, Params);
end;
{ TISAPIApplication }
constructor TISAPIApplication.Create(AOwner: TISAPIApplicationList;
const AFileName: string);
begin
FFileName := AFileName;
FOwner := AOwner;
FOwner.AddApplication(Self);
Load;
end;
destructor TISAPIApplication.Destroy;
begin
Unload(False);
FOwner.RemoveApplication(Self);
inherited Destroy;
end;
procedure TISAPIApplication.Load;
var
ErrorMode: Integer;
begin
ErrorMode := SetErrorMode(SEM_NOOPENFILEERRORBOX);
try
FModule := LoadLibrary(PChar(FFileName));
if FModule <> 0 then
begin
@GetExtensionVersion := GetProcAddress(FModule, 'GetExtensionVersion'); { do not localize }
@HTTPExtensionProc := GetProcAddress(FModule, 'HttpExtensionProc'); { do not localize }
@TerminateExtension := GetProcAddress(FModule, 'TerminateExtension'); { do not localize }
if not Assigned(GetExtensionVersion) or not Assigned(HTTPExtensionProc) then
raise EISAPIException.CreateResFmt(@sInvalidISAPIApp, [FFileName]);
if GetExtensionVersion(FVersionInfo) then
begin
LogMessage('%s: Version: $%.8x'#13#10, [FFileName, FVersionInfo.dwExtensionVersion]); { do not localize }
if (HiWord(FVersionInfo.dwExtensionVersion) <> $0001) and
(HiWord(FVersionInfo.dwExtensionVersion) <> $0002) then
raise EISAPIException.CreateResFmt(@sUnsupportedISAPIApp,
[FVersionInfo.dwExtensionVersion]);
end else
raise EISAPIException.CreateResFmt(@sGEVFailed, [GetLastError]);
end else
raise EISAPIException.CreateResFmt(@sErrorLoadingISAPIApp, [FFileName]);
finally
SetErrorMode(ErrorMode);
end;
end;
procedure TISAPIApplication.Unload(Ask: Boolean);
const
HSE_TERM: array[Boolean] of DWORD = (HSE_TERM_ADVISORY_UNLOAD, HSE_TERM_MUST_UNLOAD);
var
CanUnload: Boolean;
begin
if FModule > 32 then
begin
CanUnload := True;
if Assigned(TerminateExtension) then
CanUnload := not Ask or TerminateExtension(HSE_TERM[Ask]);
if CanUnload and FreeLibrary(FModule) then
FModule := 0;
end;
end;
function GetServerVariableProc(ConnID: HConn; VariableName: PChar;
Buffer: Pointer; var Size: DWORD): BOOL; stdcall;
begin
if ConnID <> 0 then
Result := TISAPISession(ConnID).GetServerVariable(VariableName, Buffer, Size)
else
begin
Result := False;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
function WriteClientProc(ConnID: HConn; Buffer: Pointer; var Bytes: DWORD;
dwReserved: DWORD): BOOL; stdcall;
begin
if ConnID <> 0 then
Result := TISAPISession(ConnID).WriteClient(Buffer, Bytes)
else
begin
Result := False;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
function ReadClientProc(ConnID: HConn; Buffer: Pointer;
var Size: DWORD): BOOL; stdcall;
begin
if ConnID <> 0 then
Result := TISAPISession(ConnID).ReadClient(Buffer, Size)
else
begin
Result := False;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
function ServerSupportProc(ConnID: HConn; HSERequest: DWORD; Buffer: Pointer;
Size: LPDWORD; DataType: LPDWORD): BOOL; stdcall;
begin
if ConnID <> 0 then
Result := TISAPISession(ConnID).ServerSupportFunction(HSERequest, Buffer,
Size, DataType)
else
begin
Result := False;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
function MakeValid(Str: PChar): PChar;
begin
if Str = nil then
Result := ''
else Result := Str;
end;
const
DocumentMoved =
'<head><title>Document moved</title></head>' + { do not localize }
'<body><h1>Object Moved</h1>' + { do not localize }
'This document may be found <a HREF="%s">here</a></body>'#13#10; { do not localize }
// Diagnostic purposes only... Do not resource these strings
function GetObjectConfig(os: PHttpdObjSet): string;
var
obj: PHttpdObject;
dt: PDtable;
dir: PDirective;
I, J, K: Integer;
begin
Result := Format('os: $%p'#13#10, [os]); { do not localize }
try
if os <> nil then
begin
K := 0;
obj := PPointerList(os.obj)^[K];
Result := Format('%sobj: $%p'#13#10, [Result, obj]); { do not localize }
if obj <> nil then
begin
while obj <> nil do
begin
Result := Format('%sobj.name: $%p'#13#10, [Result, obj.name]); { do not localize }
Result := Format('%sRoot Object: %s (%s)'#13#10, [Result, 'default', { do not localize }
NSstr2String(pblock_pblock2str(obj.name, nil))]);
dt := obj.dt;
Result := Format('%sobj.dt: $%p'#13#10'obj.nd: %d'#13#10, [Result, dt, obj.nd]); { do not localize }
for I := 0 to obj.nd - 1 do
begin
dir := dt.inst;
Result := Format('%sdt.inst: $%p'#13#10'dt.ni: %d'#13#10, [Result, dir, dt.ni]); { do not localize }
for J := 0 to dt.ni - 1 do
begin
if dir <> nil then
begin
if dir.param <> nil then
Result := Format('%s Param: %s'#13#10, [Result, { do not localize }
NSstr2String(pblock_pblock2str(dir.param, nil))])
else Result := Format('%s Param:'#13#10, [Result]); { do not localize }
if dir.client <> nil then
Result := Format('%s Client: %s'#13#10, [Result, { do not localize }
NSstr2String(pblock_pblock2str(dir.client, nil))])
else Result := Format('%s Client:'#13#10, [Result]); { do not localize }
end;
Inc(dir);
end;
Inc(dt);
end;
Inc(K);
obj := PPointerList(os.obj)^[K];
end;
end else Result := 'root_object not found'; { do not localize }
end else Result := 'std_os Objset not found'; { do not localize }
except
on E: Exception do
Result := Format('%sException %s: %s'#13#10, [Result, E.ClassName, E.Message]);
end;
end;
{ TISAPISession }
constructor TISAPISession.Create(pb: PPblock; sn: PSession; rq: PRequest;
ISAPIApplication: TISAPIApplication);
var
Temp: PChar;
begin
Fpb := pb;
Fsn := sn;
Frq := rq;
FISAPIApplication := ISAPIApplication;
FEvent := TSimpleEvent.Create;
with FECB do
begin
cbSize := SizeOf(FECB);
dwVersion := MAKELONG(HSE_VERSION_MINOR, HSE_VERSION_MAJOR);
ConnID := THandle(Self);
lpszMethod := MakeValid(pblock_findval('method', rq.reqpb)); { do not localize }
lpszQueryString := MakeValid(pblock_findval('query', rq.reqpb)); { do not localize }
lpszPathInfo := MakeValid(pblock_findval('path-info', rq.vars)); { do not localize }
FPathTranslated := UnixPathToDosPath(NSstr2String(
pblock_findval('path-translated', rq.vars))); { do not localize }
lpszPathTranslated := PChar(FPathTranslated);
lpszContentType := MakeValid(pblock_findval('content-type', rq.headers)); { do not localize }
Temp := pblock_findval('content-length', rq.headers); { do not localize }
try
cbTotalBytes := StrToIntDef(MakeValid(Temp), 0);
finally
system_free(Temp);
end;
with Fsn.inbuf^ do
begin
while (inbuf[pos] in [#13,#10]) and (pos < cursize) do Inc(pos);
cbAvailable := cursize - pos;
if cbTotalBytes < cbAvailable then
cbTotalBytes := cbAvailable;
GetMem(lpbData, cbAvailable);
Move(inbuf[pos], lpbData^, cbAvailable);
end;
GetServerVariable := GetServerVariableProc;
WriteClient := WriteClientProc;
ReadClient := ReadClientProc;
ServerSupportFunction := ServerSupportProc;
end;
end;
destructor TISAPISession.Destroy;
procedure FreeStr(Str: PChar);
begin
if (Str <> nil) and (Str^ <> #0) then
system_free(Str);
end;
begin
with FECB do
begin
FreeStr(lpszMethod);
FreeStr(lpszQueryString);
FreeStr(lpszPathInfo);
FreeStr(lpszContentType);
FreeMem(lpbData);
end;
if Fenv <> nil then util_env_free(Fenv);
FEvent.Free;
inherited Destroy;
end;
function TISAPISession.GetServerVariable(VariableName: PChar; Buffer: Pointer;
var Size: DWORD): Boolean;
var
HeaderName: string;
HeaderValue: PChar;
procedure InitEnv;
var
Value: PChar;
procedure AddToEnv(var Env: PPCharArray; Name, Value: PChar);
var
Pos: Integer;
begin
Env := util_env_create(Env, 1, Pos);
Env[Pos] := util_env_str(Name, Value);
Env[Pos+1] := nil;
end;
begin
if Fenv = nil then
begin
Fenv := http_hdrs2env(Frq.headers);
Value := pblock_findval('content-length', Frq.headers); { do not localize }
try
if Value <> nil then
AddToEnv(Fenv, 'HTTP_CONTENT_LENGTH', Value); { do not localize }
finally
system_free(Value);
end;
Value := pblock_findval('content-type', Frq.headers); { do not localize }
try
if Value <> nil then
AddToEnv(Fenv, 'HTTP_CONTENT_TYPE', Value); { do not localize }
finally
system_free(Value);
end;
Value := pblock_findval('authorization', Frq.headers); { do not localize }
try
if Value <> nil then
AddToEnv(Fenv, 'HTTP_AUTHORIZATION', Value); { do not localize }
finally
system_free(Value);
end;
end;
end;
procedure CopyValue(Value: PChar; var Result: Boolean);
begin
Result := False;
PChar(Buffer)[0] := #0;
if Value <> nil then
begin
StrLCopy(Buffer, Value, Size - 1);
if Size - 1 < StrLen(Value) then
SetLastError(ERROR_INSUFFICIENT_BUFFER)
else Result := True;
Size := StrLen(Value) + 1;
end else SetLastError(ERROR_NO_DATA);
end;
function AllHeaders: string;
var
P: PPCharArray;
I: Integer;
begin
InitEnv;
P := Fenv;
Result := '';
I := 0;
while P^[I] <> nil do
begin
Result := Format('%s%s'#13#10, [Result, TranslateChar(P^[I], '=', ':')]);
Inc(I);
end;
end;
begin
// Check if this is a request for an HTTP header
if VariableName = nil then VariableName := 'BAD'; { do not localize }
LogMessage('GetServerVariable(%s, $%p, %d)'#13#10, [VariableName, Buffer, Size]); { do not localize }
HeaderValue := nil;
HeaderName := VariableName;
if shexp_casecmp(VariableName, 'HTTP_*') = 0 then { do not localize }
begin
InitEnv;
CopyValue(util_env_find(Fenv, VariableName), Result);
Exit;
end else
begin
if CompareText('CONTENT_LENGTH', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('content-length', Frq.headers) { do not localize }
else if CompareText('CONTENT_TYPE', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('content-type', Frq.headers) { do not localize }
else if CompareText('PATH_INFO', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('path-info', Frq.vars) { do not localize }
else if CompareText('PATH_TRANSLATED', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('path-translated', Frq.vars) { do not localize }
else if CompareText('QUERY_STRING', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('query', Frq.reqpb) { do not localize }
else if CompareText('REMOTE_ADDR', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('ip', Fsn.client) { do not localize }
else if CompareText('REMOTE_HOST', HeaderName) = 0 then { do not localize }
HeaderValue := session_dns(Fsn)
else if CompareText('REQUEST_METHOD', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('method', Frq.reqpb) { do not localize }
else if CompareText('SCRIPT_NAME', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('uri', Frq.reqpb) { do not localize }
else if CompareText('SERVER_NAME', HeaderName) = 0 then { do not localize }
HeaderValue := system_version
else if CompareText('ALL_HTTP', HeaderName) = 0 then { do not localize }
begin
CopyValue(PChar(AllHeaders), Result);
Exit;
end else if CompareText('SERVER_PORT', HeaderName) = 0 then { do not localize }
begin
CopyValue(PChar(IntToStr(conf_getglobals.Vport)), Result);
Exit
end else if CompareText('SERVER_PROTOCOL', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('protocol', Frq.reqpb) { do not localize }
else if CompareText('URL', HeaderName) = 0 then { do not localize }
HeaderValue := pblock_findval('uri', Frq.reqpb) { do not localize }
else if CompareText('OBJECT_CONFIG', HeaderName) = 0 then { do not localize }
begin
CopyValue(PChar(Format('<pre>%s</pre><br>', [GetObjectConfig(Frq.os)])), Result); { do not localize }
Exit;
end else
begin
Result := False;
SetLastError(ERROR_INVALID_INDEX);
end;
end;
try
CopyValue(HeaderValue, Result);
finally
system_free(HeaderValue);
end;
end;
function TISAPISession.WriteClient(Buffer: Pointer; var Bytes: DWORD): Boolean;
var
nWritten: DWORD;
begin
LogMessage('WriteClient($%p, %d)'#13#10, [Buffer, Bytes]); { do not localize }
nWritten := net_write(Fsn.csd, Buffer, Bytes);
Result := not (nWritten < Bytes) and not (nWritten = DWORD(IO_ERROR));
Bytes := nWritten;
end;
function TISAPISession.ReadClient(Buffer: Pointer; var Size: DWORD): Boolean;
var
nBuf, nRemaining: DWORD;
begin
LogMessage('ReadClient($%p, %d)'#13#10, [Buffer, Size]); { do not localize }
nRemaining := Size;
while nRemaining > 0 do
begin
with Fsn.inbuf^ do
if pos < cursize then
begin
nBuf := cursize - pos;
if nBuf > Size then nBuf := Size;
Move(inbuf[pos], Buffer^, nBuf);
Inc(pos, nBuf);
Dec(nRemaining, nBuf);
Inc(Integer(Buffer), nBuf);
end else
begin
nBuf := net_read(Fsn.csd, Buffer, nRemaining, NET_READ_TIMEOUT);
if nBuf = DWORD(IO_ERROR) then Break;
Inc(pos, nBuf);
Dec(nRemaining, nBuf);
end;
end;
if nRemaining = 0 then
Result := True
else Result := False;
Size := Size - nRemaining;
end;
function TISAPISession.ServerSupportFunction(HSERequest: DWORD; Buffer: Pointer;
Size: LPDWORD; DataType: LPDWORD): Boolean;
var
Content: PChar;
ContentLen: Integer;
ContentStr: string;
// This function will parse out any ISAPI application supplied headers and
// place them into the appropriate parameter block.
function SkipHeaders(Content: PChar): PChar;
var
T: array[0..REQ_MAX_LINE - 1] of Char;
pb: PPblock;
NetBuf: TNetBuf;
begin
if Content <> nil then
begin
pb := pblock_create(10);
try
FillChar(NetBuf, SizeOf(NetBuf), 0);
with NetBuf do
begin
cursize := StrLen(Content);
maxSize := curSize;
inbuf := Content;
end;
http_scan_headers(nil, @NetBuf, T, pb);
pblock_copy(pb, Frq.srvhdrs);
// Skip past the headers if present
Inc(Content, NetBuf.pos);
Result := Content;
finally
pblock_free(pb);
end;
end else Result := Content;
end;
procedure SetStatus(StatusStr: PChar);
var
StatusCode: Integer;
I: Integer;
begin
if StatusStr = nil then
StatusCode := PROTOCOL_OK
else
begin
StatusCode := StrToIntDef(Copy(StatusStr, 1, 3), PROTOCOL_OK);
for I := 0 to 3 do
begin
if StatusStr[0] = #0 then Break;
Inc(StatusStr);
end;
end;
http_status(Fsn, Frq, StatusCode, StatusStr);
end;
begin
case HSERequest of
HSE_REQ_SEND_RESPONSE_HEADER:
begin
if DataType <> nil then
Content := PChar(Datatype)
else Content := #0;
if Size <> nil then
LogMessage('ServerSupportFunction(HSE_REQ_SEND_RESPONSE_HEADER' + { do not localize }
', $%p, %d, %s)'#13#10, [Buffer, Size^, Content])
else LogMessage('ServerSupportFunction(HSE_REQ_SEND_RESPONSE_HEADER' + { do not localize }
', $%p, nil, %s)'#13#10, [Buffer, Content]);
SetStatus(PChar(Buffer));
param_free(pblock_remove('content-type', Frq.srvhdrs)); { do not localize }
param_free(pblock_remove('content-length', Frq.srvhdrs)); { do not localize }
Content := SkipHeaders(PChar(DataType));
ContentLen := StrLen(Content);
Result := True;
if http_start_response(Fsn, Frq) <> REQ_NOACTION then
begin
if (Content <> nil) and (Content[0] <> #0) then
if net_write(Fsn.csd, Content, ContentLen) < ContentLen then
Result := False;
end else Result := False;
end;
HSE_REQ_SEND_URL_REDIRECT_RESP:
begin
if Size <> nil then
LogMessage('ServerSupportFunction(HSE_REQ_SEND_URL_REDIRECT_RESP' + { do not localize }
', %s, %d)'#13#10, [PChar(Buffer), Size^])
else LogMessage('ServerSupportFunction(HSE_REQ_SEND_URL_REDIRECT_RESP' + { do not localize }
', %s, nil)'#13#10, [PChar(Buffer)]);
http_status(Fsn, Frq, PROTOCOL_REDIRECT, 'Object moved'); { do not localize }
param_free(pblock_remove('content-type', Frq.srvhdrs)); { do not localize }
param_free(pblock_remove('content-length', Frq.srvhdrs)); { do not localize }
if Buffer <> nil then
begin
pblock_nvinsert('Location', PChar(Buffer), Frq.srvhdrs); { do not localize }
ContentStr := Format(DocumentMoved, [PChar(Buffer)]);
ContentLen := Length(ContentStr);
pblock_nvinsert('content-type', 'text/html', Frq.srvhdrs); { do not localize }
pblock_nninsert('content-length', ContentLen, Frq.srvhdrs); { do not localize }
Result := True;
if http_start_response(Fsn, Frq) <> REQ_NOACTION then
begin
if net_write(Fsn.csd, PChar(ContentStr), ContentLen) < ContentLen then
Result := False;
end else Result := False;
end else raise EISAPIException.CreateRes(@sInvalidRedirectParam);
end;
HSE_REQ_SEND_URL:
begin
Result := False;
end;
HSE_REQ_MAP_URL_TO_PATH:
begin
Result := True;
Content := request_translate_uri(Buffer, Fsn);
if Content <> nil then
try
StrPLCopy(Buffer, Content, Size^ - 1);
if Size^ - 1 < StrLen(Content) + 1 then
begin
Result := False;
SetLastError(ERROR_INSUFFICIENT_BUFFER);
end;
finally
system_free(Content);
end else
begin
Result := False;
SetLastError(ERROR_NO_DATA);
end;
end;
HSE_REQ_DONE_WITH_SESSION:
begin
FEvent.SetEvent;
Result := True;
end;
else
Result := False;
end;
end;
procedure TISAPISession.ProcessExtension;
begin
LogMessage('ProcessExtension -- Application: %s'#13#10, [FISAPIApplication.FFileName]); { do not localize }
if Assigned(FISAPIApplication.HTTPExtensionProc) then
case FISAPIApplication.HTTPExtensionProc(FECB) of
HSE_STATUS_ERROR: raise EISAPIException.CreateRes(@sISAPIAppError);
HSE_STATUS_PENDING: FEvent.WaitFor(INFINITE);
end;
end;
{ TISAPIApplicationList }
constructor TISAPIApplicationList.Create;
begin
FList := TList.Create;
FCriticalSection := TCriticalSection.Create;
FLogfd := SYS_ERROR_FD;
end;
destructor TISAPIApplicationList.Destroy;
begin
ClearApplications;
FList.Free;
FCriticalSection.Free;
if FLogfd <> SYS_ERROR_FD then
system_fclose(FLogfd);
inherited Destroy;
end;
procedure TISAPIApplicationList.AddApplication(ISAPIApplication: TISAPIApplication);
begin
FCriticalSection.Enter;
try
if FList.IndexOf(ISAPIApplication) = -1 then
FList.Add(ISAPIApplication);
finally
FCriticalSection.Leave;
end;
end;
procedure TISAPIApplicationList.ClearApplications;
var
ISAPIApplication: TISAPIApplication;
begin
FCriticalSection.Enter;
try
while FList.Count > 0 do
begin
ISAPIApplication := FList.Last;
FList.Remove(ISAPIApplication);
ISAPIApplication.Free;
end;
finally
FCriticalSection.Leave;
end;
end;
function TISAPIApplicationList.FindApplication(const AFileName: string): TISAPIApplication;
var
I: Integer;
begin
FCriticalSection.Enter;
try
for I := 0 to FList.Count - 1 do
begin
Result := FList[I];
with Result do
if CompareText(AFileName, FFileName) = 0 then
Exit;
end;
Result := nil;
finally
FCriticalSection.Leave;
end;
end;
function TISAPIApplicationList.InitLog(pb: PPblock; sn: PSession; rq: Prequest): Integer;
var
fn: Pchar;
begin
fn := pblock_findval('file', pb); { do not localize }
try
if fn = nil then
begin
pblock_nvinsert('error', 'TISAPIApplicationList: please supply a file name', pb); { do not localize }
Result := REQ_ABORTED;
Exit;
end;
FLogfd := system_fopenWA(fn);
if FLogfd = SYS_ERROR_FD then
begin
pblock_nvinsert('error', 'TISAPIApplicationList: please supply a file name', pb); { do not localize }
Result := REQ_ABORTED;
Exit;
end;
finally
system_free(fn);
end;
{* Close log file when server is restarted *}
Result := REQ_PROCEED;
end;
function TISAPIApplicationList.LoadApplication(const AFileName: string): TISAPIApplication;
begin
Result := FindApplication(AFileName);
if Result = nil then
Result := TISAPIApplication.Create(Self, AFileName);
end;
procedure TISAPIApplicationList.LogMessage(const Fmt: string; const Params: array of const);
var
logmsg: string;
len: Integer;
begin
if FLogfd <> SYS_ERROR_FD then
begin
FmtStr(logmsg, Fmt, Params);
len := Length(logmsg);
system_fwrite_atomic(FLogfd, PChar(logmsg), len);
end;
end;
procedure TISAPIApplicationList.RemoveApplication(ISAPIApplication: TISAPIApplication);
begin
FCriticalSection.Enter;
try
if FList.IndexOf(ISAPIApplication) > -1 then
FList.Remove(ISAPIApplication);
finally
FCriticalSection.Leave;
end;
end;
procedure InitISAPIApplicationList;
begin
if ISAPIApplicationList = nil then
ISAPIApplicationList := TISAPIApplicationList.Create;
end;
procedure DoneISAPIAPplicationList;
begin
ISAPIApplicationList.Free;
ISAPIApplicationList := nil;
end;
end.
|
Unit PathInfo;
Interface
uses DirectoryStat,
SysUtils,
InternalTypes;
type
tPIState = (tpisNone, tpisConfigured, tpisFound, tpisFilled, tpisExcluded);
TPathInfo = class
private
fPathName : WideString;
fState : tPIState;
fGroupName : String;
fSpecificName : String;
fDirStats : tDirectoryStat;
public
constructor Create(PathN : WideString);
destructor Destroy; override;
function AddSizeExtension(info : TSearchRec; LimIndex : Integer; TypeExt : String; KeepUnknown: boolean; GpName, SpName : string): UInt64;
function dumpData() : AnsiString;
function dumpJSON() : AnsiString;
class function CompareNode(Item1 : TPathInfo; Item2 : TPathInfo) : Longint;
property PathName: WideString read FPathName write FPathName;
property State: tPIState read FState write FState;
property GroupName: String read FGroupName write FGroupName;
property SpecificName: String read FSpecificName write FSpecificName;
property DirStats: tDirectoryStat read FDirStats;
end;
Implementation
uses typinfo;
constructor TPathInfo.Create(PathN : WideString);
begin
fPathName := NormalizePath(PathN);
fDirStats := tDirectoryStat.Create();
end;
destructor TPathInfo.Destroy;
begin
fPathName := '';
fDirStats.free;
inherited Destroy;
end;
function TPathInfo.AddSizeExtension(Info : TSearchRec; LimIndex : Integer; TypeExt : String; KeepUnknown: boolean; GpName, SpName : string): UInt64;
var Ext : string;
begin
if (TypeExt='') and KeepUnknown then
begin
Ext := Copy(lowerCase(ExtractFileExt(Info.Name)),1,5);
if Length(ExtractFileExt(Info.Name))>5 then
Ext[5] := '*';
TypeExt := '!na'+Ext;
LimIndex := 0;
GroupName := GpName;
SpecificName := SpName;
Result := fDirStats.AddFileStat(Info,LimIndex,TypeExt);
end;
end;
class function TPathInfo.CompareNode(Item1 : TPathInfo; Item2 : TPathInfo) : Longint;
begin
Result := AnsiCompareText(Item1.PathName, Item1.PathName);
end;
function TPathInfo.dumpData() : AnsiString;
var i : integer;
begin
Result := 'Path(' + PathName +
') State(' + GetEnumName(TypeInfo(tPIState), ord(State)) +
') Size(' + DirStats.Size.FromByteToHR +
') Specific(' + SpecificName +
') GroupName(' + GroupName +')';
for i:= 0 to Pred(fDirStats.count) do
Result := Result + '\n' + fDirStats.TypeExtension[i]+':'+fDirStats.FileInfoFromIndex[i].GetData;
end;
function TPathInfo.dumpJSON() : AnsiString;
var i : integer;
begin
Result := '{ "Name" : "'+StringReplace(PathName,'\','\\',[rfReplaceAll])+'", '+
'"Group" : "'+GroupName+'", '+
'"Specific" : "'+SpecificName+'", '+
fDirStats.GetJSON() +
'}';
end;
end.
|
program Punto5Tp2;
{
5. Una empresa dedicada a la fabricación de licores necesita programa que le permita gestionar la producción
de sus productos. Sus necesidades están basadas en los siguientes requerimientos:
a. Cargar los diferentes tipos de licores que fabrica. Los mismos están caracterizados por código de licor,
nombre, forma de elaboración (A, B, C), cantidad en stock y stock mínimo.
b. Mostrar todos los licores guardados en el sistema
c. Mostrar los licores de una forma de elaboración dada
d. Mostrar los licores cuyo stock es menor al mínimo
e. Mostrar el stock cuyo stock es el menor de todos }
uses crt;
const
MAX=100;
type
TLicor= record
codigo:integer;
nombre:string[30];
formaElaboracion:char;
stock:integer;
stockMinimo:integer;
end;
TLicores= array[1..MAX] of TLicor;
procedure cargarLicor(var licor:TLicor);
begin
with licor do
begin
writeln('Ingrese los datos del licor');
write('Codigo ->');
readln(codigo);
write('Nombre ->');
readln(nombre);
write('Elaboracion A,B,C ->');
readln(formaElaboracion);
write('Stock Minimo ->');
readln(stockMinimo);
write('Stock ->');
readln(stock);
end;
end;
procedure cargarLicores(var licores:TLicores;var n:integer);
var
opcion:char;
begin
repeat
cargarLicor(licores[n+1]);
n:=n+1;
write('Desea cargar otro licor? S/N-> ');
readln(opcion);
until (opcion='n') or (opcion='N');
end;
procedure mostrarLicorTabla(licor:TLicor;y:integer);
begin
with licor do
begin
Write(codigo); gotoxy(10,y);
Write(nombre); gotoxy(30,y);
Write(formaElaboracion); gotoxy(40,y);
Write(stock); gotoxy(50,y);
Writeln(stockMinimo);
end;
end;
procedure Cabecera();
begin
ClrScr();
Write('Codigo'); gotoxy(10,1);
Write('Nombre'); gotoxy(30,1);
Write('F. Elab.'); gotoxy(40,1);
Write('Stock'); gotoxy(50,1);
Writeln('Stock Min.');
end;
procedure mostrarLicores(Licores:TLicores;n:integer);
var
i:integer;
begin
cabecera();
for i:=1 to n do
mostrarLicorTabla(licores[i],i+1);
end;
procedure mostrarLicoresPorFormaElaboracion (Licores:Tlicores;n:integer;elaboracion:char);
var cont,i:integer;
begin
cabecera();
cont:=0;
for i:=1 to n do
if (licores[i].formaElaboracion=elaboracion) then
begin
cont:=cont+1;
mostrarLicorTabla(licores[i],cont+1);
end;
end;
procedure mostrarLicoresMenoresStockMinimo(Licores:Tlicores;n:integer);
var i,cont:integer;
begin
cabecera();
cont:=0;
for i:=1 to n do
with licores[i] do
if (stock<stockMinimo) then
begin
cont:=cont+1;
mostrarLicorTabla(licores[i],cont+1);
end;
end;
procedure mostrarMenorStock (var licores:Tlicores;n:integer);
var menor:tlicor;i:integer;
begin
menor:= licores[1];
for i:=2 to n do
if menor.stock>licores[i].stock then
menor:=licores[i];
Cabecera();
mostrarLicorTabla(menor,2);
end;
function menu():integer;
begin
writeln('Menu');
writeln('1- Cargar Licores');
writeln('2- Mostrar Licores');
writeln('3- Mostrar licores por forma de elaboración');
writeln('4- Mostrar Cuyo stock es menor al minimo');
writeln('5 - Mostrar el producto con menor stock');
writeln('0 - Salir');
write('-> ');
readln(menu);
end;
var
option:integer;
elab:char;
licores:tLicores;
n:integer;
begin
n:=0;
repeat
clrscr();
option:=menu();
case option of
1:cargarLicores(licores,n);
2:mostrarLicores(licores,n);
3:
begin
write('ingrese la forma de elaboracion ->');
readln(elab);
mostrarLicoresPorFormaElaboracion(licores,n,elab);
end;
4: mostrarLicoresMenoresStockMinimo(licores,n);
5: mostrarMenorStock(licores,n);
0: writeln('Fin del Programa');
otherwise
end;
writeln();
write('Presione una tecla para continuar');readkey();
until (option=0);
end.
|
unit uTypes;
interface
type
TOraConfig = record
HOST: string;
PORT: string;
SID: string;
USERNAME: string;
PASSWORD: string;
TableName: string;
InsertSQL: string;
SelectSQL: string;
OrderField: string;
MaxOrderFieldValue: string;
TargetFilePath: string;
IntervalSecond: integer;
end;
implementation
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.6 7/21/04 3:14:04 PM RLebeau
Removed local Buffer variable from TIdMappedPortUDP.DoUDPRead(), not needed
Rev 1.5 2004.02.03 5:44:00 PM czhower
Name changes
Rev 1.4 2/2/2004 4:20:30 PM JPMugaas
Removed warning from Delphi 8. It now should compile in DotNET.
Rev 1.3 1/21/2004 3:11:34 PM JPMugaas
InitComponent
Rev 1.2 10/25/2003 06:52:14 AM JPMugaas
Updated for new API changes and tried to restore some functionality.
Rev 1.1 2003.10.24 10:38:28 AM czhower
UDP Server todos
Rev 1.0 11/13/2002 07:56:46 AM JPMugaas
}
unit IdMappedPortUDP;
interface
{$i IdCompilerDefines.inc}
{
- Syncronized with Indy standards by Gregor Ibic
- Original DNS mapped port by Gregor Ibic
}
uses
Classes,
IdGlobal,
IdUDPServer,
IdSocketHandle,
IdGlobalProtocols;
type
TIdMappedPortUDP = class(TIdUDPServer)
protected
FMappedPort: TIdPort;
FMappedHost: String;
FOnRequest: TNotifyEvent;
//
procedure DoRequestNotify; virtual;
procedure InitComponent; override;
procedure DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); override;
published
property MappedHost: string read FMappedHost write FMappedHost;
property MappedPort: TIdPort read FMappedPort write FMappedPort;
property OnRequest: TNotifyEvent read FOnRequest write FOnRequest;
end;
implementation
uses
IdAssignedNumbers,
IdUDPClient, SysUtils;
procedure TIdMappedPortUDP.InitComponent;
begin
inherited InitComponent;
DefaultPort := IdPORT_DOMAIN;
end;
procedure TIdMappedPortUDP.DoRequestNotify;
begin
if Assigned(OnRequest) then begin
OnRequest(Self);
end;
end;
procedure TIdMappedPortUDP.DoUDPRead(AThread: TIdUDPListenerThread;
const AData: TIdBytes; ABinding: TIdSocketHandle);
var
LClient: TIdUDPClient;
LData: TIdBytes;
i: Integer;
begin
inherited DoUDPRead(AThread, AData, ABinding);
DoRequestNotify;
LClient := TIdUDPClient.Create(nil);
try
LClient.Host := FMappedHost;
LClient.Port := FMappedPort;
LClient.SendBuffer(AData);
SetLength(LData, LClient.BufferSize);
i := LClient.ReceiveBuffer(LData);
if i > 0 then begin
SetLength(LData, i);
with ABinding do begin
SendTo(PeerIP, PeerPort, LData, 0, i);
end;
end;
finally
FreeAndNil(LClient);
end;
end;
end.
|
unit ufrmMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
System.SyncObjs, ncSocketList, ncSources;
type
TfrmMain = class(TForm)
Server: TncServerSource;
memLog: TMemo;
ToolBar1: TToolBar;
btnActivateServer: TButton;
btnShutDownClients: TButton;
procedure FormDestroy(Sender: TObject);
function ServerHandleCommand(Sender: TObject; aLine: TncLine; aCmd: Integer; const aData: TArray<System.Byte>; aRequiresResult: Boolean;
const aSenderComponent, aReceiverComponent: string): TArray<System.Byte>;
procedure ServerConnected(Sender: TObject; aLine: TncLine);
procedure ServerDisconnected(Sender: TObject; aLine: TncLine);
procedure btnActivateServerClick(Sender: TObject);
procedure btnShutDownClientsClick(Sender: TObject);
private
public
procedure Log(aStr: string);
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
Server.Active := False;
end;
procedure TfrmMain.Log(aStr: string);
begin
// This is thread safe
TThread.Queue(nil,
procedure
begin
memLog.Lines.Add(aStr);
memLog.ScrollBy(0, 100);
end);
end;
procedure TfrmMain.btnActivateServerClick(Sender: TObject);
begin
try
Server.Active := not Server.Active;
finally
if Server.Active then
begin
btnActivateServer.Text := 'Deactivate Server';
Log('Server is activated');
end
else
begin
btnActivateServer.Text := 'Activate Server';
Log('Server was deactivated');
end;
end;
end;
procedure TfrmMain.ServerConnected(Sender: TObject; aLine: TncLine);
begin
Log('Client connected: ' + aLine.PeerIP);
end;
procedure TfrmMain.ServerDisconnected(Sender: TObject; aLine: TncLine);
begin
Log('Client disconnected: ' + aLine.PeerIP);
end;
function TfrmMain.ServerHandleCommand(Sender: TObject; aLine: TncLine; aCmd: Integer; const aData: TArray<System.Byte>; aRequiresResult: Boolean;
const aSenderComponent, aReceiverComponent: string): TArray<System.Byte>;
var
Clients: TSocketList;
i: Integer;
begin
Log('Received: "' + StringOf(aData) + '" from peer: ' + aLine.PeerIP);
// Now send this to all clients
Clients := Server.Lines.LockList;
try
for i := 0 to Clients.Count - 1 do
// if Clients.Lines[i] <> aLine then // If you do not want to send text back to original client
Server.ExecCommand(Clients.Lines[i], 0, aData, False);
// You can shutdown a line here by calling Server.ShutdownLine,
// see following procecure
finally
Server.Lines.UnlockList;
end;
end;
procedure TfrmMain.btnShutDownClientsClick(Sender: TObject);
var
Clients: TSocketList;
i: Integer;
begin
Clients := Server.Lines.LockList;
try
for i := 0 to Clients.Count - 1 do
Server.ShutDownLine(Clients.Lines[i]);
finally
Server.Lines.UnlockList;
end;
end;
end.
|
unit DominioDataUn;
interface
uses
SysUtils, Classes, FMTBcd, DB, Provider, osSQLDataSetProvider, SqlExpr, osUtils,
osCustomDataSetProvider, osSQLDataSet;
type
TDominioData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
MasterDataSetIDDOMINIO: TIntegerField;
MasterDataSetDESCRICAO: TStringField;
MasterDataSetNUMORDEM: TIntegerField;
private
public
procedure Validate(PDataSet: TDataSet);
end;
var
DominioData: TDominioData;
implementation
uses osErrorHandler, SQLMainData;
{$R *.dfm}
procedure TDominioData.Validate(PDataSet: TDataSet);
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('Descricao'));
WarningEmpty(FieldByName('NumOrdem'));
Check;
end;
end;
initialization
OSRegisterClass(TDominioData);
end.
|
unit uMythos;
interface
type
TMythosCard = record
fId: integer;
fClueSpawn: integer;
fCloseLok:integer;
fProcess: integer;
fHeadline: integer;
fSkillChk: integer;
fSkillChkTrue: integer;
fSkillChkFalse: integer;
fSpeedMod: integer;
fSneakMod: integer;
fFightMod: integer;
fWillMod: integer;
fLoreMod: integer;
fLuckMod: integer;
fGateSpawn: integer;
fMobMoveWhite: array [1..9] of integer;
fMobMoveBlack: array [1..9] of integer;
end;
TMythosArray = array of TMythosCard;
{ function LoadMonsterCards(var monsters: TMonsterArray; file_path: string): integer;
function DrawMonsterCard(var monsters: TMonsterArray): integer;
procedure ShuffleMonsterDeck(var monsters: TMonsterArray);
function GetMonsterNameByID(id: integer): string;
function GetMonsterByID(var monsters: TMonsterArray; id: integer): TMonster; // Get mob from pool
function GetMonsterCount(var monsters: TMonsterArray): integer;
}
implementation
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.1 1/21/2004 3:27:14 PM JPMugaas
InitComponent
Rev 1.0 11/13/2002 07:58:46 AM JPMugaas
}
unit IdQOTDUDP;
interface
{$i IdCompilerDefines.inc}
uses
IdAssignedNumbers, IdUDPBase, IdUDPClient;
type
TIdQOTDUDP = class(TIdUDPClient)
protected
Function GetQuote : String;
procedure InitComponent; override;
public
{ This is the quote from the server }
Property Quote: String read GetQuote;
published
Property Port default IdPORT_QOTD;
end;
implementation
uses
IdGlobal;
{ TIdQOTDUDP }
procedure TIdQOTDUDP.InitComponent;
begin
inherited;
Port := IdPORT_QOTD;
end;
function TIdQOTDUDP.GetQuote: String;
begin
//The string can be anything - The RFC says the server should discard packets
Send(' '); {Do not Localize}
Result := ReceiveString(IdTimeoutDefault, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF});
end;
end.
|
unit UVersionLabel;
// UVersionLabel.pas - Fills in the version label from the FileVersionInfo
// Copyright (c) 2000. All Rights Reserved.
// Written by Paul Kimmel. Okemos, MI USA
// Software Conceptions, Inc 800-471-5890
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs,
StdCtrls;
type
TVersionLabel = class(TCustomLabel)
private
{ Private declarations }
FFileName : TFileName;
FMask: String;
function GetEnvPathString: String;
function GetApplicationName(const AppName: String): String;
protected
{ Protected declarations }
procedure SetFileName(Value: TFileName);
procedure SetVersion;
procedure SetMask(const Value: String);
property Caption stored False;
public
{ Public declarations }
published
{ Published declarations }
constructor Create(AOwner: TComponent); override;
property FileName: TFileName read FFileName write SetFileName;
property Mask: String read FMask write SetMask stored True;
end;
//procedure Register;
implementation
//uses
// UzslEditors, DesignIntf;
//
//procedure Register;
//begin
// RegisterComponents('zhshll', [TVersionLabel]);
////RegisterPropertyEditor(TypeInfo(TFileName), TVersionLabel, 'FileName', TFileNameProperty);
//end;
////////////////////////////////////////////////////////////////////////////////
function GetVersionString(FileName : String): String;
resourcestring
VersionRequestString = '\\StringFileInfo\\040904E4\\FileVersion';
var
Size, Dummy, Len: DWord;
Buffer: PChar;
RawPointer: Pointer;
begin
result := '<unknown>';
Size := GetFileVersionInfoSize(PChar(FileName), Dummy);
if(Size = 0) then exit;
GetMem(Buffer, Size);
try
if(GetFileVersionInfo(PChar(FileName), Dummy, Size, Buffer) = False) then
exit;
if(VerQueryValue(Buffer, PChar(VersionRequestString), RawPointer,
Len) = False) then exit;
result := StrPas(PChar(RawPointer));
finally
FreeMem(Buffer);
end;
end;
procedure DecodeVersion(Version : String; var MajorVersion,
MinorVersion, Release, Build: String);
function GetValue(var Version : String): String;
begin
result := Copy(Version, 1, Pos('.', Version) - 1);
if(result = EmptyStr) then result := 'x';
Delete(Version, 2, Pos('.', Version));
end;
begin
MajorVersion := GetValue(Version);
MinorVersion := GetValue(Version);
Release := GetValue(Version);
Build := GetValue(Version);
end;
////////////////////////////////////////////////////////////////////////////////
constructor TVersionLabel.Create(AOwner : TComponent);
resourcestring
DefaultMask = 'Version %s.%s (Release %s Build %s)';
begin
inherited Create(AOwner);
Mask := DefaultMask;
end;
procedure TVersionLabel.SetVersion;
var
MajorVersion, MinorVersion, Release, Build : String;
Version : String;
begin
Version := GetVersionString(FFileName);
DecodeVersion(Version, MajorVersion, MinorVersion, Release, Build);
Caption := Format(FMask, [MajorVersion, MinorVersion, Release, Build]);
end;
resourcestring
DefaultPath = '.\;\';
function TVersionLabel.GetEnvPathString : String;
const
MAX = 1024;
begin
SetLength(result, MAX);
if(GetEnvironmentVariable(PChar('Path'), PChar(result), MAX) = 0) then
result := DefaultPath;
end;
function TVersionLabel.GetApplicationName(const AppName: String): String;
begin
if( csDesigning in ComponentState ) then
// see if a compiled version already exists, if we are designing
result := FileSearch(AppName, GetEnvPathString + DefaultPath)
else
result := Application.EXEName;
end;
procedure TVersionLabel.SetFileName( Value : TFileName );
begin
if(CompareText(FFileName, Value) = 0) then exit;
FFileName := GetApplicationName(Value);
SetVersion;
end;
procedure TVersionLabel.SetMask(const Value: String);
begin
if(FMask = Value) then exit;
FMask := Value;
SetVersion;
end;
end.
|
unit FastStopThreadUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SyncObjs, StdCtrls, TimeIntervals, ProgressViewer, ExtCtrls;
type
TMyThread = class(TThread)
private
Event: TEvent;
FUseProgressViewer: Boolean;
FUseFullCalls: Integer;
procedure DoUsefullWork;
protected
procedure Execute; override;
public
constructor Create(UseProgressViewer: Boolean);
destructor Destroy; override;
procedure WakeUp; // Команда "Проснуться"
property UseFullCalls: Integer read FUseFullCalls;
end;
TForm2 = class(TForm)
Label1: TLabel;
btnRunThread: TButton;
btnStopThread: TButton;
Label2: TLabel;
labFreeThreadTime: TLabel;
btnWakeUp: TButton;
cbUseProgressViewer: TCheckBox;
Timer1: TTimer;
Label3: TLabel;
labUseFullCalls: TLabel;
Label4: TLabel;
labResumeThreadAfterSetEvent: TLabel;
procedure btnRunThreadClick(Sender: TObject);
procedure btnStopThreadClick(Sender: TObject);
procedure btnWakeUpClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
MyThread: TMyThread;
public
{ Public declarations }
end;
var
Form2: TForm2;
tiSignalled: TTimeInterval;
implementation
{$R *.dfm}
{ TMyThread }
constructor TMyThread.Create(UseProgressViewer: Boolean);
const
STATE_NONSIGNALED = FALSE;
AUTO_RESET = FALSE;
begin
inherited Create(False);
// Создаём объект "Event" в состоянии "nonsignaled" и просим, чтобы
// он автоматически переходил в состояние "nonsignaled" после WaitFor
Event := TEvent.Create(nil, AUTO_RESET, STATE_NONSIGNALED, '', False);
FUseProgressViewer := UseProgressViewer;
end;
destructor TMyThread.Destroy;
begin
// Очень важно, чтобы вызов Terminate был раньше вызова SetEvent!
Terminate; // 1. Выставляем флаг Terminated
tiSignalled.Start;
Event.SetEvent; // 2. Переводим Event в состояние SIGNALED
inherited; // 3. Дожидаемся выхода из метода Execute
Event.Free; // 4. Уничтожаем объект Event
end;
procedure TMyThread.DoUsefullWork;
begin
// Любая полезная работа, выполняемая потоком
Inc(FUseFullCalls); // Учитываем количество вызовов данного метода
end;
procedure TMyThread.Execute;
var
WaitRes: TWaitResult;
pv: TProgressViewer;
begin
pv := nil; // Чтобы компилятор не выдавал Warning
while not Terminated do
begin
// Внимание! Визуализация ожидания события вносит значительные накладные
// расходы и значительно увеличивает время уничтожения потока!
if FUseProgressViewer then
pv := TProgressViewer.Create('Ожидание события');
WaitRes := Event.WaitFor(5 * 1000); // Ожидание события - 5 секунд
if WaitRes = wrSignaled then
tiSignalled.Stop; // Останавливаем измерение времени
if FUseProgressViewer then
pv.TerminateProgress;
// Выполняем полезную работу если окончился таймаут ожидания (wrTimeout),
// либо если произошёл вызов метода WakeUp
if (WaitRes = wrTimeout) or ((WaitRes = wrSignaled) and (not Terminated)) then
DoUsefullWork;
end;
end;
procedure TMyThread.WakeUp;
begin
tiSignalled.Start;
Event.SetEvent; // Просим поток проснуться и выполнить полезную работу
end;
procedure TForm2.btnRunThreadClick(Sender: TObject);
begin
MyThread := TMyThread.Create(cbUseProgressViewer.Checked);
btnRunThread.Enabled := False;
btnStopThread.Enabled := True;
btnWakeUp.Enabled := True;
end;
procedure TForm2.btnStopThreadClick(Sender: TObject);
var
ti: TTimeInterval;
begin
ti.Start;
FreeAndNil(MyThread);
ti.Stop;
labFreeThreadTime.Caption := Format('%d мкс', [ti.ElapsedMicroseconds]);
btnRunThread.Enabled := True;
btnStopThread.Enabled := False;
btnWakeUp.Enabled := False;
end;
procedure TForm2.btnWakeUpClick(Sender: TObject);
begin
MyThread.WakeUp;
end;
procedure TForm2.Timer1Timer(Sender: TObject);
begin
if Assigned(MyThread) then
labUseFullCalls.Caption := IntToStr(MyThread.UseFullCalls);
if tiSignalled.ElapsedMicroseconds() > 0 then
labResumeThreadAfterSetEvent.Caption := Format('%d мкс', [tiSignalled.ElapsedMicroseconds]);
end;
end.
|
unit ConfiguracoesSistema;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TemplateCadastroArquivoIni, StdCtrls, Buttons, ExtCtrls;
type
TfrmConfiguracoesSistema = class(TTemplateCadastroIni)
lbl3: TLabel;
edtPathBaseDadosXML: TEdit;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function permiteGravar():Boolean;override;
end;
var
frmConfiguracoesSistema: TfrmConfiguracoesSistema;
implementation
{$R *.dfm}
procedure TfrmConfiguracoesSistema.FormCreate(Sender: TObject);
begin
CaminhoArquivoIni := ExtractFilePath(Application.ExeName)+'\config.ini';
inherited;
end;
function TfrmConfiguracoesSistema.permiteGravar: Boolean;
begin
if edtPathBaseDadosXML.Text=EmptyStr then
Application.MessageBox(Pchar('Digite um caminho para o repositório da base de dados XML.'),
Pchar(application.Title),MB_ICONERROR)
else if copy(edtPathBaseDadosXML.Text,length(edtPathBaseDadosXML.text),length(edtPathBaseDadosXML.text))<>'\' then
Application.MessageBox(Pchar('Formato de Path inválido.Coloque no final do caminho o caractere '+QuotedStr('\')),
Pchar(application.Title),MB_ICONERROR)
else if not DirectoryExists(edtPathBaseDadosXML.Text) then
Application.MessageBox(Pchar('Path não encontrado.'),
Pchar(application.Title),MB_ICONERROR)
else
Result := true;
end;
end.
|
{***************************************************************
*
* Project : TFTPServer
* Unit Name: transfer
* Purpose : Sub form
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:40:05
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit transfer;
interface
uses
{$IFDEF Linux}
QControls, QForms, QDialogs, QComCtrls, QStdCtrls,
{$ELSE}
Controls, Forms, Dialogs, ComCtrls, StdCtrls,
{$ENDIF}
Classes, SyncObjs;
type
TProgressStream = class(TFileStream) // single way progress anyway
private
FActivity: TEvent;
FProgress: Integer;
public
constructor Create(const FileName: string; Mode: Word);
destructor Destroy; override;
function Read(var Buffer; Count: Integer): Integer; override;
function Write(const Buffer; Count: Integer): Integer; override;
property Progress: Integer read FProgress;
end;
TfrmTransfer = class(TForm)
prgTransfer: TProgressBar;
Label1: TLabel;
lblByteRate: TLabel;
private
FStartTime: Cardinal;
FThread: TThread;
function GetStream: TProgressStream;
public
procedure CheckProgress;
constructor Create(AOwner: TComponent; AStream: TProgressStream; const
FileName: string; const FileMode: Word); reintroduce; virtual;
destructor Destroy; override;
property Stream: TProgressStream read GetStream;
end;
implementation
uses SysUtils, windows;
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
type
TWaitThread = class(TThread)
private
FOwner: TfrmTransfer;
FStream: TProgressStream;
evtFinished: TEvent;
protected
procedure Execute; override;
public
constructor Create(AOwner: TfrmTransfer; AStream: TProgressStream);
destructor Destroy; override;
end;
{ TfrmTransfer }
procedure TfrmTransfer.CheckProgress;
begin
prgTransfer.Position := Stream.Progress;
prgTransfer.Update;
lblByteRate.Caption := IntToStr(Round((Stream.Progress / (GetTickCount -
FStartTime)) * 1000));
end;
constructor TfrmTransfer.Create(AOwner: TComponent; AStream: TProgressStream;
const FileName: string; const FileMode: Word);
var
s: string;
begin
inherited Create(AOwner);
prgTransfer.Max := AStream.Size;
if FileMode = fmOpenRead then
s := 'Reading'
else
s := 'Writing';
Caption := Format('%s %s', [s, ExtractFileName(FileName)]);
FThread := TWaitThread.Create(self, AStream);
FStartTime := GetTickCount;
end;
destructor TfrmTransfer.Destroy;
begin
FThread.Free;
inherited;
end;
function TfrmTransfer.GetStream: TProgressStream;
begin
result := TWaitThread(FThread).FStream;
end;
{ TWaitThread }
constructor TWaitThread.Create(AOwner: TfrmTransfer; AStream: TProgressStream);
begin
FOwner := AOwner;
FStream := AStream;
FreeOnTerminate := False;
evtFinished := TEvent.Create(nil, false, false, '');
inherited Create(False);
end;
destructor TWaitThread.Destroy;
begin
evtFinished.SetEvent;
WaitFor;
evtFinished.Free;
inherited;
end;
procedure TWaitThread.Execute;
var
hndArray: array[0..1] of THandle;
begin
hndArray[0] := FStream.FActivity.Handle;
hndArray[1] := evtFinished.Handle;
while WaitForMultipleObjects(2, @hndArray, false, INFINITE) = WAIT_OBJECT_0 do
Synchronize(FOwner.CheckProgress);
end;
{ TProgressStream }
constructor TProgressStream.Create(const FileName: string; Mode: Word);
begin
inherited Create(FileName, Mode);
FActivity := TEvent.Create(nil, False, False, '');
end;
destructor TProgressStream.Destroy;
begin
FActivity.Free;
sleep(0);
inherited;
end;
function TProgressStream.Read(var Buffer; Count: Integer): Integer;
begin
FProgress := FProgress + Count;
Result := inherited Read(Buffer, Count);
FActivity.SetEvent;
end;
function TProgressStream.Write(const Buffer; Count: Integer): Integer;
begin
FProgress := FProgress + Count;
Result := inherited Write(Buffer, Count);
FActivity.SetEvent;
end;
end.
|
unit EstimatedTaxLetterUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Db, DBTables;
type
TEstimatedTaxLetterForm = class(TForm)
Label1: TLabel;
EditNewAssessmentAmount: TEdit;
PrintButton: TBitBtn;
RAVEEstimatedTaxLetterHeaderTable: TTable;
RAVEEstimatedTaxLetterDetailsTable: TTable;
ParcelTable: TTable;
SwisCodeTable: TTable;
AssessmentYearControlTable: TTable;
procedure PrintButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SwisSBLKey : String;
end;
var
EstimatedTaxLetterForm: TEstimatedTaxLetterForm;
implementation
{$R *.DFM}
uses PASUtils, GlblVars, GlblCnst, PASTypes, DataAccessUnit,
WinUtils, Utilitys, UtilEstimatedTaxComputation;
{==============================================================}
Procedure FillInHeaderInformation(ParcelTable : TTable;
SwisCodeTable : TTable;
AssessmentYearControlTable : TTable;
RAVEEstimatedTaxLetterHeaderTable : TTable;
SwisSBLKey : String;
NewAssessedValue : LongInt;
CombinedTaxRate : Double;
EstimatedTax : Double);
var
NAddrArray : NameAddrArray;
begin
GetNameAddress(ParcelTable, NAddrArray);
with RAVEEstimatedTaxLetterHeaderTable do
try
Insert;
FieldByName('LetterDate').Text := DateToStr(Date);
FieldByName('ParcelID').Text := ConvertSwisSBLToDashDot(SwisSBLKey);
FieldByName('AccountNumber').Text := ParcelTable.FieldByName('AccountNo').Text;
FieldByName('LegalAddress').Text := GetLegalAddressFromTable(ParcelTable);
FieldByName('SwisCode').Text := ParcelTable.FieldByName('SwisCode').Text;
FieldByName('SchoolCode').Text := ParcelTable.FieldByName('SchoolCode').Text;
FieldByName('PropertyClass').Text := ParcelTable.FieldByName('PropertyClassCode').Text;
FieldByName('RollSection').Text := ParcelTable.FieldByName('RollSection').Text;
FieldByName('MortgageNumber').Text := ParcelTable.FieldByName('MortgageNumber').Text;
FieldByName('BankCode').Text := ParcelTable.FieldByName('BankCode').Text;
FieldByName('FullMarketValue').Text := FormatFloat(CurrencyDisplayNoDollarSign,
ComputeFullValue(NewAssessedValue,
SwisCodeTable,
ParcelTable.FieldByName('PropertyClassCode').Text,
ParcelTable.FieldByName('OwnershipCode').Text,
False));
FieldByName('ValuationDate').Text := AssessmentYearControlTable.FieldByName('ValuationDate').Text;
FieldByName('AssessedValue').Text := FormatFloat(CurrencyDisplayNoDollarSign, NewAssessedValue);
FieldByName('UniformPercentOfValue').Text := FormatFloat(DecimalEditDisplay,
SwisCodeTable.FieldByName('UniformPercentValue').AsFloat);
FieldByName('NameAddr1').Text := NAddrArray[1];
FieldByName('NameAddr2').Text := NAddrArray[2];
FieldByName('NameAddr3').Text := NAddrArray[3];
FieldByName('NameAddr4').Text := NAddrArray[4];
FieldByName('NameAddr5').Text := NAddrArray[5];
FieldByName('NameAddr6').Text := NAddrArray[6];
FieldByName('CombinedTaxRate').Text := FormatFloat(DecimalDisplay, CombinedTaxRate);
FieldByName('EstimatedTax').Text := FormatFloat(DecimalDisplay, EstimatedTax);
Post;
except
end; {with RAVEEstimatedTaxLetterHeaderTable do}
end; {FillInHeaderInformation}
{==============================================================}
Procedure FillInDetailInformation( ParcelTable : TTable;
RAVEEstimatedTaxLetterDetailTable : TTable;
SwisSBLKey : String;
NewAssessedValue : LongInt;
var CombinedTaxRate : Double;
var EstimatedTax : Double);
var
TaxInformationList : TList;
I : Integer;
begin
TaxInformationList := TList.Create;
EstimatedTax := GetProjectedTaxInformation(NewAssessedValue, 0,
SwisSBLKey,
ParcelTable.FieldByName('SchoolCode').Text,
TaxInformationList,
[ltMunicipal, ltSchool],
trAny,
False);
For I := 0 to (TaxInformationList.Count - 1) do
with TaxInformationPointer(TaxInformationList[I])^, RAVEEstimatedTaxLetterDetailTable do
try
Insert;
FieldByName('LevyDescription').AsString := LevyCode + ' ' + LevyDescription;
FieldByName('TaxableValue').AsString := FormatFloat(CurrencyDisplayNoDollarSign, TaxableValue);
FieldByName('TaxRate').AsString := FormatFloat(ExtendedDecimalDisplay, TaxRate);
FieldByName('TaxRateUnits').AsString := TaxRateDescription;
If _Compare(ExtensionCode, SDistEcTO, coEqual)
then CombinedTaxRate := CombinedTaxRate + TaxRate;
FieldByName('TaxAmount').AsString := FormatFloat(DecimalDisplay, TaxAmount);
Post;
except
end;
FreeTList(TaxInformationList, SizeOf(TaxInformationRecord));
end; {FillInDetailInformation}
{==============================================================}
Procedure TEstimatedTaxLetterForm.PrintButtonClick(Sender: TObject);
var
NewAssessedValue : LongInt;
CombinedTaxRate, EstimatedTax : Double;
RAVEEstimatedTaxLetterHeaderTableSortFileName,
RAVEEstimatedTaxLetterDetailsTableSortFileName : String;
Quit : Boolean;
begin
NewAssessedValue := 0;
try
NewAssessedValue := StrToInt(EditNewAssessmentAmount.Text);
except
MessageDlg('Please enter a valid assessment amount.', mtError, [mbOK], 0);
EditNewAssessmentAmount.SetFocus;
Abort;
end;
CopyAndOpenSortFile(RAVEEstimatedTaxLetterHeaderTable,
'RAVE_EstTaxLetterHdr',
RAVEEstimatedTaxLetterHeaderTable.TableName,
RAVEEstimatedTaxLetterHeaderTableSortFileName,
False, True, Quit);
CopyAndOpenSortFile(RAVEEstimatedTaxLetterDetailsTable,
'RAVE_EstTaxLetterDtl',
RAVEEstimatedTaxLetterDetailsTable.TableName,
RAVEEstimatedTaxLetterDetailsTableSortFileName,
False, True, Quit);
_OpenTablesForForm(Self, ThisYear, [toNoReopen]);
_OpenTable(ParcelTable, ParcelTableName, '', '', NextYear, []);
_Locate(ParcelTable, [GlblNextYear, SwisSBLKey], '', [loParseSwisSBLKey]);
_Locate(SwisCodeTable, [Copy(SwisSBLKey, 1, 6)], '', []);
_Locate(AssessmentYearControlTable, [GlblThisYear], '', []);
FillInDetailInformation(ParcelTable, RAVEEstimatedTaxLetterDetailsTable, SwisSBLKey, NewAssessedValue,
CombinedTaxRate, EstimatedTax);
FillInHeaderInformation(ParcelTable, SwisCodeTable, AssessmentYearControlTable,
RAVEEstimatedTaxLetterHeaderTable, SwisSBLKey,
NewAssessedValue, CombinedTaxRate, EstimatedTax);
_CloseTablesForForm(Self);
LaunchRAVE('letter_yorktown_what_if.rav', ['HEADER', 'DETAIL'],
[RAVEEstimatedTaxLetterHeaderTableSortFileName,
RAVEEstimatedTaxLetterDetailsTableSortFileName],
rltLetter);
Close;
end; {PrintButtonClick}
end.
|
unit CSCServer;
interface
uses
Classes,
Windows,
WinSock,
Dialogs,
Math,
SysUtils,
Messages,
CSCBase,
CSCCustomBase,
CSCQueue,
CSCTimer,
ScktComp;
type
TMyServerWinSocket = class (TServerWinSocket);
TCSCServerClientWinsocket = class (TServerClientWinSocket)
private
FSndRcv: TCSCSenderReceiver;
public
constructor Create(Socket: TSocket; ServerWinSocket: TServerWinSocket);
destructor Destroy; override;
property SndRcv: TCSCSenderReceiver
read FSndRcv write FSndRcv;
end;
TCSCServer = class ( TCSCCustomCommBase )
protected
FDaemon : TServerSocket;
FConnected : Boolean;
FBusy : Boolean;
FBuffer : PByteArray;
FSndBuffer : PnmHeader;
FTimeout : integer;
FAckReceived : Boolean;
FReplyTimer : TCSCTimer;
FAckMsg : TnmHeader;
private
// FMsgQueue: TCSCMessageQueue;
protected
procedure OnClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure OnClientWrite(Sender: TObject;
Socket: TCustomWinSocket);
procedure OnClientError(Sender: TObject;
Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
procedure OnGetSocket(Sender: TObject; Socket: TSocket; var ClientSocket: TServerClientWinSocket);
procedure SetListening(Value : Boolean);
function GetListening: Boolean;
function WaitForAckReply(aHandle: HWND) : Boolean;
function GetPort: Integer;
procedure SetPort(Value: Integer);
function GetOnConnect: TSocketNotifyEvent;
procedure SetOnConnect(Value: TSocketNotifyEvent);
function GetOnDisconnect: TSocketNotifyEvent;
procedure SetOnDisconnect(Value: TSocketNotifyEvent);
published
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure WinsockBreath(aHandle: HWND);
function LockSocket(Socket: TCustomWinSocket): Boolean;
procedure OnMsgReceived(Socket: TCustomWinSocket; Data: Pointer; DataLen: Integer);
procedure MsgReceived(aClientSck: TCustomWinSocket; aMsg: PnmHeader); override;
procedure SendFilePacket(aClientSck: TCustomWinSocket;
aFFP: PCSCnmFirstFilePacket;
aFP: TCSCnmFilePacket;
aFS: TFileStream); override;
procedure Disconnect(NH : HWND);
procedure SendInternalMsg(aMsg : longint;
aEvent : Boolean;
aClient : TCustomWinSocket;
aData : pointer;
aDataLen : LongInt;
aDataType : TNetMsgDataType;
aErrorCode : Word);
procedure SendMsg(aMsg : longint;
aEvent : Boolean;
aClient : TCustomWinSocket;
aData : pointer;
aDataLen : LongInt;
aDataType : TNetMsgDataType;
aErrorCode : Word); override;
procedure SendACK(Socket: TCustomWinSocket);
property Daemon: TServerSocket read FDaemon;
property Listening: Boolean read GetListening write SetListening;
{ property MsgQueue: TCSCMessageQueue
read FMsgQueue; }
published
property Port: Integer
read GetPort write SetPort;
property OnConnect: TSocketNotifyEvent
read GetOnConnect write SetOnConnect;
property OnDisconnect: TSocketNotifyEvent
read GetOnDisconnect write SetOnDisconnect;
end;
implementation
{===TCSCServer=========================================}
function TCSCServer.GetPort: Integer;
begin
Result := FDaemon.Port;
end;
function TCSCServer.LockSocket(Socket: TCustomWinSocket): Boolean;
var I : Integer;
begin
FDaemon.Socket.Lock;
try
for I := 0 to FDaemon.Socket.ActiveConnections-1 do
if Socket = FDaemon.Socket.Connections[I] then begin
Socket.Lock;
Result := True;
Exit;
end;
finally
FDaemon.Socket.Unlock;
end;
Result := False;
end;
procedure TCSCServer.SetPort(Value: Integer);
begin
FDaemon.Port := Value;
end;
procedure TCSCServer.WinsockBreath(aHandle: HWND);
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, CM_SOCKETMESSAGE, CM_LOOKUPCOMPLETE, PM_REMOVE) do begin
// while PeekMessage(Msg, 0, WM_User, WM_User+100, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
function TCSCServer.WaitForAckReply(aHandle: HWND) : Boolean;
begin
{wait for reply or timeout, whichever occurs first}
SetTimer(FReplyTimer, 10000);
FAckReceived := False;
while not FAckReceived and
(not HasTimerExpired(FReplyTimer))
do WinsockBreath(aHandle);
Result := FAckReceived;
if not FAckReceived then begin
Result := False;
end;
end;
{function TCSCServer.SocketByHWND(NH : HWND) : TCustomWinSocket;
var I : Integer;
begin
with FDaemon.Socket do
for I := 0 to ActiveConnections-1 do
if Connections[I].Handle=NH then begin
Result := Connections[I];
Exit;
end;
Result := nil;
end;}
procedure TCSCServer.Disconnect(NH : HWND);
var I : Integer;
begin
with FDaemon.Socket do
for I := 0 to ActiveConnections-1 do
if Connections[I].Handle=NH then begin
FDaemon.Socket.Disconnect(NH);
Exit;
end;
end;
procedure TCSCServer.SetListening(Value : Boolean);
begin
if Value=FDaemon.Active then Exit;
if Value then
FDaemon.Open
else
FDaemon.Close;
end;
function TCSCServer.GetListening: Boolean;
begin
Result := FDaemon.Active;
end;
constructor TCSCServer.Create(Owner: TComponent);
begin
inherited;
FIsServer := True;
FAckMsg.nmhEvent := False;
FAckMsg.nmhMsgID := cscnmAck;
FAckMsg.nmhFirst := True;
FAckMsg.nmhLast := True;
FAckMsg.nmhErrorCode := 0;
FAckMsg.nmhMsgLen := NetMsgHeaderSize;
FAckMsg.nmhTotalSize := 0;
FBusy := False;
GetMem(FBuffer, MaxNetMsgSize);
FSndBuffer := PnmHeader(FBuffer);
FTimeout := CSCTimerMaxExpiry;
FDaemon := TServerSocket.Create(nil);
FDaemon.OnClientRead := OnClientRead;
FDaemon.OnClientWrite := OnClientWrite;
FDaemon.OnClientError := OnClientError;
FDaemon.OnGetSocket := OnGetSocket;
FDaemon.ServerType := stNonBlocking;
FDaemon.Active := False;
end;
function TCSCServer.GetOnConnect: TSocketNotifyEvent;
begin
Result := FDaemon.OnClientConnect;
end;
procedure TCSCServer.SetOnConnect(Value: TSocketNotifyEvent);
begin
FDaemon.OnClientConnect := Value;
end;
function TCSCServer.GetOnDisconnect: TSocketNotifyEvent;
begin
Result := FDaemon.OnClientDisconnect;
end;
procedure TCSCServer.SetOnDisconnect(Value: TSocketNotifyEvent);
begin
FDaemon.OnClientDisconnect := Value;
end;
{--------}
procedure ProcessMessages;
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
destructor TCSCServer.Destroy;
var I : Integer;
begin
with FDaemon.Socket do begin
for I := 0 to pred(ActiveConnections) do
Connections[I].Close;
while ActiveConnections > 0 do ProcessMessages;
end;
FDaemon.Close;
FDaemon.Free;
FreeMem(FBuffer, MaxNetMsgSize);
inherited Destroy;
end;
{--------}
procedure TCSCServer.OnClientError(Sender: TObject;
Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent;
var ErrorCode: Integer);
begin
if (ErrorEvent=eeDisconnect) then begin
TMyServerWinSocket(FDaemon.Socket).ClientDisconnect(Socket);
ErrorCode := 0;
end;
end;
{--------}
procedure TCSCServer.OnMsgReceived(Socket: TCustomWinSocket; Data: Pointer; DataLen: Integer);
begin
MsgQueue.AddPacket(Data, Socket, DataLen);
end;
procedure TCSCServer.OnClientRead(Sender: TObject;
Socket: TCustomWinSocket);
{var DataLen : Integer;}
begin
{ DataLen := Socket.ReceiveBuf(FBuffer^[0], MaxNetMsgSize);
MsgQueue.AddPacket(FBuffer, Socket.Handle, DataLen);}
TCSCServerClientWinsocket(Socket).SndRcv.Read;
end;
procedure TCSCServer.OnClientWrite(Sender: TObject;
Socket: TCustomWinSocket);
begin
TCSCServerClientWinsocket(Socket).SndRcv.Write;
end;
{--------}
procedure TCSCServer.MsgReceived(aClientSck: TCustomWinSocket; aMsg: PnmHeader);
begin
with aMsg^ do begin
if nmhMsgID = cscnmAck then
FAckReceived := True
else
if (not nmhLast) then
SendAck(aClientSck);
end;
end;
procedure TCSCServer.SendFilePacket(aClientSck: TCustomWinSocket;
aFFP: PCSCnmFirstFilePacket;
aFP: TCSCnmFilePacket;
aFS: TFileStream);
var
S : TMemoryStream;
MsgID,
FPLen,
HeaderLen: Integer;
begin
S := TMemoryStream.Create;
try
HeaderLen := 0;
if aFFP<>nil then begin
HeaderLen := SizeOf(TCSCnmFirstFilePacket);
S.WriteBuffer(aFFP^, HeaderLen);
MsgID := CSCnmFirstFilePacket;
end else
MsgID := CSCnmFilePacket;
HeaderLen := HeaderLen + SizeOf(aFP);
FPLen := MaxNetMsgSize-NetMsgHeaderSize-HeaderLen-1;
if FPLen > (aFP.nmFileSize - aFS.Position) then begin
FPLen := aFP.nmFileSize - aFS.Position;
aFP.nmLast := True;
end else aFP.nmLast := False;
S.WriteBuffer(aFP, SizeOf(aFP));
S.CopyFrom(aFS, FPLen);
SendMsg(MsgID, True, aClientSck, Pointer(S), S.Size, nmdStream, 0);
finally
S.Free;
end;
end;
procedure TCSCServer.SendACK(Socket: TCustomWinSocket);
var BytesSent: integer;
begin
with TCSCServerClientWinSocket(Socket) do
SndRcv.Send(PByteArray(@FAckMsg), NetMsgHeaderSize, 0, BytesSent);
end;
{--------}
procedure TCSCServer.SendInternalMsg(aMsg : longint;
aEvent : Boolean;
aClient : TCustomWinSocket;
aData : pointer;
aDataLen : LongInt;
aDataType : TNetMsgDataType;
aErrorCode : Word);
var
DataAsStream : TStream absolute aData;
DataAsBytes : PByteArray absolute aData;
TotalDataLen : longint;
BytesToGo : longint;
BytesToSend : longint;
StartOfs : longint;
FirstMsg : boolean;
LastMsg : boolean;
begin
{check for reentrancy}
if FBusy then Exit;
FBusy := true;
StartOfs := 0;
try
{ if (aDataType = nmdByteArray)
then TotalDataLen := aDataLen
else TotalDataLen := DataAsStream.Size;}
TotalDataLen := aDataLen;
{we're just about to send the first message of (maybe) many}
FirstMsg := true;
{send the message}
{..initialize loop variables}
BytesToGo := TotalDataLen;
if (aDataType = nmdByteArray)
then StartOfs := 0
else if aDataLen > 0
then DataAsStream.Position := 0;
{..send data in reasonably sized chunks}
repeat
{..set up the invariant parts of the message header}
with FSndBuffer^ do begin
nmhMsgID := aMsg;
nmhEvent := aEvent;
nmhTotalSize := TotalDataLen;
nmhErrorCode := aErrorCode;
nmhDataType := aDataType;
end;
{calculate the size of data in this message packet}
BytesToSend := MinIntValue([BytesToGo,
MaxNetMsgSize-NetMsgHeaderSize]);
LastMsg := (BytesToSend = BytesToGo);
with FSndBuffer^ do begin
nmhMsgLen := NetMsgHeaderSize + BytesToSend;
nmhFirst := FirstMsg;
nmhLast := LastMsg;
end;
if (BytesToSend > 0) then begin
if (aDataType = nmdByteArray)
then Move(DataAsBytes^[StartOfs], FSndBuffer^.nmhData, BytesToSend)
else DataAsStream.Read(FSndBuffer^.nmhData, BytesToSend);
end;
MsgQueue.AddPacket(PByteArray(FSndBuffer), aClient, NetMsgHeaderSize + BytesToSend);
if not LastMsg then begin
dec(BytesToGo, BytesToSend);
if (aDataType = nmdByteArray)
then inc(StartOfs, BytesToSend);
FirstMsg := false;
end;
until LastMsg;
finally
{we're no longer busy}
FBusy := false;
end;
end;
procedure TCSCServer.SendMsg(aMsg : longint;
aEvent : Boolean;
aClient : TCustomWinSocket;
aData : pointer;
aDataLen : LongInt;
aDataType : TNetMsgDataType;
aErrorCode : Word);
var
DataAsStream : TStream absolute aData;
DataAsBytes : PByteArray absolute aData;
TotalDataLen : longint;
BytesToGo : longint;
BytesToSend : longint;
BytesSent : longint;
StartOfs : longint;
FirstMsg : boolean;
LastMsg : boolean;
begin
{check for reentrancy}
if FBusy then
Exit;
StartOfs := 0;
FBusy := true;
try
{ if (aDataType = nmdByteArray)
then TotalDataLen := aDataLen
else TotalDataLen := DataAsStream.Size;}
TotalDataLen := aDataLen;
{we're just about to send the first message of (maybe) many}
FirstMsg := true;
{send the message}
{..initialize loop variables}
BytesToGo := TotalDataLen;
if (aDataType = nmdByteArray)
then StartOfs := 0
else if aDataLen > 0
then DataAsStream.Position := 0;
{..send data in reasonably sized chunks}
repeat
{..set up the invariant parts of the message header}
with FSndBuffer^ do begin
nmhMsgID := aMsg;
nmhEvent := aEvent;
nmhTotalSize := TotalDataLen;
nmhErrorCode := aErrorCode;
nmhDataType := aDataType;
end;
{calculate the size of data in this message packet}
BytesToSend := MinIntValue([BytesToGo,
MaxNetMsgSize-NetMsgHeaderSize]);
LastMsg := (BytesToSend = BytesToGo);
with FSndBuffer^ do begin
nmhMsgLen := NetMsgHeaderSize + BytesToSend;
nmhFirst := FirstMsg;
nmhLast := LastMsg;
end;
if (BytesToSend > 0) then begin
if (aDataType = nmdByteArray)
then Move(DataAsBytes^[StartOfs], FSndBuffer^.nmhData, BytesToSend)
else DataAsStream.Read(FSndBuffer^.nmhData, BytesToSend);
end;
if not LockSocket(aClient) then begin
Exit;
end;
try
with TCSCServerClientWinSocket(aClient) do
SndRcv.Send(PByteArray(FSndBuffer), NetMsgHeaderSize + BytesToSend, 0, BytesSent);
finally
aClient.Unlock;
end;
if not LastMsg then begin
LastMsg := not WaitForAckReply(aClient.Handle);
dec(BytesToGo, BytesToSend);
if (aDataType = nmdByteArray)
then inc(StartOfs, BytesToSend);
FirstMsg := false;
end;
until LastMsg;
finally
{we're no longer busy}
FBusy := false;
end;
end;
{--------}
procedure TCSCServer.OnGetSocket(Sender: TObject; Socket: TSocket; var ClientSocket: TServerClientWinSocket);
begin
ClientSocket := TCSCServerClientWinsocket.Create(Socket, FDaemon.Socket);
TCSCServerClientWinSocket(ClientSocket).SndRcv.OnMsgReceived := OnMsgReceived;
end;
{====================================================================}
constructor TCSCServerClientWinsocket.Create(Socket: TSocket; ServerWinSocket: TServerWinSocket);
begin
FSndRcv := TCSCSenderReceiver.Create(Self);
inherited Create(Socket, ServerWinSocket);
end;
destructor TCSCServerClientWinsocket.Destroy;
begin
FSndRcv.Free;
inherited;
end;
end.
|
{***************************************************************}
{* }
{* Purpose : The Editor dialog for Funnel or Pipeline Series }
{* Author : Marjan Slatinek, marjan@steema.com }
{* }
{***************************************************************}
unit TeeFunnelEditor;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
TeeFunnel, TeCanvas, TeePenDlg, TeeProcs;
type
TFunnelSeriesEditor = class(TForm)
ButtonPen1: TButtonPen;
ButtonPen2: TButtonPen;
Button1: TButton;
AboveColor: TButtonColor;
WithinColor: TButtonColor;
BelowColor: TButtonColor;
Label1: TLabel;
Edit1: TEdit;
DifLimit: TUpDown;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Funnel : TFunnelSeries;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeBrushDlg;
procedure TFunnelSeriesEditor.FormShow(Sender: TObject);
begin
Funnel:=TFunnelSeries(Tag);
if Assigned(Funnel) then
begin
ButtonPen1.LinkPen(Funnel.LinesPen);
ButtonPen2.LinkPen(Funnel.Pen);
AboveColor.LinkProperty(Funnel,'AboveColor');
WithinColor.LinkProperty(Funnel,'WithinColor');
BelowColor.LinkProperty(Funnel,'BelowColor');
DifLimit.Position:=Round(Funnel.DifferenceLimit);
end;
end;
procedure TFunnelSeriesEditor.Button1Click(Sender: TObject);
begin
EditChartBrush(Self,Funnel.Brush);
end;
procedure TFunnelSeriesEditor.Edit1Change(Sender: TObject);
begin
if Showing then Funnel.DifferenceLimit:=DifLimit.Position;
end;
procedure TFunnelSeriesEditor.FormCreate(Sender: TObject);
begin
Align:=alClient;
end;
initialization
RegisterClass(TFunnelSeriesEditor);
end.
|
program Sample;
function Add(A,B : Integer) : Integer;
begin
Add := A + B
end;
begin
WriteLn('A + B = ', Add(1,2))
end.
|
unit ExpenseController;
interface
uses
Classes, Expense, AccountTitle, Generics.Collections;
type
TExpenseController = class
private
FExpense: TExpense;
FData: TDataModule;
FTitles: TObjectList<TAccountTitle>;
public
property Expense: TExpense read FExpense write FExpense;
property Data: TDataModule read FData write FData;
property Titles: TObjectList<TAccountTitle> read FTitles write FTitles;
procedure Save;
procedure Add;
constructor Create(AData: TDataModule);
destructor Destroy;
end;
implementation
uses
ExpenseDataMethodsIntf, SysUtils;
{ TExpenseController }
procedure TExpenseController.Add;
var
intf: IExpenseDataMethods;
begin
if Supports(FData,IExpenseDataMethods,intf) then
intf.Add;
end;
constructor TExpenseController.Create(AData: TDataModule);
var
intf: IExpenseDataMethods;
begin
inherited Create;
FExpense := TExpense.Create;
FData := AData;
if Supports(FData,IExpenseDataMethods,intf) then
FTitles := intf.GetAccountTitles;
end;
destructor TExpenseController.Destroy;
begin
FExpense.Free;
FData.Free;
FTitles.Destroy;
inherited;
end;
procedure TExpenseController.Save;
var
intf: IExpenseDataMethods;
begin
if Supports(FData,IExpenseDataMethods,intf) then
intf.Save(FExpense);
end;
end.
|
unit fCoverSheetDetailDisplay;
{
================================================================================
*
* Application: CPRS - Coversheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: ####-##-##
*
* Description: Main form for displaying detail on coversheet items.
*
* Notes:
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls;
type
TfrmCoverSheetDetailDisplay = class(TForm)
pnlOptions: TPanel;
btnClose: TButton;
memDetails: TMemo;
btnPrint: TButton;
lblFontSizer: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmCoverSheetDetailDisplay: TfrmCoverSheetDetailDisplay;
function ReportBox(aText: TStrings; aTitle: string; aAllowPrint: boolean): boolean;
implementation
{$R *.dfm}
{ TfrmCoverSheetDetailDisplay }
function ReportBox(aText: TStrings; aTitle: string; aAllowPrint: boolean): boolean;
var
aStr: string;
aWidth: integer;
aCurWidth: integer;
aMaxWidth: integer;
begin
with TfrmCoverSheetDetailDisplay.Create(Application.MainForm) do
try
memDetails.Lines.Clear;
memDetails.ScrollBars := ssVertical;
aCurWidth := 300;
aMaxWidth := Screen.Width - 100;
lblFontSizer.Font := memDetails.Font;
for aStr in aText do
begin
aWidth := lblFontSizer.Canvas.TextWidth(aStr);
if aWidth > aCurWidth then
if aWidth < aMaxWidth then
aCurWidth := aWidth
else
begin
aCurWidth := aMaxWidth;
memDetails.ScrollBars := ssHorizontal;
end;
memDetails.Lines.Add(aStr);
end;
Caption := aTitle;
btnPrint.Visible := aAllowPrint;
ClientWidth := aCurWidth + 50;
ShowModal;
finally
Free;
end;
Result := True;
end;
end.
|
program nasledujuca_permutacia;
function nasledujucaVacsia(permutacia : string; index: word) : word;
var
najIndex, i: word;
begin
najIndex := index+1;
for i:=index + 2 to length(permutacia) do
begin
if (permutacia[i] > permutacia[index]) and
(permutacia[i] <= permutacia[najIndex]) then
najIndex := i;
end;
nasledujucaVacsia := najIndex;
end;
procedure swap(var permutacia : string; i1, i2:word);
var
tmp: char;
begin
tmp := permutacia[i1];
permutacia[i1] := permutacia[i2];
permutacia[i2] := tmp;
end;
procedure otoc(var permutacia: string; indexStart, indexEnd: word);
var
i: word;
begin
for i:=indexStart to indexEnd-1 do
begin
swap(permutacia, i,i+1);
end;
if (indexStart < i) then
otoc(permutacia,indexStart, indexEnd-1);
end;
var
permutacia: string;
i: word;
begin
readln(permutacia);
i := length(permutacia) - 1;
// Citame kym je zprava rastuca.
while (i > 0) and (permutacia[i] > permutacia[i+1]) do
begin
i -= 1;
end;
if (i = 0) then writeln('Toto je lexikograficky posledna permutacia.')
else
begin
swap(permutacia, i, nasledujucaVacsia(permutacia,i));
otoc(permutacia, i+1, length(permutacia));
writeln(permutacia);
end;
readln;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.EdgeService;
interface
{$HPPEMIT LINKUNIT}
uses System.SysUtils, System.Classes,
REST.Backend.EMSProvider, REST.Backend.EMSApi,
REST.Backend.ServiceComponents, REST.Backend.Providers,
REST.Backend.ServiceTypes, System.JSON, EMSHosting.RequestTypes;
type
IBackendEdgemoduleAPI = interface;
IBackendEdgemoduleService = interface;
// Wrapper
TBackendEdgemoduleApi = class(TBackendAuthenticationApi)
private
FServiceApi: IBackendEdgemoduleAPI;
FService: IBackendEdgemoduleService;
function GetServiceAPI: IBackendEdgemoduleAPI;
function GetModuleID: string;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AApi: IBackendEdgemoduleAPI); overload;
constructor Create(const AService: IBackendEdgemoduleService); overload;
procedure RegisterModule(const AName: string;
const AModuleDetails: TJSONObject; const AProtocolName, AProtocolProperties: string;
const AResources: TJSONArray);
procedure UnregisterModule;
property ProviderAPI: IBackendEdgemoduleAPI read FServiceAPI;
property ModuleID: string read GetModuleID;
end;
IBackendEdgemoduleAPI = interface
['{DF5C4F53-5058-4E75-A33B-ABC5D07139B2}']
procedure RegisterModule(const AName: string;
const AModuleDetails: TJSONObject; const AProtocolName, AProtocolProperties: string;
const AResources: TJSONArray);
procedure UnregisterModule;
function GetModuleID: string;
property ModuleID: string read GetModuleID;
end;
IBackendEdgemoduleService = interface(IBackendService)
['{80409801-58DB-4DEF-8207-EA0E28773C89}']
function GetModuleAPI: IBackendEdgemoduleAPI;
function CreateModuleApi: IBackendEdgemoduleAPI;
property ModuleAPI: IBackendEdgemoduleAPI read GetModuleAPI;
end;
TEMSEdgeListener = class;
TCustomEMSEdgeService = class(TBackendServiceComponentAuth<IBackendEdgemoduleService, TBackendEdgemoduleApi>)
public type
THandledEvent = procedure(Sender: TObject; var AHandled: Boolean) of object;
TRegisteringEvent = procedure(Sender: TObject; const AModuleDetail: TJSONObject; const AResources: TJSONArray; var AHandled: Boolean) of object;
private
FModuleName: string;
FAutoActivate: Boolean;
FAutoRegister: Boolean;
FAutoUnRegister: Boolean;
FDeferActive: Boolean;
FListenerProtocol: string;
FListenerService: TEMSEdgeListener;
FOnUnregistering: THandledEvent;
FOnRegistered: TNotifyEvent;
FOnUnregistered: TNotifyEvent;
FOnRegistering: TRegisteringEvent;
FModuleVersion: string;
function GetModuleAPI: TBackendEdgemoduleApi;
function GetProviderService: IBackendEdgemoduleService;
procedure SetModuleName(const Value: string);
procedure CheckModuleName;
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
procedure SetListenerProtocol(const Value: string);
procedure CheckListenerProtocol;
procedure SetModuleVersion(const Value: string);
function GetModuleID: string;
protected
procedure Loaded; override;
function InternalCreateBackendServiceAPI: TBackendEdgemoduleApi; override;
function InternalCreateIndependentBackendServiceAPI: TBackendEdgemoduleApi; override;
function CreateAuthAccess: IAuthAccess; override;
procedure DoOnRegistering(const AModuleDetails: TJSONObject; const AResources: TJSONArray; var AHandled: Boolean); virtual;
procedure DoOnRegistered; virtual;
procedure DoOnUnregistering(var AHandled: Boolean); virtual;
procedure DoOnUnregistered; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ProviderChanged; override;
public
constructor Create(AOwner: TComponent); override;
procedure UnregisterModule;
procedure RegisterModule(const ADetails: TJSONObject = nil);
property Active: Boolean read GetActive write SetActive;
property ListenerProtocol: string read FListenerProtocol write SetListenerProtocol;
property ListenerService: TEMSEdgeListener read FListenerService;
property AutoActivate: Boolean read FAutoActivate write FAutoActivate default True;
property AutoRegister: Boolean read FAutoRegister write FAutoRegister default True;
property AutoUnRegister: Boolean read FAutoUnRegister write FAutoUnRegister default True;
property ModuleName: string read FModuleName write SetModuleName;
property ModuleVersion: string read FModuleVersion write SetModuleVersion;
property ModuleAPI: TBackendEdgemoduleApi read GetModuleAPI;
property ModuleID: string read GetModuleID;
property ProviderService: IBackendEdgemoduleService read GetProviderService;
property OnRegistering: TRegisteringEvent read FOnRegistering write FOnRegistering;
property OnRegistered: TNotifyEvent read FOnRegistered write FOnRegistered;
property OnUnregistering: THandledEvent read FOnUnregistering write FOnUnregistering;
property OnUnregistered: TNotifyEvent read FOnUnregistered write FOnUnregistered;
function CreateModuleAPI: TBackendEdgemoduleApi;
end;
TEMSEdgeService = class(TCustomEMSEdgeService)
published
property AutoActivate;
property AutoRegister;
property AutoUnRegister;
property ModuleName;
property ModuleVersion;
property Provider;
property Auth;
property ListenerProtocol;
property ListenerService;
property OnRegistering;
property OnUnregistering;
property OnRegistered;
property OnUnregistered;
end;
TEMSEdgeListener = class(TComponent)
public type
TModule = class abstract
private
FModuleName: string;
FModuleVersion: string;
public
constructor Create(const AModuleName, AModuleVersion: string);
function GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>; virtual; abstract;
function UserIDOfSession(const ASessionToken: string; out AUserID: string): Boolean; virtual; abstract;
function UserNameOfID(const AUserID: string; out AUserName: string): Boolean; virtual; abstract;
function GetTenantNameByTenantId(const ATenantId: string): string; virtual; abstract;
property ModuleName: string read FModuleName;
property ModuleVersion: string read FModuleVersion;
end;
TModuleContext = class(TEMSEdgeHostContext)
private
FModule: TEMSEdgeListener.TModule;
protected
function GetModuleName: string; override;
function GetModuleVersion: string; override;
function GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>; override;
function UserIDOfSession(const ASessionID: string; out AUserID: string): Boolean; override;
function UserNameOfID(const AUserID: string; out AUserName: string): Boolean; override;
function GetTenantNameByTenantId(const ATenantId: string): string; override;
public
constructor Create(const AModule: TEMSEdgeListener.TModule);
end;
TCreateModuleEvent = reference to function: TModule;
private
FProtocolProps: TJSONObject;
FOnCreateModule: TCreateModuleEvent;
function GetProtocolProps: TJSONObject;
protected
function CreateModule: TModule;
function GetActive: Boolean; virtual; abstract;
procedure SetActive(const Value: Boolean); virtual; abstract;
procedure AddProtocolProps(const AProperties: TJSONObject); virtual; abstract;
function GetModule: TModule; virtual; abstract;
public
destructor Destroy; override;
property Active: Boolean read GetActive write SetActive;
property Module: TModule read GetModule;
property ProtocolProps: TJSONObject read GetProtocolProps;
property OnCreateModule: TCreateModuleEvent read FOnCreateModule write FOnCreateModule;
end;
implementation
uses REST.Backend.ServiceFactory, System.Generics.Collections, REST.Backend.EMSServices,
EMS.ResourceAPI, EMS.ResourceTypes, EMSHosting.EdgeListeners, EMSHosting.ExtensionsServices,
EMSHosting.Consts, EMSHosting.APIDocResource, EMSHosting.APIDocConsts;
{ TCustomBackendModule }
constructor TCustomEMSEdgeService.Create(AOwner: TComponent);
begin
inherited;
FAutoActivate := True;
FAutoRegister := True;
FAutoUnRegister := True;
FModuleVersion := '1';
end;
function TCustomEMSEdgeService.CreateAuthAccess: IAuthAccess;
begin
Result := TAuthAccess.Create(Self,
function: IBackendAuthenticationApi
begin
Result := Self.GetModuleAPI.AuthenticationApi;
end);
end;
function TCustomEMSEdgeService.CreateModuleAPI: TBackendEdgemoduleApi;
begin
Result := InternalCreateIndependentBackendServiceAPI;
end;
procedure TCustomEMSEdgeService.DoOnRegistering(const AModuleDetails: TJSONObject; const AResources: TJSONArray; var AHandled: Boolean);
begin
if Assigned(FOnRegistering) then
FOnRegistering(Self, AModuleDetails, AResources, AHandled);
end;
procedure TCustomEMSEdgeService.DoOnRegistered;
begin
if Assigned(FOnRegistered) then
FOnRegistered(Self);
end;
procedure TCustomEMSEdgeService.DoOnUnregistering(var AHandled: Boolean);
begin
if Assigned(FOnUnregistering) then
FOnUnregistering(Self, AHandled);
end;
procedure TCustomEMSEdgeService.DoOnUnregistered;
begin
if Assigned(FOnUnregistered) then
FOnUnregistered(Self);
end;
function TCustomEMSEdgeService.GetProviderService: IBackendEdgemoduleService;
begin
Result := GetBackendService;
end;
function TCustomEMSEdgeService.GetActive: Boolean;
begin
Result := (FListenerService <> nil) and FListenerService.Active;
end;
function TCustomEMSEdgeService.GetModuleAPI: TBackendEdgemoduleApi;
begin
Result := GetBackendServiceAPI;
end;
function TCustomEMSEdgeService.GetModuleID: string;
begin
Result := ModuleAPI.ModuleID;
end;
function TCustomEMSEdgeService.InternalCreateBackendServiceAPI: TBackendEdgemoduleApi;
begin
Result := TBackendEdgemoduleApi.Create(GetBackendService); // Service.CreateModuleAPI);
end;
function TCustomEMSEdgeService.InternalCreateIndependentBackendServiceAPI: TBackendEdgemoduleApi;
begin
Result := TBackendEdgemoduleApi.Create(GetBackendService.CreateModuleAPI); // Service.CreateModuleAPI);
end;
procedure TCustomEMSEdgeService.Loaded;
begin
try
inherited;
if FDeferActive then
begin
FDeferActive := False;
SetActive(True)
end
else if AutoActivate and (Provider <> nil) then
SetActive(True);
except
// Do not raise exception while loading
end;
end;
procedure TCustomEMSEdgeService.ProviderChanged;
begin
if AutoActivate and (Provider <> nil) then
Active := True;
end;
procedure TCustomEMSEdgeService.CheckModuleName;
begin
if ModuleName = '' then
raise Exception.Create(sEdgeModuleNameBlank);
end;
procedure TCustomEMSEdgeService.CheckListenerProtocol;
begin
if ListenerProtocol = '' then
raise Exception.Create(sEdgeProtocolBlank);
end;
procedure TCustomEMSEdgeService.RegisterModule(const ADetails: TJSONObject);
var
LProtocolProperties: string;
LResource: TEMSResource;
LJSONResources: TJSONArray;
LJSONResource: TJSONObject;
LHandled: Boolean;
LDetails: TJSONObject;
begin
LJSONResources := nil;
LDetails := ADetails;
try
for LResource in TEMSEndpointManager.Instance.Resources do
begin
if LJSONResources = nil then
LJSONResources := TJSONArray.Create;
LJSONResource := TJSONObject.Create;
LJSONResources.AddElement(LJSONResource);
LJSONResource.AddPair('resourcename', LResource.Name); // Do not localize
end;
LHandled := False;
if ADetails <> nil then
// Make a copy for event handler to modify
LDetails := ADetails.Clone as TJSONObject
else
LDetails := TJSONObject.Create;
DoOnRegistering(LDetails, LJSONResources, LHandled);
if not LHandled then
begin
CheckModuleName;
CheckListenerProtocol;
if ListenerService <> nil then
LProtocolProperties := ListenerService.ProtocolProps.ToJSON;
ModuleAPI.RegisterModule(
ModuleName, LDetails, Self.ListenerProtocol, LProtocolProperties, LJSONResources);
DoOnRegistered;
end;
finally
LJSONResources.Free;
if LDetails <> ADetails then
LDetails.Free;
end;
end;
procedure TCustomEMSEdgeService.SetActive(const Value: Boolean);
begin
if Active <> Value then
begin
if csLoading in ComponentState then
FDeferActive := Value
else
begin
if not (csDesigning in ComponentState) then
begin
if FListenerService <> nil then
FListenerService.Active := Value;
if Active then
begin
if FAutoRegister then
RegisterModule;
end
else
if FAutoUnRegister then
if ModuleID <> '' then
UnregisterModule;
end;
end;
end;
end;
procedure TCustomEMSEdgeService.Notification(
AComponent: TComponent; Operation: TOperation);
begin
inherited;
/// clean up component-references
if Operation = opRemove then
begin
if FListenerService = AComponent then
FListenerService := nil;
end;
end;
procedure TCustomEMSEdgeService.SetModuleName(const Value: string);
begin
FModuleName := Value;
end;
procedure TCustomEMSEdgeService.SetModuleVersion(const Value: string);
begin
FModuleVersion := Value;
end;
type
TCustomModule = class(TEMSEdgeListener.TModule)
private
FAPI: TEMSClientAPI;
protected
function GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>; override;
function UserIDOfSession(const SessionToken: string; out AUserID: string): Boolean; override;
function UserNameOfID(const AUserID: string; out AUserName: string): Boolean; override;
function GetTenantNameByTenantId(const ATenantId: string): string; override;
public
constructor Create(const AModuleName, AModuleVersion: string);
destructor Destroy; override;
procedure UpdateAPI(const AProvider: TEMSProvider);
end;
constructor TCustomModule.Create(const AModuleName, AModuleVersion: string);
begin
inherited Create(AModuleName, AModuleVersion);
FAPI := TEMSClientAPI.Create;
end;
procedure TCustomModule.UpdateAPI(const AProvider: TEMSProvider);
begin
AProvider.UpdateApi(FAPI);
end;
destructor TCustomModule.Destroy;
begin
FAPI.Free;
inherited;
end;
function TCustomModule.GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>;
begin
Result := FAPI.RetrieveUserGroups(AUserID);
end;
function TCustomModule.GetTenantNameByTenantId(const ATenantId: string): string;
begin
Result := '';
end;
function TCustomModule.UserIDOfSession(const SessionToken: string; out AUserID: string): Boolean;
var
LUserID: string;
begin
FAPI.Login(SessionToken);
try
Result := FAPI.RetrieveCurrentUser(
procedure(const AUser: TEMSClientAPI.TUser; const AObj: TJSONObject)
begin
LUserID := AUser.UserID;
end);
if Result then
AUserID := LUserID;
finally
FAPI.Logout;
end;
end;
function TCustomModule.UserNameOfID(const AUserID: string; out AUserName: string): Boolean;
var
LUserName: string;
begin
Result := FAPI.RetrieveUser(AUserID,
procedure(const AUser: TEMSClientAPI.TUser;
const AObj: TJSONObject)
begin
LUserName := AUser.UserName;
end);
if Result then
AUserName := LUserName;
end;
procedure TCustomEMSEdgeService.SetListenerProtocol(const Value: string);
var
LFactory: TEMSEdgeListenerFactory;
begin
if FListenerProtocol <> Value then
begin
FreeAndNil(FListenerService);
FListenerProtocol := '';
if Value <> '' then
begin
if TEMSEdgeListenerFactories.Instance.TryGetFactory(Value, LFactory) then
begin
FListenerService := LFactory.CreateListener(Self, Value);
FListenerService.OnCreateModule :=
function: TEMSEdgeListener.TModule
var
LModule: TCustomModule;
begin
LModule := TCustomModule.Create(Self.ModuleName, Self.ModuleVersion);
try
if Provider is TEMSProvider then
LModule.UpdateAPI(TEMSProvider(Provider));
Result := LModule;
except
LModule.Free;
raise;
end;
end;
end
else
raise Exception.CreateFmt(sEdgeUnknownListenerProtocol, [Value]);
FListenerProtocol := Value;
if FListenerService <> nil then
begin
FListenerService.Name := 'ListenerService'; // Do not localize
FListenerService.SetSubComponent(True);
end;
end;
end;
end;
procedure TCustomEMSEdgeService.UnregisterModule;
var
LHandled: Boolean;
begin
LHandled := False;
if Assigned(OnUnregistering) then
OnUnregistering(Self, LHandled);
if not LHandled then
begin
ModuleAPI.UnregisterModule;
if Assigned(OnUnregistered) then
OnUnregistered(Self);
end;
end;
function TBackendEdgemoduleApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendEdgemoduleApi.GetModuleID: string;
begin
Result := GetServiceApi.ModuleID;
end;
function TBackendEdgemoduleApi.GetServiceAPI: IBackendEdgemoduleAPI;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetModuleApi
end;
procedure TBackendEdgemoduleApi.RegisterModule(const AName: string;
const AModuleDetails: TJSONObject; const AProtocolName, AProtocolProperties: string;
const AResources: TJSONArray);
begin
GetServiceApi.RegisterModule(AName, AModuleDetails,
AProtocolName, AProtocolProperties, AResources);
end;
procedure TBackendEdgemoduleApi.UnregisterModule;
begin
GetServiceApi.UnRegisterModule;
end;
constructor TBackendEdgemoduleApi.Create(const AApi: IBackendEdgemoduleAPI);
begin
FServiceApi := AApi;
end;
constructor TBackendEdgemoduleApi.Create(const AService: IBackendEdgemoduleService);
begin
FService := AService;
end;
type
TEMSModuleAPI = class(TEMSLoginAPI, IBackendEdgemoduleAPI)
private
FModuleID: string;
protected
procedure RegisterModule(const AName: string;
const AModuleDetails: TJSONObject; const AProtocolName, AProtocolProperties: string;
const AResources: TJSONArray);
procedure UnregisterModule;
function GetModuleID: string;
end;
TEMSModuleService = class(TEMSBackendService<TEMSModuleAPI>, IBackendService,
IBackendEdgemoduleService)
protected
{ IBackendModuleService }
function CreateModuleApi: IBackendEdgemoduleAPI;
function GetModuleApi: IBackendEdgemoduleAPI;
end;
{ TEMSModuleAPI }
function TEMSModuleAPI.GetModuleID: string;
begin
Result := FModuleID;
end;
procedure TEMSModuleAPI.RegisterModule(const AName: string;
const AModuleDetails: TJSONObject; const AProtocolName, AProtocolProperties: string;
const AResources: TJSONArray);
var
LModule: TEMSClientAPI.TModule;
LUpdatedAt: TEMSClientAPI.TUpdatedAt;
begin
if FModuleID <> '' then
begin
try
EMSAPI.UpdateModule(FModuleID, AName, AProtocolName, AProtocolProperties, AModuleDetails, AResources, LUpdatedAt)
except
FModuleID := '';
raise;
end;
end
else
begin
EMSAPI.RegisterModule(AName, AProtocolName, AProtocolProperties, AModuleDetails, AResources, LModule);
FModuleID := LModule.ModuleID;
end;
end;
procedure TEMSModuleAPI.UnregisterModule;
begin
if FModuleID = '' then
raise Exception.Create('Can''t unregister module. ModuleID is blank.');
try
EMSAPI.UnregisterModule(FModuleID);
finally
FModuleID := '';
end;
end;
{ TEMSModuleService }
function TEMSModuleService.CreateModuleApi: IBackendEdgemoduleAPI;
begin
Result := CreateBackendApi;
end;
function TEMSModuleService.GetModuleApi: IBackendEdgemoduleAPI;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
var
FFactories: TList<TProviderServiceFactory>;
procedure RegisterServices;
var
LFactory: TProviderServiceFactory;
begin
FFactories := TObjectList<TProviderServiceFactory>.Create;
LFactory := TEMSProviderServiceFactory<IBackendEdgemoduleService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TEMSModuleService.Create(AProvider);
end);
FFactories.Add(LFactory);
for LFactory in FFactories do
LFactory.Register;
end;
procedure UnregisterServices;
var
LFactory: TProviderServiceFactory;
begin
for LFactory in FFactories do
LFactory.Unregister;
FreeAndNil(FFactories);
end;
type
TModuleJSONNames = record
public const
ModuleVersion = 'moduleversion';
ModuleName = 'modulename';
sGetVersion = 'GetVersion';
sVersion = 'version';
end;
[ResourceName(TModuleJSONNames.sVersion)]
[EndPointObjectsYAMLDefinitions(EdgeVersionObjectsYMALDefinition)]
[EndPointObjectsJSONDefinitions(EdgeVersionObjectsJSONDefinition)]
{$METHODINFO ON}
TVersionResource = class
published
[EndpointName(TModuleJSONNames.sGetVersion)]
[EndPointRequestSummary(cVersionTag, cGetVersionSummaryTitle, cGetVersionSummaryDesc, cApplicationJSON, '')]
[EndPointResponseDetails(200, cResponseOK, TAPIDoc.TPrimitiveType.spObject, TAPIDoc.TPrimitiveFormat.None, '', '#/definitions/versionEdgeObject')]
procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
{$METHODINFO OFF}
procedure RegisterVersionResource;
begin
RegisterResource(TypeInfo(TVersionResource));
end;
procedure TVersionResource.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LValue: TJSONObject;
LVersion: string;
LModuleName: string;
begin
if AContext.Edgemodule <> nil then
begin
LVersion := AContext.Edgemodule.ModuleVersion;
LModuleName := AContext.Edgemodule.ModuleName;
end;
LValue := TJSONObject.Create;
try
LValue.AddPair(TModuleJSONNames.ModuleVersion, TJSONString.Create(LVersion));
LValue.AddPair(TModuleJSONNames.ModuleName, TJSONString.Create(LModuleName));
AResponse.Body.SetValue(LValue, False);
finally
LValue.Free;
end;
end;
{ TEMSEdgeListener }
function TEMSEdgeListener.CreateModule: TModule;
begin
if Assigned(FOnCreateModule) then
Result := FOnCreateModule()
else
Result := nil;
end;
destructor TEMSEdgeListener.Destroy;
begin
FProtocolProps.Free;
inherited;
end;
function TEMSEdgeListener.GetProtocolProps: TJSONObject;
begin
FProtocolProps.Free;
FProtocolProps := TJSONObject.Create;
// Refresh
Self.AddProtocolProps(FProtocolProps);
Result := FProtocolProps;
end;
{ TEMSEdgeListener.TModule }
constructor TEMSEdgeListener.TModule.Create(const AModuleName,
AModuleVersion: string);
begin
FModuleName := AModuleName;
FModuleVersion := AModuleVersion;
end;
{ TEMSEdgeListener.TModuleContext }
constructor TEMSEdgeListener.TModuleContext.Create(
const AModule: TEMSEdgeListener.TModule);
begin
FModule := AModule;
end;
function TEMSEdgeListener.TModuleContext.GetGroupsByUser(
const AUserID, ATenantId: string): TArray<string>;
begin
Result := FModule.GetGroupsByUser(AUserID, ATenantId);
end;
function TEMSEdgeListener.TModuleContext.GetModuleName: string;
begin
Result := FModule.ModuleName;;
end;
function TEMSEdgeListener.TModuleContext.GetModuleVersion: string;
begin
Result := FModule.ModuleVersion;
end;
function TEMSEdgeListener.TModuleContext.GetTenantNameByTenantId(
const ATenantId: string): string;
begin
Result := FModule.GetTenantNameByTenantId(ATenantId);
end;
function TEMSEdgeListener.TModuleContext.UserIDOfSession(
const ASessionID: string; out AUserID: string): Boolean;
begin
Result := FModule.UserIDOfSession(ASessionID, AUserID);
end;
function TEMSEdgeListener.TModuleContext.UserNameOfID(const AUserID: string;
out AUserName: string): Boolean;
begin
Result := FModule.UserNameOfID(AUserID, AUserName);
end;
initialization
TResourceStringsTable.Add(cResponseOK, sResponseOK);
TResourceStringsTable.Add(cGetVersionSummaryTitle, sGetVersionSummaryTitle);
TResourceStringsTable.Add(cGetVersionSummaryDesc, sGetVersionSummaryDesc);
RegisterServices;
RegisterVersionResource;
RegisterAPIDocResource;
finalization
UnregisterServices;
end.
|
namespace Anonymous_Methods;
interface
uses
System.Threading,
System.Windows.Forms;
type
Program = assembly static class
public
class method Main;
end;
implementation
/// <summary>
/// The main entry point for the application.
/// </summary>
//[STAThread]
class method Program.Main;
begin
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Default exception handler - using an anonymous method.
Application.ThreadException += method (sender: Object; e: ThreadExceptionEventArgs);
begin
MessageBox.Show(e.Exception.Message);
end;
using lMainForm := new MainForm do
Application.Run(lMainForm);
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Internal.MachExceptions;
{
<code>MachExceptions</code> contains the OS specific code for setting up Mach
exception handlers. These handlers catch hardware exceptions, such as
floating point errors, memory access violations, and illegal instructions.<p>
The Mach exception API is used for these exceptions instead of sigaction and
friends because of GDB issues. There is a long standing bug with GDB that
prevents signal handlers for the above exceptions from being invoked when
the child process is run under GDB.<p>
Note that Ctrl-C handling doesn't come through this layer of support. The
Mach exception handling ports never see such user interrupt methods. Instead
we use the POSIX signal APIs to deal with those. GDB is well behaved for those
signals.<p>
On initialization, the exception handling code allocates a Mach exception
handling port, and spins up a pthread to watch that port. Mach uses a message
passing model to inform the watcher thread of exceptions on other threads.
The watcher thread processes the exception, and then modifies the pending
thread to cause it to transfer control to the RTL, where somewhat more
platform independent code can take over to raise a standard language
exception.<p>
}
interface
{
Initializes the Mach exception handling system. This will allocate a
Mach exception port, and spin up a POSIX thread. This API should only
be called once per process.
}
procedure MachExceptionsInit;
{
Shuts down the Mach exception handling system for the task. This API
should only be called once per process.
}
procedure MachExceptionsShutdown;
implementation
uses Macapi.Mach, System.SysUtils, Posix.SysTypes, Posix.Pthread, System.Internal.ExcUtils, System.SysConst;
const
{
We save off the old exception ports for the task. We expect a maximum
of 16 of these for any task.
}
MAX_EXCEPTION_PORTS = 16;
var
{ This is the Mach exception port that our POSIX thread will be watching. }
ExceptionPort: mach_port_t;
{ The following hold the old port information when we install our exception
port. }
OldPortMasks: array [0..MAX_EXCEPTION_PORTS-1] of exception_mask_t;
OldPorts: array [0..MAX_EXCEPTION_PORTS-1] of exception_handler_t;
OldBehaviors: array [0..MAX_EXCEPTION_PORTS-1] of exception_behavior_t;
OldFlavors: array [0..MAX_EXCEPTION_PORTS-1] of thread_state_flavor_t;
OldPortCount: mach_msg_type_number_t;
type
{
The reply message structure for Mach messages. The actual maximum
payload size for messages is not defined in Mach. The values below
are drawn from the source code for Xnu, apparently. These values
were obtained from an example found on the web.
}
MachMsgReply = record
header: mach_msg_header_t;
data: array [0..255] of Byte;
end;
{
The send message structure for Mach messages. See the comment
on <code>MachMsgReply</code> for information about the structure size.
}
MachMsgSend = record
header: mach_msg_header_t;
body: mach_msg_body_t;
data: array [0..1023] of Byte;
end;
{
This is our POSIX thread function. It watches for messages on the exception
port, and dispatches them as needed.<p>
Some Mach exception APIs are used here, and these can fail. If they do, we
have no really viable options for recovering, and we just abort the task.
Presumably, the relevant APIs can only fail under some catastrophic
circumstances, in which case, the definition of 'recovery' would be pretty
subjective anyway.
}
function ExcThread(Parameter: Pointer): Pointer; cdecl;
var
R: mach_msg_return_t;
Reply: MachMsgReply;
Msg: MachMsgSend;
begin
while true do
begin
R := mach_msg(Msg.header, MACH_RCV_MSG or MACH_RCV_LARGE,
0, SizeOf(Msg), ExceptionPort,
MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
if R <> MACH_MSG_SUCCESS then
abort;
{
exc_server is not documented anywhere, really. It isn't defined
in any Mach header files. It handles all the book-keeping on the
Mach messages to dispatch messages to the appropriate catch_*
APIs, which the client application may have defined.
}
if not exc_server(Msg.header, Reply.header) then
abort;
R := mach_msg(Reply.header, MACH_SEND_MSG, Reply.header.msgh_size,
0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
if R <> MACH_MSG_SUCCESS then
abort;
end;
end;
procedure MachExceptionsInit;
var
Task: mach_port_t;
KRes: kern_return_t;
Mask: exception_mask_t;
Attr: pthread_attr_t;
Thread: pthread_t;
begin
Task := mach_task_self;
KRes := mach_port_allocate(Task, MACH_PORT_RIGHT_RECEIVE, ExceptionPort);
if KRes <> MACH_MSG_SUCCESS then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
KRes := mach_port_insert_right(Task, ExceptionPort, ExceptionPort, MACH_MSG_TYPE_MAKE_SEND);
if KRes <> MACH_MSG_SUCCESS then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
Mask := EXC_MASK_BAD_ACCESS or EXC_MASK_ARITHMETIC or EXC_MASK_BAD_INSTRUCTION;
KRes := task_get_exception_ports(Task, Mask, @OldPortMasks, OldPortCount, @OldPorts,
@OldBehaviors, @OldFlavors);
if KRes <> MACH_MSG_SUCCESS then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
KRes := task_set_exception_ports(Task, Mask, ExceptionPort, EXCEPTION_STATE_IDENTITY, MACHINE_THREAD_STATE);
if KRes <> MACH_MSG_SUCCESS then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
if pthread_attr_init(Attr) <> 0 then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
if pthread_attr_setdetachstate(Attr, PTHREAD_CREATE_DETACHED) <> 0 then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
if pthread_create(Thread, Attr, @ExcThread, nil) <> 0 then
raise Exception.CreateRes(@SOSExceptionHandlingFailed);
pthread_attr_destroy(Attr);
end;
procedure MachExceptionsShutdown;
begin
{
We're keeping this as a placeholder in case we do decide to shut down the
POSIX thread watching the exception ports, or free up the Mach resources
for the exception ports. Currently, we don't see the need for it, so we
will allow the OS to dispose of those resources when it shuts down the
task.
}
end;
{
Some floating point status word constants. These same constants
work for the MXCSR, too.
}
const
PRECISION_MASK = 1 shl 5;
UNDERFLOW_MASK = 1 shl 4;
OVERFLOW_MASK = 1 shl 3;
ZERODIVIDE_MASK = 1 shl 2;
DENORMAL_MASK = 1 shl 1;
INVALIDOP_MASK = 1 shl 0;
{
Floating point exceptions for both the FPU and SSE are masked and have
their status represented in the same bit order, but at different bit offsets
in their respective status and control words. The FPU has the floating point
status word, and the floating point control word. The control word holds the
exception masks, and the status word holds the signalled exceptions. In both
words, the bits of interest are 0-5, which is convenient.
The SSE unit has just the one control/status word, with mask and status bits
in different bit positions, but in the same bit order as for the FPU control
and status words. So we can use a single function to test for the masking
state and status state of a given floating point exception by just passing
shifted bits of the various words to this little support function.
@param StatusBits - holds the floating point exception status bits.
These are bits 0-5 of the respective status registers.
@param Mask - holds bits 0-5 of the floating point mask bits. If a bit in the
mask is 1, then it means that exception is masked.
}
function UnmaskedExceptions(StatusBits: UInt16; Mask: UInt16): UInt16;
begin
Result := StatusBits and (not Mask);
end;
{
This function will be dispatched to from <code>exc_server</code>. This is
where we decode the exception, and set up the dispatch to the RTL on the
faulting thread.<p>
We call Mach support methods to inquire into the thread state. It's extremely
unlikely that these could ever fail, but if they do, then we have no way to
recover. In that event, we return a code which will cause the Mach exception
server to kill off the task.
The name of this function, as it is exported is important. See the comment
at the export statement at the end of this unit for more detail.
}
function catch_exception_raise_state_identity(
ExceptionPort: mach_port_name_t;
Thread: mach_port_t;
Task: mach_port_t;
ExceptionType: exception_type_t;
Code: exception_data_t;
CodeCount: mach_msg_type_number_t;
var Flavor: Integer;
OldState: thread_state_t;
OldStateCount: Integer;
NewState: thread_state_t;
var NewStateCount: Integer): kern_return_t; cdecl;
var
ExceptionStateCount: mach_msg_type_number_t;
//ThreadStateCount: mach_msg_type_number_t;
FloatStateCount: mach_msg_type_number_t;
ExceptionState: x86_exception_state_t;
ThreadState: Px86_thread_state_t;
FloatState: x86_float_state_t;
KRes: kern_return_t;
ExcCode: Integer;
FPExceptions: UInt16;
begin
KRes := thread_get_state(Thread, x86_EXCEPTION_STATE,
thread_state_t(@ExceptionState), ExceptionStateCount);
if KRes <> KERN_SUCCESS then
begin
// Fatal
Result := KERN_INVALID_ARGUMENT;
Exit;
end;
KRes := thread_get_state(Thread, x86_FLOAT_STATE,
thread_state_t(@FloatState), FloatStateCount);
if KRes <> KERN_SUCCESS then
begin
// Fatal
Result := KERN_INVALID_ARGUMENT;
Exit;
end;
ThreadState := Px86_thread_state_t(OldState);
// writeln(Format('Exception @%p, trap #%d(0x%x), err = %d(0x%x), esp = %p, fault addr=%p',
// [Pointer(ThreadState^.ts32.eip), ExceptionState.es32.__trapno,
// ExceptionState.es32.__trapno,
// ExceptionState.es32.__err, ExceptionState.es32.__err,
// Pointer(ThreadState^.ts32.esp),
// Pointer(ExceptionState.es32.__faultvaddr)]));
if (ExceptionState.es32.__trapno = $E) and
((ThreadState^.ts32.esp and $FFFFF000) = (ExceptionState.es32.__faultvaddr and $FFFFF000)) then
begin
// writeln('stack fault');
{
Stack fault. We can't allow the exception to be propagated back to the faulting thread,
or we'll loop (forever). We have to take down the app at this point.
}
Result := KERN_FAILURE;
Exit;
end;
Result := KERN_SUCCESS;
if ExceptionType = EXC_BAD_ACCESS then
begin
{
Memory access violation. E.g. segv. We don't care, really, what the
actual fault was - they all get dispatched the same way to the user.
}
ExcCode := Integer(System.reAccessViolation);
end
else if ExceptionType = EXC_ARITHMETIC then
begin
// writeln(format('FSW = %x, MXCSR = %x', [FloatState.fs32.fpu_fsw, FloatState.fs32.fpu_mxcsr]));
{
All arithmetic exceptions come here. This includes all floating point
violations, and integer violations. This depends, of course, on the
settings of the floating point and MX control words. We'll check to see if there
are unmasked exceptions flagged in either of them, and report on the first unmasked
exception we see, if any.
}
FPExceptions := UnmaskedExceptions(FloatState.fs32.fpu_fsw, FloatState.fs32.fpu_fcw);
FPExceptions := FPExceptions or
UnmaskedExceptions(FloatState.fs32.fpu_mxcsr, FloatState.fs32.fpu_mxcsr shr 7);
if (FPExceptions and PRECISION_MASK <> 0) then
ExcCode := Integer(System.reInvalidOp)
else if (FPExceptions and UNDERFLOW_MASK <> 0) then
ExcCode := Integer(System.reUnderflow)
else if (FPExceptions and OVERFLOW_MASK <> 0) then
ExcCode := Integer(System.reOverflow)
else if (FPExceptions and ZERODIVIDE_MASK <> 0) then
ExcCode := Integer(System.reZeroDivide)
else if (FPExceptions and DENORMAL_MASK <> 0) then
ExcCode := Integer(System.reInvalidOp)
else if (FPExceptions and INVALIDOP_MASK <> 0) then
ExcCode := Integer(System.reInvalidOp)
{
On OS X Lion, the OS will sometimes dispatch an integer
divide by zero here with __trapno set to $10000 instead of
0. This happens randomly. We currently believe this to be a
bug in the OS, and we guard against it by masking off the high
bits of the trap number before testing.
}
else if (ExceptionState.es32.__trapno and $FFFF) = 0 then
ExcCode := Integer(System.reDivByZero)
else
ExcCode := Integer(System.reInvalidOp); // shouldn't happen
end
else if ExceptionType = EXC_BAD_INSTRUCTION then
begin
{
Illegal instruction, or privileged instruction. We don't discriminate.
}
ExcCode := Integer(System.rePrivInstruction);
end
else
begin
ExcCode := 0;
{ This can't happen. We do the equivalent of asserting here. If we return
this value, the kernel will take down the process.
}
Result := KERN_INVALID_ARGUMENT;
end;
{
Now we set up the thread state for the faulting thread so that when we
return, control will be passed to the exception dispatcher on that thread,
and this POSIX thread will continue watching for Mach exception messages.
See the documentation at <code>DispatchMachException()</code> for more
detail on the parameters loaded in EAX, EDX, and ECX.
}
ThreadState^.ts32.eax := ThreadState^.ts32.eip;
ThreadState^.ts32.edx := ExceptionState.es32.__faultvaddr;
ThreadState^.ts32.ecx := ExcCode;
ThreadState^.ts32.eip := UIntPtr(@SignalConverter);
Px86_thread_state_t(NewState)^ := ThreadState^;
NewStateCount := OldStateCount;
end;
{
This export is required, as <code>exc_server</code> expects to be able to call
this function by this particular name.
}
exports
catch_exception_raise_state_identity name '_catch_exception_raise_state_identity';
end.
|
{*************************************************************}
{ }
{ Embarcadero Delphi Visual Component Library }
{ InterBase Express core components }
{ }
{ Copyright (c) 1998-2017 Embarcadero Technologies, Inc.}
{ All rights reserved }
{ }
{ Additional code created by Jeff Overcash and used }
{ with permission. }
{*************************************************************}
unit IBX.IBCSMonitor;
interface
uses
System.Classes, IBX.IBSQLMonitor, IBX.IBSQL, IBX.IBDatabase,
IBX.IBServices, IBX.IB, IPPeerAPI, System.Generics.Collections,
System.SyncObjs, System.SysUtils;
type
TIBContext = class
private
FQueue : TThreadList<TBytes>;
FEvent: TEvent;
FContext : IIPContext;
public
constructor Create(AContext : IIPContext);
destructor Destroy; override;
property Context : IIPContext read FContext;
procedure AddMsgToQueue(const Msg: TBytes);
function GetQueuedMsgs: TList<TBytes>;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TIBMonitorServer = class(TComponent, IIBSQLMonitorHook)
private
FidServer : IIPTCPServer;
FContexts : TObjectDictionary<IIPContext, TIBContext>;
FEnabled: Boolean;
FTraceFlags : TTraceFlags;
FOldmonitor : IIBSQLMonitorHook;
FActive : Boolean;
FPort: Integer;
procedure OnConnect (AContext: IIPContext);
procedure OnDisconnect(AContext: IIPContext);
procedure ServerExecute(AContext: IIPContext);
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
procedure Start;
procedure Stop;
protected
procedure WriteSQLData(Text: String; DataType: TTraceFlag);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure RegisterMonitor(SQLMonitor : TIBCustomSQLMonitor);
procedure UnregisterMonitor(SQLMonitor : TIBCustomSQLMonitor);
procedure ReleaseMonitor(Arg : TIBCustomSQLMonitor);
procedure SQLPrepare(qry: TIBSQL); virtual;
procedure SQLExecute(qry: TIBSQL); virtual;
procedure SQLFetch(qry: TIBSQL); virtual;
procedure DBConnect(db: TIBDatabase); virtual;
procedure DBDisconnect(db: TIBDatabase); virtual;
procedure TRStart(tr: TIBTransaction); virtual;
procedure TRCommit(tr: TIBTransaction); virtual;
procedure TRCommitRetaining(tr: TIBTransaction); virtual;
procedure TRRollback(tr: TIBTransaction); virtual;
procedure TRRollbackRetaining(tr: TIBTransaction); virtual;
procedure ServiceAttach(service: TIBCustomService); virtual;
procedure ServiceDetach(service: TIBCustomService); virtual;
procedure ServiceQuery(service: TIBCustomService); virtual;
procedure ServiceStart(service: TIBCustomService); virtual;
procedure SendMisc(Msg : String);
procedure SendError(Msg : String; db: TIBDatabase); overload;
procedure SendError(Msg : String); overload;
function GetEnabled: Boolean;
function GetTraceFlags: TTraceFlags;
function GetMonitorCount : Integer;
procedure SetEnabled(const Value: Boolean);
procedure SetTraceFlags(const Value: TTraceFlags);
published
property TraceFlags: TTraceFlags read GetTraceFlags write SetTraceFlags;
[default (True)]
property Enabled : Boolean read GetEnabled write SetEnabled default true;
[default (212)]
property Port : Integer read FPort write FPort default 212;
property Active : Boolean read GetActive write SetActive;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TIBMonitorClient = class(TIBCustomSQLMonitor)
private
FidClient : IIPTCPClient;
FThread : TThread;
FEnabled : Boolean;
function GetPort: Integer;
procedure SetPort(const Value: Integer);
function GetHost: String;
procedure SetHost(const Value: String);
function GetIPVersion: TIPVersionPeer;
procedure SetIPVersion(const Value: TIPVersionPeer);
procedure ClientConnected;
procedure FOnTerminate(Sender : TObject);
procedure OnData(TraceFlag : TTraceFlag; EventTime : TDateTime; Msg : String);
function GetEnabled: Boolean;
procedure SetEnabled(const Value: Boolean);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
[default (212)]
property Port : Integer read GetPort write SetPort default 212;
property Host : String read GetHost write SetHost;
property IPVersion : TIPVersionPeer read GetIPVersion write SetIPVersion;
property OnSQL;
property TraceFlags;
property Enabled : Boolean read GetEnabled write SetEnabled;
end;
implementation
uses
IBX.IBCustomDataset, IBX.IBXConst, IBX.IBHeader;
{ TIBServerMonitor }
const
cMsgLength = SizeOf(Integer);
cTSOffset = SizeOf(TTraceFlag) + cMsgLength;
cTextOffset = cTSOffSet + SizeOf(TDateTime);
type
TIBOnData = procedure(TraceFlag : TTraceFlag; EventTime : TDateTime; Msg : String) of object;
TClientReader = class(TThread)
private
FClient: IIPTCPClient;
FOnData: TIBOnData;
protected
procedure Execute; override;
public
constructor Create(aClient : IIPTCPClient);
property OnData : TIBOnData read FOnData write FOnData;
property Client : IIPTCPClient read FClient write FClient;
end;
constructor TIBMonitorServer.Create(AOwner : TComponent);
begin
inherited;
FEnabled := true;
FContexts := TObjectDictionary<IIPContext, TIBContext>.Create([doOwnsValues]);
FPort := 212;
FTraceFlags := [tfQPrepare..tfMisc];
FOldMonitor := SetMonitorHook(Self);
end;
procedure TIBMonitorServer.DBConnect(db: TIBDatabase);
var
st : String;
begin
if FEnabled then
begin
if not (tfConnect in FTraceFlags * db.TraceFlags) then
Exit;
st := db.Name + ': [Connect]'; {do not localize}
WriteSQLData(st, tfConnect);
end;
end;
procedure TIBMonitorServer.DBDisconnect(db: TIBDatabase);
var
st: String;
begin
if FEnabled then
begin
if not (tfConnect in FTraceFlags * db.TraceFlags) then
Exit;
st := db.Name + ': [Disconnect]'; {do not localize}
WriteSQLData(st, tfConnect);
end;
end;
destructor TIBMonitorServer.Destroy;
begin
if Assigned(FidServer) then
FidServer.Active := false;
FContexts.Free;
SetMonitorHook(FOldmonitor);
inherited;
end;
function TIBMonitorServer.GetActive: Boolean;
begin
Result := FActive;
end;
function TIBMonitorServer.GetEnabled: Boolean;
begin
Result := FEnabled;
end;
function TIBMonitorServer.GetMonitorCount: Integer;
begin
Result := FContexts.Count;
end;
function TIBMonitorServer.GetTraceFlags: TTraceFlags;
begin
Result := FTraceFlags;
end;
procedure TIBMonitorServer.OnConnect(AContext: IIPContext);
begin
TMonitor.Enter(FContexts);
FContexts.Add(AContext, TIBContext.Create(AContext));
TMonitor.Exit(FContexts);
end;
procedure TIBMonitorServer.OnDisconnect(AContext: IIPContext);
begin
TMonitor.Enter(FContexts);
FContexts.Remove(AContext);
TMonitor.Exit(FContexts);
end;
procedure TIBMonitorServer.RegisterMonitor(SQLMonitor: TIBCustomSQLMonitor);
begin
end;
procedure TIBMonitorServer.ReleaseMonitor(Arg: TIBCustomSQLMonitor);
begin
end;
procedure TIBMonitorServer.SendError(Msg: String; db: TIBDatabase);
begin
if FEnabled and (tfError in FTraceFlags * db.TraceFlags) then
WriteSQLData(StrError + Msg, tfError);
end;
procedure TIBMonitorServer.SendError(Msg: String);
begin
if FEnabled and (tfError in FTraceFlags) then
WriteSQLData(StrError + Msg, tfError);
end;
procedure TIBMonitorServer.SendMisc(Msg: String);
begin
if FEnabled then
WriteSQLData(StrMisc + Msg, tfMisc);
end;
procedure TIBMonitorServer.ServerExecute(AContext: IIPContext);
var
List: TList<TBytes>;
I: Integer;
begin
TMonitor.Enter(FContexts);
try
List := FContexts[AContext].GetQueuedMsgs;
finally
TMonitor.Exit(FContexts);
end;
if List = nil then
Exit;
try
for I := 0 to List.Count-1 do
AContext.Connection.IOHandler.Write(List[I]);
finally
List.Free;
end;
end;
procedure TIBMonitorServer.ServiceAttach(service: TIBCustomService);
var
st: String;
begin
if FEnabled then
begin
if not (tfService in (FTraceFlags * service.TraceFlags)) then
Exit;
st := service.Name + StrAttach;
WriteSQLData(st, tfService);
end;
end;
procedure TIBMonitorServer.ServiceDetach(service: TIBCustomService);
var
st: String;
begin
if FEnabled then
begin
if not (tfService in (FTraceFlags * service.TraceFlags)) then
Exit;
st := service.Name + StrDetach;
WriteSQLData(st, tfService);
end;
end;
procedure TIBMonitorServer.ServiceQuery(service: TIBCustomService);
var
st: String;
begin
if FEnabled then
begin
if not (tfService in (FTraceFlags * service.TraceFlags)) then
Exit;
st := service.Name + StrQuery;
WriteSQLData(st, tfService);
end;
end;
procedure TIBMonitorServer.ServiceStart(service: TIBCustomService);
var
st: String;
begin
if FEnabled then
begin
if not (tfService in (FTraceFlags * service.TraceFlags)) then
Exit;
st := service.Name + StrStart;
WriteSQLData(st, tfService);
end;
end;
procedure TIBMonitorServer.SetActive(const Value: Boolean);
begin
if not (csDesigning in ComponentState) and
(FActive <> Value) then
begin
if Value then
Start
else
Stop;
end;
FActive := Value;
end;
procedure TIBMonitorServer.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
end;
procedure TIBMonitorServer.SetTraceFlags(const Value: TTraceFlags);
begin
FTraceFlags := Value
end;
procedure TIBMonitorServer.SQLExecute(qry: TIBSQL);
var
st: String;
i: Integer;
begin
if FEnabled then
begin
if not ((tfQExecute in (FTraceFlags * qry.Database.TraceFlags)) or
(tfStmt in (FTraceFlags * qry.Database.TraceFlags)) ) then
Exit;
if qry.Owner is TIBCustomDataSet then
st := TIBCustomDataSet(qry.Owner).Name
else
st := qry.Name;
st := st + StrExecute + qry.SQL.Text;
if qry.Params.Count > 0 then
begin
for i := 0 to qry.Params.Count - 1 do
begin
st := st + CRLF + ' ' + qry.Params[i].Name + ' = '; {do not localize}
try
if qry.Params[i].IsNull then
st := st + StrNULL
else
if qry.Params[i].SQLType <> SQL_BLOB then
st := st + qry.Params[i].AsString
else
st := st + StrBLOB;
except
st := st + '<' + SCantPrintValue + '>'; {do not localize}
end;
end;
end;
WriteSQLData(st, tfQExecute);
end;
end;
procedure TIBMonitorServer.SQLFetch(qry: TIBSQL);
var
st: String;
begin
if FEnabled then
begin
if not ((tfQFetch in (FTraceFlags * qry.Database.TraceFlags)) or
(tfStmt in (FTraceFlags * qry.Database.TraceFlags))) then
Exit;
if qry.Owner is TIBCustomDataSet then
st := TIBCustomDataSet(qry.Owner).Name
else
st := qry.Name;
st := st + StrFetch + qry.SQL.Text;
if (qry.EOF) then
st := st + CRLF + ' ' + SEOFReached; {do not localize}
WriteSQLData(st, tfQFetch);
end;
end;
procedure TIBMonitorServer.SQLPrepare(qry: TIBSQL);
var
st : String;
begin
if FEnabled then
begin
if not ((tfQPrepare in (FTraceFlags * qry.Database.TraceFlags)) or
(tfStmt in (FTraceFlags * qry.Database.TraceFlags))) then
Exit;
if qry.Owner is TIBCustomDataSet then
st := TIBCustomDataSet(qry.Owner).Name
else
st := qry.Name;
st := st + StrPrepare + qry.SQL.Text + CRLF;
try
st := st + StrPlan + qry.Plan;
except
st := st + StrPlanCantRetrive;
end;
WriteSQLData(st, tfQPrepare);
end;
end;
procedure TIBMonitorServer.Start;
var
LSocketHandle: IIPSocketHandle;
begin
try
FidServer := PeerFactory.CreatePeer('', IIPTCPServer, nil) as IIPTCPServer;
except
on e : EIPAbstractError do
raise EIPAbstractError.Create('Can not start IBMOnitorServer. IIPTCPServer peer not registered. Make sure IPPeerServer (or an alternative IP Implementation unit) is in the uses clause');
end;
FidServer.OnConnect := OnConnect;
FidServer.OnDisconnect := OnDisconnect;
FidServer.OnExecute := ServerExecute;
FidServer.UseNagle := false;
FidServer.Bindings.Add.Port := FPort; //default IPv4
if GStackPeers('').SupportsIPv6 then
begin
LSocketHandle := FidServer.Bindings.Add;
LSocketHandle.Port := FPort; //default IPv4
LSocketHandle.IPVersion := TIPVersionPeer.IP_IPv6
end;
FidServer.Active := true;
end;
procedure TIBMonitorServer.Stop;
begin
if FidServer <> nil then
begin
FidServer.Active := False;
FidServer := nil;
end;
FContexts.Clear;
end;
procedure TIBMonitorServer.TRCommit(tr: TIBTransaction);
var
st: String;
begin
if FEnabled then
begin
if Assigned(tr.DefaultDatabase) and
(tfTransact in (FTraceFlags * tr.DefaultDatabase.TraceFlags)) then
begin
st := tr.Name + StrCommitHardComm;
WriteSQLData(st, tfTransact);
end;
end;
end;
procedure TIBMonitorServer.TRCommitRetaining(tr: TIBTransaction);
var
st: String;
begin
if FEnabled then
begin
if Assigned(tr.DefaultDatabase) and
(tfTransact in (FTraceFlags * tr.DefaultDatabase.TraceFlags)) then
begin
st := tr.Name + StrCommitRetaining;
WriteSQLData(st, tfTransact);
end;
end;
end;
procedure TIBMonitorServer.TRRollback(tr: TIBTransaction);
var
st: String;
begin
if FEnabled then
begin
if Assigned(tr.DefaultDatabase) and
(tfTransact in (FTraceFlags * tr.DefaultDatabase.TraceFlags)) then
begin
st := tr.Name + StrRollback;
WriteSQLData(st, tfTransact);
end;
end;
end;
procedure TIBMonitorServer.TRRollbackRetaining(tr: TIBTransaction);
var
st: String;
begin
if FEnabled then
begin
if Assigned(tr.DefaultDatabase) and
(tfTransact in (FTraceFlags * tr.DefaultDatabase.TraceFlags)) then
begin
st := tr.Name + StrRollbackRetainin;
WriteSQLData(st, tfTransact);
end;
end;
end;
procedure TIBMonitorServer.TRStart(tr: TIBTransaction);
var
st: String;
begin
if FEnabled then
begin
if Assigned(tr.DefaultDatabase) and
(tfTransact in (FTraceFlags * tr.DefaultDatabase.TraceFlags)) then
begin
st := tr.Name + StrStartTransaction;
WriteSQLData(st, tfTransact);
end;
end;
end;
procedure TIBMonitorServer.UnregisterMonitor(SQLMonitor: TIBCustomSQLMonitor);
begin
end;
procedure TIBMonitorServer.WriteSQLData(Text: String; DataType: TTraceFlag);
var
b : TBytes;
MsgLength : Integer;
ts : TDateTime;
AContext : TIBContext;
begin
if FContexts.Count > 0 then
begin
MsgLength := (Text.Length * SizeOf(char));
SetLength(b, cTextOffSet + MsgLength);
System.Move(MsgLength, b[0], cMsgLength);
b[cMsgLength] := Ord(DataType);
ts := now;
System.Move(ts, b[cTSOffset], 8);
Move(Text[low(Text)], b[cTextOffset], Text.Length * SizeOf(char));
TMonitor.Enter(FContexts);
try
for AContext in FContexts.Values do
begin
AContext.AddMsgToQueue(b);
end;
finally
TMonitor.Exit(FContexts);
end;
end;
end;
{ TIBMonitorClient }
procedure TIBMonitorClient.ClientConnected;
begin
FThread := TClientReader.Create(FidClient);
begin
FThread.OnTerminate := FOnTerminate;
TClientReader(FThread).OnData := OnData;
FThread.Start;
end;
end;
constructor TIBMonitorClient.Create(AOwner: TComponent);
begin
inherited;
try
FidClient := PeerFactory.CreatePeer('', IIPTCPClient, nil) as IIPTCPClient;
FidClient.UseNagle := false;
except
on e : EIPAbstractError do
raise EIPAbstractError.Create('Can not create TIBMonitorClient. IIPTCPClient peer not registered. Make sure IPPeerClient (or an alternative IP Implementation unit) is in the uses clause');
end;
FidClient.Port := 212;
end;
destructor TIBMonitorClient.Destroy;
begin
if Assigned(FThread) then
begin
TClientReader(FThread).OnTerminate := nil;
FThread.Terminate;
end;
if Assigned(FidClient) and FidClient.Connected then
FidClient.Disconnect;
inherited;
end;
function TIBMonitorClient.GetEnabled: Boolean;
begin
Result := FEnabled;
end;
function TIBMonitorClient.GetHost: String;
begin
Result := FidClient.Host;
end;
function TIBMonitorClient.GetIPVersion: TIPVersionPeer;
begin
Result := FidClient.IPVersion;
end;
function TIBMonitorClient.GetPort: Integer;
begin
Result := FidClient.Port;
end;
procedure TIBMonitorClient.OnData(TraceFlag: TTraceFlag; EventTime: TDateTime;
Msg: String);
begin
if (Assigned(OnSQL)) and
(TraceFlag in TraceFlags) then
OnSQL(Msg, EventTime);
end;
procedure TIBMonitorClient.FOnTerminate(Sender: TObject);
begin
FThread := nil;
end;
procedure TIBMonitorClient.SetEnabled(const Value: Boolean);
begin
if not (csDesigning in ComponentState) then
begin
if FidClient.Connected <> Value then
if Value then
begin
FidClient.Connect;
ClientConnected;
end
else
begin
FidClient.Disconnect;
if Assigned(FThread) then
FThread.Terminate;
end;
end;
FEnabled := Value;
end;
procedure TIBMonitorClient.SetHost(const Value: String);
begin
FidClient.Host := Value;
end;
procedure TIBMonitorClient.SetIPVersion(const Value: TIPVersionPeer);
begin
FidClient.IPVersion := Value;
end;
procedure TIBMonitorClient.SetPort(const Value: Integer);
begin
FidClient.Port := Value;
end;
{ TClientReader }
constructor TClientReader.Create(aClient : IIPTCPClient);
begin
inherited create(true);
FreeOnTerminate := true;
FClient := aClient;
end;
procedure TClientReader.Execute;
var
b : TIPBytesPeer;
bMsg : TBytes;
tf : TTraceFlag;
EventDate : TDateTime;
Msg : String;
MsgLength, MsgOffset : Integer;
ActualReadCount: Integer;
begin
try
while (not Terminated) and Assigned(FClient) and (FClient.Connected) do
begin
if FClient.IOHandler.InputBuffer.Size = 0 then
FClient.IOHandler.CheckForDataOnSource(10)
else
begin
ActualReadCount := FClient.IOHandler.InputBuffer.Size;
SetLength(b, ActualReadcount);
FClient.IOHandler.ReadBytes(b, ActualReadCount, false);
MsgOffset := 0;
while MsgOffset < ActualReadCount do
begin
System.Move(b[MsgOffset], MsgLength, cMsgLength);
tf := TTraceFlag(b[cMsgLength + MsgOffset]);
System.Move(b[cTSOffset + MsgOffset], EventDate, 8);
SetLength(bMsg, MsgLength);
System.Move(b[cTextOffset + MsgOffset], bMsg[0], MsgLength);
SetString(Msg, PChar(bMsg), Length(bMsg) div SizeOf(char));
if Assigned(FOnData) then
Synchronize(procedure begin FOnData(tf, EventDate, Msg); end);
Inc(MsgOffset, cTextOffset + MsgLength);
end;
end;
end;
except
on e: Exception do
begin
if Assigned(FClient) and FClient.Connected then
FClient.Disconnect;
end;
end;
end;
{ TIBContext }
procedure TIBContext.AddMsgToQueue(const Msg: TBytes);
begin
with FQueue.LockList do
try
Add(Msg);
FEvent.SetEvent;
finally
FQueue.UnlockList;
end;
end;
constructor TIBContext.Create(AContext: IIPContext);
begin
inherited Create;
FContext := AContext;
FQueue := TThreadList<TBytes>.Create;
FEvent := TEvent.Create(nil, True, False, '');
end;
destructor TIBContext.Destroy;
begin
FQueue.Free;
FEvent.Free;
inherited;
end;
function TIBContext.GetQueuedMsgs: TList<TBytes>;
var
List: TList<TBytes>;
begin
Result := nil;
if FEvent.WaitFor(100) <> wrSignaled then
Exit;
List := FQueue.LockList;
try
if List.Count > 0 then
begin
Result := TList<TBytes>.Create;
try
Result.AddRange(List);
List.Clear;
except
Result.Free;
raise;
end;
end;
FEvent.ResetEvent;
finally
FQueue.UnlockList;
end;
end;
end.
|
program queues;
type
LongItemPtr = ^LongItem;
LongItem = record
data: longint;
next: LongItemPtr;
end;
type QueueLongInts = record
first, last: LongItemPtr;
end;
procedure QueueInit(var queue: QueueLongInts);
begin
queue.first := nil;
queue.last := nil
end;
procedure QueuePut(var queue: QueueLongInts; n: longint);
begin
if queue.first = nil then
begin
new(queue.first);
queue.last := queue.first
end
else
begin
new(queue.last^.next);
queue.last := queue.last^.next
end;
queue.last^.data := n;
queue.last^.next := nil
end;
function QueueGet(var queue: QueueLongInts; var n: longint): boolean;
var
tmp: LongItemPtr;
begin
if queue.first = nil then
begin
QueueGet := false;
exit
end;
n := queue.first^.data;
tmp := queue.first;
queue.first := queue.first^.next;
if queue.first = nil then
queue.last := nil;
dispose(tmp);
QueueGet := true
end;
function QueueEmpty(var queue: QueueLongInts): boolean;
begin
QueueEmpty := queue.first = nil
end;
var
s: QueueLongInts;
n: longint;
begin
QueueInit(s);
while not eof do
begin
readln(n);
QueuePut(s, n);
end;
while QueueGet(s, n) do
writeln(n)
end.
|
unit Model.Telefone;
interface
type
TTelefone=class
private
FDDD: string;
FNumero: String;
procedure SetDDD(const Value: string);
procedure SetNumero(const Value: String);
published
property DDD:string read FDDD write SetDDD;
property Numero:String read FNumero write SetNumero;
end;
implementation
{ TTelefone }
procedure TTelefone.SetDDD(const Value: string);
begin
FDDD := Value;
end;
procedure TTelefone.SetNumero(const Value: String);
begin
FNumero := Value;
end;
end.
|
unit SimulatorMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GMGlobals, GMConst, Vcl.Buttons, Threads.Base,
Connection.TCP, Connection.Base;
type
TEmulationThread = class(TGMThread)
private
con: TConnectionObjectTCP_OwnSocket;
function PrepareBuffer(n_car, utime: int): ArrayOfByte;
protected
procedure SafeExecute; override;
constructor Create(const ip: string; port: int);
end;
TEmulationThreadPack = class(TEmulationThread)
private
FCount, FNCar: int;
protected
procedure SafeExecute; override;
constructor Create(const ip: string; port, ncar, count: int);
end;
TForm1 = class(TForm)
Memo1: TMemo;
btnGo: TSpeedButton;
eNCar: TEdit;
Label1: TLabel;
eCount: TEdit;
Label2: TLabel;
Button1: TButton;
ePort: TEdit;
Label3: TLabel;
procedure btnGoClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
thrEmulate: TEmulationThread;
thrEmulatePack: TEmulationThreadPack;
procedure EmulationThreadPackDone(Sender: TObject);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnGoClick(Sender: TObject);
begin
btnGo.Down := not btnGo.Down;
if btnGo.Down then
thrEmulate := TEmulationThread.Create('127.0.0.1', StrToInt(ePort.Text))
else
thrEmulate.Free();
end;
{ TEmulationThread }
constructor TEmulationThread.Create(const ip: string; port: int);
begin
inherited Create();
con := TConnectionObjectTCP_OwnSocket.Create();
con.Host := ip;
con.Port := port;
end;
function TEmulationThread.PrepareBuffer(n_car, utime: int): ArrayOfByte;
begin
Result := TextNumbersStringToArray('55 18 7A 03 E9 68 74 1C 00 00 00 00 00 00 00 00 12 00 F4 00 85 00 53 00 44 00 BB 00 16 00 72 07 76 01 00 00 00 00 06 00 00 00 00 00 00 00');
WriteWORD(Result, 2, n_car); // N_Car
if utime <= 0 then
WriteUINT(Result, 4, NowGM()) // UTime
else
WriteUINT(Result, 4, utime);
end;
procedure TEmulationThread.SafeExecute;
begin
while not Terminated do
begin
con.ExchangeBlockData(etSend);
SleepThread(10000);
end;
end;
procedure TForm1.EmulationThreadPackDone(Sender: TObject);
begin
Memo1.Lines.Add('Pack done');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
thrEmulatePack := TEmulationThreadPack.Create('127.0.0.1', StrToInt(ePort.Text), 1, 1000);
thrEmulatePack.OnTerminate := EmulationThreadPackDone;
end;
{ TEmulationThreadPack }
constructor TEmulationThreadPack.Create(const ip: string; port, ncar, count: int);
begin
inherited Create(ip, port);
FCount := count;
FNCar := ncar;
FreeOnTerminate := true;
end;
procedure TEmulationThreadPack.SafeExecute;
const packSize = 10;
var i, j: int;
buf: ArrayOfByte;
utime: LongWord;
begin
for i := 0 to FCount div packSize do
begin
for j := 0 to packSize - 1 do
begin
utime := int64(NowGM()) - (i * packSize + j) * UTC_MINUTE;
buf := PrepareBuffer(FNCar, utime);
WriteBuf(con.buffers.BufSend, j * length(buf), buf, Length(buf));
end;
con.buffers.LengthSend := Length(buf) * packSize;
con.ExchangeBlockData(etSend);
Sleep(100);
end;
end;
end.
|
program RecursiveFibonacci;
{1 1 2 3 5 :-) Done.}
var
i : integer;
procedure printInt(i:integer);
begin
putint(i);
putch(' ')
end;
function fib(n:integer):integer;
begin
if n <= 2 then
fib := 1
else
begin
fib := fib(n-1) + fib(n-2)
end
end;
begin
for i := 1 to 5 do
printInt(fib(i))
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.ABAccessibility;
interface
uses Winapi.Windows, System.Classes, Winapi.ActiveX, Winapi.oleacc, Vcl.ActnMan, Vcl.ActnMenus, Vcl.Controls;
type
TActionBarAccessibility = class(TInterfacedObject, IDispatch, IAccessible)
private
FActionClient: TActionClient;
FParent: TActionClient;
{ IAccessibility }
function Get_accParent(out ppdispParent: IDispatch): HResult; stdcall;
function Get_accChildCount(out pcountChildren: Integer): HResult; stdcall;
function Get_accChild(varChild: OleVariant; out ppdispChild: IDispatch): HResult; stdcall;
function Get_accName(varChild: OleVariant; out pszName: WideString): HResult; stdcall;
function Get_accValue(varChild: OleVariant; out pszValue: WideString): HResult; stdcall;
function Get_accDescription(varChild: OleVariant; out pszDescription: WideString): HResult; stdcall;
function Get_accRole(varChild: OleVariant; out pvarRole: OleVariant): HResult; stdcall;
function Get_accState(varChild: OleVariant; out pvarState: OleVariant): HResult; stdcall;
function Get_accHelp(varChild: OleVariant; out pszHelp: WideString): HResult; stdcall;
function Get_accHelpTopic(out pszHelpFile: WideString; varChild: OleVariant;
out pidTopic: Integer): HResult; stdcall;
function Get_accKeyboardShortcut(varChild: OleVariant; out pszKeyboardShortcut: WideString): HResult; stdcall;
function Get_accFocus(out pvarChild: OleVariant): HResult; stdcall;
function Get_accSelection(out pvarChildren: OleVariant): HResult; stdcall;
function Get_accDefaultAction(varChild: OleVariant; out pszDefaultAction: WideString): HResult; stdcall;
function accSelect(flagsSelect: Integer; varChild: OleVariant): HResult; stdcall;
function accLocation(out pxLeft: Integer; out pyTop: Integer; out pcxWidth: Integer;
out pcyHeight: Integer; varChild: OleVariant): HResult; stdcall;
function accNavigate(navDir: Integer; varStart: OleVariant; out pvarEndUpAt: OleVariant): HResult; stdcall;
function accHitTest(xLeft: Integer; yTop: Integer; out pvarChild: OleVariant): HResult; stdcall;
function accDoDefaultAction(varChild: OleVariant): HResult; stdcall;
function Set_accName(varChild: OleVariant; const pszName: WideString): HResult; stdcall;
function Set_accValue(varChild: OleVariant; const pszValue: WideString): HResult; stdcall;
{IDispatch}
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount: Integer; LocaleID: Integer; DispIDs: Pointer): HRESULT; stdcall;
function GetTypeInfo(Index: Integer; LocaleID: Integer;
out TypeInfo): HRESULT; stdcall;
function GetTypeInfoCount(out Count: Integer): HRESULT; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult: Pointer; ExcepInfo: Pointer;
ArgErr: Pointer): HRESULT; stdcall;
public
constructor Create(Parent, ActionClient: TActionClient);
end;
TActionMenuBarAccessibility = class(TActionBarAccessibility, IAccessible)
public
function Get_accChild(varChild: OleVariant;
out ppdispChild: IDispatch): HRESULT; stdcall;
function Get_accState(varChild: OleVariant;
out pvarState: OleVariant): HRESULT; stdcall;
function Get_accRole(varChild: OleVariant;
out pvarRole: OleVariant): HRESULT; stdcall;
function Get_accDescription(varChild: OleVariant; out pszDescription: WideString): HResult; stdcall;
end;
implementation
uses Vcl.ActnList, System.Variants, System.SysUtils, Vcl.Menus, System.Types;
type
TCustomActionMenuBarClass = class(TCustomActionMenuBar);
{ TActionBarAccessibility }
function TActionBarAccessibility.accDoDefaultAction(varChild: OleVariant): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.accHitTest(xLeft: Integer; yTop: Integer; out pvarChild: OleVariant): HResult;
var
Pt: TPoint;
Control: TControl;
begin
VariantInit(pvarChild);
TVarData(pvarChild).VType := VT_I4;
Control := nil;
Result := S_FALSE;
if FActionClient is TActionBarItem then
begin
Pt := FActionClient.ActionBar.ScreenToClient(Point(xLeft, yTop));
Control := FActionClient.ActionBar;
if Control <> nil then
begin
pvarChild := TCustomActionControl(Control).ActionClient.Index + 1;
Result := S_OK;
end;
end
else if (FActionClient is TActionClientItem) and Assigned(TActionClientItem(FActionClient).Control) then
begin
Control := FActionClient.ChildActionBar.ControlAtPos(FActionClient.ChildActionBar.ScreenToClient(Point(xLeft, yTop)), True);
pvarChild := TCustomActionControl(Control).ActionClient.Index + 1;
Result := S_OK;
end
else
if Assigned(Control) and PtInRect(Control.BoundsRect, Pt) then
begin
pvarChild := CHILDID_SELF;
Result := S_OK;
end
else
Result := S_FALSE;
end;
function TActionBarAccessibility.accLocation(out pxLeft: Integer;
out pyTop: Integer; out pcxWidth: Integer;
out pcyHeight: Integer; varChild: OleVariant): HResult;
var
P: TPoint;
Control: TControl;
begin
Result := S_FALSE;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
Control := FActionClient.ActionBar
else
Control := TActionClientItem(FActionClient).Control;
end
else
Control := FActionClient.Items[varChild - 1].Control;
if Control = nil then
exit;
P := Control.ClientToScreen(Control.ClientRect.TopLeft);
pxLeft := P.X;
pyTop := P.Y;
pcxWidth := Control.Width;
pcyHeight := Control.Height;
Result := S_OK;
end;
function TActionBarAccessibility.accNavigate(navDir: Integer; varStart: OleVariant;
out pvarEndUpAt: OleVariant): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.Get_accSelection(out pvarChildren: OleVariant): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
constructor TActionBarAccessibility.Create(Parent, ActionClient: TActionClient);
begin
FParent := Parent;
FActionClient := ActionClient;
FActionClient.Accessible := Self;
end;
function TActionBarAccessibility.GetIDsOfNames(const IID: TGUID;
Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TActionBarAccessibility.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TActionBarAccessibility.GetTypeInfoCount(
out Count: Integer): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TActionBarAccessibility.Get_accChild(varChild: OleVariant; out ppdispChild: IDispatch): HResult;
begin
if varChild = CHILDID_SELF then
Result := E_INVALIDARG
else
begin
if varChild > FActionClient.Items.Count then
begin
ppdispChild := nil;
Result := S_FALSE;
exit;
end;
ppdispChild := TActionBarAccessibility.Create(FActionClient, FActionClient.Items[varChild - 1]);
Result := S_OK;
end;
end;
function TActionBarAccessibility.Get_accChildCount(out pcountChildren: Integer): HResult;
begin
pcountChildren := FActionClient.Items.Count;
Result := S_OK;
end;
function TActionBarAccessibility.Get_accDefaultAction(varChild: OleVariant; out pszDefaultAction: WideString): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.Get_accDescription(varChild: OleVariant; out pszDescription: WideString): HResult;
begin
Result := S_FALSE;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
pszDescription := GetLongHint(FActionClient.ActionBar.Hint)
else
pszDescription := GetLongHint(TActionClientItem(FActionClient).Control.Hint);
end
else
pszDescription := GetLongHint(TCustomAction(FActionClient.Items[varChild - 1].Action).Hint);
if Length(pszDescription) > 0 then
Result := S_OK;
end;
function TActionBarAccessibility.Get_accFocus(out pvarChild: OleVariant): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.Get_accHelp(varChild: OleVariant; out pszHelp: WideString): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.Get_accHelpTopic(out pszHelpFile: WideString; varChild: OleVariant;
out pidTopic: Integer): HResult;
begin
pszHelpFile := '';
pidTopic := 0;
Result := S_FALSE;
if varChild = CHILDID_SELF then
if (FActionClient is TActionClientItem) and Assigned(TActionClientItem(FActionClient).Action) then
begin
pidTopic := TCustomAction(TActionClientItem(FActionClient).Action).HelpContext;
Result := S_OK;
end;
end;
function TActionBarAccessibility.Get_accKeyboardShortcut(varChild: OleVariant; out pszKeyboardShortcut: WideString): HResult;
begin
Result := S_FALSE;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
pszKeyboardShortcut := ''
else
begin
if TActionClientItem(FActionClient).Action = nil then
pszKeyboardShortcut := GetHotkey(TActionClientItem(FActionClient).Caption)
else
pszKeyboardShortcut := ShortCutToText(TCustomAction(TActionClientItem(FActionClient).Action).ShortCut);
if Length(pszKeyboardShortcut) > 0 then
Result := S_OK;
end;
end
else
begin
pszKeyboardShortcut := ShortCutToText(TCustomAction(TActionClientItem(FActionClient.Items[varChild - 1]).Action).ShortCut);
if Length(pszKeyboardShortcut) > 0 then
Result := S_OK;
end;
end;
function TActionBarAccessibility.Get_accName(varChild: OleVariant; out pszName: WideString): HResult;
begin
Result := S_OK;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionClientItem then
pszName := StripHotkey(TActionClientItem(FActionClient).Caption)
else if FActionClient is TActionBarItem then
FActionClient.ActionBar.Caption;
end
else
if varChild > FActionClient.Items.Count then
Result := S_FALSE
else
pszName := StripHotkey(FActionClient.Items[varChild - 1].Caption);
end;
function TActionBarAccessibility.Get_accParent(out ppdispParent: IDispatch): HResult;
begin
Result := S_FALSE;
if FParent <> nil then
begin
ppdispParent := FParent.Accessible;
Result := S_OK;
end;
end;
function TActionBarAccessibility.Get_accRole(varChild: OleVariant; out pvarRole: OleVariant): HResult;
begin
Result := S_OK;
VariantInit(pvarRole);
TVarData(pvarRole).VType := VT_I4;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUBAR
else
if Assigned(TActionClientItem(FActionClient).Control) and (TActionClientItem(FActionClient).Control.Parent is TCustomActionMainMenuBar) then
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUPOPUP
else
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUITEM;
end
else
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUITEM;
end;
function TActionBarAccessibility.accSelect(flagsSelect: Integer; varChild: OleVariant): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND;
end;
type
TCustomActionControlClass = class(TCustomActionControl);
function TActionBarAccessibility.Get_accState(varChild: OleVariant; out pvarState: OleVariant): HResult;
const
IsEnabled: array[Boolean] of Integer = (STATE_SYSTEM_UNAVAILABLE, 0);
HasPopup: array[Boolean] of Integer = (0, STATE_SYSTEM_HASPOPUP);
IsVisible: array[Boolean] of Integer = (STATE_SYSTEM_INVISIBLE, 0);
IsChecked: array[Boolean] of Integer = (0, STATE_SYSTEM_CHECKED);
var
Control: TControl;
begin
Result := S_OK;
VariantInit(pvarState);
TVarData(pvarState).VType := VT_I4;
Control := nil;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
Control := FActionClient.ActionBar
else if FActionClient is TActionClientItem then
Control := TActionClientItem(FActionClient).Control;
if Control = nil then
begin
Result := E_INVALIDARG;
exit;
end;
TVarData(pvarState).VInteger := STATE_SYSTEM_FOCUSED or STATE_SYSTEM_FOCUSABLE or STATE_SYSTEM_HOTTRACKED;
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsVisible[Control.Visible];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsEnabled[Control.Enabled];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsChecked[TCustomAction(Control.Action).Checked];
end
else
begin
TVarData(pvarState).VInteger := STATE_SYSTEM_FOCUSED or STATE_SYSTEM_FOCUSABLE or STATE_SYSTEM_HOTTRACKED;
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
IsVisible[FActionClient.Items[varChild - 1].Control.Visible];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
HasPopup[FActionClient.Items[varChild - 1].HasItems];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
IsEnabled[FActionClient.Items[varChild - 1].Control.Enabled];
if TCustomActionControlClass(FActionClient.Items[varChild - 1].Control).IsChecked then
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or STATE_SYSTEM_CHECKED;
end;
end;
function TActionBarAccessibility.Get_accValue(varChild: OleVariant; out pszValue: WideString): HResult;
begin
pszValue := '';
Result := S_FALSE;//DISP_E_MEMBERNOTFOUND;
end;
function TActionBarAccessibility.Invoke(DispID: Integer; const IID: TGUID;
LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo,
ArgErr: Pointer): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TActionBarAccessibility.Set_accName(varChild: OleVariant; const pszName: WideString): HResult; stdcall;
begin
Result := DISP_E_MEMBERNOTFOUND
end;
function TActionBarAccessibility.Set_accValue(varChild: OleVariant; const pszValue: WideString): HResult;
begin
Result := DISP_E_MEMBERNOTFOUND
end;
{ TActionMenuBarAccessibility }
function TActionMenuBarAccessibility.Get_accChild(varChild: OleVariant;
out ppdispChild: IDispatch): HRESULT;
begin
if varChild = CHILDID_SELF then
Result := E_INVALIDARG
else
begin
if varChild > FActionClient.Items.Count then
begin
ppdispChild := nil;
Result := S_FALSE;
exit;
end;
ppdispChild := TActionMenuBarAccessibility.Create(FActionClient, FActionClient.Items[varChild - 1]);
Result := S_OK;
end;
end;
function TActionMenuBarAccessibility.Get_accDescription(varChild: OleVariant;
out pszDescription: WideString): HResult;
begin
Result := S_FALSE;
pszDescription := '';
if varChild = CHILDID_SELF then
pszDescription := TActionClientItem(FActionClient).Caption + ' menu';
if Length(pszDescription) > 0 then
Result := S_OK;
end;
function TActionMenuBarAccessibility.Get_accRole(varChild: OleVariant;
out pvarRole: OleVariant): HRESULT;
begin
Result := S_OK;
VariantInit(pvarRole);
TVarData(pvarRole).VType := VT_I4;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUBAR
else
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUITEM;
end
else
TVarData(pvarRole).VInteger := ROLE_SYSTEM_MENUITEM;
end;
function TActionMenuBarAccessibility.Get_accState(varChild: OleVariant;
out pvarState: OleVariant): HRESULT;
const
IsEnabled: array[Boolean] of Integer = (STATE_SYSTEM_UNAVAILABLE, 0);
HasPopup: array[Boolean] of Integer = (0, STATE_SYSTEM_HASPOPUP);
IsVisible: array[Boolean] of Integer = (STATE_SYSTEM_INVISIBLE, 0);
IsChecked: array[Boolean] of Integer = (0, STATE_SYSTEM_CHECKED);
var
Control: TControl;
begin
Result := S_OK;
VariantInit(pvarState);
TVarData(pvarState).VType := VT_I4;
Control := nil;
if varChild = CHILDID_SELF then
begin
if FActionClient is TActionBarItem then
Control := FActionClient.ActionBar
else if FActionClient is TActionClientItem then
Control := TActionClientItem(FActionClient).Control;
if Control <> nil then
begin
TVarData(pvarState).VInteger := STATE_SYSTEM_FOCUSED or STATE_SYSTEM_FOCUSABLE;
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsVisible[Control.Visible];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsEnabled[Control.Enabled];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsChecked[TCustomActionControlClass(Control).IsChecked];
end
else
begin
TVarData(pvarState).VInteger := STATE_SYSTEM_FOCUSED or STATE_SYSTEM_FOCUSABLE;
if TActionClientItem(FActionClient).Action <> nil then
begin
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsVisible[TCustomAction(TActionClientItem(FActionClient).Action).Visible];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or IsEnabled[TCustomAction(TActionClientItem(FActionClient).Action).Enabled];
end;
end;
end
else
begin
if varChild > FActionClient.Items.Count then
begin
Result := E_INVALIDARG;
exit;
end;
if FActionClient.Items[varChild - 1].Control = nil then
beep;
TVarData(pvarState).VInteger := STATE_SYSTEM_FOCUSED or STATE_SYSTEM_FOCUSABLE;
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
IsVisible[FActionClient.Items[varChild - 1].Control.Visible];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
HasPopup[FActionClient.Items[varChild - 1].HasItems];
TVarData(pvarState).VInteger := TVarData(pvarState).VInteger or
IsEnabled[FActionClient.Items[varChild - 1].Control.Enabled];
end;
end;
end.
|
unit MapRangeSelectDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls, PASTypes, Mask;
type
TMapRangeSelectDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
ColorDialog: TColorDialog;
Panel1: TPanel;
StartValueLabel: TLabel;
EndValueLabel: TLabel;
StartColorShape: TShape;
IncrementsLabel: TLabel;
Label4: TLabel;
EndColorShape: TShape;
Label5: TLabel;
ValueRangeHeaderLabel: TLabel;
ValueRangeHeaderLabel2: TLabel;
StartValueEdit: TEdit;
EndValueEdit: TEdit;
LevelsEdit: TEdit;
StartColorButton: TButton;
EndColorButton: TButton;
StartYearLabel: TLabel;
EndYearLabel: TLabel;
CodeRangeHeaderLabel: TLabel;
StartYearEdit: TMaskEdit;
EndYearEdit: TMaskEdit;
MapSizeRadioGroup: TRadioGroup;
DisplayLabelsCheckBox: TCheckBox;
Label1: TLabel;
procedure OKButtonClick(Sender: TObject);
procedure SetColorButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
RangeType : Integer;
StartYear, EndYear : String;
MapRangeRec : MapRangeRecord;
StartDate, EndDate : TDateTime;
SelectedCodesList : TStringList;
Procedure InitializeForm(MapRangeRec : MapRangeRecord;
FillInCurrentValues : Boolean;
_SelectedCodesList : TStringList);
end;
var
MapRangeSelectDialog: TMapRangeSelectDialog;
implementation
uses Utilitys, GlblCnst, MapRangeCodeSelectDialogUnit;
{$R *.DFM}
{================================================================}
Procedure TMapRangeSelectDialog.InitializeForm(MapRangeRec : MapRangeRecord;
FillInCurrentValues : Boolean;
_SelectedCodesList : TStringList);
begin
SelectedCodesList := _SelectedCodesList;
case RangeType of
rtAssessmentChange :
begin
StartYearEdit.Visible := True;
StartYearLabel.Visible := True;
EndYearEdit.Visible := True;
EndYearLabel.Visible := True;
end;
rtSalesPrice :
begin
StartYearEdit.Visible := True;
StartYearLabel.Visible := True;
StartYearLabel.Caption := 'Start Date';
StartYearEdit.EditMask := DateMask;
StartYearEdit.Text := DateToStr(MoveDateTimeBackwards(Date, 2, 0, 0));
EndYearEdit.Visible := True;
EndYearLabel.Visible := True;
EndYearLabel.Caption := 'End Date';
EndYearEdit.EditMask := DateMask;
EndYearEdit.Text := DateToStr(Date);
end; {rtSalesPrice}
rtZoningCodes,
rtNeighborhoodCodes,
rtPropertyClass :
begin
ValueRangeHeaderLabel.Visible := False;
ValueRangeHeaderLabel2.Visible := False;
CodeRangeHeaderLabel.Visible := True;
StartValueEdit.Visible := False;
EndValueEdit.Visible := False;
LevelsEdit.Visible := False;
StartValueLabel.Visible := False;
EndValueLabel.Visible := False;
IncrementsLabel.Visible := False;
Label1.Visible := False;
end; {rtZoningCodes,...}
end; {case RangeType of}
{Fill in the values from last time.}
If FillInCurrentValues
then
with MapRangeRec do
begin
StartValueEdit.Text := FloatToStr(StartValue);
EndValueEdit.Text := FloatToStr(EndValue);
LevelsEdit.Text := IntToStr(NumberOfIncrements);
StartColorShape.Brush.Color := StartColor;
EndColorShape.Brush.Color := EndColor;
If (Deblank(StartYear) <> '')
then
begin
StartYearEdit.Text := StartYear;
EndYearEdit.Text := EndYear;
end;
try
If (EndDate > StrToDate('1/1/1910'))
then
begin
StartYearEdit.Text := DateToStr(StartDate);
EndYearEdit.Text := DateToStr(EndDate);
end;
except
end;
If UseFullMapExtent
then MapSizeRadioGroup.ItemIndex := 1
else MapSizeRadioGroup.ItemIndex := 0;
DisplayLabelsCheckBox.Checked := UseFullMapExtent;
end; {If (FillInCurrentValue and ...}
end; {InitializeForm}
{================================================================}
Procedure TMapRangeSelectDialog.SetColorButtonClick(Sender: TObject);
begin
If ColorDialog.Execute
then
If (Pos('Start', TButton(Sender).Name) > 0)
then
begin
StartColorShape.Brush.Color := ColorDialog.Color;
StartColorShape.Refresh;
end
else
begin
EndColorShape.Brush.Color := ColorDialog.Color;
EndColorShape.Refresh;
end;
end; {SetColorButtonClick}
{================================================================}
Procedure TMapRangeSelectDialog.OKButtonClick(Sender: TObject);
var
Continue : Boolean;
_EndValue, _StartValue : Double;
_Increments : Integer;
MapRangeCodeSelectDialog: TMapRangeCodeSelectDialog;
begin
try
_StartValue := StrToFloat(StartValueEdit.Text);
except
_StartValue := 0;
end;
try
_EndValue := StrToFloat(EndValueEdit.Text);
except
_EndValue := 0;
end;
try
_Increments := StrToInt(LevelsEdit.Text);
except
_Increments := 0;
end;
Continue := True;
If not (RangeType in [rtZoningCodes, rtNeighborhoodCodes, rtPropertyClass])
then
begin
If (_StartValue >= _EndValue)
then
begin
StartValueEdit.SetFocus;
Continue := False;
MessageDlg('The starting value must be less than the ending value.',
mtError, [mbOK], 0);
end; {If (StartValue >= EndValue)}
If (Continue and
(Roundoff(_Increments, 2) = 0))
then
begin
LevelsEdit.SetFocus;
Continue := False;
MessageDlg('Please enter the number of value breaks you want (levels).', mtError, [mbOK], 0);
end;
end; {If not (RangeType in [rtZoningCodes, rtNeighborhoodCodes])}
If (Continue and
(RangeType = rtAssessmentChange) and
(Deblank(StartYearEdit.Text) = ''))
then
begin
StartYearEdit.SetFocus;
Continue := False;
MessageDlg('Please enter the first year to compare for the assessment percent change.',
mtError, [mbOK], 0);
end;
If (Continue and
(RangeType = rtAssessmentChange) and
(Deblank(EndYearEdit.Text) = ''))
then
begin
EndYearEdit.SetFocus;
Continue := False;
MessageDlg('Please enter the second year to compare for the assessment percent change.',
mtError, [mbOK], 0);
end;
If Continue
then
with MapRangeRec do
begin
StartValue := _StartValue;
EndValue := _EndValue;
NumberOfIncrements := _Increments;
StartColor := StartColorShape.Brush.Color;
EndColor := EndColorShape.Brush.Color;
DisplayLabels := DisplayLabelsCheckBox.Checked;
case RangeType of
rtAssessmentChange :
begin
StartYear := StartYearEdit.Text;
EndYear := EndYearEdit.Text;
end;
rtSalesPrice :
begin
try
StartDate := StrToDate(StartYearEdit.Text);
except
end;
try
EndDate := StrToDate(EndYearEdit.Text);
except
end;
end; {rtSalesPrice}
end; {case RangeType of}
UseFullMapExtent := (MapSizeRadioGroup.ItemIndex = 1);
Continue := True;
If (RangeType in [rtZoningCodes,
rtNeighborhoodCodes,
rtPropertyClass])
then
try
MapRangeCodeSelectDialog := TMapRangeCodeSelectDialog.Create(nil);
MapRangeCodeSelectDialog.InitializeForm(RangeType, SelectedCodesList);
If (MapRangeCodeSelectDialog.ShowModal = idOK)
then SelectedCodesList := MapRangeCodeSelectDialog.SelectedCodesList
else Continue := False;
finally
MapRangeCodeSelectDialog.Free;
end;
If Continue
then ModalResult := mrOK;
end; {with RangeRec do}
end; {OKButtonClick}
{==================================================================}
Procedure TMapRangeSelectDialog.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
unit MD.View.Client.DataSet;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
FMX.TabControl, FMX.Edit,
System.Generics.Collections, Data.Bind.EngExt, Fmx.Bind.DBEngExt,
System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors,
Data.Bind.Components, Data.Bind.ObjectScope, FMX.Layouts,
System.JSON, REST.Json, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error,
FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Bind.DBScope,
GBClient.Interfaces;
type
TfrmMobileDayDataSet = class(TForm)
Rectangle1: TRectangle;
Label5: TLabel;
tbcClient: TTabControl;
tiList: TTabItem;
tiCrud: TTabItem;
tiSettings: TTabItem;
lvClients: TListView;
btnAdd: TCircle;
Rectangle3: TRectangle;
Label2: TLabel;
edtName: TEdit;
Label3: TLabel;
edtLastName: TEdit;
Label4: TLabel;
edtPhone: TEdit;
btnSave: TCircle;
Path1: TPath;
Path2: TPath;
Path3: TPath;
Rectangle2: TRectangle;
Label1: TLabel;
edtBaseUrl: TEdit;
btnClear: TSpeedButton;
VertScrollBox1: TVertScrollBox;
dsClient: TFDMemTable;
dsClientid: TIntegerField;
dsClientname: TStringField;
dsClientlastName: TStringField;
dsClientphone: TStringField;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkListControlToField1: TLinkListControlToField;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
LinkControlToField3: TLinkControlToField;
procedure FormCreate(Sender: TObject);
procedure tbcClientChange(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure lvClientsButtonClick(const Sender: TObject; const AItem: TListItem; const AObject: TListItemSimpleControl);
procedure btnClearClick(Sender: TObject);
procedure lvClientsItemClick(const Sender: TObject; const AItem: TListViewItem);
procedure btnSaveClick(Sender: TObject);
private
function PrepareRequest : IGBClientRequest;
procedure listAll;
procedure Insert;
procedure Update;
procedure Delete;
{ Private declarations }
public
{ Public declarations }
end;
var
frmMobileDayDataSet: TfrmMobileDayDataSet;
implementation
{$R *.fmx}
procedure TfrmMobileDayDataSet.btnAddClick(Sender: TObject);
begin
tbcClient.ActiveTab := tiCrud;
dsClient.Insert;
end;
procedure TfrmMobileDayDataSet.btnClearClick(Sender: TObject);
begin
dsClient.Cancel;
tbcClient.ActiveTab := tiList;
end;
procedure TfrmMobileDayDataSet.btnSaveClick(Sender: TObject);
begin
if dsClient.State = dsInsert then
Insert
else
Update;
tbcClient.ActiveTab := tiList;
end;
procedure TfrmMobileDayDataSet.Delete;
var
request: IGBClientRequest;
begin
request := PrepareRequest;
request
.DELETE
.BaseURL(edtBaseUrl.Text + '/' + dsClient.FieldByName('id').AsString)
.Send;
end;
procedure TfrmMobileDayDataSet.FormCreate(Sender: TObject);
begin
btnClear.Visible := False;
tbcClient.ActiveTab := tiList;
tbcClient.TabPosition := TTabPosition.None;
listAll;
end;
procedure TfrmMobileDayDataSet.Insert;
var
request: IGBClientRequest;
begin
dsClient.Post;
request := PrepareRequest;
request
.POST
.BaseURL(edtBaseUrl.Text)
.Body
.AddOrSet(dsClient)
.&End
.Send;
dsClient.Edit;
dsClient.FieldByName('id').AsFloat :=
request.Response.HeaderAsFloat('location');
dsClient.Post;
end;
procedure TfrmMobileDayDataSet.listAll;
var
request: IGBClientRequest;
begin
request := PrepareRequest;
request
.GET
.BaseURL(edtBaseUrl.Text)
.Send
.DataSet(dsClient)
end;
procedure TfrmMobileDayDataSet.lvClientsButtonClick(const Sender: TObject; const AItem: TListItem; const AObject: TListItemSimpleControl);
begin
tbcClient.ActiveTab := tiList;
Delete;
dsClient.Delete;
end;
procedure TfrmMobileDayDataSet.lvClientsItemClick(const Sender: TObject; const AItem: TListViewItem);
begin
tbcClient.ActiveTab := tiCrud;
end;
function TfrmMobileDayDataSet.PrepareRequest: IGBClientRequest;
begin
result := newClientRequest;
result
.Authorization
.Basic
.Username('mobileDay')
.Password('2020');
end;
procedure TfrmMobileDayDataSet.tbcClientChange(Sender: TObject);
begin
btnClear.Visible := tbcClient.ActiveTab = tiCrud;
end;
procedure TfrmMobileDayDataSet.Update;
var
request: IGBClientRequest;
begin
dsClient.Post;
request := PrepareRequest;
request
.PUT
.BaseURL(edtBaseUrl.Text + '/' + dsClient.FieldByName('id').AsString)
.Body
.AddOrSet(dsClient)
.&End
.Send;
end;
initialization
ReportMemoryLeaksOnShutdown := True;
end.
|
unit uTypes;
/// всех типов для сокращения основных модулей и возможности передачи типов
/// между ними, при необходимости
interface
type
////////////////////////////////////////////////////////////////////////////////
/// TGameManager
////////////////////////////////////////////////////////////////////////////////
/// описание способности "Прыжок", позволяющего мгновенно переместиться по уровню
/// на несколько "клеток"
TJumpAbility = record
baseJumpDistance: real; // расстояние прокрутки уровня в ширине стандартного объекта
fullJumpDistance: real; // тоже, с учетом всех текущих наложенных бонусов
baseCooldownLength: real; // время восстановления способности в милисекундах
fullCooldownLength: real; // тоже, с учетом всех наложенных бонусов
currentCooldown: real; // теекущее прошедшее время отката в милисекундах, если в откате
InCooldown: boolean; // находится способность ли в откате
end;
////////////////////////////////////////////////////////////////////////////////
/// TTravelManager
////////////////////////////////////////////////////////////////////////////////
TTravelSlot = record
kind : integer; // id типа из таблицы типов, позволяет узнать точный тип обработчика
active : boolean; // активен ли объект в слоте. в большинстве случаев,
// это видимые в окне приключения слоты, а остальные
// считаются невидимыми, но возможна ситуация, что активны и скрытые
// объекты. активные объекты обсчитываются на каждом тике логики
// что позволяет им влиять на игровой процесс
alive : boolean; // не является ли объект разрушенным. например, разграбленный источник ресурсов
// при возврате к началу уровня и проходе заново этого объекта он не будет
// обрабатываться даже если попадет в поле видимости (станет активным)
position : integer; // позиция относительно начала пуровня.
// изначально это возрастающее по массиву значение,
// но объекты могут менять позицию при некторых
// условиях или эффектах
instance : TObject; // объект-обработчик, содержащий все параметры, логику и текущее состояние объекта
// при обработке логики, основное взаимодействие происходит именно с ним
end;
TTravelArr = array of TTravelSlot;
// массив объектов текущего приключения
////////////////////////////////////////////////////////////////////////////////
/// TInterfaceManager
////////////////////////////////////////////////////////////////////////////////
TMainComponents = record
/// основные элементы окна приключения
topPanel, landscape, bottomPanel, lootPanel, travelBG, travelFG: TObject;
end;
/// все компоненты панели скорости путешествия
TPanelWalk = record
/// panel - сама общая панель раздела интерфейса
/// stepPanel1 - панелька, содержащая картинку режима перемещения со скоростью 1 (тихий шаг)
/// stepImg1 - картинка тихого шага
/// stepPanel2 - панелька, содержащая картинку режима перемещения со скоростью 2 (шаг)
/// stepImg2 - картинка шага
/// stepPanel3 - панелька, содержащая картинку режима перемещения со скоростью 3 (бег)
/// stepImg3 - картинка бега
/// jumpPanel - пенель абилки прыжка
/// jumpImg - картинка абилки прыжка
/// jumpBG - фон прогрессбара отката прыжка
/// jumpProgress - сама шкала прогрессбара
panel, stepPanel1, stepImg1, stepPanel2, stepImg2, stepPanel3, stepImg3,
jumpPanel, jumpImg, jumpBG, jumpProgress
: TObject
end;
TPanelPers = record
/// panel - сама панель
/// pers1 - иконка первого персонажа
/// pers2 - иконка второго персонажа
/// pers3 - иконка третьего персонажа
panel, pers1, pers2, pers3 : TObject
end;
TPanelAbility = record
/// panel - сама панель
/// abilityButton - основа кнопки переключения на способности
/// abilityCaption - текст кнопки
/// itemButton - основа кнопки переключения на предметы
/// itemCaption - текст кнопки
/// slot1, slot2, slot3, slot4, slot5, slot6 - картинки слоты отображения предметов/способностей
panel, abilityButton, abilityCaption, itemButton, itemCaption,
slot1, slot2, slot3, slot4, slot5, slot6,
slotBG1, slotBG2, slotBG3, slotBG4, slotBG5, slotBG6,
slotFG1, slotFG2, slotFG3, slotFG4, slotFG5, slotFG6
: TObject
end;
TPanelState = record
/// компоненты отображения статуса игрока:
/// основные параметры (атака, здоровье, мана,.. и текущие активные
/// временные эффекты (bonusXXX)
///
panel, HPpanel, HPLabel, HPCount, HPCountBG, HPCountFG,
MPPanel, MPLabel, MPCount, MPCountBG, MPCountFG,
DEFPanel, DEFLabel, DEFCount, ATKPanel, ATKLabel, ATKCount,
GLDPanel, GLDLabel, GLDCount, EXPPanel, EXPLabel, EXPCount,
buttonBG, buttonLabel : TObject;
end;
TPanelInfo = record
/// panel - сама панель информации
/// layout - контейнер, где будет строиться представление информации
panel, layout : TObject
end;
TLootPanel = record
/// resourcePanel - floatlayout для счетчиков ресурсов собранных в приключении
/// buttonSettings - картинка-иконка вызова экрана меню
resourcePanel,
buttonSettings : TObject;
end;
implementation
end.
|
unit Unit2;
interface
uses
{$IFDEF TESTING}
TestFramework,
{$ENDIF}
Classes, SysUtils;
type
TSuperObject = class(TObject)
public
function DoSomethingSuper: boolean;
end;
{$IFDEF TESTING}
TTestSuperObject = class(TTestCase)
private
FSuperObject: TSuperObject;
public
procedure Setup; override;
procedure TearDown; override;
published
procedure testSuperObject;
end;
function Suite: ITestSuite;
{$ENDIF}
implementation
{ TSuperObject }
function TSuperObject.DoSomethingSuper :boolean;
begin
// do something ...
Result := (Random < 0.5);
end;
{$IFDEF TESTING}
function Suite: ITestSuite;
begin
Result := TTestSuite.Create(TTestSuperObject);
end;
{ TTestSuperObject }
procedure TTestSuperObject.Setup;
begin
FSuperObject := TSuperObject.Create;
end;
procedure TTestSuperObject.TearDown;
begin
FSuperObject.Free;
end;
procedure TTestSuperObject.testSuperObject;
begin
check(FSuperObject.DoSomethingSuper);
end;
{$ENDIF}
initialization
{$IFDEF TESTING}
RegisterTest('', TTestSuperObject.Suite);
{$ENDIF}
end.
|
unit fARTFreeTextMsg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fAutoSz, StdCtrls, ComCtrls, ORFn, ExtCtrls, ORCtrls,
VA508AccessibilityManager;
type
TfrmARTFreeTextMsg = class(TfrmAutoSz)
pnlText: TORAutoPanel;
pnlButton: TORAutoPanel;
cmdContinue: TButton;
lblText: TLabel;
memFreeText: TCaptionRichEdit;
lblComments: TOROffsetLabel;
procedure cmdContinueClick(Sender: TObject);
private
FContinue: boolean;
public
end;
const
LABEL_TEXT = 'You may now add any comments you may have to the message that' + CRLF +
'is going to be sent with the request to add this reactant.' + CRLF + CRLF +
'You may want to add things like sign/symptoms, observed or historical, etc.,' + CRLF +
'that may be useful to the reviewer.' + CRLF + CRLF +
'Already included are the entry you attempted, the patient you attempted to' + CRLF +
'enter it for, and your name, title, and contact information.';
var
tmpList: TStringList;
procedure GetFreeTextARTComment(var AFreeTextComment: TStringList; var OKtoContinue: boolean);
implementation
{$R *.dfm}
procedure GetFreeTextARTComment(var AFreeTextComment: TStringList; var OKtoContinue: boolean);
var
frmARTFreeTextMsg: TfrmARTFreeTextMsg;
begin
frmARTFreeTextMsg := TfrmARTFreeTextMsg.Create(Application);
tmpList := TStringList.Create;
try
with frmARTFreeTextMsg do
begin
FContinue := OKtoContinue;
tmpList.Text := '';
lblText.Caption := LABEL_TEXT;
ResizeFormToFont(TForm(frmARTFreeTextMsg));
ActiveControl := memFreeText;
frmARTFreeTextMsg.ShowModal;
OKtoContinue := FContinue;
FastAssign(tmpList, AFreeTextComment);
end;
finally
tmpList.Free;
frmARTFreeTextMsg.Release;
end;
end;
procedure TfrmARTFreeTextMsg.cmdContinueClick(Sender: TObject);
begin
inherited;
tmpList.Assign(memFreeText.Lines);
FContinue := True;
Close;
end;
end.
|
Program SqRoot(input, output); {find the square root by averages}
{15/9/21 Nev Goodyer: created from pseudo at https://bwattle.github.io/SquareRoot/JS/Q23.html}
{NOTE: int16, int8, single & double are types discussed in the NSW Software Design & Development course}
{v1.02 with decPlaces=8 is a great demo of int16 2's compliment and single precision limitations}
{CLOSE WINDOW TO STOP INFINITE LOOP}
Uses crt, Math; {crt is a standard Pascal library, Math has standard Maths functions}
Var
number: single; {16 bit integer - signed to approx 32,000}
decPlaces : SmallInt; {8 bit integer - unsigned 0-255}
minimum : single;
maximum : single;
middle : single;
accuracy : single;
Begin
Writeln('Enter the number you want the square root of: ');
Readln(number);
Writeln('Enter the accuracy in number of decimal places: ');
Readln(decPlaces);
minimum := 0 ;
maximum := Number ;
middle := (minimum + maximum) / 2 ;
accuracy := Power (10, (-1 * decPlaces)) ;
While Abs((middle * middle) - number) > accuracy Do
Begin
If middle * middle > Number Then
Begin
maximum := middle ;
End
Else
Begin
minimum := middle;
End;
middle := (minimum + maximum) / 2;
End;
middle := Int(middle / accuracy) * accuracy ;
Writeln('The unformatted square root is ', middle);
{at the end of the next line, 0 is minimum total digits: decPlaces is what it says}
Writeln('The formatted square root is ', middle:0:decPlaces);
End . |
program BaseBoardInformation;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
function ByteToBinStr(AValue:Byte):string;
const
Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1);
var i: integer;
begin
Result:='00000000';
if (AValue<>0) then
for i:=1 to 8 do
if (AValue and Bits[i])<>0 then Result[i]:='1';
end;
procedure GetBaseBoardInfo;
Var
SMBios: TSMBios;
LBaseBoard: TBaseBoardInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Base Board Information');
if SMBios.HasBaseBoardInfo then
for LBaseBoard in SMBios.BaseBoardInfo do
begin
//WriteLn('Manufacter '+SMBios.GetSMBiosString(BBI.LocalIndex + BBI.Header.Length, BBI.Manufacturer));
WriteLn('Manufacter '+LBaseBoard.ManufacturerStr);
WriteLn('Product '+LBaseBoard.ProductStr);
WriteLn('Version '+LBaseBoard.VersionStr);
WriteLn('Serial Number '+LBaseBoard.SerialNumberStr);
WriteLn('Asset Tag '+LBaseBoard.AssetTagStr);
WriteLn('Feature Flags '+ByteToBinStr(LBaseBoard.RAWBaseBoardInformation^.FeatureFlags));
WriteLn('Location in Chassis '+LBaseBoard.LocationinChassisStr);
WriteLn(Format('Chassis Handle %0.4x',[LBaseBoard.RAWBaseBoardInformation^.ChassisHandle]));
WriteLn(Format('Board Type %0.2x %s',[LBaseBoard.RAWBaseBoardInformation^.BoardType, LBaseBoard.BoardTypeStr]));
WriteLn('Number of Contained Object Handles '+IntToStr(LBaseBoard.RAWBaseBoardInformation^.NumberofContainedObjectHandles));
WriteLn;
end
else
Writeln('No Base Board Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetBaseBoardInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
{$Q-,R-,S-,G-}
Unit tfastwrite;
{
WARNING:
Do not use snow checking if calling these routines from an interrupt.
(You should not be writing strings from an interrupt anyway!)
TFASTWRITE:
Yet another "fastwrite" routine (write text directly to screen ram).
Now that 25 years have gone by and I know 8088 assembler to a decent
level, I got fed up with Borland's routines (I see snow even with
CheckSnow true!) and decided to write my own.
However, this unit is much faster than Borland's routines; in fact, it
is likely the fastest implementation possible for a 4.77MHz 8088 with
CGA that fully handles CGA hardware "snow":
- No MULs; uses a lookup table for the "y*80*2" portion of the offset calcs
- Optimal unrolled copy based on 8088 timings
- When PreventSnow is on, both horizontal and vertical retrace are used
when writing strings or doing full-screen copies
- Usual 8088 tricks: Using SHL; JC/JNC instead of
CMP/TEST... full use of LODS/STOS/MOVS where appropriate...1-byte
opcodes when possible... etc. I have tried to note this in the code but
ask me if something seems weird.
trixter@oldskool.org, JL20060318
Code revised JL20121013:
+ Wrung a hair more speed out of it, can now copy an 80x25 screen
in < 50ms with snow checking on
+ added MDA support, and won't check for snow on MDAs
Code revised JL20130627:
- Adjusted copyscreen chunksize to avoid single scanline character of snow
+ Added more MDA speedups
+ Added write/writeln functionality
Code revised JL20190621:
* comments and cleanup
}
Interface
Const
tfPreventSnow:Boolean=False;
togglechar='~';
maxscrlines=16384 div (80*2);
var
tfMaxScrX,tfMaxScrY:byte;
tfScrSizeInWords:word;
tfOFStable:Array[0..maxscrlines-1] Of Word;
{bytes would work too as the four lower bits of
all offsets are 0, but then you'd have to SHL num,4 and that eats
up the time you're trying to save in the first place}
Procedure tfastinit(X,Y:Word);
{Must be called before using the unit; it sets up a lookup table. This is
done automatically for 80x25; you will have to call this again if you are
using something else like 40x25, 90x30, etc.}
Procedure tfastwritexy(SPtr,destscr:Pointer;X,Y:Word;backfore:Byte);
{Take string s, stick it at scrseg:x,y using attribute byte backfore. This is
very standard stuff, just fast :-) *This procedure honors the PreventSnow
variable.*}
Procedure tfastwritexyHI(SPtr,destscr:Pointer;X,Y:Word;backfore,backforeHI:Byte);
{Identical to tfastwritexy except it will highlight any portion of the string
surrounded by togglechar ("~").}
Procedure tfastwritexyATTR(SPtr,destscr:Pointer;X,Y:Word);
{Take string SPtr and assume it is actually text ATTRIBUTES (not chars!)
and write it to the attribute bytes at X,Y.}
Procedure tfastclrscr(destscr:Pointer;backfore,filler:Byte);
{Clears the screen using attribute backfore. Call this *after* tfastinit. No
wait for retrace on this one since there's no point, it's not called often
enough.}
Procedure tfastcopyscreen(sourcescr,destscr:Pointer;size:word);
{Copies a hidden screen to visible screen ram.
Size is in WORDS, and is provided so that a partial area can be copied if only
some of the screen has changed.
If size=0 then the full screen area is assumed.
*This procedure honors the PreventSnow variable*.}
{These next few implement a "set and forget" write/writeln clone.
Once you set the params, tfastwriteln will do what you expect it to do.}
Procedure tfastsetpos(x,y:word);
Procedure tfastsetcolor(b:byte);
Procedure tfastsetdest(p:pointer);
Procedure tfastwrite_(s:string);
Procedure tfastwriteln(s:string);
Implementation
Uses
m6845ctl,
support;
Const
tftableready:Boolean=False;
maxscrcols=132; {for vesa, although I've gotten 90x30 to work on stock CGA}
{these are for supporting tfastwriteln}
tfwx:byte=0;
tfwy:word=0;
tfwc:byte=0;
tfwp:pointer=ptr($b800,0); {dummy default value}
Procedure tfastinit(X,Y: Word);
{This sets up a lookup table used so that the MULs can be turned into a table.
Yes, I know that you can calc *80 using *64+*16 -- this is still faster.}
Var
ycount:Byte;
Begin
If X > maxscrcols Then X := maxscrcols;
If Y > maxscrlines Then Y := maxscrlines;
{build start-of-line offset table}
For ycount := 0 To Y Do tfOFStable [ycount] := (ycount * X * 2);
{set some sanity vars}
tfmaxscrx := X; tfmaxscry := Y;
tfscrsizeinwords := X * Y;
tftableready := True;
{set default screen pointer to color or mono based on BIOS data area}
tfwp := vidp;
End;
Procedure tfastwritexy(SPtr,destscr: Pointer; X,Y: Word; backfore: Byte); Assembler;
{
CGA "snow" handling OFF notes: Unless I'm missing something obvious, this
is the fastest routine of its kind for 8088. If you can optimize it to be
faster on 8088, you win a prize from trixter@oldskool.org.
CGA "snow" handling ON notes: Eliminates snow by waiting for horizontal
retrace and utilizing vertical retrace if possible. The tradeoff for using
vertical retrace is that sometimes there is snow *barely visible* in the
*first scanline only* of the visible display, but it is annoying, so you can
undefine PERFECTNOSNOW if you want to speed up the routine 30%-60%.
}
{$DEFINE PERFECTNOSNOW}
Asm
cmp tftableready,0 {0 = byte(boolean(false))}
je @alldone {Don't write into an unknown void without the lookup table}
mov dx,m6845_status
les di,destscr {set up es:di to point to base of destination}
mov si,Y
shl si,1 {si=Y * 2 because si is an index into a table of words}
add di,[offset tfOFStable+si] {advance es:di to correct row using precalc table}
mov ax,X {grab x,}
shl ax,1 {multiply by 2,}
add di,ax {now di = (y*numcols) + (x*2), so es:di points to where we'll start writing}
mov ah,backfore {get attribute byte ready for our STOSW}
mov bx,es {for later comparison}
mov bl,tfPreventSnow {when we change DS, we lose our vars, so save this}
push ds
lds si,SPtr {ds:si = string with first byte as length}
cld
lodsb {grab length of string}
xor ch,ch
mov cl,al {use it as our counter}
jcxz @alldone {0 length? get out of here before we write FFFF bytes by mistake}
{at this point, we have everything we need:}
{ds:si=source string; cx=length of string; es:di=destination}
shr bl,1 {is preventsnow false? (bl=01=true}
jnc @writeloopfast {if so, jump to the fast screen update loop}
cmp bh,$b0 {are we writing to the MDA? (dx=$b000)}
je @writeloopfast {if so, jump to the fast screen update loop}
cmp bh,$b8 {are we writing to the CGA? (dx=$b800)}
jne @writeloopfast {if not, jump to the fast screen update loop}
@writeloopslow:
lodsb {grab our character to al}
xchg bx,ax {now hide it in bl - xchg bx,ax is 1-byte opcode}
cli {start of critical time}
@WDN: {wait until we're out of some random retrace we may have started in}
in al,dx {grab status bits}
{$IFNDEF PERFECTNOSNOW}
test al,c_vertical_sync {are we in vertical retrace?}
jnz @blastit {if so, we've got time to write a word, let's do it!}
{$ENDIF}
shr al,1 {are we in some random horiz retrace? If so, wait}
jc @WDN {until we're out of it so we can sync properly}
@WDR: {wait until we're in either vert or horiz retrace}
in al,dx {grab status bits}
shr al,1 {were we in horizontal retrace?}
jnc @WDR {if not, keep waiting}
@blastit:
xchg bx,ax {get char back - 1-byte opcode}
stosw {write it out - another 1-byte opcode - we need speed because otherwise we will see snow!}
sti {end of critical time}
loop @writeloopslow {keep looping to put the string out}
jmp @alldone
@writeloopfast:
{we unroll this so we can exploit our tiny 4-byte prefetch queue on 8088}
mov dx,cx {preserve original count for later}
shr cx,1
shr cx,1
shr cx,1
jcxz @handlestragglers {jump if string length < size that unrolled loop handles}
@copyloopunrolled:
lodsb {load character}
stosw {store attrib+char}
lodsb {in case it wasn't obvious, lodsb and stosw are}
stosw {1 bytes, so we keep the 4-byte prefetch queue}
lodsb {full by doing this. In case this seems like}
stosw {a waste, go ahead and do your own tests and}
lodsb {you'll see this is the fastest mix of unrolling.}
stosw {I tried multiple combinations and this was the}
lodsb {best result.}
stosw
lodsb
stosw
lodsb
stosw
lodsb
stosw
loop @copyloopunrolled
@handlestragglers:
mov cx,dx {cx:=number of times we'll have to do this after the unrolled loop}
and cx,00000111b
jcxz @alldone {Length was a multiple of the size of the unroll loop (no remainder) so bail}
@copyloopsingle:
lodsb
stosw
loop @copyloopsingle
@alldone:
pop ds
End;
Procedure tfastwritexyATTR(SPtr,destscr: Pointer; X,Y: Word); Assembler;
Asm
cmp tftableready,0 {0 = byte(boolean(false))}
je @alldone {Don't write into an unknown void without the lookup table}
mov dx,m6845_status
les di,destscr {set up es:di to point to base of destination}
mov dx,es {need this for later comparison}
mov si,Y
shl si,1 {si=Y * 2 because si is an index into a table of words}
add di,[offset tfOFStable+si] {advance es:di to correct row using precalc table}
mov ax,X {grab x,}
shl ax,1 {multiply by 2,}
add di,ax {now di = (y*numcols) + (x*2), so es:di points to where we'll start writing}
inc di {...but only to the attribute bytes}
mov bx,es
mov bl,tfPreventSnow {when we change DS, we lose our vars, so save this}
push ds
lds si,SPtr {ds:si = string with first byte as length}
cld
lodsb {grab length of string}
xor ch,ch
mov cl,al {use it as our counter}
jcxz @alldone {0 length? get out of here before we write FFFF bytes by mistake}
{at this point, we have everything we need:}
{ds:si=source string; cx=length of string; es:di=destination}
shr bl,1 {is preventsnow false? (bl=01=true}
jnc @writeloopfast {if so, jump to the fast screen update loop}
cmp bh,$b0 {are we writing to the MDA? (dx=$b000)}
je @writeloopfast {if so, jump to the fast screen update loop}
cmp bh,$b8 {are we writing to the CGA? (dx=$b800)}
jne @writeloopfast {if not, jump to the fast screen update loop}
@writeloopslow:
lodsb {grab our attribute to al}
xchg bx,ax {now hide it in bl - xchg bx,ax is 1-byte opcode}
cli {start of critical time}
@WDN: {wait until we're out of some random retrace we may have started in}
in al,dx {grab status bits}
{$IFNDEF PERFECTNOSNOW}
test al,c_vertical_sync {are we in vertical retrace?}
jnz @blastit {if so, we've got time to write a word, let's do it!}
{$ENDIF}
shr al,1 {are we in some random horiz retrace? If so, wait}
jc @WDN {until we're out of it so we can sync properly}
@WDR: {wait until we're in either vert or horiz retrace}
in al,dx {grab status bits}
shr al,1 {were we in horizontal retrace?}
jnc @WDR {if not, keep waiting}
@blastit:
xchg bx,ax {get char back - 1-byte opcode}
stosb {write it out}
inc di {skip next char}
sti {end of critical time}
loop @writeloopslow {keep looping to put the string out}
jmp @alldone
@writeloopfast:
{we unroll this so we can exploit our tiny 4-byte prefetch queue on 8088}
mov dx,cx {preserve original count for later}
shr cx,1
shr cx,1
shr cx,1
jcxz @handlestragglers {jump if string length < size that unrolled loop handles}
@copyloopunrolled:
movsb {load attribute and store it}
inc di {and move to next attrib location}
movsb
inc di
movsb
inc di
movsb
inc di
movsb
inc di
movsb
inc di
movsb
inc di
movsb
inc di
loop @copyloopunrolled
@handlestragglers:
mov cx,dx {cx:=number of times we'll have to do this after the unrolled loop}
and cx,00000111b
jcxz @alldone {Length was a multiple of the size of the unroll loop (no remainder) so bail}
@copyloopsingle:
movsb
inc di
loop @copyloopsingle
@alldone:
pop ds
End;
Procedure tfastwritexyHI(SPtr,destscr: Pointer; X,Y: Word; backfore,backforeHI: Byte);
type
pstringbyte=^tstringbyte;
tstringbyte=array[0..255] of byte;
pstringword=^tstringword;
tstringword=array[0..255] of word;
var
sa:tstringword; {built-up vidram to copy}
ndp,massaged:pointer;
_sp:pstringbyte;
sizew:word;
begin
ndp:=destscr;
massaged:=@sa;
_sp:=sptr;
{if the last character is a toggle, this will cause problems, so we'll trim}
if char(_sp^[_sp^[0]])=togglechar then dec(_sp^[0]);
asm
push ds
mov dl,backfore
mov dh,backforeHI
xor dh,dl {now we can xor with dh to toggle}
les di,massaged {es:di = where we write massaged string to}
lds si,_sp {ds:si = source string}
xor cx,cx
mov bx,cx
lodsb {grab length of string}
mov cl,al
mov ah,dl {preload attribute}
@massage:
lodsb
cmp al,togglechar {is it our toggle char?}
jne @writechar {write char if not}
lodsb {grab real char if so}
xor ah,dh {toggle our attribute}
dec cx {account for the togglechar}
@writechar:
stosw
inc bx {increase our "words output" var}
loop @massage
pop ds
mov sizew,bx
end;
{at this point massaged has the char+attr buffer.
calc new destination based on x,y and do a
tfastcopyscreen(sourcescr,destscr:Pointer;size:word);}
inc(word(ndp),tfOfsTable[y] + (x*2));
tfastcopyscreen(massaged,ndp,sizew);
end;
Procedure tfastclrscr(destscr:Pointer;backfore,filler:Byte); Assembler;
Asm
cmp tftableready,0 {we need this to get sizeinwords}
je @cleardone {Need lookup table for vars to be initialized}
les DI,destscr
cld
mov AH,backfore
mov AL,filler
mov CX,tfscrsizeinwords
rep stosw
@cleardone:
End;
Procedure tfastcopyscreen(sourcescr,destscr:Pointer;size:word); Assembler;
{
If prevent snow is on, screen ram is updated during vertical and horizontal
retraces only. This means a full-screen snow-free update can happen about 12
times a second (fast!), thanks to taking advantage of horizontal retrace too.
Much thanks to Richard Wilton for the idea and example code.
}
Const
horiz_timeout=6;
vb_chunksize=478; {empirically discovered on a stock IBM 5160}
Asm
cmp tftableready,0 {we need this to get sizeinwords}
je @finalend {Don't write into an unknown void without the lookup table}
MOV DX, m6845_status
mov CX,tfscrsizeinwords {assume user wants full screen copied}
cmp size,0 {does user want full screen?}
je @init2
mov cx,size
@init2:
mov AL,tfPreventSnow
les DI,destscr
mov bx,es
push DS
lds SI,sourcescr
cmp bx,$b000 {are we writing to the MDA?}
je @slamit {if so, jump to the fast screen update loop}
cmp AL, 0 {is preventsnow true?}
ja @doitnicely {if so, jump to our screen update loop}
@slamit:
cld
rep movsw {if not, slam it!!}
jmp @donecopy {...and then exit the routine}
@doitnicely:
{write during remaining vertical blanking interval}
@L01:
mov bx,cx {preserve buffer length in BX}
mov cx,horiz_timeout {CX := horizontal timeout}
cli {disable interrupts during loop}
@L02:
in al,dx {AL := video status}
test al,c_display_enable
loopnz @L02 {loop while Display Enable inactive}
jz @L03 {jump if loop did not time out}
movsw {copy one word}
sti
mov cx,bx {CX := buffer length}
loop @L01
jmp @donecopy {exit (entire string copied)}
{write during horizontal blanking intervals}
@L03:
sti {enable previous interrupt state}
mov cx,bx {restore CX}
@L04:
lodsw {AL := character code, AH := attribute}
mov bx,ax {BX := character and attribute}
push cx {preserve word loop counter}
mov cx,horiz_timeout {CX := timeout loop limit}
cli {clear interrupts during one scan line}
@L05:
in al,dx
test al,c_display_enable
loopnz @L05 {loop during horizontal blanking until timeout occurs}
jnz @L07 {jump if timed out (vertical blanking has started)}
@L06:
in al,dx
test al,c_display_enable
jz @L06 {loop while Display Enable is active}
xchg bx,ax {AX := character & attribute}
stosw {copy 2 bytes to display buffer}
sti {restore interrupts}
pop cx {CX := word loop counter}
loop @L04
jmp @donecopy {exit (entire string copied)}
{write during entire vertical blanking interval}
@L07:
pop bx {BX := word loop counter}
dec si
dec si {DS:SI -> word to copy from buffer}
mov cx,vb_chunksize {CX := # of words to copy}
cmp bx,cx
jnb @L08 {jump if more than vb_chunksize words remain in buffer}
mov cx,bx {CX := # of remaining words in buffer}
xor bx,bx {BX := 0}
jmp @L09
@L08:
sub bx,cx {BX := (# of remaining words) - vb_chunksize}
@L09:
cld
rep movsw {copy to video buffer}
mov cx,bx {CX := # of remaining words}
test cx,cx
jnz @L01 {loop until buffer is displayed}
@donecopy:
pop DS
@finalend:
End;
Procedure tfastsetpos(x,y:word); begin tfwx:=x; tfwy:=y; end;
Procedure tfastsetcolor(b:byte); begin tfwc:=b; end;
Procedure tfastsetdest(p:pointer); begin tfwp:=p; end;
Procedure tfastwrite_(s:string);
begin
tfastwritexy(@s,tfwp, tfwx, tfwy, tfwc);
inc(tfwx,length(s));
end;
Procedure tfastwriteln(s:string);
begin
tfastwritexy(@s,tfwp, tfwx, tfwy, tfwc);
tfwx:=0;
inc(tfwy);
end;
begin
tfastinit(80,25);
end.
|
unit VersionQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TVersionW = class(TDSWrap)
private
FVersion: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property Version: TFieldWrap read FVersion;
end;
TQueryVersion = class(TQueryBase)
private
FW: TVersionW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
class function GetDBVersion: Integer; static;
property W: TVersionW read FW;
{ Public declarations }
end;
implementation
constructor TVersionW.Create(AOwner: TComponent);
begin
inherited;
FVersion := TFieldWrap.Create(Self, 'Version', '', True);
end;
constructor TQueryVersion.Create(AOwner: TComponent);
begin
inherited;
FW := TVersionW.Create(FDQuery);
end;
class function TQueryVersion.GetDBVersion: Integer;
var
Q: TQueryVersion;
begin
Q := TQueryVersion.Create(nil);
try
Q.W.TryOpen;
Result := Q.W.Version.F.AsInteger;
finally
FreeAndNil(Q);
end;
end;
{$R *.dfm}
end.
|
PROGRAM Hello(INPUT, OUTPUT);
BEGIN REPEAT WRITELN('BEGIN Hello world!');
UNTIL FALSE;END. |
unit MD5.Console;
INTERFACE
uses
System.SysUtils,
MD5.Utils,
Windows;
type
TConsole = class
private
CharsCounter: Integer;
DefaultAttr: Integer;
OutputHandle: Integer;
FWidth, FHeight: Integer;
procedure Write0(const Attr: Integer; P: PChar; Len: Integer); overload; // MAIN!
public
// cursor moves/info
function GetCursorX: Integer;
function GetCursorY: Integer;
procedure GetCursorXY(out x, y: Integer);
procedure SetCursorXY(x, y: Integer);
// write text
procedure Write(const S: String); overload;
procedure Write(const Attr: Integer; const S: String); overload;
procedure WriteLn; overload;
// write numbers
procedure WriteFormatNumber(const Attr: Integer; N: UInt64); overload;
procedure WriteFormatNumber(N: UInt64); overload;
procedure WriteFormatNumberSize(const Attr: Integer; N: UInt64);
// write paths
procedure WriteFileName(const Attr: Integer; const S: String; ReduceToScreenEdge: Boolean = FALSE);
// write repeated text
procedure WriteRepeat(const S: String; Count: Integer); overload;
procedure WriteRepeat(const Attr: Integer; const S: String; Count: Integer); overload;
// useful functions
// procedure WriteValueLn(const Attr: Integer; const S1, S2, S3: String);
procedure WritePointLn;
// update engine :)
procedure UpdateBegin(var Counter: Integer);
procedure UpdateEnd(var Counter: Integer);
procedure UpdateClear(var Counter: Integer);
// init/done
constructor Create;
destructor Destroy; override;
//
property Width: Integer read FWidth;
property Height: Integer read FHeight;
end;
IMPLEMENTATION
uses
MD5.FileUtils;
constructor TConsole.Create;
var
Info: TConsoleScreenBufferInfo;
begin
inherited;
OutputHandle := GetStdHandle( STD_OUTPUT_HANDLE );
GetConsoleScreenBufferInfo(OutputHandle, Info);
DefaultAttr := Info.wAttributes;
CharsCounter := -1;
FWidth := Info.dwSize.X;
FHeight := Info.dwSize.Y;
end;
destructor TConsole.Destroy;
begin
OutputHandle := 0;
inherited;
end;
function TConsole.GetCursorX: Integer;
var
Dummy: Integer;
begin
GetCursorXY(Result, Dummy);
end;
function TConsole.GetCursorY: Integer;
var
Dummy: Integer;
begin
GetCursorXY(Dummy, Result);
end;
procedure TConsole.SetCursorXY(x, y: Integer);
var
Info: TConsoleScreenBufferInfo;
Coord: TCoord;
begin
if (x = -1) OR (y = -1) then
begin
GetConsoleScreenBufferInfo(OutputHandle, Info);
end;
//
if x = -1 then Coord.X := Info.dwCursorPosition.X else Coord.X := x;
if y = -1 then Coord.Y := Info.dwCursorPosition.Y else Coord.Y := y;
//
SetConsoleCursorPosition(OutputHandle, Coord);
end;
procedure TConsole.GetCursorXY(out x, y: Integer);
var
Info: TConsoleScreenBufferInfo;
begin
GetConsoleScreenBufferInfo(OutputHandle, Info);
x := Info.dwCursorPosition.X;
y := Info.dwCursorPosition.Y;
end;
procedure TConsole.Write0(const Attr: Integer; P: PChar; Len: Integer);
var
t: Cardinal;
begin
if OutputHandle = 0 then Exit;
//
// Установка атрибутов цвета
if Attr = -1 then SetConsoleTextAttribute(OutputHandle, DefaultAttr)
else SetConsoleTextAttribute(OutputHandle, Attr);
// Вывод текста
WriteConsoleW(OutputHandle, P, Len, t, NIL);
// Если нужно, подсчет количества выведенных символов
if CharsCounter >= 0 then Inc(CharsCounter, t);
end;
//==============================================================================
procedure TConsole.WriteRepeat(const S: String; Count: Integer);
begin
WriteRepeat(-1, S, Count);
end;
procedure TConsole.WriteRepeat(const Attr: Integer; const S: String; Count: Integer);
begin
if Count > 0 then
begin
case S.Length of
0: Exit;
1: Write0(Attr, PChar(StringOfChar(S[1], Count)), Count);
else
while Count > 0 do
begin
Dec(Count);
Write0(Attr, PChar(S), S.Length);
end;
end;
end;
end;
procedure TConsole.Write(const S: String);
begin
Write0(-1, PChar(S), S.Length);
end;
procedure TConsole.Write(const Attr: Integer; const S: String);
begin
Write0(Attr, PChar(S), S.Length);
end;
procedure TConsole.WriteFileName(const Attr: Integer; const S: String; ReduceToScreenEdge: Boolean = FALSE);
var
ReduceChars: Integer;
begin
Write(Attr, '"');
if ReduceToScreenEdge then
begin
ReduceChars := Width - GetCursorX - 5;
Write(Attr, ReduceFileName(S, ReduceChars));
end else
begin
Write(Attr, S);
end;
Write(Attr, '"');
end;
procedure TConsole.WriteFormatNumber(N: UInt64);
begin
WriteFormatNumber(-1, N);
end;
procedure TConsole.WriteFormatNumber(const Attr: Integer; N: UInt64);
var
S: String;
begin
S := FormatNumberHelper(N);
Write0(Attr, PChar(S), S.Length);
end;
procedure TConsole.WriteFormatNumberSize(const Attr: Integer; N: UInt64);
//var
// Value, KBytes, MBytes, GBytes, PBytes: Double;
// Suffix: String;
const
MB_DIVISOR = 1024*1024;
GB_DIVISOR = 1024*1024*1024;
//var
// FS: TFormatSettings;
begin
if (N DIV MB_DIVISOR) >= 1 then
begin
Write(' (');
WriteFormatNumber(Attr, N DIV MB_DIVISOR);
Write(' MBytes');
if (N DIV GB_DIVISOR) >= 1 then // if >= 1.xxx Gb
begin
Write('; ');
// FS := TFormatSettings.Create;
// FS.DecimalSeparator := '.';
// Write(Attr, Format('%.2f', [N/GB_DIVISOR], FS));
Write(Attr, Format('%.2f', [N/GB_DIVISOR]));
Write(' GBytes');
end;
Write(')');
end;
//
(*
KBytes := N / 1024;
MBytes := KBytes / 1024;
GBytes := MBytes / 1024;
PBytes := GBytes / 1024;
//
if PBytes < 1 then
begin
Suffix := 'GBytes';
Value := GBytes;
end else if GBytes < 1 then
begin
Suffix := 'MBytes';
Value := MBytes;
end else if MBytes < 1 then
begin
Suffix := 'KBytes';
Value := KBytes;
end else Exit; // bytes and pbytes is show as bytes
//
Write(' (');
Write(Attr, Format('%.2f', [Value]));
Write(' ');
Write(Suffix);
Write(')');
*)
end;
procedure TConsole.WriteLn;
const
CRLF = #13#10;
begin
Write0(-1, PChar(CRLF), CRLF.Length);
end;
procedure TConsole.WritePointLn;
begin
// Write('.');
WriteLn;
end;
//procedure TConsole.WriteValueLn(const Attr: Integer; const S1, S2, S3: String);
//begin
// Write0(-1, PChar(S1), S1.Length);
// Write0(Attr, PChar(S2), S2.Length);
// Write0(-1, PChar(S3), S3.Length);
// WriteLn;
//end;
procedure TConsole.UpdateBegin(var Counter: Integer);
begin
WriteRepeat(#8, Counter);
CharsCounter := 0;
end;
procedure TConsole.UpdateEnd(var Counter: Integer);
var
Diff: Integer;
begin
Diff := Counter - CharsCounter;
Counter := CharsCounter;
CharsCounter := -1;
// Действуем в том случае, если вывели
// меньше символов, чем в предыдущий раз
if Diff > 0 then
begin
// clear trail symbols
WriteRepeat(' ', Diff);
WriteRepeat(#8, Diff);
end;
end;
procedure TConsole.UpdateClear(var Counter: Integer);
begin
WriteRepeat(#8, Counter); // back to begin
WriteRepeat(' ', Counter); // clear
WriteRepeat(#8, Counter); // again back to begin
Counter := 0;
// UpdateBegin(Counter);
// UpdateEnd(Counter);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSClientResStrs;
interface
resourcestring
SJSProxyNoStream = 'No output stream was specified.';
SJSProxyNoConnection = 'No Connection was specified.';
SUnexpectedRequestType = 'Unexpected request type: %s.';
sUnexpectedResult = 'Unexpected server method result';
SNoWriter = 'Proxy writer not specified';
SUnknownWriter = 'Unknown proxy writer: %s';
SGeneratedCode = 'Created by the DataSnap proxy generator.';
SStreamNotFound = 'Stream not found';
SNoMetaData = 'No proxy meta data';
SNoMetaDataAtDesignTime = 'Cannot retrieve meta data from %s at design time.';
SUnableToRetrieveServerMethodParameters = 'Unable to retrieve server method parameters';
sInvalidServerMethodName = 'Invalid server method name: %s';
sMissingCommandPath = 'Missing command path';
sMissingParameterPath = 'Missing parameter path';
sLoadPackageNextTime = 'Do you want to attempt to load this package in the future?';
sUntitledPackage = '(untitled)';
sErrorLoadingPackage = 'Can''t load package %s.' + sLineBreak + '%s';
sCannotChangeIPImplID = 'Cannot change IPImplementationID once DSRestConnection is initialized';
implementation
end.
|
unit adot.Collections;
{$OVERFLOWCHECKS OFF}
{ Definition of classes/record types:
TAutoFreeCollection = record
Collection of objects to be destroyed automaticaly when collection goes out of scope.
TComparerUtils = class
Default comparer/equality comparer etc.
TCompound<TypeA,TypeB,TypeC> = record
Compound record with three fields. Provides constructor and comparers for use in collections.
TCompound<TypeA,TypeB> = record
Compound record with two fields. Provides constructor and comparers for use in collections.
TCompoundComparer<TypeA,TypeB,TypeC> = class
Comparer for compound of three fields.
TCompoundComparer<TypeA,TypeB> = class
Comparer for compound of two fields.
TCompoundEqualityComparer<TypeA,TypeB,TypeC> = class
Equality comparer for compound of three fields.
TCompoundEqualityComparer<TypeA,TypeB> = class
Equality comparer for compound of two fields.
TIndexBackEnumerator = record
Index enumerator "from last to first".
}
interface
uses
adot.Types,
System.Generics.Collections,
System.Generics.Defaults,
System.TypInfo,
System.SysUtils,
System.Math;
type
{ Delphi has two definitions of TCollectionNotification: System.Classes and System.Generics.Collections }
TCollectionNotification = System.Generics.Collections.TCollectionNotification;
{ All objects placed in TAutoFreeCollection will be destroyed automatically
when collection goes out of the scope. Items will be removed in reverse order.
Example:
var
C: TAutoFreeCollection;
A: T1;
B: T2;
begin
A := C.Add( T1.Create ); // First added, last destroyed.
B := C.Add( T2.Create ); // Last added, first destroyed.
[do something with A and B]
End; }
{ Collection of objects to be destroyed automaticaly when collection goes out of scope }
TAutoFreeCollection = record
private
type
IAutoFreeCollection = interface(IUnknown)
procedure Add(AObject: TObject);
function GetCount: integer;
function GetItem(n: integer): TObject;
function Extract(n: integer): TObject;
function ExtractAll: TArray<TObject>;
end;
TAutoFreeCollectionImpl = class(TInterfacedObject, IAutoFreeCollection)
protected
FList: TObjectList<TObject>;
public
constructor Create;
destructor Destroy; override;
procedure Add(AObject: TObject);
function GetCount: integer;
function GetItem(n: integer): TObject;
function Extract(n: integer): TObject;
function ExtractAll: TArray<TObject>;
end;
var
FGuard: IAutoFreeCollection;
function GetCount: integer;
function GetItem(n: integer): TObject;
function Guard: IAutoFreeCollection;
public
procedure Init;
class function Create: TAutoFreeCollection; static;
procedure Clear;
function Add<T: class>(AObject: T):T;
function Empty: Boolean;
function Extract(n: integer): TObject;
function ExtractAll: TArray<TObject>;
property Count: integer read GetCount;
property Items[n: integer]: TObject read GetItem;
end;
TAC = TAutoFreeCollection;
{ Always use TCompoundEqualityComparer.Default for creating of compatible comparer
It supports efficiently both - record types and managed types.
There is also TCompoundComparer class.
Example:
type
TKey = TCompound<String, TArray<Integer>>;
var
m: TMap<TKey, Double>;
begin
m := TMap<TKey, Double>.Create(TCompoundEqualityComparer<String, TArray<Integer>>.Default);
m.Add(TKey.Create('test', TArrayHelper.Get<integer>([1,2,3])), 3.1415926);
end; }
{ Compound record with two fields. Provides constructor and comparers for use in collections. }
TCompound<TypeA,TypeB> = record
A: TypeA;
B: TypeB;
constructor Create(const A: TypeA; const B: TypeB);
procedure Init(const A: TypeA; const B: TypeB);
class operator Implicit(const Src: TCompound<TypeA,TypeB>): TPair<TypeA,TypeB>;
class operator Implicit(const Src: TPair<TypeA,TypeB>): TCompound<TypeA,TypeB>;
class operator Explicit(const Src: TCompound<TypeA,TypeB>): TPair<TypeA,TypeB>;
class operator Explicit(const Src: TPair<TypeA,TypeB>): TCompound<TypeA,TypeB>;
end;
{ Compound record with three fields. Provides constructor and comparers for use in collections. }
TCompound<TypeA,TypeB,TypeC> = record
A: TypeA;
B: TypeB;
C: TypeC;
constructor Create(const A: TypeA; const B: TypeB; const C: TypeC);
procedure Init(const A: TypeA; const B: TypeB; const C: TypeC);
end;
{ Equality comparer for compound of two fields. }
TCompoundEqualityComparer<TypeA,TypeB> = class(TEqualityComparer<TCompound<TypeA,TypeB>>)
protected
var
FComparerA: IEqualityComparer<TypeA>;
FComparerB: IEqualityComparer<TypeB>;
class var
FOrdinalComparer: IEqualityComparer<TCompound<TypeA,TypeB>>;
public
class function Default: IEqualityComparer<TCompound<TypeA,TypeB>>; reintroduce;
constructor Create(
ComparerA: IEqualityComparer<TypeA>;
ComparerB: IEqualityComparer<TypeB>
);
function Equals(const Left, Right: TCompound<TypeA,TypeB>): Boolean; overload; override;
function GetHashCode(const Value: TCompound<TypeA,TypeB>): Integer; overload; override;
end;
{ Equality comparer for compound of three fields. }
TCompoundEqualityComparer<TypeA,TypeB,TypeC> = class(TEqualityComparer<TCompound<TypeA,TypeB,TypeC>>)
protected
var
FComparerA: IEqualityComparer<TypeA>;
FComparerB: IEqualityComparer<TypeB>;
FComparerC: IEqualityComparer<TypeC>;
class var
FOrdinalComparer: IEqualityComparer<TCompound<TypeA,TypeB,TypeC>>;
public
class function Default: IEqualityComparer<TCompound<TypeA,TypeB,TypeC>>; reintroduce;
constructor Create(
ComparerA: IEqualityComparer<TypeA>;
ComparerB: IEqualityComparer<TypeB>;
ComparerC: IEqualityComparer<TypeC>
);
function Equals(const Left, Right: TCompound<TypeA,TypeB,TypeC>): Boolean; overload; override;
function GetHashCode(const Value: TCompound<TypeA,TypeB,TYpeC>): Integer; overload; override;
end;
{ Comparer for compound of two fields. }
TCompoundComparer<TypeA,TypeB> = class(TComparer<TCompound<TypeA,TypeB>>)
protected
var
FComparerA: IComparer<TypeA>;
FComparerB: IComparer<TypeB>;
class var
FOrdinalComparer: IComparer<TCompound<TypeA,TypeB>>;
public
class function Default: IComparer<TCompound<TypeA,TypeB>>; reintroduce;
constructor Create(ComparerA: IComparer<TypeA>; ComparerB: IComparer<TypeB>);
function Compare(const Left, Right: TCompound<TypeA,TypeB>): Integer; override;
end;
{ Comparer for compound of three fields. }
TCompoundComparer<TypeA,TypeB,TypeC> = class(TComparer<TCompound<TypeA,TypeB,TypeC>>)
protected
var
FComparerA: IComparer<TypeA>;
FComparerB: IComparer<TypeB>;
FComparerC: IComparer<TypeC>;
class var
FOrdinalComparer: IComparer<TCompound<TypeA,TypeB,TypeC>>;
public
class function Default: IComparer<TCompound<TypeA,TypeB,TypeC>>; reintroduce;
constructor Create(
ComparerA: IComparer<TypeA>;
ComparerB: IComparer<TypeB>;
ComparerC: IComparer<TypeC>
);
function Compare(const Left, Right: TCompound<TypeA,TypeB,TypeC>): Integer; override;
end;
{ Default comparer/equality comparer etc. }
TComparerUtils = class
public
{ For string type we use case insensitive comparer by default }
class function DefaultComparer<T>: IComparer<T>; static;
class function DefaultEqualityComparer<T>: IEqualityComparer<T>; static;
class function DefaultArithmetic<T>: IArithmetic<T>; static;
class function CompoundComparer<A,B>: IComparer<TCompound<A,B>>; overload; static;
class function CompoundComparer<A,B,C>: IComparer<TCompound<A,B,C>>; overload; static;
class function CompoundEqualityComparer<A,B>: IEqualityComparer<TCompound<A,B>>; overload; static;
class function CompoundEqualityComparer<A,B,C>: IEqualityComparer<TCompound<A,B,C>>; overload; static;
class function Equal<T>(A,B: TEnumerable<T>): boolean; overload; static;
class function Equal<T>(A,B: TEnumerable<T>; Comparer: IComparer<T>): boolean; overload; static;
class function Equal<T>(A: TEnumerable<T>; const B: TArray<T>): boolean; overload; static;
class function Equal<T>(A: TEnumerable<T>; const B: TArray<T>; Comparer: IComparer<T>): boolean; overload; static;
class function Compare<T>(const Left, Right: TList<T>; ItemComparer: IComparer<T>): integer; overload; static;
class function Compare<T>(const Left, Right: TArray<T>; ItemComparer: IComparer<T>): integer; overload; static;
class function Compare(const Left, Right: string; CaseInsensitive: boolean = True): integer; overload; static;
class function Compare(const Left, Right: integer): integer; overload; static;
class function Compare(const Left, Right: double): integer; overload; static;
class function Compare(const Left, Right: boolean): integer; overload; static;
end;
{ Integer range (pair [min_value; max_value]).
Example 1:
var R: TRange; // we will generate ranges for array of item numbers
for R in TArrayUtils.Ranges([9, 1, 7, 2, 5, 8]) do // R : [1-2] [5] [7-9]
DeleteItems(R.Start, R.Length); // Params: (1,2) (5,1) (7,3)
Example 2:
var X,Y: TRange;
X.Clear; Y.Clear; // we will find min rectange containing all controls
for I := 0 to ControlCount-1 do
begin
X.AddOrSet(Controls[I].Left, Controls[I].Left + Controls[I].Width);
Y.AddOrSet(Controls[I].Top, Controls[I].Top + Controls[I].Height);
end;
R := TRectangle.Create(X.ValueMin,Y.ValueMin,X.ValueMax,Y.ValueMax);
}
TRange = record
private
FValueMin,FValueMax: integer;
type
TEnumerator = record
private
FCurValue, FMaxValue: integer;
public
constructor Create(const R: TRange);
function MoveNext: boolean;
function GetCurrentValue: integer;
property Current: integer read GetCurrentValue;
end;
function GetAsString: string;
procedure SetAsString(const Value: string);
function GetEmpty: boolean;
function GetLength: integer;
public
procedure Init(AValueMin,AValueMax: integer);
function GetEnumerator: TEnumerator;
{ assign empty range (with no elements) }
procedure Clear;
{ Assign new range or extend existing one (Range[1,3] = Range[3,1]) }
procedure AddOrSet(AValueMin,AValueMax: integer);
{ Extend range (Range[1,3] = Range[3,1]) }
procedure Add(AValueMin,AValueMax: integer);
{ Check if range has intersection with A }
function Overlaps(const a: TRange): boolean;
{ Check if B contains all elements from A }
class operator In(const a: TRange; b: TRange) : Boolean;
class operator In(const a: integer; b: TRange) : Boolean;
{ [1,3] + [5,7] -> [1,7]}
class operator Add(const a,b: TRange) : TRange;
{ Subtract may produce two ranges, it can't be implemented with single TRange as result
class operator Subtract(const a,b: TRange) : TRange; }
{ [1,5] AND [4,7] = [4,5] }
class operator LogicalAnd(const a,b: TRange) : TRange;
{ Similar to ADD, but returns empty range if A and B has no intersection }
class operator LogicalOr(const a,b: TRange) : TRange;
{ XOR may produce two ranges, it can't be implemented with single TRange as result
class operator LogicalXor(const a,b: TRange) : TRange; }
{ [1,5] -> [2,6] }
class operator Inc(const a: TRange) : TRange;
{ [1,5] -> [0,4] }
class operator Dec(const a: TRange) : TRange;
class operator Equal(const a,b: TRange) : Boolean;
class operator NotEqual(const a,b: TRange) : Boolean;
class operator GreaterThanOrEqual(const a,b: TRange) : Boolean;
class operator GreaterThan(const a,b: TRange) : Boolean;
class operator LessThan(const a,b: TRange) : Boolean;
class operator LessThanOrEqual(const a,b: TRange) : Boolean;
{ [1,3] -> "[1,3]" }
property AsString: string read GetAsString write SetAsString;
property Empty: boolean read GetEmpty;
property Length: integer read GetLength;
{ synonyms to FValueMin/FValueMax }
property Start: integer read FValueMin write FValueMin;
property Finish: integer read FValueMax write FValueMax;
property Left: integer read FValueMin write FValueMin;
property Right: integer read FValueMax write FValueMax;
property ValueMin: integer read FValueMin write FValueMin;
property ValueMax: integer read FValueMax write FValueMax;
end;
TRangeEnumerator = record
private
Src: TArray<integer>;
Cur: integer;
function GetCurrent: TRange;
public
procedure Init(Src: TArray<integer>);
function MoveNext: boolean;
property Current: TRange read GetCurrent;
end;
TRangeEnumerable = record
private
Src: TArray<integer>;
public
procedure Init(Src: TArray<integer>);
function GetEnumerator: TRangeEnumerator;
end;
TRangeComparer = class(TComparer<TRange>)
protected
class var
FOrdinalComparer: IComparer<TRange>;
public
class function Ordinal: IComparer<TRange>; reintroduce;
function Compare(const Left, Right: TRange): Integer; override;
end;
{ Generic singleton pattern. Creates instance on first request. Example:
Type
TOptions = class(TSingletonConstr<TStringList>)
protected
class function CreateInstance: TStringList; override;
end;
class function TOptions.CreateInstance: TStringList;
begin
result := TStringList.Create;
end;
procedure Test;
begin
TOptions.Ordinal.Add('test');
end;
}
{ constructor is required (CreateInstance) }
TSingletonConstr<T: class> = class abstract
protected
class var
FOrdinal: T;
{ must be overridden by descendant class }
class function CreateInstance: T; virtual; abstract;
class destructor DestroyClass;
public
{ We can't use "property Ordinal" here, because Delphi (10.2 Seattle at least) allows to map
class properties only to static class methods. But static method doesn't have access to class info
and can not call correct virtual method (we need to call CreateInstance from GetOrdinal).
That is why we have to use function Ordinal + procedure SetOrdinal instead of one property Ordinal }
class function Ordinal: T;
class procedure SetOrdinal(const Value: T); static;
end;
{
Type
TOptions = class(TSingleton<TStringList>);
procedure Test;
begin
TOptions.Ordinal.Add('test');
end;
}
{ public/parameterless constructor is used by default }
TSingleton<T: class, constructor> = class(TSingletonConstr<T>)
protected
class function CreateInstance: T; override;
end;
{ Can be used as default enumerator in indexable containers (to implement "for I in XXX do" syntax), example:
function TListExt.GetEnumerator: TIndexBackEnumerator;
begin
result := TIndexBackEnumerator.Create(LastIndex, StartIndex);
end; }
{ Index enumerator "from last to first". }
TIndexBackEnumerator = record
private
FCurrentIndex, FToIndex: integer;
public
procedure Init(AIndexFrom, AIndexTo: integer);
function GetCurrent: Integer;
function MoveNext: Boolean;
property Current: Integer read GetCurrent;
end;
implementation
uses
adot.Arithmetic,
adot.Tools,
adot.Hash;
{ TCompound<TypeA, TypeB> }
constructor TCompound<TypeA, TypeB>.Create(const A: TypeA; const B: TypeB);
begin
Init(A,B);
end;
class operator TCompound<TypeA, TypeB>.Explicit(const Src: TCompound<TypeA, TypeB>): TPair<TypeA, TypeB>;
begin
result := result.Create(Src.A, Src.B);
end;
class operator TCompound<TypeA, TypeB>.Explicit(const Src: TPair<TypeA, TypeB>): TCompound<TypeA, TypeB>;
begin
result.Init(Src.Key, Src.Value);
end;
class operator TCompound<TypeA, TypeB>.Implicit(const Src: TCompound<TypeA, TypeB>): TPair<TypeA, TypeB>;
begin
result := result.Create(Src.A, Src.B);
end;
class operator TCompound<TypeA, TypeB>.Implicit(const Src: TPair<TypeA, TypeB>): TCompound<TypeA, TypeB>;
begin
result.Init(Src.Key, Src.Value);
end;
procedure TCompound<TypeA, TypeB>.Init(const A: TypeA; const B: TypeB);
begin
Self := Default(TCompound<TypeA, TypeB>);
Self.A := A;
Self.B := B;
end;
{ TCompound<TypeA, TypeB, TypeC> }
constructor TCompound<TypeA, TypeB, TypeC>.Create(const A: TypeA; const B: TypeB; const C: TypeC);
begin
Init(A,B,C);
end;
procedure TCompound<TypeA, TypeB, TypeC>.Init(const A: TypeA; const B: TypeB; const C: TypeC);
begin
Self := Default(TCompound<TypeA, TypeB, TypeC>);
Self.A := A;
Self.B := B;
Self.C := C;
end;
{ TCompoundEqualityComparer<TypeA, TypeB> }
constructor TCompoundEqualityComparer<TypeA, TypeB>.Create(
ComparerA: IEqualityComparer<TypeA>;
ComparerB: IEqualityComparer<TypeB>);
begin
FComparerA := ComparerA;
FComparerB := ComparerB;
if FComparerA=nil then
FComparerA := TComparerUtils.DefaultEqualityComparer<TypeA>;
if FComparerB=nil then
FComparerB := TComparerUtils.DefaultEqualityComparer<TypeB>;
end;
class function TCompoundEqualityComparer<TypeA, TypeB>.Default: IEqualityComparer<TCompound<TypeA, TypeB>>;
var
A,B: PTypeInfo;
begin
if FOrdinalComparer=nil then
begin
A := TypeInfo(TypeA);
if (A<>nil) and (A.Kind in RecordTypes) then
begin
B := TypeInfo(TypeB);
if (B<>nil) and (B.Kind in RecordTypes) then
Exit(inherited Default);
end;
FOrdinalComparer := TCompoundEqualityComparer<TypeA, TypeB>.Create(nil, nil);
end;
result := FOrdinalComparer;
end;
function TCompoundEqualityComparer<TypeA, TypeB>.Equals(const Left,Right: TCompound<TypeA, TypeB>): Boolean;
begin
result :=
FComparerA.Equals(Left.A, Right.A) and
FComparerB.Equals(Left.B, Right.B);
end;
function TCompoundEqualityComparer<TypeA, TypeB>.GetHashCode(const Value: TCompound<TypeA, TypeB>): Integer;
begin
result := TDigests.Mix(FComparerA.GetHashCode(Value.A), FComparerB.GetHashCode(Value.B));
end;
{ TCompoundEqualityComparer<TypeA, TypeB, TypeC> }
constructor TCompoundEqualityComparer<TypeA, TypeB, TypeC>.Create(
ComparerA: IEqualityComparer<TypeA>;
ComparerB: IEqualityComparer<TypeB>;
ComparerC: IEqualityComparer<TypeC>);
begin
FComparerA := ComparerA;
FComparerB := ComparerB;
FComparerC := ComparerC;
if FComparerA=nil then
FComparerA := TComparerUtils.DefaultEqualityComparer<TypeA>;
if FComparerB=nil then
FComparerB := TComparerUtils.DefaultEqualityComparer<TypeB>;
if FComparerC=nil then
FComparerC := TComparerUtils.DefaultEqualityComparer<TypeC>;
end;
class function TCompoundEqualityComparer<TypeA, TypeB, TypeC>.Default: IEqualityComparer<TCompound<TypeA, TypeB, TypeC>>;
var
A,B,C: PTypeInfo;
begin
if FOrdinalComparer=nil then
begin
A := TypeInfo(TypeA);
if (A<>nil) and (A.Kind in RecordTypes) then
begin
B := TypeInfo(TypeB);
if (B<>nil) and (B.Kind in RecordTypes) then
begin
C := TypeInfo(TypeC);
if (C<>nil) and (C.Kind in RecordTypes) then
Exit(inherited Default);
end;
end;
FOrdinalComparer := TCompoundEqualityComparer<TypeA, TypeB, TypeC>.Create(nil, nil, nil);
end;
result := FOrdinalComparer;
end;
function TCompoundEqualityComparer<TypeA, TypeB, TypeC>.Equals(
const Left,Right: TCompound<TypeA, TypeB, TypeC>): Boolean;
begin
result :=
FComparerA.Equals(Left.A, Right.A) and
FComparerB.Equals(Left.B, Right.B) and
FComparerC.Equals(Left.C, Right.C);
end;
function TCompoundEqualityComparer<TypeA, TypeB, TypeC>.GetHashCode(
const Value: TCompound<TypeA, TypeB, TYpeC>): Integer;
begin
result := TDigests.Mix(
FComparerA.GetHashCode(Value.A),
FComparerB.GetHashCode(Value.B),
FComparerC.GetHashCode(Value.C)
);
end;
{ TCompoundComparer<TypeA, TypeB> }
constructor TCompoundComparer<TypeA, TypeB>.Create(ComparerA: IComparer<TypeA>; ComparerB: IComparer<TypeB>);
begin
FComparerA := ComparerA;
FComparerB := ComparerB;
if FComparerA=nil then
FComparerA := TComparerUtils.DefaultComparer<TypeA>;
if FComparerB=nil then
FComparerB := TComparerUtils.DefaultComparer<TypeB>;
end;
class function TCompoundComparer<TypeA, TypeB>.Default: IComparer<TCompound<TypeA, TypeB>>;
var
A,B: PTypeInfo;
begin
if FOrdinalComparer=nil then
begin
A := TypeInfo(TypeA);
if (A<>nil) and (A.Kind in RecordTypes) then
begin
B := TypeInfo(TypeB);
if (B<>nil) and (B.Kind in RecordTypes) then
Exit(inherited Default);
end;
FOrdinalComparer := TCompoundComparer<TypeA, TypeB>.Create(nil, nil);
end;
result := FOrdinalComparer;
end;
function TCompoundComparer<TypeA, TypeB>.Compare(const Left,Right: TCompound<TypeA, TypeB>): Integer;
begin
Result := FComparerA.Compare(Left.A, Right.A);
if Result=0 then
Result := FComparerB.Compare(Left.B, Right.B);
end;
{ TCompoundComparer<TypeA, TypeB, TypeC> }
constructor TCompoundComparer<TypeA, TypeB, TypeC>.Create(
ComparerA: IComparer<TypeA>;
ComparerB: IComparer<TypeB>;
ComparerC: IComparer<TypeC>);
begin
FComparerA := ComparerA;
FComparerB := ComparerB;
FComparerC := ComparerC;
if FComparerA=nil then
FComparerA := TComparerUtils.DefaultComparer<TypeA>;
if FComparerB=nil then
FComparerB := TComparerUtils.DefaultComparer<TypeB>;
if FComparerC=nil then
FComparerC := TComparerUtils.DefaultComparer<TypeC>;
end;
class function TCompoundComparer<TypeA, TypeB, TypeC>.Default: IComparer<TCompound<TypeA, TypeB, TypeC>>;
var
A,B,C: PTypeInfo;
begin
if FOrdinalComparer=nil then
begin
A := TypeInfo(TypeA);
if (A<>nil) and (A.Kind in RecordTypes) then
begin
B := TypeInfo(TypeB);
if (B<>nil) and (B.Kind in RecordTypes) then
begin
C := TypeInfo(TypeC);
if (C<>nil) and (C.Kind in RecordTypes) then
Exit(inherited Default);
end;
end;
FOrdinalComparer := TCompoundComparer<TypeA, TypeB, TypeC>.Create(nil, nil, nil);
end;
result := FOrdinalComparer;
end;
function TCompoundComparer<TypeA, TypeB, TypeC>.Compare(
const Left,Right: TCompound<TypeA, TypeB, TypeC>): Integer;
begin
result := FComparerA.Compare(Left.A, Right.A);
if result=0 then
begin
result := FComparerB.Compare(Left.B, Right.B);
if result=0 then
result := FComparerC.Compare(Left.C, Right.C);
end;
end;
{ TAutoFreeCollection }
procedure TAutoFreeCollection.Init;
begin
Self := Default(TAutoFreeCollection);
end;
class function TAutoFreeCollection.Create: TAutoFreeCollection;
begin
result := Default(TAutoFreeCollection);
end;
procedure TAutoFreeCollection.Clear;
begin
Self := Default(TAutoFreeCollection);
end;
function TAutoFreeCollection.Guard: IAutoFreeCollection;
begin
if FGuard=nil then
FGuard := TAutoFreeCollectionImpl.Create;
result := FGuard;
end;
function TAutoFreeCollection.Add<T>(AObject: T): T;
begin
Guard.Add(AObject);
result := AObject;
end;
function TAutoFreeCollection.Empty: Boolean;
begin
result := Guard.GetCount=0;
end;
function TAutoFreeCollection.Extract(n: integer): TObject;
begin
result := Guard.Extract(n);
end;
function TAutoFreeCollection.ExtractAll: TArray<TObject>;
begin
result := Guard.ExtractAll;
end;
function TAutoFreeCollection.GetCount: integer;
begin
result := Guard.GetCount;
end;
function TAutoFreeCollection.GetItem(n: integer): TObject;
begin
result := Guard.GetItem(n);
end;
{ TAutoFreeCollection.TAutoFreeCollectionImpl }
constructor TAutoFreeCollection.TAutoFreeCollectionImpl.Create;
begin
inherited Create;
FList := TObjectList<TObject>.Create(True);
end;
destructor TAutoFreeCollection.TAutoFreeCollectionImpl.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
function TAutoFreeCollection.TAutoFreeCollectionImpl.Extract(n: integer): TObject;
begin
FList.OwnsObjects := False;
try
result := FList[n];
FList.Delete(n);
finally
FList.OwnsObjects := True;
end;
end;
function TAutoFreeCollection.TAutoFreeCollectionImpl.ExtractAll: TArray<TObject>;
var I: integer;
begin
FList.OwnsObjects := False;
try
SetLength(result, FList.Count);
for I := 0 to FList.Count-1 do
result[I] := FList[I];
FList.Clear;
finally
FList.OwnsObjects := True;
end;
end;
procedure TAutoFreeCollection.TAutoFreeCollectionImpl.Add(AObject: TObject);
begin
FList.Add(AObject);
end;
function TAutoFreeCollection.TAutoFreeCollectionImpl.GetCount: integer;
begin
result := FList.Count;
end;
function TAutoFreeCollection.TAutoFreeCollectionImpl.GetItem(n: integer): TObject;
begin
result := FList[n];
end;
{ TComparerUtils }
class function TComparerUtils.Compare(const Left, Right: integer): integer;
begin
if Left < Right then result := -1 else
if Left > Right then result := 1 else
result := 0;
end;
class function TComparerUtils.Compare(const Left, Right: double): integer;
begin
if Left < Right then result := -1 else
if Left > Right then result := 1 else
result := 0;
end;
class function TComparerUtils.Compare(const Left, Right: boolean): integer;
begin
if Left then
if Right
then result := 0
else result := 1
else
if Right
then result := -1
else result := 0;
end;
class function TComparerUtils.Compare<T>(const Left, Right: TArray<T>; ItemComparer: IComparer<T>): integer;
var
I: Integer;
begin
result := Length(Left) - Length(Right);
for I := 0 to Length(Left)-1 do
if result = 0
then result := ItemComparer.Compare(Left[I], Right[I])
else Break;
end;
class function TComparerUtils.Compare<T>(const Left, Right: TList<T>; ItemComparer: IComparer<T>): integer;
var
I: Integer;
begin
if Left = Right then result := 0 else
if Left = nil then result := -1 else
if Right = nil then result := 1 else
begin
result := Left.Count - Right.Count;
for I := 0 to Left.Count-1 do
if result = 0
then result := ItemComparer.Compare(Left[I], Right[I])
else Break;
end;
end;
class function TComparerUtils.Compare(const Left, Right: string; CaseInsensitive: boolean = True): integer;
begin
if CaseInsensitive
then result := CompareText(Left, Right)
else result := CompareStr(Left, Right);
end;
class function TComparerUtils.CompoundComparer<A, B, C>: IComparer<TCompound<A, B, C>>;
begin
result := TCompoundComparer<A,B,C>.Default;
end;
class function TComparerUtils.CompoundComparer<A, B>: IComparer<TCompound<A, B>>;
begin
result := TCompoundComparer<A,B>.Default;
end;
class function TComparerUtils.CompoundEqualityComparer<A, B, C>: IEqualityComparer<TCompound<A, B, C>>;
begin
result := TCompoundEqualityComparer<A,B,C>.Default;
end;
class function TComparerUtils.CompoundEqualityComparer<A, B>: IEqualityComparer<TCompound<A, B>>;
begin
result := TCompoundEqualityComparer<A,B>.Default;
end;
class function TComparerUtils.DefaultArithmetic<T>: IArithmetic<T>;
begin
result := TArithmeticUtils<T>.DefaultArithmetic;
end;
class function TComparerUtils.DefaultComparer<T>: IComparer<T>;
begin
if TypeInfo(T) = TypeInfo(string) then
result := IComparer<T>( IComparer<string>(TIStringComparer.Ordinal) )
else
if TypeInfo(T) = TypeInfo(TRange) then
result := IComparer<T>( IComparer<TRange>(TRangeComparer.Ordinal) )
else
result := TComparer<T>.Default;
end;
class function TComparerUtils.DefaultEqualityComparer<T>: IEqualityComparer<T>;
begin
if TypeInfo(T) = TypeInfo(string) then
result := IEqualityComparer<T>( IEqualityComparer<string>(TIStringComparer.Ordinal) )
{ default equality comparer is ok for TRange
else
if TypeInfo(T) = TypeInfo(TRange) then
result := IEqualityComparer<T>( IEqualityComparer<TRange>(TRangeComparer.Ordinal) )}
else
result := TEqualityComparer<T>.Default;
end;
class function TComparerUtils.Equal<T>(A: TEnumerable<T>; const B: TArray<T>): boolean;
begin
result := Equal<T>(A, B, DefaultComparer<T>);
end;
class function TComparerUtils.Equal<T>(A: TEnumerable<T>; const B: TArray<T>; Comparer: IComparer<T>): boolean;
var
Enum: TEnumerator<T>;
I: Integer;
begin
result := True;
Enum := A.GetEnumerator;
for I := Low(B) to High(B) do
begin
result := Enum.MoveNext and (Comparer.Compare(Enum.Current, B[I]) = 0);
if not result then
Break;
end;
if result then
result := not Enum.MoveNext;
Sys.FreeAndNil(Enum);
end;
class function TComparerUtils.Equal<T>(A, B: TEnumerable<T>): boolean;
begin
result := Equal<T>(A,B, DefaultComparer<T>);
end;
class function TComparerUtils.Equal<T>(A, B: TEnumerable<T>; Comparer: IComparer<T>): boolean;
var
EnumA, EnumB: TEnumerator<T>;
begin
EnumA := A.GetEnumerator;
EnumB := B.GetEnumerator;
while True do
if EnumA.MoveNext then
if EnumB.MoveNext and (Comparer.Compare(EnumA.Current, EnumB.Current) = 0) then
Continue
else
begin
result := False;
Break;
end
else
begin
result := not EnumB.MoveNext;
Break;
end;
Sys.FreeAndNil(EnumA);
Sys.FreeAndNil(EnumB);
end;
{ TRange }
procedure TRange.Init(AValueMin, AValueMax: integer);
begin
Self := Default(TRange);
if AValueMin <= AValueMax then
begin
ValueMin := AValueMin;
ValueMax := AValueMax;
end
else
begin
ValueMin := AValueMax;
ValueMax := AValueMin;
end;
end;
procedure TRange.Add(AValueMin, AValueMax: integer);
begin
if AValueMin <= AValueMax then
begin
ValueMin := Min(ValueMin, AValueMin);
ValueMax := Max(ValueMax, AValueMax);
end
else
begin
ValueMin := Min(ValueMin, AValueMax);
ValueMax := Max(ValueMax, AValueMin);
end
end;
procedure TRange.AddOrSet(AValueMin, AValueMax: integer);
begin
if Empty
then Init(AValueMin, AValueMax)
else Add(AValueMin, AValueMax);
end;
procedure TRange.Clear;
begin
Self := Default(TRange);
dec(FValueMax);
end;
function TRange.GetEmpty: boolean;
begin
result := ValueMax < ValueMin;
end;
function TRange.GetEnumerator: TEnumerator;
begin
result := TEnumerator.Create(Self);
end;
function TRange.GetLength: integer;
begin
if ValueMax >= ValueMin then
result := ValueMax-ValueMin+1
else
result := 0;
end;
function TRange.GetAsString: string;
begin
result := format('[%d,%d]', [ValueMin,ValueMax]);
end;
procedure TRange.SetAsString(const Value: string);
var
a,b,c,i,j: integer;
begin
a := Value.IndexOf('[');
if a >= 0 then
begin
b := Value.IndexOf(',', a);
if b >= 0 then
begin
c := Value.IndexOf(']', b);
if (c >= 0) and TryStrToInt(Value.Substring(a+1,b-a-1), i) and TryStrToInt(Value.Substring(b,c-b-1), j) then
begin
Init(i, j);
Exit;
end;
end;
end;
Clear;
end;
class operator TRange.Inc(const a: TRange): TRange;
begin
result.Init(a.ValueMin+1, a.ValueMax+1);
end;
class operator TRange.Dec(const a: TRange): TRange;
begin
result.Init(a.ValueMin-1, a.ValueMax-1);
end;
class operator TRange.Add(const a, b: TRange): TRange;
begin
result.Init(Min(a.ValueMin, b.ValueMin), Max(a.ValueMax, b.ValueMax));
end;
class operator TRange.LogicalAnd(const a, b: TRange): TRange;
begin
{ [...XXX]
[XXX...] -> [XXX] }
if a.Overlaps(b) then
result.Init(Max(a.ValueMin, b.ValueMin), Min(a.ValueMax, b.ValueMax))
else
result.Clear;
end;
class operator TRange.LogicalOr(const a, b: TRange): TRange;
begin
{ [...XXX]
[XXX...] -> [...XXX...]
If a and b are overlapped, then A or B = A + B, otherwise A or B = empty unlike A + B }
if a.Overlaps(b) then
result.Init(Min(a.ValueMin, b.ValueMin), Max(a.ValueMax, b.ValueMax))
else
result.Clear;
end;
function TRange.Overlaps(const a: TRange): boolean;
begin
result := (ValueMin <= a.ValueMax) and (a.ValueMin <= ValueMax);
end;
class operator TRange.In(const a: TRange; b: TRange): Boolean;
begin
result := (a.ValueMin >= b.ValueMin) and (a.ValueMax <= b.ValueMax);
end;
class operator TRange.In(const a: integer; b: TRange): Boolean;
begin
result := (a >= b.ValueMin) and (a <= b.ValueMax);
end;
class operator TRange.Equal(const a, b: TRange): Boolean;
begin
result := (a.ValueMin=b.ValueMin) and (a.ValueMax=b.ValueMax);
end;
class operator TRange.NotEqual(const a, b: TRange): Boolean;
begin
result := not (a=b);
end;
class operator TRange.LessThan(const a, b: TRange): Boolean;
begin
if a.ValueMin < b.ValueMin then
result := True
else
if a.ValueMin > b.ValueMin then
result := False
else
result := a.Length < b.Length;
end;
class operator TRange.GreaterThanOrEqual(const a, b: TRange): Boolean;
begin
result := not (a < b);
end;
class operator TRange.GreaterThan(const a, b: TRange): Boolean;
begin
if a.ValueMin > b.ValueMin then
result := True
else
if a.ValueMin < b.ValueMin then
result := False
else
result := a.Length > b.Length;
end;
class operator TRange.LessThanOrEqual(const a, b: TRange): Boolean;
begin
result := not (a > b);
end;
{ TRange.TEnumerator }
constructor TRange.TEnumerator.Create(const R: TRange);
begin
FCurValue := R.ValueMin;
FMaxValue := R.ValueMax;
end;
function TRange.TEnumerator.MoveNext: boolean;
begin
result := FCurValue <= FMaxValue;
if result then
inc(FCurValue);
end;
function TRange.TEnumerator.GetCurrentValue: integer;
begin
result := FCurValue-1;
end;
{ TRangeEnumerator }
procedure TRangeEnumerator.Init(Src: TArray<integer>);
begin
Self := Default(TRangeEnumerator);
Self.Src := Src;
TArray.Sort<integer>(Self.Src);
end;
function TRangeEnumerator.MoveNext: boolean;
var
L: Integer;
begin
L := Length(Src);
result := Cur < L;
if result then
repeat
inc(Cur);
until (Cur >= L) or (Src[Cur] <> Src[Cur-1]+1);
end;
function TRangeEnumerator.GetCurrent: TRange;
var
I: integer;
begin
I := Cur-1;
while (I > 0) and (Src[I]=Src[I-1]+1) do
dec(I);
result.Init(Src[I], Src[Cur-1]);
end;
{ TRangeEnumerable }
procedure TRangeEnumerable.Init(Src: TArray<integer>);
begin
Self := Default(TRangeEnumerable);
Self.Src := Src;
end;
function TRangeEnumerable.GetEnumerator: TRangeEnumerator;
begin
result.Init(Src);
end;
{ TRangeComparer }
class function TRangeComparer.Ordinal: IComparer<TRange>;
begin
if FOrdinalComparer = nil then
FOrdinalComparer := TRangeComparer.Create;
end;
function TRangeComparer.Compare(const Left, Right: TRange): Integer;
begin
if Left < Right then
result := -1
else
if Left = Right then
result := 0
else
result := 1;
end;
{ TSingletonConstr<T> }
class destructor TSingletonConstr<T>.DestroyClass;
begin
FreeAndNil(FOrdinal);
end;
class function TSingletonConstr<T>.Ordinal: T;
begin
if FOrdinal = nil then
FOrdinal := CreateInstance;
result := FOrdinal;
end;
class procedure TSingletonConstr<T>.SetOrdinal(const Value: T);
begin
if Value = FOrdinal then
Exit;
FreeAndNil(FOrdinal);
FOrdinal := Value;
end;
{ TSingleton<T> }
class function TSingleton<T>.CreateInstance: T;
begin
result := T.Create;
end;
{ TIndexBackEnumerator }
procedure TIndexBackEnumerator.Init(AIndexFrom, AIndexTo: integer);
begin
Self := Default(TIndexBackEnumerator);
FCurrentIndex := AIndexFrom;
FToIndex := AIndexTo;
end;
function TIndexBackEnumerator.MoveNext: Boolean;
begin
result := FCurrentIndex>=FToIndex;
if result then
dec(FCurrentIndex);
end;
function TIndexBackEnumerator.GetCurrent: Integer;
begin
result := FCurrentIndex+1;
end;
end.
|
unit UnMovimentoDeCaixaListaRegistrosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvButton, JvTransparentButton, ExtCtrls, Grids,
DBGrids, StdCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit,
JvCheckedMaskEdit, JvDatePickerEdit,
{ helsonsant }
Util, DataUtil, UnModelo, Componentes, UnAplicacao,
UnMovimentoDeCaixaListaRegistrosModelo, JvExDBGrids, JvDBGrid,
JvDBUltimGrid, Data.DB;
type
TMovimentoDeCaixaListaRegistrosView = class(TForm, ITela)
Panel1: TPanel;
btnIncluir: TJvTransparentButton;
btnImprimir: TJvTransparentButton;
pnlFiltro: TPanel;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
txtInicio: TJvDatePickerEdit;
txtFim: TJvDatePickerEdit;
GroupBox2: TGroupBox;
EdtFiltro: TEdit;
gMovimentos: TJvDBUltimGrid;
procedure btnIncluirClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure gMovimentosDblClick(Sender: TObject);
private
FControlador: IResposta;
FMovimentoDeCaixaListaRegistrosModelo: TMovimentoDeCaixaListaRegistrosModelo;
public
function Descarregar: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
published
procedure FiltrarLancamentos(Sender: TObject);
end;
var
MovimentoDeCaixaListaRegistrosView: TMovimentoDeCaixaListaRegistrosView;
implementation
{$R *.dfm}
{ TMovimentoDeCaixaListaRegistrosView }
function TMovimentoDeCaixaListaRegistrosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TMovimentoDeCaixaListaRegistrosView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FMovimentoDeCaixaListaRegistrosModelo := nil;
Result := Self;
end;
function TMovimentoDeCaixaListaRegistrosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
procedure TMovimentoDeCaixaListaRegistrosView.FiltrarLancamentos(
Sender: TObject);
begin
Self.FMovimentoDeCaixaListaRegistrosModelo.CarregarRegistros(
Self.txtInicio.Date, Self.txtFim.Date, Self.EdtFiltro.Text);
end;
function TMovimentoDeCaixaListaRegistrosView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FMovimentoDeCaixaListaRegistrosModelo :=
(Modelo as TMovimentoDeCaixaListaRegistrosModelo);
Result := Self;
end;
function TMovimentoDeCaixaListaRegistrosView.Preparar: ITela;
begin
Self.gMovimentos.DataSource :=
Self.FMovimentoDeCaixaListaRegistrosModelo.DataSource;
Self.txtInicio.Date := Date - 7;
Self.txtFim.Date := Date;
Self.FMovimentoDeCaixaListaRegistrosModelo
.CarregarRegistros(Self.txtInicio.Date, Self.txtFim.Date,
Self.EdtFiltro.Text);
Result := Self;
end;
procedure TMovimentoDeCaixaListaRegistrosView.btnIncluirClick(
Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FMovimentoDeCaixaListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', Ord(adrIncluir));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TMovimentoDeCaixaListaRegistrosView.btnImprimirClick(
Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FMovimentoDeCaixaListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', Ord(adrOutra))
.Gravar('inicio', Self.txtInicio.Text)
.Gravar('fim', Self.txtFim.Text)
.Gravar('modelo',
Self.FMovimentoDeCaixaListaRegistrosModelo);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TMovimentoDeCaixaListaRegistrosView.gMovimentosDblClick(
Sender: TObject);
var
_parametros: TMap;
_chamada: TChamada;
_modelo: TModelo;
begin
_modelo := Self.FMovimentoDeCaixaListaRegistrosModelo;
_parametros := _modelo.Parametros;
_parametros
.Gravar('acao', Ord(adrCarregar))
.Gravar('oid', _modelo.DataSet.FieldByName('cxmv_oid').AsString);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Base Model algorithm classes }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.Algorithm.Model;
interface
uses
System.Classes, BI.Arrays, BI.DataItem, BI.Algorithm, BI.Tools;
type
TModelClass=class of TModel;
TModels=Array of TModelClass;
TModelsHelper=record helper for TModels
public
function Count:Integer; inline;
function Exists(const AModel:TModelClass):Boolean; inline;
function IndexOf(const AModel:TModelClass):Integer;
procedure Register(const AModel:TModelClass); overload;
procedure Register(const AModels:Array of TModelClass); overload;
procedure UnRegister(const AModel:TModelClass); overload;
procedure UnRegister(const AModels:Array of TModelClass); overload;
end;
// Base class for machine-learning algorithms that require a "Target"
// (or "Class" or "Label") data
TModel=class(TBaseAlgorithm)
public
class var
Models : TModels;
Constructor Create(AOwner:TComponent); override;
class function Description:String;
end;
// Special TDataItem containing 3 columns:
// 0 : The index position in the original source data
// 1 : The "real" value (Target) in the original source data
// 2 : The "predicted" value calculated by the algorithm
TPredictedData=class(TDataItem)
private
FConfusion : TDataItem;
FPredicted : TDataItem;
FReal : TDataItem;
procedure AddItems(const AMap:TTextMap);
procedure CheckNeeds(const A,B:TDataItem);
procedure Fill(const AMap:TTextMap; const A,B:TDataItem);
function GetConfusion:TDataItem;
function GetCorrect:TInteger;
public
class var
ConfusionClass : TBaseAlgorithmClass;
Constructor Create(const ATarget:TDataItem; const Indices:TNativeIntArray);
Destructor Destroy; override;
function IsEqual(const AIndex: TInteger):Boolean;
property Confusion:TDataItem read GetConfusion;
property Correct:TInteger read GetCorrect;
property Predicted:TDataItem read FPredicted;
property Real:TDataItem read FReal;
end;
TModelSplit=class(TPersistent)
private
IProvider : TDataProvider;
procedure Changed;
function GetBy: TSplitBy;
function GetCount: Integer;
function GetMode: TSplitMode;
function GetPercent: Single;
function IsPercentStored: Boolean;
procedure SetBy(const Value: TSplitBy);
procedure SetCount(const Value: Integer);
procedure SetMode(const Value: TSplitMode);
procedure SetPercent(const Value: Single);
public
Split : TSplitOptions;
Constructor Create(const AProvider:TDataProvider);
procedure Assign(Source:TPersistent); override;
published
property By:TSplitBy read GetBy write SetBy default TSplitBy.Percent;
property Count: Integer read GetCount write SetCount default 0;
property Mode:TSplitMode read GetMode write SetMode default TSplitMode.Random;
property Percent:Single read GetPercent write SetPercent stored IsPercentStored;
end;
// Model class supporting "train" and "test" of an algorithm
TSupervisedModel=class(TModel)
private
FNormalize : Boolean;
FSplit : TModelSplit;
function GetAttributes: TDataArray;
function GetTarget: TDataItem;
procedure SetAttributes(const Value: TDataArray);
procedure SetNormalize(const Value: Boolean);
procedure SetSplit(const Value:TModelSplit);
procedure SetTarget(const Value: TDataItem);
protected
FPredicted : TPredictedData;
procedure AddOutput(const AData:TDataItem); override;
function GetPredicted:TPredictedData;
public
Indices : TDataSplit;
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
// procedure Assign
procedure Calculate; override;
property Predicted:TPredictedData read GetPredicted;
published
property Attributes:TDataArray read GetAttributes write SetAttributes;
property Normalize:Boolean read FNormalize write SetNormalize default False;
property Split:TModelSplit read FSplit write SetSplit;
property Target:TDataItem read GetTarget write SetTarget;
end;
TSupervisedModelClass=class of TSupervisedModel;
// Base class for interfaces to frameworks like R and Python
TBIPlugin=class
public
class function ConvertToNumeric(const AData:TDataItem; out ANew:TDataItem):Boolean; static;
class function DataToVector(const Indices:TNativeIntArray; const AData:TDataItem;
const UseMissing:Boolean=True;
const MissingValue:String=''):String; static;
end;
implementation
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConfig.ListControlFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.ListBox, FMX.Layouts, RSConfig.ConfigDM;
type
TListControlFrame = class(TFrame)
Layout1: TLayout;
AddButton: TButton;
RemoveButton: TButton;
Layout2: TLayout;
DownButton: TButton;
UpButton: TButton;
HelpButton: TButton;
procedure AddButtonClick(Sender: TObject);
procedure RemoveButtonClick(Sender: TObject);
procedure DownButtonClick(Sender: TObject);
procedure UpButtonClick(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
private
{ Private declarations }
FFrameType: Integer;
FVertScrollBox: TVertScrollBox;
FListBox: TListBox;
FCallback: TNotifyEvent;
public
{ Public declarations }
function GetFrameType: Integer;
procedure SetFrameType(AFrameType: Integer);
procedure SetVertScrollBox(AVertScrollBox: TVertScrollBox);
procedure SetListBox(AListBox: TListBox);
procedure SetCallback(ACallback: TNotifyEvent);
end;
implementation
{$R *.fmx}
uses
RSConsole.FormConfig, RSConfig.NameValueFrame, RSConfig.Consts;
procedure TListControlFrame.DownButtonClick(Sender: TObject);
begin
if FListBox.Items.Count > FListBox.ItemIndex + 1 then
begin
FListBox.ItemsExchange(FListBox.ListItems[FListBox.ItemIndex],
FListBox.ListItems[FListBox.ItemIndex + 1]);
ConfigDM.RenumberListItems(FListBox);
end;
end;
function TListControlFrame.GetFrameType: Integer;
begin
Result := FFrameType;
end;
procedure TListControlFrame.HelpButtonClick(Sender: TObject);
begin
ConfigDM.ShowHelp(Sender);
end;
procedure TListControlFrame.RemoveButtonClick(Sender: TObject);
begin
if FListBox.ItemIndex > -1 then
begin
FListBox.Items.Delete(FListBox.ItemIndex);
ConfigDM.RenumberListItems(FListBox);
end;
end;
procedure TListControlFrame.SetFrameType(AFrameType: Integer);
begin
FFrameType := AFrameType;
end;
procedure TListControlFrame.AddButtonClick(Sender: TObject);
begin
ConfigDM.AddSectionListItem(True, '', '', FListBox, FCallback);
end;
procedure TListControlFrame.SetVertScrollBox(AVertScrollBox: TVertScrollBox);
begin
FVertScrollBox := AVertScrollBox;
end;
procedure TListControlFrame.UpButtonClick(Sender: TObject);
begin
if FListBox.ItemIndex > 0 then
begin
FListBox.ItemsExchange(FListBox.ListItems[FListBox.ItemIndex],
FListBox.ListItems[FListBox.ItemIndex - 1]);
ConfigDM.RenumberListItems(FListBox);
end
end;
procedure TListControlFrame.SetListBox(AListBox: TListBox);
begin
FListBox := AListBox;
end;
procedure TListControlFrame.SetCallback(ACallback: TNotifyEvent);
begin
FCallback := ACallback;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.RequestTypes;
{$SCOPEDENUMS ON}
interface
uses System.Classes, System.SysUtils, System.Generics.Collections;
type
TEMSHostMethodType = (Put, Get, Post, Head, Delete, Patch);
TStringKeyValue = TPair<string, string>;
TStringKeyValues = TArray<TPair<string, string>>;
IEMSHostRequest = interface
function GetContentType: string;
function GetMethodType: TEMSHostMethodType;
function GetPathInfo: string;
function GetQueryFields: TStringKeyValues;
function GetRawContent: TBytes;
function GetMethod: string;
function GetContentLength: Integer;
function GetHeader(const AName: string): string;
function GetBasePath: string;
function GetServerHost: string;
property ContentLength: Integer read GetContentLength;
property ContentType: string read GetContentType;
property MethodType: TEMSHostMethodType read GetMethodType;
property PathInfo: string read GetPathInfo;
property QueryFields: TStringKeyValues read GetQueryFields;
property RawContent: TBytes read GetRawContent;
property Method: string read GetMethod;
property Headers[const I: string]: string read GetHeader;
end;
IEMSHostRequestLocation = interface
['{819E8684-3455-4B8A-AE31-AE708132362E}']
function MakeAbsoluteLocation(const ALocation: string): string;
end;
TEMSHostRequest = class abstract(TInterfacedObject, IEMSHostRequest)
public type
TMethodType = TEMSHostMethodType;
protected
function GetContentType: string; virtual; abstract;
function GetMethodType: TMethodType; virtual; abstract;
function GetPathInfo: string; virtual; abstract;
function GetQueryFields: TStringKeyValues; virtual; abstract;
function GetRawContent: TBytes; virtual; abstract;
function GetMethod: string; virtual;
function GetContentLength: Integer; virtual; abstract;
function GetHeader(const AName: string): string; virtual; abstract;
function GetBasePath: string; virtual; abstract;
function GetServerHost: string; virtual; abstract;
end;
IEMSHostResponse = interface
function GetContentStream: TStream;
function GetContentType: string;
function GetStatusCode: Integer;
function GetReasonString: string;
procedure SetContentStream(const Value: TStream);
procedure SetStatusCode(const Value: Integer);
function GetRequest: IEMSHostRequest;
procedure SetContentType(const Value: string);
property ContentType: string read GetContentType write SetContentType;
property StatusCode: Integer read GetStatusCode write SetStatusCode;
property ContentStream: TStream read GetContentStream write SetContentStream;
property Request: IEMSHostRequest read GetRequest;
property ReasonString: string read GetReasonString;
end;
IEMSHostResponseLocation = interface
['{4DDEEE38-32B8-44A0-9F0E-FF16E2C4A4CA}']
procedure SetLocation(const Value: string);
property Location: string write SetLocation;
end;
IEMSHostResponseHeaders = interface
['{7364E7ED-7C27-4319-9855-11F24ACB3A77}']
function GetHeader(const AName: string): string;
procedure SetHeader(const AName, AValue: string);
end;
TEMSHostResponse = class abstract(TInterfacedObject, IEMSHostResponse)
protected
function GetContentStream: TStream; virtual; abstract;
function GetContentType: string; virtual; abstract;
function GetStatusCode: Integer; virtual; abstract;
procedure SetContentStream(const Value: TStream); virtual; abstract;
procedure SetStatusCode(const Value: Integer); virtual; abstract;
function GetRequest: IEMSHostRequest; virtual; abstract;
procedure SetContentType(const Value: string); virtual; abstract;
function GetReasonString: string; virtual;
end;
IEMSHostContext = interface
end;
IEMSEdgeHostContext = interface(IEMSHostContext)
['{4BF0A003-61EE-4196-8D6E-DBC9ACA579B3}']
function GetModuleName: string;
function GetModuleVersion: string;
function GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>;
function UserIDOfSession(const ASessionToken: string; out AUserID: string): Boolean;
function UserNameOfID(const AUserID: string; out AUserName: string): Boolean;
function GetTenantNameByTenantId(const ATenantId: string): string;
property ModuleName: string read GetModuleName;
property ModuleVersion: string read GetModuleVersion;
end;
TEMSEdgeHostContext = class(TInterfacedObject, IEMSHostContext, IEMSEdgeHostContext)
protected
function GetModuleName: string; virtual; abstract;
function GetModuleVersion: string; virtual; abstract;
function GetGroupsByUser(const AUserID, ATenantId: string): TArray<string>; virtual; abstract;
function UserIDOfSession(const ASessionID: string; out AUserID: string): Boolean; virtual; abstract;
function UserNameOfID(const AUserID: string; out AUserName: string): Boolean; virtual; abstract;
function GetTenantNameByTenantId(const ATenantId: string): string; virtual; abstract;
end;
implementation
{ TEMSHostRequest }
function TEMSHostRequest.GetMethod: string;
begin
case GetMethodType of
TEMSHostMethodType.Put: Result := 'PUT'; // do not localize
TEMSHostMethodType.Get: Result := 'GET'; // do not localize
TEMSHostMethodType.Post: Result := 'POST'; // do not localize
TEMSHostMethodType.Head: Result := 'HEAD'; // do not localize
TEMSHostMethodType.Delete: Result := 'DELETE'; // do not localize
TEMSHostMethodType.Patch: Result := 'PATCH'; // do not localize
else
Assert(False); // unexpected case
end;
end;
{ TEMSHostResponse }
function TEMSHostResponse.GetReasonString: string;
begin
if GetStatusCode >= 300 then
Result := 'Error' // do not localize
else
Result := 'OK'; // do not localize
end;
end.
|
unit U_VECTOR_LIEN_INFO;
interface
uses Classes, SysUtils, Graphics, Windows, GDIPAPI, GDIPOBJ, Math, Dialogs, System.Types;
const
/// <summary>
/// 选择线的颜色
/// </summary>
C_COLOR_SELECT = $00FF0080;
C_COLOR_A = $0000E3E3;
C_COLOR_B = $00009B00;
C_COLOR_C = $000000B7;
type
/// <summary>
/// 向量类型
/// </summary>
TVECTOR_TYPE = ( vtVol, // 电压
vtCurrent // 电流
);
/// <summary>
/// 将自定义Vtype转换成字符串
/// </summary>
function GetVTStr(AVT : TVECTOR_TYPE) : string;
function SetVTType(sStr : string):TVECTOR_TYPE;
function GetVTAllStr : string;
/// <summary>
/// 判断点是否在两点之间
/// </summary>
function IsInArea(APoint: TPoint; APoint1,APoint2 : TGPPointF): Boolean;
type
/// <summary>
/// 向量信息
/// </summary>
TVECTOR_LIEN_INFO = class
private
FVAngle: Double;
FVID: Integer;
FVValue: Double;
FVType: TVECTOR_TYPE;
FIsSelected: Boolean;
FVColor: TColor;
FOnChange: TNotifyEvent;
FCenterPoint: TPoint;
FScale: Double;
FVName: string;
FCanvas: TCanvas;
FIsDrawPoint: Boolean;
FIsMainSelect: Boolean;
FIsOver: Boolean;
procedure SetIsSelected(const Value: Boolean);
/// <summary>
/// 获取终点
/// </summary>
function GetLastPoint : TGPPointF;
function GetTextPoint : TGPPointF;
function GetVTypeStr: string;
procedure SetVTypeStr(const Value: string);
procedure SetVAngle(const Value: Double);
public
constructor Create;
procedure Assign(Source: TVECTOR_LIEN_INFO);
/// <summary>
/// 向量ID
/// </summary>
property VID : Integer read FVID write FVID;
/// <summary>
/// 向量名称
/// </summary>
property VName : string read FVName write FVName;
/// <summary>
/// 向量类型
/// </summary>
property VType : TVECTOR_TYPE read FVType write FVType;
/// <summary>
/// 向量类型 字符串形式
/// </summary>
property VTypeStr : string read GetVTypeStr write SetVTypeStr;
/// <summary>
/// 向量颜色
/// </summary>
property VColor : TColor read FVColor write FVColor;
/// <summary>
/// 向量值 填写电压电流值
/// </summary>
property VValue : Double read FVValue write FVValue;
/// <summary>
/// 基本定压电流值
/// </summary>
function GetBaseValue : Integer;
/// <summary>
/// 角度 原点水平向右为零度,上移为正角度
/// </summary>
property VAngle : Double read FVAngle write SetVAngle;
/// <summary>
/// 是否被选中
/// </summary>
property IsSelected : Boolean read FIsSelected write SetIsSelected;
/// <summary>
/// 是否选择的是主向量
/// </summary>
property IsMainSelect : Boolean read FIsMainSelect write FIsMainSelect;
/// <summary>
/// 鼠标是否在上面
/// </summary>
property IsOver : Boolean read FIsOver write FIsOver;
/// <summary>
/// 改变事件
/// </summary>
property OnChange : TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// 原点
/// </summary>
property CenterPoint : TPoint read FCenterPoint write FCenterPoint;
/// <summary>
/// 比例 默认为1 100%
/// </summary>
property Scale : Double read FScale write FScale;
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 是否画点
/// </summary>
property IsDrawPoint : Boolean read FIsDrawPoint write FIsDrawPoint;
/// <summary>
/// 画图
/// </summary>
procedure Draw;
/// <summary>
/// 点是否在线上
/// </summary>
function IsInLine(APoint: TPoint):Boolean;
end;
implementation
function IsInArea(APoint: TPoint; APoint1,APoint2 : TGPPointF): Boolean;
var
iMaxX, iMinX: Single;
iMaxY, iMinY: Single;
k, b: Real;
begin
iMaxX := Max(APoint1.X, APoint2.X);
iMinX := Min(APoint1.X, APoint2.X);
iMaxY := Max(APoint1.Y, APoint2.Y);
iMinY := Min(APoint1.Y, APoint2.Y);
{ 如果是垂直线 }
if iMaxX - iMinX <= 5 then
begin
Result := (Abs(APoint.X - iMaxX) <= 5) and (APoint.Y >= iMinY)
and (APoint.Y <= iMaxY);
end
{ 如果是水平线 }
else if iMaxY - iMinY <=5 then
begin
Result := (Abs(APoint.Y - iMaxY) <=5 ) and (APoint.X >= iMinX)
and (APoint.X <= iMaxX);
end
{ 根据公式判断 }
else
begin
{ 判断公式为:y = k * x + b 斜率:k = (y2 - y1) / (x2 - x1) y轴截距:b = y1 - k * x1 }
k := (APoint2.Y - APoint1.Y) / (APoint2.X - APoint1.X);
b := APoint1.Y - k * APoint1.X;
Result := (APoint.Y <= round(k * APoint.X + b) + 5) and
(APoint.Y >= round(k * APoint.X + b) - 5);
if Result then
Result := (APoint.X >= iMinX) and (APoint.X <= iMaxX) and
(APoint.Y >= iMinY) and (APoint.Y <= iMaxY);
end;
end;
/// <summary>
/// 将自定义Vtype转换成字符串
/// </summary>
function GetVTStr(AVT : TVECTOR_TYPE) : string;
begin
case AVT of
vtVol: Result := '电压';
vtCurrent: Result := '电流';
end;
end;
function SetVTType(sStr : string):TVECTOR_TYPE;
var
i : TVECTOR_TYPE;
begin
Result := Low(TVECTOR_TYPE);
for i := Low(TVECTOR_TYPE) to High(TVECTOR_TYPE) do
begin
if GetVTStr(i) = sStr then
begin
Result := i;
Break;
end;
end;
end;
function GetVTAllStr : string;
var
i : TVECTOR_TYPE;
begin
for i := Low(TVECTOR_TYPE) to High(TVECTOR_TYPE) do
begin
Result := Result + GetVTStr(i) + #13#10;
end;
end;
{ TVECTOR_LIEN_INFO }
procedure TVECTOR_LIEN_INFO.Assign(Source: TVECTOR_LIEN_INFO);
begin
if Assigned(Source) then
begin
FVName := Source.VName ;
FVType := Source.VType ;
FVColor := Source.VColor ;
FVValue := Source.VValue ;
FVAngle := Source.VAngle ;
FIsDrawPoint := Source.IsDrawPoint;
end;
end;
constructor TVECTOR_LIEN_INFO.Create;
begin
FCenterPoint := Point(0, 0);
FVColor := clRed;
FVValue := 220;
FVAngle := 90;
FVName := '未命名';
FVType := vtVol;
FScale := 1;
FIsDrawPoint := True;
FIsSelected := False;
FIsMainSelect := False;
FIsOver := False;
end;
procedure TVECTOR_LIEN_INFO.Draw;
var
g: TGPGraphics;
p: TGPPen;
ACap : TGPAdjustableArrowCap;
sf: TGPStringFormat;
FontSize : Integer;
// 画字母
procedure DrawLetter;
var
sLastStr : string;
APoint : TGPPointF;
sb : TGPSolidBrush;
font : TGPFont;
begin
sb := TGPSolidBrush.Create(ColorRefToARGB(FVColor));
if Length(FVName) > 0 then
begin
sLastStr := Copy(FVName, 2, Length(FVName)-1);
FontSize := Round(20*Scale);
font := TGPFont.Create('宋体', FontSize, FontStyleRegular, UnitPixel );
// 第一个字符和上面的点
if (FVAngle > 90) and (FVAngle < 270) then
begin
if FIsDrawPoint then
begin
APoint.X := GetTextPoint.X+0.12*FontSize-FontSize*length(sLastStr)*0.35;
APoint.y := GetTextPoint.Y-1.3*FontSize;
g.DrawString('.', 1, font, APoint, sf, sb);
end;
APoint.X := GetTextPoint.X-FontSize*length(sLastStr)*0.35;
APoint.y := GetTextPoint.Y-0.5*FontSize;
g.DrawString(FVName[1], 1, font, APoint,sf, sb);
end
else
begin
if FIsDrawPoint then
begin
APoint.X := GetTextPoint.X+0.12*FontSize;
APoint.y := GetTextPoint.Y-1.3*FontSize;
g.DrawString('.', 1, font, APoint, sb);
end;
APoint.X := GetTextPoint.X;
APoint.y := GetTextPoint.Y-0.5*FontSize;
g.DrawString(FVName[1], -1, font, APoint, sb);
end;
// 除去第一个字符后面字符都是右下标标示
font.Free;
font := TGPFont.Create('宋体', FontSize*0.7, FontStyleRegular, UnitPixel );
if (FVAngle > 90) and (FVAngle < 270) then
begin
APoint.X := GetTextPoint.X-0.1*FontSize;
APoint.y := GetTextPoint.Y-0.25*FontSize;
g.DrawString(sLastStr, -1, font, APoint, sf, sb);
end
else
begin
APoint.X := GetTextPoint.X+ 0.5* FontSize;
APoint.y := GetTextPoint.Y-0.25*FontSize;
g.DrawString(sLastStr, -1, font, APoint , sb);
end;
font.Free;
sb.Free;
end;
end;
begin
if not Assigned(FCanvas) then
Exit;
g := TGPGraphics.Create(FCanvas.Handle);
g.SetSmoothingMode(TSmoothingMode(2));
p := TGPPen.Create(MakeColor(255,0,0), 2);
ACap := TGPAdjustableArrowCap.Create(4,4,False);
p.SetCustomStartCap(ACap);
sf := TGPStringFormat.Create;
sf.SetFormatFlags(StringFormatFlagsDirectionRightToLeft);
// 画字母
DrawLetter;
//画向量
if FIsSelected then
begin
p.SetColor(ColorRefToARGB(C_COLOR_SELECT));
end
else
begin
p.SetColor(ColorRefToARGB(FVColor));
end;
if FIsOver then
p.SetWidth(3)
else
p.SetWidth(2);
g.DrawLine(p, GetLastPoint.X ,GetLastPoint.Y,FCenterPoint.X,FCenterPoint.Y);
g.Free;
p.Free;
ACap.free;
sf.Free;
end;
function TVECTOR_LIEN_INFO.GetBaseValue: Integer;
begin
if FVType = vtCurrent then
Result := 6
else
Result := 220;
end;
function TVECTOR_LIEN_INFO.GetLastPoint: TGPPointF;
begin
Result := MakePoint(FCenterPoint.X + (FVValue/GetBaseValue)*Cos(DegToRad(FVAngle ))*100*FScale,
FCenterPoint.Y - (FVValue/GetBaseValue)*Sin(DegToRad(FVAngle ))*100*FScale);
end;
function TVECTOR_LIEN_INFO.GetTextPoint: TGPPointF;
begin
Result := MakePoint(FCenterPoint.X + (FVValue/GetBaseValue)*Cos(DegToRad(FVAngle ))*110*FScale,
FCenterPoint.Y - (FVValue/GetBaseValue)*Sin(DegToRad(FVAngle ))*100*FScale);
end;
function TVECTOR_LIEN_INFO.GetVTypeStr: string;
begin
Result := GetVTStr(FVType);
end;
function TVECTOR_LIEN_INFO.IsInLine(APoint: TPoint): Boolean;
var
APoint1,APoint2 : TGPPointF;
begin
APoint1.X := CenterPoint.X;
APoint1.Y := CenterPoint.Y;
APoint2 := GetLastPoint;
Result := IsInArea(APoint, APoint1, APoint2);
end;
procedure TVECTOR_LIEN_INFO.SetIsSelected(const Value: Boolean);
begin
FIsSelected := Value;
end;
procedure TVECTOR_LIEN_INFO.SetVAngle(const Value: Double);
function SetValue(dValue : Double) : Double;
begin
if dValue < 0 then
begin
Result := dValue + 360;
if Result < 0 then
Result := SetValue(Result);
end
else
Result := dValue;
end;
function SetValue1(dValue : Double) : Double;
begin
if dValue > 360 then
begin
Result := dValue - 360;
if Result > 360 then
Result := SetValue1(Result)
end
else
Result := dValue;
end;
begin
if Value < 0 then
begin
FVAngle := SetValue(Value);
end
else if Value > 360 then
begin
FVAngle := SetValue1(Value);
end
else
begin
FVAngle := Value;
end;
end;
procedure TVECTOR_LIEN_INFO.SetVTypeStr(const Value: string);
begin
FVType := SetVTType(Value);
end;
end.
|
unit uCmnFunc;
interface
uses
uStruct;
function GetPollingIntervalInMinutes(PollingInterval: TPollingInterval): Integer;
implementation
function GetPollingIntervalInMinutes(PollingInterval: TPollingInterval): Integer;
begin
case PollingInterval of
pi10m:
Result:=10;
pi1h:
Result:=60;
pi5h:
Result:=5 * 60;
pi10h:
Result:=10 * 60;
pi1d:
Result:=24 * 60;
pi1w:
Result:=7 * 24 * 60;
else
Result:=0;
end;
end;
end.
|
unit EditForm;
interface
uses
Winapi.Windows
, Winapi.Messages
, System.SysUtils
, System.Variants
, System.Classes
, Vcl.Graphics
, Vcl.Controls
, Vcl.Forms
, Vcl.Dialogs
, Vcl.Mask
, Vcl.DBCtrls
, Vcl.StdCtrls
, Vcl.ExtCtrls
, Vcl.ComCtrls
, Vcl.Menus
, System.ImageList
, Vcl.ImgList
, SVGIconImageListBase //If don't compile you must before download and installa SVGIconImageList components
, SVGIconVirtualImageList //https://github.com/EtheaDev/SVGIconImageList
, IconFontsImageListBase //If don't compile you must before download and installa IconFontsImageList components
, IconFontsVirtualImageList //https://github.com/EtheaDev/IconFontsImageList
, DImageCollections, Vcl.ToolWin;
type
TFmEdit = class(TForm)
PageControl1: TPageControl;
tsParentFont: TTabSheet;
NameEdit: TEdit;
SurNameEdit: TEdit;
LabeledEdit: TLabeledEdit;
Label1: TLabel;
Label2: TLabel;
tsNoParent: TTabSheet;
Label3: TLabel;
Label4: TLabel;
Edit1: TEdit;
Edit2: TEdit;
LabeledEdit2: TLabeledEdit;
MainMenu: TMainMenu;
File1: TMenuItem;
SettingsMenuitem: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
Print1: TMenuItem;
PrintSetup1: TMenuItem;
Exit1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
IconFontsVirtualImageList: TIconFontsVirtualImageList;
SVGIconVirtualImageList: TSVGIconVirtualImageList;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
procedure FormShow(Sender: TObject);
procedure Exit1Click(Sender: TObject);
private
procedure UpdateFontAttributes;
protected
public
end;
var
FmEdit: TFmEdit;
implementation
{$R *.dfm}
procedure TFmEdit.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TFmEdit.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
begin
if ParentFont and (Application.MainForm.Monitor.Handle <> Self.Monitor.Handle) then
Font.Height := MulDiv(Font.Height, NewDPI, OldDPI);
end;
procedure TFmEdit.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
FmEdit := nil;
end;
procedure TFmEdit.FormShow(Sender: TObject);
begin
if ImageCollectionDataModule.IconsType = itIconFonts then
FmEdit.MainMenu.Images := IconFontsVirtualImageList
else
FmEdit.MainMenu.Images := SVGIconVirtualImageList;
UpdateFontAttributes;
end;
procedure TFmEdit.UpdateFontAttributes;
begin
NameEdit.ParentFont := True;
NameEdit.Font.Style := [fsBold];
SurNameEdit.ParentFont := True;
SurNameEdit.Font.Style := [fsBold];
LabeledEdit.ParentFont := True;
LabeledEdit.Font.Style := [fsBold];
end;
end.
|
unit NtUtils.Shellcode;
interface
uses
Winapi.WinNt, Ntapi.ntpsapi, NtUtils.Exceptions;
const
PROCESS_INJECT_CODE = PROCESS_CREATE_THREAD or PROCESS_VM_OPERATION or
PROCESS_VM_WRITE;
// Copy data & code into the process
function RtlxAllocWriteDataCodeProcess(hProcess: THandle; ParamBuffer: Pointer;
ParamBufferSize: NativeUInt; out Param: TMemory; CodeBuffer: Pointer;
CodeBufferSize: NativeUInt; out Code: TMemory): TNtxStatus;
// Wait for a thread & forward it exit status
function RtlxSyncThreadProcess(hProcess: THandle; hThread: THandle;
StatusLocation: String; Timeout: Int64 = NT_INFINITE): TNtxStatus;
{ Export location }
// Locate export in a known native dll
function RtlxFindKnownDllExportsNative(DllName: String;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
{$IFDEF Win64}
// Locate export in known WoW64 dll
function RtlxFindKnownDllExportsWoW64(DllName: String;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
{$ENDIF}
// Locate export in a known dll
function RtlxFindKnownDllExports(DllName: String; TargetIsWoW64: Boolean;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
implementation
uses
Ntapi.ntstatus, NtUtils.Processes.Memory, NtUtils.Threads,
NtUtils.Ldr, NtUtils.ImageHlp, NtUtils.Sections, NtUtils.Objects;
function RtlxAllocWriteDataCodeProcess(hProcess: THandle; ParamBuffer: Pointer;
ParamBufferSize: NativeUInt; out Param: TMemory; CodeBuffer: Pointer;
CodeBufferSize: NativeUInt; out Code: TMemory): TNtxStatus;
begin
// Copy data into the process
Result := NtxAllocWriteMemoryProcess(hProcess, ParamBuffer, ParamBufferSize,
Param);
if Result.IsSuccess then
begin
// Copy code into the process
Result := NtxAllocWriteExecMemoryProcess(hProcess, CodeBuffer,
CodeBufferSize, Code);
// Undo on failure
if not Result.IsSuccess then
NtxFreeMemoryProcess(hProcess, Param.Address, Param.Size);
end;
end;
function RtlxSyncThreadProcess(hProcess: THandle; hThread: THandle;
StatusLocation: String; Timeout: Int64): TNtxStatus;
var
Info: TThreadBasicInformation;
begin
// Wait for the thread
Result := NtxWaitForSingleObject(hThread, Timeout);
// Make timeouts unsuccessful
if Result.Status = STATUS_TIMEOUT then
Result.Status := STATUS_WAIT_TIMEOUT;
// Get exit status
if Result.IsSuccess then
Result := NtxThread.Query(hThread, ThreadBasicInformation, Info);
// Forward it
if Result.IsSuccess then
begin
Result.Location := StatusLocation;
Result.Status := Info.ExitStatus;
end;
end;
function RtlxFindKnownDllExportsNative(DllName: String;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
var
i: Integer;
DllHandle: HMODULE;
begin
Result := LdrxGetDllHandle(DllName, DllHandle);
if not Result.IsSuccess then
Exit;
SetLength(Addresses, Length(Names));
for i := 0 to High(Names) do
begin
Addresses[i] := LdrxGetProcedureAddress(DllHandle, Names[i], Result);
if not Result.IsSuccess then
Exit;
end;
end;
{$IFDEF Win64}
function RtlxFindKnownDllExportsWoW64(DllName: String;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
var
hxSection: IHandle;
MappedMemory: IMemory;
AllEntries: TArray<TExportEntry>;
pEntry: PExportEntry;
i: Integer;
begin
// Map 32-bit dll
Result := RtlxMapKnownDll(hxSection, DllName, True, MappedMemory);
if not Result.IsSuccess then
Exit;
// Parse its export table
Result := RtlxEnumerateExportImage(MappedMemory.Address,
Cardinal(MappedMemory.Size), True, AllEntries);
if not Result.IsSuccess then
Exit;
SetLength(Addresses, Length(Names));
for i := 0 to High(Names) do
begin
pEntry := RtlxFindExportedName(AllEntries, Names[i]);
if not Assigned(pEntry) or pEntry.Forwards then
begin
Result.Location := 'RtlxpFindKnownDll32Export';
Result.Status := STATUS_PROCEDURE_NOT_FOUND;
Exit;
end;
Addresses[i] := Pointer(NativeUInt(MappedMemory.Address) +
pEntry.VirtualAddress);
end;
end;
{$ENDIF}
function RtlxFindKnownDllExports(DllName: String; TargetIsWoW64: Boolean;
Names: TArray<AnsiString>; out Addresses: TArray<Pointer>): TNtxStatus;
begin
{$IFDEF Win64}
if TargetIsWoW64 then
begin
// Native -> WoW64
Result := RtlxFindKnownDllExportsWoW64(kernel32, Names, Addresses);
Exit;
end;
{$ENDIF}
// Native -> Native / WoW64 -> WoW64
Result := RtlxFindKnownDllExportsNative(kernel32, Names, Addresses);
end;
end.
|
unit u_xpl_custom_message;
{==============================================================================
UnitDesc = xPL Message management object and function
This unit implement strictly conform to specification message
structure
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
0.95 : First Release
1.0 : Now descendant of TxPLHeader
1.5 : Added fControlInput property to override read/write controls needed for OPC
}
{$ifdef fpc}
{$mode objfpc}{$H+}{$M+}
{$endif}
interface
uses classes
, u_xpl_body
, u_xpl_schema
, u_xpl_common
, u_xpl_header
;
type { TxPLCustomMessage =====================================================}
TxPLCustomMessage = class(TxPLHeader, IxPLCommon, IxPLRaw)
private
fBody : TxPLBody;
fTimeStamp : TDateTime;
function Get_RawXPL: string;
function Get_Size: integer;
procedure Set_RawXPL(const AValue: string);
protected
procedure Set_ControlInput(const AValue: boolean); override;
public
constructor Create(const aOwner : TComponent; const aRawxPL : string = ''); reintroduce;
procedure Assign(aMessage : TPersistent); override;
procedure AssignHeader(aMessage : TxPLCustomMessage);
procedure ResetValues; //override;
function IsLifeSign : boolean; inline;
function IsValid : boolean; override;
function MustFragment : boolean;
procedure LoadFromFile(const aFileName : string);
procedure SaveToFile(const aFileName : string);
published
property Body : TxPLBody read fBody ;
property RawXPL : string read Get_RawXPL write Set_RawXPL stored false;
property TimeStamp : TDateTime read fTimeStamp write fTimeStamp;
property Size : integer read Get_Size;
end;
PxPLCustomMessage = ^TxPLCustomMessage;
implementation // =============================================================
Uses SysUtils
, StrUtils
;
// TxPLCustomMessage ==========================================================
constructor TxPLCustomMessage.Create(const aOwner : TComponent; const aRawxPL : string = '');
begin
inherited Create(aOwner);
fBody := TxPLBody.Create(self);
fTimeStamp := now;
if aRawxPL<>'' then RawXPL := aRawXPL;
end;
procedure TxPLCustomMessage.ResetValues;
begin
inherited;
Body.ResetValues;
TimeStamp := 0;
end;
function TxPLCustomMessage.IsLifeSign: boolean;
begin
result := ( MessageType = stat) and
( Schema.IsConfig or Schema.IsHBeat ) and
( Schema.Type_ = 'app' );
end;
procedure TxPLCustomMessage.Assign(aMessage: TPersistent);
begin
if aMessage is TxPLCustomMessage then begin
fBody.Assign(TxPLCustomMessage(aMessage).Body); // Let me do specific part
AssignHeader(TxPLCustomMessage(aMessage));
end else inherited;
end;
procedure TxPLCustomMessage.AssignHeader(aMessage: TxPLCustomMessage);
begin
fTimeStamp := aMessage.TimeStamp;
inherited Assign(aMessage);
end;
function TxPLCustomMessage.Get_RawXPL: string;
begin
result := inherited RawxPL + Body.RawxPL;
end;
function TxPLCustomMessage.Get_Size: integer;
begin
result := length(RawxPL);
end;
function TxPLCustomMessage.IsValid: boolean;
begin
result := (inherited IsValid) and (Body.IsValid);
end;
function TxPLCustomMessage.MustFragment: boolean;
begin
result := (Size > XPL_MAX_MSG_SIZE);
end;
procedure TxPLCustomMessage.Set_RawXPL(const AValue: string);
var LeMessage : string;
HeadEnd, BodyStart, BodyEnd : integer;
begin
LeMessage := AnsiReplaceText(aValue,#13,''); // Delete all CR
HeadEnd := AnsiPos(#10'}',LeMessage) + 1;
BodyStart := Succ(PosEx('{'#10,LeMessage,HeadEnd));
BodyEnd := LastDelimiter('}',LeMessage);
inherited RawxPL := AnsiLeftStr(LeMessage,BodyStart-2);
Body.RawxPL := Copy(LeMessage,BodyStart,BodyEnd-BodyStart);
end;
procedure TxPLCustomMessage.Set_ControlInput(const AValue: boolean);
begin
inherited Set_ControlInput(AValue);
Body.ControlInput := aValue;
end;
procedure TxPLCustomMessage.SaveToFile(const aFileName: string);
begin
StreamObjectToFile(aFileName, self);
end;
procedure TxPLCustomMessage.LoadFromFile(const aFileName: string);
begin
ReadObjectFromFile(aFileName, self);
end;
initialization // =============================================================
Classes.RegisterClass(TxPLCustomMessage);
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2014 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Bde.Bdeconst;
interface
resourcestring
SAutoSessionExclusive = 'Impossible d'#39'activer la propriété AutoSessionName si plusieurs sessions sont sur une fiche ou un module de données';
SAutoSessionExists = 'Impossible d'#39'ajouter une session à la fiche ou au module de données tant que la session '#39'%s'#39' a AutoSessionName activé';
SAutoSessionActive = 'Impossible de modifier SessionName tant que AutoSessionName est activé';
SDuplicateDatabaseName = 'Nom de base de données dupliqué '#39'%s'#39;
SDuplicateSessionName = 'Nom de session dupliqué '#39'%s'#39;
SInvalidSessionName = 'Nom de session %s incorrect';
SDatabaseNameMissing = 'Nom de base de données manquant';
SSessionNameMissing = 'Nom de session manquant';
SDatabaseOpen = 'Impossible d'#39'effectuer cette opération sur une base de données ouverte';
SDatabaseClosed = 'Impossible d'#39'effectuer cette opération sur une base de données fermée';
SDatabaseHandleSet = 'Le handle de base de données appartient à une autre session';
SSessionActive = 'Impossible d'#39'effectuer cette opération sur une session active';
SHandleError = 'Erreur à la création du handle de curseur';
SInvalidFloatField = 'Impossible de convertir le champ '#39'%s'#39' en valeur flottante';
SInvalidIntegerField = 'Impossible de convertir le champ '#39'%s'#39' en valeur entière';
STableMismatch = 'Les tables source et destination sont incompatibles';
SFieldAssignError = 'Les champs '#39'%s'#39' et '#39'%s'#39' ne sont pas compatibles pour une affectation';
SNoReferenceTableName = 'Table de référence non spécifiée pour le champ '#39'%s'#39;
SCompositeIndexError = 'Impossible d'#39'utiliser un tableau de valeurs champs avec des indices expression';
SInvalidBatchMove = 'Paramètres de déplacement batch incorrects';
SEmptySQLStatement = 'Aucune instruction SQL disponible';
SNoParameterValue = 'Pas de valeur pour le paramètre '#39'%s'#39;
SNoParameterType = 'Pas de type pour le paramètre '#39'%s'#39;
SLoginError = 'Impossible de se connecter à la base de données '#39'%s'#39;
SInitError = 'Une erreur est survenue lors de l'#39'initialisation du Borland Database Engine (erreur $%.4x)';
SDatabaseEditor = 'E&diteur de base de données...';
SExplore = 'Exp&lorateur';
SLinkDetail = #39'%s'#39' ne peut être ouvert';
SLinkMasterSource = 'La propriété MasterSource de '#39'%s'#39' doit être liée à une source de données';
SLinkMaster = 'Impossible d'#39'ouvrir la table MasterSource';
SGQEVerb = 'Constructeur S&QL...';
SBindVerb = '&Définir les paramètres...';
SIDAPILangID = '000C';
SDisconnectDatabase = 'La base de données est actuellement connectée. Déconnecter et continuer ?';
SBDEError = 'Erreur BDE $%.4x';
SLookupSourceError = 'Impossible d'#39'utiliser DataSource et LookupSource dupliqués';
SLookupTableError = 'LookupSource doit être connecté au composant TTable';
SLookupIndexError = '%s doit être l'#39'index actif de la table de référence';
SParameterTypes = ';Entrée;Sortie;Entrée/Sortie;Résultat';
SInvalidParamFieldType = 'Un type de champ correct doit être sélectionné';
STruncationError = 'Paramètre '#39'%s'#39' tronqué en sortie';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Résultat';
SDBCaption = 'Base de données %s%s%s';
SParamEditor = 'Paramètres %s%s%s';
SIndexFilesEditor = 'Fichiers index %s%s%s';
SNoIndexFiles = '(vide)';
SIndexDoesNotExist = 'L'#39'index n'#39'existe pas. Index : %s';
SNoTableName = 'Propriété TableName manquante';
SNoDataSetField = 'Propriété DataSetField manquante';
SBatchExecute = 'E&xécuter';
SNoCachedUpdates = 'Pas en mode mise à jour en cache';
SInvalidAliasName = 'Nom d'#39'alias %s incorrect';
SNoFieldAccess = 'Impossible d'#39'accéder au champ '#39'%s'#39' dans un filtre';
SUpdateSQLEditor = 'E&diteur UpdateSQL...';
SNoDataSet = 'Aucune association d'#39'ensemble de données';
SUntitled = 'Application sans titre';
SUpdateWrongDB = 'Impossible de mettre à jour, %s n'#39'appartient pas à %s';
SUpdateFailed = 'Echec de la mise à jour';
SSQLGenSelect = 'Vous devez sélectionner au moins un champ clé et un champ de mise à jour';
SSQLNotGenerated = 'Instructions Update SQL non générées, sortir quand même ?';
SSQLDataSetOpen = 'Impossible de déterminer les noms de champs pour %s';
SLocalTransDirty = 'Le niveau d'#39'isolation de transaction doit être Lecture Dirty (dirty read) pour les bases locales';
SMissingDataSet = 'Propriété DataSet manquante';
SNoProvider = 'Aucun fournisseur disponible';
SNotAQuery = 'L'#39'ensemble de données n'#39'est pas une requête';
implementation
end.
|
unit DigitSetEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
SudokuType;
type
{ TDigitSetEditorForm }
TDigitSetEditorForm = class(TForm)
btnOK: TButton;
DigitCG: TCheckGroup;
procedure DigitCGItemClick(Sender: TObject; {%H-}Index: integer);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: char);
procedure FormShow(Sender: TObject);
private
FPreferredRight: Integer;
FOriginalDigitsPossible: TDigitSet;
function GetCurrentDigitSet: TDigitSet;
procedure SetCurrentDigitSet(ASet: TDigitSet);
procedure SetOriginalDigitsPossible(ASet: TDigitSet);
procedure SetRight({%H-}Data: PtrInt);
procedure UpdateButtonState;
public
property CurrentDigitSet: TDigitSet read GetCurrentDigitSet write SetCurrentDigitSet;
property OriginalDigitsPossible: TDigitSet read FOriginalDigitsPossible write SetOriginalDigitsPossible; //set this before CurrentDigitSet!
property PreferredRight: Integer read FPreferredRight write FPreferredRight;
end;
var
DigitSetEditorForm: TDigitSetEditorForm;
implementation
{$R *.lfm}
{ TDigitSetEditorForm }
procedure TDigitSetEditorForm.FormKeyPress(Sender: TObject; var Key: char);
var
Digit: Integer;
begin
if (Key in ['1'..'9']) then
begin
Digit := Ord(Key) - Ord('0');
if Digit in FOriginalDigitsPossible then
DigitCG.Checked[Pred(Digit)] := not DigitCG.Checked[Pred(Digit)];
Key := #0;
UpdateButtonState;
end;
if (Key = #27) then //escape
begin
Key := #0;
ModalResult := mrCancel;
end;
end;
procedure TDigitSetEditorForm.FormShow(Sender: TObject);
begin
Application.QueueAsyncCall(@SetRight, FPreferredRight)
end;
procedure TDigitSetEditorForm.FormActivate(Sender: TObject);
begin
OnACtivate := nil;
ClientWidth := 2 * DigitCG.Left + DigitCG.Width;
ClientHeight := btnOK.Top + btnOK.Height + DigitCG.Top;
end;
procedure TDigitSetEditorForm.DigitCGItemClick(Sender: TObject; Index: integer);
begin
UpdateButtonState;
end;
function TDigitSetEditorForm.GetCurrentDigitSet: TDigitSet;
var
i: Integer;
begin
Result := [];
for i := 0 to DigitCG.Items.Count - 1 do
if DigitCG.Checked[i] and (Succ(i) in FOriginalDigitsPossible)then Include(Result, Succ(i));
end;
procedure TDigitSetEditorForm.SetCurrentDigitSet(ASet: TDigitSet);
var
D: TDigits;
begin
for D in TDigits do
begin
DigitCG.Checked[D-1] := (D in ASet) and DigitCG.CheckEnabled[D-1]; //don't use Pred(D) here, gives RangeCheckError when D=1
end;
end;
procedure TDigitSetEditorForm.SetOriginalDigitsPossible(ASet: TDigitSet);
var
D: TDigits;
begin
if FOriginalDigitsPossible = ASet then Exit;
FOriginalDigitsPossible := ASet;
for D in TDigits do
begin
DigitCG.CheckEnabled[D-1] := (D in ASet); //don't use Pred(D) here, gives RangeCheckError when D=1
end;
end;
procedure TDigitSetEditorForm.SetRight(Data: PtrInt);
begin
Left := FPreferredRight - Width;
end;
procedure TDigitSetEditorForm.UpdateButtonState;
begin
btnOk.Enabled := (GetCurrentDigitSet <> []);
end;
end.
|
unit u_xPL_Custom_Header;
{==============================================================================
UnitName = uxPLCustomHeader
UnitDesc = Abstract class common to filter header and message header
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
}
{$ifdef fpc}
{$mode objfpc}{$H+}{$M+}
{$endif}
interface
uses Classes
, u_xpl_address
, u_xpl_schema
, u_xpl_common
;
type
{ TxPLCustomHeader }
TxPLCustomHeader = class(TComponent, IxPLCommon, IxPLRaw)
protected
fSource : TxPLAddress;
fTarget : TxPLTargetAddress;
fSchema : TxPLSchema;
fMsgType : TxPLMessageType;
fHop : integer;
procedure Set_Schema(const AValue: TxPLSchema);
procedure Set_Source(const AValue: TxPLAddress);
procedure Set_Target(const AValue: TxPLTargetAddress);
procedure Set_RawxPL(const aRawXPL : string);
procedure Set_MessageType(const AValue: TxPLMessageType); dynamic;
function Get_RawxPL: string; virtual; abstract;
procedure MessageTypeFromStr(const aString : string); dynamic;
function MessageTypeToStr : string; dynamic;
procedure AssignProps(const aHeader : TPersistent); virtual; abstract;
public
constructor Create(aOwner : TComponent; const aFilter : string = ''); reintroduce;
destructor Destroy; override;
function IsValid : boolean; dynamic;
procedure ResetValues; dynamic;
procedure Assign(aHeader : TPersistent); override;
property RawxPL : string read Get_RawxPL write Set_RawxPL;
property MsgTypeAsStr : string read MessageTypeToStr write MessageTypeFromStr;
published
property MessageType : TxPLMessageType read fMsgType write Set_MessageType;
property source : TxPLAddress read fSource write Set_Source;
property target : TxPLTargetAddress read fTarget write Set_Target;
property schema : TxPLSchema read fSchema write Set_Schema;
end;
implementation //==============================================================
uses SysUtils
, typinfo
, StrUtils
;
// TxPLCustomHeader ==========================================================
constructor TxPLCustomHeader.Create(aOwner: TComponent; const aFilter: string = '');
begin
inherited Create(aOwner);
include(fComponentStyle,csSubComponent);
if aFilter <> '' then
with TStringList.Create do try
Delimiter := '.';
StrictDelimiter := True;
DelimitedText := aFilter; // a string like : aMsgType.aVendor.aDevice.aInstance.aClass.aType
fSource := TxPLAddress.Create(Strings[1],Strings[2],Strings[3]); // Creates source and target with the same informations
fTarget := TxPLTargetAddress.Create(fSource);
MessageTypeFromStr(Strings[0]);
fSchema := TxPLSchema.Create(Strings[4],Strings[5]);
finally
Free;
end
else begin
fSource := TxPLAddress.Create;
fTarget := TxPLTargetAddress.Create;
fSchema := TxPLSchema.Create;
ResetValues;
end;
end;
destructor TxPLCustomHeader.destroy;
begin
Source.Free;
Target.Free;
Schema.Free;
inherited;
end;
procedure TxPLCustomHeader.MessageTypeFromStr(const aString: string);
var s : string;
begin
s := AnsiRightStr(aString, length(aString) - 4); // Removes 'xpl-'
MessageType := TxPLMessageType(GetEnumValue(TypeInfo(TxPLMessageType), s));
end;
function TxPLCustomHeader.MessageTypeToStr: string;
begin
result := 'xpl-' + GetEnumName(TypeInfo(TxPLMessageType),Ord(MessageType));
end;
procedure TxPLCustomHeader.Set_Schema(const AValue: TxPLSchema);
begin
fSchema.Assign(aValue);
end;
procedure TxPLCustomHeader.Set_Source(const AValue: TxPLAddress);
begin
fSource.Assign(aValue);
end;
procedure TxPLCustomHeader.Set_Target(const AValue: TxPLTargetAddress);
begin
fTarget.Assign(aValue);
end;
procedure TxPLCustomHeader.Set_RawXpl(const aRawXPL : string);
var i : integer;
s : string;
begin
ResetValues;
with TStringList.Create do try
DelimitedText:= AnsiReplaceText(AnsiLowerCase(aRawxPL),'}'#10,'schema=');
MessageType := StrToMsgType(Strings[0]);
fHop := StrToInt(Values['hop']);
fSource.RawxPL := Values['source'];
fTarget.RawxPL := Values['target'];
fSchema.RawxPL := Values['schema']; // => essayer SetStrProp
finally
free;
end;
with TStringList.Create do try
s := AnsiLowerCase(aRawxPL);
s := AnsiReplaceText(s,'xpl-','messagetype=');
s := AnsiReplaceText(s,'}'#10,'schema=');
DelimitedText := s;
// DelimitedText:= AnsiReplaceText(AnsiLowerCase(aRawxPL),'}'#10,'schema=');
for i:= 0 to Pred(Count) do begin
s := names[i];
if s<>'' then
SetStrProp(self,Names[i],Values[Names[i]]);
end;
// MessageType := StrToMsgType(Strings[0]);
// fHop := StrToInt(Values['hop']);
// fSource.RawxPL := Values['source'];
// fTarget.RawxPL := Values['target'];
// fSchema.RawxPL := Values['schema']; // => essayer SetStrProp
finally
free;
end;
end;
function TxPLCustomHeader.IsValid: boolean;
begin
result := Source.IsValid and
Target.IsValid and
Schema.IsValid and
(ord(MessageType)>=0);
end;
procedure TxPLCustomHeader.ResetValues;
begin
Source.ResetValues;
Target.ResetValues;
Schema.ResetValues;
Ord(fMsgType) := 0;
end;
procedure TxPLCustomHeader.Assign(aHeader : TPersistent);
begin
if aHeader is TxPLCustomHeader then begin
fSource.Assign(TxPLCustomHeader(aHeader).Source);
fTarget.Assign(TxPLCustomHeader(aHeader).Target);
fSchema.Assign(TxPLCustomHeader(aHeader).Schema);
AssignProps(aHeader);
end else inherited;
end;
procedure TxPLCustomHeader.Set_MessageType(const AValue: TxPLMessageType);
begin
if MessageType <> aValue then
fMsgType := aValue;
end;
end.
|
unit StoHtmlHelp;
////////////////////////////////////////////////////////////////
// Implementation of context sensitive HTML help (.chm) for Delphi.
//
// Version: 1.2
// Author: Martin Stoeckli
// Homepage: www.martinstoeckli.ch/delphi
// Copyright(c): Martin Stoeckli 2002
//
// Restrictions: - Works only under the Windows platform.
// - Is written for Delphi v7, should work from v6 up.
//
// Description
// ***********
// This unit enables you to call ".chm" files from your Delphi projects.
// You can use the normal Delphi VCL framework, write your projects the
// same way, as you would using normal ".hlp" files.
//
// Installation
// ************
// Simply add this unit to your project, that's all.
//
// If your help project contains files with the extension ".html"
// instead of ".htm", then you can either pass the filename with the
// extension to Application.HelpJump(), or you can set the property
// "HtmlExt" of the global object in this unit.
// StoHelpViewer.HtmlExt := '.html';
//
// Examples
// ********
// // assign a helpfile, you could also select the helpfile at the
// // options dialog "Project/Options.../Application".
// Application.HelpFile := 'C:\MyHelp.chm';
// ...
// // shows the contents of the helpfile
// Application.HelpCommand(HELP_CONTENTS, 0);
// // or
// Application.HelpSystem.ShowTableOfContents;
// ...
// // opens the context sensitive help with a numerical id.
// // you could do the same by setting the "HelpContext"
// // property of a component and pressing the F1 key.
// Application.HelpContext(1000);
// // or with a string constant
// Application.HelpJump('welcome');
// ...
// // opens the help index with a keyword.
// // you could do the same by setting the "HelpKeyword"
// // property of a component and pressing the F1 key.
// Application.HelpKeyword('how to do');
//
interface
uses Classes, Windows, HelpIntfs;
type
THtmlHelpA = function(hwndCaller: HWND; pszFile: LPCSTR; uCommand: UINT;
dwData: DWORD): HWND; stdcall;
TStoHtmlHelpViewer = class(TInterfacedObject, ICustomHelpViewer,
IExtendedHelpViewer, IHelpSelector)
private
FViewerID: Integer;
FViewerName: string;
FHtmlHelpFunction: THtmlHelpA;
protected
FHHCtrlHandle: THandle;
FHelpManager: IHelpManager;
FHtmlExt: string;
function GetHelpFileName: string;
function IsChmFile(const FileName: string): Boolean;
procedure InternalShutdown;
procedure CallHtmlHelp(const HelpFile: string; uCommand: UINT; dwData:
DWORD);
// ICustomHelpViewer
function GetViewerName: string;
function UnderstandsKeyword(const HelpString: string): Integer;
function GetHelpStrings(const HelpString: string): TStringList;
function CanShowTableOfContents: Boolean;
procedure ShowTableOfContents;
procedure ShowHelp(const HelpString: string);
procedure NotifyID(const ViewerID: Integer);
procedure SoftShutDown;
procedure ShutDown;
// IExtendedHelpViewer
function UnderstandsTopic(const Topic: string): Boolean;
procedure DisplayTopic(const Topic: string);
function UnderstandsContext(const ContextID: Integer;
const HelpFileName: string): Boolean;
procedure DisplayHelpByContext(const ContextID: Integer;
const HelpFileName: string);
// IHelpSelector
function SelectKeyword(Keywords: TStrings): Integer;
function TableOfContents(Contents: TStrings): Integer;
public
constructor Create; virtual;
destructor Destroy; override;
property HtmlExt: string read FHtmlExt write FHtmlExt;
end;
var
StoHelpViewer: TStoHtmlHelpViewer;
implementation
uses Forms, SysUtils, WinHelpViewer;
const
// imported from HTML Help Workshop
HH_DISPLAY_TOPIC = $0000;
HH_HELP_FINDER = $0000; // WinHelp equivalent
HH_DISPLAY_TOC = $0001;
HH_DISPLAY_INDEX = $0002;
HH_DISPLAY_SEARCH = $0003;
HH_KEYWORD_LOOKUP = $000D;
HH_DISPLAY_TEXT_POPUP = $000E;
// display string resource id or text in a popup window
HH_HELP_CONTEXT = $000F; // display mapped numeric value in dwData
HH_TP_HELP_CONTEXTMENU = $0010;
// text popup help, same as WinHelp HELP_CONTEXTMENU
HH_TP_HELP_WM_HELP = $0011; // text popup help, same as WinHelp HELP_WM_HELP
HH_CLOSE_ALL = $0012;
// close all windows opened directly or indirectly by the caller
HH_ALINK_LOOKUP = $0013; // ALink version of HH_KEYWORD_LOOKUP
HH_GET_LAST_ERROR = $0014; // not currently implemented // See HHERROR.h
type
TStoWinHelpTester = class(TInterfacedObject, IWinHelpTester)
protected
// IWinHelpTester
function CanShowALink(const ALink, FileName: string): Boolean;
function CanShowTopic(const Topic, FileName: string): Boolean;
function CanShowContext(const Context: Integer;
const FileName: string): Boolean;
function GetHelpStrings(const ALink: string): TStringList;
function GetHelpPath: string;
function GetDefaultHelpFile: string;
function IsHlpFile(const FileName: string): Boolean;
end;
////////////////////////////////////////////////////////////////
// like "Application.ExeName", but in a DLL you get the name of
// the DLL instead of the application name
function Sto_GetModuleName: string;
var
szFileName: array[0..MAX_PATH] of Char;
begin
FillChar(szFileName, SizeOf(szFileName), #0);
GetModuleFileName(hInstance, szFileName, MAX_PATH);
Result := szFileName;
end;
////////////////////////////////////////////////////////////////
{ TStoHtmlHelpViewer }
////////////////////////////////////////////////////////////////
procedure TStoHtmlHelpViewer.CallHtmlHelp(const HelpFile: string; uCommand:
UINT; dwData: DWORD);
begin
if Assigned(FHtmlHelpFunction) then
begin
case uCommand of
HH_CLOSE_ALL: FHtmlHelpFunction(0, nil, uCommand, dwData);
// special parameters
HH_GET_LAST_ERROR: ; // ignore
else
FHtmlHelpFunction(FHelpManager.GetHandle, PChar(HelpFile), uCommand,
dwData);
end;
end;
end;
function TStoHtmlHelpViewer.CanShowTableOfContents: Boolean;
begin
Result := True;
end;
constructor TStoHtmlHelpViewer.Create;
begin
inherited Create;
FViewerName := 'StoHtmlHelp';
FHtmlExt := '.htm';
// load dll
FHHCtrlHandle := LoadLibrary('HHCtrl.ocx');
if (FHHCtrlHandle <> 0) then
FHtmlHelpFunction := GetProcAddress(FHHCtrlHandle, 'HtmlHelpA');
end;
destructor TStoHtmlHelpViewer.Destroy;
begin
StoHelpViewer := nil;
// free dll
FHtmlHelpFunction := nil;
if (FHHCtrlHandle <> 0) then
FreeLibrary(FHHCtrlHandle);
inherited Destroy;
end;
procedure TStoHtmlHelpViewer.DisplayHelpByContext(const ContextID: Integer;
const HelpFileName: string);
var
sHelpFile: string;
begin
sHelpFile := GetHelpFileName;
if IsChmFile(sHelpFile) then
CallHtmlHelp(sHelpFile, HH_HELP_CONTEXT, ContextID);
end;
procedure TStoHtmlHelpViewer.DisplayTopic(const Topic: string);
var
sHelpFile: string;
sTopic: string;
sFileExt: string;
begin
sHelpFile := GetHelpFileName;
if IsChmFile(sHelpFile) then
begin
// prepare topicname as a html page
sTopic := Topic;
sFileExt := LowerCase(ExtractFileExt(sTopic));
if (sFileExt <> '.htm') and (sFileExt <> '.html') then
sTopic := sTopic + FHtmlExt;
CallHtmlHelp(sHelpFile + '::/' + sTopic, HH_DISPLAY_TOPIC, 0);
end;
end;
function TStoHtmlHelpViewer.GetHelpFileName: string;
var
sPath: string;
begin
Result := '';
// ask for the helpfile name
if Assigned(FHelpManager) then
Result := FHelpManager.GetHelpFile;
if (Result = '') then
Result := Application.CurrentHelpFile;
// if no path is specified, then add the application path
// (otherwise the file won't be found if the current directory is wrong).
if (Result <> '') then
begin
sPath := ExtractFilePath(Result);
if (sPath = '') then
Result := ExtractFilePath(Sto_GetModuleName) + Result;
end;
end;
function TStoHtmlHelpViewer.GetHelpStrings(const HelpString: string):
TStringList;
begin
// create a tagged keyword
Result := TStringList.Create;
Result.Add(Format('%s: %s', [FViewerName, HelpString]));
end;
function TStoHtmlHelpViewer.GetViewerName: string;
begin
Result := FViewerName;
end;
procedure TStoHtmlHelpViewer.InternalShutdown;
begin
if Assigned(FHelpManager) then
begin
FHelpManager.Release(FViewerID);
FHelpManager := nil;
end;
end;
function TStoHtmlHelpViewer.IsChmFile(const FileName: string): Boolean;
var
iPos: Integer;
sFileExt: string;
begin
// find extension
iPos := LastDelimiter('.', FileName);
if (iPos > 0) then
begin
sFileExt := Copy(FileName, iPos, Length(FileName));
Result := CompareText(sFileExt, '.chm') = 0;
end
else
Result := False;
end;
procedure TStoHtmlHelpViewer.NotifyID(const ViewerID: Integer);
begin
FViewerID := ViewerID;
end;
function TStoHtmlHelpViewer.SelectKeyword(Keywords: TStrings): Integer;
var
i: Integer;
sViewerName: string;
begin
Result := 0;
i := 0;
// find first tagged line (see GetHelpStrings)
while (Result = 0) and (i <= Keywords.Count - 1) do
begin
sViewerName := Keywords.Strings[i];
Delete(sViewerName, Pos(':', sViewerName), Length(sViewerName));
if (FViewerName = sViewerName) then
Result := i
else
Inc(i);
end;
end;
procedure TStoHtmlHelpViewer.ShowHelp(const HelpString: string);
var
sHelpFile: string;
sHelpString: string;
begin
sHelpFile := GetHelpFileName;
if IsChmFile(sHelpFile) then
begin
// remove the tag if necessary (see GetHelpStrings)
sHelpString := HelpString;
Delete(sHelpString, 1, Pos(':', sHelpString));
sHelpString := Trim(sHelpString);
CallHtmlHelp(sHelpFile, HH_DISPLAY_INDEX, DWORD(Pchar(sHelpString)));
end;
end;
procedure TStoHtmlHelpViewer.ShowTableOfContents;
var
sHelpFile: string;
begin
sHelpFile := GetHelpFileName;
if IsChmFile(sHelpFile) then
CallHtmlHelp(sHelpFile, HH_DISPLAY_TOC, 0);
end;
procedure TStoHtmlHelpViewer.ShutDown;
begin
SoftShutDown;
if Assigned(FHelpManager) then
FHelpManager := nil;
end;
procedure TStoHtmlHelpViewer.SoftShutDown;
begin
CallHtmlHelp('', HH_CLOSE_ALL, 0);
end;
function TStoHtmlHelpViewer.TableOfContents(Contents: TStrings): Integer;
begin
// find line with viewer name
Result := Contents.IndexOf(FViewerName);
end;
function TStoHtmlHelpViewer.UnderstandsContext(const ContextID: Integer;
const HelpFileName: string): Boolean;
begin
Result := IsChmFile(HelpFileName);
end;
function TStoHtmlHelpViewer.UnderstandsKeyword(const HelpString: string):
Integer;
begin
if IsChmFile(GetHelpFileName) then
Result := 1
else
Result := 0;
end;
function TStoHtmlHelpViewer.UnderstandsTopic(const Topic: string): Boolean;
begin
Result := IsChmFile(GetHelpFileName);
end;
////////////////////////////////////////////////////////////////
{ TStoWinHelpTester }
//
// delphi will call the WinHelpTester to determine, if the default
// winhelp should handle the requests.
// don't allow anything, because delphi (v7) will create an invalid
// helpfile path, calling GetHelpPath (it puts a pathdelimiter
// before the filename in "TWinHelpViewer.HelpFile").
////////////////////////////////////////////////////////////////
function TStoWinHelpTester.CanShowALink(const ALink,
FileName: string): Boolean;
begin
Result := False;
// Result := IsHlpFile(FileName);
end;
function TStoWinHelpTester.CanShowContext(const Context: Integer;
const FileName: string): Boolean;
begin
Result := False;
// Result := IsHlpFile(FileName);
end;
function TStoWinHelpTester.CanShowTopic(const Topic,
FileName: string): Boolean;
begin
Result := False;
// Result := IsHlpFile(FileName);
end;
function TStoWinHelpTester.GetDefaultHelpFile: string;
begin
Result := '';
end;
function TStoWinHelpTester.GetHelpPath: string;
begin
Result := '';
end;
function TStoWinHelpTester.GetHelpStrings(
const ALink: string): TStringList;
begin
// as TWinHelpViewer would do it
Result := TStringList.Create;
Result.Add(': ' + ALink);
end;
function TStoWinHelpTester.IsHlpFile(const FileName: string): Boolean;
var
iPos: Integer;
sFileExt: string;
begin
// file has extension '.hlp' ?
iPos := LastDelimiter('.', FileName);
if (iPos > 0) then
begin
sFileExt := Copy(FileName, iPos, Length(FileName));
Result := CompareText(sFileExt, '.hlp') = 0;
end
else
Result := False;
end;
initialization
StoHelpViewer := TStoHtmlHelpViewer.Create;
RegisterViewer(StoHelpViewer, StoHelpViewer.FHelpManager);
Application.HelpSystem.AssignHelpSelector(StoHelpViewer);
WinHelpTester := TStoWinHelpTester.Create;
finalization
// do not free StoHelpViewer, because the object is referenced by the
// interface and will be freed automatically by releasing the last reference
if Assigned(StoHelpViewer) then
StoHelpViewer.InternalShutdown;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QDialogs;
{$R-,T-,H+,X+}
interface
uses
{$IFDEF MSWINDOWS} Windows, Messages, ShlObj, ActiveX, CommDlg, {$ENDIF}
SysUtils, Types, QTypes, Qt, Classes, QGraphics, QControls, QStdCtrls, QForms,
QExtCtrls;
const
{ Maximum number of custom colors in color dialog }
MaxCustomColors = 16;
type
EQtDialogException = class(Exception);
TDialog = class(TComponent)
private
FHelpType: THelpType;
FHelpContext: THelpContext;
FHelpKeyword: string;
FOnClose: TNotifyEvent;
FOnShow: TNotifyEvent;
FModal: Boolean;
FPosition: TPoint;
FWidth: Integer;
FHeight: Integer;
FTitle: WideString;
FShowing: Boolean;
FScaleFlags: TScalingFlags;
procedure SetPosition(const Value: TPoint);
function GetPosition: TPoint;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
protected
procedure DoClose; dynamic;
function DoExecute: Boolean; virtual; abstract;
procedure DoShow; dynamic;
function GetBounds: TRect; virtual; abstract;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); virtual; abstract;
procedure SetTitle(const Value: WideString); virtual;
property Height: Integer read GetHeight write SetHeight;
property Modal: Boolean read FModal write FModal;
property Position: TPoint read GetPosition write SetPosition;
property Title: WideString read FTitle write SetTitle;
property Width: Integer read GetWidth write SetWidth;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
public
function Execute: Boolean; virtual;
published
property HelpType: THelpType read FHelpType write FHelpType default htKeyword;
property HelpContext: THelpContext read FHelpContext write FHelpContext default 0;
property HelpKeyword: string read FHelpKeyword write FHelpKeyword;
end;
{ TQtDialog }
TQtDialog = class(TDialog)
private
FHooks: QObject_hookH;
FHandle: QDialogH;
{$IFDEF MSWINDOWS}
FUseNative: Boolean;
FNativeFlags: Integer;
{$ENDIF}
function GetHandle: QDialogH;
procedure CreateHandle;
procedure DestroyedHook; cdecl;
procedure HandleNeeded;
procedure InvokeHelp;
function GetHooks: QObject_hookH;
protected
function AppEventFilter(Sender: QObjectH; Event: QEventH): Boolean; virtual; cdecl;
procedure CreateWidget; virtual;
procedure DestroyWidget;
procedure InitWidget; virtual;
function GetBounds: TRect; override;
procedure HookEvents; virtual;
function DoExecute: Boolean; override;
procedure DoShow; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; virtual;
{$ENDIF}
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetTitle(const Value: WideString); override;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; virtual; cdecl;
function WidgetFlags: Integer; virtual;
property Hooks: QObject_hookH read GetHooks write FHooks;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean; override;
function HandleAllocated: Boolean;
property Handle: QDialogH read GetHandle;
property Position;
published
property Height default 0;
{$IFDEF MSWINDOWS}
property NativeFlags: Integer read FNativeFlags write FNativeFlags default 0;
property UseNativeDialog: Boolean read FUseNative write FUseNative default True;
{$ENDIF}
property Width default 0;
end;
{ TOpenDialog }
TOpenOption = (ofShowHidden, ofOverwritePrompt, ofNoChangeDir, ofAllowMultiSelect,
ofExtensionDifferent, ofPathMustExist, ofFileMustExist, ofEnableSizing,
ofViewDetail);
TOpenOptions = set of TOpenOption;
TFileAddEvent = procedure(Sender: TObject; const Filename: string; const Readable,
Writeable, Executable: Boolean; var CanAdd: Boolean) of object;
TFileSelectEvent = procedure(Sender: TObject; const Filename: string) of object;
TDirChangeEvent = procedure(Sender: TObject; const Dir: string) of object;
TOpenDialog = class(TQtDialog)
private
FHistoryList: TStrings;
FFilter: string;
FInitialDir: string;
FSaveDir: string;
FDefaultExt: string;
FFileName: TFileName;
FFiles: TStrings;
FFilterIndex: Integer;
FOptions: TOpenOptions;
FTempFiles: TStringList;
FTempFilename: string;
FOnFileAdd: TFileAddEvent;
FOnFolderChange: TDirChangeEvent;
FOnSelected: TFileSelectEvent;
FOnCanClose: TCloseQueryEvent;
procedure CanCloseHook(canClose: PBoolean); cdecl;
procedure DirEnteredHook(P1: PWideString); cdecl;
procedure FileAddHook(Filename: PString; const Readable, Writeable, Executable: Boolean;
var CanAdd: Boolean); cdecl;
procedure FilterChangedHook(Index: Integer); cdecl;
function GetHandle: QClxFileDialogH;
procedure FileHighlightedHook(P1: PWideString); cdecl;
procedure SetHistoryList(Value: TStrings);
protected
procedure CreateWidget; override;
procedure DefineProperties(Filer: TFiler); override;
procedure DoCanClose(var CanClose: Boolean); virtual;
function DoExecute: Boolean; override;
function DoFileAdd(const Filename: string; const Readable, Writeable, Executable: Boolean): Boolean; virtual;
procedure DoFolderChange(const Dir: string); dynamic;
procedure DoSelected(const Filename: string); dynamic;
procedure HookEvents; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
procedure SetOptions; virtual;
procedure RetrieveOptions; virtual;
function WidgetFlags: Integer; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh;
property Files: TStrings read FFiles;
property Handle: QClxFileDialogH read GetHandle;
property HistoryList: TStrings read FHistoryList write SetHistoryList;
published
property DefaultExt: string read FDefaultExt write FDefaultExt;
property FileName: TFileName read FFileName write FFileName;
property Filter: string read FFilter write FFilter;
property FilterIndex: Integer read FFilterIndex write FFilterIndex default 1;
property InitialDir: string read FInitialDir write FInitialDir;
property Options: TOpenOptions read FOptions write FOptions default [ofEnableSizing];
property Height default 350;
property Title;
property Width default 550;
property OnClose;
property OnCanClose: TCloseQueryEvent read FOnCanClose write FOnCanClose;
property OnFileAdd: TFileAddEvent read FOnFileAdd write FOnFileAdd;
property OnFolderChange: TDirChangeEvent read FOnFolderChange write FOnFolderChange;
property OnSelected: TFileSelectEvent read FOnSelected write FOnSelected;
property OnShow;
end;
{ TSaveDialog }
TSaveDialog = class(TOpenDialog)
protected
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
procedure SetOptions; override;
public
constructor Create(AOwner: TComponent); override;
end;
{ TColorDialog }
TCustomColors = array[0..MaxCustomColors - 1] of Longint;
TColorDialog = class(TQtDialog)
private
FColor: TColor;
FCustomColors: TStrings;
procedure SetCustomColors(Value: TStrings);
protected
function DoExecute: Boolean; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Color: TColor read FColor write FColor default clBlack;
property CustomColors: TStrings read FCustomColors write SetCustomColors;
end;
{ TFontDialog }
TFontDialog = class(TQtDialog)
private
FFont: TFont;
procedure SetFont(Value: TFont);
protected
function DoExecute: Boolean; override;
{$IFDEF MSWINDOWS}
function NativeExecute(Flags: Integer): Boolean; override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Font: TFont read FFont write SetFont;
end;
TCustomDialog = class;
TDialogForm = class(TCustomForm)
private
FDialog: TCustomDialog;
public
procedure InvokeHelp; override;
end;
TCustomDialog = class(TDialog)
private
FForm: TDialogForm;
procedure Close(Sender: TObject; var Action: TCloseAction);
protected
function CreateForm: TDialogForm; virtual; abstract;
function DoExecute: Boolean; override;
procedure DoShow; override;
procedure DoClose; override;
function GetBounds: TRect; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure SetTitle(const Value: WideString); override;
public
function Execute: Boolean; override;
procedure InvokeHelp;
end;
{ TFindDialog }
TFindOption = (frDown, frFindNext, frHideMatchCase, frHideWholeWord,
frHideUpDown, frMatchCase, frDisableMatchCase, frDisableUpDown,
frDisableWholeWord, frReplace, frReplaceAll, frWholeWord, frShowHelp);
TFindOptions = set of TFindOption;
TFindDialogForm = class(TDialogForm)
private
FindEdit: TEdit;
FindLabel: TLabel;
WholeWord: TCheckBox;
MatchCase: TCheckBox;
Direction: TRadioGroup;
FindNext: TButton;
Cancel: TButton;
Help: TButton;
DialogUnits: TPoint;
protected
procedure ButtonPress(Sender: TObject); virtual;
procedure CheckboxCheck(Sender: TObject);
procedure DirectionClick(Sender: TObject);
procedure EditChanged(Sender: TObject); virtual;
procedure SetDialogOption(Option: TFindOption; Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
end;
TFindDialog = class(TCustomDialog)
private
FOptions: TFindOptions;
FOnFind: TNotifyEvent;
FFindText: WideString;
procedure SetFindText(const Value: WideString);
protected
function CreateForm: TDialogForm; override;
procedure DoShow; override;
procedure Find; dynamic;
public
constructor Create(AOwner: TComponent); override;
property Position;
published
property FindText: WideString read FFindText write SetFindText;
property Options: TFindOptions read FOptions write FOptions default [frDown];
property Title;
property OnClose;
property OnFind: TNotifyEvent read FOnFind write FOnFind;
property OnShow;
end;
TReplaceDialogForm = class(TFindDialogForm)
private
ReplaceBtn: TButton;
ReplaceAll: TButton;
ReplaceEdit: TEdit;
ReplaceLabel: TLabel;
protected
procedure EditChanged(Sender: TObject); override;
procedure ButtonPress(Sender: TObject); override;
public
constructor Create(AOwner: TComponent); override;
end;
{ TReplaceDialog }
TReplaceDialog = class(TFindDialog)
private
FReplaceText: WideString;
FOnReplace: TNotifyEvent;
procedure SetReplaceText(const Value: WideString);
protected
function CreateForm: TDialogForm; override;
procedure DoShow; override;
procedure Replace; dynamic;
public
constructor Create(AOwner: TComponent); override;
published
property ReplaceText: WideString read FReplaceText write SetReplaceText;
property OnReplace: TNotifyEvent read FOnReplace write FOnReplace;
end;
{ Message dialog }
type
TMsgDlgType = (mtCustom, mtInformation, mtWarning, mtError, mtConfirmation);
TMsgDlgBtn = (mbNone, mbOk, mbCancel, mbYes, mbNo, mbAbort, mbRetry, mbIgnore);
TMsgDlgButtons = set of TMsgDlgBtn;
const
mbYesNoCancel = [mbYes, mbNo, mbCancel];
mbYesNo = [mbYes, mbNo];
mbOKCancel = [mbOK, mbCancel];
mbAbortRetryIgnore = [mbAbort, mbRetry, mbIgnore];
function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultBtn: TMsgDlgBtn = mbNone;
Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Button1, Button2, Button3: TMsgDlgBtn; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
procedure ShowMessage(const Msg: WideString); overload;
procedure ShowMessage(const Msg: WideString; Params: array of const); overload;
procedure ShowMessageFmt(const Msg: WideString; Params: array of const);
procedure ShowMessagePos(const Msg: WideString; X, Y: Integer);
{ Input dialogs }
function InputBox(const ACaption, APrompt, ADefault: WideString): WideString; overload;
function InputBox(const ACaption, APrompt: WideString; ADefault: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Integer; overload;
function InputBox(const ACaption, APrompt: WideString; ADefault: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Double; overload;
function InputQuery(const ACaption, APrompt: WideString;
var Value: WideString): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString;
var Value: string): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString; var Value: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Boolean; overload;
function InputQuery(const ACaption, APrompt: WideString; var Value: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Boolean; overload;
{$IFDEF LINUX}
function SelectDirectory(const Caption: WideString; const Root: string;
var Directory: string): Boolean;
{$ENDIF}
{$IFDEF MSWINDOWS}
function SelectDirectory(const Caption: string; const Root: WideString;
out Directory: string): Boolean;
{$ENDIF}
implementation
uses QConsts {$IFDEF LINUX}, DirSel {$ENDIF};
{$R *.res}
var
CustomColorCount: Integer;
type
TOpenApplication = class(TApplication);
{$IFDEF LINUX}
function SelectDirectory(const Caption: WideString; const Root: string;
var Directory: string): Boolean;
var
Dlg: TDirSelDlg;
begin
Dlg := TDirSelDlg.Create(Application);
try
Dlg.RootDirectory := Root;
Dlg.Directory := Directory;
Dlg.Caption := Caption;
Result := Dlg.ShowModal = mrOK;
if Result then Directory := Dlg.SelectedDir;
finally
Dlg.Free;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
type
PTaskWindow = ^TTaskWindow;
TTaskWindow = record
Next: PTaskWindow;
Window: HWnd;
end;
var
TaskActiveWindow: HWnd = 0;
TaskFirstWindow: HWnd = 0;
TaskFirstTopMost: HWnd = 0;
TaskWindowList: PTaskWindow = nil;
function DoDisableWindow(Window: HWnd; Data: Longint): Bool; stdcall;
var
P: PTaskWindow;
begin
if (Window <> TaskActiveWindow) and IsWindowVisible(Window) and
IsWindowEnabled(Window) then
begin
New(P);
P^.Next := TaskWindowList;
P^.Window := Window;
TaskWindowList := P;
EnableWindow(Window, False);
end;
Result := True;
end;
procedure EnableTaskWindows(WindowList: Pointer);
var
P: PTaskWindow;
begin
while WindowList <> nil do
begin
P := WindowList;
if IsWindow(P^.Window) then EnableWindow(P^.Window, True);
WindowList := P^.Next;
Dispose(P);
end;
end;
function DisableTaskWindows(ActiveWindow: HWnd): Pointer;
var
SaveActiveWindow: HWND;
SaveWindowList: Pointer;
begin
Result := nil;
SaveActiveWindow := TaskActiveWindow;
SaveWindowList := TaskWindowList;
TaskActiveWindow := ActiveWindow;
TaskWindowList := nil;
try
try
EnumThreadWindows(GetCurrentThreadID, @DoDisableWindow, 0);
Result := TaskWindowList;
except
EnableTaskWindows(TaskWindowList);
raise;
end;
finally
TaskWindowList := SaveWindowList;
TaskActiveWindow := SaveActiveWindow;
end;
end;
var
CreationControl: TQtDialog = nil;
WndProcPtrAtom: TAtom = 0;
InstancePtrAtom: TAtom = 0;
function TaskModalDialog(DialogFunc: Pointer; var DialogData): Bool;
type
TDialogFunc = function(var DialogData): Bool stdcall;
var
ActiveWindow: HWnd;
WindowList: Pointer;
FPUControlWord: Word;
AtomText: array[0..31] of Char;
begin
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
WndProcPtrAtom := GlobalAddAtom(StrFmt(AtomText,
'WndProcPtr%.8X%.8X', [HInstance, GetCurrentThreadID]));
InstancePtrAtom := GlobalAddAtom(StrFmt(AtomText,
'DlgInstancePtr%.8X%.8X', [HInstance, GetCurrentThreadID]));
try
asm
// Avoid FPU control word change in NETRAP.dll, NETAPI32.dll, etc
FNSTCW FPUControlWord
end;
try
Result := TDialogFunc(DialogFunc)(DialogData);
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
finally
if WndProcPtrAtom <> 0 then GlobalDeleteAtom(WndProcPtrAtom);
if InstancePtrAtom <> 0 then GlobalDeleteAtom(WndProcPtrAtom);
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
end;
end;
{ Open and Save dialog routines for Windows native dialog }
procedure GetFileNames(OpenDialog: TOpenDialog; var OpenFileName: TOpenFileName);
var
Separator: Char;
function ExtractFileName(P: PChar; var S: TFilename): PChar;
begin
Result := AnsiStrScan(P, Separator);
if Result = nil then
begin
S := P;
Result := StrEnd(P);
end
else
begin
SetString(S, P, Result - P);
Inc(Result);
end;
end;
procedure ExtractFileNames(P: PChar);
var
DirName, FileName: TFilename;
begin
P := ExtractFileName(P, DirName);
P := ExtractFileName(P, FileName);
if FileName = '' then
OpenDialog.FFiles.Add(DirName)
else
begin
if AnsiLastChar(DirName)^ <> '\' then
DirName := DirName + '\';
repeat
if (FileName[1] <> '\') and ((Length(FileName) <= 3) or
(FileName[2] <> ':') or (FileName[3] <> '\')) then
FileName := DirName + FileName;
OpenDialog.FFiles.Add(FileName);
P := ExtractFileName(P, FileName);
until FileName = '';
end;
end;
begin
Separator := #0;
with OpenFileName do
begin
if ofAllowMultiSelect in OpenDialog.FOptions then
begin
ExtractFileNames(lpstrFile);
OpenDialog.FFileName := OpenDialog.FFiles[0];
end else
begin
ExtractFileName(lpstrFile, OpenDialog.FFileName);
OpenDialog.FFiles.Add(OpenDialog.FFileName);
end;
end;
end;
function OpenWndProc(Wnd: HWND; Msg, WParam, LParam: Longint): Longint; stdcall;
function StrRetToString(PIDL: PItemIDList; StrRet: TStrRet): string;
var
P: PChar;
begin
case StrRet.uType of
STRRET_CSTR:
SetString(Result, StrRet.cStr, lStrLen(StrRet.cStr));
STRRET_OFFSET:
begin
P := @PIDL.mkid.abID[StrRet.uOffset - SizeOf(PIDL.mkid.cb)];
SetString(Result, P, PIDL.mkid.cb - StrRet.uOffset);
end;
STRRET_WSTR:
Result := StrRet.pOleStr;
end;
end;
function CallDefWndProc: Longint;
begin
Result := CallWindowProc(Pointer(GetProp(Wnd,
MakeIntAtom(WndProcPtrAtom))), Wnd, Msg, WParam, LParam);
end;
var
Instance: TOpenDialog;
CanClose: Boolean;
Include: Boolean;
StrRet: TStrRet;
Path: array[0..MAX_PATH] of Char;
begin
Result := 0;
{ If not ofOldStyleDialog then DoShow on CDN_INITDONE, not WM_INITDIALOG }
if (Msg = WM_INITDIALOG) {and not (ofOldStyleDialog in Options) }then Exit;
Instance := TOpenDialog(GetProp(Wnd, MakeIntAtom(InstancePtrAtom)));
case Msg of
WM_NOTIFY:
case (POFNotify(LParam)^.hdr.code) of
CDN_FILEOK:
begin
CanClose := True;
GetFileNames(Instance, POFNotify(LParam)^.lpOFN^);
Instance.DoCanClose(CanClose);
Instance.FFiles.Clear;
if not CanClose then
begin
Result := 1;
SetWindowLong(Wnd, DWL_MSGRESULT, Result);//Wnd??
Exit;
end;
end;
CDN_INITDONE:
Instance.DoShow;
CDN_SELCHANGE:
begin
SendMessage(GetParent(Longint(Instance.FHandle)), CDM_GETFILEPATH,
SizeOf(Path), Integer(@Path));
Instance.DoSelected(Path);
end;
CDN_FOLDERCHANGE:
begin
SendMessage(GetParent(Longint(Instance.FHandle)), CDM_GETFOLDERPATH,
SizeOf(Path), Integer(@Path));
Instance.DoFolderChange(Path);
end;
CDN_INCLUDEITEM:
if (LParam <> 0) and Assigned(Instance.OnFileAdd) then
begin
POFNotifyEx(LParam)^.psf.GetDisplayNameOf(POFNotifyEx(LParam)^.pidl, SHGDN_FORPARSING, StrRet);
Include := Instance.DoFileAdd(StrRetToString(POFNotifyEx(LParam)^.pidl, StrRet), True, True, True);
Result := Byte(Include);
Exit;
end;
end;
WM_NCDESTROY:
begin
Result := CallDefWndProc;
Instance.FHandle := nil;
RemoveProp(Wnd, MakeIntAtom(InstancePtrAtom));
RemoveProp(Wnd, MakeIntAtom(WndProcPtrAtom));
Exit;
end;
end;
Result := CallDefWndProc;
end;
function OpenDialogHook(Wnd: HWnd; Msg: UINT; WParam: WPARAM; LParam: LPARAM): UINT; stdcall;
begin
Result := 0;
if Msg = WM_INITDIALOG then
begin
SetProp(Wnd, MakeIntAtom(InstancePtrAtom), Longint(POpenFileName(LParam)^.lCustData));
SetProp(Wnd, MakeIntAtom(WndProcPtrAtom), GetWindowLong(Wnd, GWL_WNDPROC));
TOpenDialog(POpenFileName(LParam)^.lCustData).FHandle := QDialogH(Wnd);
SetWindowLong(Wnd, GWL_WNDPROC, Longint(@OpenWndProc));
Result := 1;
end;
end;
function WinFileDialogExecute(Dialog: TOpenDialog; DlgFunc: Pointer; ODFlags: DWORD): Boolean;
const
MultiSelectBufferSize = High(Word) - 16;
OpenOptions: array [TOpenOption] of DWORD = (
OFN_FORCESHOWHIDDEN, OFN_OVERWRITEPROMPT, OFN_NOCHANGEDIR,
OFN_ALLOWMULTISELECT, OFN_EXTENSIONDIFFERENT, OFN_PATHMUSTEXIST,
OFN_FILEMUSTEXIST, OFN_ENABLESIZING, 0);
var
Option: TOpenOption;
OpenFilename: TOpenFilename;
function AllocFilterStr(const S: string): string;
var
P, P1: PChar;
Desc, Mask: string;
I, J: Integer;
begin
{ It is assumed the filter string is in CLX (Qt-native) format and needs to
be translated to what Windows expects }
Result := '';
if S <> '' then
begin
P := PChar(S);
P1 := StrPos(P, '|');
if P1 = nil then
P1 := P + StrLen(P);
while P - PChar(S) < Length(S) do
begin
SetString(Desc, P, Integer(P1-P));
I := Pos('(', Desc);
J := Pos(')', Desc);
Result := Result + Desc + #0;
if (I > 0) and (J > 0) and (J > I) then
Mask := Copy(Desc, I+1, J-I-1)
else
Mask := Desc;
Result := Result + Mask + #0;
P := P1 + 1;
P1 := StrPos(P, '|');
if P1 = nil then
P1 := P + StrLen(P);
end;
Result := Result + #0;
end;
end;
var
TempFilter, TempFilename, TempExt: string;
ATitle: string;
begin
Dialog.FFiles.Clear;
FillChar(OpenFileName, SizeOf(OpenFileName), 0);
with OpenFilename do
begin
if (Win32MajorVersion >= 5) and (Win32Platform = VER_PLATFORM_WIN32_NT) or { Win2k }
((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (Win32MajorVersion >= 4) and (Win32MinorVersion >= 90)) then { WinME }
lStructSize := SizeOf(TOpenFilename)
else
lStructSize := SizeOf(TOpenFilename) - (SizeOf(DWORD) shl 1) - SizeOf(Pointer); { subtract size of added fields }
hInstance := SysInit.HInstance;
TempFilter := AllocFilterStr(Dialog.Filter);
lpstrFilter := PChar(TempFilter);
nFilterIndex := Dialog.FilterIndex;
if ofAllowMultiSelect in Dialog.Options then
nMaxFile := MultiSelectBufferSize else
nMaxFile := MAX_PATH;
SetLength(TempFilename, nMaxFile + 2);
lpstrFile := PChar(TempFilename);
FillChar(lpstrFile^, nMaxFile + 2, 0);
StrLCopy(lpstrFile, PChar(Dialog.FileName), nMaxFile);
if (Dialog.InitialDir = '') then
lpstrInitialDir := '.'
else
lpstrInitialDir := PChar(Dialog.InitialDir);
ATitle := Dialog.Title;
lpstrTitle := PChar(ATitle);
if ODFlags = 0 then
Flags := OFN_HIDEREADONLY or OFN_NOREADONLYRETURN
else
Flags := ODFlags;
Flags := Flags or OFN_ENABLEHOOK or OFN_ENABLEINCLUDENOTIFY or OFN_EXPLORER;
for Option := Low(Option) to High(Option) do
if Option in Dialog.Options then
Flags := Flags or OpenOptions[Option];
TempExt := Dialog.DefaultExt;
if (TempExt = '') and (Flags and OFN_EXPLORER = 0) then
begin
TempExt := ExtractFileExt(Dialog.Filename);
Delete(TempExt, 1, 1);
end;
if TempExt <> '' then lpstrDefExt := PChar(TempExt);
lCustData := Integer(Dialog);
lpfnHook := OpenDialogHook;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(DlgFunc, OpenFileName);
if Result then
begin
GetFileNames(Dialog, OpenFilename);
if (Flags and OFN_EXTENSIONDIFFERENT) <> 0 then
Include(Dialog.FOptions, ofExtensionDifferent) else
Exclude(Dialog.FOptions, ofExtensionDifferent);
Dialog.FFilterIndex := nFilterIndex;
end;
end;
end;
{ Font dialog routine for Windows native dialog }
function WinFontDialogExecute(FontDialog: TFontDialog; FDFlags: DWORD = 0): Boolean;
var
FontCharSetModified: Boolean;
procedure UpdateFromLogFont(const LogFont: TLogFont);
var
Style: TFontStyles;
begin
with LogFont do
begin
FontDialog.Font.Name := LogFont.lfFaceName;
FontDialog.Font.Height := LogFont.lfHeight;
if FontCharsetModified then
FontDialog.Font.Charset := TFontCharset(LogFont.lfCharSet);
Style := [];
with LogFont do
begin
if lfWeight > FW_REGULAR then Include(Style, fsBold);
if lfItalic <> 0 then Include(Style, fsItalic);
if lfUnderline <> 0 then Include(Style, fsUnderline);
if lfStrikeOut <> 0 then Include(Style, fsStrikeOut);
end;
FontDialog.Font.Style := Style;
end;
end;
var
ChooseFontRec: TChooseFont;
LogFont: TLogFont;
OriginalFaceName: string;
begin
with ChooseFontRec do
begin
lStructSize := SizeOf(ChooseFontRec);
hDC := 0;
lpLogFont := @LogFont;
GetObject(QFont_handle(FontDialog.Font.Handle), SizeOf(LogFont), @LogFont);
OriginalFaceName := LogFont.lfFaceName;
if FDFlags = 0 then
Flags := CF_BOTH or CF_EFFECTS
else
Flags := FDFlags;
Flags := Flags or CF_INITTOLOGFONTSTRUCT;
rgbColors := FontDialog.Font.Color;
lCustData := 0;
lpfnHook := nil;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(@ChooseFont, ChooseFontRec);
if Result then
begin
if AnsiCompareText(OriginalFaceName, LogFont.lfFaceName) <> 0 then
FontCharsetModified := True;
UpdateFromLogFont(LogFont);
FontDialog.Font.Color := rgbColors;
end;
end;
end;
function WinColorDialogExecute(ColorDialog: TColorDialog; CDFlags: DWORD = 0): Boolean;
var
ChooseColorRec: TChooseColor;
CustomColorsArray: TCustomColors;
const
ColorPrefix = 'Color';
procedure GetCustomColorsArray;
var
I: Integer;
begin
for I := 0 to MaxCustomColors - 1 do
ColorDialog.CustomColors.Values[ColorPrefix + Char(Ord('A') + I)] :=
Format('%.6x', [CustomColorsArray[I]]);
end;
procedure SetCustomColorsArray;
var
Value: string;
I: Integer;
begin
for I := 0 to MaxCustomColors - 1 do
begin
Value := ColorDialog.CustomColors.Values[ColorPrefix + Char(Ord('A') + I)];
if Value <> '' then
CustomColorsArray[I] := StrToInt('$' + Value) else
CustomColorsArray[I] := -1;
end;
end;
begin
with ChooseColorRec do
begin
SetCustomColorsArray;
lStructSize := SizeOf(ChooseColorRec);
hInstance := SysInit.HInstance;
rgbResult := ColorToRGB(ColorDialog.Color);
lpCustColors := @CustomColorsArray;
if CDFlags = 0 then
Flags := CC_FULLOPEN or CC_ANYCOLOR
else
Flags := CDFlags;
Flags := Flags or CC_RGBINIT;
lpfnHook := nil;
hWndOwner := GetActiveWindow;
Result := TaskModalDialog(@ChooseColor, ChooseColorRec);
if Result then
begin
ColorDialog.Color := rgbResult;
GetCustomColorsArray;
end;
end;
end;
function SelectDirectory(const Caption: string; const Root: WideString;
out Directory: string): Boolean;
var
WindowList: Pointer;
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
begin
Result := False;
Directory := '';
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(0, nil,
POleStr(Root), Eaten, RootItemIDList, Flags);
end;
with BrowseInfo do
begin
hwndOwner := 0;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
ulFlags := BIF_RETURNONLYFSDIRS;
end;
WindowList := DisableTaskWindows(0);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
EnableTaskWindows(WindowList);
end;
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Directory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
{$ENDIF}
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Button1, Button2, Button3: TMsgDlgBtn; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
const
ConfirmResName = 'MSGDLG_CONFIRM';
MessageBox_DefaultMask = $100;
MessageBox_EscapeMask = $200;
var
MB: QMessageBoxH;
B1, B2, B3: Integer;
Title: WideString;
FreeBitmap: Boolean;
DlgParent: QWidgetH;
DlgLabel: QLabelH;
begin
if Application.Terminated then
begin
Result := -1;
Exit;
end;
FreeBitmap := (Bitmap = nil) and (DlgType = mtConfirmation);
case DlgType of
mtCustom: Title := Caption;
mtInformation: Title := SMsgDlgInformation;
mtError: Title := SMsgDlgError;
mtWarning: Title := SMsgDlgWarning;
mtConfirmation:
begin
Title := SMsgDlgConfirm;
if Bitmap = nil then
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromResourceName(hInstance, ConfirmResName);
end;
end;
end;
B1 := Ord(Button1);
B2 := Ord(Button2);
B3 := Ord(Button3);
if Button1 = DefaultBtn then
B1 := B1 or MessageBox_DefaultMask
else if Button2 = DefaultBtn then
B2 := B2 or MessageBox_DefaultMask
else if Button3 = DefaultBtn then
B3 := B3 or MessageBox_DefaultMask;
if DlgType = mtConfirmation then
begin
DlgType := mtCustom;
Bitmap.Transparent := True;
end;
if (Screen.ActiveCustomForm <> nil) and Screen.ActiveCustomForm.HandleAllocated then
DlgParent := Screen.ActiveCustomForm.Handle
else
DlgParent := TOpenApplication(Application).AppWidget;
MB := QMessageBox_create(PWideString(@Title), PWideString(@Msg),
QMessageBoxIcon(DlgType), B1, B2, B3, DlgParent, nil, True, 0);
try
if Bitmap <> nil then
QMessageBox_setIconPixmap(MB, Bitmap.Handle);
if (X >= 0) and (Y >= 0) then QDialog_move(MB, X, Y);
DlgLabel := QLabelH(QObject_child(MB, 'text', nil));
if DlgLabel <> nil then
QLabel_setAlignment(DlgLabel, QLabel_alignment(DlgLabel)
or Integer(AlignmentFlags_WordBreak));
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
Result := QDialog_exec(MB);
finally
QForms.Application.ModalFinished(nil);
end;
finally
QMessageBox_destroy(MB);
if FreeBitmap then
Bitmap.Free;
end;
end;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
X, Y: Integer; DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer; overload;
var
Btns: array[0..2] of TMsgDlgBtn;
B: TMsgDlgBtn;
I: Integer;
begin
I := 0;
FillChar(Btns, SizeOf(Btns), 0);
{ Button order is hard-coded in Windows. We follow their conventions here. }
if Buttons = mbYesNoCancel then
begin
Btns[0] := mbYes;
Btns[1] := mbNo;
Btns[2] := mbCancel;
end;
if Buttons = mbYesNo then
begin
Btns[0] := mbYes;
Btns[1] := mbNo;
Btns[2] := mbNone;
end;
if Buttons = mbOkCancel then
begin
Btns[0] := mbOk;
Btns[1] := mbCancel;
Btns[2] := mbNone;
end;
if Buttons = mbAbortRetryIgnore then
begin
Btns[0] := mbAbort;
Btns[1] := mbRetry;
Btns[2] := mbIgnore;
end;
for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if B in Buttons then
begin
Inc(I);
if I > Ord(High(TMsgDlgBtn)) then
raise EInvalidOperation.CreateRes(@STooManyMessageBoxButtons);
end;
Result := MessageDlg(Caption, Msg, DlgType, Btns[0], Btns[1], Btns[2],
HelpCtx, X, Y, DefaultBtn, Bitmap);
end;
function MessageDlg(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultBtn: TMsgDlgBtn = mbNone;
Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Application.Title, Msg, DlgType, Buttons, HelpCtx, -1,
-1, DefaultBtn, Bitmap);
end;
function MessageDlg(const Caption: WideString; const Msg: WideString;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Caption, Msg, DlgType, Buttons, HelpCtx, -1, -1,
DefaultBtn, Bitmap);
end;
function MessageDlgPos(const Msg: WideString; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
DefaultBtn: TMsgDlgBtn = mbNone; Bitmap: TBitmap = nil): Integer;
begin
Result := MessageDlg(Application.Title, Msg, DlgType, Buttons, HelpCtx,
X, Y, DefaultBtn, Bitmap);
end;
procedure ShowMessage(const Msg: WideString);
begin
MessageDlg(Msg, mtCustom, [mbOk], 0);
end;
procedure ShowMessage(const Msg: WideString; Params: array of const);
begin
ShowMessageFmt(Msg, Params);
end;
procedure ShowMessageFmt(const Msg: WideString; Params: array of const);
begin
ShowMessage(Format(Msg, Params));
end;
procedure ShowMessagePos(const Msg: WideString; X, Y: Integer);
begin
MessageDlg(Application.Title, Msg, mtCustom, [mbOk], 0, X, Y);
end;
function InputQuery(const ACaption, APrompt: WideString;
var Value: WideString): Boolean;
var
RetVal: WideString;
begin
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
QInputDialog_getText(PWideString(@RetVal), PWideString(@ACaption),
PWideString(@APrompt), PWideString(@Value), @Result, nil, nil);
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
end;
function InputQuery(const ACaption, APrompt: WideString;
var Value: string): Boolean;
var
WValue: WideString;
begin
WValue := Value;
Result := InputQuery(ACaption, APrompt, WValue);
if Result then Value := WValue;
end;
function InputQuery(const ACaption, APrompt: WideString; var Value: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Boolean;
var
RetVal: Integer;
begin
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
RetVal := QInputDialog_getInteger(PWideString(@ACaption),
PWideString(@APrompt), Value, Min, Max, Increment, @Result, nil, nil);
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
end;
function InputQuery(const ACaption, APrompt: WideString; var Value: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Boolean;
var
RetVal: Double;
begin
SetCaptureControl(nil);
QForms.Application.ModalStarted(nil);
try
RetVal := QInputDialog_getDouble(PWideString(@ACaption), PWideString(@APrompt),
Value, Min, Max, Decimals, @Result, nil, nil);
if Result then Value := RetVal;
finally
QForms.Application.ModalFinished(nil);
end;
end;
function InputBox(const ACaption, APrompt, ADefault: WideString): WideString;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result);
end;
function InputBox(const ACaption, APrompt: WideString; ADefault: Integer;
Min: Integer = Low(Integer); Max: Integer = High(Integer);
Increment: Integer = 1): Integer;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result, Min, Max, Increment);
end;
function InputBox(const ACaption, APrompt: WideString; ADefault: Double;
Min: Double = Low(Integer); Max: Double = High(Integer);
Decimals: Integer = 1): Double;
begin
Result := ADefault;
InputQuery(ACaption, APrompt, Result, Min, Max, Decimals);
end;
{ TDialog }
procedure TDialog.DoClose;
begin
FWidth := Width;
FHeight := Height;
if Assigned(FOnClose) then FOnClose(Self);
end;
procedure TDialog.DoShow;
begin
if Assigned(FOnShow) then FOnShow(Self);
end;
function TDialog.Execute: Boolean;
var
ALeft, ATop, AWidth, AHeight: Integer;
GrabControl: TControl;
begin
GrabControl := GetMouseGrabControl;
try
SetMouseGrabControl(nil);
{ accept defaults if necessary. }
if not (sfLeft in FScaleFlags) then ALeft := GetPosition.X else ALeft := FPosition.X;
if not (sfTop in FScaleFlags) then ATop := GetPosition.Y else ATop := FPosition.Y;
if not (sfWidth in FScaleFlags) then AWidth := GetWidth else AWidth := FWidth;
if not (sfHeight in FScaleFlags) then AHeight := GetHeight else AHeight := FHeight;
SetBounds(ALeft, ATop, AWidth, AHeight);
Result := DoExecute;
finally
SetMouseGrabControl(GrabControl);
end;
end;
function TDialog.GetHeight: Integer;
begin
Result := GetBounds.Bottom;
end;
function TDialog.GetPosition: TPoint;
begin
Result.X := GetBounds.Left;
Result.Y := GetBounds.Top;
end;
function TDialog.GetWidth: Integer;
begin
Result := GetBounds.Right;
end;
procedure TDialog.SetHeight(const Value: Integer);
begin
SetBounds(Position.X, Position.Y, Width, Value);
Include(FScaleFlags, sfHeight);
end;
procedure TDialog.SetPosition(const Value: TPoint);
begin
SetBounds(Value.X, Value.Y, Width, Height);
Include(FScaleFlags, sfLeft);
Include(FScaleFlags, sfTop);
end;
procedure TDialog.SetTitle(const Value: WideString);
begin
FTitle := Value;
end;
procedure TDialog.SetWidth(const Value: Integer);
begin
SetBounds(Position.X, Position.Y, Value, Height);
Include(FScaleFlags, sfWidth);
end;
{ TQtDialog }
function TQtDialog.AppEventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
Result := False;
try
Result := (QEvent_type(Event) = QEventType_KeyPress)
and (QKeyEvent_key(QKeyEventH(Event)) = Application.HelpKey) and
(QWidget_topLevelWidget(QWidgetH(Sender)) = Handle);
if Result then InvokeHelp;
except
Application.HandleException(Self);
end;
end;
constructor TQtDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModal := True;
FShowing := False;
{$IFDEF MSWINDOWS}
FUseNative := True;
{$ENDIF}
end;
procedure TQtDialog.CreateHandle;
begin
{$IFDEF MSWINDOWS}
if UseNativeDialog then Exit;
{$ENDIF}
if FHandle = nil then
begin
CreateWidget;
InitWidget;
HookEvents;
if (FHandle = nil) then
raise EQtDialogException.CreateResFmt(@SInvalidCreateWidget, [ClassName]);
QClxObjectMap_add(QWidgetH(FHandle), Integer(Self));
end;
end;
procedure TQtDialog.CreateWidget;
begin
FHandle := QDialog_create(nil, nil, FModal, WidgetFlags);
FHooks := QWidget_hook_create(FHandle);
end;
procedure TQtDialog.DestroyedHook;
begin
try
QClxObjectMap_remove(FHandle);
FHandle := nil;
QObject_hook_destroy(FHooks);
FHooks := nil;
Application.EnableQtAccelerators := False;
except
Application.HandleException(Self);
end;
end;
function TQtDialog.DoExecute: Boolean;
begin
QDialog_show(Handle);
if FModal then
begin
try
Result := QDialog_result(Handle) = Integer(QDialogDialogCode_Accepted);
finally
QDialog_destroy(Handle);
end;
end
else
Result := True;
end;
function TQtDialog.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
try
Result := False;
case QEvent_type(Event) of
QEventType_WindowActivate:
{ for modeless Qt dialogs}
Application.EnableQtAccelerators := True;
QEventType_WindowDeactivate:
{ for modeless Qt dialogs}
Application.EnableQtAccelerators := False;
QEventType_Show:
begin
Application.EnableQtAccelerators := True;
FShowing := True;
DoShow;
end;
QEventType_Hide:
begin
Application.EnableQtAccelerators := False;
DoClose;
FShowing := False;
end;
end;
except
Application.HandleException(Self);
Result := False;
end;
end;
function TQtDialog.GetHandle: QDialogH;
begin
{$IFDEF MSWINDOWS}
if not UseNativeDialog then
{$ENDIF}
HandleNeeded;
Result := FHandle;
end;
function TQtDialog.GetHooks: QObject_hookH;
begin
HandleNeeded;
Result := FHooks;
end;
function TQtDialog.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TQtDialog.HandleNeeded;
begin
if FHandle = nil then CreateHandle;
end;
procedure TQtDialog.HookEvents;
var
Method: TMethod;
begin
if FHooks = nil then
begin
Assert(FHandle <> nil);
FHooks := QObject_hook_create(Handle);
end;
TEventFilterMethod(Method) := EventFilter;
Qt_hook_hook_events(FHooks, Method);
QObject_destroyed_event(Method) := Self.DestroyedHook;
QObject_hook_hook_destroyed(FHooks, Method);
end;
procedure TQtDialog.InitWidget;
begin
Application.EnableQtAccelerators := True;
end;
procedure TQtDialog.InvokeHelp;
begin
case HelpType of
htKeyword:
Application.KeywordHelp(HelpKeyword);
htContext:
Application.ContextHelp(HelpContext);
end;
end;
procedure TQtDialog.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if not (csDesigning in ComponentState) and HandleAllocated then
begin
QWidget_move(Handle, ALeft, ATop);
QWidget_resize(Handle, AWidth, AHeight);
end;
FPosition.X := ALeft;
FPosition.Y := ATop;
FWidth := AWidth;
FHeight := AHeight;
end;
procedure TQtDialog.SetTitle(const Value: WideString);
begin
inherited;
if {$IFDEF MSWINDOWS} not UseNativeDialog and {$ENDIF} HandleAllocated then
QWidget_setCaption(Handle, PWideString(@FTitle));
end;
function TQtDialog.WidgetFlags: Integer;
begin
Result := Integer(WidgetFlags_WStyle_DialogBorder) or
Integer(WidgetFlags_WStyle_Title) or
Integer(WidgetFlags_WStyle_Customize) or
Integer(WidgetFlags_WStyle_SysMenu) or
Integer(WidgetFlags_WStyle_ContextHelp);
end;
procedure TQtDialog.DestroyWidget;
begin
if FHandle <> nil then QObject_destroy(FHandle);
FHandle := nil;
end;
destructor TQtDialog.Destroy;
begin
if FHandle <> nil then
begin
DestroyWidget;
FHandle := nil;
end;
inherited Destroy;
end;
function TQtDialog.GetBounds: TRect;
begin
if HandleAllocated {$IFDEF MSWINDOWS} and not UseNativeDialog {$ENDIF} then
begin
QWidget_geometry(Handle, @Result);
Result.Right := Result.Right - Result.Left;
Result.Bottom := Result.Bottom - Result.Top;
end
else
Result := Rect(FPosition.X, FPosition.Y, FWidth, FHeight);
end;
procedure TQtDialog.DoShow;
begin
{$IFDEF MSWINDOWS}
if not UseNativeDialog then
{$ENDIF}
QWidget_setCaption(Handle, PWideString(@FTitle));
inherited;
end;
{$IFDEF MSWINDOWS}
function TQtDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := False;
end;
{$ENDIF}
function TQtDialog.Execute: Boolean;
var
AppHook: QObject_hookH;
Method: TMethod;
{$IFDEF MSWINDOWS}
GrabControl: TControl;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
if UseNativeDialog then
begin
GrabControl := GetMouseGrabControl;
try
SetMouseGrabControl(nil);
Result := NativeExecute(FNativeFlags);
finally
SetMouseGrabControl(GrabControl);
end;
end
else
{$ENDIF}
if FShowing then
begin
QWidget_raise(Handle);
Result := True;
end
else
begin
Application.ModalStarted(Self);
try
HandleNeeded;
AppHook := QObject_Hook_create(Application.Handle);
try
TEventFilterMethod(Method) := AppEventFilter;
Qt_hook_hook_events(AppHook, Method);
Result := inherited Execute;
finally
QObject_hook_destroy(AppHook);
if FModal then DestroyWidget;
end;
finally
Application.ModalFinished(Self);
end;
end;
end;
{ TOpenDialog }
function ConvertSeparators(const S: string): string;
begin
{$IFDEF MSWINDOWS}
Result := StringReplace(S, '/', '\', [rfReplaceAll]);
{$ENDIF}
{$IFDEF LINUX}
Result := S;
{$ENDIF}
end;
procedure TOpenDialog.CanCloseHook(canClose: PBoolean);
procedure GetFilename;
var
WFilename: WideString;
begin
QClxFileDialog_selectedFile(Handle, PWideString(@WFilename));
FFilename := ExpandFileName(ConvertSeparators(WFilename));
FFiles.Add(FFilename);
end;
var
QFilesH: QStringListH;
I: Integer;
WS, SelExt, ThisExt: WideString;
begin
try
FTempFilename := FFilename;
FTempFiles.Assign(FFiles);
if ofAllowMultiSelect in FOptions then
begin
QFilesH := QStringList_create;
try
QClxFileDialog_selectedFiles(Handle, QFilesH);
FFiles.Clear;
if QOpenStringList_count(QOpenStringListH(QFilesH)) = 0 then
GetFilename
else
for I := 0 to QOpenStringList_count(QOpenStringListH(QFilesH)) - 1 do
begin
QOpenStringList_value(QOpenStringListH(QFilesH), PWideString(@WS),
I);
FFiles.Add(ExpandFileName(ConvertSeparators(WS)));
end;
finally
QStringList_destroy(QFilesH);
end;
FFilename := FFiles[0];
end else
GetFilename;
if FDefaultExt <> '' then
begin
QClxFileDialog_selectedExt(Handle, @SelExt);
begin
if SelExt = '' then
SelExt := FDefaultExt;
SelExt := '.' + SelExt;
if not FileExists(FFilename) then
begin
ThisExt := ExtractFileExt(FFilename);
if Length(ThisExt) > 0 then Delete(ThisExt, 1, 1);
if not QClxFileDialog_isRegisteredExtension(Handle, @ThisExt)
and (AnsiCompareStr(ExtractFileExt(FFilename), SelExt) <> 0) then
FFilename := FFilename + SelExt;
end;
for I := 0 to FFiles.Count - 1 do
begin
if not FileExists(FFiles[I]) then
begin
ThisExt := ExtractFileExt(FFiles[I]);
if Length(ThisExt) > 0 then Delete(ThisExt, 1, 1);
if not QClxFileDialog_isRegisteredExtension(Handle, @ThisExt)
and (AnsiCompareStr(ExtractFileExt(FFiles[I]), SelExt) <> 0) then
FFiles[I] := FFiles[I] + SelExt;
end;
end;
end;
end;
if (Self is TSaveDialog) and (ofOverwritePrompt in Options) and FileExists(FFilename) then
canClose^ := MessageDlg(Format(SOverwriteCaption, [FFilename]),
Format(SOverwriteText, [FFilename]), mtWarning, [mbNo, mbYes], 0, mbNo) = mrYes
else if canClose^ and ((ofPathMustExist in Options) or (ofFileMustExist in Options)) then
for I := 0 to FFiles.Count - 1 do
begin
if ofFileMustExist in Options then
begin
canClose^ := FileExists(FFiles[I]);
if not canClose^ then
begin
MessageDlg(Title, Format(SFileMustExist, [FFiles[I]]),
mtCustom, [mbOk], 0);
QWidget_show(Handle);
end;
end
else if ofPathMustExist in Options then
begin
canClose^ := DirectoryExists(ExtractFilePath(FFiles[I]));
if not canClose^ then
begin
MessageDlg(Title, Format(SPathMustExist, [ExtractFilePath(FFiles[I])]),
mtCustom, [mbOk], 0);
QWidget_show(Handle);
end;
end;
end;
if canClose^ then DoCanClose(canClose^);
if not canClose^ then
begin
FFiles.Assign(FTempFiles);
FFilename := FTempFilename;
end;
except
Application.HandleException(Self);
end;
end;
constructor TOpenDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFiles := TStringList.Create;
FHistoryList := TStringList.Create;
FFilterIndex := 1;
FTitle := SOpen;
FTempFiles := TStringList.Create;
FOptions := [ofEnableSizing];
FWidth := 550;
FHeight := 350;
end;
procedure TOpenDialog.CreateWidget;
begin
FHandle := QClxFileDialog_create(nil, True, WidgetFlags);
FHooks := QClxFileDialog_hook_create(FHandle);
end;
procedure TOpenDialog.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
end;
destructor TOpenDialog.Destroy;
begin
FFiles.Free;
FHistoryList.Free;
FTempFiles.Free;
inherited Destroy;
end;
procedure TOpenDialog.DirEnteredHook(P1: PWideString);
begin
try
DoFolderChange(ConvertSeparators(P1^));
except
Application.HandleException(Self);
end;
end;
procedure TOpenDialog.DoCanClose(var CanClose: Boolean);
begin
if Assigned(FOnCanClose) then FOnCanClose(Self, CanClose);
end;
function TOpenDialog.DoExecute: Boolean;
begin
SetOptions;
Result := QDialog_exec(Handle) = Integer(QDialogDialogCode_Accepted);
if Result then RetrieveOptions;
end;
function TOpenDialog.DoFileAdd(const Filename: string; const Readable, Writeable,
Executable: Boolean): Boolean;
begin
Result := True;
if Assigned(FOnFileAdd) then FOnFileAdd(Self, Filename, Readable, Writeable,
Executable, Result);
end;
procedure TOpenDialog.DoFolderChange(const Dir: string);
begin
if Assigned(FOnFolderChange) then
FOnFolderChange(Self, ConvertSeparators(Dir));
end;
procedure TOpenDialog.FileAddHook(Filename: PString; const Readable, Writeable,
Executable: Boolean; var CanAdd: Boolean);
begin
if Filename <> nil then
CanAdd := DoFileAdd(Filename^, Readable, Writeable, Executable);
end;
procedure TOpenDialog.DoSelected(const Filename: string);
begin
{$IFDEF LINUX}
FFilename := Filename;
{$ENDIF}
if Assigned(FOnSelected) then FOnSelected(Self, Filename);
end;
procedure TOpenDialog.FileHighlightedHook(P1: PWideString);
begin
try
DoSelected(ConvertSeparators(P1^));
except
Application.HandleException(Self);
end;
end;
procedure TOpenDialog.FilterChangedHook(Index: Integer);
begin
FFilterIndex := Index + 1;
end;
function TOpenDialog.GetHandle: QClxFileDialogH;
begin
HandleNeeded;
Result := QClxFileDialogH(FHandle);
end;
type
QClxFileDialog_fileAdd_Event = procedure(Filename: PString; const Readable, Writeable,
Executable: Boolean; var CanAdd: Boolean) of object cdecl;
procedure TOpenDialog.HookEvents;
var
Method: TMethod;
begin
QClxFileDialog_fileHighlighted_Event(Method) := FileHighlightedHook;
QClxFileDialog_hook_hook_fileHighlighted(QClxFileDialog_hookH(Hooks), Method);
QClxFileDialog_hook_hook_fileSelected(QClxFileDialog_hookH(Hooks), Method);
QClxFileDialog_dirEntered_Event(Method) := DirEnteredHook;
QClxFileDialog_hook_hook_DirEntered(QClxFileDialog_hookH(Hooks), Method);
QClxFileDialog_closeRequest_Event(Method) := CanCloseHook;
QClxFileDialog_hook_hook_closeRequest(QClxFileDialog_hookH(Hooks), Method);
QClxFileDialog_filterChanged_Event(Method) := FilterChangedHook;
QClxFileDialog_hook_hook_filterChanged(QClxFileDialog_hookH(Hooks), Method);
if Assigned(FOnFileAdd) then
begin
//FileAddHook does not operate off a signal for performance reasons; it's
//a direct callback which doesn't use emit().
QClxFileDialog_fileAdd_Event(Method) := FileAddHook;
QClxFileDialog_hook_addFile(QClxFileDialogH(FHandle), Method);
end;
inherited HookEvents;
end;
{$IFDEF MSWINDOWS}
function TOpenDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFileDialogExecute(Self, @GetOpenFileName, Flags);
end;
{$ENDIF}
procedure TOpenDialog.Refresh;
begin
if Handle <> nil then QClxFileDialog_rereadDir(Handle);
end;
procedure TOpenDialog.RetrieveOptions;
var
ViewMode: QClxFileDialogViewMode;
begin
if not (ofNoChangeDir in FOptions) then
FSaveDir := ExtractFilePath(FFilename);
SetCurrentDir(FSaveDir);
if AnsiCompareStr(ExtractFileExt(FFilename), FDefaultExt) <> 0 then
Include(FOptions, ofExtensionDifferent)
else
Exclude(FOptions, ofExtensionDifferent);
ViewMode := QClxFileDialog_viewMode(Handle);
if ViewMode = QClxFileDialogViewMode_Detail then
Include(FOptions, ofViewDetail)
else
Exclude(FOptions, ofViewDetail);
end;
procedure TOpenDialog.SetHistoryList(Value: TStrings);
begin
end;
procedure TOpenDialog.SetOptions;
procedure SetFilters;
var
QSL: QStringListH;
P, P0: PChar;
AFilter: string;
WFilter: WideString;
begin
QClxFileDialog_setFilters(Handle, NullWideStr); // is this necessary?
QSL := QStringList_create;
try
P0 := @FFilter[1];
if FFilter <> '' then
begin
P := AnsiStrScan(PChar(FFilter), '|');
while P <> nil do
begin
SetString(AFilter, P0, P - P0);
WFilter := AFilter;
QOpenStringList_append(QOpenStringListH(QSL), PWideString(@WFilter));
Inc(P);
P0 := P;
P := AnsiStrScan(P, '|');
end;
end;
SetString(AFilter, P0, @FFilter[Length(FFilter)+1] - P0);
WFilter := AFilter;
QOpenStringList_append(QOpenStringListH(QSL), PWideString(@WFilter));
QClxFileDialog_setFilters(Handle, QSL);
finally
QStringList_destroy(QSL);
end;
end;
var
UseFilename: Boolean;
FilePath: WideString;
WInitialDir: WideString;
WFilename: WideString;
WDefaultExt: WideString;
begin
FFiles.Clear;
FSaveDir := GetCurrentDir;
WInitialDir := FInitialDir;
if (Length(WInitialDir) > 0) and (WInitialDir[Length(WInitialDir)] <> PathDelim) then
WInitialDir := WInitialDir + PathDelim;
WFilename := FFilename;
WDefaultExt := FDefaultExt;
FilePath := ExtractFilePath(WFilename);
UseFilename := DirectoryExists(FilePath);
if UseFilename then
WInitialDir := FilePath;
QClxFileDialog_setDir(Handle, PWideString(@WInitialDir));
WFilename := ExtractFileName(WFilename);
QClxFileDialog_setEditText(Handle, @WFilename);
QClxFileDialog_setDefaultExt(Handle, @WDefaultExt);
QWidget_setCaption(Handle, PWideString(@FTitle));
if ofAllowMultiSelect in FOptions then
QClxFileDialog_setMode(Handle, QClxFileDialogMode_ExistingFiles)
else
QClxFileDialog_setMode(Handle, QClxFileDialogMode_ExistingFile);
if ofViewDetail in FOptions then
QClxFileDialog_setViewMode(Handle, QClxFileDialogViewMode_Detail);
QClxFileDialog_setShowHiddenFiles(Handle, ofShowHidden in FOptions);
SetFilters;
QClxFileDialog_setFilterIndex(Handle, FFilterIndex-1);
end;
function TOpenDialog.WidgetFlags: Integer;
begin
if (ofEnableSizing in Options) then
Result := 0
else
Result := inherited WidgetFlags;
end;
{ TSaveDialog }
constructor TSaveDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTitle := SSave;
end;
{$IFDEF MSWINDOWS}
function TSaveDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFileDialogExecute(Self, @GetSaveFileName, Flags);
end;
{$ENDIF}
procedure TSaveDialog.SetOptions;
begin
inherited SetOptions;
QClxFileDialog_setMode(Handle, QClxFileDialogMode_AnyFile);
end;
{ TFontDialog }
constructor TFontDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFont := TFont.Create;
end;
destructor TFontDialog.Destroy;
begin
inherited Destroy;
FFont.Free;
end;
function TFontDialog.DoExecute: Boolean;
var
QFont: QFontH;
begin
QFont := QFont_create;
try
QFontDialog_getFont(QFont, @Result, FFont.Handle, Screen.ActiveWidget, nil);
if Result then
begin
FFont.Handle := QFont;
FFont.OwnHandle;
end;
finally
if not Result then QFont_destroy(QFont);
end;
end;
{$IFDEF MSWINDOWS}
function TFontDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinFontDialogExecute(Self, Flags);
end;
{$ENDIF}
procedure TFontDialog.SetFont(Value: TFont);
begin
FFont.Assign(Value);
end;
{ TColorDialog }
constructor TColorDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCustomColors := TStringList.Create;
end;
destructor TColorDialog.Destroy;
begin
FCustomColors.Free;
inherited Destroy;
end;
function TColorDialog.DoExecute: Boolean;
const
ColorPrefix = 'Color';
procedure GetCustomColors;
var
I: Integer;
Color: QRgb;
begin
Color := 0;
for I := 0 to CustomColorCount - 1 do
begin
QColorDialog_customColor(@Color, I);
FCustomColors.Values[ColorPrefix + Char(Ord('A') + I)] :=
Format('%.6x', [Color]);
end;
end;
procedure SetCustomColors;
var
Value: string;
I: Integer;
CustomColor: QRgb;
begin
for I := 0 to CustomColorCount - 1 do
begin
Value := FCustomColors.Values[ColorPrefix + Char(Ord('A') + I)];
if Value <> '' then
CustomColor := QRgb(StrToInt('$' + Value))
else
CustomColor := QRgb(0);
QColorDialog_setCustomColor(I, @CustomColor);
end;
end;
var
QC: QColorH;
begin
SetCustomColors;
QC := QColor_create;
try
QColorDialog_getColor(QC, QColor(FColor), Screen.ActiveWidget, nil);
Result := QColor_isValid(QC);
if Result then
begin
FColor := QColorColor(QC);
GetCustomColors;
end;
finally
QColor_destroy(QC);
end;
end;
{$IFDEF MSWINDOWS}
function TColorDialog.NativeExecute(Flags: Integer): Boolean;
begin
Result := WinColorDialogExecute(Self, Flags);
end;
{$ENDIF}
procedure TColorDialog.SetCustomColors(Value: TStrings);
begin
FCustomColors.Assign(Value);
end;
{ TDialogForm }
procedure TDialogForm.InvokeHelp;
begin
if ((HelpType = htKeyword) and (HelpKeyword = '')) or
((HelpType = htContext) and (HelpContext = 0)) then
FDialog.InvokeHelp
else
inherited;
end;
{ TCustomDialog }
function TCustomDialog.DoExecute: Boolean;
begin
Result := True;
DoShow;
if FModal then
Result := FForm.ShowModal = mrOK
else
FForm.Show;
end;
procedure TCustomDialog.Close(Sender: TObject; var Action: TCloseAction);
begin
DoClose;
end;
procedure TCustomDialog.DoClose;
begin
FWidth := FForm.Width;
FHeight := FForm.Height;
FPosition.Y := FForm.Top;
FPosition.X := FForm.Left;
inherited;
end;
procedure TCustomDialog.DoShow;
begin
FForm.Caption := FTitle;
FForm.OnClose := Self.Close;
inherited;
end;
procedure TCustomDialog.InvokeHelp;
begin
case HelpType of
htKeyword:
Application.KeywordHelp(HelpKeyword);
htContext:
Application.ContextHelp(HelpContext);
end;
end;
procedure TCustomDialog.SetTitle(const Value: WideString);
begin
inherited;
if FForm <> nil then FForm.Caption := Value;
end;
procedure TCustomDialog.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if not (csDesigning in ComponentState) and (FForm <> nil) then
FForm.SetBounds(ALeft, ATop, AWidth, AHeight);
FPosition.X := ALeft;
FPosition.Y := ATop;
FWidth := AWidth;
FHeight := AHeight;
end;
function TCustomDialog.GetBounds: TRect;
begin
if FForm <> nil then
Result := Rect(FForm.Left, FForm.Top, FForm.Width, FForm.Height)
else
Result := Rect(FPosition.X, FPosition.Y, FWidth, FHeight);
end;
function TCustomDialog.Execute: Boolean;
begin
if FForm = nil then
FForm := CreateForm;
Result := inherited Execute;
end;
{ TFindDialog }
constructor TFindDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModal := False;
FTitle := SFindTitle;
FOptions := [frDown];
Position := Point(Screen.Width div 3, Screen.Height div 3);
end;
function TFindDialog.CreateForm: TDialogForm;
begin
Result := TFindDialogForm.Create(Self);
Result.FDialog := Self;
end;
procedure TFindDialog.DoShow;
begin
with TFindDialogForm(FForm) do
begin
FindEdit.Text := FindText;
ActiveControl := FindEdit;
WholeWord.Visible := not (frHideWholeWord in FOptions);
WholeWord.Checked := frWholeWord in FOptions;
WholeWord.Enabled := not (frDisableWholeWord in FOptions);
MatchCase.Visible := not (frHideMatchCase in FOptions);
MatchCase.Checked := frMatchCase in Options;
MatchCase.Enabled := not (frDisableMatchCase in FOptions);
if frDown in FOptions then Direction.ItemIndex := 1 else Direction.ItemIndex := 0;
Direction.Enabled := not (frDisableUpDown in FOptions);
Direction.Visible := not (frHideUpDown in FOptions);
Help.Visible := frShowHelp in FOptions;
end;
inherited DoShow;
end;
procedure TFindDialog.Find;
begin
if Assigned(FOnFind) then FOnFind(Self);
end;
type
TWidgetAccess = class(TWidgetControl);
function TextWidth(Control: TWidgetControl; const Text: WideString): Integer;
var
FM: QFontMetricsH;
begin
FM := QFontMetrics_create(TWidgetAccess(Control).Font.Handle);
try
QWidget_FontMetrics(Control.Handle, FM);
Result := QFontMetrics_width(FM, PWideString(@Text), -1);
finally
QFontMetrics_destroy(FM);
end;
end;
procedure TFindDialog.SetFindText(const Value: WideString);
begin
if FindText <> Value then
begin
FFindText := Value;
if FForm <> nil then
TFindDialogForm(FForm).FindEdit.Text := Value;
end;
end;
{ TFindDialogForm }
procedure TFindDialogForm.ButtonPress(Sender: TObject);
begin
with TFindDialog(FDialog) do
if Sender = FindNext then
begin
Include(FOptions, frFindNext);
FFindText := FindEdit.Text;
Find;
end
else if Sender = Cancel then
begin
SetDialogOption(frFindNext, False);
Exclude(FOptions, frFindNext);
Exclude(FOptions, frReplace);
Self.Close;
end;
end;
procedure TFindDialogForm.CheckboxCheck(Sender: TObject);
var
Option: TFindOption;
begin
if Sender = WholeWord then
Option := frWholeWord
else
Option := frMatchCase;
if (Sender as TCheckBox).Checked then
Include(TFindDialog(FDialog).FOptions, Option)
else
Exclude(TFindDialog(FDialog).FOptions, Option);
end;
constructor TFindDialogForm.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
BorderStyle := fbsDialog;
DialogUnits := Types.Point(6, 13);
SetBounds(FLeft, FTop, MulDiv(245, DialogUnits.x, 4),
MulDiv(65, DialogUnits.y, 8));
FindLabel := TLabel.Create(Self);
with FindLabel do
begin
Parent := Self;
Caption := SFindWhat;
AutoSize := True;
SetBounds(MulDiv(5, DialogUnits.y, 8), MulDiv(10, DialogUnits.x, 4),
TextWidth(FindLabel, Caption), Font.Height + 2);
Visible := True;
Name := 'FindLabel';
end;
FindEdit := TEdit.Create(Self);
with FindEdit do
begin
Parent := Self;
HandleNeeded;
AutoSize := True;
Left := FindLabel.Left + FindLabel.Width + 5;
Top := FindLabel.Top + ((FindLabel.Height - Height) div 2);
Width := MulDiv(135, DialogUnits.x, 4);
FindLabel.FocusControl := FindEdit;
Visible := True;
OnChange := EditChanged;
AutoSelect := True;
TabOrder := 0;
// Name := 'FindEdit';
end;
WholeWord := TCheckBox.Create(Self);
with WholeWord do
begin
Parent := Self;
Caption := SWholeWord;
Left := FindLabel.Left;
Top := MulDiv(30, DialogUnits.y, 8);
Width := TextWidth(WholeWord, Caption) + 20;
Height := Font.Height + 2;
OnClick := CheckBoxCheck;
Name := 'WholeWordCheckbox';
TabOrder := 1;
end;
MatchCase := TCheckBox.Create(Self);
with MatchCase do
begin
Parent := Self;
Caption := SMatchCase;
Left := FindLabel.Left;
Top := WholeWord.Top + WholeWord.Height + 7;
Width := TextWidth(MatchCase, Caption) + 20;
Height := Font.Height + 2;
OnClick := CheckBoxCheck;
Name := 'MatchCaseCheckbox';
TabOrder := 2;
end;
Direction := TRadioGroup.Create(Self);
with Direction do
begin
Parent := Self;
Caption := SDirection;
Left := WholeWord.Left + WholeWord.Width + 5;
Top := FindEdit.Top + FindEdit.Height + 5;
Width := (FindEdit.Left + FindEdit.Width) - Left;
Height := (MatchCase.Top + MatchCase.Height) - Top + 5;
Orientation := orHorizontal;
Items.Add(SUp);
Items.Add(SDown);
OnClick := Self.DirectionClick;
Name := 'DirectionRadioGroup';
TabStop := True;
TabOrder := 3;
end;
FindNext := TButton.Create(Self);
with FindNext do
begin
Parent := Self;
Caption := SFindNext;
Enabled := False;
Left := FindEdit.Left + FindEdit.Width + 10;
Top := FindEdit.Top - 1;
Height := 24;
Width := 75;
Default := True;
OnClick := Self.ButtonPress;
Visible := True;
Name := 'FindNextButton';
TabOrder := 4;
end;
Cancel := TButton.Create(Self);
with Cancel do
begin
Parent := Self;
Caption := SCancel;
Left := FindNext.Left;
Top := FindNext.Top + FindNext.Height + 3;
Width := FindNext.Width;
Height := FindNext.Height;
Cancel := True;
OnClick := Self.ButtonPress;
Visible := True;
Name := 'CancelButton';
TabOrder := 5;
end;
Help := TButton.Create(Self);
with Help do
begin
Parent := Self;
Caption := SHelp;
Left := FindNext.Left;
Top := Self.Cancel.Top + Self.Cancel.Height + 3;
Width := FindNext.Width;
Height := FindNext.Height;
OnClick := Self.ButtonPress;
Name := 'HelpButton';
TabOrder := 6;
end;
Width := FindNext.Left + FindNext.Width + 10;
end;
procedure TFindDialogForm.DirectionClick(Sender: TObject);
begin
case Direction.ItemIndex of
0: SetDialogOption(frDown, False);
1: SetDialogOption(frDown, True);
end;
end;
procedure TFindDialogForm.EditChanged(Sender: TObject);
begin
FindNext.Enabled := FindEdit.Text <> '';
end;
procedure TFindDialogForm.SetDialogOption(Option: TFindOption;
Value: Boolean);
begin
if Value then
Include(TFindDialog(FDialog).FOptions, Option)
else
Exclude(TFindDialog(FDialog).FOptions, Option);
end;
{ TReplaceDialog }
constructor TReplaceDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTitle := SReplaceTitle;
end;
function TReplaceDialog.CreateForm: TDialogForm;
begin
Result := TReplaceDialogForm.Create(Self);
Result.FDialog := Self;
end;
procedure TReplaceDialog.DoShow;
begin
with TReplaceDialogForm(FForm) do
ReplaceEdit.Text := FReplaceText;
inherited;
end;
procedure TReplaceDialog.Replace;
begin
if Assigned(FOnReplace) then FOnReplace(Self);
end;
procedure TReplaceDialog.SetReplaceText(const Value: WideString);
begin
if ReplaceText <> Value then
begin
FReplaceText := Value;
if FForm <> nil then
TReplaceDialogForm(FForm).ReplaceEdit.Text := FReplaceText;
end;
end;
{ TReplaceDialogForm }
procedure TReplaceDialogForm.ButtonPress(Sender: TObject);
begin
if Sender = ReplaceBtn then
begin
SetDialogOption(frReplace, True);
SetDialogOption(frReplaceAll, False);
end
else if Sender = ReplaceAll then
begin
SetDialogOption(frReplaceAll, True);
SetDialogOption(frReplace, False);
end;
TReplaceDialog(FDialog).FFindText := FindEdit.Text;
TReplaceDialog(FDialog).FReplaceText := ReplaceEdit.Text;
if (Sender = ReplaceBtn) or (Sender = ReplaceAll) then
TReplaceDialog(FDialog).Replace;
inherited ButtonPress(Sender);
end;
constructor TReplaceDialogForm.Create(AOwner: TComponent);
begin
inherited;
Height := MulDiv(95, DialogUnits.y, 8);
ReplaceBtn := TButton.Create(Self);
with ReplaceBtn do
begin
Parent := Self;
HandleNeeded;
SetBounds(Self.Cancel.Left, Self.Cancel.Top, Self.Cancel.Width,
Self.Cancel.Height);
Caption := SReplace;
OnClick := ButtonPress;
Visible := True;
Enabled := False;
Name := 'ReplaceButton';
TabOrder := 5;
end;
ReplaceAll := TButton.Create(Self);
with ReplaceAll do
begin
Parent := Self;
HandleNeeded;
SetBounds(FindNext.Left, ReplaceBtn.Top + ReplaceBtn.Height + 3,
FindNext.Width, FindNext.Height);
Caption := SReplaceAll;
OnClick := ButtonPress;
Visible := True;
Enabled := False;
Name := 'ReplaceAllButton';
TabOrder := 6;
end;
ReplaceLabel := TLabel.Create(Self);
with ReplaceLabel do
begin
Parent := Self;
Caption := SReplaceWith;
SetBounds(FindLabel.Left, FindEdit.Top + FindEdit.Height + 13,
TextWidth(ReplaceLabel, ReplaceLabel.Caption), Font.Height + 4);
Visible := True;
Name := 'ReplaceLabel';
end;
FindEdit.Left := ReplaceLabel.Left + ReplaceLabel.Width + 5;
FindEdit.Width := MulDiv(125, DialogUnits.x, 4);
Cancel.Top := ReplaceAll.Top + ReplaceAll.Height + 3;
WholeWord.Top := MulDiv(50, DialogUnits.Y, 8);
MatchCase.Top := WholeWord.Top + WholeWord.Height + 10;
ReplaceEdit := TEdit.Create(Self);
with ReplaceEdit do
begin
Parent := Self;
HandleNeeded;
AutoSize := True;
Left := ReplaceLabel.Left + ReplaceLabel.Width + 5;
Top := ReplaceLabel.Top + ((ReplaceLabel.Height - Height) div 2);
Width := FindEdit.Width;
Visible := True;
Name := 'ReplaceEdit';
TabOrder := 1;
end;
ReplaceLabel.FocusControl := ReplaceEdit;
Direction.Top := WholeWord.Top - 5;
Help.Top := Cancel.Top + Cancel.Height + 3;
end;
procedure TReplaceDialogForm.EditChanged(Sender: TObject);
begin
inherited EditChanged(Sender);
ReplaceBtn.Enabled := FindEdit.Text <> '';
ReplaceAll.Enabled := FindEdit.Text <> '';
end;
initialization
CustomColorCount := QColorDialog_customCount;
StartClassGroup(TControl);
ActivateClassGroup(TControl);
GroupDescendentsWith(TDialog, TControl);
end.
|
unit Serv_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. }
{ SetParam Demo Server Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_Serv: TGUID = '{518F9D60-F90A-11D0-9FFC-00A0248E4B9A}';
const
{ Component class GUIDs }
Class_SetParamDemo: TGUID = '{518F9D64-F90A-11D0-9FFC-00A0248E4B9A}';
type
{ Forward declarations: Interfaces }
ISetParamDemo = interface;
ISetParamDemoDisp = dispinterface;
{ Forward declarations: CoClasses }
SetParamDemo = ISetParamDemo;
{ Dispatch interface for SetParamDemo Object }
ISetParamDemo = interface(IDataBroker)
['{518F9D63-F90A-11D0-9FFC-00A0248E4B9A}']
function Get_Events: IProvider; safecall;
property Events: IProvider read Get_Events;
end;
{ DispInterface declaration for Dual Interface ISetParamDemo }
ISetParamDemoDisp = dispinterface
['{518F9D63-F90A-11D0-9FFC-00A0248E4B9A}']
function GetProviderNames: OleVariant; dispid 22929905;
property Events: IProvider readonly dispid 1;
end;
{ SetParamDemoObject }
CoSetParamDemo = class
class function Create: ISetParamDemo;
class function CreateRemote(const MachineName: string): ISetParamDemo;
end;
implementation
uses ComObj;
class function CoSetParamDemo.Create: ISetParamDemo;
begin
Result := CreateComObject(Class_SetParamDemo) as ISetParamDemo;
end;
class function CoSetParamDemo.CreateRemote(const MachineName: string): ISetParamDemo;
begin
Result := CreateRemoteComObject(MachineName, Class_SetParamDemo) as ISetParamDemo;
end;
end.
|
unit fGridCases;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
fGridBaseRep, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator,
dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog,
Data.DB, cxDBData, frxClass, frxDBSet, System.ImageList, Vcl.ImgList,
cxImageList, System.Actions, Vcl.ActnList, dxBar, cxClasses, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, Vcl.StdCtrls, REST.Types, 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,
REST.Response.Adapter, REST.Client, Data.Bind.Components,
Data.Bind.ObjectScope, Vcl.ExtCtrls, cxContainer, cxTextEdit, cxDBEdit,
cxLabel;
type
TfrmGridCases = class(TfrmGridBaseRep)
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter;
FDMemTable1: TFDMemTable;
FDMemTable1ConfirmDate: TWideStringField;
FDMemTable1No: TWideStringField;
FDMemTable1Age: TWideStringField;
FDMemTable1Gender: TWideStringField;
FDMemTable1GenderEn: TWideStringField;
FDMemTable1Nation: TWideStringField;
FDMemTable1NationEn: TWideStringField;
FDMemTable1Province: TWideStringField;
FDMemTable1ProvinceId: TWideStringField;
FDMemTable1District: TWideStringField;
FDMemTable1ProvinceEn: TWideStringField;
cxDBTV1ConfirmDate: TcxGridDBColumn;
cxDBTV1No: TcxGridDBColumn;
cxDBTV1Age: TcxGridDBColumn;
cxDBTV1Gender: TcxGridDBColumn;
cxDBTV1GenderEn: TcxGridDBColumn;
cxDBTV1Nation: TcxGridDBColumn;
cxDBTV1NationEn: TcxGridDBColumn;
cxDBTV1Province: TcxGridDBColumn;
cxDBTV1ProvinceId: TcxGridDBColumn;
cxDBTV1District: TcxGridDBColumn;
cxDBTV1ProvinceEn: TcxGridDBColumn;
dxBarButton6: TdxBarButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmGridCases: TfrmGridCases;
implementation
uses
dxSkinsLookAndFeelPainter,
dxSkinsCore;
{$R *.dfm}
procedure TfrmGridCases.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := cafree;
frmGridCases := nil;
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit Utilities;
interface
// Ported to Delphi from KeePass Password Safe (PwUtil.cpp)
function EstimatePasswordBits(Password: WideString): Integer;
// Extremely simple password generator, and not really "random".
function GenerateRandomPassword(DrawSet: string; PwLength: Integer): string;
implementation
uses
SysUtils, Math, JclStrHashMap;
const CHARSPACE_ESCAPE = 60;
const CHARSPACE_ALPHA = 26;
const CHARSPACE_NUMBER = 10;
const CHARSPACE_SIMPSPECIAL = 16;
const CHARSPACE_EXTSPECIAL = 17;
const CHARSPACE_HIGH = 112;
function EstimatePasswordBits(Password: WideString): Integer;
var
I: Integer;
PwLength: Integer;
EffectiveLength: Double;
CurChar: WideChar;
HasChLower, HasChUpper, HasChNumber, HasChSimpleSpecial, HasChExtSpecial,
HasChHigh, hasChEscape: Boolean;
CharSpace: Integer;
BitsPerChar: Double;
DiffFactor: Double;
Diff: Integer;
Differences, CharCounts: TStringHashMap;
_int: PInteger;
function FreeHashData(AUserData: PUserData; const AStr: string; var APtr: PData): Boolean;
begin
Dispose(APtr);
Result := True;
end;
begin
Differences := TStringHashMap.Create(CaseSensitiveTraits, 1);
CharCounts := TStringHashMap.Create(CaseSensitiveTraits, 1);
HasChLower := False; HasChUpper := False; HasChNumber := False;
HasChSimpleSpecial := False; HasChExtSpecial := False;
HasChHigh := False; hasChEscape := False;
try
// If there is no password, return 0 (bits)
if Password = '' then begin Result := 0; Exit; end;
PwLength := Length(Password);
if PwLength = 0 then begin Result := 0; Exit; end;
// loop through all characters
EffectiveLength := 0;
for I := 1 to PwLength do
begin
CurChar := Password[I];
// determine character class
if (Ord(Ord(CurChar)) < Ord(' ')) then HasChEscape := true;
if ((Ord(CurChar) >= Ord('A')) and(Ord(CurChar) <= Ord('Z'))) then HasChUpper := True;
if ((Ord(CurChar) >= Ord('a')) and (Ord(CurChar) <= Ord('z'))) then HasChLower := True;
if ((Ord(CurChar) >= Ord('0')) and (Ord(CurChar) <= Ord('9'))) then HasChNumber := True;
if ((Ord(CurChar) >= Ord(' ')) and (Ord(CurChar) <= Ord('/'))) then HasChSimpleSpecial := True;
if ((Ord(CurChar) >= Ord(':')) and (Ord(CurChar) <= Ord('@'))) then HasChExtSpecial := True;
if ((Ord(CurChar) >= Ord('[')) and (Ord(CurChar) <= Ord('`'))) then HasChExtSpecial := True;
if ((Ord(CurChar) >= Ord('{')) and (Ord(CurChar) <= Ord('~'))) then HasChExtSpecial := True;
if (Ord(CurChar) > Ord('~')) then HasChHigh := True;
// diff factor? (not sure what this is for)
DiffFactor := 1.0;
if (I > 1) then
begin
Diff := Ord(CurChar) - Ord(Password[I-1]);
if not Differences.Has(IntToStr(Diff)) then
begin
New(_int);
_int^ := 1;
Differences.Add(IntToStr(Diff), _int);
end
else begin
Inc(PInteger(Differences.Data[IntToStr(Diff)])^);
DiffFactor := DiffFactor / PInteger(Differences.Data[IntToStr(Diff)])^;
end;
end;
if not CharCounts.Has(CurChar) then
begin
New(_int);
_int^ := 1;
CharCounts.Add(CurChar, _int);
EffectiveLength := EffectiveLength + DiffFactor;
end
else begin
Inc(PInteger(CharCounts.Data[CurChar])^);
EffectiveLength := EffectiveLength +
DiffFactor * (1.0 / PInteger(CharCounts.Data[CurChar])^);
end;
end;
// Calculate total number of bits to consider
CharSpace := 0;
if (HasChEscape = TRUE) then Inc(CharSpace, CHARSPACE_ESCAPE);
if (HasChUpper = TRUE) then Inc(CharSpace, CHARSPACE_ALPHA);
if (HasChLower = TRUE) then Inc(CharSpace, CHARSPACE_ALPHA);
if (HasChNumber = TRUE) then Inc(CharSpace, CHARSPACE_NUMBER);
if (HasChSimpleSpecial = TRUE) then Inc(CharSpace, CHARSPACE_SIMPSPECIAL);
if (HasChExtSpecial = TRUE) then Inc(CharSpace, CHARSPACE_EXTSPECIAL);
if (HasChHigh = TRUE) then Inc(CharSpace, CHARSPACE_HIGH);
// Usually shoulnd't happen
if CharSpace = 0 then begin Result := 0; Exit; end;
// Calculate total bit strength
BitsPerChar := Ln(CharSpace) / Ln(2.00);
Result := Ceil(BitsPerChar * EffectiveLength);
finally
// Free the both hashes, plus the memory we filled along the way
Differences.Iterate(nil, @FreeHashData);
Differences.Free;
CharCounts.Iterate(nil, @FreeHashData);
CharCounts.Free;
end;
end;
function GenerateRandomPassword(DrawSet: string; PwLength: Integer): string;
var
I: Integer;
begin
Randomize;
Result := '';
for I := 1 to PwLength do
begin
Result := Result + DrawSet[Random(Length(DrawSet))+1];
end;
end;
end.
|
unit uCreateAnim;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, pngimage, ExtCtrls, ComCtrls, Buttons, FaceUnit;
type
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Bevel1: TBevel;
Panel2: TPanel;
Image1: TImage;
Panel3: TPanel;
Bevel2: TBevel;
Label1: TLabel;
ListBox1: TListBox;
Label2: TLabel;
Timer1: TTimer;
Image2: TImage;
Image3: TImage;
Image4: TImage;
Image5: TImage;
Image6: TImage;
Procedure BuildFrames;
procedure FormShow(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Image4Click(Sender: TObject);
procedure Image3Click(Sender: TObject);
procedure Image6Click(Sender: TObject);
procedure Image5Click(Sender: TObject);
private
{ Private declarations }
public
Anim : TAnimations;
Editable : boolean;
AnimName : String;
{ Public declarations }
end;
var
Form1: TForm1;
Frame: integer = 0;
implementation
uses uCreateFace, uAnimView;
{$R *.dfm}
Procedure TForm1.BuildFrames;
var
i : integer;
begin
ListBox1.Clear;
for i := 0 to length(Anim)-1 do
ListBox1.Items.Add('Frame '+inttostr(i));
end;
procedure TForm1.FormShow(Sender: TObject);
begin
if not Editable then
SetLength(Anim, 0);
end;
procedure TForm1.ListBox1Click(Sender: TObject);
begin
if ListBox1.ItemIndex < 0 then exit;
DrawFace(Image1.Canvas,anim[ListBox1.ItemIndex]);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Editable then begin
SaveAnimations(Anim,AnimName);
Close;
end else begin
AnimName := InputBox('Имя анимации','Введите имя:','Моя анимация');
SaveAnimations(Anim,AnimName+'.anim');
Close;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if ListBox1.Items.Count = 0 then exit;
if Frame > ListBox1.Items.Count then Frame := 0;
DrawFace(Image1.Canvas,anim[Frame]);
inc(Frame);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Timer1.Enabled := False;
end;
procedure TForm1.Image4Click(Sender: TObject);
begin
if Timer1.Enabled then
Timer1.Enabled := false
else
Timer1.Enabled := true;
end;
procedure TForm1.Image3Click(Sender: TObject);
begin
if ListBox1.ItemIndex < 0 then exit;
Form2.EditFace := true;
Form2.NewFace := false;
Form2.MyFace := anim[ListBox1.ItemIndex];
if Form2.showmodal = mrOk then begin
SetLength(Anim, length(Anim)+1);
Anim[Length(Anim)-1] := Form2.MyFace;
BuildFrames;
end;
end;
procedure TForm1.Image6Click(Sender: TObject);
begin
if ListBox1.ItemIndex < 0 then exit;
DeleteFrame(Anim,ListBox1.ItemIndex);
BuildFrames;
end;
procedure TForm1.Image5Click(Sender: TObject);
begin
Form2.EditFace := false;
Form2.NewFace := false;
if Form2.showmodal = mrOk then begin
SetLength(Anim, length(Anim)+1);
Anim[Length(Anim)-1] := Form2.MyFace;
BuildFrames;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSLog<p>
Activate GLS_LOGGING in "GLSCene.inc" to turn on inner GLScene logger.<p>
You may have only one instance of TGLSLogger<p>
To obtain it, call UserLog() function from any unit.<p>
<b>Historique : </b><font size=-1><ul>
<li>25/03/13 - DaStr - Added WriteInternalMessages and DisplayErrorDialogs options
<li>30/01/13 - DaStr - Added "save-old-logs" option
<li>09/01/13 - DaStr - Added Log buffering and auto-splitting options
Other misc changes.
<li>18/01/11 - Yar - Added message sending to IDE memo in design time
<li>07/01/10 - Yar - Added formated string logging
<li>29/11/10 - Yar - Added log raising in Linux
<li>04/11/10 - DaStr - Added Delphi5 and Delphi6 compatibility
Fixed unit description
<li>07/09/10 - Yar - Added Enabled property to TLogSession
<li>02/04/10 - Yar - Added properties TimeFormat, LogLevels to TGLSLogger
Added function UserLog.
GLS_LOGGING now only turn on inner GLScene logger
<li>24/03/10 - Yar - Added TGLSLogger component,
possibility to use a more than one of log,
limit the number of error messages
<li>06/03/10 - Yar - Added to GLScene
</ul></font>
(C) 2004-2007 George "Mirage" Bakhtadze.
<a href="http://www.casteng.com">www.casteng.com</a> <br>
The source code may be used under either MPL 1.1 or LGPL 2.1 license.
See included license.txt file <br>
Unit contains some text file related utilities and logging class
}
unit GLSLog;
interface
{$I GLScene.inc}
uses
{$IFDEF MSWINDOWS} Winapi.Windows, Winapi.ShellApi, {$ENDIF}
{$IFDEF LINUX} Process, {$ENDIF}
System.StrUtils, System.Classes, System.SysUtils,
System.UITypes, System.SyncObjs,
VCL.Dialogs, VCL.Controls,
GLCrossPlatform;
type
{ : Levels of importance of log messages }
TLogLevel = (lkDebug, lkInfo, lkNotice, lkWarning, lkError, lkFatalError);
{ : Log level setting type }
TLogLevels = set of TLogLevel;
{: What to do when number of messages exceeds message limit. }
TLogMessageLimitAction = (mlaContinue, mlaStopLogging, mlaHalt);
var
llMessageLimit: array [TLogLevel] of Integer = (MaxInt, MaxInt, MaxInt,
500, 100, 10);
lkPrefix: array [TLogLevel] of string = (' (D) ', ' (i) ', ' (M) ',
' (W) ', ' (Er) ', ' (!!) ');
const
llMax: TLogLevels = [lkDebug, lkInfo, lkNotice, lkWarning, lkError, lkFatalError];
llMedium: TLogLevels = [lkNotice, lkWarning, lkError, lkFatalError];
llMin: TLogLevels = [lkError, lkFatalError];
type
{ : Log date and time setting type }
TLogTimeFormat = (
{ : doesn't output any time information }
lfNone,
{ : include date in the log }
lfDate,
{ : include time in the log }
lfTime,
{ : include time in the log, including milliseconds }
lfTimeExact,
{ : include date and time in the log }
lfDateTime,
{ : include time elapsed since startup in the log }
lfElapsed);
{: How log is buffered. }
TLogBufferingMode =
(
lbmWriteEmidiatly,
lbmWritePeriodically,
lbmWriteInTheEnd
);
{ : Class reference to log session class }
CLogSession = class of TLogSession;
TLogSession = class;
{: Thread that periodically flushes the buffer to disk. }
TLogBufferFlushThread = class(TThread)
private
FParent: TLogSession;
protected
procedure Execute; override;
public
constructor Create(const AParent: TLogSession);
end;
{: Thread that checks file size and splits the file if nessesary. }
TLogCheckSizeThread = class(TThread)
private
FParent: TLogSession;
protected
procedure Execute; override;
public
constructor Create(const AParent: TLogSession);
end;
{: Abstract Logger class }
TLogSession = class(TPersistent)
private
FBuffer: TStringList;
FBuffered: Boolean;
FBufferProcessingThread: TLogBufferFlushThread;
FCheckLogSizeThread: TLogCheckSizeThread;
FFlushBufferPeriod: Integer;
FLogFile: Text; // TextFile.
FDestroying: Boolean;
FOriginalLogFileName: string; // Original name
FCurrentLogFileName: string; // Current log file, if original exceeded certain size limit.
FUsedLogFileNames: TStringList; // List of all created log files.
FLogLevels: TLogLevels;
FEnabled: Boolean;
FBufferCriticalSection: TCriticalSection;
FFileAccessCriticalSection: TCriticalSection;
FModeTitles: array [TLogLevel] of string;
FLogKindCount: array [TLogLevel] of Integer;
FLogThreadId: Boolean;
FMessageLimitAction: TLogMessageLimitAction;
{ : Determines which date or time to include in the log }
FTimeFormat: TLogTimeFormat;
{ : Startup timestamp in milliseconds }
FStartedMs: Cardinal;
FLogFileMaxSize: Integer;
FCheckFileSizePeriod: Integer;
FDisplayLogOnExitIfItContains: TLogLevels;
FWriteInternalMessages: Boolean;
FDisplayErrorDialogs: Boolean;
{$IFNDEF GLS_LOGGING}
constructor OnlyCreate;
{$ENDIF}
procedure SetBuffered(const Value: Boolean);
procedure SetMode(const NewMode: TLogLevels);
procedure ChangeBufferedState();
procedure SetEnabled(const Value: Boolean);
procedure SetLogFileMaxSize(const Value: Integer);
protected
procedure PrintLogLevels();
procedure PrintLogStatistics();
function AttachLogFile(const AFileName: string; const AResetFile: Boolean = True): Boolean;
procedure ClearLogsInTheSameDir();
procedure BackUpOldLogs(const ACurrentLogFileName: string);
procedure CreateNewLogFileIfNeeded();
{ : Appends a string to log. Thread-safe. }
procedure AppendLog(const AString: string; const ALevel: TLogLevel; const ALogTime: Boolean = True);
{: Writes string to log. Returns True if everything went ok.}
function DoWriteToLog(const AString: string): Boolean; virtual;
{: Writes FBuffer to log. Returns True if everything went ok.}
function DoWriteBufferToLog(): Boolean; virtual;
{: Resets log. Returns True if everything went ok.}
function DoResetLog: Boolean; virtual;
public
{ Initializes a log session with the specified log file name, time and level settings }
constructor Init(const AFileName: string;
const ATimeFormat: TLogTimeFormat; const ALevels: TLogLevels;
const ALogThreadId: Boolean = True; const ABuffered: Boolean = False;
const AMaxSize: Integer = 0; const ABackUpOldLogs: Boolean = False;
const AClearOldLogs: Boolean = True; const AWriteInternalMessages: Boolean = True); virtual;
{ : Destructor }
destructor Destroy; override;
{ : General Logging procedures }
procedure Log(const Desc: string; const Level: TLogLevel = lkInfo);
procedure LogAdv(const args: array of const; const ALevel: TLogLevel = lkError);
procedure LogException(const E: Exception; const aFunctionName: string;
const args: array of const; const ALevel: TLogLevel = lkError);
{ : Logs a string <b>Desc</b> if <b>Level</b>
matches current GLS_LOGGING level (see @Link(LogLevels)) }
procedure LogDebug(const Desc: string);
procedure LogInfo(const Desc: string);
procedure LogNotice(const Desc: string);
procedure LogWarning(const Desc: string);
procedure LogError(const Desc: string);
procedure LogFatalError(const Desc: string);
procedure LogEmtryLine();
{ : Logs a formatted string assembled from a format string and an array of arguments. }
procedure LogDebugFmt(const Desc: string; const Args: array of const );
procedure LogInfoFmt(const Desc: string; const Args: array of const );
procedure LogNoticeFmt(const Desc: string; const Args: array of const );
procedure LogWarningFmt(const Desc: string; const Args: array of const );
procedure LogErrorFmt(const Desc: string; const Args: array of const );
procedure LogFatalErrorFmt(const Desc: string; const Args: array of const );
{ : Mics procedures. }
procedure DisplayLog();
procedure FlushBuffer(); // If log is buffered, calling this will flush the buffer.
{ : Set of levels which to include in the log }
property LogLevels: TLogLevels read FLogLevels write SetMode
default [lkDebug, lkInfo, lkNotice, lkWarning, lkError, lkFatalError];
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Buffered: Boolean read FBuffered write SetBuffered default False;
property FlushBufferPeriod: Integer read FFlushBufferPeriod write FFlushBufferPeriod default 5000; // In ms.
property LogThreadId: Boolean read FLogThreadId write FLogThreadId default True;
property DisplayErrorDialogs: Boolean read FDisplayErrorDialogs write FDisplayErrorDialogs default True;
property MessageLimitAction: TLogMessageLimitAction read FMessageLimitAction write FMessageLimitAction default mlaHalt;
property WriteInternalMessages: Boolean read FWriteInternalMessages write FWriteInternalMessages default True;
{: To always display log, put all log types. To never display log, leave this empty. }
property DisplayLogOnExitIfItContains: TLogLevels read FDisplayLogOnExitIfItContains write FDisplayLogOnExitIfItContains
default [lkDebug, lkInfo, lkNotice, lkWarning, lkError, lkFatalError];
{: If LogFileMaxSize is not 0, then:
1) At start, all logs with the same extention will be deleted.
2) All logs wil be periodically cheked for FileSize.
New log file will be created when this size exceeds limit.
}
property LogFileMaxSize: Integer read FLogFileMaxSize write SetLogFileMaxSize default 0; // In bytes, limited to 2Gb.
property CheckFileSizePeriod: Integer read FCheckFileSizePeriod write FCheckFileSizePeriod default 4000; // In ms.
end;
// TGLSLoger
//
{ : Abstract class for control loging.<p> }
TGLSLogger = class(TComponent)
private
{ Private Declarations }
FReplaceAssertion: Boolean;
FTimeFormat: TLogTimeFormat;
FLogLevels: TLogLevels;
FLog: TLogSession;
procedure SetReplaceAssertion(Value: Boolean);
function GetLog: TLogSession;
protected
{ Protected Declarations }
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ : Set component primary and then UserLog return it's log }
procedure DoPrimary;
property Log: TLogSession read GetLog;
published
{ Published Declarations }
property ReplaceAssertion: Boolean read FReplaceAssertion
write SetReplaceAssertion default False;
{ : Only design time sets. Define Log initial properties }
property TimeFormat: TLogTimeFormat read FTimeFormat write FTimeFormat
default lfElapsed;
property LogLevels: TLogLevels read FLogLevels write FLogLevels
default [lkDebug, lkInfo, lkNotice, lkWarning, lkError, lkFatalError];
end;
TIDELogProc = procedure(const AMsg: string);
{ : Return logger wich created by TGLSLogger component }
function UserLog: TLogSession;
function SkipBeforeSTR(var TextFile: Text; SkipSTR: string): Boolean;
function ReadLine(var TextFile: Text): string;
{ : GLScene inner logger.
DaStr: Converted to a function, because in case of a DLL and main app using this module,
log is written to the same file on initialization and finalization,
which is not what one might want. This also allows to create a GLSLogger with
custom parameters for user's application, for example a different log path
(Often the EXE application directory is read-only).
}
function GLSLogger(): TLogSession;
procedure UseCustomGLSLogger(const ALogger: TLogSession);
function ConstArrayToString(const Elements: array of const): String;
var
vIDELogProc: TIDELogProc;
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
implementation
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
var
v_GLSLogger: TLogSession;
vAssertErrorHandler: TAssertErrorProc;
vCurrentLogger: TGLSLogger;
{ : GLScene inner logger. Create on first use, not in unit initialization. }
function GLSLogger(): TLogSession;
begin
if v_GLSLogger = nil then
begin
{$IFDEF GLS_LOGGING}
v_GLSLogger := TLogSession.Init(Copy(ExtractFileName(ParamStr(0)), 1,
Length(ExtractFileName(ParamStr(0))) - Length(ExtractFileExt(ParamStr(0)))) +
'.log', lfElapsed, llMax);
{$ELSE}
v_GLSLogger := TLogSession.OnlyCreate;
{$ENDIF}
end;
Result := v_GLSLogger;
end;
procedure UseCustomGLSLogger(const ALogger: TLogSession);
begin
if (v_GLSLogger <> nil) then v_GLSLogger.Destroy;
v_GLSLogger := ALogger;
end;
const
//VarRec -> String
vTypeDesc : Array[0..16] of String = ('vtInteger','vtBoolean','vtChar',
'vtExtended','vtString','vtPointer','vtPChar','vtObject', 'vtClass',
'vtWideChar','vtPWideChar','vtAnsiString','vtCurrency','vtVariant',
'vtInterface','vtWideString','vtInt64');
vTypeAsSring : Array[0..17] of String = ('Integer : ', 'Boolean : ', 'Char : ',
'Extended : ', 'String : ', 'Pointer : ', 'PChar : ',
'TObject : ', 'Class : ', 'WideChar : ', 'PWideChar : ',
'AnsiString : ', 'Currency : ', 'Variant : ', 'Interface : ',
'WideString : ', 'Int64 : ', '#HLType : ');
{: Function from HotLog by Olivier Touzot "QnnO".}
Function GetOriginalValue(s:String):String;
// Called to remove the false 'AnsiString :' assertion, for pointers and objects
Begin
result := RightStr(s,Length(s)-19);
End;
{: Function from HotLog by Olivier Touzot "QnnO".}
Function VarRecToStr(vr:TVarRec):String;
// See D6PE help topic "TVarRec"
Begin
Result := vTypeAsSring[vr.VType] + ' ';
TRY
With vr Do
Case VType of
vtInteger: result := result + IntToStr(VInteger);
vtBoolean: result := result + BoolToStr(VBoolean, True);
vtChar: Result := Result + string(VChar);
vtExtended: Result := Result + FloatToStr(VExtended^);
vtString: result := result + string(VString^);
// maintened in case of future need, but will actually not arrive.
vtPointer: result := result + '^(' + Format('%P', [(addr(VPointer)) ]) +')';
vtPChar: result := Result + string(VPChar);
// ...
vtObject: Begin
If VObject = Nil Then result := result + '^(NIL)'
Else result := result + VObject.classname;
End;
// ...
vtClass: result := result + VClass.classname;
vtWideChar: Result := Result + string(VWideChar);
vtPWideChar: Result := Result + VPWideChar;
vtAnsiString: Result := Result + string(VAnsiString);
vtCurrency: result := result + CurrToStr(VCurrency^);
vtVariant: Result := Result + string(VVariant^);
vtInterface: Result := Result + '(Interfaced object)';
vtWideString: Result := Result + string(VWideString^);
vtInt64: Result := Result + IntToStr(VInt64^);
else result := result + Format('[#HLvrType(%d)]', // "Else" not possible...
[ integer(vr.VType) ]); // ...with D6, but laters ?
End;{case}
EXCEPT
result := result + Format('[#HLvrValue(%s)]', [vTypeDesc[vr.VType]]);
END;
end;
{: Function from HotLog by Olivier Touzot "QnnO".}
Function GetBasicValue(s:String; vKind:Byte):String;
var iTmp : Integer;
wasTObject: Boolean;
Begin
Result := s;
If s = '' Then exit;
TRY
iTmp := Pos('$_H_',s);
wasTObject := (Pos('$_H_TObject',s) > 0);
If (iTmp > 0 ) Then Result := GetOriginalValue(s); // converts fake strings back to original
Result := RightStr(Result, length(result)-15); // From now on, works on "result"
If (vKind In [vtString,vtAnsiString,vtWideString,vtPChar,vtWideChar,vtPWideChar])
And Not(wasTObject) Then Exit
Else Begin
iTmp := Pos(' ',Result);
If ( iTmp > 0 ) And (iTmp < Length(result))
Then result := LeftStr(result, iTmp);
End;
EXCEPT; END;
End;
{: Function from HotLog by Olivier Touzot "QnnO".}
function ConstArrayToString(const Elements: array of const): String;
// -2-> Returns à string, surrounded by parenthesis : '(elts[0]; ...; elts[n-1]);'
// ("Basic infos" only.)
Var i: Integer;
s,sep: String;
Begin
TRY
if Length(Elements) = 0 then
begin
Result := '';
Exit;
end;
Result := '(';
sep := '; ';
For i:= Low(Elements) to High(Elements) do
Begin
s := VarRecToStr(Elements[I]);
Result := Result + GetBasicValue(s,Elements[i].VType) + sep;
End;
Result := LeftStr(Result, length(result)-2) + ');' ; // replaces last ", " by final ");".
EXCEPT result := '[#HLvrConvert]';
END;
End;
function UserLog: TLogSession;
begin
if Assigned(vCurrentLogger) then
Result := vCurrentLogger.Log
else
Result := nil;
end;
function RemovePathAndExt(const aFileName: string): string;
var
lExtIndex: Integer;
begin
Result := ExtractFileName(aFileName);
lExtIndex := Pos(ExtractFileExt(Result), Result);
Result := Copy(Result, 1, lExtIndex - 1);
end;
procedure LogedAssert(const Message, FileName: string; LineNumber: Integer;
ErrorAddr: Pointer);
begin
UserLog.Log(Message + ': in ' + FileName + ' at line ' +
IntToStr(LineNumber), lkError);
Abort;
end;
function FileSize(const aFilename: String): Integer;
var
sr : TSearchRec;
begin
if FindFirst(aFilename, faAnyFile, sr ) = 0 then
begin
Result := sr.Size;
FindClose(sr);
end
else
Result := -1;
end;
function SkipBeforeSTR(var TextFile: Text; SkipSTR: string): Boolean;
var
s: string;
begin
repeat
readln(TextFile, s);
if s = SkipSTR then
begin
Result := True;
Exit;
end;
until False;
Result := False;
end;
function ReadLine(var TextFile: Text): string;
var
i: Word;
var
s: string;
begin
if EOF(TextFile) then
Exit;
i := 1;
repeat
readln(TextFile, s);
until (s <> '') and (s[1] <> '#') or EOF(TextFile);
if s <> '' then
begin
while s[i] = ' ' do
inc(i);
if i = Length(s) then
s := ''
else
s := Copy(s, i, Length(s) - i + 1);
end;
Result := s;
end;
// ------------------
// ------------------ TGLSLogger ------------------
// ------------------
constructor TGLSLogger.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTimeFormat := lfElapsed;
FLogLevels := llMax;
vAssertErrorHandler := AssertErrorProc;
vCurrentLogger := Self;
end;
destructor TGLSLogger.Destroy;
begin
if vCurrentLogger = Self then
vCurrentLogger := nil;
if Assigned(FLog) then
FLog.Destroy;
inherited Destroy;
end;
function TGLSLogger.GetLog: TLogSession;
begin
if not Assigned(FLog) then
FLog := TLogSession.Init(Name + '.log', FTimeFormat, FLogLevels);
Result := FLog;
end;
procedure TGLSLogger.DoPrimary;
begin
vCurrentLogger := Self;
end;
procedure TGLSLogger.SetReplaceAssertion(Value: Boolean);
begin
if Value <> FReplaceAssertion then
begin
FReplaceAssertion := Value;
case FReplaceAssertion of
True:
AssertErrorProc := @LogedAssert;
False:
AssertErrorProc := @vAssertErrorHandler;
end;
end;
end;
// ------------------
// ------------------ TLogSession ------------------
// ------------------
procedure TLogSession.BackUpOldLogs(const ACurrentLogFileName: string);
var
sRec: TSearchRec;
lLogFileName: string;
lLogOriginalDir: string;
lLogSaveDir: string;
lLogExt: string;
procedure SaveCurrentFile();
var
lErrorMessage: string;
lFile: File;
begin
if not FDisplayErrorDialogs then
RenameFile(lLogOriginalDir + sRec.Name, lLogSaveDir + sRec.Name)
else
begin
lErrorMessage := 'Renaming of "%s" failed with error : %d. Try again?';
while not RenameFile(lLogOriginalDir + sRec.Name, lLogSaveDir + sRec.Name) do
begin
if MessageDlg(Format(lErrorMessage, [lLogOriginalDir + sRec.Name,
GetLastError]), mtWarning, [mbNo], 0) = mrNo
then Break;
AssignFile(lFile, lLogOriginalDir + sRec.Name);
CloseFile(lFile);
end;
end;
end;
begin
lLogExt := ExtractFileExt(ACurrentLogFileName);
lLogFileName := RemovePathAndExt(ACurrentLogFileName);
lLogOriginalDir := ExtractFilePath(ACurrentLogFileName);
lLogSaveDir := lLogOriginalDir + FormatDateTime('yyyy-mm-dd hh-nn-ss', Now);
if not CreateDir(lLogSaveDir) then Exit;
lLogSaveDir := lLogSaveDir + PathDelim;
If FindFirst(lLogOriginalDir + lLogFileName + '*' + lLogExt, faAnyfile, sRec) = 0 then
begin
try
SaveCurrentFile();
except
end;
while ( FindNext(sRec) = 0 ) do
try
SaveCurrentFile();
except
end;
FindClose(sRec);
end;
end;
procedure TLogSession.SetBuffered(const Value: Boolean);
begin
if FBuffered = Value then Exit;
FBuffered := Value;
ChangeBufferedState();
end;
procedure TLogSession.SetEnabled(const Value: Boolean);
begin
if (FEnabled = Value) then Exit;
FEnabled := Value;
if (FEnabled) then
Log('Logging session resumed')
else
Log('Logging session paused');
end;
procedure TLogSession.SetLogFileMaxSize(const Value: Integer);
begin
if FLogFileMaxSize = Value then Exit;
FLogFileMaxSize := Value;
if FLogFileMaxSize > 0 then
begin
FCheckLogSizeThread := TLogCheckSizeThread.Create(Self);
FCheckLogSizeThread.Start();
end
else
begin
FCheckLogSizeThread.Terminate();
// DaStr: Not really safe because we can wait forever.
// But other methods known to me are platform-dependant.
FCheckLogSizeThread.WaitFor();
FCheckLogSizeThread.Free();
end;
end;
procedure TLogSession.SetMode(const NewMode: TLogLevels);
begin
{$IFNDEF GLS_LOGGING}
if Self = v_GLSLogger then
Exit;
{$ENDIF}
FLogLevels := NewMode;
PrintLogLevels();
end;
function TLogSession.DoResetLog: Boolean;
begin
try
FFileAccessCriticalSection.Enter;
Rewrite(FLogFile);
CloseFile(FLogFile);
FFileAccessCriticalSection.Leave;
Result := True;
except on E: Exception do
begin
// Ignore exceptions.
Result := False;
FFileAccessCriticalSection.Leave;
end;
end;
end;
function TLogSession.DoWriteBufferToLog: Boolean;
var
I: Integer;
lLast: Integer;
begin
try
// Open file.
FFileAccessCriticalSection.Enter;
Append(FLogFile);
// Write buffer.
lLast := FBuffer.Count - 1;
for I := 0 to lLast do
WriteLn(FLogFile, FBuffer[I]);
// Clear buffer.
FBufferCriticalSection.Enter;
FBuffer.Clear();
FBufferCriticalSection.Leave;
// Close file.
CloseFile(FLogFile);
FFileAccessCriticalSection.Release();
Result := True;
except
// Ignore exceptions.
Result := False;
FFileAccessCriticalSection.Release();
end;
end;
function TLogSession.DoWriteToLog(const AString: string): Boolean;
begin
try
FFileAccessCriticalSection.Enter;
Append(FLogFile);
WriteLn(FLogFile, AString);
CloseFile(FLogFile);
FFileAccessCriticalSection.Release();
Result := True;
except
// Ignore exceptions.
Result := False;
FFileAccessCriticalSection.Release();
end;
end;
procedure TLogSession.FlushBuffer;
begin
if Buffered then
DoWriteBufferToLog();
end;
constructor TLogSession.Init(const AFileName: string;
const ATimeFormat: TLogTimeFormat; const ALevels: TLogLevels;
const ALogThreadId: Boolean = True; const ABuffered: Boolean = False;
const AMaxSize: Integer = 0; const ABackUpOldLogs: Boolean = False;
const AClearOldLogs: Boolean = True; const AWriteInternalMessages: Boolean = True);
var
i: Integer;
ModeStr: string;
begin
FBuffer := TStringList.Create();
FLogThreadId := ALogThreadId;
FFlushBufferPeriod := 5000; // 5 sec.
FCheckFileSizePeriod := 4000; // 4 sec.
FBufferCriticalSection := TCriticalSection.Create;
FFileAccessCriticalSection := TCriticalSection.Create;
FBuffered := ABuffered; // Do not call the setter, create thread later.
FStartedMs := GLGetTickCount;
FTimeFormat := ATimeFormat;
FLogLevels := ALevels;
FMessageLimitAction := mlaHalt;
FDisplayErrorDialogs := True;
FDisplayLogOnExitIfItContains := [lkError, lkFatalError];
FWriteInternalMessages := AWriteInternalMessages;
// Set up strings.
FModeTitles[lkDebug] := 'debug info';
FModeTitles[lkInfo] := 'info';
FModeTitles[lkNotice] := 'notices';
FModeTitles[lkWarning] := 'warnings';
FModeTitles[lkError] := 'errors';
FModeTitles[lkFatalError] := 'fatal errors';
case FTimeFormat of
lfNone:
ModeStr := 'no timestamp mode.';
lfDate:
ModeStr := 'date only mode.';
lfTime:
ModeStr := 'time only mode.';
lfTimeExact:
ModeStr := 'time mode with milliseconds.';
lfDateTime:
ModeStr := 'date and time mode.';
lfElapsed:
ModeStr := 'elapsed time mode.';
end;
if ABackUpOldLogs then
BackUpOldLogs(AFileName);
// Attach log file.
FUsedLogFileNames := TStringList.Create();
FOriginalLogFileName := AFileName;
FEnabled := AttachLogFile(AFileName, AClearOldLogs);
// Clear all logs and set log max size.
if AMaxSize > 0 then
ClearLogsInTheSameDir();
Self.SetLogFileMaxSize(AMaxSize);
// Reset log counters.
for i := Ord( Low(TLogLevel)) to Ord( High(TLogLevel)) do
FLogKindCount[TLogLevel(i)] := 0;
// Print some initial logs.
if FWriteInternalMessages then
begin
Log('Log subsystem started in ' + ModeStr, lkInfo);
PrintLogLevels();
Log('Buffered mode: ' + BoolToStr(FBuffered, True), lkInfo);
end;
// Start BufferProcessing thread.
if FBuffered then
ChangeBufferedState();
end;
{$IFNDEF GLS_LOGGING}
constructor TLogSession.OnlyCreate;
begin
inherited;
end;
{$ENDIF}
procedure TLogSession.PrintLogLevels;
var
ModeStr: string;
i: Integer;
begin
ModeStr := '[';
for i := Ord( Low(TLogLevel)) to Ord( High(TLogLevel)) do
if TLogLevel(i) in FLogLevels then
begin
if ModeStr <> '[' then
ModeStr := ModeStr + ', ';
ModeStr := ModeStr + FModeTitles[TLogLevel(i)] + ' ' +
Trim(lkPrefix[TLogLevel(i)]);
end;
ModeStr := ModeStr + ']';
if FLogLevels = [] then
ModeStr := 'nothing';
Log('Logging ' + ModeStr, lkInfo);
end;
procedure TLogSession.PrintLogStatistics;
begin
Log('Logged fatal_errors: ' + IntToStr(FLogKindCount[lkFatalError]) +
', errors: ' + IntToStr(FLogKindCount[lkError]) +
', warnings: ' + IntToStr(FLogKindCount[lkWarning]) +
', notices: ' + IntToStr(FLogKindCount[lkNotice]) +
', info: ' + IntToStr(FLogKindCount[lkInfo]) +
', debug: ' + IntToStr(FLogKindCount[lkDebug]));
end;
function TLogSession.AttachLogFile(const AFileName: string; const AResetFile: Boolean = True): Boolean;
var
lPath: string;
begin
try
lPath := ExtractFilePath(AFileName);
if Length(lPath) > 0 then
begin
FCurrentLogFileName := AFileName;
ForceDirectories(lPath);
end
else
FCurrentLogFileName := IncludeTrailingPathDelimiter(GetCurrentDir) + AFileName;
FFileAccessCriticalSection.Enter;
AssignFile(FLogFile, FCurrentLogFileName);
FFileAccessCriticalSection.Leave;
FUsedLogFileNames.Add(FCurrentLogFileName);
if not FileExists(FCurrentLogFileName) then
Result := DoResetLog()
else
begin
if not AResetFile then
Result := True
else
Result := DoResetLog();
end;
except
FFileAccessCriticalSection.Leave;
Result := False;
end;
end;
procedure TLogSession.ChangeBufferedState();
begin
if (FBuffered) then
begin
FBufferProcessingThread := TLogBufferFlushThread.Create(Self);
FBufferProcessingThread.Start();
end
else
begin
FBufferProcessingThread.Terminate();
// DaStr: Not really safe because we can wait forever.
// But other methods known to me are platform-dependant.
FBufferProcessingThread.WaitFor();
FBufferProcessingThread.Free();
end;
end;
procedure TLogSession.ClearLogsInTheSameDir;
var
sRec: TSearchRec;
lFilePath: string;
procedure DeleteCurrentFile();
begin
if FCurrentLogFileName <> lFilePath + sRec.Name then
DeleteFile(lFilePath + sRec.Name);
end;
begin
lFilePath := ExtractFilePath(FCurrentLogFileName);
If FindFirst(lFilePath + RemovePathAndExt(FCurrentLogFileName) +
'*' + ExtractFileExt(FCurrentLogFileName), faAnyfile, sRec) = 0 then
begin
try
DeleteCurrentFile()
except
end;
while ( FindNext(sRec) = 0 ) do
try
DeleteCurrentFile();
except
end;
FindClose(sRec);
end;
end;
procedure TLogSession.CreateNewLogFileIfNeeded;
var
lNewFileName: string;
I, Index: Integer;
lFileSize: Integer;
begin
try
FFileAccessCriticalSection.Enter;
lFileSize := FileSize(FCurrentLogFileName);
FFileAccessCriticalSection.Leave();
except
lFileSize := -1;
FFileAccessCriticalSection.Leave();
end;
if lFileSize >= FLogFileMaxSize then
begin
I := 1;
lNewFileName := FOriginalLogFileName;
repeat
Index := LastDelimiter('.', FOriginalLogFileName);
if Index = -1 then Exit;
lNewFileName := FOriginalLogFileName;
Insert('_' + IntToStr(I), lNewFileName, Index);
Inc(i);
until
not FileExists(lNewFileName);
if FWriteInternalMessages then
begin
Log(Format('Creating new log file "%s" because old one became too big (%d bytes)',
[lNewFileName, lFileSize]));
end;
AttachLogFile(lNewFileName, True);
end;
end;
destructor TLogSession.Destroy;
var
I: TLogLevel;
begin
FDestroying := True;
{$IFNDEF GLS_LOGGING}
if Self = v_GLSLogger then
Exit;
{$ENDIF}
if FWriteInternalMessages then
begin
PrintLogStatistics();
Log('Log session shutdown');
end;
SetBuffered(False);
DoWriteBufferToLog(); // Terminates TLogBufferFlushThread.
FBuffer.Free;
SetLogFileMaxSize(0); // Terminates TLogCheckSizeThread.
// Display log?
for I := Low(TLogLevel) to High(TLogLevel) do
if (I in FDisplayLogOnExitIfItContains) and (FLogKindCount[I] > 0) then
begin
DisplayLog();
Break;
end;
if Self = v_GLSLogger then
v_GLSLogger := nil;
FUsedLogFileNames.Destroy;
FBufferCriticalSection.Destroy;
FFileAccessCriticalSection.Destroy;
end;
procedure TLogSession.DisplayLog;
{$IFDEF LINUX}
var
lProcess: TProcess;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
ShellExecute(0, 'open', 'C:\WINDOWS\notepad.exe',
PChar(FCurrentLogFileName), nil, 1);
{$ENDIF}
{$IFDEF LINUX}
lProcess := TProcess.Create(nil);
lProcess.CommandLine := 'gedit ' + FCurrentLogFileName;
lProcess.Execute;
lProcess.Destroy;
{$ENDIF}
end;
procedure TLogSession.Log(const Desc: string; const Level: TLogLevel = lkInfo);
begin
AppendLog(Desc, Level);
end;
procedure TLogSession.LogAdv(const args: array of const;
const ALevel: TLogLevel);
begin
Log(constArrayToString(args), ALevel);
end;
procedure TLogSession.LogDebug(const Desc: string);
begin
Log(Desc, lkDebug);
end;
procedure TLogSession.LogInfo(const Desc: string);
begin
Log(Desc, lkInfo);
end;
procedure TLogSession.LogNotice(const Desc: string);
begin
Log(Desc, lkNotice);
end;
procedure TLogSession.LogWarning(const Desc: string);
begin
Log(Desc, lkWarning);
end;
procedure TLogSession.LogEmtryLine;
begin
if not FEnabled then Exit;
{$IFNDEF GLS_LOGGING}
if Self = v_GLSLogger then
Exit;
{$ENDIF}
if FBuffered then
begin
// Critical section is always used.
FBufferCriticalSection.Enter;
FBuffer.Add('');
FBufferCriticalSection.Leave;
end
else
begin
DoWriteToLog('');
end;
// IDELogProc.
if (Self = v_GLSLogger) and Assigned(vIDELogProc) then
vIDELogProc('');
end;
procedure TLogSession.LogError(const Desc: string);
begin
Log(Desc, lkError);
end;
procedure TLogSession.LogFatalError(const Desc: string);
begin
Log(Desc, lkFatalError);
end;
procedure TLogSession.LogDebugFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkDebug);
end;
procedure TLogSession.LogInfoFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkInfo);
end;
procedure TLogSession.LogNoticeFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkWarning);
end;
procedure TLogSession.LogWarningFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkWarning);
end;
procedure TLogSession.LogErrorFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkError);
end;
procedure TLogSession.LogException(const E: Exception; const aFunctionName: string;
const args: array of const; const ALevel: TLogLevel = lkError);
begin
Log('Exception in ' + aFunctionName + ': ' + E.Message + string(#13#10) +
'Input parameters:' + string(#13#10) +
constArrayToString(args), ALevel);
end;
procedure TLogSession.LogFatalErrorFmt(const Desc: string;
const Args: array of const );
begin
Log(Format(Desc, Args), lkFatalError);
end;
procedure TLogSession.AppendLog(const AString: string; const ALevel: TLogLevel;
const ALogTime: Boolean);
var
line: string;
begin
{$IFNDEF GLS_LOGGING}
if Self = v_GLSLogger then
Exit;
{$ENDIF}
if not(ALevel in LogLevels) or not FEnabled then
Exit;
if ALogTime then
case FTimeFormat of
lfNone:
line := lkPrefix[ALevel] + AString;
lfDate:
line := DateToStr(Now) + #9 + lkPrefix[ALevel] + AString;
lfTime:
line := TimeToStr(Now) + #9 + lkPrefix[ALevel] + AString;
lfTimeExact:
line := FormatDateTime('hh:nn:ss zzz "ms"', Now) + #9 + lkPrefix[ALevel] + AString;
lfDateTime:
line := DateTimeToStr(Now) + #9 + lkPrefix[ALevel] + AString;
lfElapsed:
line := IntToStr(GLGetTickCount - FStartedMs) + #9 +
lkPrefix[ALevel] + AString;
end
else
line := AString;
{$IFDEF GLS_MULTITHREAD}
if (FLogThreadId) then
line := #9 + 'Thread ID ' + IntToStr(PtrUInt(GetCurrentThreadId)) + #9 + line;
{$ENDIF}
if FBuffered then
begin
// Critical section is always used.
FBufferCriticalSection.Enter;
FBuffer.Add(line);
FBufferCriticalSection.Leave;
end
else
begin
DoWriteToLog(line);
end;
// IDELogProc.
if (Self = v_GLSLogger) and Assigned(vIDELogProc) then
vIDELogProc('GLScene: ' + line);
// Message limit?
Inc(FLogKindCount[ALevel]);
if llMessageLimit[ALevel] < FLogKindCount[ALevel] then
case FMessageLimitAction of
mlaContinue: { Do nothing. } ;
mlaStopLogging:
begin
Log('Logging stopped due to reaching message limit (' +
FModeTitles[ALevel] + ' = ' + IntToStr(FLogKindCount[ALevel]) + ')');
FEnabled := False;
end;
mlaHalt:
begin
Log('Application halted due to reaching log message limit (' +
FModeTitles[ALevel] + ' = ' + IntToStr(FLogKindCount[ALevel]) + ')');
SetBuffered(False);
Halt;
end;
end;
end;
{ TLogBufferFlushThread }
constructor TLogBufferFlushThread.Create(const AParent: TLogSession);
begin
FParent := AParent;
inherited Create(True);
end;
procedure TLogBufferFlushThread.Execute;
begin
while (not Terminated) or (FParent.FBuffer.Count > 0) do
begin
FParent.DoWriteBufferToLog();
Sleep(FParent.FFlushBufferPeriod);
end;
end;
{ TLogCheckSizeThread }
constructor TLogCheckSizeThread.Create(const AParent: TLogSession);
begin
FParent := AParent;
inherited Create(True);
end;
procedure TLogCheckSizeThread.Execute;
begin
while (not Terminated and not FParent.FDestroying) do
begin
FParent.CreateNewLogFileIfNeeded();
Sleep(FParent.FCheckFileSizePeriod);
end;
end;
initialization
finalization
if (v_GLSLogger <> nil) then v_GLSLogger.Destroy;
end.
|
{_______________________________________________________________
FRAKVOSS.PAS Accompanies "Mimicking Mountains," by Tom Jeffery,
FRAKFFC.PAS
BYTE, December 1987, page 337
revised:
12/11/87 by Art Steinmetz
Version for IBM Turbo Pascal v.4.0
Combined FFC and Voss algorithms in one module
______________________________________________________________}
unit fracsurf;
{$I FLOAT.INC}
interface
uses MathLib0;
CONST
size = 64; { compute size x size surface. 64 is recommended }
type
AlgorithmType = (Voss, FFC);
surface = array[0..size, 0..size] of longint;
procedure DoFractal(VAR srf : surface;
H : float; { roughness factor between 0 and 1 }
Algo : AlgorithmType);
procedure SaveFractal(srf : surface;
{ optional filename to store array in }
datafile : string);
implementation
var
row, col, n, step, st : longint;
stepfactor : float;
function gauss : float;
{Returns a gaussian variable with mean = 0, variance = 1}
{Polar method due to Knuth, vol. 2, pp. 104, 113 }
{but found in "Smalltalk-80, Language and Implementation",}
{Goldberg and Robinson, p. 437.}
var
i : integer;
sum, v1, v2, s : float;
begin
sum := 0;
repeat
v1 := (random / maxint);
v2 := (random / maxint);
s := sqr(v1) + sqr(v2);
until s < 1;
s := sqrt(-2 * ln(s) / s) * v1;
gauss := s;
end;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
procedure DoFractal( var srf : surface;
H : float;
algo : AlgorithmType);
procedure horintpol (row : longint);
{Interpolates midpoints for 1 row}
var
i, col : longint;
begin
col := 0;
while col < size do
begin
srf[row, col + step] := (srf[row, col] + srf[row, col
+ 2 * step]) div 2; {New point}
col := col + 2 * step;
end;
end;
procedure verintpol (col : longint);
{Interpolates midpoints for 1 column}
var
i, row : longint;
begin
row := 0;
while row < size do
begin
srf[row + step, col] := (srf[row, col]
+ srf[row + 2 * step, col]) div 2; {New point}
row := row + 2 * step;
end;
end;
procedure centintpol (row : longint);
{Interpolates center points for all cells in a row}
var
i, col : longint;
begin
col := step;
while col < size do
begin
srf[row, col] := (srf[row, col - step] + srf[row, col + step]
+ srf[row - step, col] + srf[row + step, col]) div 4;
{New point}
col := col + 2 * step;
end;
end;
procedure intpol;
{Interpolates all midpoints at current step size}
var
i, row, col : longint;
begin
row := 0;
col := 0;
while row <= size do
begin
horintpol(row);
row := row + 2 * step;
end;
while col <= size do
begin
verintpol(col);
col := col + 2 * step;
end;
row := step;
while row <= size - step do
begin
centintpol(row);
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure hordetail (row : longint);
{Calculates new points for one row}
var
disp, i, col : longint;
begin
col := 0;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col + step] :=
(srf[row, col] + srf[row, col + 2 * step]) div 2; {Midpoint}
srf[row, col + step] := srf[row, col + step] + disp;{New point}
col := col + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure verdetail (col : longint);
{Calculates new points for one column}
var
disp, i, row : longint;
begin
row := 0;
while row < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row + step, col] :=
(srf[row, col] + srf[row + 2 * step, col]) div 2; {Midpoint}
srf[row + step, col] := srf[row + step, col] + disp; {New point}
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure centdetail (row : longint);
{Calculates new points for centers of all cells in a row}
var
disp, i, col : longint;
begin
col := step;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col] :=
(srf[row, col - step] + srf[row, col + step]
+ srf[row - step, col]
+ srf[row + step, col]) div 4; {Center Point}
srf[row, col] := srf[row, col] + disp; {New point}
col := col + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure FFCDetail;
{Calculates new points at current step size}
var
i, row, col : longint;
begin
row := 0;
col := 0;
while row <= size do
begin
hordetail(row);
row := row + 2 * step;
end;
while col <= size do
begin
verdetail(col);
col := col + 2 * step;
end;
row := step;
while row <= size - step do
begin
centdetail(row);
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure VossDetail;
{Adds random displacement to all points at current step size}
var
r, c, disp : longint;
begin
r := 0;
while r <= size do
begin
c := 0;
while c <= size do
begin
disp := Round(100 * (gauss * stepfactor));
srf[r, c] := srf[r, c] + disp;
c := c + step;
end;
r := r + step;
end;
end;
procedure newsurface;
begin
step := size;
stepfactor := exp(2 * H * ln(step));
{ nail down the corners }
srf[0, 0] := Round(100 * (gauss * stepfactor));
srf[0, size] := Round(100 * (gauss * stepfactor));
srf[size, 0] := Round(100 * (gauss * stepfactor));
srf[size, size] := Round(100 * (gauss * stepfactor));
repeat
step := step div 2; {Go to smaller scale}
{ optional computing progress report goes here }
stepfactor := exp(2 * H * ln(step)); {Factor proportional to step size}
if Algo = Voss then
begin
intpol;
VossDetail;
end
else FFCDetail;
until step = 1;
end;
begin { DoFractal }
Randomize;
newsurface; {Calculate surface}
end;
procedure SaveFractal(srf :surface; datafile : string);
var
srfile : file of surface;
begin
assign(srfile, datafile);
rewrite(srfile);
write(srfile, srf); {Store surface in file}
(* ALTERNATE WAY OF WRITING
for row := 0 to size do
for col := 0 to size do
begin
write(srfile, srf { srf[row, col] }); {Store surface in file}
write(srf[row, col]:8);
end;
*)
close(srfile);
end;
procedure ReadFractal(srf :surface; datafile : string);
var
srfile : file of surface;
begin
assign(srfile, datafile);
reset(srfile);
read(srfile, srf);
close(srfile);
end;
begin
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Web services description language (WSDL) }
{ generation from RTTI }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WebServExp;
interface
uses
SysUtils, Classes, {Variants, ActiveX,} IntfInfo, TypInfo, XMLIntf, XMLDoc, xmldom, XmlSchema,
WSDLIntf, WSDLBind, XMLSchemaTags;
type
ArgumentType = (argIn, argOut, argInOut, argReturn);
MessageType = (mtInput, mtOutput, mtHeaderInput, mtHeaderOutput,
mtFault);
TSchemaType = record
TypeName: WideString;
NameSpace: WideString;
TypeInfo: PTypeinfo;
NSPrefix: WideString;
XSGenerated: Boolean;
end;
TSchemaTypeArray = array of TSchemaType;
IWebServExp = interface
['{77099743-C063-4174-BA64-53847693FB1A}']
function FindOrAddSchema(const ATypeInfo: PTypeinfo; const TnsURI: string): Boolean;
procedure GenerateXMLSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo, ParentInfo: PTypeinfo; Namespace: WideString);
end;
TBeforePublishingTypesEvent = procedure(const WebServ: IWebServExp) of object;
TPublishingTypeEvent = procedure(const WebServ: IWebServExp; const SchemaDef: IXMLSchemaDef;
const ATypeInfo: PTypeinfo; Namespace: WideString) of object;
TAfterPublishingWSDLEvent = procedure(const WSDLDoc: IWSDLDocument) of object;
TWebServExp = class;
IWebServExpAccess = interface
['{1BB5EB76-AC77-47EE-BCF2-99C7B54386C3}']
function GetWebServExp: TWebServExp;
end;
TWebServExp = class(TInterfacedObject, IWebServExp, IWebServExpAccess)
private
Definition: IDefinition;
ComplexTypeList: TStringList;
bHasComplexTypes: Boolean;
FServiceAddress: WideString;
FBindingType: TWebServiceBindingType;
FWSDLElements: TWSDLElements;
FImportNames: TWideStrings;
FImportLocation: TWideStrings;
FArrayAsComplexContent: Boolean;
SchemaArray: TSchemaTypeArray;
FTargetNameSpace: WideString;
FOnBeforePublishingTypes: TBeforePublishingTypesEvent;
FOnPublishingType: TPublishingTypeEvent;
FOnAfterPublishingWSDL: TAfterPublishingWSDLEvent;
procedure GenerateWSDL(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString);
procedure GenerateNestedArraySchema(SchemaDef: IXMLSchemaDef; ComplexType: IXMLComplexTypeDef; const ATypeInfo: PTypeinfo; var Dimension: Integer; Namespace: WideString);
procedure AddImports(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
procedure AddTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
function GetMessageName(const MethName: WideString; MethIndex: Integer; MsgType: MessageType; const ASuffix: WideString = ''): WideString;
function AddMessage(const Messages: IMessages; const Name: WideString): IMessage;
procedure AddMessages(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
procedure AddHeaders(const IntfMD: TIntfMetaData; MethIndex: Integer;
const Messages: IMessages; const MethodExtName: WideString);
procedure AddFaultMessages(const IntfMD: TIntfMetaData; MethIndex: Integer;
const Messages: IMessages; const MethodExtName: WideString;
WSDLDoc: IWSDLDocument);
procedure AddPortTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
procedure AddBinding(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
procedure AddServices(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames: array of WideString; Locations: array of WideString);
function GetXMLSchemaType(const ParamTypeInfo: PTypeInfo): string;
function GetXMLSchemaTypeName(const ParamTypeInfo: PTypeInfo): WideString;
function IsComplexType(const ParamType: TTypeKind ):Boolean; overload;
function IsComplexType(const ParamTypeInfo: PTypeInfo): Boolean; overload;
procedure SetBindingType(const Value: TWebServiceBindingType);
procedure SetServiceAddress(const Value: WideString);
function GetImportNamespace(const Index: Integer): WideString;
procedure SetImportNamespace(const Index: Integer; const Value: WideString);
function GetImportLocation(const Index: Integer): WideString;
procedure SetImportLocation(const Index: Integer; const Value: WideString);
procedure SetArrayType(const Value: Boolean);
function GetPrefixForURI(SchemaDef: IXMLSchemaDef; const URI: WideString): WideString; overload;
function GetPrefixForURI(Def: IDefinition; const URI: WideString): WideString; overload;
function GetPrefixForTypeInfo(const ATypeInfo: PTypeinfo): WideString; overload;
function AddNamespaceURI(RootNode: IXMLNode; const URI: WideString): WideString;
function GetNodeNameForURI(SchemaDef: IXMLSchemaDef; const URI: WideString): WideString;
procedure GenerateArraySchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString);
procedure GenerateEnumSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString);
procedure GenerateAliasSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString;
const ABaseTypeInfo: PTypeInfo = nil);
procedure GenerateClassSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo, ParentInfo: PTypeinfo; const Namespace: WideString);
procedure GenerateDerivedClassSchema(SchemaDef: IXMLSchemaDef; const ParentTypeInfo: PTypeinfo; const Namespace: WideString);
procedure GetAllSchemaTypes(const IntfMD: TIntfMetaData);
procedure GetSchemaTypes(const ATypeInfo, ParentInfo: PTypeinfo);
function FindOrAddSchema(const ATypeInfo: PTypeinfo; const TnsURI: string): Boolean;
procedure GetClassSchema(const ATypeInfo, ParentInfo: PTypeinfo);
procedure GetDerivedClassSchema(const ParentTypeInfo: PTypeinfo);
function IsSchemaGenerated(const ATypeInfo: PTypeinfo; const TnsURI: WideString): Boolean;
procedure GetArraySchema(const ATypeInfo: PTypeinfo);
public
constructor Create;
destructor Destroy; override;
procedure GetWSDLForInterface(const IntfTypeInfo: Pointer; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString);
procedure GenerateXMLSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo, ParentInfo: PTypeinfo; Namespace: WideString);
function GetWebServExp: TWebServExp;
property ImportNames [const Index: Integer]: WideString read GetImportNamespace write SetImportNamespace;
property ImportLocations[const Index: Integer]: WideString read GetImportLocation write SetImportLocation;
property TargetNameSpace: WideString read FTargetNameSpace write FTargetNameSpace;
published
property ArrayAsComplexContent: Boolean read FArrayAsComplexContent write SetArrayType;
property BindingType: TWebServiceBindingType read FBindingType write SetBindingType;
property ServiceAddress: WideString read FServiceAddress write SetServiceAddress;
property WSDLElements: TWSDLElements read FWSDLElements write FWSDLElements default [weServiceIntf];
property OnBeforePublishingTypes: TBeforePublishingTypesEvent read FOnBeforePublishingTypes write FOnBeforePublishingTypes;
property OnPublishingType: TPublishingTypeEvent read FOnPublishingType write FOnPublishingType;
property OnAfterPublishingWSDL: TAfterPublishingWSDLEvent read FOnAfterPublishingWSDL write FOnAfterPublishingWSDL;
end;
{ Returns the BindingType of a particular Method. Input species whether the
request/call or response/return since a method may have one input binding
and another binding for output }
function GetBindingType(const MethEntry: TIntfMethEntry; Input: Boolean): TWebServiceBindingType; overload;
{ Returns the underlying of an alias of the specified TypeKind, if any }
function GetAliasBaseTypeInfo(const ParamType: TTypeKind): PTypeInfo;
function IsBaseClassTypeInfo(const ATypeInfo: PTypeInfo): Boolean;
implementation
uses InvokeRegistry, SOAPConst, XSBuiltIns;
{$IFDEF LINUX}
{$IFNDEF OPENDOM}
{$DEFINE OPENDOM}
{$ENDIF}
{$ENDIF}
{$IFDEF MSWINDOWS}
//{$DEFINE OPENDOM}
{$ENDIF}
function IsBaseClassTypeInfo(const ATypeInfo: PTypeInfo): Boolean;
begin
Result := (ATypeInfo = TypeInfo(TObject)) or
(ATypeInfo = TypeInfo(TRemotable)) or
(ATypeInfo = TypeInfo(TSOAPHeader)) or
(ATypeInfo = TypeInfo(ERemotableException));
end;
{ WebServExp Implementation }
constructor TWebServExp.Create;
begin
ComplexTypeList := TStringList.Create;
FWSDLElements := [weServiceIntf];
FImportNames := TWideStrings.Create;
FImportLocation := TWideStrings.Create;
FArrayAsComplexContent := True;
end;
destructor TWebServExp.Destroy;
begin
ComplexTypeList.Free;
FImportNames.Free;
FImportLocation.Free;
inherited Destroy;
end;
procedure TWebServExp.SetArrayType(const Value: Boolean);
begin
FArrayAsComplexContent := Value;
end;
{ Set default binding type }
procedure TWebServExp.SetBindingType(const Value: TWebServiceBindingType);
begin
FBindingType := Value;
end;
procedure TWebServExp.SetServiceAddress(const Value: WideString);
begin
FServiceAddress := Value;
end;
function TWebServExp.GetImportNamespace(const Index: Integer): WideString;
begin
if FImportNames.Count > Index then
Result := FImportNames.Strings[Index]
else
Result := '';
end;
function TWebServExp.GetImportLocation(const Index: Integer): WideString;
begin
if FImportLocation.Count > Index then
Result := FImportLocation.Strings[Index]
else
Result := '';
end;
procedure TWebServExp.SetImportNamespace(const Index: Integer; const Value: WideString);
begin
FImportNames.Insert(Index, Value);
end;
procedure TWebServExp.SetImportLocation(const Index: Integer; const Value: WideString);
begin
FImportLocation.Insert(Index, Value);
end;
procedure TWebServExp.GetWSDLForInterface(const IntfTypeInfo: Pointer; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString);
var
IntfMD: TIntfMetaData;
begin
bHasComplexTypes := False;
GetIntfMetaData(IntfTypeInfo, IntfMD);
GenerateWSDL(IntfMD, WSDLDoc, PortNames, Locations);
end;
procedure TWebServExp.GenerateWSDL(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames, Locations: array of WideString);
var
Encoding: WideString;
begin
if IntfMD.Name <> '' then
begin
{ Add WSDL:Definitions and its attributes }
Definition := WSDLDoc.Definition;
Definition.Attributes[Sname] := IntfMD.Name+SService;
if (TargetNamespace <> '') then
begin
Definition.Attributes[Stns] := TargetNamespace;
{$IFDEF OPENDOM}
Definition.DeclareNameSpace('tns', TargetNameSpace);
{$ELSE}
Definition.Attributes['xmlns:tns'] := TargetNamespace;
{$ENDIF}
end;
{$IFDEF OPENDOM}
Definition.DeclareNameSpace('soap', Soapns); { do not localize }
Definition.DeclareNameSpace('soapenc', SSoap11EncodingS5); { do not localize }
Definition.DeclareNamespace('mime', SWSDLMIMENamespace); { do not localize }
{$ELSE}
Definition.Attributes['xmlns:soap'] := Soapns;
Definition.Attributes['xmlns:soapenc'] := SSoap11EncodingS5;
Definition.Attributes['xmlns:mime'] := SWSDLMIMENamespace;
{$ENDIF}
{ Add Encoding }
if WSDLDoc.Encoding = '' then
begin
Encoding := InvRegistry.GetWSDLEncoding(IntfMD.Info, '', IntfMD.Name);
if Encoding <> '' then
WSDLDoc.Encoding := Encoding
else
WSDLDoc.Encoding := 'utf-8';
end;
{ Set the Namespace prefix }
(WSDLDoc as IXMLDocumentAccess).DocumentObject.NSPrefixBase := SNsPrefix;
{ Add WSDL Types }
if (WeTypes in FWSDLElements) or (WeServiceIntf in FWSDLElements) then
AddTypes(IntfMD, WSDLDoc);
{ Add Imports }
if (WeImport in FWSDLElements) or (WeServiceImpl in FWSDLElements) then
if (FImportNames.Count = FImportLocation.Count) then
AddImports(IntfMD, WSDLDoc);
{ Add WSDL Message and its parts }
if ((weMessage in FWSDLElements) or (weServiceIntf in FWSDLElements) ) then
AddMessages(IntfMD, WSDLDoc);
{ Add WSDL PortType and its Operations }
if ((wePortType in FWSDLElements) or (weServiceIntf in FWSDLElements) ) then
AddPortTypes(IntfMD, WSDLDoc);
{ Add WSDL Binding for operations }
if (WeBinding in FWSDLElements) or (weServiceIntf in FWSDLElements) then
AddBinding(IntfMD, WSDLDoc);
{ Add WSDL Service and its port }
if (WeService in FWSDLElements) or (WeServiceImpl in FWSDLElements) then
AddServices(IntfMD, WSDLDoc, PortNames, Locations);
{ Give user a chance to customize WSDL }
if Assigned(FOnAfterPublishingWSDL) then
FOnAfterPublishingWSDL(WSDLDoc);
end;
end;
procedure TWebServExp.AddImports(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
var
Imports: IImports;
Index: Integer;
begin
Imports := WSDLDoc.Definition.Imports;
for Index := 0 to FImportNames.Count -1 do
Imports.Add(FImportNames.Strings[Index], FImportLocation.Strings[Index]);
end;
function HeaderUsedWithMethod(HeaderItem: IntfHeaderItem;
MethodExtName: WideString; MType: EHeaderMethodType): Boolean;
var
Methods: TStrings;
I: Integer;
begin
Result := HeaderItem.MethodNames = '';
if not Result then
begin
Methods := TStringList.Create;
try
Methods.CommaText := HeaderItem.MethodNames;
for I := 0 to Methods.Count -1 do
begin
if SameText(Methods[I], MethodExtName) then
begin
if (not Assigned(HeaderItem.MethodTypes)) or
(HeaderItem.MethodTypes[I] in [hmtAll, MType]) then
Result := True;
break;
end;
end;
finally
Methods.Free;
end;
end;
end;
function ExceptionUsedWithMethod(ExceptItem: IntfExceptionItem; MethodExtName: WideString): Boolean;
var
Methods: TStrings;
I: Integer;
begin
Result := ExceptItem.MethodNames = '';
if not Result then
begin
Methods := TStringList.Create;
try
Methods.CommaText := ExceptItem.MethodNames;
for I := 0 to Methods.Count -1 do
begin
if SameText(Methods[I], MethodExtName) then
begin
Result := True;
break;
end;
end;
finally
Methods.Free;
end;
end;
end;
function TWebServExp.GetMessageName(const MethName: WideString; MethIndex: Integer;
MsgType: MessageType; const ASuffix: WideString): WideString;
var
Prefix: WideString;
begin
Prefix := IntToStr(MethIndex);
case MsgType of
mtInput: Result := MethName + Prefix + SRequest;
mtOutput: Result := MethName + Prefix + SResponse;
mtHeaderInput: Result := MethName + Prefix + SHeader + SRequest;
mtHeaderOutput: Result := MethName + Prefix + SHeader + SResponse;
mtFault: Result := MethName + Prefix + SFault;
end;
{ Use suffix for Operations with multiple faults since
the fault message can have only a single part. }
Result := Result + ASuffix;
end;
function TWebServExp.AddMessage(const Messages: IMessages; const Name: WideString): IMessage;
begin
Result := Messages.Add(Name);
end;
procedure TWebServExp.AddFaultMessages(const IntfMD: TIntfMetaData; MethIndex: Integer;
const Messages: IMessages; const MethodExtName: WideString;
WSDLDoc: IWSDLDocument);
var
I: Integer;
TnsPre: WideString;
ExceptItems: TExceptionItemArray;
NewMessage: IMessage;
Parts: IParts;
MessageName: WideString;
begin
TnsPre := GetPrefixForURI(WSDLDoc.Definition, TargetNameSpace);
ExceptItems := InvRegistry.GetExceptionInfoForInterface(IntfMD.Info);
{ Publish fault messages }
for I := 0 to Length(ExceptItems) -1 do
begin
if ExceptionUsedWithMethod(ExceptItems[I], MethodExtName) then
begin
MessageName := GetMessageName(MethodExtName, MethIndex, mtFault, IntToStr(I));
NewMessage := AddMessage(Messages, MessageName);
Parts := NewMessage.Parts;
Parts.Add(ExceptItems[I].ClassType.ClassName, '',
GetXMLSchemaType(ExceptItems[I].ClassType.ClassInfo));
end;
end;
end;
procedure TWebServExp.AddHeaders(const IntfMD: TIntfMetaData; MethIndex: Integer;
const Messages: IMessages; const MethodExtName: WideString);
var
NewMessage: IMessage;
Parts: IParts;
HeaderItems: THeaderItemArray;
I: Integer;
HeaderName, TypeName: WideString;
AClass: TClass;
begin
HeaderItems := InvRegistry.GetRequestHeaderInfoForInterface(IntfMD.Info);
NewMessage := nil;
for I := 0 to Length(HeaderItems)-1 do
begin
if HeaderUsedWithMethod(HeaderItems[I], MethodExtName, hmtRequest) then
begin
if not Assigned(NewMessage) then
NewMessage := AddMessage(Messages, GetMessageName(MethodExtName, MethIndex, mtHeaderInput));
AClass := HeaderItems[I].ClassType;
HeaderName := InvRegistry.GetHeaderName(IntfMD.Info, AClass);
TypeName := GetXMLSchemaType(AClass.ClassInfo);
Parts := NewMessage.Parts;
Parts.Add(HeaderName, '', TypeName);
end;
end;
HeaderItems := InvRegistry.GetResponseHeaderInfoForInterface(IntfMD.Info);
NewMessage := nil;
for I := 0 to Length(HeaderItems) -1 do
begin
if HeaderUsedWithMethod(HeaderItems[I], MethodExtName, hmtResponse) then
begin
if not Assigned(NewMessage) then
NewMessage := AddMessage(Messages, GetMessageName(MethodExtName, MethIndex, mtHeaderOutput));
AClass := HeaderItems[I].ClassType;
HeaderName := InvRegistry.GetHeaderName(IntfMD.Info, AClass);
TypeName := GetXMLSchemaType(AClass.ClassInfo);
Parts := NewMessage.Parts;
Parts.Add(HeaderName, '', TypeName);
end;
end;
end;
procedure TWebServExp.AddMessages(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
var
IntfMethArray: TIntfMethEntryArray;
ParamArray: TIntfParamEntryArray;
Methods, Params, NoOfMethods, NoOfParams: Integer;
ParamType: string;
Messages: IMessages;
NewMessage: IMessage;
Parts: IParts;
MethodExtName, ParamExtName: WideString;
begin
IntfMethArray := nil;
ParamArray := nil;
IntfMethArray := IntfMD.MDA;
NoOfMethods := Length(IntfMethArray);
{ Add WSDL Message and its parts }
Messages := WSDLDoc.Definition.Messages;
for Methods := 0 to NoOfMethods -1 do
begin
ParamArray := IntfMD.MDA[Methods].Params;
NoOfParams := Length(ParamArray);
{ Add InOut parts }
{ Note: We always have a Message for the request - irrespective of in parameters }
MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name);
NewMessage := AddMessage(Messages, GetMessageName(MethodExtName, Methods, mtInput));
Parts := NewMessage.Parts;
for Params := 0 to NoOfParams-2 do { Skip Self/this }
begin
{ Note: No pfOut implies [in] parameter }
if not (pfOut in ParamArray[Params].Flags) then
begin
ParamType := GetXMLSchemaType(ParamArray[Params].Info);
ParamExtName := InvRegistry.GetParamExternalName(IntfMD.Info, MethodExtName, ParamArray[Params].Name);
Parts.Add(ParamExtName,'',ParamType);
end;
end;
{ Add Out parts }
{ Note: We always have a Message for the response - irrespective of return|out }
NewMessage := AddMessage(Messages, GetMessageName(MethodExtName, Methods, mtOutput));
Parts := NewMessage.Parts;
for Params := 0 to NoOfParams-2 do { Skip Self/this }
begin
{ pfOut or pfVar implies [out] parameter }
if ( (pfOut in ParamArray[Params].Flags) or (pfVar in ParamArray[Params].Flags) ) then
begin
ParamType := GetXMLSchemaType(ParamArray[Params].Info);
ParamExtName := InvRegistry.GetParamExternalName(IntfMD.Info, MethodExtName, ParamArray[Params].Name);
Parts.Add(ParamExtName,'',ParamType);
end;
end;
{ For Functions create a response }
if IntfMD.MDA[Methods].ResultInfo <> nil then
begin
ParamType := GetXMLSchemaType(IntfMD.MDA[Methods].ResultInfo);
Parts.Add(SReturn, '', ParamType);
end;
{ Add headers - if any have been registered }
AddHeaders(IntfMD, Methods, Messages, MethodExtName);
{ And faults }
AddFaultMessages(IntfMD, Methods, Messages, MethodExtName, WSDLDoc);
end;
end;
procedure TWebServExp.AddPortTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
function AddOperation(const Operations: IOperations; const MethName, Request, Response: WideString): IOperation;
begin
Result := Operations.Add(MethName, Request, '', Response);
end;
var
IntfMethArray: TIntfMethEntryArray;
Methods, I, NoOfMethods: Integer;
PortTypes: IPortTypes;
PortType: IPortType;
Operations: IOperations;
Operation: IOperation;
PortExtName, MethodExtName: WideString;
TnsPre: WideString;
ExceptItems: TExceptionItemArray;
MessageName: WideString;
begin
{ Add WSDL PortType and its Operations }
IntfMethArray := nil;
IntfMethArray := IntfMD.MDA;
NoOfMethods := Length(IntfMethArray);
PortTypes := WSDLDoc.Definition.PortTypes;
PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name);
PortType := PortTypes.Add(PortExtName);
TnsPre := GetPrefixForURI(WSDLDoc.Definition, TargetNameSpace);
ExceptItems := InvRegistry.GetExceptionInfoForInterface(IntfMD.Info);
{ Operations }
for Methods := 0 to NoOfMethods -1 do
begin
Operations := PortType.Operations;
MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name);
Operation := AddOperation(Operations, MethodExtName,
TnsPre+':'+GetMessageName(MethodExtName, Methods, mtInput),
TnsPre+':'+GetMessageName(MethodExtName, Methods, mtOutput));
{ Add operation <fault> node }
for I := 0 to Length(ExceptItems) -1 do
begin
if ExceptionUsedWithMethod(ExceptItems[I], MethodExtName) then
begin
MessageName := GetMessageName(MethodExtName, Methods, mtFault, IntToStr(I));
Operation.Faults.Add(ExceptItems[I].ClassType.ClassName,
TnsPre+ ':' + MessageName);
end;
end;
end;
end;
function IsInputParam(const Param: TIntfParamEntry): Boolean;
begin
{ To be consistent with AddMessages we'll assume no 'pfOut' makes
it an in parameter.
NOTE: This function does *NOT* mean it's not an Out parameter }
Result := not (pfOut in Param.Flags);
end;
function IsOutputParam(const Param: TIntfParamEntry): Boolean;
begin
Result := (pfOut in Param.Flags) or (pfVar in Param.Flags);
end;
function GetBindingType(const ParamInfo: PTypeInfo): TWebServiceBindingType; overload;
var
ClsType: TClass;
begin
{ Default to btSOAP }
Result := btSoap;
if ParamInfo = nil then
Exit;
{ Here we attempt to detect if it's an attachment. Attachments parameters
can be TSOAPAttachment or TSOAPAttachment-derived.
Arrays of the latter or classes that contain members of type
TSOAPAttachment(derived) are *NOT* considered attachment. The latter
because WSDL does not provide for a way to describe a part that's
non-Multipart and yet contains Multipart members. The former because
every SOAP implementation seems to ignore the array portion and maps
the parameter to a plain attachment }
if ParamInfo.Kind = tkClass then
begin
ClsType := GetTypeData(ParamInfo).ClassType;
if ClsType.InheritsFrom(TSOAPAttachment) then
begin
Result := btMIME;
Exit;
end;
end;
end;
function GetBindingType(const Param: TIntfParamEntry): TWebServiceBindingType; overload;
begin
Result := GetBindingType(Param.Info);
end;
function GetBindingType(const MethEntry: TIntfMethEntry;
Input: Boolean): TWebServiceBindingType; overload;
var
I: Integer;
ParamArray: TIntfParamEntryArray;
begin
{ Default to SOAP }
Result := btSoap;
ParamArray := MethEntry.Params;
if (Input) then
begin
{ Skip this/Self }
for I := 0 to Length(ParamArray)-2 do
begin
if (IsInputParam(ParamArray[I])) then
begin
Result := GetBindingType(ParamArray[I]);
{ End as soon as we get anything other than SOAP binding }
if Result <> btSoap then
Exit;
end;
end;
end else
begin
{ Skip this/Self }
for I := 0 to Length(ParamArray)-2 do
begin
if (IsOutputParam(ParamArray[I])) then
begin
Result := GetBindingType(ParamArray[I]);
{ End as soon as we get anything other than SOAP binding }
if Result <> btSoap then
Exit;
end;
end;
{ For output, we also check the return type, if any }
Result := GetBindingType(MethEntry.ResultInfo);
end;
end;
procedure TWebServExp.AddBinding(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
var
NewNode, SoapBodyNode, SoapHeaderNode, PartNode, ContentNode: IXMLNode;
HeaderItems: THeaderItemArray;
TnsPre: WideString;
function GetOverloadDigit( const MethNames: TWideStrings; Name: WideString): string;
var
I, Count: Integer;
begin
Result := '';
Count := 0;
for I := 0 to MethNames.Count -1 do
if SameText(MethNames[I], Name) then
Inc(Count);
MethNames.Add(Name);
if Count > 0 then
Result := IntToStr(Count);
end;
procedure SetupSoapBodyNode(const SBodyNode: IXMLNode);
begin
{ SBodyNode.Attributes[SParts] := ''; }
SBodyNode.Attributes[SUse] := SSoapBodyUseEncoded;
SBodyNode.Attributes[SEncodingStyle] := SSoap11EncodingS5;
SBodyNode.Attributes[SNameSpace] := InvRegistry.GetNamespaceByGUID(IntfMD.IID);
end;
procedure SetupSoapHeaderNode(const HeaderNode: IXMLNode;
const MsgName, PartName, Namespace: WideString;
Required: Boolean);
const
Prefix = 'n1';
begin
if Required then
begin
HeaderNode.DeclareNameSpace(Prefix, Wsdlns);
HeaderNode.SetAttribute(MakeNodeName(Prefix, SRequired), STrue);
end;
HeaderNode.Attributes[SUse] := SSoapBodyUseEncoded;
HeaderNode.Attributes[SMessage] := MsgName;
HeaderNode.Attributes[SPart] := PartName;
HeaderNode.Attributes[SEncodingStyle] := SSoap11EncodingS5;
HeaderNode.Attributes[SNameSpace] := Namespace;
end;
function HeaderRequired(const MethName: WideString; Item: IntfHeaderItem): Boolean;
var
Meths: TStringList;
I: Integer;
begin
Result := Item.DefaultRequired;
if Item.MethodNames <> '' then
begin
Meths := TStringList.Create;
try
Meths.CommaText := Item.MethodNames;
for I := 0 to Meths.Count -1 do
if SameText(Meths[I], MethName) then
begin
Result := Item.HeaderRequired[I];
break;
end;
finally
Meths.Free;
end;
end;
end;
function SetupMultiPartRelatedNode(const MPRelatedNode: IXMLNode;
const MethodExtName: WideString;
Input: Boolean;
const HdrMsgName: WideString): IXMLNode;
var
I: Integer;
PartName, Namespace: WideString;
AClass: TClass;
begin
PartNode := MPRelatedNode.AddChild(SPart, SWSDLMIMENamespace);
SoapBodyNode := PartNode.AddChild(SBody, Soapns);
SetupSoapBodyNode(SoapBodyNode);
if Input then
HeaderItems := InvRegistry.GetRequestHeaderInfoForInterface(IntfMD.Info)
else
HeaderItems := InvRegistry.GetResponseHeaderInfoForInterface(IntfMD.Info);
for I := 0 to Length(HeaderItems) -1 do
begin
if HeaderUsedWithMethod(HeaderItems[I], MethodExtName, hmtRequest) then
begin
AClass := HeaderItems[I].ClassType;
PartName := InvRegistry.GetHeaderName(IntfMD.Info, AClass);
Namespace:= InvRegistry.GetHeaderNamespace(IntfMD.Info, AClass);
SoapHeaderNode := NewNode.AddChild(SHeader, Soapns);
SetupSoapHeaderNode(SoapHeaderNode, TnsPre + ':' + HdrMsgName,
PartName, Namespace, HeaderRequired(MethodExtName, HeaderItems[I]));
end;
end;
end;
procedure SetupMultiPartNode(const MPRelatedNode: IXMLNode; const ParamName: String);
begin
PartNode := MPRelatedNode.AddChild(SPart, SWSDLMIMENamespace);
ContentNode := PartNode.AddChild('content');
{ TODO User:BB Must retrieve external name of parameter }
ContentNode.SetAttributeNS(SPart, '', ParamName);
ContentNode.SetAttributeNS(SType, '', 'application/binary');
end;
var
I, Methods, NoOfMethods, Params: Integer;
ParamArray: TIntfParamEntryArray;
Bindings: IBindings;
Binding: IBinding;
BindOperations: IBindingOperations;
NewBindOperation: IBindingOperation;
MPartRelated : IXMLNode;
PartName, PortExtName, MethodExtName, HeaderNamespace: WideString;
MethodBindingType: TWebServiceBindingType;
MethNames: TWideStrings;
OverloadDigit: string;
ExceptItems: TExceptionItemArray;
AClass: TClass;
begin
SetLength(ParamArray, 0);
{ Method Array }
NoOfMethods := Length(IntfMD.MDA);
{ Porttype Name + Namespace }
PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name);
TnsPre := GetPrefixForURI(WSDLDoc.Definition, TargetNameSpace);
{ Add WSDL Binding and its Operations }
Bindings := WSDLDoc.Definition.Bindings;
Binding := Bindings.Add(PortExtName+SBinding,TnsPre + ':' + PortExtName);
{ Add Binding specific elements }
if FBindingType = btSoap then
begin
{ Add soap:binding }
NewNode := Binding.AddChild(SBinding, Soapns);
NewNode.Attributes[SStyle] := 'rpc';
NewNode.Attributes[STransport] := SSoapHTTPTransport;
end;
OverloadDigit := '';
ExceptItems := InvRegistry.GetExceptionInfoForInterface(IntfMD.Info);
MethNames := TWideStrings.Create;
try
{ Generate input and output nodes for operations of this binding }
for Methods := 0 to NoOfMethods -1 do
begin
{ Add operation node }
MethodExtName := InvRegistry.GetMethExternalName(IntfMD.Info, IntfMD.MDA[Methods].Name);
BindOperations := Binding.BindingOperations;
NewBindOperation := BindOperations.Add(MethodExtName);
if FBindingType = btSoap then
begin
{ Add soap:operation }
NewNode := NewBindOperation.AddChild(SOperation, Soapns);
NewNode.Attributes[SSoapAction] := InvRegistry.GetActionURIOfInfo(IntfMD.Info, MethodExtName, Methods);
NewNode.Attributes[SStyle] := 'rpc';
end;
{ Get parameters }
ParamArray := IntfMD.MDA[Methods].Params;
{ Find the Input Binding Type }
MethodBindingType := GetBindingType(IntfMD.MDA[Methods], True);
{ Add input/output }
NewNode := NewBindOperation.AddChild(SInput);
{
Having the message attribute is only necessary to disambiguate overloaded methods:
"An operation element within a binding specifies binding information for the operation with
the same name within the binding's portType. Since operation names are not required to be
unique (for example, in the case of overloading of method names), the name attribute in the
operation binding element might not be enough to uniquely identify an operation. In that
case, the correct operation should be identified by providing the name attributes of the
corresponding wsdl:input and wsdl:output elements.
}
NewNode.Attributes[SMessage] := TnsPre + ':' + GetMessageName(MethodExtName, Methods, mtInput);
if MethodBindingType = btSoap then
begin
SoapBodyNode := NewNode.AddChild(SBody, Soapns);
SetupSoapBodyNode(SoapBodyNode);
HeaderItems := InvRegistry.GetRequestHeaderInfoForInterface(IntfMD.Info);
for I := 0 to Length(HeaderItems) -1 do
begin
if HeaderUsedWithMethod(HeaderItems[I], MethodExtName, hmtRequest) then
begin
AClass := HeaderItems[I].ClassType;
PartName := InvRegistry.GetHeaderName(IntfMD.Info, AClass);
HeaderNamespace := InvRegistry.GetHeaderNamespace(IntfMD.Info, AClass);
SoapHeaderNode := NewNode.AddChild(SHeader, Soapns);
SetupSoapHeaderNode(SoapHeaderNode, TnsPre + ':' +
GetMessageName(MethodExtName, Methods, mtHeaderInput),
PartName, HeaderNamespace,
HeaderRequired(MethodExtName, HeaderItems[I]));
end;
end;
end else if MethodBindingType = btMIME then
begin
{ We make the <input> node's name match that of the input message of this operation -
NOTE: This is purely conventional - i.e not according to the spec. }
NewNode.SetAttributeNS(Sname, '', GetMessageName(MethodExtName, Methods, mtInput));
{ TODO Localize these strings - move to SOAPConst }
MPartRelated := NewNode.AddChild(SMultiPartRelatedNoSlash, SWSDLMIMENamespace, True);
SetupMultiPartRelatedNode(MPartRelated, MethodExtName, True,
GetMessageName(MethodExtName, Methods, mtHeaderInput));
{ Here add <mime:part ><mime:content>...</mime:content></mime:part> nodes for
each MultiPart parameter }
{ NOTE: Skip this/Self }
for Params := 0 to Length(ParamArray)-2 do
begin
if IsInputParam(ParamArray[Params]) and
(GetBindingType(ParamArray[Params]) = btMIME) then
begin
{ TODO User:BB Must retrieve external name of parameter }
SetupMultiPartNode(MPartRelated, ParamArray[Params].Name);
end;
end;
end;
{ Output Node }
{ According to the spec, we don't really need an <output..> node; however,
the current version of Axis/Apache is not very happy when that node
is missing:
java.lang.NullPointerException
at org.apache.axis.wsdl.WsdlAttributes.scanBindings(WsdlAttributes.java:271)
at org.apache.axis.wsdl.WsdlAttributes.init(WsdlAttributes.java:114)
at org.apache.axis.wsdl.WsdlAttributes.<init>(WsdlAttributes.java:109)
at org.apache.axis.wsdl.Emitter.emit(Emitter.java:169)
at org.apache.axis.wsdl.Emitter.emit(Emitter.java:134)
at org.apache.axis.wsdl.Wsdl2java.main(Wsdl2java.java:199)
Error in parsing: null
I've relayed the issue; but in the meantime, we'll output a node anyway
}
{ if IntfMD.MDA[Methods].ResultInfo <> nil then }
NewNode := NewBindOperation.AddChild(SOutput);
{ See note on Input node about the message attribute }
NewNode.Attributes[SMessage] := TnsPre + ':' + GetMessageName(MethodExtName, Methods, mtOutput);
{ Find the Output Binding Type }
MethodBindingType := GetBindingType(IntfMD.MDA[Methods], False);
if MethodBindingType = btSoap then
begin
SoapBodyNode := NewNode.AddChild(SBody, Soapns);
SetupSoapBodyNode(SoapBodyNode);
HeaderItems := InvRegistry.GetResponseHeaderInfoForInterface(IntfMD.Info);
for I := 0 to Length(HeaderItems) -1 do
begin
if HeaderUsedWithMethod(HeaderItems[I], MethodExtName, hmtResponse) then
begin
AClass := HeaderItems[I].ClassType;
PartName := InvRegistry.GetHeaderName(IntfMD.Info, AClass);
HeaderNamespace := InvRegistry.GetHeaderNamespace(IntfMD.Info, AClass);
SoapHeaderNode := NewNode.AddChild(SHeader, Soapns);
SetupSoapHeaderNode(SoapHeaderNode, TnsPre + ':' +
GetMessageName(MethodExtName, Methods, mtHeaderOutput),
PartName, HeaderNamespace,
HeaderRequired(MethodExtName, HeaderItems[I]));
end;
end;
end else if MethodBindingType = btMIME then
begin
{ We make the <input> node's name match that of the input message of this operation -
NOTE: This is purely conventional - i.e not according to the spec. }
NewNode.SetAttributeNS(Sname, '', GetMessageName(MethodExtName, Methods, mtOutput));
{ TODO Localize these strings - move to SOAPConst }
MPartRelated := NewNode.AddChild(SMultiPartRelatedNoSlash, SWSDLMIMENamespace, True);
SetupMultiPartRelatedNode(MPartRelated, MethodExtName, False,
GetMessageName(MethodExtName, Methods, mtHeaderOutput));
{ Here add <mime:part ><mime:content >...</mime:content></mime:part> nodes for
each MultiPart parameter }
{ NOTE: Skip this/Self }
for Params := 0 to Length(ParamArray)-2 do
begin
if IsOutputParam(ParamArray[Params]) and
(GetBindingType(ParamArray[Params]) = btMIME) then
begin
{ TODO User:BB Must retrieve external name of parameter }
SetupMultiPartNode(MPartRelated, ParamArray[Params].Name);
end;
end;
{ For output we also check the return type, if any }
if GetBindingType(IntfMD.MDA[Methods].ResultInfo) = btMIME then
begin
SetupMultiPartNode(MPartRelated, SReturn);
end;
end;
{ Fault Binding }
for I := 0 to Length(ExceptItems) -1 do
begin
if ExceptionUsedWithMethod(ExceptItems[I], MethodExtName) then
begin
NewNode := NewBindOperation.AddChild(SFault);
NewNode := NewNode.AddChild(SFault, Soapns);
SetUpSoapBodyNode(NewNode);
break;
end;
end
end;
finally
MethNames.Free;
end;
end;
procedure TWebServExp.AddServices(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument; PortNames: array of WideString; Locations: array of WideString);
var
Services: IServices;
NewService: IService;
NewPort: IPort;
NewNode: IXMLNode;
I: Integer;
PortExtName: WideString;
TnsPre: WideString;
begin
Services := WSDLDoc.Definition.Services;
PortExtName := InvRegistry.GetInterfaceExternalName(IntfMD.Info,'',IntfMD.Name);
NewService := Services.Add(PortExtName + SService);
for I := 0 to Length(Locations) - 1 do
begin
TnsPre := GetPrefixForURI(WSDLDoc.Definition, TargetNameSpace);
NewPort := NewService.Ports.Add(PortNames[I], TnsPre + ':' + PortExtName+SBinding);
NewNode := NewPort.AddChild(SAddress, Soapns);
NewNode.Attributes[SLocation] := Locations[I];
end;
end;
procedure TWebServExp.AddTypes(const IntfMD: TIntfMetaData; WSDLDoc: IWSDLDocument);
var
{ NewNode: IXMLNode; }
SchemaDef: IXMLSchemaDef;
Index, Count: Integer;
UniqueURI: TWideStrings;
begin
{ Collect all schema types to be generated }
GetAllSchemaTypes(IntfMD);
{ Allow user chance to add more types }
if Assigned(FOnBeforePublishingTypes) then
FOnBeforePublishingTypes(Self);
if Length(SchemaArray) > 0 then
begin
UniqueURI := TWideStrings.Create;
try
{ Get Unique URI's and namespace prefix }
for Index := 0 to Length(SchemaArray) -1 do
begin
if (UniqueURI.IndexOf(SchemaArray[Index].NameSpace)= -1) then
UniqueURI.Add(SchemaArray[Index].NameSpace);
SchemaArray[Index].NSPrefix := GetPrefixForURI(Definition, SchemaArray[Index].NameSpace);
end;
{ Add seperate schema nodes for each unique URI }
for Count := 0 to UniqueURI.Count -1 do
begin
SchemaDef := WSDLDoc.Definition.Types.SchemaDefs.Add('',UniqueURI.Strings[Count]);
for Index := 0 to Length(SchemaArray) -1 do
begin
if Assigned(FOnPublishingType) then
FOnPublishingType(Self, SchemaDef, SchemaArray[Index].TypeInfo, UniqueURI.Strings[Count]);
GenerateXMLSchema(SchemaDef, SchemaArray[Index].TypeInfo, nil, UniqueURI.Strings[Count]);
end;
end;
finally
UniqueURI.Free;
end;
end;
end;
{ NOTE: Consider TOrdType and TFloatType subtypes of tkInteger and tkFloat... }
{ share with TypeTrans.pas ?? }
function TWebServExp.GetXMLSchemaType(const ParamTypeInfo: PTypeInfo):string;
var
TypeName, URI, Prefix: WideString;
begin
Prefix := '';
case ParamTypeInfo^.Kind of
tkClass, tkDynArray, tkEnumeration, tkSet:
begin
{ See if it's a predefined XML Schema Type }
RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI , TypeName);
{ Here if the URI did not match XMLNamespaces, we're dealing with a non-predefined XML Type }
if ((URI <> SXMLSchemaURI_2000_10) and (URI <> SXMLSchemaURI_1999) and (URI <> SXMLSchemaURI_2001)) then
begin
Prefix := GetPrefixForTypeInfo(ParamTypeInfo);
Result := MakeNodeName(Prefix, GetXMLSchemaTypeName(ParamTypeInfo));
end
else
begin
{ We always publish 2001 XMLSchema currently }
URI := SXMLSchemaURI_2001;
Prefix := GetPrefixForURI(Definition, URI);
Result := MakeNodeName(Prefix, TypeName);
end;
bHasComplexTypes := True;
end;
else
RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI, TypeName);
if TypeName <> '' then
begin
Prefix := GetPrefixForURI(Definition, URI);
Result := MakeNodeName(Prefix, TypeName);
end
else { When all fails - anything goes!! }
begin
Prefix := GetPrefixForURI(Definition, SXMLSchemaURI_2001);
Result := MakeNodeName(Prefix, SAnyType);
end;
end;
end;
function TWebServExp.GetXMLSchemaTypeName(const ParamTypeInfo: PTypeInfo): WideString;
var
URI: WideString;
begin
Result := '';
RemTypeRegistry.TypeInfoToXSD(ParamTypeInfo, URI, Result);
if Result = '' then
Result := ParamTypeInfo.Name;
end;
function GetAliasBaseTypeInfo(const ParamType: TTypeKind): PTypeInfo;
begin
case ParamType of
tkInteger: Result := TypeInfo(System.Integer);
tkInt64: Result := TypeInfo(System.Int64);
tkLString: Result := TypeInfo(System.String);
tkWString: Result := TypeInfo(System.WideString);
else
Result := nil;
end;
end;
function TWebServExp.IsComplexType(const ParamTypeInfo: PTypeInfo): Boolean;
var
Name, URI: WideString;
IsScalar: Boolean;
Kind: TTypeKind;
begin
Kind := ParamTypeInfo.Kind;
Result := IsComplexType(Kind);
{ If not, could it be that we have an alias }
if Result = False then
begin
{ Handle a few alias kinds }
if GetAliasBaseTypeInfo(Kind) <> nil then
begin
RemTypeRegistry.InfoToURI(ParamTypeInfo, URI, Name, IsScalar);
{ Provided the typeinfos don't map back to the XMLNamespace }
if URI <> XMLSchemaNameSpace then
Result := True;
end;
end;
end;
function TWebServExp.IsComplexType(const ParamType: TTypeKind ):Boolean;
begin
case ParamType of
tkClass, tkDynArray, tkEnumeration, tkSet:
Result := True;
else
Result := False;
end;
end;
function TWebServExp.GetPrefixForURI(Def: IDefinition; const URI: WideString): WideString;
var
NameSpaceNode: IXMLNode;
begin
Result := '';
if Definition <> nil then
begin
NamespaceNode := Def.FindNamespaceDecl(URI);
if NamespaceNode <> nil then
begin
Result := NamespaceNode.LocalName;
exit;
end;
Result := AddNamespaceURI(Def as IXMLNode, URI);
end;
end;
function TWebServExp.GetPrefixForURI(SchemaDef: IXMLSchemaDef; const URI: WideString): WideString;
var
NameSpaceNode: IXMLNode;
begin
Result := '';
{ Check if the XMLSchema root has it }
NamespaceNode := SchemaDef.FindNamespaceDecl(URI);
if NamespaceNode <> nil then
begin
Result := NamespaceNode.LocalName;
exit;
end
else
begin
{ Check if its a WSDL and if the root has it }
if Definition <> nil then
begin
NamespaceNode := Definition.FindNamespaceDecl(URI);
if NamespaceNode <> nil then
begin
Result := NamespaceNode.LocalName;
exit;
end
else
Result := AddNamespaceURI(Definition as IXMLNode, URI);
end
else
Result := AddNamespaceURI(SchemaDef as IXMLNode, URI);
end;
end;
function TWebServExp.AddNamespaceURI(RootNode: IXMLNode; const URI: WideString): WideString;
begin
Result := RootNode.OwnerDocument.GeneratePrefix(RootNode);
RootNode.DeclareNamespace(Result, URI);
end;
function TWebServExp.GetNodeNameForURI(SchemaDef: IXMLSchemaDef; const URI: WideString): WideString;
var
NameSpaceNode: IXMLNode;
begin
Result := '';
{ Check if the XMLSchema root has it }
NamespaceNode := SchemaDef.FindNamespaceDecl(URI);
if NamespaceNode <> nil then
begin
Result := NamespaceNode.NodeName;
exit;
end
else
begin
{ Check if its a WSDL and if the root has it }
if Definition <> nil then
begin
NamespaceNode := Definition.FindNamespaceDecl(URI);
if NamespaceNode <> nil then
Result := NamespaceNode.NodeName;
end;
end;
end;
procedure TWebServExp.GenerateDerivedClassSchema(SchemaDef: IXMLSchemaDef; const ParentTypeInfo: PTypeinfo; const Namespace:WideString);
var
Count, Index: Integer;
RegEntry: TRemRegEntry;
begin
Count := RemClassRegistry.GetURICount;
for Index := 0 to Count -1 do
begin
RegEntry := RemClassRegistry.GetURIMap(Index);
if RegEntry.ClassType <> nil then
begin
if RegEntry.ClassType.InheritsFrom(GetTypeData(ParentTypeInfo).ClassType)
and (RegEntry.ClassType <> GetTypeData(ParentTypeInfo).ClassType) then
begin
GenerateXMLSchema(SchemaDef, RegEntry.Info, ParentTypeInfo, Namespace);
end;
end;
end;
end;
(*
{ Similar to TypInfo's GetPropInfos except that we don't walk up the base classes }
procedure GetPropInfosInternal(TypeInfo: PTypeInfo; PropList: PPropList); assembler;
asm
{ -> EAX Pointer to type info }
{ EDX Pointer to prop list }
{ <- nothing }
PUSH EBX
PUSH ESI
PUSH EDI
XOR ECX,ECX
MOV ESI,EAX
MOV CL,[EAX].TTypeInfo.Name.Byte[0]
MOV EDI,EDX
XOR EAX,EAX
MOVZX ECX,[ESI].TTypeInfo.Name[ECX+1].TTypeData.PropCount
REP STOSD
@outerLoop:
MOV CL,[ESI].TTypeInfo.Name.Byte[0]
LEA ESI,[ESI].TTypeInfo.Name[ECX+1]
MOV CL,[ESI].TTypeData.UnitName.Byte[0]
MOVZX EAX,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropCount
TEST EAX,EAX
JE @parent
LEA EDI,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropList
@innerLoop:
MOVZX EBX,[EDI].TPropInfo.NameIndex
MOV CL,[EDI].TPropInfo.Name.Byte[0]
CMP dword ptr [EDX+EBX*4],0
JNE @alreadySet
MOV [EDX+EBX*4],EDI
@alreadySet:
LEA EDI,[EDI].TPropInfo.Name[ECX+1]
DEC EAX
JNE @innerLoop
@parent:
@exit:
POP EDI
POP ESI
POP EBX
end;
function GetPropListInternal(TypeInfo: PTypeInfo; out PropList: PPropList): Integer;
begin
Result := GetTypeData(TypeInfo)^.PropCount;
if Result > 0 then
begin
GetMem(PropList, Result * SizeOf(Pointer));
FillChar(PropList^, Result * SizeOf(Pointer), 0);
GetPropInfosInternal(TypeInfo, PropList);
end;
end;
{ Similar to TypInfo's IsStoredProp although this version only handles cases
where the attribute was assigned 'true' or 'false' directly }
function IsStoredPropInternal(Instance: TObject; PropInfo: PPropInfo): Boolean;
asm
{ -> EAX Pointer to Instance }
{ EDX Pointer to prop info }
{ <- AL Function result }
MOV ECX,[EDX].TPropInfo.StoredProc
TEST ECX,0FFFFFF00H
JE @@returnCL
MOV CL, 1
@@returnCL:
MOV AL,CL
@@exit:
end;
{ Returns the TypeInfo of a class member }
function GetMemberTypeInfo(const ObjectTypeInfo: PTypeInfo; const MemberName: string): PTypeInfo;
var
PropList: PPropList;
Size, Props: Integer;
begin
Result := nil;
Size := GetPropListInternal(ObjectTypeInfo, PropList);
try
for Props := 0 to Size -1 do
begin
if PropList[Props] <> nil then
begin
{ Either there's a match or send the only member's TypeInfo back }
if SameText(PropList[Props].Name, MemberName) or ((MemberName = '') and (Size = 1)) then
begin
Result := PropList[Props].PropType^;
Exit;
end;
end;
end;
finally
if Size > 0 then
FreeMem(PropList);
end;
end;
*)
procedure TWebServExp.GenerateClassSchema(SchemaDef: IXMLSchemaDef;
const ATypeInfo, ParentInfo: PTypeinfo;
const Namespace: WideString);
var
Size, Props: integer;
PropList: PPropList;
ComplexType: IXMLComplexTypeDef;
ElementType: IXMLElementDef;
AttributeType: IXMLAttributeDef;
ParamType: string;
BaseName, Pre, PropName: WideString;
AncInfo: PTypeInfo;
SerialOpts: TSerializationOptions;
begin
Size := GetPropListFlat(ATypeInfo, PropList);
try
{ Catch case where class is simply an alias wrapper for a simple type }
SerialOpts := RemClassRegistry.SerializeOptions(GetTypeData(ATypeInfo).ClassType);
if (xoSimpleTypeWrapper in SerialOpts) and (Size = 1) then
begin
{ The class is considered as an alias of the type of it's sole (published) member }
GenerateAliasSchema(SchemaDef, ATypeInfo, Namespace, PropList[0].PropType^);
end
else
begin
if ParentInfo <> nil then
begin
{ Namespace prefix of base type }
Pre := GetPrefixForTypeInfo(ParentInfo);
if Pre <> '' then
BaseName := MakeNodeName(Pre, ParentInfo.Name)
else
BaseName := ParentInfo.Name;
{ Does the parent have a parent ?? }
if GetTypeData(ParentInfo).ParentInfo <> nil then
AncInfo := GetTypeData(ParentInfo).ParentInfo^
else
AncInfo := nil;
{ If yes, validate Grandparent }
if (AncInfo <> nil) and IsBaseClassTypeInfo(AncInfo) then
AncInfo := nil;
{ Generate parent schema }
GenerateXMLSchema(SchemaDef, ParentInfo, AncInfo, Namespace);
{ Add this type's complex type }
ComplexType := SchemaDef.ComplexTypes.Add(GetXMLSchemaTypeName(ATypeInfo), BaseName)
end else
ComplexType := SchemaDef.ComplexTypes.Add(GetXMLSchemaTypeName(ATypeInfo));
{ And the properties }
for Props := 0 to Size -1 do
begin
if PropList[Props] <> nil then
begin
ParamType := GetXMLSchemaType(PropList[Props].PropType^);
PropName := RemClassRegistry.GetExternalPropName(ATypeInfo, PropList[Props].Name);
if IsStoredPropConst(nil, PropList[Props]) then
ElementType := ComplexType.ElementDefs.Add(PropName, ParamType)
else
AttributeType := ComplexType.AttributeDefs.Add(PropName, ParamType);
if IsComplexType(PropList[Props].PropType^) then
GenerateXMLSchema(SchemaDef, PropList[Props].PropType^, nil, Namespace);
end;
end;
end;
finally
if Size > 0 then
FreeMem(PropList);
end;
end;
procedure TWebServExp.GenerateEnumSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString);
var
SimpleType: IXMLSimpleTypeDef;
TypeData: PTypeData;
Index: Integer;
Value: string;
EnumInfo: PTypeInfo;
begin
EnumInfo := ATypeInfo;
{ Here we need to shortcircuit ByteBool, WordBool and LongBool - the
RTTI/Compiler treats them as enumerations with 256, 32K and 2G members
respectively - We don't want to publish these members:) }
if (EnumInfo = TypeInfo(System.ByteBool)) or
(EnumInfo = TypeInfo(System.WordBool)) or
(EnumInfo = TypeInfo(System.LongBool)) then
EnumInfo := TypeInfo(System.Boolean);
TypeData := GetTypeData(EnumInfo);
if TypeData <> nil then
begin
SimpleType := SchemaDef.SimpleTypes.Add(GetXMLSchemaTypeName(ATypeInfo), 'string'); { do not localize }
for Index := 0 to TypeData.MaxValue do
begin
Value := GetEnumName(ATypeInfo, Index);
SimpleType.Enumerations.Add(RemClassRegistry.GetExternalPropName(EnumInfo, Value));
end;
end;
end;
procedure TWebServExp.GenerateAliasSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString;
const ABaseTypeInfo: PTypeInfo = nil);
var
SimpleType: IXMLSimpleTypeDef;
TypeData: PTypeData;
BaseInfo: PTypeInfo;
TypeName: WideString;
begin
TypeData := GetTypeData(ATypeInfo);
if TypeData <> nil then
begin
{ Name ?? }
TypeName := ATypeInfo.Name;
{ Base Type Info }
if ABaseTypeInfo = nil then
BaseInfo := GetAliasBaseTypeInfo(ATypeInfo.Kind)
else
BaseInfo := ABaseTypeInfo;
{ Add type }
SimpleType := SchemaDef.SimpleTypes.Add(GetXMLSchemaTypeName(ATypeInfo), TypeName);
SimpleType.BaseTypeName := GetXMLSchemaType(BaseInfo);
end;
end;
procedure TWebServExp.GenerateArraySchema(SchemaDef: IXMLSchemaDef; const ATypeInfo: PTypeinfo; const Namespace: WideString);
var
ComplexType: IXMLComplexTypeDef;
ElementType: IXMLElementDef;
ElementTypeInfo: PTypeinfo;
I, Dimensions: integer;
ParamType, ArrayElementName: string;
ArrayType: string;
TypeName, Prefix, SoapEncPrefix: WideString;
AttrDef: IXMLAttributeDef;
DimString, ArrayName, TempName: string;
XMLElementDefs: IXMLElementDefs;
begin
if FArrayAsComplexContent then
begin
ElementTypeInfo := GetDynArrayNextInfo2(ATypeInfo, ArrayName);
Dimensions := 1;
while (ElementTypeInfo <> nil) and (ElementTypeInfo.Kind = tkDynArray ) and (ElementTypeInfo.Name[1] = '.') do
begin
Inc(Dimensions);
ElementTypeInfo := GetDynArrayNextInfo2(ElementTypeInfo, TempName);
end;
if (ElementTypeInfo = nil) or (ElementTypeInfo.Name[1] = '.') then
GetDynArrayElTypeInfo(ATypeInfo, ElementTypeInfo, Dimensions);
{
if (ElementTypeInfo.Kind = tkDynArray) and (ArrayName <> '') and (ArrayName[1] <> '.') then
GenerateArraySchema(RootNode, ElementTypeInfo, Namespace);
if (ElementTypeInfo.Kind = tkClass) or (ElementTypeInfo.Kind = tkEnumeration) then
GenerateXMLSchema(RootNode, ElementTypeInfo, nil, Namespace);
}
ParamType := GetXMLSchemaType(ElementTypeInfo);
ArrayType := SArrayOf + ParamType;
{ Get Soap Encoding prefix }
SoapEncPrefix := GetPrefixForURI(SchemaDef, SSoap11EncodingS5);
TypeName := GetXMLSchemaTypeName(ATypeInfo);
ComplexType := SchemaDef.ComplexTypes.Add(TypeName, SoapEncPrefix + ':' + SSoapEncodingArray, dmComplexRestriction);
AttrDef:= ComplexType.AttributeDefs.Add(SoapEncPrefix + ':'+ SArrayType);
{ Get WSDL URI prefix }
Prefix := GetNodeNameForURI(SchemaDef, Wsdlns);
{ Create dimension string }
DimString := '[';
if (Dimensions > 1) then
for I := 1 to Dimensions-1 do
DimString := DimString + ',';
DimString := DimString + ']';
{$IFDEF OPENDOM}
AttrDef.DeclareNameSpace('n1', Wsdlns);
AttrDef.SetAttributeNS(SArrayType, Wsdlns, ParamType + DimString);
{$ELSE}
AttrDef.Attributes['n1'+':'+SArrayType] := ParamType + DimString;
AttrDef.Attributes[Prefix+':'+'n1'] := Wsdlns;
{$ENDIF}
end
else
begin
GetDynArrayElTypeInfo(ATypeInfo, ElementTypeInfo, Dimensions);
ParamType := GetXMLSchemaType(ElementTypeInfo);
ArrayType := SArrayOf + ParamType;
XMLElementDefs := SchemaDef.ElementDefs;
Prefix := GetPrefixForURI(SchemaDef, Soapns);
TypeName := GetXMLSchemaTypeName(ATypeInfo);
ElementType := XMLElementDefs.Add(TypeName, True, MakeNodeName(Prefix, SArray));
{ ElementType := RootNode.SchemaDef.ElementDefs.Add(ATypeInfo.Name, True, SSoapArray); }
{ ElementType := SchemaDef.ElementDefs.Add(ATypeInfo.Name, True, SSoapArray); }
ComplexType := ElementType.DataType as IXMLComplexTypeDef;
ComplexType.Attributes[SName] := ArrayType;
if Dimensions > 1 then
GenerateNestedArraySchema(SchemaDef, ComplexType, ElementTypeInfo, Dimensions, Namespace)
else
begin
ArrayElementName := 'Dimension' + IntToStr(Dimensions);
ParamType := GetXMLSchemaType(ElementTypeInfo);
ElementType := ComplexType.ElementDefs.Add(ArrayElementName, ParamType);
ElementType.Attributes[SMaxOccurs] := SUnbounded;
if IsComplexType(ElementTypeInfo) then
GenerateXMLSchema(SchemaDef, ElementTypeInfo, nil, Namespace);
end;
end;
end;
procedure TWebServExp.GenerateNestedArraySchema(SchemaDef: IXMLSchemaDef; ComplexType: IXMLComplexTypeDef; const ATypeInfo: PTypeinfo; var Dimension: Integer; Namespace: WideString);
var
ParamType: string;
ArrayElementName: String;
ElementType: IXMLElementDef;
NestedType: IXMLComplexTypeDef;
begin
while Dimension <> 0 do
begin
if Dimension > 1 then
begin
ArrayElementName := 'Dimension' + IntToStr(Dimension);
ElementType := ComplexType.ElementDefs.Add(ArrayElementName, True);
ElementType.Attributes[SMaxOccurs] := SUnbounded;
NestedType := ElementType.DataType as IXMLComplexTypeDef;
Dimension := Dimension -1;
GenerateNestedArraySchema(SchemaDef, NestedType, ATypeInfo, Dimension, Namespace);
end
else
begin
ArrayElementName := 'Dimension' + IntToStr(Dimension);
ParamType := GetXMLSchemaType(ATypeInfo);
ElementType := ComplexType.ElementDefs.Add(ArrayElementName, ParamType);
ElementType.Attributes[SMaxOccurs] := SUnbounded;
Dimension := Dimension -1;
if IsComplexType(ATypeInfo) then
GenerateXMLSchema(SchemaDef, ATypeInfo, nil, Namespace);
end;
end; //while
end;
procedure TWebServExp.GenerateXMLSchema(SchemaDef: IXMLSchemaDef; const ATypeInfo, ParentInfo: PTypeinfo; Namespace: WideString);
var
TempURI, TempName: WideString;
AncInfo: PTypeInfo;
begin
if IsComplexType(ATypeInfo) then
begin
{ NOTE: IsSchemaGenerated will toggle the generated flag if it returns false }
if (not IsSchemaGenerated(ATypeInfo, Namespace)) then
begin
case ATypeInfo.Kind of
tkDynArray: GenerateArraySchema(SchemaDef, ATypeInfo, NameSpace);
tkEnumeration: GenerateEnumSchema(SchemaDef, ATypeInfo, NameSpace);
tkClass:
begin
{ Determine the base class info. }
if (ParentInfo = nil) and ((GetTypeData(ATypeInfo).ParentInfo)^ <> nil) then
begin
AncInfo := (GetTypeData(ATypeInfo).ParentInfo)^;
{ Stop as soon as we get to a base class }
if (AncInfo <> nil) and IsBaseClassTypeInfo(AncInfo) then
AncInfo := nil;
{ Or something not registered }
if (AncInfo <> nil) and not RemTypeRegistry.TypeInfoToXSD(AncInfo, TempURI , TempName) then
AncInfo := nil;
end else
AncInfo := ParentInfo;
{ Generate the class schemae }
GenerateClassSchema(SchemaDef, ATypeInfo, AncInfo, Namespace);
{ Generate XML Schema for registered derived classes }
GenerateDerivedClassSchema(SchemaDef, ATypeInfo, Namespace);
end;
else
begin
{ Generate alias }
if GetAliasBaseTypeInfo(ATypeInfo.Kind) <> nil then
GenerateAliasSchema(SchemaDef, ATypeInfo, NameSpace);
end
end;
end;
end;
end;
procedure TWebServExp.GetAllSchemaTypes(const IntfMD: TIntfMetaData);
var
I, Methods, Params, NoOfMethods, NoOfParams: Integer;
IntfMethArray: TIntfMethEntryArray;
ParamArray: TIntfParamEntryArray;
HeaderItems: THeaderItemArray;
ExceptItems: TExceptionItemArray;
begin
IntfMethArray := nil;
ParamArray := nil;
IntfMethArray := IntfMD.MDA;
NoOfMethods := Length(IntfMethArray);
for Methods := 0 to NoOfMethods -1 do
begin
ParamArray := IntfMD.MDA[Methods].Params;
NoOfParams := Length(ParamArray);
{ Note: Skip this/Self }
for Params := 0 to NoOfParams -2 do
begin
if IsComplexType(ParamArray[Params].Info) then
GetSchemaTypes(ParamArray[Params].Info, nil);
end;
{ For Function return type }
if IntfMD.MDA[Methods].ResultInfo <> nil then
begin
{ If the return type is an object }
if IsComplexType(IntfMD.MDA[Methods].ResultInfo) then
GetSchemaTypes(IntfMD.MDA[Methods].ResultInfo, nil);
end;
end;
{ Add all headers of interface to types }
HeaderItems := InvRegistry.GetHeaderInfoForInterface(IntfMD.Info);
for I := 0 to Length(HeaderItems) -1 do
GetSchemaTypes(HeaderItems[I].ClassType.ClassInfo, nil);
{ And all faults of interface to types }
ExceptItems := InvRegistry.GetExceptionInfoForInterface(IntfMD.Info);
for I := 0 to Length(ExceptItems) -1 do
GetSchemaTypes(ExceptItems[I].ClassType.ClassInfo, nil);
end;
procedure TWebServExp.GetDerivedClassSchema(const ParentTypeInfo: PTypeinfo);
var
Count, Index: Integer;
RegEntry: TRemRegEntry;
begin
Count := RemClassRegistry.GetURICount;
for Index := 0 to Count -1 do
begin
RegEntry := RemClassRegistry.GetURIMap(Index);
if RegEntry.ClassType <> nil then
begin
if RegEntry.ClassType.InheritsFrom(GetTypeData(ParentTypeInfo).ClassType) then
GetSchemaTypes(RegEntry.Info, ParentTypeInfo);
end;
end;
end;
function TWebServExp.FindOrAddSchema(const ATypeInfo: PTypeinfo; const TnsURI: string): Boolean;
var
Index: Integer;
begin
Result := False;
{ Do not register Empty TnsURI or tkSet or any predefined type from XMLSchema }
if ((TnsURI = '') or (ATypeInfo.Kind = tkSet) or (TnsURI = SXMLSchemaURI_1999) or (TnsURI = SXMLSchemaURI_2000_10) or
(TnsURI = SXMLSchemaURI_2001)) then
begin
Result := True;
Exit;
end;
for Index := 0 to Length(SchemaArray) -1 do
begin
if SchemaArray[Index].TypeInfo = ATypeInfo then
begin
Result := True;
Exit;
end;
end;
{ Add new type }
Index := Length(SchemaArray);
SetLength(SchemaArray, Index+1);
SchemaArray[Index].TypeName := GetXMLSchemaTypeName(ATypeInfo);
SchemaArray[Index].NameSpace := TnsURI;
SchemaArray[Index].TypeInfo := ATypeInfo;
SchemaArray[Index].XSGenerated := False;
end;
{ NOTE: IsSchemaGenerated has a nasty side-effect - if the generated flag is false, it will
toggle it - Argghh!! }
function TWebServExp.IsSchemaGenerated(const ATypeInfo: PTypeinfo; const TnsURI: WideString): Boolean;
var
Index: Integer;
begin
Result := True;
for Index := 0 to Length(SchemaArray) -1 do
begin
if ((SchemaArray[Index].TypeInfo = ATypeInfo) and
(SchemaArray[Index].NameSpace = TnsURI) ) then
begin
if SchemaArray[Index].XSGenerated = False then
begin
Result := False;
SchemaArray[Index].XSGenerated := True;
end
else
Result := True;
Exit;
end;
end;
end;
function TWebServExp.GetPrefixForTypeInfo(const ATypeInfo: PTypeinfo): WideString;
var
Index: Integer;
begin
Result := '';
for Index := 0 to Length(SchemaArray) -1 do
begin
if (SchemaArray[Index].TypeInfo = ATypeInfo) then
begin
Result := SchemaArray[Index].NSPrefix;
exit;
end;
end;
end;
{ This routines collects all schemas associated with a typeinfo - the Getxxx routines
collect the types; the Generatexxxx generate the XML }
procedure TWebServExp.GetSchemaTypes(const ATypeInfo, ParentInfo: PTypeinfo);
var
URI, Name: WideString;
IsScalar, Registered: Boolean;
begin
if IsComplexType(ATypeInfo) then
begin
Registered := RemClassRegistry.InfoToURI(ATypeInfo, URI, Name, IsScalar);
{ NOTE: If the user forgot to register the type, and
auto-registration is probably turned off ??? }
if not Registered then
begin
{ NOTE: We get here if the user forgot to register the type, and
auto-registration is turned off ??? }
;
end;
{ Add to the SchemaArray to keep track of what complex type has }
{ already been encountered }
if (not FindOrAddSchema(ATypeInfo, URI)) then
begin
case ATypeInfo.Kind of
tkDynArray: GetArraySchema(ATypeInfo);
tkClass:
begin
GetClassSchema(ATypeInfo, ParentInfo);
{ Get all the registered derived classes }
GetDerivedClassSchema(ATypeInfo);
end;
end;
end;
end;
end;
procedure TWebServExp.GetClassSchema(const ATypeInfo, ParentInfo: PTypeinfo);
var
Size, Props: integer;
PropList: PPropList;
begin
Size := GetPropList(ATypeInfo, [tkUnknown..tkDynArray], nil);
if Size > 0 then
begin
PropList := AllocMem(sizeof(TPropInfo) * Size);
try
Size := GetPropList(ATypeInfo, PropList);
for Props := 0 to Size -1 do
begin
if IsComplexType(PropList[Props].PropType^) then
GetSchemaTypes(PropList[Props].PropType^, nil);
end;
finally
FreeMem(PropList);
end;
end; //Size > 0
end;
procedure TWebServExp.GetArraySchema(const ATypeInfo: PTypeinfo);
var
ElementTypeInfo: PTypeInfo;
Dimensions: Integer;
ArrayName, TempName: String;
begin
ElementTypeInfo := GetDynArrayNextInfo2(ATypeInfo, ArrayName);
Dimensions := 1;
{ When the compiler generates *intermediate* typeinfos for multidim arrays, the
ElementTypeInfo name is '.#'; so we can use the '.' to detect this case }
while (ElementTypeInfo <> nil) and (ElementTypeInfo.Kind = tkDynArray ) and (ElementTypeInfo.Name[1] = '.') do
begin
Inc(Dimensions);
ElementTypeInfo := GetDynArrayNextInfo2(ElementTypeInfo, TempName);
end;
if (ElementTypeInfo = nil) or (ElementTypeInfo.Name[1] = '.') then
GetDynArrayElTypeInfo(ATypeInfo, ElementTypeInfo, Dimensions);
if (ElementTypeInfo.Kind = tkDynArray) and (ArrayName <> '') and (ArrayName[1] <> '.') then
GetSchemaTypes(ElementTypeInfo, nil);
if (ElementTypeInfo.Kind = tkClass) or (ElementTypeInfo.Kind = tkEnumeration) then
GetSchemaTypes(ElementTypeInfo, nil);
{
GetDynArrayElTypeInfo(ATypeInfo, ElementTypeInfo, Dim);
if ElementTypeInfo <> nil then
GetSchemaTypes(ElementTypeInfo, nil);
}
end;
function TWebServExp.GetWebServExp: TWebServExp;
begin
Result := Self;
end;
initialization
finalization
end.
|
{
"HTTP Client provider (WinHTTP)" - Copyright (c) Danijel Tkalcec
@html(<br>)
Using WinHTTP API to implement a HTTP Client
connection provider through HTTP Proxy servers
@exclude
}
unit rtcWinHttpCliProv;
{$INCLUDE rtcDefs.inc}
interface
uses
rtcTrashcan,
SysUtils,
Windows,
Classes,
rtcSyncObjs,
rtcThrPool,
rtcFastStrings,
rtcLog,
rtcInfo,
rtcConn,
rtcConnProv,
rtcThrConnProv;
const
LOG_WINHTTP_ERRORS:boolean=False;
type
HINTERNET = Pointer;
RtcWinHttpException = class(Exception);
TRtcWinHttpClientProvider = class;
TRtcWinHttpClientThread = class(TRtcThread)
public
RtcConn:TRtcWinHttpClientProvider;
Releasing:boolean;
public
constructor Create; override;
destructor Destroy; override;
function Work(Job:TObject):boolean; override;
procedure OpenConn;
procedure CloseConn(_lost:boolean);
// procedure Connect;
// procedure Disconnect;
// procedure Release;
end;
TRtcWinHttpClientProvider = class(TRtcThrClientProvider)
private
Client_Thread:TRtcWinHttpClientThread;
Forc:boolean;
FCS:TRtcCritSec;
FOnInvalidResponse:TRtcEvent;
FResponseBuffer:TRtcHugeString;
FReadBuffer:string;
FMaxHeaderSize:integer;
FMaxResponseSize:integer;
FHeaderOut:boolean;
FHeaderEx:boolean;
LenToWrite:int64;
FRequest:TRtcClientRequest;
FResponse:TRtcClientResponse;
FDataWasSent:boolean;
hSession, hConnect, hRequest: hInternet;
hStore, pContext: pointer;
hStoreReady: boolean;
FUseHttps: boolean;
FCertSubject: string;
FCertStoreType: TRtcCertStoreType;
protected
procedure Enter; override;
procedure Leave; override;
function GetClientThread:TRtcThread; override;
procedure TriggerInvalidResponse; virtual;
procedure AcceptResponse; virtual;
function _Active:boolean;
procedure OpenConnection;
function SetupCertificate:boolean;
procedure SendHeaderOut(const s:string);
public
constructor Create; override;
destructor Destroy; override;
procedure Connect(Force:boolean=False); override;
procedure Disconnect; override;
procedure Release; override;
procedure InternalDisconnect; override;
procedure LeavingEvent; virtual;
procedure SetTriggerInvalidResponse(Event:TRtcEvent);
procedure WriteHeader(SendNow:boolean=True); overload; virtual;
procedure WriteHeader(const Header_Text:string; SendNow:boolean=True); overload; virtual;
procedure Write(const s:string; SendNow:boolean=True); override;
function Read:string; override;
property Request:TRtcClientRequest read FRequest write FRequest;
property Response:TRtcClientResponse read FResponse write FResponse;
// Max. allowed size of the first (status) line in response header
property MaxResponseSize:integer read FMaxResponseSize write FMaxResponseSize;
// Max. allowed size of the complete response Header
property MaxHeaderSize:integer read FMaxHeaderSize write FMaxHeaderSize;
// Use HTTPS protocol instead of HTTP
property useHttps:boolean read FUseHttps write FUseHttps;
property CertStoreType:TRtcCertStoreType read FCertStoreType write FCertStoreType;
property CertSubject:string read FCertSubject write FCertSubject;
end;
function HaveWinHTTP:boolean;
implementation
Type
INTERNET_PORT = WORD;
Const
INTERNET_DEFAULT_PORT = 0; // use the protocol-specific default
INTERNET_DEFAULT_HTTP_PORT = 80; // " " HTTP "
INTERNET_DEFAULT_HTTPS_PORT = 443; // " " HTTPS "
WINHTTP_FLAG_ASYNC = $10000000; // this session is asynchronous (where supported)
WINHTTP_FLAG_SECURE = $00800000; // use SSL if applicable (HTTPS)
WINHTTP_FLAG_ESCAPE_PERCENT = $00000004; // if escaping enabled, escape percent as well
WINHTTP_FLAG_NULL_CODEPAGE = $00000008; // assume all symbols are ASCII, use fast convertion
WINHTTP_FLAG_BYPASS_PROXY_CACHE = $00000100; // add "pragma: no-cache" request header
WINHTTP_FLAG_REFRESH = WINHTTP_FLAG_BYPASS_PROXY_CACHE;
WINHTTP_FLAG_ESCAPE_DISABLE = $00000040; // disable escaping
WINHTTP_FLAG_ESCAPE_DISABLE_QUERY = $00000080; // if escaping enabled escape path part, but do not escape query
SECURITY_FLAG_IGNORE_REVOCATION = $00000080;
SECURITY_FLAG_IGNORE_UNKNOWN_CA = $00000100;
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = $00002000; // expired X509 Cert.
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = $00001000; // bad common name in X509 Cert.
SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = $00000200;
Type
PWINHTTP_ASYNC_RESULT=^WINHTTP_ASYNC_RESULT;
WINHTTP_ASYNC_RESULT = packed record
dwResult:PDWORD; // indicates which async API has encountered an error
dwError:DWORD; // the error code if the API failed
End;
PHTTP_VERSION_INFO = ^HTTP_VERSION_INFO;
HTTP_VERSION_INFO = packed record
dwMajorVersion:DWORD;
dwMinorVersion:DWORD;
End;
PINTERNET_SCHEME = ^INTERNET_SCHEME;
INTERNET_SCHEME = integer;
PURL_COMPONENTS = ^URL_COMPONENTS;
URL_COMPONENTS = packed record
dwStructSize:DWORD;
lpszScheme:PWideChar;
dwSchemeLength:DWORD;
nScheme:INTERNET_SCHEME;
lpszHostName:PWideChar;
dwHostNameLength:DWORD;
nPort:INTERNET_PORT;
lpszUserName:PWideChar;
dwUserNameLength:DWORD;
lpszPassword:PWideChar;
dwPasswordLength:DWORD;
lpszUrlPath:PWideChar;
dwUrlPathLength:DWORD;
lpszExtraInfo:PWideChar;
dwExtraInfoLength:DWORD;
End;
PWINHTTP_PROXY_INFO = ^WINHTTP_PROXY_INFO;
WINHTTP_PROXY_INFO = packed record
dwAccessType:DWORD; // see WINHTTP_ACCESS_* types below
lpszProxy:PWideChar; // proxy server list
lpszProxyBypass:PWideChar; // proxy bypass list
End;
PWINHTTP_AUTOPROXY_OPTIONS = ^WINHTTP_AUTOPROXY_OPTIONS;
WINHTTP_AUTOPROXY_OPTIONS = packed record
dwFlags:DWORD;
dwAutoDetectFlags:DWORD;
lpszAutoConfigUrl:PWideChar;
lpvReserved:Pointer;
dwReserved:DWORD;
fAutoLogonIfChallenged:BOOL;
End;
Const
WINHTTP_AUTOPROXY_AUTO_DETECT = $00000001;
WINHTTP_AUTOPROXY_CONFIG_URL = $00000002;
WINHTTP_AUTOPROXY_RUN_INPROCESS = $00010000;
WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = $00020000;
WINHTTP_AUTO_DETECT_TYPE_DHCP = $00000001;
WINHTTP_AUTO_DETECT_TYPE_DNS_A = $00000002;
Type
PWINHTTP_CERTIFICATE_INFO = ^WINHTTP_CERTIFICATE_INFO;
WINHTTP_CERTIFICATE_INFO = packed record
ftExpiry:FILETIME;
ftStart:FILETIME;
lpszSubjectInfo:PWideChar;
lpszIssuerInfo:PWideChar;
lpszProtocolName:PWideChar;
lpszSignatureAlgName:PWideChar;
lpszEncryptionAlgName:PWideChar;
dwKeySize:DWORD;
End;
Const
WINHTTP_TIME_FORMAT_BUFSIZE = 62;
ICU_NO_ENCODE = $20000000; // Don't convert unsafe characters to escape sequence
ICU_DECODE = $10000000; // Convert %XX escape sequences to characters
ICU_NO_META = $08000000; // Don't convert .. etc. meta path sequences
ICU_ENCODE_SPACES_ONLY = $04000000; // Encode spaces only
ICU_BROWSER_MODE = $02000000; // Special encode/decode rules for browser
ICU_ENCODE_PERCENT = $00001000; // Encode any percent (ASCII25)
ICU_ESCAPE = $80000000; // (un)escape URL characters
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0;
WINHTTP_ACCESS_TYPE_NO_PROXY = 1;
WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3;
WINHTTP_NO_PROXY_NAME = nil;
WINHTTP_NO_PROXY_BYPASS = nil;
WINHTTP_FIRST_OPTION = 1; //WINHTTP_OPTION_CALLBACK;
WINHTTP_OPTION_CALLBACK = 1;
WINHTTP_OPTION_RESOLVE_TIMEOUT = 2;
WINHTTP_OPTION_CONNECT_TIMEOUT = 3;
WINHTTP_OPTION_CONNECT_RETRIES = 4;
WINHTTP_OPTION_SEND_TIMEOUT = 5;
WINHTTP_OPTION_RECEIVE_TIMEOUT = 6;
WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT = 7;
WINHTTP_OPTION_HANDLE_TYPE = 9;
WINHTTP_OPTION_READ_BUFFER_SIZE = 12;
WINHTTP_OPTION_WRITE_BUFFER_SIZE = 13;
WINHTTP_OPTION_PARENT_HANDLE = 21;
WINHTTP_OPTION_EXTENDED_ERROR = 24;
WINHTTP_OPTION_SECURITY_FLAGS = 31;
WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT = 32;
WINHTTP_OPTION_URL = 34;
WINHTTP_OPTION_SECURITY_KEY_BITNESS = 36;
WINHTTP_OPTION_PROXY = 38;
WINHTTP_OPTION_USER_AGENT = 41;
WINHTTP_OPTION_CONTEXT_VALUE = 45;
WINHTTP_OPTION_CLIENT_CERT_CONTEXT = 47;
WINHTTP_OPTION_REQUEST_PRIORITY = 58;
WINHTTP_OPTION_HTTP_VERSION = 59;
WINHTTP_OPTION_DISABLE_FEATURE = 63;
WINHTTP_OPTION_CODEPAGE = 68;
WINHTTP_OPTION_MAX_CONNS_PER_SERVER = 73;
WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER = 74;
WINHTTP_OPTION_AUTOLOGON_POLICY = 77;
WINHTTP_OPTION_SERVER_CERT_CONTEXT = 78;
WINHTTP_OPTION_ENABLE_FEATURE = 79;
WINHTTP_OPTION_WORKER_THREAD_COUNT = 80;
WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT = 81;
WINHTTP_OPTION_PASSPORT_COBRANDING_URL = 82;
WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH = 83;
WINHTTP_OPTION_SECURE_PROTOCOLS = 84;
WINHTTP_OPTION_ENABLETRACING = 85;
WINHTTP_OPTION_PASSPORT_SIGN_OUT = 86;
WINHTTP_OPTION_PASSPORT_RETURN_URL = 87;
WINHTTP_OPTION_REDIRECT_POLICY = 88;
WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS = 89;
WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE = 90;
WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE = 91;
WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE = 92;
WINHTTP_LAST_OPTION = WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE;
WINHTTP_OPTION_USERNAME = $1000;
WINHTTP_OPTION_PASSWORD = $1001;
WINHTTP_OPTION_PROXY_USERNAME = $1002;
WINHTTP_OPTION_PROXY_PASSWORD = $1003;
WINHTTP_CONNS_PER_SERVER_UNLIMITED = $FFFFFFFF;
WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM = 0;
WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW = 1;
WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH = 2;
WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM;
// values for WINHTTP_OPTION_REDIRECT_POLICY
WINHTTP_OPTION_REDIRECT_POLICY_NEVER = 0;
WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP = 1;
WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS = 2;
WINHTTP_OPTION_REDIRECT_POLICY_LAST = WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS;
WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT = WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP;
WINHTTP_DISABLE_PASSPORT_AUTH = $00000000;
WINHTTP_ENABLE_PASSPORT_AUTH = $10000000;
WINHTTP_DISABLE_PASSPORT_KEYRING = $20000000;
WINHTTP_ENABLE_PASSPORT_KEYRING = $40000000;
// values for WINHTTP_OPTION_DISABLE_FEATURE
WINHTTP_DISABLE_COOKIES = $00000001;
WINHTTP_DISABLE_REDIRECTS = $00000002;
WINHTTP_DISABLE_AUTHENTICATION = $00000004;
WINHTTP_DISABLE_KEEP_ALIVE = $00000008;
// values for WINHTTP_OPTION_ENABLE_FEATURE
WINHTTP_ENABLE_SSL_REVOCATION = $00000001;
WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION = $00000002;
//
// winhttp handle types
//
WINHTTP_HANDLE_TYPE_SESSION = 1;
WINHTTP_HANDLE_TYPE_CONNECT = 2;
WINHTTP_HANDLE_TYPE_REQUEST = 3;
//
// values for auth schemes
//
WINHTTP_AUTH_SCHEME_BASIC = $00000001;
WINHTTP_AUTH_SCHEME_NTLM = $00000002;
WINHTTP_AUTH_SCHEME_PASSPORT = $00000004;
WINHTTP_AUTH_SCHEME_DIGEST = $00000008;
WINHTTP_AUTH_SCHEME_NEGOTIATE = $00000010;
// WinHttp supported Authentication Targets
WINHTTP_AUTH_TARGET_SERVER = $00000000;
WINHTTP_AUTH_TARGET_PROXY = $00000001;
//
// values for WINHTTP_OPTION_SECURITY_FLAGS
//
// query only
SECURITY_FLAG_SECURE = $00000001; // can query only
SECURITY_FLAG_STRENGTH_WEAK = $10000000;
SECURITY_FLAG_STRENGTH_MEDIUM = $40000000;
SECURITY_FLAG_STRENGTH_STRONG = $20000000;
// Secure connection error status flags
WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED = $00000001;
WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT = $00000002;
WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED = $00000004;
WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA = $00000008;
WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID = $00000010;
WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID = $00000020;
WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE = $00000040;
WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR = $80000000;
WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 = $00000008;
WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 = $00000020;
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 = $00000080;
WINHTTP_FLAG_SECURE_PROTOCOL_ALL = (WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 or
WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 or
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1);
//
// callback function for WinHttpSetStatusCallback
//
type
WINHTTP_STATUS_CALLBACK = procedure (hInternet:HINTERNET;dwContext:PDWORD;dwInternetStatus:DWORD;lpvStatusInformation:Pointer;dwStatusInformationLength:DWORD);stdcall;
Const
WINHTTP_CALLBACK_STATUS_RESOLVING_NAME = $00000001;
WINHTTP_CALLBACK_STATUS_NAME_RESOLVED = $00000002;
WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER = $00000004;
WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER = $00000008;
WINHTTP_CALLBACK_STATUS_SENDING_REQUEST = $00000010;
WINHTTP_CALLBACK_STATUS_REQUEST_SENT = $00000020;
WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE = $00000040;
WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED = $00000080;
WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION = $00000100;
WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED = $00000200;
WINHTTP_CALLBACK_STATUS_HANDLE_CREATED = $00000400;
WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING = $00000800;
WINHTTP_CALLBACK_STATUS_DETECTING_PROXY = $00001000;
WINHTTP_CALLBACK_STATUS_REDIRECT = $00004000;
WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE = $00008000;
WINHTTP_CALLBACK_STATUS_SECURE_FAILURE = $00010000;
WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE = $00020000;
WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE = $00040000;
WINHTTP_CALLBACK_STATUS_READ_COMPLETE = $00080000;
WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE = $00100000;
WINHTTP_CALLBACK_STATUS_REQUEST_ERROR = $00200000;
WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE = $00400000;
WINHTTP_CALLBACK_FLAG_RESOLVE_NAME = (WINHTTP_CALLBACK_STATUS_RESOLVING_NAME or WINHTTP_CALLBACK_STATUS_NAME_RESOLVED);
WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER = (WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER or WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER);
WINHTTP_CALLBACK_FLAG_SEND_REQUEST = (WINHTTP_CALLBACK_STATUS_SENDING_REQUEST or WINHTTP_CALLBACK_STATUS_REQUEST_SENT);
WINHTTP_CALLBACK_FLAG_RECEIVE_RESPONSE = (WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE or WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED);
WINHTTP_CALLBACK_FLAG_CLOSE_CONNECTION = (WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION or WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED);
WINHTTP_CALLBACK_FLAG_HANDLES = (WINHTTP_CALLBACK_STATUS_HANDLE_CREATED or WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING);
WINHTTP_CALLBACK_FLAG_DETECTING_PROXY = WINHTTP_CALLBACK_STATUS_DETECTING_PROXY;
WINHTTP_CALLBACK_FLAG_REDIRECT = WINHTTP_CALLBACK_STATUS_REDIRECT;
WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE = WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE;
WINHTTP_CALLBACK_FLAG_SECURE_FAILURE = WINHTTP_CALLBACK_STATUS_SECURE_FAILURE;
WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE = WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE;
WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE = WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE;
WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE = WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE;
WINHTTP_CALLBACK_FLAG_READ_COMPLETE = WINHTTP_CALLBACK_STATUS_READ_COMPLETE;
WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE = WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE;
WINHTTP_CALLBACK_FLAG_REQUEST_ERROR = WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS = (WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE
or WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
or WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
or WINHTTP_CALLBACK_STATUS_READ_COMPLETE
or WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
or WINHTTP_CALLBACK_STATUS_REQUEST_ERROR);
WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS = $ffffffff;
//
// if the following value is returned by WinHttpSetStatusCallback, then
// probably an invalid (non-code) address was supplied for the callback
//
WINHTTP_INVALID_STATUS_CALLBACK = (Pointer(-1));
//
// WinHttpQueryHeaders info levels. Generally, there is one info level
// for each potential RFC822/HTTP/MIME header that an HTTP server
// may send as part of a request response.
//
// The WINHTTP_QUERY_RAW_HEADERS info level is provided for clients
// that choose to perform their own header parsing.
//
WINHTTP_QUERY_MIME_VERSION = 0;
WINHTTP_QUERY_CONTENT_TYPE = 1;
WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2;
WINHTTP_QUERY_CONTENT_ID = 3;
WINHTTP_QUERY_CONTENT_DESCRIPTION = 4;
WINHTTP_QUERY_CONTENT_LENGTH = 5;
WINHTTP_QUERY_CONTENT_LANGUAGE = 6;
WINHTTP_QUERY_ALLOW = 7;
WINHTTP_QUERY_PUBLIC = 8;
WINHTTP_QUERY_DATE = 9;
WINHTTP_QUERY_EXPIRES = 10;
WINHTTP_QUERY_LAST_MODIFIED = 11;
WINHTTP_QUERY_MESSAGE_ID = 12;
WINHTTP_QUERY_URI = 13;
WINHTTP_QUERY_DERIVED_FROM = 14;
WINHTTP_QUERY_COST = 15;
WINHTTP_QUERY_LINK = 16;
WINHTTP_QUERY_PRAGMA = 17;
WINHTTP_QUERY_VERSION = 18; // special: part of status line
WINHTTP_QUERY_STATUS_CODE = 19; // special: part of status line
WINHTTP_QUERY_STATUS_TEXT = 20; // special: part of status line
WINHTTP_QUERY_RAW_HEADERS = 21; // special: all headers as ASCIIZ
WINHTTP_QUERY_RAW_HEADERS_CRLF = 22; // special: all headers
WINHTTP_QUERY_CONNECTION = 23;
WINHTTP_QUERY_ACCEPT = 24;
WINHTTP_QUERY_ACCEPT_CHARSET = 25;
WINHTTP_QUERY_ACCEPT_ENCODING = 26;
WINHTTP_QUERY_ACCEPT_LANGUAGE = 27;
WINHTTP_QUERY_AUTHORIZATION = 28;
WINHTTP_QUERY_CONTENT_ENCODING = 29;
WINHTTP_QUERY_FORWARDED = 30;
WINHTTP_QUERY_FROM = 31;
WINHTTP_QUERY_IF_MODIFIED_SINCE = 32;
WINHTTP_QUERY_LOCATION = 33;
WINHTTP_QUERY_ORIG_URI = 34;
WINHTTP_QUERY_REFERER = 35;
WINHTTP_QUERY_RETRY_AFTER = 36;
WINHTTP_QUERY_SERVER = 37;
WINHTTP_QUERY_TITLE = 38;
WINHTTP_QUERY_USER_AGENT = 39;
WINHTTP_QUERY_WWW_AUTHENTICATE = 40;
WINHTTP_QUERY_PROXY_AUTHENTICATE = 41;
WINHTTP_QUERY_ACCEPT_RANGES = 42;
WINHTTP_QUERY_SET_COOKIE = 43;
WINHTTP_QUERY_COOKIE = 44;
WINHTTP_QUERY_REQUEST_METHOD = 45; // special: GET/POST etc.
WINHTTP_QUERY_REFRESH = 46;
WINHTTP_QUERY_CONTENT_DISPOSITION = 47;
//
// HTTP 1.1 defined headers
//
WINHTTP_QUERY_AGE = 48;
WINHTTP_QUERY_CACHE_CONTROL = 49;
WINHTTP_QUERY_CONTENT_BASE = 50;
WINHTTP_QUERY_CONTENT_LOCATION = 51;
WINHTTP_QUERY_CONTENT_MD5 = 52;
WINHTTP_QUERY_CONTENT_RANGE = 53;
WINHTTP_QUERY_ETAG = 54;
WINHTTP_QUERY_HOST = 55;
WINHTTP_QUERY_IF_MATCH = 56;
WINHTTP_QUERY_IF_NONE_MATCH = 57;
WINHTTP_QUERY_IF_RANGE = 58;
WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59;
WINHTTP_QUERY_MAX_FORWARDS = 60;
WINHTTP_QUERY_PROXY_AUTHORIZATION = 61;
WINHTTP_QUERY_RANGE = 62;
WINHTTP_QUERY_TRANSFER_ENCODING = 63;
WINHTTP_QUERY_UPGRADE = 64;
WINHTTP_QUERY_VARY = 65;
WINHTTP_QUERY_VIA = 66;
WINHTTP_QUERY_WARNING = 67;
WINHTTP_QUERY_EXPECT = 68;
WINHTTP_QUERY_PROXY_CONNECTION = 69;
WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70;
WINHTTP_QUERY_PROXY_SUPPORT = 75;
WINHTTP_QUERY_AUTHENTICATION_INFO = 76;
WINHTTP_QUERY_PASSPORT_URLS = 77;
WINHTTP_QUERY_PASSPORT_CONFIG = 78;
WINHTTP_QUERY_MAX = 78;
//
// WINHTTP_QUERY_CUSTOM - if this special value is supplied as the dwInfoLevel
// parameter of WinHttpQueryHeaders() then the lpBuffer parameter contains the name
// of the header we are to query
//
WINHTTP_QUERY_CUSTOM = 65535;
//
// WINHTTP_QUERY_FLAG_REQUEST_HEADERS - if this bit is set in the dwInfoLevel
// parameter of WinHttpQueryHeaders() then the request headers will be queried for the
// request information
//
WINHTTP_QUERY_FLAG_REQUEST_HEADERS = $80000000;
//
// WINHTTP_QUERY_FLAG_SYSTEMTIME - if this bit is set in the dwInfoLevel parameter
// of WinHttpQueryHeaders() AND the header being queried contains date information,
// e.g. the "Expires:" header then lpBuffer will contain a SYSTEMTIME structure
// containing the date and time information converted from the header string
//
WINHTTP_QUERY_FLAG_SYSTEMTIME = $40000000;
//
// WINHTTP_QUERY_FLAG_NUMBER - if this bit is set in the dwInfoLevel parameter of
// HttpQueryHeader(), then the value of the header will be converted to a number
// before being returned to the caller, if applicable
//
WINHTTP_QUERY_FLAG_NUMBER = $20000000;
//
// HTTP Response Status Codes:
//
HTTP_STATUS_CONTINUE = 100; // OK to continue with request
HTTP_STATUS_SWITCH_PROTOCOLS = 101; // server has switched protocols in upgrade header
HTTP_STATUS_OK = 200; // request completed
HTTP_STATUS_CREATED = 201; // object created, reason = new URI
HTTP_STATUS_ACCEPTED = 202; // async completion (TBS)
HTTP_STATUS_PARTIAL = 203; // partial completion
HTTP_STATUS_NO_CONTENT = 204; // no info to return
HTTP_STATUS_RESET_CONTENT = 205; // request completed, but clear form
HTTP_STATUS_PARTIAL_CONTENT = 206; // partial GET fulfilled
HTTP_STATUS_WEBDAV_MULTI_STATUS= 207; // WebDAV Multi-Status
HTTP_STATUS_AMBIGUOUS = 300; // server couldn't decide what to return
HTTP_STATUS_MOVED = 301; // object permanently moved
HTTP_STATUS_REDIRECT = 302; // object temporarily moved
HTTP_STATUS_REDIRECT_METHOD = 303; // redirection w/ new access method
HTTP_STATUS_NOT_MODIFIED = 304; // if-modified-since was not modified
HTTP_STATUS_USE_PROXY = 305; // redirection to proxy, location header specifies proxy to use
HTTP_STATUS_REDIRECT_KEEP_VERB = 307; // HTTP/1.1: keep same verb
HTTP_STATUS_BAD_REQUEST = 400; // invalid syntax
HTTP_STATUS_DENIED = 401; // access denied
HTTP_STATUS_PAYMENT_REQ = 402; // payment required
HTTP_STATUS_FORBIDDEN = 403; // request forbidden
HTTP_STATUS_NOT_FOUND = 404; // object not found
HTTP_STATUS_BAD_METHOD = 405; // method is not allowed
HTTP_STATUS_NONE_ACCEPTABLE = 406; // no response acceptable to client found
HTTP_STATUS_PROXY_AUTH_REQ = 407; // proxy authentication required
HTTP_STATUS_REQUEST_TIMEOUT = 408; // server timed out waiting for request
HTTP_STATUS_CONFLICT = 409; // user should resubmit with more info
HTTP_STATUS_GONE = 410; // the resource is no longer available
HTTP_STATUS_LENGTH_REQUIRED = 411; // the server refused to accept request w/o a length
HTTP_STATUS_PRECOND_FAILED = 412; // precondition given in request failed
HTTP_STATUS_REQUEST_TOO_LARGE = 413; // request entity was too large
HTTP_STATUS_URI_TOO_LONG = 414; // request URI too long
HTTP_STATUS_UNSUPPORTED_MEDIA = 415; // unsupported media type
HTTP_STATUS_RETRY_WITH = 449; // retry after doing the appropriate action.
HTTP_STATUS_SERVER_ERROR = 500; // internal server error
HTTP_STATUS_NOT_SUPPORTED = 501; // required not supported
HTTP_STATUS_BAD_GATEWAY = 502; // error response received from gateway
HTTP_STATUS_SERVICE_UNAVAIL = 503; // temporarily overloaded
HTTP_STATUS_GATEWAY_TIMEOUT = 504; // timed out waiting for gateway
HTTP_STATUS_VERSION_NOT_SUP = 505; // HTTP version not supported
HTTP_STATUS_FIRST = HTTP_STATUS_CONTINUE;
HTTP_STATUS_LAST = HTTP_STATUS_VERSION_NOT_SUP;
WINHTTP_NO_REFERER = nil;
WINHTTP_DEFAULT_ACCEPT_TYPES = nil;
WINHTTP_ADDREQ_INDEX_MASK = $0000FFFF;
WINHTTP_ADDREQ_FLAGS_MASK = $FFFF0000;
WINHTTP_ADDREQ_FLAG_ADD_IF_NEW = $10000000;
WINHTTP_ADDREQ_FLAG_ADD = $20000000;
WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = $40000000;
WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = $01000000;
WINHTTP_ADDREQ_FLAG_COALESCE = WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA;
WINHTTP_ADDREQ_FLAG_REPLACE = $80000000;
WINHTTP_NO_ADDITIONAL_HEADERS = nil;
WINHTTP_NO_REQUEST_DATA = nil;
WINHTTP_HEADER_NAME_BY_INDEX = nil;
WINHTTP_NO_OUTPUT_BUFFER = nil;
WINHTTP_NO_HEADER_INDEX = nil;
Type
PWINHTTP_CURRENT_USER_IE_PROXY_CONFIG = ^WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG = packed record
fAutoDetect:BOOL;
lpszAutoConfigUrl:PWideChar;
lpszProxy:PWideChar;
lpszProxyBypass:PWideChar;
End;
Const
WINHTTP_ERROR_BASE = 12000;
ERROR_WINHTTP_OUT_OF_HANDLES = (WINHTTP_ERROR_BASE + 1);
ERROR_WINHTTP_TIMEOUT = (WINHTTP_ERROR_BASE + 2);
ERROR_WINHTTP_INTERNAL_ERROR = (WINHTTP_ERROR_BASE + 4);
ERROR_WINHTTP_INVALID_URL = (WINHTTP_ERROR_BASE + 5);
ERROR_WINHTTP_UNRECOGNIZED_SCHEME = (WINHTTP_ERROR_BASE + 6);
ERROR_WINHTTP_NAME_NOT_RESOLVED = (WINHTTP_ERROR_BASE + 7);
ERROR_WINHTTP_INVALID_OPTION = (WINHTTP_ERROR_BASE + 9);
ERROR_WINHTTP_OPTION_NOT_SETTABLE = (WINHTTP_ERROR_BASE + 11);
ERROR_WINHTTP_SHUTDOWN = (WINHTTP_ERROR_BASE + 12);
ERROR_WINHTTP_LOGIN_FAILURE = (WINHTTP_ERROR_BASE + 15);
ERROR_WINHTTP_OPERATION_CANCELLED = (WINHTTP_ERROR_BASE + 17);
ERROR_WINHTTP_INCORRECT_HANDLE_TYPE = (WINHTTP_ERROR_BASE + 18);
ERROR_WINHTTP_INCORRECT_HANDLE_STATE = (WINHTTP_ERROR_BASE + 19);
ERROR_WINHTTP_CANNOT_CONNECT = (WINHTTP_ERROR_BASE + 29);
ERROR_WINHTTP_CONNECTION_ERROR = (WINHTTP_ERROR_BASE + 30);
ERROR_WINHTTP_RESEND_REQUEST = (WINHTTP_ERROR_BASE + 32);
ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = (WINHTTP_ERROR_BASE + 44);
//
// WinHttpRequest Component errors
//
ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN = (WINHTTP_ERROR_BASE + 100);
ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND = (WINHTTP_ERROR_BASE + 101);
ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND = (WINHTTP_ERROR_BASE + 102);
ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN = (WINHTTP_ERROR_BASE + 103);
ERROR_WINHTTP_HEADER_NOT_FOUND = (WINHTTP_ERROR_BASE + 150);
ERROR_WINHTTP_INVALID_SERVER_RESPONSE = (WINHTTP_ERROR_BASE + 152);
ERROR_WINHTTP_INVALID_QUERY_REQUEST = (WINHTTP_ERROR_BASE + 154);
ERROR_WINHTTP_HEADER_ALREADY_EXISTS = (WINHTTP_ERROR_BASE + 155);
ERROR_WINHTTP_REDIRECT_FAILED = (WINHTTP_ERROR_BASE + 156);
ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR = (WINHTTP_ERROR_BASE + 178);
ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT = (WINHTTP_ERROR_BASE + 166);
ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = (WINHTTP_ERROR_BASE + 167);
ERROR_WINHTTP_NOT_INITIALIZED = (WINHTTP_ERROR_BASE + 172);
ERROR_WINHTTP_SECURE_FAILURE = (WINHTTP_ERROR_BASE + 175);
ERROR_WINHTTP_SECURE_CERT_DATE_INVALID = (WINHTTP_ERROR_BASE + 37);
ERROR_WINHTTP_SECURE_CERT_CN_INVALID = (WINHTTP_ERROR_BASE + 38);
ERROR_WINHTTP_SECURE_INVALID_CA = (WINHTTP_ERROR_BASE + 45);
ERROR_WINHTTP_SECURE_CERT_REV_FAILED = (WINHTTP_ERROR_BASE + 57);
ERROR_WINHTTP_SECURE_CHANNEL_ERROR = (WINHTTP_ERROR_BASE + 157);
ERROR_WINHTTP_SECURE_INVALID_CERT = (WINHTTP_ERROR_BASE + 169);
ERROR_WINHTTP_SECURE_CERT_REVOKED = (WINHTTP_ERROR_BASE + 170);
ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE = (WINHTTP_ERROR_BASE + 179);
ERROR_WINHTTP_AUTODETECTION_FAILED = (WINHTTP_ERROR_BASE + 180);
ERROR_WINHTTP_HEADER_COUNT_EXCEEDED = (WINHTTP_ERROR_BASE + 181);
ERROR_WINHTTP_HEADER_SIZE_OVERFLOW = (WINHTTP_ERROR_BASE + 182);
ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW= (WINHTTP_ERROR_BASE + 183);
ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW = (WINHTTP_ERROR_BASE + 184);
WINHTTP_ERROR_LAST = (WINHTTP_ERROR_BASE + 184);
const
CRLF = #13#10;
winhttpdll = 'winhttp.dll';
wincrypt = 'crypt32.dll';
CERT_STORE_CLOSE_FORCE_FLAG = 1;
X509_ASN_ENCODING:DWORD = 1;
PKCS_7_ASN_ENCODING:DWORD = 65536;
CERT_FIND_SUBJECT_STR_A = 458759;
CERT_FIND_SUBJECT_STR_W = 524295;
CERT_FIND_ISSUER_STR_A = 458756;
CERT_FIND_ISSUER_STR_W = 524292;
INTERNET_OPTION_CLIENT_CERT_CONTEXT = 84;
type
TRtcBaseMessage=class
end;
//Function WinHttpQueryDataAvailable(hRequest:HINTERNET;var lpdwNumberOfBytesAviable:DWORD):BOOL; stdcall external 'winhttp.dll' name 'WinHttpQueryDataAvailable';
//Function WinHttpAddRequestHeaders(hRequest:HINTERNET;pwszHeaders:PWideChar;dwHeaderLength:DWORD;dwModifiers:DWORD):BOOL; stdcall external 'winhttp.dll' name 'WinHttpAddRequestHeaders';
EWinCryptException=Class(Exception);
EWinInetException=Class(Exception);
HCERTSTORE = pointer;
PCERT_INFO = pointer;
CERT_CONTEXT = packed record
dwCertEncodingType:DWORD;
pbCertEncoded:pointer;
cbCertEncoded:DWORD;
pCertInfo:PCERT_INFO;
hCertStore:HCERTSTORE;
end;
PCCERT_CONTEXT = ^CERT_CONTEXT;
{CertOpenSystemStoreA}
TCertOpenSystemStore = function(hprov:pointer;
szSubsystemProtocol:LPTSTR):HCERTSTORE; stdcall;
{CertCloseStore}
TCertCloseStore = function(hCertStore:HCERTSTORE;
dwFlags:DWORD):BOOL; stdcall;
{CertFindCertificateInStore}
TCertFindCertificateInStore = function(hCertStore:HCERTSTORE;
dwCertEncodingType:DWORD;
dwFindFlags:DWORD;
dwFindType:DWORD;
pvFindPara:PChar;
pPrevCertContext:PCCERT_CONTEXT):PCCERT_CONTEXT; stdcall;
{CertFreeCertificateContext}
TCertFreeCertificateContext = function(pCertContext:PCCERT_CONTEXT):BOOL; stdcall;
{InternetQueryOption}
TInternetQueryOption = Function(hInet: HINTERNET; dwOption: DWORD;
lpBuffer: Pointer;
var lpdwBufferLength: DWORD): BOOL; stdcall;
{InternetSetOption}
TInternetSetOption = Function(hInet: HINTERNET; dwOption: DWORD;
lpBuffer: Pointer;
dwBufferLength: DWORD): BOOL; stdcall;
{InternetOpen}
TInternetOpen = Function(pwszUserAgent:PWideChar;
dwAccessType:DWORD;
pwszProxyName:PWideChar;
pwszProxyBypass:PWideChar;
dwFlags:DWORD):HINTERNET;stdcall;
{InternetConnect}
TInternetConnect = Function(hSession:HINTERNET;
pswzServerName:PWideChar;
nServerPort:WORD;
dwReserved:DWORD):HINTERNET; stdcall;
{InternetCloseHandle}
TInternetCloseHandle = Function(hInternet:HINTERNET):BOOL; stdcall;
{HttpOpenRequest}
THttpOpenRequest = Function(hConnect:HINTERNET;
pwszVerb:PWideChar;
pwszObjectName:PWideChar;
pwszVersion:PWideChar;
pwszReferrer:PWideChar;
ppwszAccessTypes:PWideChar;
dwFalgs:DWORD):HINTERNET; stdcall;
{HttpSendRequest}
THttpSendRequest = Function(hRequest:HINTERNET;
pwszHeaders:PWideChar;
dwHeadersLength:DWORD;
lpOptional:Pointer;
dwOptionalLength:DWORD;
dwTotalLength:DWORD;
dwContext:PDWORD):BOOL; stdcall;
{HttpEndRequest}
THttpEndRequest = function(hRequest:HINTERNET;
lpReserved:Pointer):BOOL; stdcall;
{InternetReadFile}
TInternetReadFile = Function(hRequest:HINTERNET;
lpBuffer:Pointer;
dwNumberOfBytesToRead:DWORD;
var lpdwNumberOfBytesRead:DWORD):BOOL; stdcall;
{InternetWriteFile}
TInternetWriteFile = Function(hRequest:HINTERNET;
lpBuffer:Pointer;
dwNumberOfBytesToWrite:DWORD;
var lpdwNumberOfBytesWritten:DWORD):BOOL; stdcall;
{HttpQueryInfo}
THttpQueryInfo = Function(hRequest:HINTERNET;
dwInfoLevel:DWORD;
pwszName:PWideChar;
lpBuffer:Pointer;
var lpdwBufferLength:DWORD;
var lpdwIndex:DWORD):BOOL; stdcall;
var
CertOpenSystemStore: TCertOpenSystemStore;
CertCloseStore: TCertCloseStore;
CertFindCertificateInStore: TCertFindCertificateInStore;
CertFreeCertificateContext: TCertFreeCertificateContext;
InternetOpen: TInternetOpen;
InternetConnect: TInternetConnect;
InternetCloseHandle: TInternetCloseHandle;
HttpOpenRequest: THttpOpenRequest;
HttpSendRequest: THttpSendRequest;
HttpEndRequest: THttpEndRequest;
InternetReadFile: TInternetReadFile;
InternetWriteFile: TInternetWriteFile;
HttpQueryInfo: THttpQueryInfo;
InternetSetOption: TInternetSetOption;
InternetQueryOption: TInternetQueryOption;
LibCS:TRtcCritSec;
Message_WSStop,
Message_WSRelease,
Message_WSOpenConn,
Message_WSCloseConn:TRtcBaseMessage;
TriedLoading:boolean = False;
FDllHandle:THandle = 0;
FDllHandle2:THandle = 0;
function WinCryptGetProc(const ProcName : String) : Pointer;
begin
if Length(ProcName) = 0 then
Result := nil
else
begin
Result := GetProcAddress(FDllHandle, @ProcName[1]);
if Result = nil then
raise EWinCryptException.Create('Procedure ' + ProcName +
' not found in ' + wincrypt +
' Error #' + IntToStr(GetLastError));
end;
end;
procedure WinCryptLoad;
begin
LibCS.Enter;
try
if FDllHandle = 0 then
begin
FDllHandle := LoadLibrary(@wincrypt[1]);
if FDllHandle = 0 then
raise EWinCryptException.Create('Unable to load ' + wincrypt +
' Error #' + IntToStr(GetLastError));
try
CertOpenSystemStore := TCertOpenSystemStore(WinCryptGetProc('CertOpenSystemStoreA'));
CertCloseStore := TCertCloseStore(WinCryptGetProc('CertCloseStore'));
CertFindCertificateInStore := TCertFindCertificateInStore(WinCryptGetProc('CertFindCertificateInStore'));
CertFreeCertificateContext := TCertFreeCertificateContext(WinCryptGetProc('CertFreeCertificateContext'));
except
FreeLibrary(FDllHandle);
FDllHandle:=0;
raise;
end;
end;
finally
LibCS.Leave;
end;
end;
procedure WinCryptUnload;
begin
LibCS.Enter;
try
if FDllHandle<>0 then
begin
FreeLibrary(FDllHandle);
FDllHandle:=0;
end;
finally
LibCS.Leave;
end;
end;
function WinHttpGetProc(const ProcName : String) : Pointer;
begin
if Length(ProcName) = 0 then
Result := nil
else
begin
Result := GetProcAddress(FDllHandle2, @ProcName[1]);
if Result = nil then
raise RtcWinHttpException.Create('Procedure ' + ProcName +
' not found in ' + winhttpdll +
' Error #' + IntToStr(GetLastError));
end;
end;
procedure WinHttpLoad;
begin
LibCS.Enter;
try
if FDllHandle2 = 0 then
begin
if not TriedLoading then
begin
TriedLoading:=True;
FDllHandle2 := LoadLibrary(@winhttpdll[1]);
if FDllHandle2 <> 0 then
begin
try
InternetOpen := TInternetOpen(WinHttpGetProc('WinHttpOpen'));
InternetConnect := TInternetConnect(WinHttpGetProc('WinHttpConnect'));
InternetCloseHandle := TInternetCloseHandle(WinHttpGetProc('WinHttpCloseHandle'));
HttpOpenRequest := THttpOpenRequest(WinHttpGetProc('WinHttpOpenRequest'));
HttpSendRequest := THttpSendRequest(WinHttpGetProc('WinHttpSendRequest'));
HttpEndRequest := THttpEndRequest(WinHttpGetProc('WinHttpReceiveResponse'));
InternetReadFile := TInternetReadFile(WinHttpGetProc('WinHttpReadData'));
InternetWriteFile := TInternetWriteFile(WinHttpGetProc('WinHttpWriteData'));
HttpQueryInfo := THttpQueryInfo(WinHttpGetProc('WinHttpQueryHeaders'));
InternetSetOption := TInternetSetOption(WinHttpGetProc('WinHttpSetOption'));
InternetQueryOption := TInternetQueryOption(WinHttpGetProc('WinHttpQueryOption'));
except
FreeLibrary(FDllHandle2);
FDllHandle2:=0;
end;
end;
end;
end;
finally
LibCS.Leave;
end;
end;
procedure WinHttpUnload;
begin
LibCS.Enter;
try
if FDllHandle2<>0 then
begin
FreeLibrary(FDllHandle2);
FDllHandle2:=0;
end;
finally
LibCS.Leave;
end;
end;
function HaveWinHTTP:boolean;
begin
WinHttpLoad;
LibCS.Enter;
try
Result:=FDllHandle2<>0;
finally
LibCS.Leave;
end;
end;
{ TRtcWInetHttpClientProvider }
constructor TRtcWinHttpClientProvider.Create;
begin
inherited;
FUseHttps:=False;
FCS:=TRtcCritSec.Create;
FResponseBuffer:=TRtcHugeString.Create;
FDataWasSent:=False;
SetLength(FReadBuffer,32000);
hStore:=nil;
hStoreReady:=False;
end;
destructor TRtcWinHttpClientProvider.Destroy;
begin
Silent:=True;
Closing:=True;
InternalDisconnect;
if assigned(Client_Thread) then
TRtcThread.PostJob(Client_Thread, Message_WSStop, True);
FResponseBuffer.Free;
FResponseBuffer:=nil;
FReadBuffer:='';
FCS.Free;
if hStore<>nil then
begin
try
CertCloseStore(hStore,CERT_STORE_CLOSE_FORCE_FLAG);
except
end;
hStore:=nil;
hStoreReady:=False;
end;
inherited;
end;
procedure TRtcWinHttpClientProvider.Enter;
begin
FCS.Enter;
end;
procedure TRtcWinHttpClientProvider.Leave;
begin
FCS.Leave;
end;
procedure TRtcWinHttpClientProvider.SetTriggerInvalidResponse(Event: TRtcEvent);
begin
FOnInvalidResponse:=Event;
end;
procedure TRtcWinHttpClientProvider.TriggerInvalidResponse;
begin
if assigned(FOnInvalidResponse) then
FOnInvalidResponse;
end;
function TRtcWinHttpClientProvider.GetClientThread: TRtcThread;
begin
Result:=Client_Thread;
end;
procedure TRtcWinHttpClientProvider.Connect(Force: boolean);
begin
if assigned(Client_Thread) and not inThread then
TRtcThread.PostJob(Client_Thread, Message_WSOpenConn)
else
begin
if GetMultiThreaded then
begin
if not assigned(Client_Thread) then
begin
Client_Thread:=TRtcWinHttpClientThread.Create;
Client_Thread.RtcConn:=self;
end;
Forc:=Force;
TRtcThread.PostJob(Client_Thread, Message_WSOpenConn);
end
else
OpenConnection;
end;
end;
procedure TRtcWinHttpClientProvider.OpenConnection;
var
myPort:integer;
myWAddr:WideString;
begin
if (State=conActive) or (State=conActivating) then Exit; // already connected !!!
if State<>conInactive then
raise Exception.Create('Can not connect again, connection in use.');
if FUseHttps then
myPort:=StrToIntDef(GetPort,INTERNET_DEFAULT_HTTPS_PORT)
else
myPort:=StrToIntDef(GetPort,INTERNET_DEFAULT_HTTP_PORT);
WinHttpLoad;
try
if CertStoreType<>certNone then
WinCryptLoad;
Lost:=True;
Closing:=False;
Silent:=False;
Request.Init;
Response.Clear;
State:=conActivating;
TriggerConnectionOpening(Forc);
try
hSession := InternetOpen(nil, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, nil, nil, 0);
except
hSession := nil;
end;
if hSession=nil then
raise RtcWinHttpException.Create('Error initializing Internet API [Code #'+IntToStr(GetLastError)+'].');
try
myWAddr:=GetAddr;
hConnect := InternetConnect(hSession, PWChar(myWAddr), myPort, 0);
except
hConnect := nil;
end;
if hConnect=nil then
raise RtcWinHttpException.Create('Error opening Internet Connection [Code #'+IntToStr(GetLastError)+'].');
State:=conActive;
TriggerConnecting;
TriggerConnect;
except
on E:Exception do
begin
if hConnect<>nil then
begin
InternetCloseHandle(hConnect);
hConnect:=nil;
end;
if hSession<>nil then
begin
InternetCloseHandle(hSession);
hSession:=nil;
end;
TriggerConnectionClosing;
TriggerConnectError(E);
TriggerReadyToRelease;
end;
end;
end;
procedure TRtcWinHttpClientProvider.Disconnect;
var
hReq:HINTERNET;
begin
Lost:=False;
if assigned(Client_Thread) and not inThread then
begin
if TRtcThread.Lock(Client_Thread) then
try
if hRequest<>nil then
begin
try
hReq:=hRequest;
hRequest:=nil;
InternetCloseHandle(hReq);
except
end;
end;
TRtcThread.PostJob(Client_Thread, Message_WSCloseConn);
finally
TRtcThread.UnLock;
end;
end
else
InternalDisconnect;
end;
procedure TRtcWinHttpClientProvider.InternalDisconnect;
var
hReq:HINTERNET;
begin
if Closing then Exit;
Closing:=True;
State:=conClosing;
if hRequest<>nil then
begin
try
hReq:=hRequest;
hRequest:=nil;
InternetCloseHandle(hReq);
except
end;
end;
if hConnect<>nil then
begin
try
InternetCloseHandle(hConnect);
except
end;
hConnect:=nil;
end;
if hSession<>nil then
begin
try
InternetCloseHandle(hSession);
except
end;
hSession:=nil;
end;
if State=conClosing then
begin
TriggerDisconnecting;
TriggerConnectionClosing;
State:=conInactive;
try
TriggerDisconnect;
if Lost then
TriggerConnectLost;
except
end;
FHeaderOut:=False;
FDataWasSent:=False;
TriggerReadyToRelease;
end;
end;
function TRtcWinHttpClientProvider.Read: string;
begin
if not _Active then
begin
Result:='';
Exit;
end;
if FResponseBuffer.Size>0 then
begin
Result:=FResponseBuffer.Get;
FResponseBuffer.Clear;
end
else
Result:='';
end;
procedure TRtcWinHttpClientProvider.SendHeaderOut(const s:string);
var
MyHeader:WideString;
ex:Exception;
certOK:boolean;
lastErr:DWORD;
begin
FHeaderOut:=False;
FHeaderEx:=False;
certOK:=False;
myHeader:=Request.HeaderText;
repeat
if hRequest=nil then
Break
else
begin
if Request.ContentLength=0 then // No content
begin
if myHeader<>'' then
FHeaderOut:=HttpSendRequest(hRequest, PWChar(MyHeader), length(MyHeader), nil, 0,
0, nil)
else
FHeaderOut:=HttpSendRequest(hRequest, nil, 0, nil, 0,
0, nil);
end
else // Content in "s"
begin
if myHeader<>'' then
FHeaderOut:=HttpSendRequest(hRequest, PWChar(MyHeader), length(MyHeader), Addr(s[1]), length(s),
Request.ContentLength, nil)
else
FHeaderOut:=HttpSendRequest(hRequest, nil, 0, Addr(s[1]), length(s),
Request.ContentLength, nil);
end;
FHeaderEx:=FHeaderOut and (Request.Contentlength>length(s));
end;
if hRequest=nil then
begin
FHeaderOut:=False;
Break;
end
else if not FHeaderOut then
begin
lastErr:=GetLastError;
if (lastErr = ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) or
(lastErr = ERROR_WINHTTP_SECURE_INVALID_CA) or
(lastErr = ERROR_WINHTTP_SECURE_FAILURE) then
begin
if certOK or (FCertStoreType=certNone) then
Break
else
begin
certOK:=True;
if not SetupCertificate then Break;
end;
end
else
Break;
end;
until FHeaderOut;
if not FHeaderOut then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Sending the Request [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
end
else
begin
LenToWrite:=Request.ContentLength-length(s);
FDataOut:=length(Request.Method)+length(Request.URI)+10;
if not FHeaderEx then
begin
FDataOut:=FDataOut+length(myHeader)+length(s);
Request.ContentOut:=length(s);
end
else
begin
FDataOut:=FDataOut+length(myHeader);
Request.ContentOut:=0;
end;
TriggerDataOut;
FDataWasSent:=True; // will call DataSent
end;
end;
procedure TRtcWinHttpClientProvider.WriteHeader(SendNow:boolean=True);
var
ex:Exception;
hReq:HINTERNET;
myWMethod,
myWURI,
myWHTTP:WideString;
begin
if not _Active then Exit;
if FHeaderOut then
raise Exception.Create('Last header intercepted with new header, before data sent out.');
if hRequest<>nil then
begin
try
hReq:=hRequest;
hRequest:=nil;
InternetCloseHandle(hReq);
except
end;
end;
myWMethod:=Request.Method;
myWURI:=Request.URI;
myWHTTP:='HTTP/1.1';
if FUseHttps then
hRequest := HttpOpenRequest(hConnect, PWChar(myWMethod), PWChar(myWURI), PWChar(myWHTTP),
'', nil, WINHTTP_FLAG_REFRESH or WINHTTP_FLAG_SECURE)
else
hRequest := HttpOpenRequest(hConnect, PWChar(myWMethod), PWChar(myWURI), PWChar(myWHTTP),
'', nil, WINHTTP_FLAG_REFRESH);
if hRequest=nil then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error opening HTTP Request [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
Exit;
end;
if FUseHttps and (FCertStoreType<>certNone) and not hStoreReady then
SetupCertificate;
if SendNow or (Request.ContentLength=0) then
SendHeaderOut('');
if hRequest=nil then
begin
if _Active then
InternalDisconnect;
Exit;
end;
if not FHeaderOut then
begin
LenToWrite:=Request.ContentLength;
FDataWasSent:=True;
end;
Request.Started:=True;
Request.Active:=True;
end;
procedure TRtcWinHttpClientProvider.WriteHeader(const Header_Text: string; SendNow:boolean=True);
begin
if not _Active then Exit;
Request.HeaderText:=Header_Text;
WriteHeader(SendNow);
end;
procedure TRtcWinHttpClientProvider.Write(const s: string; SendNow:boolean=True);
var
bOK:boolean;
ex:Exception;
bWritten:DWORD;
begin
if not _Active then Exit;
if not Request.Active then
raise Exception.Create('Sending data without header.');
if not FHeaderOut then
SendHeaderOut(s);
if s='' then Exit;
if FHeaderEx then
begin
bOK := InternetWriteFile(hRequest, Addr(s[1]), length(s), bWritten);
if not bOK or (bWritten<>dword(length(s))) then
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Sending the Request [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
Exit;
end;
FDataOut:=length(s);
LenToWrite:=LenToWrite-FDataOut;
Request.ContentOut:=Request.ContentOut + FDataOut;
TriggerDataOut;
FDataWasSent:=True; // will call DataSent
end;
end;
procedure TRtcWinHttpClientProvider.LeavingEvent;
begin
If _Active and FDataWasSent then
begin
FDataWasSent:=False;
if LenToWrite=0 then
begin
Request.Complete:=True;
TriggerDataSent;
if Request.Complete and not Response.Done then
AcceptResponse;
end
else
TriggerDataSent;
end;
TriggerReadyToRelease;
end;
procedure TRtcWinHttpClientProvider.AcceptResponse;
var
dwBufLen,dwIndex:DWord;
LenToRead:int64;
hReq:HINTERNET;
InBuffer:string;
myHeader:WideString;
BytesRead:DWord;
ex:Exception;
function ReadNextBlock:boolean;
var
ReadNowBytes:int64;
begin
BytesRead:=0;
if LenToRead>0 then
begin
ReadNowBytes:=LenToRead;
if ReadNowBytes>length(FReadBuffer) then
ReadNowBytes:=length(FReadBuffer);
end
else
ReadNowBytes:=length(FReadBuffer);
if hRequest=nil then
Result:=False
else
Result:=InternetReadFile(hRequest, Addr(FReadBuffer[1]), ReadNowBytes, BytesRead);
if Result then
if BytesRead>0 then
begin
FDataIn:=BytesRead;
TriggerDataIn;
end;
end;
begin
if not _Active then Exit;
if not FHeaderOut then // This should not happen!
raise Exception.Create('AcceptResponse was called before WriteHeader.');
// if FHeaderEx then
if not HttpEndRequest(hRequest, nil) then
begin
InternalDisconnect;
Exit;
end;
FHeaderOut:=False;
Response.Started:=True;
Response.Receiving:=True;
FResponseBuffer.Clear;
// Get Raw Header ...
myHeader:=' ';
dwBufLen:=1;
dwIndex:=0;
if hRequest=nil then
begin
InternalDisconnect;
Exit;
end;
try
if not HttpQueryInfo(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, nil, Addr(myHeader[1]), dwBufLen, dwIndex) then
begin
if not _Active then Exit;
if GetLastError<>ERROR_INSUFFICIENT_BUFFER then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Reading a Response Header [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
Exit;
end
else if hRequest<>nil then
begin
SetLength(myHeader, dwBufLen);
if not HttpQueryInfo(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, nil, Addr(myHeader[1]), dwBufLen, dwIndex) then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Reading a Response Header [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
Exit;
end;
end
else
begin
InternalDisconnect;
Exit;
end;
end
else
SetLength(myHeader,dwBufLen);
FDataIn:=length(myHeader);
TriggerDataIn;
Response.HeaderText:=myHeader;
if Request.Method='HEAD' then
begin
LenToRead:=0;
Response.Done:=True;
if _Active then
TriggerDataReceived;
Exit;
end
else if Response['CONTENT-LENGTH']<>'' then
begin
LenToRead:=Response.ContentLength;
if LenToRead=0 then
begin
Response.Done:=True;
if _Active then
TriggerDataReceived;
Exit;
end;
end
else
LenToRead:=-1;
InBuffer:='';
while _Active and not Response.Done do
begin
if not ReadNextBlock then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Reading a Response Header [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
Exit;
end
else if BytesRead>0 then
InBuffer:=InBuffer+Copy(FReadBuffer,1,BytesRead)
else if (LenToRead>0) and (BytesRead=0) then
begin
if _Active then
begin
ex:=RtcWinHttpException.Create('Error Reading a Response Header [Code #'+IntToStr(GetLastError)+'].');
try
TriggerException(ex);
finally
ex.Free;
end;
InternalDisconnect;
end;
Exit;
end;
if (LenToRead>0) or (LenToRead=-1) then
begin
if (LenToRead>length(InBuffer)) or // need more than we have
(LenToRead=-1) then // size unknown
begin
Response.ContentIn:=Response.ContentIn + length(InBuffer);
if LenToRead>0 then
Dec(LenToRead, length(InBuffer))
else if BytesRead=0 then // last byte read
begin
LenToRead:=0;
Response.Done:=True;
Request.Active:=False;
FHeaderOut:=False;
end;
FResponseBuffer.Add(InBuffer);
InBuffer:='';
end
else
begin
Response.ContentIn:=Response.ContentIn + LenToRead;
FResponseBuffer.Add(Copy(InBuffer,1,LenToRead));
Delete(InBuffer,1,LenToRead);
LenToRead:=0;
Response.Done:=True;
Request.Active:=False;
FHeaderOut:=False;
end;
end
else
begin
Response.Done:=True;
Request.Active:=False;
FHeaderOut:=False;
end;
if not _Active then Exit;
if Response.Done then
begin
TriggerDataReceived;
Exit;
end
else
begin
TriggerDataReceived;
Response.Started:=False;
end;
end;
finally
if _Active and not Request.Active then
begin
FResponseBuffer.Clear;
if hRequest<>nil then
begin
try
hReq:=hRequest;
hRequest:=nil;
InternetCloseHandle(hReq);
except
end;
end;
end;
end;
end;
function TRtcWinHttpClientProvider._Active: boolean;
begin
Result:=not Closing and (FState in [conActive,conActivating]);
end;
procedure TRtcWinHttpClientProvider.Release;
begin
if assigned(Client_Thread) then
TRtcThread.PostJob(Client_Thread, Message_WSRelease, True)
else
inherited;
end;
function TRtcWinHttpClientProvider.SetupCertificate:boolean;
var
lpszStoreName,
lpszSubjectName:PChar;
dwFlags, dwBuffLen:DWORD;
pDWFlags:^DWORD;
res:bool;
begin
Result:=False;
if hStore<>nil then
begin
try
CertCloseStore(hStore, CERT_STORE_CLOSE_FORCE_FLAG);
except
end;
hStore:=nil;
hStoreReady:=False;
end;
if FCertStoreType=certAny then
begin
dwBuffLen:=sizeof(dwFlags);
pdwFlags:=addr(dwFlags);
InternetQueryOption (hRequest, WINHTTP_OPTION_SECURITY_FLAGS,
pdwFlags, dwBuffLen);
pdwFlags^ := pdwFlags^
or SECURITY_FLAG_IGNORE_UNKNOWN_CA
or SECURITY_FLAG_IGNORE_CERT_CN_INVALID
or SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
or SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;
res := InternetSetOption (hRequest, WINHTTP_OPTION_SECURITY_FLAGS,
pdwFlags, dwBuffLen );
if res then
begin
// hStoreReady:=True;
Result:=True;
end;
end
else
begin
case FCertStoreType of
certMY: lpszStoreName := 'MY';
certCA: lpszStoreName := 'CA';
certROOT: lpszStoreName := 'ROOT';
certSPC: lpszStoreName := 'SPC';
else Exit;
end;
hStore := CertOpenSystemStore(nil, lpszStoreName);
if hStore<>nil then
begin
lpszSubjectName:=PChar(FCertSubject);
pContext := CertFindCertificateInStore(hStore,
X509_ASN_ENCODING or PKCS_7_ASN_ENCODING,
0, CERT_FIND_SUBJECT_STR_A, lpszSubjectName, nil);
if (pContext<>nil) then
begin
if hRequest<>nil then
begin
res := InternetSetOption(hRequest,
INTERNET_OPTION_CLIENT_CERT_CONTEXT,
pContext, sizeof(CERT_CONTEXT));
if res then
begin
hStoreReady:=True;
Result:=True;
end;
end;
end;
end;
end;
end;
{ TRtcWinHttpClientThread }
constructor TRtcWinHttpClientThread.Create;
begin
inherited;
RtcConn:=nil;
end;
procedure TRtcWinHttpClientThread.OpenConn;
begin
RtcConn.OpenConnection;
end;
procedure TRtcWinHttpClientThread.CloseConn(_lost:boolean);
begin
if assigned(RtcConn) then
begin
try
RtcConn.Lost:=_lost;
if not Releasing then
RtcConn.InternalDisconnect;
except
on E:Exception do
if LOG_WINHTTP_ERRORS then
Log('WInetClientThread.CloseConn : RtConn.InternalDisconnect',E);
// ignore exceptions
end;
end;
end;
destructor TRtcWinHttpClientThread.Destroy;
begin
CloseConn(false);
if assigned(RtcConn) then
begin
try
if Releasing then
RtcConn.Free
else if assigned(RtcConn.Client_Thread) then
RtcConn.Client_Thread:=nil;
finally
RtcConn:=nil;
end;
end;
inherited;
end;
function TRtcWinHttpClientThread.Work(Job: TObject):boolean;
begin
Result:=False;
try
if Job=Message_WSOpenConn then
OpenConn
else if Job=Message_WSCloseConn then
CloseConn(false)
else if Job=Message_WSStop then
begin
RtcConn:=nil;
Result:=True;
Free;
end
else if Job=Message_WSRelease then
begin
Releasing:=True;
Result:=True;
Free;
end
else
Result:=inherited Work(Job);
except
on E:Exception do
begin
if LOG_WINHTTP_ERRORS then
Log('WInetClientThread.Work',E);
CloseConn(true);
// raise;
end;
end;
end;
type
TMyWinInet=class
public
constructor Create;
destructor Destroy; override;
end;
var
MyWinInet:TMyWinInet;
{ TMyWinInet }
constructor TMyWinInet.Create;
begin
inherited;
LibCS:=TRtcCritSec.Create;
Message_WSOpenConn:=TRtcBaseMessage.Create;
Message_WSCloseConn:=TRtcBaseMessage.Create;
Message_WSStop:=TRtcBaseMessage.Create;
Message_WSRelease:=TRtcBaseMessage.Create;
end;
destructor TMyWinInet.Destroy;
begin
WinHttpUnload;
WinCryptUnload;
Message_WSOpenConn.Free;
Message_WSCloseConn.Free;
Message_WSStop.Free;
Message_WSRelease.Free;
LibCS.Free;
inherited;
end;
initialization
MyWinInet:=TMyWinInet.Create;
finalization
Garbage(MyWinInet);
end.
|
program matrizMultiplica2Diagonal;
uses Crt;
{Algoritimo que checa as entradas do usuário e }
{armazena na matriz os número e multiplica os }
{elementos da diagonal principal por 2 e imprima }
{a matrizresultante} }
var aMatriz :array [1..3,1..3] of integer;
aLinha,aColuna : integer;
begin
{Começa a estrutura de repetição}
for aLinha := 1 to 3 do begin
for aColuna := 1 to 3 do begin
{Entrada de dados}
write ('Entre com o número ', aLinha, ',', aColuna,': ');
readln (aMatriz[aLinha,aColuna]);
writeln ('');
{Verifica e calcula se for o elemento da diagonal}
if aLinha = aColuna then begin
aMatriz[aLinha,aColuna] := aMatriz[aLinha,aColuna]*2;
end;
end;
end;
ClrScr;
{Saida de dados}
writeln ('Mostrando os valores: ');
for aLinha := 1 to 3 do begin
for aColuna := 1 to 3 do begin
write (aMatriz[aLinha,aColuna]: 4,'|');
end;
writeln ('');
end;
end.
|
unit Emacsbufferlist;
interface
procedure Register;
implementation
uses Windows, Classes, SysUtils, ToolsAPI, Menus, Forms, Dialogs, Controls,
Emacsbasebindings;
type
TEmacsBinding = class(TEmacsBindings, IOTAKeyboardBinding)
protected
procedure AdjustBlockCase(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure AdjustWordCase(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure BackspaceDelete(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CapitalizeWord(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CursorLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure CursorRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteChar(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteToEOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteToBOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteWordLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure DeleteWordRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure GotoBookmark(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertCharacter(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertFile(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure InsertTab(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LineDown(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure LineUp(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToBOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToBOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToEOF(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure MoveCursorToEOL(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure PageDown(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure PageUp(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure SaveFile(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure SaveAllFiles(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure SetBookmark(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure ToggleInsertMode(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure TransposeChar(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure TransposeLine(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure TransposeWord(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure Undo(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure WordLeft(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
procedure WordRight(const Context: IOTAKeyContext; KeyCode: TShortCut;
var BindingResult: TKeyBindingResult);
public
function GetBindingType: TBindingType;
function GetDisplayName: string;
function GetName: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
end;
resourcestring
sNewIDEEmacs = 'New IDE Emacs';
procedure Register;
begin
(BorlandIDEServices as IOTAKeyBoardServices).AddKeyboardBinding(TEmacsBinding.Create);
end;
{ TEmacsBinding }
{ Do no localize the following strings }
procedure TEmacsBinding.BindKeyboard(const BindingServices: IOTAKeyBindingServices);
begin
// Commands and Help
BindingServices.AddKeyBinding([ShortCut(Ord('H'), [ssCtrl])], HelpKeyword, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('S'), [ssCtrl])], SaveFile, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('S'), [])], SaveAllFiles, nil);
// Cursor Movement
BindingServices.AddKeyBinding([ShortCut(Ord('P'), [ssCtrl])], LineUp, nil);
BindingServices.AddKeyBinding([ShortCut(VK_UP, [])], LineUp, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('N'), [ssCtrl])], LineDown, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DOWN, [])], LineDown, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('V'), [])], PageUp, nil);
BindingServices.AddKeyBinding([ShortCut(VK_PRIOR, [])], PageUp, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('V'), [ssCtrl])], PageDown, nil);
BindingServices.AddKeyBinding([ShortCut(VK_NEXT, [])], PageDown, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('B'), [ssCtrl])], CursorLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [])], CursorLeft, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('F'), [ssCtrl])], CursorRight, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [])], CursorRight, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('B'), [])], WordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_LEFT, [ssCtrl])], WordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('F'), [])], WordRight, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RIGHT, [ssCtrl])], WordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('A'), [ssCtrl])], MoveCursorToBOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('E'), [ssCtrl])], MoveCursorToEOL, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('<'), [])], MoveCursorToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('>'), [])], MoveCursorToEOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_HOME, [])], MoveCursorToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_END, [])], MoveCursorToEOF, nil);
// Deleting Text
BindingServices.AddKeyBinding([ShortCut(VK_BACK, [])], BackSpaceDelete, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('D'), [ssCtrl])], DeleteChar, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DELETE, [])], BackspaceDelete, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(VK_BACK, [])], DeleteWordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DELETE, [ssCtrl])], DeleteWordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('D'), [])], DeleteWordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssAlt])], DeleteToBOL, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('K'), [ssCtrl])], DeleteToEOL, nil);
// Cut, Paste, and Undo
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('I'), [])], InsertFile, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('U'), [])], Undo, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('W'), [])], ClipCopy, nil, kfImplicits, '', 'EditCopyItem');
BindingServices.AddKeyBinding([ShortCut(Ord('W'), [ssCtrl])], ClipCut, nil, kfImplicits, '', 'EditCutItem');
BindingServices.AddKeyBinding([ShortCut(Ord('Y'), [ssCtrl])], ClipPaste, nil, kfImplicits, '', 'EditPasteItem');
BindingServices.AddMenuCommand(mcClipPaste, ClipPaste, nil);
BindingServices.AddMenuCommand(mcClipCopy, ClipCopy, nil);
BindingServices.AddMenuCommand(mcClipCut, ClipCut, nil);
// Search and Replace
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('%'), [])], SearchReplace, nil);
// BindingServices.AddKeyBinding([ShortCut(Ord('S'), [ssCtrl])], SearchFind, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('L'), [ssCtrl])], SearchAgain, nil, kfImplicits, '', 'SearchAgainItem');
BindingServices.AddKeyBinding([ShortCut(Ord('S'), [ssCtrl])], IncrementalSearch, nil, kfImplicits, '', 'SearchIncrementalItem');
BindingServices.AddKeyBinding([ShortCut(Ord('R'), [ssCtrl])], IncrementalSearch, Pointer(1), kfImplicits, '', 'SearchIncrementalItem');
BindingServices.AddMenuCommand(mcIncrementalSearch, IncrementalSearch, nil);
BindingServices.AddMenuCommand(mcReplace, SearchReplace, nil);
BindingServices.AddMenuCommand(mcGetFindString, SearchFind, nil);
// Transposing Text and Capitalization
// Esc-c Capitalizes the first Charcter after the point and makes the rest after lowercase
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('C'), [])], CapitalizeWord, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('T'), [ssCtrl])], TransposeChar, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('T'), [ssCtrl])], TransposeLine, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('T'), [])], TransposeWord, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('U'), [])], AdjustWordCase, nil);
BindingServices.AddKeyBinding([ShortCut(VK_ESCAPE, []), ShortCut(Ord('L'), [])], AdjustWordCase, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('U'), [ssCtrl])], AdjustBlockCase, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('L'), [ssCtrl])], AdjustBlockCase, Pointer(1));
// Debug (Non-Emacs)
BindingServices.AddKeyBinding([ShortCut(VK_F5, [ssAlt])], DebugInspect, nil);
BindingServices.AddKeyBinding([ShortCut(VK_F7, [ssCtrl])], AddWatchAtCursor, nil);
BindingServices.AddMenuCommand(mcAddWatchAtCursor, AddWatchAtCursor, nil);
BindingServices.AddMenuCommand(mcInspectAtCursor, DebugInspect, nil);
BindingServices.AddMenuCommand(mcRunToHere, RunToCursor, nil);
BindingServices.AddMenuCommand(mcModify, EvaluateModify, nil);
// Bookmarks
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('0'), [ssShift, ssCtrl])], GotoBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('1'), [ssShift, ssCtrl])], GotoBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('2'), [ssShift, ssCtrl])], GotoBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('3'), [ssShift, ssCtrl])], GotoBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('4'), [ssShift, ssCtrl])], GotoBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('5'), [ssShift, ssCtrl])], GotoBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('6'), [ssShift, ssCtrl])], GotoBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('7'), [ssShift, ssCtrl])], GotoBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('8'), [ssShift, ssCtrl])], GotoBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('B'), []), ShortCut(Ord('9'), [ssShift, ssCtrl])], GotoBookmark, Pointer(9));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('0'), [])], SetBookmark, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('1'), [])], SetBookmark, Pointer(1));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('2'), [])], SetBookmark, Pointer(2));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('3'), [])], SetBookmark, Pointer(3));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('4'), [])], SetBookmark, Pointer(4));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('5'), [])], SetBookmark, Pointer(5));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('6'), [])], SetBookmark, Pointer(6));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('7'), [])], SetBookmark, Pointer(7));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('8'), [])], SetBookmark, Pointer(8));
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssCtrl]), ShortCut(Ord('M'), []), ShortCut(Ord('9'), [])], SetBookmark, Pointer(9));
BindingServices.AddMenuCommand(mcMoveToMark0, GotoBookmark, nil);
BindingServices.AddMenuCommand(mcMoveToMark1, GotoBookmark, Pointer(1));
BindingServices.AddMenuCommand(mcMoveToMark2, GotoBookmark, Pointer(2));
BindingServices.AddMenuCommand(mcMoveToMark3, GotoBookmark, Pointer(3));
BindingServices.AddMenuCommand(mcMoveToMark4, GotoBookmark, Pointer(4));
BindingServices.AddMenuCommand(mcMoveToMark5, GotoBookmark, Pointer(5));
BindingServices.AddMenuCommand(mcMoveToMark6, GotoBookmark, Pointer(6));
BindingServices.AddMenuCommand(mcMoveToMark7, GotoBookmark, Pointer(7));
BindingServices.AddMenuCommand(mcMoveToMark8, GotoBookmark, Pointer(8));
BindingServices.AddMenuCommand(mcMoveToMark9, GotoBookmark, Pointer(9));
BindingServices.AddMenuCommand(mcSetMark0, SetBookmark, nil);
BindingServices.AddMenuCommand(mcSetMark1, SetBookmark, Pointer(1));
BindingServices.AddMenuCommand(mcSetMark2, SetBookmark, Pointer(2));
BindingServices.AddMenuCommand(mcSetMark3, SetBookmark, Pointer(3));
BindingServices.AddMenuCommand(mcSetMark4, SetBookmark, Pointer(4));
BindingServices.AddMenuCommand(mcSetMark5, SetBookmark, Pointer(5));
BindingServices.AddMenuCommand(mcSetMark6, SetBookmark, Pointer(6));
BindingServices.AddMenuCommand(mcSetMark7, SetBookmark, Pointer(7));
BindingServices.AddMenuCommand(mcSetMark8, SetBookmark, Pointer(8));
BindingServices.AddMenuCommand(mcSetMark9, SetBookmark, Pointer(9));
// Delphi IDE (Non-Emacs) Keys
BindingServices.AddKeyBinding([ShortCut(VK_RETURN, [ssCtrl])], OpenFileAtCursor, nil, kfImplicits, '', 'ecOpenFileAtCursor');
BindingServices.AddKeyBinding([ShortCut(VK_INSERT, [])], ToggleInsertMode, nil);
BindingServices.AddKeyBinding([ShortCut(VK_TAB, [])], InsertTab, nil);
BindingServices.AddKeyBinding([ShortCut(VK_RETURN, [])], InsertCharacter, Pointer($0D));
BindingServices.AddMenuCommand(mcOpenFileAtCursor, OpenFileAtCursor, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('/'), [ssAlt])], CodeCompletion, Pointer(csCodeList or csManual));
BindingServices.AddKeyBinding([ShortCut(Ord('J'), [ssCtrl])], CodeTemplate, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('C'), [ssShift, ssCtrl])], ClassComplete, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('G'), [ssShift, ssCtrl])], InsertNewGUID, nil);
BindingServices.AddKeyBinding([ShortCut(VK_SPACE, [ssShift, ssCtrl])], CodeCompletion, Pointer(csParamList or csManual));
BindingServices.AddKeyBinding([ShortCut(VK_UP, [ssShift, ssCtrl])], ClassNavigate, nil);
BindingServices.AddKeyBinding([ShortCut(VK_DOWN, [ssShift, ssCtrl])], ClassNavigate, nil);
BindingServices.AddKeyBinding([TextToShortCut('.')], AutoCodeInsight, Pointer(Ord('.')));
BindingServices.AddKeyBinding([ShortCut(Ord('>'), [])], AutoCodeInsight, Pointer(Ord('>')));
BindingServices.AddKeyBinding([TextToShortCut('(')], AutoCodeInsight, Pointer(Ord('(')));
// Duplicate Key Mappings to allow the Alt key to be used instead of ESC
BindingServices.AddKeyBinding([ShortCut(Ord('V'), [ssAlt])], PageUp, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('B'), [ssAlt])], WordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('F'), [ssAlt])], WordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('<'), [ssAlt])], MoveCursorToBOF, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('>'), [ssAlt])], MoveCursorToEOF, nil);
BindingServices.AddKeyBinding([ShortCut(VK_BACK, [ssAlt])], DeleteWordLeft, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('D'), [ssAlt])], DeleteWordRight, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('W'), [ssAlt])], ClipCopy, nil, kfImplicits, '', 'EditCopyItem');
BindingServices.AddKeyBinding([ShortCut(Ord('%'), [ssAlt])], SearchReplace, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('C'), [ssAlt])], CapitalizeWord, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('T'), [ssAlt])], TransposeWord, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('U'), [ssAlt])], AdjustWordCase, nil);
BindingServices.AddKeyBinding([ShortCut(Ord('L'), [ssAlt])], AdjustWordCase, Pointer(1));
end;
function TEmacsBinding.GetBindingType: TBindingType;
begin
{$IFDEF DEBUG}
Result := btPartial;
{$ELSE}
Result := btComplete;
{$ENDIF}
end;
function TEmacsBinding.GetDisplayName: string;
begin
Result := sNewIDEEmacs;
end;
function TEmacsBinding.GetName: string;
begin
Result := 'Borland.NewEmacs'; //do not localize
end;
procedure TEmacsBinding.DeleteToEOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
Pos: IOTAEditPosition;
Block: IOTAEditBlock;
begin
Pos := Context.EditBuffer.EditPosition;
Block := Context.EditBuffer.EditBlock;
Block.Visible := False;
Block.Save;
try
Block.Style := btNonInclusive;
Block.BeginBlock;
Pos.MoveEOL;
Block.EndBlock;
Block.Delete;
finally
Block.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.DeleteToBOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
Pos: IOTAEditPosition;
Block: IOTAEditBlock;
begin
Pos := Context.EditBuffer.EditPosition;
Block := Context.EditBuffer.EditBlock;
Block.Visible := False;
Block.Save;
try
Block.Style := btNonInclusive;
Block.EndBlock;
Pos.MoveBOL;
Block.BeginBlock;
Block.Delete;
finally
Block.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.WordLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveCursor(mmSkipLeft or mmSkipNonWord);
Context.EditBuffer.EditPosition.MoveCursor(mmSkipLeft or mmSkipWord or mmSkipStream);
BindingResult := krHandled;
end;
procedure TEmacsBinding.WordRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveCursor(mmSkipRight or mmSkipWord or mmSkipStream);
Context.EditBuffer.EditPosition.MoveCursor(mmSkipRight or mmSkipNonWord);
BindingResult := krHandled;
end;
const
BOOKMARK_ID_SYSTEM_ONE = 19;
BOOKMARK_ID_SYSTEM_TWO = 18;
BOOKMARK_ID_SYSTEM_THREE = 17;
procedure TEmacsBinding.DeleteWordLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
EB.Save;
try
EP.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.Move(EB.EndingRow,EB.EndingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
finally
EP.Restore;
end;
finally
EB.Restore;
end;
Blocked := True;
end else
Blocked := False;
EB.Style := btNonInclusive;
EB.Reset;
EB.EndBlock;
EP.MoveCursor(mmSkipLeft or mmSkipNonWord);
EP.MoveCursor(mmSkipLeft or mmSkipWord);
EB.BeginBlock;
EB.Delete;
if Blocked then
begin
EB.Style := btNonInclusive;
EP.Save;
try
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.EndBlock;
finally
EP.Restore;
end;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.BackspaceDelete(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.BackspaceDelete(1);
BindingResult := krHandled;
end;
procedure TEmacsBinding.CursorRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(0, 1);
BindingResult := krHandled;
end;
procedure TEmacsBinding.LineUp(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(-1, 0);
BindingResult := krHandled;
end;
procedure TEmacsBinding.PageDown(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.PageDown;
BindingResult := krHandled;
end;
procedure TEmacsBinding.CursorLeft(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(0, -1);
BindingResult := krHandled;
end;
procedure TEmacsBinding.LineDown(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveRelative(1, 0);
BindingResult := krHandled;
end;
procedure TEmacsBinding.PageUp(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.PageUp;
BindingResult := krHandled;
end;
procedure TEmacsBinding.DeleteWordRight(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
C, SpaceAdjust: Integer;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if (EB.Style <> btNonInclusive) or (EB.Size <> 0) then
begin
EB.Save;
try
EP.Save;
try
EP.Move(EB.StartingRow, EB.StartingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.Move(EB.EndingRow,EB.EndingColumn);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
finally
EP.Restore;
end;
finally
EB.Restore;
end;
Blocked := True;
end else
Blocked := False;
EB.Style := btNonInclusive;
EB.Reset;
EB.BeginBlock;
SpaceAdjust := 0;
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_THREE);
if EP.IsWhiteSpace then
begin
if EP.Character = #9 then
begin
C := EP.Column;
EP.Delete(1);
if C <> EP.Column then
SpaceAdjust := C - EP.Column;
end;
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else if EP.IsWordCharacter then
begin
EP.MoveCursor(mmSkipRight or mmSkipWord);
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else if EP.IsSpecialCharacter then
begin
EP.Delete(1);
EP.MoveCursor(mmSkipRight or mmSkipWhite);
end
else
EP.Delete(1);
EB.EndBlock;
EB.Delete;
while SpaceAdjust > 0 do
begin
EP.InsertCharacter(' ');
Dec(SpaceAdjust);
end;
if Blocked then
begin
EB.Style := btNonInclusive;
EP.Save;
try
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EB.BeginBlock;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.EndBlock;
finally
EP.Restore;
end;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.DeleteChar(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Delete(1);
BindingResult := krHandled;
end;
procedure TEmacsBinding.InsertTab(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EO: IOTABufferOptions;
begin
EP := Context.EditBuffer.EditPosition;
EO := Context.EditBuffer.BufferOptions;
if not EO.InsertMode then
EP.Tab(1)
else if EO.SmartTab then
EP.Align(1)
else
EP.InsertCharacter(#9);
BindingResult := krHandled;
end;
procedure TEmacsBinding.AdjustWordCase(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
try
if LongBool(Context.Context) then
MarkWord(Context).LowerCase
else MarkWord(Context).UpperCase;
EB.Reset;
finally
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
end;
finally
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.AdjustBlockCase(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EB: IOTAEditBlock;
begin
EB := Context.EditBuffer.EditBlock;
if EB.Size <> 0 then
begin
if Context.Context <> nil then
EB.LowerCase
else EB.UpperCase;
end else
Context.EditBuffer.TopView.SetTempMsg(sNoBlockMarked);
BindingResult := krHandled;
end;
procedure TEmacsBinding.InsertFile(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
begin
EP := Context.EditBuffer.EditPosition;
EP.Save;
try
EP.InsertFile('');
finally
EP.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.SetBookmark(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.BookmarkToggle(Integer(Context.Context));
BindingResult := krHandled;
end;
procedure TEmacsBinding.MoveCursorToBOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.Move(1, 1);
BindingResult := krHandled;
end;
procedure TEmacsBinding.MoveCursorToEOF(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveEOF;
BindingResult := krHandled;
end;
procedure TEmacsBinding.MoveCursorToBOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveBOL;
BindingResult := krHandled;
end;
procedure TEmacsBinding.MoveCursorToEOL(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.MoveEOL;
BindingResult := krHandled;
end;
procedure TEmacsBinding.GotoBookmark(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.TopView.BookmarkGoto(Integer(Context.Context));
Context.EditBuffer.TopView.MoveViewToCursor;
BindingResult := krHandled;
end;
procedure TEmacsBinding.ToggleInsertMode(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EO: IOTABufferOptions;
begin
EO := Context.KeyboardServices.EditorServices.EditOptions.BufferOptions;
EO.InsertMode := not EO.InsertMode;
BindingResult := krHandled;
end;
procedure TEmacsBinding.InsertCharacter(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.EditPosition.InsertCharacter(Char(Byte(Context.Context)));
BindingResult := krHandled;
end;
procedure TEmacsBinding.SaveAllFiles(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
(Context.EditBuffer.TopView as IOTAEditActions).SaveAll;
BindingResult := krHandled;
end;
procedure TEmacsBinding.SaveFile(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
(Context.EditBuffer.TopView as IOTAEditActions).Save;
BindingResult := krHandled;
end;
procedure TEmacsBinding.TransposeChar(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
EP.Save;
EB.Visible := false;
EP.MoveRelative(0, -1);
EB.BeginBlock;
EP.MoveRelative(0,1);
EB.EndBlock;
EB.Cut(false);
EP.MoveRelative(0,1);
EP.Paste;
EB.Reset;
finally
EP.Restore;
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.TransposeLine(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
begin
EV := Context.EditBuffer.TopView;
EB := EV.Block;
EP := EV.Position;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
EP.Save;
EB.Visible := false;
EP.MoveBOL;
EP.MoveRelative(-1, 0);
EB.BeginBlock;
EP.MoveRelative(1,0);
EB.EndBlock;
EB.Cut(false);
EP.MoveRelative(1,0);
EP.Paste;
EB.Reset;
finally
EP.Restore;
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.TransposeWord(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
OnFirstWord: Boolean;
LastCol: integer;
begin
EV := Context.EditBuffer.TopView;
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
OnFirstWord := False;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
EP.Save;
// Cursor is not on a word so skip left to a word
if not EP.IsWordCharacter then
begin
EP.MoveCursor(mmSkipLeft or mmSkipStream or mmSkipNonWord or mmSkipWhite);
OnFirstWord := True;
end;
// Cursor is on a valid word position
if EP.IsWordCharacter then
begin
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
EP.MoveCursor(mmSkipLeft or mmSkipWhite);
if (EP.IsWhiteSpace or (EP.Column = 1)) and not OnFirstWord then
begin
// first character of word or line so assume its the word on the right
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EB.Reset;
EB.Visible := False;
EB.Style := btNonInclusive;
EB.BeginBlock;
EP.MoveCursor(mmSkipRight or mmSkipWord);
EB.EndBlock;
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EB.Cut(False);
// skip left to the first word or to the top of the file
repeat
EP.MoveCursor(mmSkipLeft or mmSkipStream or mmSkipNonWord);
EP.MoveCursor(mmSkipLeft or mmSkipStream or mmSkipWhite);
EP.MoveCursor(mmSkipLeft or mmSkipStream or mmSkipWord);
until EP.IsWordCharacter or ((EP.Row = 1) and (EP.Column = 1));
EP.Paste;
EB.BeginBlock;
EP.MoveCursor(mmSkipRight or mmSkipWord);
EB.EndBlock;
EB.Cut(False);
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EP.Paste;
EB.Reset;
// Position the cursor at the end of the second word
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
end
else
begin
// not first char so its the word on the left
//skip to the beginning of the word
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
EP.MoveCursor(mmSkipLeft or mmSkipWord);
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EB.Reset;
EB.Visible := False;
EB.Style := btNonInclusive;
EB.BeginBlock;
EP.MoveCursor(mmSkipRight or mmSkipWord);
EB.EndBlock;
EB.Cut(False);
// locate the EOF
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_THREE);
EP.MoveEOF;
LastCol := EP.Column;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_THREE);
// skip right to the first word or to the end of the file
repeat
EP.MoveCursor(mmSkipRight or mmSkipStream or mmSkipWord);
EP.MoveCursor(mmSkipRight or mmSkipNonWord);
until EP.IsWordCharacter or ((EP.Row >= EP.LastRow) and (EP.Column >= LastCol));
if not EP.IsWordCharacter then
begin
// Hit EOF
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EP.Paste;
end
else
begin
// Found a word instead of EOF
EP.Paste;
EB.BeginBlock;
EP.MoveCursor(mmSkipRight or mmSkipWord);
EB.EndBlock;
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_TWO);
EB.Cut(False);
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
EP.Paste;
end;
EB.Reset;
// Position the cursor at the end of the second word
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_TWO);
end
end;
finally
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
procedure TEmacsBinding.Undo(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
begin
Context.EditBuffer.Undo;
BindingResult := krHandled;
end;
procedure TEmacsBinding.CapitalizeWord(const Context: IOTAKeyContext;
KeyCode: TShortCut; var BindingResult: TKeyBindingResult);
var
EP: IOTAEditPosition;
EB: IOTAEditBlock;
EV: IOTAEditView;
Blocked: Boolean;
LastCol: integer;
begin
EV := Context.EditBuffer.TopView;
EB := Context.EditBuffer.EditBlock;
EP := Context.EditBuffer.EditPosition;
if EB.Size <> 0 then
begin
EB.Save;
Blocked := True;
end else
Blocked := False;
try
// locate the EOF
EV.BookmarkRecord(BOOKMARK_ID_SYSTEM_ONE);
EP.MoveEOF;
LastCol := EP.Column;
EV.BookmarkGoto(BOOKMARK_ID_SYSTEM_ONE);
// Not on a word so skip right to the next word or EOF
if not EP.IsWordCharacter then
repeat
EP.MoveCursor(mmSkipRight or mmSkipStream or mmSkipWord);
EP.MoveCursor(mmSkipRight or mmSkipNonWord);
until EP.IsWordCharacter or ((EP.Row >= EP.LastRow) and (EP.Column >= LastCol));
// Cursor is on a valid word position
if EP.IsWordCharacter then
begin
// Capitalize the character
EB.BeginBlock;
EP.MoveRelative(0, 1);
EB.EndBlock;
EB.UpperCase;
// Lowercase the rest of the word
EB.BeginBlock;
EP.MoveCursor(mmSkipRight or mmSkipWord);
EB.EndBlock;
EB.LowerCase;
EB.Reset;
end;
finally
if Blocked then
EB.Restore;
end;
BindingResult := krHandled;
end;
end .
|
unit frm_SqlExportar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frm_connection, StdCtrls, DBCtrls, ComCtrls, ExtCtrls, DB,
Mask, Grids, DBGrids, global, Buttons, RXCtrls, StrUtils,DBTables,
ZAbstractRODataset, ZDataset, UnitExcepciones;
type
TfrmSqlExportar = class(TForm)
ds_Sql: TDataSource;
btnExit: TBitBtn;
btnExport: TBitBtn;
SaveSql: TSaveDialog;
Group_Exportacion: TGroupBox;
rbtUno: TRadioButton;
rbnDos: TRadioButton;
rbtTres: TRadioButton;
Group_Periodo: TGroupBox;
Label1: TLabel;
tdFechaInicio: TDateTimePicker;
Label2: TLabel;
tdFechaFinal: TDateTimePicker;
rbtCuatro: TRadioButton;
tsTabla: TComboBox;
tsNumeroOrden: TDBLookupComboBox;
ds_ordenesdetrabajo: TDataSource;
rbtOrden: TRadioButton;
ordenesdetrabajo: TZReadOnlyQuery;
Sql: TZReadOnlyQuery;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure tdFechaInicioEnter(Sender: TObject);
procedure tdFechaInicioExit(Sender: TObject);
procedure tdFechaInicioKeyPress(Sender: TObject; var Key: Char);
procedure tdFechaFinalEnter(Sender: TObject);
procedure tdFechaFinalExit(Sender: TObject);
procedure tdFechaFinalKeyPress(Sender: TObject; var Key: Char);
procedure tsNumeroOrdenEnter(Sender: TObject);
procedure tsTablaEnter(Sender: TObject);
procedure tsTablaExit(Sender: TObject);
procedure tsNumeroOrdenExit(Sender: TObject);
procedure tsTablaKeyPress(Sender: TObject; var Key: Char);
procedure tsNumeroOrdenKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmSqlExportar: TfrmSqlExportar;
implementation
{$R *.dfm}
procedure TfrmSqlExportar.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
action := cafree ;
end;
procedure TfrmSqlExportar.FormShow(Sender: TObject);
begin
try
tdFechaInicio.Date := Date ;
tdFechaFinal.Date := Date ;
OrdenesdeTrabajo.Active := False ;
OrdenesdeTrabajo.Params.ParamByName('Contrato').DataType := ftString ;
OrdenesdeTrabajo.Params.ParamByName('Contrato').Value := Global_Contrato ;
ordenesdetrabajo.Params.ParamByName('status').DataType := ftString ;
ordenesdetrabajo.Params.ParamByName('status').Value := connection.configuracion.FieldValues [ 'cStatusProceso' ];
OrdenesdeTrabajo.Open ;
Sql.Active := False ;
except
on e : exception do begin
UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Exportacion de datos', 'Al abrir formulario', 0);
end;
end;
end;
procedure TfrmSqlExportar.btnExitClick(Sender: TObject);
begin
Close
end;
procedure TfrmSqlExportar.btnExportClick(Sender: TObject);
const backupcompleto : array [1..22] of string = ('actividadesxanexo', 'anexosmensuales', 'alcancesxactividad', 'avancesglobales', 'avancesxactividad', 'ordenesdetrabajo', 'actividadesxorden',
'contratos','configuracion','convenios','distribuciondeanexo', 'distribuciondeactividades','equipos', 'personal',
'gruposisometrico','isometricos', 'turnos', 'tiposdemovimiento', 'anexo_requision', 'anexo_prequision','anexo_pedidos','anexo_ppedidos' ) ;
const backupsencillo : array [1..8] of string = ('actividadesxanexo', 'actividadesxorden', 'avancesglobales','convenios','anexosmensuales','distribuciondeanexo','distribuciondeactividades', 'avancesxactividad') ;
const backupfechas : array [1..9] of string = ('avancesglobalesxorden', 'bitacoradeactividades', 'bitacoradepaquetes', 'bitacoradeequipos','bitacoradepersonal', 'firmas','reportediario','bitacoradealcances','jornadasdiarias' ) ;
const backupfechas2 : array [1..10] of string = ('actividadesxorden','actividadesxanexo','alcancesxactividad','bitacoradealcances','personal','equipos','anexo_requision', 'anexo_prequision','anexo_pedidos','anexo_ppedidos' ) ;
const backuporden : array [1..9] of string = ('ordenesdetrabajo', 'actividadesxorden', 'avancesglobales','distribuciondeactividades', 'avancesxactividad','anexo_requision', 'anexo_prequision','anexo_pedidos','anexo_ppedidos') ;
Var
F1 : TextFile;
Registro : Integer ;
Cadena : WideString ;
ValorNumerico, Borrar :String ;
ValorFecha : String ;
valorCampo : Variant ;
NoTabla : Byte ;
BlobStream : TStream;
BlobField : tField ;
begin
//Verifica que la fecha final no sea menor que la fecha inicio
if tdFechaFinal.Date<tdFechaInicio.Date then
begin
showmessage('la fecha final es menor a la fecha de inicio' );
tdFechaFinal.SetFocus;
exit;
end;
try
SaveSql.Title := 'Guardar Consulta';
If SaveSql.Execute Then
Begin
AssignFile(F1, SaveSql.FileName);
rewrite(F1) ;
WriteLn(F1, '#Inteligent ... Administración de Contratos' ) ;
WriteLn(F1, '#Exportando Información del Sistema' ) ;
WriteLn(F1, '' ) ;
If rbtUno.Checked = True Then
Begin
For NoTabla := 1 To 22 Do
Begin
WriteLn(F1, '' ) ;
WriteLn(F1, '' ) ;
WriteLn(F1, '## Tabla ..: ' + BackupCompleto [NoTabla] ) ;
If BackupCompleto[NoTabla] = 'avancesglobales' Then
Begin
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupCompleto [NoTabla] + ' Where sContrato = :Contrato And sNumeroOrden = ""' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Open ;
End
Else
Begin
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupCompleto [NoTabla] + ' Where sContrato = :Contrato' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Open ;
End ;
Sql.First ;
While Sql.Eof <> True Do
Begin
Cadena := 'INSERT INTO ' + BackupCompleto [NoTabla] + ' VALUES ( ' ;
ValorCampo := '' ;
for Registro := 0 to Sql.FieldCount - 1 do
Begin
ValorCampo := Sql.Fields[Registro].Value ;
If VarIsnull(ValorCampo) Then
Begin
ValorCampo := '' ;
Cadena := Cadena + chr(39) + ValorCampo + chr(39) ;
end
Else
Begin
If (Sql.Fields[Registro].DataType = ftString) OR (Sql.Fields[Registro].DataType = ftMemo) Then
Begin
ValorCampo := AnsiReplaceText ( ValorCampo , chr(39) , '') ;
If Length(ValorCampo) > 0 Then
ValorCampo := chr(39) + ValorCampo + chr(39)
Else
ValorCampo := chr(39) + chr(39) ;
Cadena := Cadena + ValorCampo ;
End
Else
If Sql.Fields[Registro].DataType = ftDate Then
Begin
ValorFecha := chr(39) + FormatDateTime('yyyy-mm-dd', ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorFecha ) ;
End
Else
If Sql.Fields[Registro].DataType <> ftBlob Then
Begin
ValorNumerico := chr(39) + Trim(ValorCampo) +chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End
Else
If Sql.Fields[Registro].DataType = ftBlob Then
Begin
ValorNumerico := chr(39) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End ;
End ;
If Registro < ( Sql.FieldCount - 1 ) Then
Cadena := Cadena + ', '
end ;
Cadena := Cadena + ') ; ' ;
WriteLn(F1, Cadena ) ;
Sql.Next ;
End ;
End ;
End
Else
If rbnDos.Checked = True Then
Begin
For NoTabla := 1 To 8 Do
Begin
WriteLn(F1, '' ) ;
WriteLn(F1, '' ) ;
WriteLn(F1, '## Tabla ..: ' + BackupSencillo [NoTabla] ) ;
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupSencillo [NoTabla] + ' Where sContrato = :Contrato And sIdConvenio = :Convenio' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Params.ParamByName('Convenio').DataType := ftString ;
Sql.Params.ParamByName('Convenio').Value := global_convenio ;
Sql.Open ;
Sql.First ;
While Sql.Eof <> True Do
Begin
Cadena := 'INSERT INTO ' + BackupSencillo [NoTabla] + ' VALUES ( ' ;
ValorCampo := '' ;
for Registro := 0 to Sql.FieldCount - 1 do
Begin
ValorCampo := Sql.Fields[Registro].Value ;
If VarIsnull(ValorCampo) Then
Begin
ValorCampo :='' ;
Cadena := Cadena + chr(39) + ValorCampo + chr(39) ;
end
Else
Begin
If (Sql.Fields[Registro].DataType = ftString) OR (Sql.Fields[Registro].DataType = ftMemo) Then
Begin
ValorCampo := AnsiReplaceText ( ValorCampo , chr(39) , '') ;
If Length(ValorCampo) > 0 Then
ValorCampo := chr(39) + ValorCampo + chr(39)
Else
ValorCampo := chr(39) + chr(39) ;
Cadena := Cadena + ValorCampo ;
End
Else
If Sql.Fields[Registro].DataType = ftDate Then
Begin
ValorFecha := chr(39) + FormatDateTime('yyyy-mm-dd', ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorFecha ) ;
End
Else
If Sql.Fields[Registro].DataType <> ftBlob Then
Begin
ValorNumerico := chr(39) + Trim(ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End
Else
If Sql.Fields[Registro].DataType = ftBlob Then
Begin
ValorNumerico := chr(39) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End ;
End ;
If Registro < ( Sql.FieldCount - 1 ) Then
Cadena := Cadena + ', '
end ;
Cadena := Cadena + ') ; ' ;
WriteLn(F1, Cadena ) ;
Sql.Next ;
End ;
End ;
End
Else
If rbtTres.Checked = True Then
Begin
// Importación x Periodo del Primer bloque
For NoTabla := 1 To 9 Do
Begin
WriteLn(F1, '' ) ;
WriteLn(F1, '' ) ;
WriteLn(F1, '## Tabla ..: ' + BackupFechas[NoTabla] ) ;
Borrar := 'Delete from ' + BackupFechas[NoTabla] + ' Where sContrato= ' + chr(39) + global_contrato + chr(39) ;
Borrar := Borrar + ' And dIdFecha >= ' + chr(39) + FormatDateTime('yyyy-mm-dd', tdFechaInicio.Date) + chr(39) + ' And dIdFecha <= ' + chr(39) + FormatDateTime('yyyy-mm-dd', tdFechaFinal.Date ) + chr(39) + ' ;' ;
WriteLn(F1, Borrar) ;
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupFechas[NoTabla] + ' Where sContrato = :Contrato And dIdFecha >= :FechaInicio And dIdFecha <= :FechaFinal' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Params.ParamByName('FechaInicio').DataType := ftDate;
Sql.Params.ParamByName('FechaInicio').Value := tdFechaInicio.Date ;
Sql.Params.ParamByName('FechaFinal').DataType := ftDate ;
Sql.Params.ParamByName('FechaFinal').Value := tdFechaFinal.Date ;
Sql.Open ;
Sql.First ;
While Sql.Eof <> True Do
Begin
Cadena := 'INSERT INTO ' + BackupFechas[NoTabla] + ' VALUES ( ' ;
ValorCampo := '' ;
for Registro := 0 to Sql.FieldCount - 1 do
Begin
ValorCampo := Sql.Fields[Registro].Value ;
If VarIsnull(ValorCampo) Then
Begin
ValorCampo :='' ;
Cadena := Cadena + chr(39) + ValorCampo + chr(39) ;
end
Else
Begin
If (Sql.Fields[Registro].DataType = ftString) OR (Sql.Fields[Registro].DataType = ftMemo) Then
Begin
ValorCampo := AnsiReplaceText ( ValorCampo , chr(39) , '' ) ;
If Length(ValorCampo) > 0 Then
ValorCampo := chr(39) + ValorCampo + chr(39)
Else
ValorCampo := chr(39) + chr(39) ;
Cadena := Cadena + ValorCampo ;
End
Else
If Sql.Fields[Registro].DataType = ftDate Then
Begin
ValorFecha := chr(39) + FormatDateTime('yyyy-mm-dd', ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorFecha ) ;
End
Else
If Sql.Fields[Registro].DataType <> ftBlob Then
Begin
ValorNumerico := chr(39) + Trim(ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End
Else
If Sql.Fields[Registro].DataType = ftBlob Then
Begin
ValorNumerico := chr(39) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End ;
End ;
If Registro < ( Sql.FieldCount - 1 ) Then
Cadena := Cadena + ', '
end ;
Cadena := Cadena + ') ; ' ;
WriteLn(F1, Cadena ) ;
Sql.Next ;
End ;
End ;
End
Else
If rbtCuatro.Checked = True Then
Begin
WriteLn(F1, '' ) ;
WriteLn(F1, '' ) ;
WriteLn(F1, '## Tabla ..: ' + tsTabla.Text ) ;
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + tsTabla.Text ) ;
Sql.Open ;
Sql.First ;
While Sql.Eof <> True Do
Begin
Cadena := 'INSERT INTO ' + tsTabla.Text + ' VALUES ( ' ;
ValorCampo := '' ;
for Registro := 0 to Sql.FieldCount - 1 do
Begin
ValorCampo := Sql.Fields[Registro].Value ;
If VarIsnull(ValorCampo) Then
Begin
ValorCampo :='' ;
Cadena := Cadena + chr(39) + ValorCampo + chr(39) ;
end
Else
Begin
If (Sql.Fields[Registro].DataType = ftString) OR (Sql.Fields[Registro].DataType = ftMemo) Then
Begin
ValorCampo := AnsiReplaceText ( ValorCampo , chr(39) , '') ;
If Length(ValorCampo) > 0 Then
ValorCampo := chr(39) + ValorCampo + chr(39)
Else
ValorCampo := chr(39) + chr(39) ;
Cadena := Cadena + ValorCampo ;
End
Else
If Sql.Fields[Registro].DataType = ftDate Then
Begin
ValorFecha := chr(39) + FormatDateTime('yyyy-mm-dd', ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorFecha ) ;
End
Else
If Sql.Fields[Registro].DataType <> ftBlob Then
Begin
ValorNumerico := chr(39) + Trim(ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End
Else
If Sql.Fields[Registro].DataType = ftBlob Then
Begin
ValorNumerico := chr(39) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End ;
End ;
If Registro < ( Sql.FieldCount - 1 ) Then
Cadena := Cadena + ', '
end ;
Cadena := Cadena + ') ; ' ;
WriteLn(F1, Cadena ) ;
Sql.Next ;
End ;
End
Else
If rbtOrden.Checked Then
Begin
// Importación x Orden de Trabajo
For NoTabla := 1 To 9 Do
Begin
WriteLn(F1, '' ) ;
WriteLn(F1, '' ) ;
WriteLn(F1, '## Tabla ..: ' + BackupOrden[NoTabla] ) ;
If BackupOrden[NoTabla] = 'OrdenesdeTrabajo' Then
Begin
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupOrden[NoTabla] + ' Where sContrato = :Contrato And sNumeroOrden = :Orden' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Params.ParamByName('Orden').DataType := ftString ;
Sql.Params.ParamByName('Orden').Value := tsNumeroOrden.Text ;
Sql.Open ;
End
Else
Begin
Sql.Active := False ;
Sql.SQL.Clear ;
Sql.SQL.Add('Select * From ' + BackupOrden[NoTabla] + ' Where sContrato = :Contrato And sNumeroOrden = :Orden And sIdConvenio = :Convenio' ) ;
Sql.Params.ParamByName('Contrato').DataType := ftString ;
Sql.Params.ParamByName('Contrato').Value := global_contrato ;
Sql.Params.ParamByName('Convenio').DataType := ftString ;
Sql.Params.ParamByName('Convenio').Value := global_convenio ;
Sql.Params.ParamByName('Orden').DataType := ftString ;
Sql.Params.ParamByName('Orden').Value := tsNumeroOrden.Text ;
Sql.Open ;
End ;
Sql.First ;
While Sql.Eof <> True Do
Begin
Cadena := 'INSERT INTO ' + BackupOrden[NoTabla] + ' VALUES ( ' ;
ValorCampo := '' ;
for Registro := 0 to Sql.FieldCount - 1 do
Begin
ValorCampo := Sql.Fields[Registro].Value ;
If VarIsnull(ValorCampo) Then
Begin
ValorCampo :='' ;
Cadena := Cadena + chr(39) + ValorCampo + chr(39) ;
end
Else
Begin
If (Sql.Fields[Registro].DataType = ftString) OR (Sql.Fields[Registro].DataType = ftMemo) Then
Begin
ValorCampo := AnsiReplaceText ( ValorCampo , chr(39) , '' ) ;
If Length(ValorCampo) > 0 Then
ValorCampo := chr(39) + ValorCampo + chr(39)
Else
ValorCampo := chr(39) + chr(39) ;
Cadena := Cadena + ValorCampo ;
End
Else
If Sql.Fields[Registro].DataType = ftDate Then
Begin
ValorFecha := chr(39) + FormatDateTime('yyyy-mm-dd', ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorFecha ) ;
End
Else
If Sql.Fields[Registro].DataType <> ftBlob Then
Begin
ValorNumerico := chr(39) + Trim(ValorCampo) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End
Else
If Sql.Fields[Registro].DataType = ftBlob Then
Begin
ValorNumerico := chr(39) + chr(39) ;
Cadena := Trim(Cadena + ValorNumerico) ;
End ;
End ;
If Registro < ( Sql.FieldCount - 1 ) Then
Cadena := Cadena + ', '
end ;
Cadena := Cadena + ') ; ' ;
WriteLn(F1, Cadena ) ;
Sql.Next ;
End ;
End ;
End ;
closefile(F1) ;
MessageDlg('Proceso Terminado.', mtInformation, [mbOk], 0);
End;
except
on e : exception do begin
UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Exportacion de datos', 'Al exportar', 0);
end;
end;
end;
procedure TfrmSqlExportar.tdFechaInicioEnter(Sender: TObject);
begin
tdFechaInicio.Color := global_color_entradaERP
end;
procedure TfrmSqlExportar.tdFechaInicioExit(Sender: TObject);
begin
tdFechaInicio.Color := global_color_salidaPU
end;
procedure TfrmSqlExportar.tdFechaInicioKeyPress(Sender: TObject;
var Key: Char);
begin
If Key = #13 Then
tdFechaFinal.SetFocus
end;
procedure TfrmSqlExportar.tdFechaFinalEnter(Sender: TObject);
begin
tdFechaFinal.Color := global_color_entradaERP
end;
procedure TfrmSqlExportar.tdFechaFinalExit(Sender: TObject);
begin
tdFechaFinal.Color := global_color_salidaPU
end;
procedure TfrmSqlExportar.tdFechaFinalKeyPress(Sender: TObject;
var Key: Char);
begin
If Key = #13 Then
tstabla.SetFocus
end;
procedure TfrmSqlExportar.tsNumeroOrdenEnter(Sender: TObject);
begin
rbtOrden.Checked := True ;
tsNumeroOrden.Color := global_color_entradaERP
end;
procedure TfrmSqlExportar.tsTablaEnter(Sender: TObject);
begin
rbtCuatro.Checked := True ;
tsTabla.Color := global_color_entradaERP
end;
procedure TfrmSqlExportar.tsTablaExit(Sender: TObject);
begin
tsTabla.Color := global_color_salidaPU
end;
procedure TfrmSqlExportar.tsTablaKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 Then
tsnumeroorden.SetFocus;
end;
procedure TfrmSqlExportar.tsNumeroOrdenExit(Sender: TObject);
begin
tsNumeroOrden.Color := global_color_salidaPU
end;
procedure TfrmSqlExportar.tsNumeroOrdenKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 Then
tdfechainicio.SetFocus;
end;
end.
|
//Text file utilities
//(C)1999-2003 George Birbilis <birbilis@kagi.com>
//5Apr2002 - added "skipLines" procedure
//5Jun2002 - fixed "loadText" function to not skip empty lines inside the file neither at the end of the file
//1Jan2003 - added "writeText" procedure
unit ac_TextFileUtil;
interface
function loadText(var f:text):string;
procedure writeText(var f:text; content:string);
function countNonBlankLines(var f:text):cardinal;
procedure skipLines(var f:text; n:cardinal);
implementation
{$i-}
function loadText;
const CRLF=#13#10;
var s:string;
begin
result:='';
filemode:=0; //read-only
reset(f);
while (ioresult=0) and (not eof(f)) do //use "eof", not "seekeof" else empty lines will be skipped!
begin
read(f,s); //read text till end-of-line or end-of-file without reading the finishing marker
result:=result+s;
if(eoln(f) and (not eof(f))) then //if end-of-line marker (eoln also returns true if eof=true, so checking that this isn't that case)
begin
readln(f); //read the end-of-line marker
result:=result+CRLF; //add a CRLF marker to the result
end;
end;
close(f);
end;
procedure writeText;
begin
filemode:=1;
rewrite(f);
write(f,content);
close(f);
end;
function countNonBlankLines;
begin
result:=0;
filemode:=0; //read-only
reset(f);
while (ioresult=0) and (not seekeof(f)) do
begin
readln(f);
inc(result);
end;
close(f);
end;
procedure skipLines;
var i:cardinal;
begin
for i:=1 to n do //n times
readln(f); //skip a line
end;
end.
|
{
unit RegisterComp
ES: unidad para registrar los componentes FireMonkey
EN: unit to register the components FireMonkey
=========================================================================
History:
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
Unit to register the FireMonkey components.
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Unidad para registrar los componentes FireMonkey.
@author Xavier Martinez (cadetill)
@version 1.5.0
-------------------------------------------------------------------------------}
unit RegisterCompFMX;
{.$DEFINE CHROMIUMFMX}
{$I ..\gmlib.inc}
{$R ..\Resources\gmlibres.res}
interface
{$IFDEF CHROMIUMFMX}
{*------------------------------------------------------------------------------
The Register procedure register the FireMonkey components.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El procedimiento Register registra los componentes FireMonkey.
-------------------------------------------------------------------------------}
procedure Register;
{$ENDIF}
implementation
{$IFDEF CHROMIUMFMX}
uses
System.Classes, FMX.Types,
GMMapFMX, GMMarkerFMX, GMPolylineFMX, GMPolygonFMX, GMRectangleFMX,
GMCircleFMX, GMDirectionFMX, GMElevationFMX;
procedure Register;
begin
GroupDescendentsWith(TGMMapChr, Fmx.Types.TControl);
GroupDescendentsWith(TGMMarker, Fmx.Types.TControl);
GroupDescendentsWith(TGMPolyline, Fmx.Types.TControl);
GroupDescendentsWith(TGMPolygon, Fmx.Types.TControl);
GroupDescendentsWith(TGMRectangle, Fmx.Types.TControl);
GroupDescendentsWith(TGMCircle, Fmx.Types.TControl);
GroupDescendentsWith(TGMDirection, Fmx.Types.TControl);
GroupDescendentsWith(TGMElevation, Fmx.Types.TControl);
RegisterComponents('GoogleMaps', [TGMMapChr, TGMMarker,
TGMPolyline, TGMPolygon,
TGMRectangle, TGMCircle,
TGMDirection, TGMElevation
]);
end;
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.iOS.Sensors;
interface
uses
System.Sensors;
type
TPlatformSensorManager = class(TSensorManager)
protected
class function GetSensorManager: TSensorManager; override;
end;
TPlatformGeocoder = class(TGeocoder)
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
end;
TPlatformGpsStatus = class(TGpsStatus)
protected
class function GetGpsStatusImplementer: TGpsStatusClass; override;
end;
implementation
uses
System.SysUtils, System.Math, System.Generics.Collections, System.RTLConsts, iOSapi.Foundation, Macapi.ObjectiveC,
iOSapi.CocoaTypes, iOSapi.CoreLocation, iOSapi.CoreMotion, Macapi.Helpers, Macapi.Consts;
function ConvCLLocationCoord(const Value: CLLocationCoordinate2D): TLocationCoord2D;
begin
Result := TLocationCoord2D.Create(Value.latitude, Value.longitude);
end;
function ConvCLLocation(const Value: CLLocation): TLocationCoord2D;
begin
if Value <> nil then
Result := ConvCLLocationCoord(Value.coordinate)
else
Result := TLocationCoord2D.Create(0, 0);
end;
// Note:
// Because method definition of CLRegion.initCircularRegionWithCenter is incorrect.
// identifier parameter have to use Pointer, not NSString.
// For Tokyo update, we can't chagne the inteface, then we add the following code.
const
libobjc = '/usr/lib/libobjc.dylib';
{$IF NOT DECLARED(_PU)}
const
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
{$ENDIF}
function objc_msgSend(theReceiver: Pointer; theSelector: Pointer): Pointer; cdecl; overload;
external libobjc name _PU + 'objc_msgSend';
function objc_msgSendPD3(theReceiver: Pointer; theSelector: Pointer; center: CLLocationCoordinate2D; radius: CLLocationDistance; identifier: Pointer): Pointer; cdecl;
external libobjc name _PU + 'objc_msgSend';
function objc_getClass(const name: MarshaledAString): Pointer; cdecl;
external libobjc name _PU + 'objc_getClass';
function sel_getUid(const str: MarshaledAString): Pointer; cdecl; external libobjc name _PU + 'sel_getUid';
function ConvLocationRegion(const Region: TLocationRegion): CLRegion;
var
Center: CLLocationCoordinate2D;
UniqueID: NSString;
CLRegionPtr: Pointer;
begin
Center := CLLocationCoordinate2DMake(Region.Center.Latitude, Region.Center.Longitude);
UniqueID := TNSString.Wrap(TNSString.OCClass.stringWithUTF8String(MarshaledAString(UTF8Encode(Region.ID))));
// create the region object and add it for monitorization
CLRegionPtr := objc_msgSend(objc_getClass('CLRegion'), sel_getUid('alloc'));
Result := TCLRegion.Wrap(
objc_msgSendPD3(CLRegionPtr, sel_getUid('initCircularRegionWithCenter:radius:identifier:'),
Center, Region.Radius, NSStringToID(UniqueID)) );
end;
function ConvCLRegion(const Region: CLRegion): TLocationRegion;
begin
Result := TLocationRegion.Create(ConvCLLocationCoord(Region.center), Region.radius, NSStrToStr(Region.identifier));
end;
function GetLocalTimeZone: Integer;
begin
Result := TNSTimeZone.Wrap(TNSTimeZone.OCClass.localTimeZone).secondsFromGMT;
end;
function NSDateToDateTime(const ANSDate: NSDate): TDateTime;
begin
Result := (TNSDate.OCClass.timeIntervalSinceReferenceDate + GetLocalTimeZone) / SecsPerDay
+ EncodeDate(2001, 1, 1);
end;
type
{$M+}
{ Location Sensor }
// Notification about changed sensor's data
TOnStateChanged = procedure (const ANewState: TSensorState) of object;
TOnLocationChanged = procedure (const ANewLocation, AFromLocation: TLocationCoord2D) of object;
TOnDidEnterRegion = procedure (const ADidEnterRegion: TLocationRegion) of object;
TOnDidExitRegion = procedure (const didExitRegion: TLocationRegion) of object;
TOnHeadingChanged = procedure (const ANewHeading: CLHeading) of object;
TOnCLLocationChanged = procedure (const ACLLocation: CLLocation ) of object;
/// <summary>
/// Implementation of iOS Delegate for receive data from location sensor
/// </summary>
TiOSLocationDelegate = class(TOCLocal, CLLocationManagerDelegate)
strict private
FPreviousLocation: TLocationCoord2D;
FOnStateChanged: TOnStateChanged;
FOnLocationChanged: TOnLocationChanged;
FOnDidEnterRegion: TOnDidEnterRegion;
FOnDidExitRegion: TOnDidExitRegion;
FOnHeadingChanged: TOnHeadingChanged;
FOnCLLocationChanged : TOnCLLocationChanged;
procedure DoStateChanged(const ANewState: TSensorState);
procedure DoLocationChanged(const ANewLocation, AFromLocation: TLocationCoord2D);
procedure DoDidEnterRegion(const ADidEnterRegion: TLocationRegion);
procedure DoDidExitRegion(const ADidExitRegion: TLocationRegion);
procedure DoHeadingChanged(const ANewHeading: CLHeading);
procedure DoCLLocationChanged(const ACLLocation:CLLocation);
public
constructor Create;
{ CLLocationManagerDelegate }
procedure locationManager(manager: CLLocationManager; didChangeAuthorizationStatus: CLAuthorizationStatus); overload; cdecl;
[MethodName('locationManager:didEnterRegion:')]
procedure locationManagerDidEnterRegion(manager: CLLocationManager; region: CLRegion); cdecl;
[MethodName('locationManager:didExitRegion:')]
procedure locationManagerDidExitRegion(manager: CLLocationManager; region: CLRegion); cdecl;
procedure locationManager(manager: CLLocationManager; didFailWithError: NSError); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateHeading: CLHeading); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateToLocation: CLLocation; fromLocation: CLLocation); overload; cdecl;
procedure locationManager(manager: CLLocationManager; monitoringDidFailForRegion: CLRegion; withError: NSError); overload; cdecl;
function locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager): Boolean; cdecl;
[MethodName('locationManager:didUpdateLocations:')]
procedure locationManagerDidUpdateLocations(manager: CLLocationManager; locations: NSArray); cdecl;
[MethodName('locationManager:didDetermineState:forRegion:')]
procedure locationManagerDidDetermineStateForRegion(manager: CLLocationManager; state: CLRegionState; region: CLRegion); cdecl;
[MethodName('locationManager:didRangeBeacons:inRegion:')]
procedure locationManagerDidRangeBeaconsInRegion(manager: CLLocationManager; beacons: NSArray; region: CLBeaconRegion); cdecl;
[MethodName('locationManager:rangingBeaconsDidFailForRegion:withError:')]
procedure locationManagerRangingBeaconsDidFailForRegionWithError(manager: CLLocationManager; region: CLBeaconRegion; error: NSError); cdecl;
[MethodName('locationManager:didStartMonitoringForRegion:')]
procedure locationManagerDidStartMonitoringForRegion(manager: CLLocationManager; region: CLRegion); cdecl;
procedure locationManagerDidPauseLocationUpdates(manager: CLLocationManager); cdecl;
procedure locationManagerDidResumeLocationUpdates(manager: CLLocationManager); cdecl;
[MethodName('locationManager:didFinishDeferredUpdatesWithError:')]
procedure locationManagerDidFinishDeferredUpdatesWithError(manager: CLLocationManager; error: NSError); cdecl;
property OnStateChanged: TOnStateChanged read FOnStateChanged write FOnStateChanged;
property OnLocationChanged: TOnLocationChanged read FOnLocationChanged write FOnLocationChanged;
property OnDidEnterRegion: TOnDidEnterRegion read FOnDidEnterRegion write FOnDidEnterRegion;
property OnDidExitRegion: TOnDidExitRegion read FOnDidExitRegion write FOnDidExitRegion;
property OniOSHeadingChanged: TOnHeadingChanged read FOnHeadingChanged write FOnHeadingChanged;
property OnCLLocationChanged : TOnCLLocationChanged read FOnCLLocationChanged write FOnCLLocationChanged;
end;
TiOSLocationSensor = class(TCustomLocationSensor)
private const
CRegionAccuracy = 2; // 2 meters
private var
FLocater: CLLocationManager;
FLocationDelegate: TiOSLocationDelegate;
FLocation: CLLocation;
FHeading: CLHeading;
FSensorState: TSensorState;
// when the app is relaunched, it puts the existing monitored regions into the
// current regions list
procedure GrabExistingRegions;
protected
// determines if the device can monitor regions
function CanMonitorRegions: Boolean;
// determines if the device has heading support
function CanUseHeading: Boolean;
// determines if significant change notifications are supported
function CanUseSignifChangeNotifs: Boolean;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetLocationSensorType: TLocationSensorType; override;
// the sensor doesn't support properties such as address, city, street name etc
// because they can be easily obtain using the Geocoder class
function GetAvailableProperties: TCustomLocationSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double; override;
function GetAuthorized: TAuthorizationType; override;
function GetAccuracy: TLocationAccuracy; override;
function GetDistance: TLocationDistance; override;
function GetPowerConsumption: TPowerConsumption; override;
procedure SetAccuracy(const Value: TLocationAccuracy); override;
procedure SetDistance(const Value: TLocationDistance); override;
procedure DoLocationChangeType; override;
procedure DoOptimize; override;
procedure DoStateChanged(const ANewState: TSensorState);
procedure DoiOSHeadingChanged(const ANewHeading: CLHeading);
procedure DoCLLocationChanged(const ACLLocation : CLLocation);
function DoStart: Boolean; override;
procedure DoStop; override;
procedure RegionAdded(const Item: TLocationRegion); override;
procedure RegionRemoved(const Item: TLocationRegion); override;
constructor Create(AManager: TSensorManager); override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
destructor Destroy; override;
end;
{ Motion Sensor }
IMotionSensorDelegate = interface
['{D9DFC491-3BDA-4F45-864F-66D9358600A1}']
function GetSensorCategory: TSensorCategory;
function GetSensorType: TMotionSensorType;
function GetAvailableProperties: TCustomMotionSensor.TProperties;
function GetDoubleProperty(AProp: TCustomMotionSensor.TProperty): Double;
procedure Start;
procedure Stop;
end;
TAccelerometerDelegate = class(TInterfacedObject, IMotionSensorDelegate)
private
[weak] FNativeManager: CMMotionManager;
public
constructor Create(ANativeManager: CMMotionManager);
function GetSensorCategory: TSensorCategory;
function GetSensorType: TMotionSensorType;
function GetAvailableProperties: TCustomMotionSensor.TProperties;
function GetDoubleProperty(AProp: TCustomMotionSensor.TProperty): Double;
procedure Start;
procedure Stop;
end;
TDeviceMotionDelegate = class(TInterfacedObject, IMotionSensorDelegate)
private
[weak] FNativeManager: CMMotionManager;
public
constructor Create(ANativeManager: CMMotionManager);
function GetSensorCategory: TSensorCategory;
function GetSensorType: TMotionSensorType;
function GetAvailableProperties: TCustomMotionSensor.TProperties;
function GetDoubleProperty(AProp: TCustomMotionSensor.TProperty): Double;
procedure Start;
procedure Stop;
end;
// Represents any iOS motion sensor: accelerometer, device motion, magnetometer,
// etc. Because the callbacks and data types for each sensor are different,
// this class delegates retrieving those properties to an instance of IMotionSensorDelegate.
// A specific delegate must be created for each sensor.
TiOSMotionSensor = class(TCustomMotionSensor)
private
FIsDeviceMotionAvailable : Boolean;
FSensorState: TSensorState;
FSensorDelegate: IMotionSensorDelegate;
FQueue: NSOperationQueue;
FUpdateInterval : Double;
protected
function GetMotionSensorType: TMotionSensorType; override;
function GetAvailableProperties: TCustomMotionSensor.TProperties; override;
function GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double; override;
function GetSensorCategory: TSensorCategory; override;
function GetState: TSensorState; override;
function GetTimeStamp: TDateTime; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
function DoStart: Boolean; override;
procedure DoStop; override;
// determines if the device supports providing motion events
function Supported: Boolean; inline;
constructor Create(AManager: TSensorManager; ADelegate: IMotionSensorDelegate); reintroduce;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
destructor Destroy; override;
property IsDeviceMotionAvailable: Boolean read FIsDeviceMotionAvailable write FIsDeviceMotionAvailable;
end;
{ Orientation Sensor: Gyroscope and Compass }
TiOSCustomOrientationSensor = class (TCustomOrientationSensor)
private
FUpdateInterval: Double;
protected
function GetSensorCategory: TSensorCategory; override;
function GetUpdateInterval: Double; override;
procedure SetUpdateInterval(AInterval: Double); override;
public
constructor Create(AManager: TSensormanager); override;
end;
{ Gyroscope Sensor }
TiOSGyroscopeSensor = class (TiOSCustomOrientationSensor)
strict private
FNativeManager: CMMotionManager;
protected
function GetOrientationSensorType: TOrientationSensorType; override;
function GetAvailableProperties: TCustomOrientationSensor.TProperties; override;
function GetDoubleProperty(AProp: TCustomOrientationSensor.TProperty): Double; override;
function GetTimeStamp: TDateTime; override;
function GetState: TSensorState; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
destructor Destroy; override;
end;
{ Compass Sensor }
TiOSCompassSensor = class (TiOSCustomOrientationSensor)
strict private
FNativeManager: CLLocationManager;
FDelegate: TiOSLocationDelegate;
FHeading: CLHeading;
FSensorState: TSensorState;
private
procedure DoStateChanged(const ANewState: TSensorState);
procedure DoHeadingChanged(const ANewHeading: CLHeading);
protected
function GetOrientationSensorType: TOrientationSensorType; override;
function GetAvailableProperties: TCustomOrientationSensor.TProperties; override;
function GetDoubleProperty(AProp: TCustomOrientationSensor.TProperty): Double; override;
function GetTimeStamp: TDateTime; override;
function GetState: TSensorState; override;
function DoStart: Boolean; override;
procedure DoStop; override;
function DoGetInterface(const IID: TGUID; out Obj): HResult; override;
public
constructor Create(AManager: TSensorManager); override;
destructor Destroy; override;
end;
{ Sensor Manager }
TiOSSensorManager = class(TPlatformSensorManager)
private
FActive: Boolean;
FMotionManager: CMMotionManager;
FLocationManager: CLLocationManager;
FCoreMotionHandle: HMODULE;
protected
function GetCanActivate: Boolean; override;
function GetActive: Boolean; override;
public
constructor Create;
destructor Destroy; override;
procedure Activate; override;
procedure Deactivate; override;
end;
TiOSGeocoder = class(TGeocoder)
private class var
FGeocoder: CLGeocoder;
private
// these handlers receive the forward and reverse geocoding results
// and trigger the events
class procedure GeocodeForwardHandler(const placemark: NSArray;const error: NSError);
class procedure GeocodeReverseHandler(const placemark: NSArray;const error: NSError);
class constructor Create;
class destructor Destroy;
protected
class function GetGeocoderImplementer: TGeocoderClass; override;
class procedure GeocodeRequest(const Address: TCivicAddress); override;
class procedure GeocodeReverseRequest(const Coords: TLocationCoord2D); override;
public
class function Supported: Boolean; override;
class function Authorized: TAuthorizationType; override;
class procedure Cancel; override;
end;
TiOSGpsStatus = class(TGpsStatus)
public
class function Supported: Boolean; override;
class function Authorized: TAuthorizationType; override;
class function Satellites(Index: Integer): TGpsSatellite; override;
class function SatelliteCount: Integer; override;
class function SatelliteFirstFixTime: Integer; override;
end;
{ TPlatformSensorManager }
class function TPlatformSensorManager.GetSensorManager: TSensorManager;
begin
Result := TiOSSensorManager.Create;
end;
{ TiOSSensorManager }
procedure TiOSSensorManager.Activate;
var
LMotionSensor : TiOSMotionSensor;
begin
if not Active then
begin
FActive := True;
{ Acelerometer }
if FMotionManager.isAccelerometerAvailable then
begin
LMotionSensor := TiOSMotionSensor.Create(Self, TAccelerometerDelegate.Create(FMotionManager));
LMotionSensor.IsDeviceMotionAvailable := True;
AddSensor(LMotionSensor);
end;
{ Motion }
if FMotionManager.isDeviceMotionAvailable then
begin
LMotionSensor := TiOSMotionSensor.Create(Self, TDeviceMotionDelegate.Create(FMotionManager));
LMotionSensor.IsDeviceMotionAvailable := FMotionManager.isDeviceMotionAvailable;
AddSensor(LMotionSensor);
end;
{ Gyroscope }
if FMotionManager.isGyroAvailable then
AddSensor(TiOSGyroscopeSensor.Create(Self));
{ Location }
if FLocationManager.locationServicesEnabled then
AddSensor(TiOSLocationSensor.Create(Self));
{ Compass (Heading) }
if FLocationManager.headingAvailable then
AddSensor(TiOSCompassSensor.Create(Self));
end;
end;
constructor TiOSSensorManager.Create;
begin
inherited;
FCoreMotionHandle := LoadLibrary('/System/Library/Frameworks/CoreMotion.framework/CoreMotion');
FMotionManager := TCMMotionManager.Create;
FLocationManager := TCLLocationManager.Create;
end;
procedure TiOSSensorManager.Deactivate;
var
I: Integer;
begin
FActive := False;
for I := Count - 1 downto 0 do
RemoveSensor(Sensors[I]);
end;
destructor TiOSSensorManager.Destroy;
begin
if FCoreMotionHandle <> 0 then
FreeLibrary(FCoreMotionHandle);
inherited;
end;
function TiOSSensorManager.GetActive: Boolean;
begin
Result := FActive;
end;
function TiOSSensorManager.GetCanActivate: Boolean;
begin
Result := True;
end;
{ TiOSLocationSensor }
function TiOSLocationSensor.CanMonitorRegions: Boolean;
begin
Result := TCLLocationManager.OCClass.regionMonitoringAvailable and
TCLLocationManager.OCClass.regionMonitoringEnabled;
end;
function TiOSLocationSensor.CanUseHeading: Boolean;
begin
Result := [TProperty.TrueHeading, TProperty.MagneticHeading] * AvailableProperties <> [];
end;
function TiOSLocationSensor.CanUseSignifChangeNotifs: Boolean;
begin
Result := TCLLocationManager.OCClass.significantLocationChangeMonitoringAvailable;
end;
constructor TiOSLocationSensor.Create(AManager: TSensorManager);
begin
inherited Create(AManager);
FLocationDelegate := TiOSLocationDelegate.Create;
FLocationDelegate.OnStateChanged := DoStateChanged;
FLocationDelegate.OnLocationChanged := DoLocationChanged;
FLocationDelegate.OnDidEnterRegion := DoEnterRegion;
FLocationDelegate.OnDidExitRegion := DoExitRegion;
FLocationDelegate.OniOSHeadingChanged := DoiOSHeadingChanged;
FLocationDelegate.OnCLLocationChanged := DoCLLocationChanged;
FLocater := TCLLocationManager.Create;
FLocater.retain;
FLocater.setDelegate(FLocationDelegate.GetObjectID);
GrabExistingRegions;
end;
destructor TiOSLocationSensor.Destroy;
begin
FLocater.setDelegate(nil);
if FLocation <> nil then
FLocation.release;
FLocater.release;
FLocationDelegate.Free;
inherited;
end;
procedure TiOSLocationSensor.DoCLLocationChanged(const ACLLocation: CLLocation);
begin
if FLocation <> nil then
FLocation.release;
FLocation := ACLLocation;
FLocation.retain;
end;
function TiOSLocationSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FLocater <> nil then
Result := FLocater.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FLocationDelegate <> nil) then
Result := FLocationDelegate.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FLocation <> nil) then
Result := FLocation.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FHeading <> nil) then
Result := FHeading.QueryInterface(IID, Obj);
end;
procedure TiOSLocationSensor.DoiOSHeadingChanged(const ANewHeading: CLHeading);
var
LHeading: THeading;
begin
if ANewHeading <> nil then
begin
LHeading.Azimuth := ANewHeading.trueHeading;
inherited DoHeadingChanged(LHeading);
end;
if FHeading <> nil then
FHeading.release;
FHeading := ANewHeading;
FHeading.retain;
end;
procedure TiOSLocationSensor.DoLocationChangeType;
begin
// do nothing; location change type values influence the way notifications
// will be done the next time the sensor is started
end;
procedure TiOSLocationSensor.DoOptimize;
begin
// do nothing; the location services on iOS are already optimized
// by selecting the appropriate sensor (GPS, Wifi, cell towers) to determine
// the best location
end;
function TiOSLocationSensor.DoStart: Boolean;
var
I: Integer;
begin
if TOSVersion.Check(8) and (FLocater <> nil) then
FLocater.requestWhenInUseAuthorization;
// check authorization
if Authorized = TAuthorizationType.atUnauthorized then
SensorError(SLocationServiceUnauthorized);
// check if location sensor is enabled
if not FLocater.locationServicesEnabled then
SensorError(SLocationServiceDisabled);
// start location updates
if (LocationChange = TLocationChangeType.lctLarge) and CanUseSignifChangeNotifs then
FLocater.startMonitoringSignificantLocationChanges
else
FLocater.startUpdatingLocation;
// start heading updates
if CanUseHeading then
begin
FLocater.startUpdatingHeading;
end;
// start monitoring regions
if CanMonitorRegions then
for I := 0 to Regions.Count - 1 do
FLocater.startMonitoringForRegion(ConvLocationRegion(Regions[I]));
Result := FLocater.locationServicesEnabled;
if Result then
Result := Authorized = TAuthorizationType.atAuthorized;
end;
procedure TiOSLocationSensor.DoStateChanged(const ANewState: TSensorState);
begin
FSensorState := ANewState;
if FSensorState = TSensorState.AccessDenied then
Stop;
// If the sensor was already started and we just received a state change to Ready,
// it means that we just received authorization, so restart the sensor.
if (FSensorState = TSensorState.Ready) and Started then
Start;
end;
procedure TiOSLocationSensor.DoStop;
var
I: Integer;
begin
// stop the location update
if (LocationChange = TLocationChangeType.lctLarge) and CanUseSignifChangeNotifs then
FLocater.stopMonitoringSignificantLocationChanges
else
FLocater.stopUpdatingLocation;
// stop receiving heading updates
FLocater.stopUpdatingHeading;
// stop receiving region proximity updates
if CanMonitorRegions then
for I := 0 to Regions.Count - 1 do
FLocater.stopMonitoringForRegion(ConvLocationRegion(Regions[I]));
end;
function TiOSLocationSensor.GetAccuracy: TLocationAccuracy;
begin
Result := FLocater.desiredAccuracy
end;
function TiOSLocationSensor.GetAuthorized: TAuthorizationType;
begin
case TCLLocationManager.OCClass.authorizationStatus of
kCLAuthorizationStatusNotDetermined:
Result := TAuthorizationType.atNotSpecified;
kCLAuthorizationStatusDenied,
kCLAuthorizationStatusRestricted:
Result := TAuthorizationType.atUnauthorized;
kCLAuthorizationStatusAuthorizedWhenInUse,
kCLAuthorizationStatusAuthorized:
Result := TAuthorizationType.atAuthorized;
else // avoids compiler warnings
Result := TAuthorizationType.atNotSpecified;
end;
end;
function TiOSLocationSensor.GetAvailableProperties: TCustomLocationSensor.TProperties;
begin
Result := [];
if (Authorized <> TAuthorizationType.atUnauthorized) and
FLocater.locationServicesEnabled then
Result := [TProperty.Latitude, TProperty.Longitude, TProperty.Altitude, TProperty.Speed];
if FLocater.headingAvailable then
Result := Result + [TProperty.TrueHeading, TProperty.MagneticHeading];
end;
function TiOSLocationSensor.GetDistance: TLocationDistance;
begin
Result := FLocater.distanceFilter;
end;
function TiOSLocationSensor.GetDoubleProperty(Prop: TCustomLocationSensor.TProperty): Double;
begin
Result := NaN;
case Prop of
TProperty.Latitude:
if FLocation <> nil then
Result := FLocation.coordinate.latitude;
TProperty.Longitude:
if FLocation <> nil then
Result := FLocation.coordinate.longitude;
TProperty.Speed:
if FLocation <> nil then
Result := FLocation.speed;
TProperty.Altitude:
if FLocation <> nil then
Result := FLocation.altitude;
TProperty.ErrorRadius:
Result := 0;
TProperty.TrueHeading:
if FHeading <> nil then
Result := FHeading.trueHeading;
TProperty.MagneticHeading:
if FHeading <> nil then
Result := FHeading.magneticHeading;
end;
end;
function TiOSLocationSensor.GetLocationSensorType: TLocationSensorType;
begin
Result := TLocationSensorType.GPS;
end;
function TiOSLocationSensor.GetPowerConsumption: TPowerConsumption;
begin
if LocationChange = TLocationChangeType.lctSmall then
Result := TPowerConsumption.pcHigh
else
Result := TPowerConsumption.pcLow;
end;
function TiOSLocationSensor.GetState: TSensorState;
begin
Result := FSensorState;
end;
function TiOSLocationSensor.GetTimeStamp: TDateTime;
begin
Result := 0;
end;
procedure TiOSLocationSensor.GrabExistingRegions;
var
RegionArray: NSArray;
Current: CLRegion;
I: Integer;
begin
if CanMonitorRegions and (FLocater.monitoredRegions.count > 0) then
begin
RegionArray := FLocater.monitoredRegions.allObjects;
for I := 0 to RegionArray.count - 1 do
begin
Current := TCLRegion.Wrap(RegionArray.objectAtIndex(I));
Regions.Add(ConvCLRegion(Current));
end;
end;
end;
procedure TiOSLocationSensor.RegionAdded(const Item: TLocationRegion);
begin
if CanMonitorRegions and Started then
FLocater.startMonitoringForRegion(ConvLocationRegion(Item), CRegionAccuracy)
end;
procedure TiOSLocationSensor.RegionRemoved(const Item: TLocationRegion);
begin
if CanMonitorRegions and Started then
FLocater.stopMonitoringForRegion(ConvLocationRegion(Item));
end;
procedure TiOSLocationSensor.SetAccuracy(const Value: TLocationAccuracy);
begin
FLocater.setDesiredAccuracy(Value);
end;
procedure TiOSLocationSensor.SetDistance(const Value: TLocationDistance);
begin
FLocater.setDistanceFilter(Value);
end;
{ TiOSGpsStatus }
class function TiOSGpsStatus.Authorized: TAuthorizationType;
begin
Result := TAuthorizationType.atNotSpecified;
end;
class function TiOSGpsStatus.Supported: Boolean;
begin
Result := False;
end;
class function TiOSGpsStatus.SatelliteCount: Integer;
begin
Result := 0;
end;
class function TiOSGpsStatus.SatelliteFirstFixTime: Integer;
begin
Result := 0;
end;
class function TiOSGpsStatus.Satellites(Index: Integer): TGpsSatellite;
begin
Result := TGpsSatellite.Create(0, 0, 0, 0, False, False, False);
end;
{ TiOSGeocoder }
class function TiOSGeocoder.Authorized: TAuthorizationType;
begin
Result := TAuthorizationType.atNotSpecified;
end;
class procedure TiOSGeocoder.Cancel;
begin
inherited;
FGeocoder.cancelGeocode;
end;
class function TiOSGeocoder.Supported: Boolean;
begin
// geocoding is supported for the device
Result := True;
end;
class constructor TiOSGeocoder.Create;
begin
FGeocoder := TCLGeocoder.Create;
FGeocoder.retain;
end;
class destructor TiOSGeocoder.Destroy;
begin
TiOSGeocoder.FGeocoder.release;
TiOSGeocoder.FGeocoder := nil;
end;
class procedure TiOSGeocoder.GeocodeRequest(const Address: TCivicAddress);
begin
if Address = nil then
GeocodeForwardHandler(nil, nil);
if not FGeocoder.isGeocoding then
FGeocoder.geocodeAddressString(StrToNSStr(Address.ToString), GeocodeForwardHandler);
end;
class procedure TiOSGeocoder.GeocodeReverseRequest(const Coords: TLocationCoord2D);
var
Location: CLLocation;
begin
Location := TCLLocation.Create;
Location.initWithLatitude(Coords.Latitude, Coords.Longitude);
if Location = nil then
GeocodeReverseHandler(nil, nil);
if not FGeocoder.isGeocoding then
FGeocoder.reverseGeocodeLocation(Location, GeocodeReverseHandler );
end;
class function TiOSGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := Self;
end;
class procedure TiOSGeocoder.GeocodeForwardHandler(const placemark: NSArray; const error: NSError);
var
Current: CLPlacemark;
I: Integer;
begin
// adapt the coordinates storage
SetLength(FGeoFwdCoords, placemark.count);
for I := 0 to placemark.count - 1 do
begin
Current := TCLPlacemark.Wrap(placemark.objectAtIndex(I));
FGeoFwdCoords[I] := ConvCLLocation(Current.location);
end;
// call the event-handler
DoGeocode(FGeoFwdCoords);
end;
class procedure TiOSGeocoder.GeocodeReverseHandler(const placemark: NSArray; const error: NSError);
var
Current: CLPlacemark;
Addr: TCivicAddress;
begin
if (placemark <> nil) and (placemark.count > 0) then
begin
// grab the actual placemark object
Current := TCLPlacemark.Wrap(placemark.objectAtIndex(0));
Addr := FGeoRevAddress;
Addr.AdminArea := NSStrToStr(Current.administrativeArea);
Addr.CountryName := NSStrToStr(Current.country);
Addr.CountryCode := NSStrToStr(Current.ISOCountryCode);
Addr.Locality := NSStrToStr(Current.locality);
Addr.Coord := ConvCLLocation(Current.location);
Addr.FeatureName := NSStrToStr(Current.name);
Addr.PostalCode := NSStrToStr(Current.postalCode);
Addr.SubAdminArea := NSStrToStr(Current.subAdministrativeArea);
Addr.SubLocality := NSStrToStr(Current.subLocality);
Addr.SubThoroughfare := NSStrToStr(Current.subThoroughfare);
Addr.Thoroughfare := NSStrToStr(Current.thoroughfare);
end
else
Addr := nil;
// call the event handler
DoGeocodeReverse(Addr);
end;
{ TiOSLocationDelegate }
procedure TiOSLocationDelegate.locationManagerDidDetermineStateForRegion(manager: CLLocationManager;
state: CLRegionState; region: CLRegion);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidEnterRegion(manager: CLLocationManager; region: CLRegion);
var
LRegion: TLocationRegion;
begin
DoStateChanged(TSensorState.Ready);
try
LRegion := ConvCLRegion(region);
DoDidEnterRegion(LRegion);
finally
DoStateChanged(TSensorState.NoData);
end;
end;
procedure TiOSLocationDelegate.locationManagerDidExitRegion(manager: CLLocationManager; region: CLRegion);
var
LRegion: TLocationRegion;
begin
DoStateChanged(TSensorState.Ready);
try
LRegion := ConvCLRegion(region);
DoDidExitRegion(LRegion);
finally
DoStateChanged(TSensorState.NoData);
end;
end;
procedure TiOSLocationDelegate.locationManagerDidFinishDeferredUpdatesWithError(manager: CLLocationManager;
error: NSError);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidPauseLocationUpdates(manager: CLLocationManager);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidRangeBeaconsInRegion(manager: CLLocationManager; beacons: NSArray;
region: CLBeaconRegion);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidResumeLocationUpdates(manager: CLLocationManager);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidStartMonitoringForRegion(manager: CLLocationManager; region: CLRegion);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManagerDidUpdateLocations(manager: CLLocationManager; locations: NSArray);
var
Location: CLLocation;
NewLocation: TLocationCoord2D;
begin
DoStateChanged(TSensorState.Ready);
try
Location := TCLLocation.Wrap(locations.lastObject);
NewLocation := ConvCLLocation(Location);
DoCLLocationChanged(manager.location);
DoLocationChanged(NewLocation, FPreviousLocation);
FPreviousLocation := NewLocation;
finally
DoStateChanged(TSensorState.NoData);
end;
end;
procedure TiOSLocationDelegate.locationManagerRangingBeaconsDidFailForRegionWithError(manager: CLLocationManager;
region: CLBeaconRegion; error: NSError);
begin
{ For debugging purporses }
end;
procedure TiOSLocationDelegate.locationManager(
manager: CLLocationManager;
didChangeAuthorizationStatus: CLAuthorizationStatus);
var
State: TSensorState;
begin
case didChangeAuthorizationStatus of
// The user has not yet made a choice regarding whether this application
// can use location services.
kCLAuthorizationStatusNotDetermined:
State := TSensorState.AccessDenied;
// This application is not authorized to use location services.
// The user cannot change this application’s status, possibly due to active
// restrictions such as parental controls being in place.
kCLAuthorizationStatusRestricted:
State := TSensorState.AccessDenied;
// The user explicitly denied the use of location services for this
// application or location services are currently disabled in Settings.
kCLAuthorizationStatusDenied:
State := TSensorState.AccessDenied;
// This application is authorized to use location services.
kCLAuthorizationStatusAuthorized:
State := TSensorState.Ready;
else
State := TSensorState.Error;
end;
DoStateChanged(State);
end;
procedure TiOSLocationDelegate.locationManager(manager: CLLocationManager; didFailWithError: NSError);
var
State: TSensorState;
begin
case didFailWithError.code of
// can't get a location right now; wait for a new event
kCLErrorLocationUnknown:
State := TSensorState.Error;
// user denied usage of location services
kCLErrorDenied:
State := TSensorState.AccessDenied;
// strong interference from nearby magnetic fields
kCLErrorHeadingFailure:
State := TSensorState.Error;
else
State := TSensorState.Error;
end;
DoStateChanged(State);
end;
procedure TiOSLocationDelegate.DoDidEnterRegion(const ADidEnterRegion: TLocationRegion);
begin
if Assigned(FOnDidEnterRegion) then
FOnDidEnterRegion(ADidEnterRegion);
end;
procedure TiOSLocationDelegate.DoDidExitRegion(const ADidExitRegion: TLocationRegion);
begin
if Assigned(FOnDidExitRegion) then
FOnDidExitRegion(ADidExitRegion);
end;
procedure TiOSLocationDelegate.DoHeadingChanged(const ANewHeading: CLHeading);
begin
if Assigned(FOnHeadingChanged) then
FOnHeadingChanged(ANewHeading);
end;
procedure TiOSLocationDelegate.DoLocationChanged(const ANewLocation, AFromLocation: TLocationCoord2D);
begin
if Assigned(FOnLocationChanged) then
FOnLocationChanged(ANewLocation, AFromLocation);
end;
constructor TiOSLocationDelegate.Create;
begin
inherited;
FPreviousLocation := TLocationCoord2D.Create(0, 0);
end;
procedure TiOSLocationDelegate.DoCLLocationChanged(const ACLLocation: CLLocation);
begin
if Assigned(FOnCLLocationChanged) then
FOnCLLocationChanged(ACLLocation);
end;
procedure TiOSLocationDelegate.DoStateChanged(const ANewState: TSensorState);
begin
if Assigned(FOnStateChanged) then
FOnStateChanged(ANewState);
end;
procedure TiOSLocationDelegate.locationManager(manager: CLLocationManager; monitoringDidFailForRegion: CLRegion;
withError: NSError);
begin
DoStateChanged(TSensorState.Error)
end;
function TiOSLocationDelegate.locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager): Boolean;
begin
// Orientation Sensor didn't support sensor calibration
Result := False;
end;
procedure TiOSLocationDelegate.locationManager(manager: CLLocationManager; didUpdateHeading: CLHeading);
begin
DoStateChanged(TSensorState.Ready);
try
DoHeadingChanged(didUpdateHeading);
finally
DoStateChanged(TSensorState.NoData);
end;
end;
procedure TiOSLocationDelegate.locationManager(manager: CLLocationManager; didUpdateToLocation, fromLocation: CLLocation);
begin
end;
{ TPlatformGeocoder }
class function TPlatformGeocoder.GetGeocoderImplementer: TGeocoderClass;
begin
Result := TiOSGeocoder;
end;
{ TPlatformGpsStatus }
class function TPlatformGpsStatus.GetGpsStatusImplementer: TGpsStatusClass;
begin
Result := TiOSGpsStatus;
end;
{ TiOSMotionSensor }
constructor TiOSMotionSensor.Create(AManager: TsensorManager; ADelegate: IMotionSensorDelegate);
begin
inherited Create(AManager);
FSensorDelegate := ADelegate;
FUpdateInterval := 50;
end;
destructor TiOSMotionSensor.Destroy;
begin
Stop;
inherited;
end;
function TiOSMotionSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FSensorDelegate <> nil then
Result := FSensorDelegate.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FQueue <> nil) then
Result := FQueue.QueryInterface(IID, Obj);
end;
function TiOSMotionSensor.DoStart: Boolean;
begin
if FQueue = nil then
FQueue := TNSOperationQueue.Create;
FQueue.setSuspended(False);
FSensorDelegate.Start;
Result := True;
end;
procedure TiOSMotionSensor.DoStop;
begin
FSensorDelegate.Stop;
FQueue.cancelAllOperations;
FQueue.setSuspended(True);
end;
function TiOSMotionSensor.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
if Supported then
Result := FSensorDelegate.GetAvailableProperties
else
Result := [];
end;
function TiOSMotionSensor.GetDoubleProperty(Prop: TCustomMotionSensor.TProperty): Double;
begin
Result := NaN;
if Prop in AvailableProperties then
Result := FSensorDelegate.GetDoubleProperty(Prop);
end;
function TiOSMotionSensor.GetMotionSensorType: TMotionSensorType;
begin
Result := FSensorDelegate.GetSensorType;
end;
function TiOSMotionSensor.GetSensorCategory: TSensorCategory;
begin
Result := FSensorDelegate.GetSensorCategory;
end;
function TiOSMotionSensor.GetState: TSensorState;
begin
Result := FSensorState;
end;
function TiOSMotionSensor.GetTimeStamp: TDateTime;
begin
Result := 0;
end;
function TiOSMotionSensor.GetUpdateInterval: Double;
begin
Result := FUpdateInterval;
end;
procedure TiOSMotionSensor.SetUpdateInterval(AInterval: Double);
begin
// inherited;
if not SameValue(FUpdateInterval, AInterval) then
FUpdateInterval := AInterval;
end;
function TiOSMotionSensor.Supported: Boolean;
begin
Result := IsDeviceMotionAvailable;
end;
{ TAccelerometerDelegate }
constructor TAccelerometerDelegate.Create(ANativeManager: CMMotionManager);
begin
FNativeManager := ANativeManager;
end;
function TAccelerometerDelegate.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AccelerationX, TCustomMotionSensor.TProperty.AccelerationY, TCustomMotionSensor.TProperty.AccelerationZ];
end;
function TAccelerometerDelegate.GetDoubleProperty(AProp: TCustomMotionSensor.TProperty): Double;
var
LAccelData: CMAccelerometerData;
begin
Result := 0;
LAccelData := FNativeManager.accelerometerData;
if LAccelData <> nil then
case AProp of
TCustomMotionSensor.TProperty.AccelerationX:
Result := LAccelData.acceleration.x;
TCustomMotionSensor.TProperty.AccelerationY:
Result := LAccelData.acceleration.y;
TCustomMotionSensor.TProperty.AccelerationZ:
Result := LAccelData.acceleration.z;
end;
end;
function TAccelerometerDelegate.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TAccelerometerDelegate.GetSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.Accelerometer3D;
end;
procedure TAccelerometerDelegate.Start;
begin
if FNativeManager <> nil then
FNativeManager.startAccelerometerUpdates;
end;
procedure TAccelerometerDelegate.Stop;
begin
if FNativeManager <> nil then
FNativeManager.stopAccelerometerUpdates;
end;
{ TDeviceMotionDelegate }
constructor TDeviceMotionDelegate.Create(ANativeManager: CMMotionManager);
begin
FNativeManager := ANativeManager;
end;
function TDeviceMotionDelegate.GetAvailableProperties: TCustomMotionSensor.TProperties;
begin
Result := [TCustomMotionSensor.TProperty.AccelerationX, TCustomMotionSensor.TProperty.AccelerationY,
TCustomMotionSensor.TProperty.AccelerationZ, TCustomMotionSensor.TProperty.AngleAccelX,
TCustomMotionSensor.TProperty.AngleAccelY, TCustomMotionSensor.TProperty.AngleAccelZ]
end;
function TDeviceMotionDelegate.GetDoubleProperty(AProp: TCustomMotionSensor.TProperty): Double;
var
LMotionData: CMDeviceMotion;
begin
Result := 0;
LMotionData := FNativeManager.deviceMotion;
if LMotionData <> nil then
case AProp of
TCustomMotionSensor.TProperty.AccelerationX:
Result := LMotionData.userAcceleration.x;
TCustomMotionSensor.TProperty.AccelerationY:
Result := LMotionData.userAcceleration.y;
TCustomMotionSensor.TProperty.AccelerationZ:
Result := LMotionData.userAcceleration.z;
TCustomMotionSensor.TProperty.AngleAccelX:
Result := RadToDeg(LMotionData.rotationRate.x);
TCustomMotionSensor.TProperty.AngleAccelY:
Result := RadToDeg(LMotionData.rotationRate.y);
TCustomMotionSensor.TProperty.AngleAccelZ:
Result := RadToDeg(LMotionData.rotationRate.z);
end;
end;
function TDeviceMotionDelegate.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Motion;
end;
function TDeviceMotionDelegate.GetSensorType: TMotionSensorType;
begin
Result := TMotionSensorType.MotionDetector;
end;
procedure TDeviceMotionDelegate.Start;
begin
if FNativeManager <> nil then
FNativeManager.startDeviceMotionUpdates;
end;
procedure TDeviceMotionDelegate.Stop;
begin
if FNativeManager <> nil then
FNativeManager.stopDeviceMotionUpdates;
end;
{ TiOSCustomOrientationSensor }
constructor TiOSCustomOrientationSensor.Create(AManager: TSensormanager);
begin
inherited;
FUpdateInterval := 50;
end;
function TiOSCustomOrientationSensor.GetSensorCategory: TSensorCategory;
begin
Result := TSensorCategory.Orientation;
end;
function TiOSCustomOrientationSensor.GetUpdateInterval: Double;
begin
Result := FUpdateInterval;
end;
procedure TiOSCustomOrientationSensor.SetUpdateInterval(AInterval: Double);
begin
if not SameValue(FUpdateInterval, AInterval) then
FUpdateInterval := AInterval;
end;
{ TiOSGyroscopeSensor }
constructor TiOSGyroscopeSensor.Create(AManager: TSensorManager);
begin
inherited Create(AManager);
FNativeManager := TCMMotionManager.Create;
end;
destructor TiOSGyroscopeSensor.Destroy;
begin
//CFRelease(FNativeManager.);
inherited Destroy;
end;
function TiOSGyroscopeSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FNativeManager <> nil then
Result := FNativeManager.QueryInterface(IID, Obj);
end;
function TiOSGyroscopeSensor.DoStart: Boolean;
begin
FNativeManager.startDeviceMotionUpdates;
Result := FNativeManager.isGyroAvailable and FNativeManager.isGyroActive;
end;
procedure TiOSGyroscopeSensor.DoStop;
begin
FNativeManager.stopDeviceMotionUpdates;
end;
function TiOSGyroscopeSensor.GetAvailableProperties: TCustomOrientationSensor.TProperties;
begin
Result := [TCustomOrientationSensor.TProperty.TiltX,
TCustomOrientationSensor.TProperty.TiltY,
TCustomOrientationSensor.TProperty.TiltZ];
end;
function TiOSGyroscopeSensor.GetDoubleProperty(AProp: TCustomOrientationSensor.TProperty): Double;
var
LCCMDeviceMotion : CMDeviceMotion;
begin
Result := NaN;
LCCMDeviceMotion := FNativeManager.deviceMotion;
if LCCMDeviceMotion <> nil then
case AProp of
TCustomOrientationSensor.TProperty.TiltX:
Result := RadToDeg(LCCMDeviceMotion.attitude.roll);
TCustomOrientationSensor.TProperty.TiltY:
Result := RadToDeg(LCCMDeviceMotion.attitude.pitch);
TCustomOrientationSensor.TProperty.TiltZ:
Result := RadToDeg(LCCMDeviceMotion.attitude.yaw);
else
Result := 0;
end;
end;
function TiOSGyroscopeSensor.GetOrientationSensorType: TOrientationSensorType;
begin
Result := TOrientationSensorType.Inclinometer3D;
end;
function TiOSGyroscopeSensor.GetState: TSensorState;
begin
Result := TSensorState.Ready;
end;
function TiOSGyroscopeSensor.GetTimeStamp: TDateTime;
begin
// IOS does not support a property "TimeStamp"
Result := 0;
end;
{ TiOSCompassSensor }
constructor TiOSCompassSensor.Create(AManager: TSensorManager);
begin
inherited Create(AManager);
FDelegate := TiOSLocationDelegate.Create;
FDelegate.OnStateChanged := DoStateChanged;
FDelegate.OniOSHeadingChanged := DoHeadingChanged;
FNativeManager := TCLLocationManager.Create;
// FNativeManager.setHeadingFilter(0); // kCLHeadingFilterNone
FNativeManager.retain;
FNativeManager.setDelegate(FDelegate.GetObjectID);
FSensorState := TSensorState.NoData;
end;
destructor TiOSCompassSensor.Destroy;
begin
FNativeManager.setDelegate(nil);
FNativeManager.release;
FDelegate.Free;
if FHeading <> nil then
FHeading.release;
inherited Destroy;
end;
function TiOSCompassSensor.DoStart: Boolean;
begin
FNativeManager.startUpdatingHeading;
Result := FNativeManager.headingAvailable;
end;
procedure TiOSCompassSensor.DoStateChanged(const ANewState: TSensorState);
begin
FSensorState := ANewState;
StateChanged;
end;
procedure TiOSCompassSensor.DoStop;
begin
FNativeManager.stopUpdatingHeading;
end;
function TiOSCompassSensor.DoGetInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NOTIMPL;
if FNativeManager <> nil then
Result := FNativeManager.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FDelegate <> nil) then
Result := FDelegate.QueryInterface(IID, Obj);
if (Result <> S_OK) and (FHeading <> nil) then
Result := FHeading.QueryInterface(IID, Obj);
end;
procedure TiOSCompassSensor.DoHeadingChanged(const ANewHeading: CLHeading);
begin
FHeading := ANewHeading;
FHeading.retain;
end;
function TiOSCompassSensor.GetAvailableProperties: TCustomOrientationSensor.TProperties;
begin
Result := [TCustomOrientationSensor.TProperty.HeadingX,
TCustomOrientationSensor.TProperty.HeadingY,
TCustomOrientationSensor.TProperty.HeadingZ];
end;
function TiOSCompassSensor.GetDoubleProperty(AProp: TCustomOrientationSensor.TProperty): Double;
begin
Result := NaN;
if FHeading <> nil then
case AProp of
TCustomOrientationSensor.TProperty.HeadingX:
Result := FHeading.x; // MicroTeslas
TCustomOrientationSensor.TProperty.HeadingY:
Result := FHeading.y; // MicroTeslas
TCustomOrientationSensor.TProperty.HeadingZ:
Result := FHeading.z; // MicroTeslas
end;
end;
function TiOSCompassSensor.GetOrientationSensorType: TOrientationSensorType;
begin
Result := TOrientationSensorType.Compass3D;
end;
function TiOSCompassSensor.GetState: TSensorState;
begin
if not FNativeManager.headingAvailable then
FSensorState := TSensorState.Error;
Result := FSensorState;
end;
function TiOSCompassSensor.GetTimeStamp: TDateTime;
begin
Result := NSDateToDateTime(FHeading.timestamp);
end;
initialization
end.
|
unit adot.Grammar.Demo;
interface
uses
adot.Collections,
adot.Strings,
adot.Tools,
adot.Tools.IO,
adot.Grammar,
adot.Grammar.Types,
adot.Grammar.Peg,
System.SysUtils;
type
THTMLParser = class(TCustomLanguage)
protected
{ grammar rules }
Dok, Element,
EndTag, StartTag,
Definition, DefContent,
Comment, CommentBody,
Attr, AttrName, AttrValue,
DoubleQuotedAttrValue,
SingleQuotedAttrValue,
UnquotedAttrValue,
TagName, WS, AsciiChar: TGrammar;
{ parser (TPegParser for example) }
Parser: TGrammarParser;
function GetTotalSizeBytes: int64;
public
type
TReplaceImageProc = reference to procedure(var ImageSrc: string);
constructor Create;
destructor Destroy; override;
{ Parse input text and build ParseTree }
function Parse(const Html: string): Boolean;
{ StartTagNode - index of StartTag in ParseTree }
function GetTagName(StartTagNode: integer): string;
{ AttrNode - index of Attr in ParseTree }
function GetAttrName(AttrNode: integer): string;
{ AttrNode - index of Attr in ParseTree, AttrValueNode - index of AttrValue in ParseTree }
function FindAttrValue(AttrNode: integer; var AttrValueNode: integer): boolean;
{ StartTagNode - index of StartTag in ParseTree, AttrNode - index of first Attr with given Name }
function FindAttrByName(StartTagNode: integer; const Name: string; var AttrNode: integer): boolean;
{ Replacing/enumerating of images in HTML }
function ReplaceImages(AProc: TReplaceImageProc): string; overload;
{ Replace all images in source HTML to ANewImageSrc, for example: ReplaceImages('"NoImage.jpg"').
Returns new HTML generated. }
function ReplaceImages(const ANewImageSrc: string): string; overload;
class function RandomHtml(SizeBytes: int64): string; static;
property GrammarParser: TGrammarParser read Parser;
property TotalSizeBytes: int64 read GetTotalSizeBytes;
end;
TCalc = class(TCustomLanguage)
protected
Input, Expr, Sum, Product, Value, SumOp, ProdOp, MulOp: TGrammar;
Number,FixedNum,IntNum,Digit: TGrammar;
Parser: TGrammarParser;
FormatSettings: TFormatSettings;
function GetResultValue(TreeIndex: integer): Double;
public
constructor Create;
destructor Destroy; override;
function Evaluate(const Expr: string): Double;
class function Eval(const Expr: string): Double; static;
end;
implementation
{ THTMLParser }
constructor THTMLParser.Create;
begin
{ We will try to create robust parser. It should be able to recognize correct HTML
elements even in non-HTML stream (corrupted files, HTML generating errors etc). }
{ we use small optimization here, we skip all chars until "<", it makes parser 50% faster }
//Dok := ( Ex(Element) or Ex(ccAny))*Rep;
Dok := ((not Ex('<',True) + Ex(ccAny))*Rep + (Ex(Element) or Ex(ccAny)))*Rep;
Element := Ex(EndTag) or Ex(StartTag) or Ex(Definition) or Ex(Comment);
{ definition: <!DOCTYPE html>}
Definition := Ex('<!') + Ex(DefContent) + Ex('>');
DefContent := (not Ex('>') + Ex(ccAny))*Rep;
{ Comment: <!-- xxx --> }
Comment := Ex('<!--') + Ex(CommentBody) + Ex('-->');
CommentBody:= (not Ex('-->') + Ex(ccAny))*Rep;
{ Tags }
EndTag := Ex('</') + Ex(TagName)*Opt + Ex('>');
StartTag := Ex('<' ) + Ex(TagName)*Opt + Ex(Attr)*Rep + Ex(WS) + Ex('/')*Opt + Ex('>');
{ attribute: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 }
Attr := Ex(WS) + Ex(AttrName) + Ex(WS) + (Ex('=') + Ex(WS) + Ex(AttrValue))*Opt;
AttrName := (not Ex(ccWhiteSpace) + not Ex(ccControl) + not Ex(['"','''','>','/','=']) + Ex(ccAny))*Rep1;
AttrValue :=
(Ex('"') + Ex(DoubleQuotedAttrValue) + Ex('"')) or
(Ex('''') + Ex(SingleQuotedAttrValue) + Ex('''')) or
(Ex(UnquotedAttrValue));
DoubleQuotedAttrValue := (not Ex('"') + Ex(ccAny))*Rep;
SingleQuotedAttrValue := (not Ex('''') + Ex(ccAny))*Rep;
UnquotedAttrValue := (not Ex(ccWhiteSpace) + not Ex(['"','''','=','<','>','`']) + Ex(ccAny)) * Rep1;
{ additional rules }
AsciiChar := Ex('a','z') or Ex('0','9');
TagName := Ex(AsciiChar)*Rep1;
WS := Ex(ccWhiteSpace)*Rep;
{ readable names (usefull for debugging, logging etc) }
SetNames(
[ Dok, Element, Definition, DefContent, Comment, CommentBody, EndTag, StartTag, Attr, AttrName, AttrValue,
DoubleQuotedAttrValue, SingleQuotedAttrValue, UnquotedAttrValue, TagName, WS, AsciiChar],
['Dok','Element', 'Definition', 'DefContent', 'Comment', 'CommentBody', 'EndTag','StartTag','Attr','AttrName','AttrValue',
'DoubleQuotedAttrValue','SingleQuotedAttrValue','UnquotedAttrValue', 'TagName','WS','AsciiChar']);
Parser := TPegParser.Create(Dok.Grm);
end;
destructor THTMLParser.Destroy;
begin
FreeAndNil(Parser);
inherited;
end;
function THTMLParser.Parse(const Html: string): Boolean;
begin
Result := Parser.Accepts(Html);
end;
function THTMLParser.GetTagName(StartTagNode: integer): string;
var I: integer;
begin
for I in Parser.ParseTree.RuleMatches[StartTagNode, TagName.Id] do
Exit( Parser.DataToken[Parser.ParseTree.Tree.Nodes.Items[I].Data.Position] );
Result := '';
end;
function THTMLParser.GetTotalSizeBytes: int64;
begin
result := Parser.TotalSizeBytes;
end;
function THTMLParser.GetAttrName(AttrNode: integer): string;
var I: integer;
begin
for I in Parser.ParseTree.RuleMatches[AttrNode, AttrName.Id] do
Exit( Parser.DataToken[Parser.ParseTree.Tree.Nodes.Items[I].Data.Position] );
Result := '';
end;
function THTMLParser.FindAttrValue(AttrNode: integer; var AttrValueNode: integer): boolean;
var I: integer;
begin
for I in Parser.ParseTree.RuleMatches[AttrNode, AttrValue.Id] do
begin
AttrValueNode := I;
Exit(True);
end;
Result := False;
end;
function THTMLParser.FindAttrByName(StartTagNode: integer; const Name: string; var AttrNode: integer): boolean;
var I: integer;
begin
for I in Parser.ParseTree.RuleMatches[StartTagNode, Attr.Id] do
if TStr.SameText(GetAttrName(I),Name) then
begin
AttrNode := I;
Exit(True);
end;
Result := False;
end;
function THTMLParser.ReplaceImages(AProc: TReplaceImageProc): string;
var
StringEditor: TStringEditor;
StartTagNode,AttrNode,AttrValueNode: integer;
Src, Dst: string;
begin
StringEditor.Clear;
{ Hierarchy of HTML elements in our parser (see grammar definition for details):
Dok
Element
StartTag
TagName?
Attr*
AttrName
AttrValue
EndTag
TagName? }
for StartTagNode in Parser.ParseTree.RuleMatches[0, StartTag.Id] do
if TStr.SameText(GetTagName(StartTagNode), 'img') then
if FindAttrByName(StartTagNode, 'src', AttrNode) then
if FindAttrValue(AttrNode, AttrValueNode) then
begin
Src := Parser.DataToken[Parser.ParseTree[AttrValueNode].Position];
Dst := Src;
AProc(Dst);
if Src<>Dst then
StringEditor.Replace(Parser.ParseTree[AttrValueNode].Position.BytesToChars, Dst);
end;
Result := StringEditor.Apply(Parser.Data.Text);
end;
class function THTMLParser.RandomHtml(SizeBytes: int64): string;
var
Buf: TBuffer;
{ generates random attrobutes with or without values }
function GenAttrNameAndValue: string;
begin
{ attr name }
result := TStr.Random(1+Random(10));
{ attr value }
case Random(4) of
0 : ;
1 : result := result + '=' + TStr.Random(1+Random(10));
2 : result := result + '="' + TStr.Random(1+Random(10)) + '"';
3 : result := result + '=''' + TStr.Random(1+Random(10)) + '''';
end;
end;
{ generates nodename with random attributes without '<>') }
procedure GenNodeName(var NodeName,NodeWithRandomAttrs: string);
var
I,J: Integer;
begin
NodeName := TStr.Random(1+Random(10));
J := Random(5);
NodeWithRandomAttrs := NodeName;
for I := 0 to J-1 do
NodeWithRandomAttrs := NodeWithRandomAttrs + ' ' + GenAttrNameAndValue;
end;
{ generates node with sunbodes recursively }
procedure GenNode(offset: integer);
var
NodeName,NodeWithAttrs: string;
I,J,N: integer;
begin
J := Random(10);
for I := 0 to J do
begin
if Buf.Size >= SizeBytes then Exit;
GenNodeName(NodeName, NodeWithAttrs);
Buf.Write( StringOfChar(' ',Offset) );
N := Random(31);
case N of
0..10:
Buf.Write( format('<%s/>#13#10', [NodeWithAttrs]) );
11..20:
Buf.Write( format('%s'#13#10, [NodeName]) ); { content }
21..30:
begin
Buf.Write( format('<%s>'#13#10, [NodeWithAttrs]) );
GenNode(offset + 2);
Buf.Write( StringOfChar(' ',Offset) );
Buf.Write( format('</%s>'#13#10, [NodeName]) );
end;
end;
end;
end;
begin
Buf.Clear;
Buf.Write('<html>');
while Buf.Size < SizeBytes do
GenNode(2);
Buf.Write('</html>');
result := Buf.Text;
end;
function THTMLParser.ReplaceImages(const ANewImageSrc: string): string;
begin
Result := ReplaceImages(
procedure(var ImageSrc: string)
begin
ImageSrc := ANewImageSrc;
end);
end;
{ TCalc }
constructor TCalc.Create;
begin
{ general parser of expressions: 12+3, 4/5, 2*4, (3+1)*2 etc }
Input := Ex(Expr) + EOF;
Expr := Ex(Sum);
Sum := Ex(Product) + (Ex(SumOp) + Ex(Product))*Rep;
Product := Ex(Value) + (Ex(MulOp) + Ex(Value))*Rep;
Value := Ex(Number) or (Ex('(') + Ex(Expr) + Ex(')'));
SumOp := Ex('+') or Ex('-');
MulOp := Ex('*') or Ex('/');
{ general parser of numbers: 1, 1.2, -12e-5 etc }
Number := Ex(FixedNum) + (Ex('E') + Ex(IntNum))*Opt; { general number : +12.3E-10 }
FixedNum := Ex(IntNum) + (Ex('.') + Ex(IntNum)*Opt)*Opt; { fixed point number: +12.3 }
IntNum := (Ex('+') or Ex('-'))*Opt + Ex(Digit) + Ex(Digit)*Rep; { integer number : -12 }
Digit := Ex('0','9');
{ Friendly names for expressions parser }
Input.IncludeIntoParseTree := False;
Expr.IncludeIntoParseTree := False;
Sum.Name := 'Sum';
SumOp.Name := 'SumOp';
MulOp.Name := 'MulOp';
Product.Name := 'Product';
Value.IncludeIntoParseTree := False;
{ Friendly names for numbers parser }
Number.Name := 'Number';
FixedNum.IncludeIntoParseTree := False;
IntNum.IncludeIntoParseTree := False;
Digit.IncludeIntoParseTree := False;
Parser := TPegParser.Create(Input.Grm);
FormatSettings := TFormatSettings.Create;
FormatSettings.DecimalSeparator := '.';
end;
destructor TCalc.Destroy;
begin
Input.Release; { Just in case (if Parser is not initialized) }
FreeAndNil(Parser);
inherited;
end;
function TCalc.GetResultValue(TreeIndex: integer): Double;
var
Id: TRuleId;
I,J: integer;
ParseTree: TParseTree;
begin
ParseTree := Parser.ParseTree;
Id := ParseTree.Tree.Nodes.Items[TreeIndex].Data.Rule.Id;
{ Sum := Ex(Product) + ((Ex('+') or Ex('-')) + Ex(Product))*Rep; }
if Id=Sum.Id then
begin
I := ParseTree.Tree.Nodes.Items[TreeIndex].FirstChild;
Assert(I>=0);
result := GetResultValue(I); { Product }
repeat
I := ParseTree.NextSibling[I]; { SumOp }
if I<0 then Break;
J := ParseTree.NextSibling[I]; { Product }
Assert(J>=0);
Assert(ParseTree.Tree.Nodes.Items[I].Data.Rule.Id=SumOp.Id);
if Parser.DataToken[ParseTree.Tree.Nodes.Items[I].Data.Position]='+' then
Result := Result + GetResultValue(J)
else
Result := Result - GetResultValue(J);
I := J;
until False;
end
{ Product := Ex(Value) + ((Ex('*') or Ex('/')) + Ex(Value))*Rep; }
else if Id=Product.Id then
begin
I := ParseTree.Tree.Nodes.Items[TreeIndex].FirstChild;
Assert(I>=0);
result := GetResultValue(I); { Value }
repeat
I := ParseTree.NextSibling[I]; { MulOp }
if I<0 then Break;
J := ParseTree.NextSibling[I]; { Value }
Assert(J>=0);
Assert(ParseTree.Tree.Nodes.Items[I].Data.Rule.Id=MulOp.Id);
if Parser.DataToken[ParseTree.Tree.Nodes.Items[I].Data.Position]='*' then
Result := Result * GetResultValue(J)
else
Result := Result / GetResultValue(J);
I := J;
until False;
end
else if Id=Number.Id then
Result := StrToFloat(Parser.DataToken[ParseTree.Tree.Nodes.Items[TreeIndex].Data.Position], FormatSettings)
else
raise Exception.Create('Internal error');
end;
class function TCalc.Eval(const Expr: string): Double;
var
C: TCalc;
begin
C := TCalc.Create;
try
Result := C.Evaluate(Expr);
finally
C.Free;
end;
end;
function TCalc.Evaluate(const Expr: string): Double;
begin
if not Parser.Accepts(Expr) then
raise Exception.Create('Input rejected');
Parser.LogParseTree;
result := GetResultValue(0);
end;
end.
|
unit uTranslateVclConsts;
interface
uses
Windows,
Vcl.Consts,
uTranslate;
Type
TTranslateVclConsts = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateVclConsts.ChangeValues;
begin
SetResourceString(@SOpenFileTitle, 'Abrir');
SetResourceString(@SCantWriteResourceStreamError, 'Não é possível gravar em uma Stream de recusos somente de leitura');
SetResourceString(@SDuplicateReference, 'Objeto chamado duas vezes pela mesma instância');
SetResourceString(@SClassMismatch, 'Recurso %s é de uma classe incorreta');
SetResourceString(@SInvalidTabIndex, 'Indexador do TAB fora de faixa');
SetResourceString(@SInvalidTabPosition, 'Posição da aba incompatível com Estilo da aba corrente');
SetResourceString(@SInvalidTabStyle, 'Estilo da aba incompatível com a posição da aba corrente');
SetResourceString(@SInvalidBitmap, 'Bitmap inválido');
SetResourceString(@SInvalidIcon, 'Ícone inválido');
SetResourceString(@SInvalidMetafile, 'Metafile inválido');
SetResourceString(@SInvalidPixelFormat, 'Formato de pixel inválido');
SetResourceString(@SInvalidImage, 'Imagem inválida');
SetResourceString(@SBitmapEmpty, 'O Bitmap está vazio');
SetResourceString(@SScanLine, 'Índice da linha de escala está fora da faixa');
SetResourceString(@SChangeIconSize, 'Não é possível alterar o tamanho do ícone');
SetResourceString(@SChangeWicSize, 'Cannot change the size of a WIC Image');
SetResourceString(@SOleGraphic, 'Operação inválida no objeto TOleGraphic');
SetResourceString(@SUnknownExtension, 'Arquivo de imagem com extenção ".%s" desconhecido');
SetResourceString(@SUnknownClipboardFormat, 'Formato não suportado');
SetResourceString(@SOutOfResources, 'Sistema sem recursos ou com baixa memória');
SetResourceString(@SNoCanvasHandle, 'O canvas não esta conseguindo desenhar');
SetResourceString(@SInvalidTextFormatFlag, 'Text format flag ''%s'' not supported');
SetResourceString(@SInvalidImageSize, 'Tamanho de imagem inválido');
SetResourceString(@STooManyImages, 'Muitas imagens');
SetResourceString(@SDimsDoNotMatch, 'Dimensões da imagem diferente da lista de dimensões');
SetResourceString(@SInvalidImageList, 'ImageList inválido');
SetResourceString(@SReplaceImage, 'Não é possível trocar a imagem');
SetResourceString(@SInsertImage, 'Não é possível inserir a imagem');
SetResourceString(@SImageIndexError, 'Indexador do ImageList inválido');
SetResourceString(@SImageReadFail, 'Falha ao ler os dados do ImageList para a stream');
SetResourceString(@SImageWriteFail, 'Falha ao gravar dados no ImageList para a stream');
SetResourceString(@SWindowDCError, 'Erro ao criar a janela de contexto do dispositivo');
SetResourceString(@SClientNotSet, 'Cliente do TDrag não inicializado');
SetResourceString(@SWindowClass, 'Erro criando a classe da janela');
SetResourceString(@SWindowCreate, 'Erro criando a janela');
SetResourceString(@SCannotFocus, 'Não é possível focalizar uma janela desabilitada ou invisível');
SetResourceString(@SParentRequired, 'Controle "%s" não tem Janela antecessora');
SetResourceString(@SParentGivenNotAParent, 'Controle requerido não é um ancestral de "%s"');
SetResourceString(@SMDIChildNotVisible, 'Não é possível esconder um formulário filho MDI');
SetResourceString(@SVisibleChanged, 'Não é possível trocar a propriedade "Visible" em OnShow ou OnHide');
SetResourceString(@SCannotShowModal, 'Não é possível marcar uma janela visível como modal');
SetResourceString(@SScrollBarRange, 'Propriedade Scrollbar está fora de faixa');
SetResourceString(@SPropertyOutOfRange, 'A propriedade %s está fora de faixa');
SetResourceString(@SMenuIndexError, 'Índice do menu fora de faixa');
SetResourceString(@SMenuReinserted, 'Menu inserido duplicadamente');
SetResourceString(@SMenuNotFound, 'Este sub-menu não está em um menu');
SetResourceString(@SNoTimers, 'Não há timers disponíveis');
SetResourceString(@SNotPrinting, 'A Impressora não está imprimindo agora');
SetResourceString(@SPrinting, 'Impressão em progresso');
SetResourceString(@SPrinterIndexError, 'Indice de impressoras fora de faixa');
SetResourceString(@SInvalidPrinter, 'A impressora selecionada não é válida');
SetResourceString(@SDeviceOnPort, '"%s" em "%s"');
SetResourceString(@SGroupIndexTooLow, 'GroupIndex não pode ser menor que o ítem de menu anterior ao GroupIndex');
SetResourceString(@STwoMDIForms, 'Não é possível ter mais de um formulário MDI por aplicação');
SetResourceString(@SNoMDIForm, 'Não foi possível criar o formulário. Não há formulários MDI ativos neste momento');
SetResourceString(@SImageCanvasNeedsBitmap, 'Não é possível modificar um TImage que contém um bitmap');
SetResourceString(@SControlParentSetToSelf, 'Um controle não pode ter ele mesmo como seu antecessor');
SetResourceString(@SOKButton, 'OK');
SetResourceString(@SCancelButton, 'Cancelar');
SetResourceString(@SYesButton, '&Sim');
SetResourceString(@SNoButton, '&Não');
SetResourceString(@SHelpButton, '&Ajuda');
SetResourceString(@SCloseButton, '&Fechar');
SetResourceString(@SIgnoreButton, '&Ignorar');
SetResourceString(@SRetryButton, '&Repetir');
SetResourceString(@SAbortButton, 'Abortar');
SetResourceString(@SAllButton, '&Todos');
SetResourceString(@SCannotDragForm, 'Não é possível arrastar um formulário');
SetResourceString(@SPutObjectError, 'PutObject não definido para ítem');
SetResourceString(@SCardDLLNotLoaded, 'Não foi possível carregar a biblioteca "CARDS.DLL"');
SetResourceString(@SDuplicateCardId, 'Encontrada uma duplicata de CardId');
SetResourceString(@SDdeErr, 'Um erro retornado pelo DDE ($0%x)');
SetResourceString(@SDdeConvErr, 'Erro no DDE - conversação não estabelecida ($0%x)');
SetResourceString(@SDdeMemErr, 'Erro ocorrido quando DDE rodou sem memória ($0%x)');
SetResourceString(@SDdeNoConnect, 'Incapaz de conectar conversação DDE');
SetResourceString(@SFB, 'FB');
SetResourceString(@SFG, 'FG');
SetResourceString(@SBG, 'BG');
SetResourceString(@SOldTShape, 'Não é possível carregar uma versão antiga de TShape');
SetResourceString(@SVMetafiles, 'Metafiles');
SetResourceString(@SVEnhMetafiles, 'Metafiles realçado');
SetResourceString(@SVIcons, 'Ícone');
SetResourceString(@SVBitmaps, 'Bitmaps');
SetResourceString(@SVTIFFImages, 'TIFF Images');
SetResourceString(@SVJPGImages, 'JPEG Images');
SetResourceString(@SVPNGImages, 'PNG Images');
SetResourceString(@SVGIFImages, 'GIF Images');
SetResourceString(@SGridTooLarge, 'Grid muito larga para esta operação');
SetResourceString(@STooManyDeleted, 'Muitas linhas ou colunas deletadas');
SetResourceString(@SIndexOutOfRange, 'Índice do grid fora de faixa');
SetResourceString(@SFixedColTooBig, 'Contador de colunas fixas deve ser menor ou igual que o número de colunas');
SetResourceString(@SFixedRowTooBig, 'Contador de linhas fixas deve ser menor ou igual ao número de linhas');
SetResourceString(@SInvalidStringGridOp, 'Não é possível inserir ou deletar linhas da grade');
SetResourceString(@SInvalidEnumValue, 'Valor Numérico inválido');
SetResourceString(@SInvalidNumber, 'Valor numérico inválido');
SetResourceString(@SOutlineIndexError, 'Índice de saída inválido');
SetResourceString(@SOutlineExpandError, 'O antecessor deve ser expandido');
SetResourceString(@SInvalidCurrentItem, 'Valor inválido para o ítem corrente');
SetResourceString(@SMaskErr, 'Valor de entrada inválido');
SetResourceString(@SMaskEditErr, 'Valor de entrada inválido. Use a tecla Esc para abandonar as alterações');
SetResourceString(@SOutlineError, 'Índice de saída inválido');
SetResourceString(@SOutlineBadLevel, 'Nível de transferência incorreto');
SetResourceString(@SOutlineSelection, 'Seleção inválida');
SetResourceString(@SOutlineFileLoad, 'Erro ao carregar arquivo');
SetResourceString(@SOutlineLongLine, 'Linha muito longa');
SetResourceString(@SOutlineMaxLevels, 'Linha de saída excedeu o limíte máximo');
SetResourceString(@SMsgDlgWarning, 'Aviso');
SetResourceString(@SMsgDlgError, 'Erro');
SetResourceString(@SMsgDlgInformation, 'Informação');
SetResourceString(@SMsgDlgConfirm, 'Confirmação');
SetResourceString(@SMsgDlgYes, '&Sim');
SetResourceString(@SMsgDlgNo, '&Não');
SetResourceString(@SMsgDlgOK, 'OK');
SetResourceString(@SMsgDlgCancel, 'Cancela');
SetResourceString(@SMsgDlgHelp, '&Ajuda');
SetResourceString(@SMsgDlgHelpNone, 'Ajuda não disponível');
SetResourceString(@SMsgDlgHelpHelp, 'Ajuda');
SetResourceString(@SMsgDlgAbort, '&Abortar');
SetResourceString(@SMsgDlgRetry, '&Repetir');
SetResourceString(@SMsgDlgIgnore, '&Ignorar');
SetResourceString(@SMsgDlgAll, '&Todos');
SetResourceString(@SMsgDlgNoToAll, 'N&ão para todos');
SetResourceString(@SMsgDlgYesToAll, 'S&im para todos');
SetResourceString(@SMsgDlgClose, '&Fechar');
SetResourceString(@SmkcBkSp, 'BkSp');
SetResourceString(@SmkcTab, 'Tab');
SetResourceString(@SmkcEsc, 'Esc');
SetResourceString(@SmkcEnter, 'Enter');
SetResourceString(@SmkcSpace, 'Space');
SetResourceString(@SmkcPgUp, 'PgUp');
SetResourceString(@SmkcPgDn, 'PgDn');
SetResourceString(@SmkcEnd, 'End');
SetResourceString(@SmkcHome, 'Home');
SetResourceString(@SmkcLeft, 'Left');
SetResourceString(@SmkcUp, 'Up');
SetResourceString(@SmkcRight, 'Right');
SetResourceString(@SmkcDown, 'Down');
SetResourceString(@SmkcIns, 'Ins');
SetResourceString(@SmkcDel, 'Del');
SetResourceString(@SmkcShift, 'Shift+');
SetResourceString(@SmkcCtrl, 'Ctrl+');
SetResourceString(@SmkcAlt, 'Alt+');
SetResourceString(@srUnknown, '(Ignorado)');
SetResourceString(@srNone, '(Nenhum)');
SetResourceString(@SOutOfRange, 'Valor deve estar entre %d e %d');
SetResourceString(@SDateEncodeError, 'Arqumento inválido para decodificar data');
SetResourceString(@SDefaultFilter, 'Todos os arquivos (*.*)|*.*');
SetResourceString(@sAllFilter, 'Todos');
SetResourceString(@SNoVolumeLabel, ': [ - sem rótulo - ]');
SetResourceString(@SInsertLineError, 'Não é possível inserir linhas');
SetResourceString(@SConfirmCreateDir, 'O diretório especificado não existe. Criá-lo?');
SetResourceString(@SSelectDirCap, 'Selecione o diretório');
SetResourceString(@SDirNameCap, 'Diretório &Nome:');
SetResourceString(@SDrivesCap, 'D&rives:');
SetResourceString(@SDirsCap, '&Diretorios:');
SetResourceString(@SFilesCap, '&Arquivos: (*.*)');
SetResourceString(@SNetworkCap, 'R&ede...');
// SetResourceString(@SColorPrefix, 'Cor' deprecated; //!! obsolete - delete in 5.)0
// SetResourceString(@SColorTags, 'ABCDEFGHIJKLMNOP' deprecated; //!! obsolete - delete in 5.)0
SetResourceString(@SInvalidClipFmt, 'Formato na área de transferência inválido');
SetResourceString(@SIconToClipboard, 'Área de transferência não suporta ícones');
SetResourceString(@SCannotOpenClipboard, 'Não posso abrir a área de transferência: %s');
SetResourceString(@SDefault, 'Padrão');
SetResourceString(@SInvalidMemoSize, 'Texto excedeu a capacidade de 32K');
SetResourceString(@SCustomColors, 'Personalizar Cores');
SetResourceString(@SInvalidPrinterOp, 'Operação não suportada ao selecionar impressora');
SetResourceString(@SNoDefaultPrinter, 'Esta impressora selecionada não é a default');
SetResourceString(@SIniFileWriteError, 'Incapaz de gravar para "%s"');
SetResourceString(@SBitsIndexError, 'Índice de Bits fora de faixa');
SetResourceString(@SUntitled, '(Sem Título)');
SetResourceString(@SInvalidRegType, 'Tipo de dado inválido para "%s"');
SetResourceString(@SUnknownConversion, 'Incapaz de converter arquivo de extenção (.%s) para RichEdit');
SetResourceString(@SDuplicateMenus, 'Menu "%s" já está inicializado e usado por outro formulário');
SetResourceString(@SPictureLabel, 'Imagem:');
SetResourceString(@SPictureDesc, ' (%dx%d)');
SetResourceString(@SPreviewLabel, 'Visualizar');
SetResourceString(@SCannotOpenAVI, 'Não é possível abrir arquivo AVI');
SetResourceString(@SNotOpenErr, 'Dispositivo MCI não aberto');
SetResourceString(@SMPOpenFilter, 'Todos arquivos (*.*)|*.*|Arquivos wave (*.wav)|*.wav|Arquivos Midi (*.mid)|*.mid|Vídeo para Windows (*.avi)|*.avi');
SetResourceString(@SMCINil, '');
SetResourceString(@SMCIAVIVideo, 'AVIVídeo');
SetResourceString(@SMCICDAudio, 'CDAudio');
SetResourceString(@SMCIDAT, 'DAT');
SetResourceString(@SMCIDigitalVideo, 'Vídeo Digital');
SetResourceString(@SMCIMMMovie, 'MMMovie');
SetResourceString(@SMCIOther, 'Outro');
SetResourceString(@SMCIOverlay, 'Sobreposto');
SetResourceString(@SMCIScanner, 'Scanner');
SetResourceString(@SMCISequencer, 'Seqüência');
SetResourceString(@SMCIVCR, 'VCR');
SetResourceString(@SMCIVideodisc, 'Vídeo disco');
SetResourceString(@SMCIWaveAudio, 'Áudio Wave');
SetResourceString(@SMCIUnknownError, 'Código de erro desconhecido');
SetResourceString(@SBoldItalicFont, 'Negrito Itálico');
SetResourceString(@SBoldFont, 'Negrito');
SetResourceString(@SItalicFont, 'Itálico');
SetResourceString(@SRegularFont, 'Normal');
SetResourceString(@SPropertiesVerb, 'Propriedades');
SetResourceString(@SServiceFailed, 'Falha de serviço em %s: %s');
SetResourceString(@SExecute, 'Executar');
SetResourceString(@SStart, 'Iniciar');
SetResourceString(@SStop, 'Parar');
SetResourceString(@SPause, 'pausa');
SetResourceString(@SContinue, 'continuar');
SetResourceString(@SInterrogate, 'interrogar');
SetResourceString(@SShutdown, 'Reiniciar');
SetResourceString(@SCustomError, 'Falha de serviço sob a mensagem (%d): %s');
SetResourceString(@SServiceInstallOK, 'Serviço instalado com sucesso');
SetResourceString(@SServiceInstallFailed, 'Serviço "%s" falhou ou foi instalado com erro: "%s"');
SetResourceString(@SServiceUninstallOK, 'Serviço desinstalado com successo');
SetResourceString(@SServiceUninstallFailed, 'Serviço "%s" falhou ou foi desinstalado com erro: "%s"');
SetResourceString(@SDockedCtlNeedsName, 'O controle acoplado deve ter um conhecido');
SetResourceString(@SDockTreeRemoveError, 'Erro removendo controle da árvore');
SetResourceString(@SDockZoneNotFound, ' - Zona da doca não encontrada');
SetResourceString(@SDockZoneHasNoCtl, ' - Zona da doca não tem controle');
SetResourceString(@SDockZoneVersionConflict, 'Erro ao carregar fluxo da zona da doca. ' +
'Esperando Versão %d, mas achou %d.');
SetResourceString(@SAllCommands, 'Todos Comandos');
SetResourceString(@SDuplicateItem, 'Lista não permite duplicados ($0%x)');
SetResourceString(@STextNotFound, 'Texto não encontrado: "%s"');
SetResourceString(@SBrowserExecError, 'Nenhum navegador padrão é especificado');
SetResourceString(@SColorBoxCustomCaption, 'Customizar...');
SetResourceString(@SMultiSelectRequired, 'Mode multiseleção deve be on for this feature');
SetResourceString(@SPromptArrayTooShort, 'Length of value array must be >= length of prompt array');
SetResourceString(@SPromptArrayEmpty, 'Prompt array must not be empty');
SetResourceString(@SUsername, '&Username');
SetResourceString(@SPassword, '&Password');
SetResourceString(@SDomain, '&Domain');
SetResourceString(@SLogin, 'Login');
SetResourceString(@SKeyCaption, 'Chave');
SetResourceString(@SValueCaption, 'Valor');
SetResourceString(@SKeyConflict, 'Uma chave com o nome de "%s" já existe');
SetResourceString(@SKeyNotFound, 'Chave "%s" não encontrada');
SetResourceString(@SNoColumnMoving, 'goColMoving não é uma opção suportada');
SetResourceString(@SNoEqualsInKey, 'Chave não pode conter sinal igual a ("=")');
SetResourceString(@SSendError, 'Erro enviando email');
SetResourceString(@SAssignSubItemError, 'Não é possível associar um subítem de uma actionbar quanto um de seus antecessores estiver associado ao actionbar');
SetResourceString(@SDeleteItemWithSubItems, 'O item "%s" possui subitens, apagar mesmo assim?');
SetResourceString(@SDeleteNotAllowed, 'Não é permitido apagar este item');
SetResourceString(@SMoveNotAllowed, 'Item "%s" não tem permissão de ser movido');
SetResourceString(@SMoreButtons, 'Mais Botões');
SetResourceString(@SErrorDownloadingURL, 'Erro carregando URL: "%s"');
SetResourceString(@SUrlMonDllMissing, 'Impossível carregar "%s"');
SetResourceString(@SAllActions, '(Todas as Ações)');
SetResourceString(@SNoCategory, '(Sem Categoria)');
SetResourceString(@SExpand, 'Expandir');
SetResourceString(@SErrorSettingPath, 'Erro ajustando path: "%s"');
SetResourceString(@SLBPutError, 'Erro tentando inserir ítens em um listbox de estilo virtual');
SetResourceString(@SErrorLoadingFile, 'Erro carregando arquivo de ajustes salvos anteriormente: "%s"'#13'Você gostaria de apagá-lo?');
SetResourceString(@SResetUsageData, 'Restaurar todos os dados usados?');
SetResourceString(@SFileRunDialogTitle, 'Executar');
SetResourceString(@SNoName, '(Sem Nome Name)');
SetResourceString(@SErrorActionManagerNotAssigned, 'ActionManager deve primeiro ser atribuído');
SetResourceString(@SAddRemoveButtons, '&Adiciona ou Remove Botões');
SetResourceString(@SResetActionToolBar, 'Restaurar Toolbar');
SetResourceString(@SCustomize, '&Customizar');
SetResourceString(@SSeparator, 'Separador');
SetResourceString(@SCircularReferencesNotAllowed, 'Referências circulares não são permitidas');
SetResourceString(@SCannotHideActionBand, '"%s" não pode ser ocultada');
SetResourceString(@SErrorSettingCount, 'Erro ajustando %s.Count');
SetResourceString(@SListBoxMustBeVirtual, 'O Estilo do Listbox (%s) deve ser virtual na ordem para ajustar o Countador');
SetResourceString(@SUnableToSaveSettings, 'Não foi possível salvar as alterações');
SetResourceString(@SRestoreDefaultSchedule, 'Você gostaria de restaurar para a Programação Prioritária padrão?');
SetResourceString(@SNoGetItemEventHandler, 'Nemhum manipulador de evento OnGetItem atribuído');
SetResourceString(@SInvalidColorMap, 'ActionBand com mapa de cores inválido. Ele requer mapa de cores do tipo TCustomActionBarColorMapEx');
SetResourceString(@SDuplicateActionBarStyleName, 'Um estilo chamado "%s" já foi registrado');
SetResourceString(@SMissingActionBarStyleName, 'A style named %s has not been registered');
SetResourceString(@SStandardStyleActionBars, 'Estilo Standard');
SetResourceString(@SXPStyleActionBars, 'Estilo XP');
SetResourceString(@SActionBarStyleMissing, 'Unit sem nenhum estilo ActionBand presente na cláusula uses.'#13 +
'Sua aplicação deve incluir qualquer XPStyleActnCtrls, StdStyleActnCtrls ou ' +
'um componente ActionBand de terceiros presente na cláusula uses.');
SetResourceString(@sParameterCannotBeNil, '%s parâmetro em chamada %s não pode ser nulo');
SetResourceString(@SInvalidColorString, 'Cor Inválida da string');
SetResourceString(@SActionManagerNotAssigned, '%s ActionManager property has not been assigned');
SetResourceString(@SInvalidPath, '"%s" é um caminho inválido');
SetResourceString(@SInvalidPathCaption, 'Caminho inválido');
SetResourceString(@SANSIEncoding, 'ANSI');
SetResourceString(@SASCIIEncoding, 'ASCII');
SetResourceString(@SUnicodeEncoding, 'Unicode');
SetResourceString(@SBigEndianEncoding, 'Big Endian Unicode');
SetResourceString(@SUTF8Encoding, 'UTF-8');
SetResourceString(@SUTF7Encoding, 'UTF-7');
SetResourceString(@SEncodingLabel, 'Codificando:');
SetResourceString(@sCannotAddFixedSize, 'Não pode adicionar colunas ou linhas enquanto estilo expandido é tamanho fixo');
SetResourceString(@sInvalidSpan, '''%d'' não é um span valido');
SetResourceString(@sInvalidRowIndex, 'Indice da Linha, %d, fora da faixa');
SetResourceString(@sInvalidColumnIndex, 'Indice da Coluna, %d, fora da faixa');
SetResourceString(@sInvalidControlItem, 'ControlItem.Control não pode ser fixado possuindo GridPanel');
SetResourceString(@sCannotDeleteColumn, 'Não pode ser excluida uma coluna que contem controles');
SetResourceString(@sCannotDeleteRow, 'Não pode ser excluída uma linha que contem controles');
SetResourceString(@sCellMember, 'Member');
SetResourceString(@sCellSizeType, 'Tipo do Tamanho');
SetResourceString(@sCellValue, 'Valor');
SetResourceString(@sCellAutoSize, 'Auto');
SetResourceString(@sCellPercentSize, 'Por centos');
SetResourceString(@sCellAbsoluteSize, 'Absoluto');
SetResourceString(@sCellColumn, 'Coluna%d');
SetResourceString(@sCellRow, 'Linha%d');
SetResourceString(@STrayIconRemoveError, 'Não pode remover ícone de notificação');
SetResourceString(@STrayIconCreateError, 'Não pode criar ícone de notificação');
SetResourceString(@SPageControlNotSet, 'PageControl deve ser primeiramente designado');
SetResourceString(@SWindowsVistaRequired, '%s requires Windows Vista or later');
SetResourceString(@SXPThemesRequired, '%s requires themes to be enabled');
SetResourceString(@STaskDlgButtonCaption, 'Button%d');
SetResourceString(@STaskDlgRadioButtonCaption, 'RadioButton%d');
SetResourceString(@SInvalidTaskDlgButtonCaption, 'Caption cannot be empty');
SetResourceString(@SInvalidCategoryPanelParent, 'CategoryPanel must have a CategoryPanelGroup as its parent');
SetResourceString(@SInvalidCategoryPanelGroupChild, 'Only CategoryPanels can be inserted into a CategoryPanelGroup');
SetResourceString(@SInvalidCanvasOperation, 'Invalid canvas operation');
SetResourceString(@SNoOwner, '%s has no owner');
SetResourceString(@SRequireSameOwner, 'Source and destination require the same owner');
SetResourceString(@SDirect2DInvalidOwner, '%s cannot be owned by a different canvas');
SetResourceString(@SDirect2DInvalidSolidBrush, 'Not a solid color brush');
SetResourceString(@SDirect2DInvalidBrushStyle, 'Invalid brush style');
SetResourceString(@SKeyboardLocaleInfo, 'Error retrieving locale information');
SetResourceString(@SKeyboardLangChange, 'Failed to change input language');
SetResourceString(@SOnlyWinControls, 'You can only tab dock TWinControl based Controls');
SetResourceString(@SNoKeyword, 'No help keyword specified.');
SetResourceString(@SStyleLoadError, 'Unable to load style ''%s''');
SetResourceString(@SStyleLoadErrors, 'Unable to load styles: %s');
SetResourceString(@SStyleRegisterError, 'Style ''%s'' already registered');
SetResourceString(@SStyleClassRegisterError, 'Style class ''%s'' already registered');
SetResourceString(@SStyleNotFound, 'Style ''%s'' not found');
SetResourceString(@SStyleClassNotFound, 'Style class ''%s'' not found');
SetResourceString(@SStyleInvalidHandle, 'Invalid style handle');
SetResourceString(@SStyleFormatError, 'Invalid style format');
SetResourceString(@SStyleFileDescription, 'VCL Style File');
SetResourceString(@SStyleHookClassRegistered, 'Class ''%s'' is already registered for ''%s''');
SetResourceString(@SStyleHookClassNotRegistered, 'Class ''%s'' is not registered for ''%s''');
SetResourceString(@SStyleInvalidParameter, '%s parameter cannot be nil');
SetResourceString(@SStyleHookClassNotFound, 'A StyleHook class has not been registered for %s');
SetResourceString(@SStyleFeatureNotSupported, 'Feature not supported by this style');
SetResourceString(@SStyleNotRegistered, 'Style ''%s'' is not registered');
SetResourceString(@SStyleUnregisterError, 'Cannot unregister the system style');
SetResourceString(@SStyleNotRegisteredNoName, 'Style not registered');
// ColorToPrettyName strings
SetResourceString(@SNameBlack, 'Black');
SetResourceString(@SNameMaroon, 'Maroon');
SetResourceString(@SNameGreen, 'Green');
SetResourceString(@SNameOlive, 'Olive');
SetResourceString(@SNameNavy, 'Navy');
SetResourceString(@SNamePurple, 'Purple');
SetResourceString(@SNameTeal, 'Teal');
SetResourceString(@SNameGray, 'Gray');
SetResourceString(@SNameSilver, 'Silver');
SetResourceString(@SNameRed, 'Red');
SetResourceString(@SNameLime, 'Lime');
SetResourceString(@SNameYellow, 'Yellow');
SetResourceString(@SNameBlue, 'Blue');
SetResourceString(@SNameFuchsia, 'Fuchsia');
SetResourceString(@SNameAqua, 'Aqua');
SetResourceString(@SNameWhite, 'White');
SetResourceString(@SNameMoneyGreen, 'Money Green');
SetResourceString(@SNameSkyBlue, 'Sky Blue');
SetResourceString(@SNameCream, 'Cream');
SetResourceString(@SNameMedGray, 'Medium Gray');
SetResourceString(@SNameActiveBorder, 'Active Border');
SetResourceString(@SNameActiveCaption, 'Active Caption');
SetResourceString(@SNameAppWorkSpace, 'Application Workspace');
SetResourceString(@SNameBackground, 'Background');
SetResourceString(@SNameBtnFace, 'Button Face');
SetResourceString(@SNameBtnHighlight, 'Button Highlight');
SetResourceString(@SNameBtnShadow, 'Button Shadow');
SetResourceString(@SNameBtnText, 'Button Text');
SetResourceString(@SNameCaptionText, 'Caption Text');
SetResourceString(@SNameDefault, 'Default');
SetResourceString(@SNameGradientActiveCaption, 'Gradient Active Caption');
SetResourceString(@SNameGradientInactiveCaption, 'Gradient Inactive Caption');
SetResourceString(@SNameGrayText, 'Gray Text');
SetResourceString(@SNameHighlight, 'Highlight Background');
SetResourceString(@SNameHighlightText, 'Highlight Text');
SetResourceString(@SNameHotLight, 'Hot Light');
SetResourceString(@SNameInactiveBorder, 'Inactive Border');
SetResourceString(@SNameInactiveCaption, 'Inactive Caption');
SetResourceString(@SNameInactiveCaptionText, 'Inactive Caption Text');
SetResourceString(@SNameInfoBk, 'Info Background');
SetResourceString(@SNameInfoText, 'Info Text');
SetResourceString(@SNameMenu, 'Menu Background');
SetResourceString(@SNameMenuBar, 'Menu Bar');
SetResourceString(@SNameMenuHighlight, 'Menu Highlight');
SetResourceString(@SNameMenuText, 'Menu Text');
SetResourceString(@SNameNone, 'None');
SetResourceString(@SNameScrollBar, 'Scroll Bar');
SetResourceString(@SName3DDkShadow, '3D Dark Shadow');
SetResourceString(@SName3DLight, '3D Light');
SetResourceString(@SNameWindow, 'Window Background');
SetResourceString(@SNameWindowFrame, 'Window Frame');
SetResourceString(@SNameWindowText, 'Window Text');
SetResourceString(@SInvalidBitmapPixelFormat, 'Invalid bitmap pixel format, should be a 32 bit image');
SetResourceString(@SJumplistsItemErrorGetpsi, 'Querying the IPropertyStore interface');
SetResourceString(@SJumplistsItemErrorInitializepropvar, 'Initializing a variant property');
SetResourceString(@SJumplistsItemErrorSetps, 'Setting the value of a property store');
SetResourceString(@SJumplistsItemErrorCommitps, 'Committing a property store');
SetResourceString(@SJumplistsItemErrorSettingarguments, 'Setting the arguments of a jump list item');
SetResourceString(@SJumplistsItemErrorSettingpath, 'Setting the path of a jump list item');
SetResourceString(@SJumplistsItemErrorSettingicon, 'Setting the icon location of a jump list item');
SetResourceString(@SJumplistsItemErrorAddingtobjarr, 'Adding an item to an object array');
SetResourceString(@SJumplistsItemErrorGettingobjarr, 'Querying the IObjectArray interface');
SetResourceString(@SJumplistsItemErrorNofriendlyname, 'The FriendlyName property of an item must not be empty');
SetResourceString(@SJumplistsItemException, 'JumpListItem exception: Error %d: %s');
SetResourceString(@SJumplistException, 'JumpList exception: Error %d: %s');
SetResourceString(@SJumplistErrorBeginlist, 'Initiating a building session for a new jump list');
SetResourceString(@SJumplistErrorAppendrc, 'Appending an item to the recent files category of a new jump list');
SetResourceString(@SJumplistErrorAppendfc, 'Appending an item to the frequent files category of a new jump list');
SetResourceString(@SJumplistErrorAddusertasks, 'Adding your tasks to a new jump list');
SetResourceString(@SJumplistErrorAddcategory, 'Adding a custom category (''%s'') and its child items to a new jump list');
SetResourceString(@SJumplistErrorCommitlist, 'Committing a new jump list');
SetResourceString(@SJumplistExceptionInvalidOS, 'The current operating system does not support jump lists');
SetResourceString(@SJumplistExceptionAppID, 'The current process already has an application ID: %s');
{ BeginInvoke }
SetResourceString(@sBeginInvokeNoHandle, 'Cannot call BeginInvoke on a control with no parent or window handle');
SetResourceString(@SToggleSwitchCaptionOn, 'On');
SetResourceString(@SToggleSwitchCaptionOff, 'Off');
SetResourceString(@SInvalidRelativePanelControlItem, 'ControlItem.Control cannot be set to owning RelativePanel');
SetResourceString(@SInvalidRelativePanelSibling, 'Control is not a sibling within RelativePanel');
SetResourceString(@SInvalidRelativePanelSiblingSelf, 'Control cannot be positioned relative to itself');
end;
End. |
PROGRAM PointerExample;
TYPE IntPointer = ^integer;
PROCEDURE Swap(var x, y: integer);
var aux: integer;
BEGIN (* Swap *)
aux := x;
x := y;
y := aux;
END; (* Swap *)
PROCEDURE SwapPtr(x, y: IntPointer);
var aux: integer;
BEGIN (* SwapPtr *)
Writeln('x: ', longint(x));
WriteLn('aux: ', longint(@aux));
aux := x^;
x^ := y^;
y^ := aux;
END; (* SwapPtr *)
var x, y: integer;
p, q: IntPointer;
BEGIN (* PointerExample *)
x := 1; y := 2;
p := @x; q := @y;
WriteLn('@x: ', longint(@x));
WriteLn('@y: ', longint(@y));
WriteLn('@p: ', longint(@p));
WriteLn('@q: ', longint(@q));
Swap(x, y);
WriteLn(x, ', ', y);
SwapPtr(@x, @y);
WriteLn(x, ', ', y);
END. (* PointerExample *) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.