text stringlengths 14 6.51M |
|---|
unit ncaFrmTarifa2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, cxTextEdit, cxCurrencyEdit,
cxInplaceContainer, cxControls, StdCtrls,
dxBar, cxClasses, cxMaskEdit, cxSpinEdit, cxTimeEdit, cxContainer, cxEdit,
cxLabel, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxCheckBox, cxPC, Menus, cxLookAndFeelPainters, cxRadioGroup,
cxButtons, cxDropDownEdit, cxFilter, cxData, cxDataStorage,
cxGridCustomTableView, cxGridTableView, cxGridCustomView, cxGridLevel, cxGrid,
cxButtonEdit, cxGroupBox, cxEditRepositoryItems, cxCalc, cxHint;
type
TFrmTarifa = class(TForm)
dxBarManager1: TdxBarManager;
cmTM1: TdxBarButton;
cmTM5: TdxBarButton;
cmTM10: TdxBarButton;
cmTM15: TdxBarButton;
cmTM20: TdxBarButton;
cmTM25: TdxBarButton;
cmTM30: TdxBarButton;
cmTM60: TdxBarButton;
cm1c: TdxBarButton;
dxBarButton2: TdxBarButton;
cm10c: TdxBarButton;
cm25c: TdxBarButton;
cm50c: TdxBarButton;
Paginas: TcxPageControl;
tsMinutos: TcxTabSheet;
panMin: TLMDSimplePanel;
LMDSimplePanel1: TLMDSimplePanel;
btnAvancar: TcxButton;
btnVoltar: TcxButton;
tsHoras: TcxTabSheet;
dxBarButton1: TdxBarButton;
panHoras: TLMDSimplePanel;
dxBarButton3: TdxBarButton;
dxBarButton4: TdxBarButton;
dxBarButton5: TdxBarButton;
dxBarButton6: TdxBarButton;
dxBarButton7: TdxBarButton;
dxBarButton8: TdxBarButton;
dxBarButton9: TdxBarButton;
dxBarButton10: TdxBarButton;
LMDSimplePanel4: TLMDSimplePanel;
lbPromptHora: TcxLabel;
edValor1h: TcxCurrencyEdit;
cxLabel1: TcxLabel;
btnOkHoras: TcxButton;
cxTabSheet1: TcxTabSheet;
LMDSimplePanel5: TLMDSimplePanel;
cxLabel6: TcxLabel;
cxLabel4: TcxLabel;
edTempoI: TcxSpinEdit;
cxLabel3: TcxLabel;
edValorI: TcxCurrencyEdit;
cxLabel9: TcxLabel;
cxLabel7: TcxLabel;
dxBarButton11: TdxBarButton;
dxBarButton12: TdxBarButton;
dxBarButton13: TdxBarButton;
dxBarButton14: TdxBarButton;
dxBarButton15: TdxBarButton;
btnOkInicio: TcxButton;
LMDSimplePanel2: TLMDSimplePanel;
LMDSimplePanel6: TLMDSimplePanel;
LMDSimplePanel7: TLMDSimplePanel;
edDivMin: TcxComboBox;
cxLabel8: TcxLabel;
cxLabel10: TcxLabel;
btnAplicarMin: TcxButton;
SC: TcxEditStyleController;
GL: TcxGridLevel;
Grid: TcxGrid;
tvMin: TcxGridTableView;
tvMinTempoStr: TcxGridColumn;
tvMinValor: TcxGridColumn;
tvMinTempo: TcxGridColumn;
LMDSimplePanel3: TLMDSimplePanel;
gridH: TcxGrid;
tvH: TcxGridTableView;
tvHTempoUso: TcxGridColumn;
tvHCobrar: TcxGridColumn;
tvHTarifa: TcxGridColumn;
glH: TcxGridLevel;
cxEditRepository1: TcxEditRepository;
tvCurEdit_ReadOnly: TcxEditRepositoryCurrencyItem;
tvCurEdit: TcxEditRepositoryCurrencyItem;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
LMDSimplePanel8: TLMDSimplePanel;
cxGroupBox2: TcxGroupBox;
edArr: TcxComboBox;
cxLabel11: TcxLabel;
cxLabel12: TcxLabel;
LMDSimplePanel9: TLMDSimplePanel;
cxGroupBox1: TcxGroupBox;
lbComoTarifar: TcxLabel;
rbRepetirUltima: TcxRadioButton;
rbRepetirTodas: TcxRadioButton;
rbRepetirDesde: TcxRadioButton;
edRepetirHora: TcxSpinEdit;
cxLabel14: TcxLabel;
cxLabel2: TcxLabel;
edNumH: TcxSpinEdit;
cxLabel5: TcxLabel;
HC: TcxHintStyleController;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure cmRemoverTempoClick(Sender: TObject);
procedure PaginasChange(Sender: TObject);
procedure btnAvancarClick(Sender: TObject);
procedure btnVoltarClick(Sender: TObject);
procedure btnOkHorasClick(Sender: TObject);
procedure btnAplicarMinClick(Sender: TObject);
procedure edValor1hKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnOkInicioClick(Sender: TObject);
procedure edValorIKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edTempoIKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edArrPropertiesCloseUp(Sender: TObject);
procedure tlHorasCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas;
AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean);
procedure tlHorasInitEdit(Sender, AItem: TObject; AEdit: TcxCustomEdit);
procedure tvMinCanFocusRecord(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; var AAllow: Boolean);
procedure tvMinInitEdit(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit);
procedure tvMinInitEditValue(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var AValue: Variant);
procedure tvMinCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure FormShow(Sender: TObject);
procedure tvHCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure tvHEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
procedure tvMinEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
procedure edNumHPropertiesChange(Sender: TObject);
procedure rbRepetirDesdeClick(Sender: TObject);
procedure rbRepetirUltimaClick(Sender: TObject);
procedure rbRepetirTodasClick(Sender: TObject);
procedure tvHDataControllerRecordChanged(
ADataController: TcxCustomDataController; ARecordIndex,
AItemIndex: Integer);
procedure edRepetirHoraPropertiesChange(Sender: TObject);
procedure tvMinTempoStrCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure tvMinMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure tvMinMouseLeave(Sender: TObject);
procedure GridMouseLeave(Sender: TObject);
procedure tvMinMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
FValorI : Currency;
FTempoI : Integer;
FDivMin : Integer;
FArr : Byte;
FShowing : Boolean;
FRepetir : Byte;
FDisableCalcHoras : Boolean;
FMouseOverDel : Boolean;
FShowHint : Boolean;
{ Private declarations }
procedure Load;
procedure LoadMin;
procedure ValidaMinutos;
procedure AjustaOpcoesHora;
procedure HideHint;
procedure CalcHorasExtras;
procedure SetRepetir(const Value: Byte);
procedure SetMouseOverDel(const AValue: Boolean);
public
property Repetir: Byte
read FRepetir write SetRepetir;
{ Public declarations }
end;
var
FrmTarifa: TFrmTarifa;
implementation
uses ufmImagens, ncaFrmPri, ncClassesBase;
{$R *.dfm}
procedure TFrmTarifa.AjustaOpcoesHora;
begin
lbComoTarifar.Caption := 'Como tarifar tempo de uso maior que ' + IntToStr(edNumH.Value)+'?';
rbRepetirUltima.Caption := 'Aplicar a tarifa da ' + IntToStr(edNumH.Value) + 'a. hora nas demais horas';
edRepetirHora.Properties.MaxValue := edNumH.Value;
if edRepetirHora.Value > edNumH.Value then
edRepetirHora.Value := edNumH.Value;
edRepetirHora.Enabled := rbRepetirDesde.Checked;
end;
procedure TFrmTarifa.btnAplicarMinClick(Sender: TObject);
begin
FDivMin := StrToIntDef(Trim(edDivMin.Text), 1);
ValidaMinutos;
panMin.Visible := True;
Load;
Grid.SetFocus;
tvMin.DataController.FocusedRecordIndex := 1;
tvMin.Controller.FocusedColumnIndex := 1;
tvMin.Controller.EditingController.ShowEdit;
end;
procedure TFrmTarifa.btnAvancarClick(Sender: TObject);
var I: Integer;
begin
{ case Paginas.ActivePageIndex of
0 : ValidaP;
1 : if edValor1h.Value<FValorI then
Raise Exception.Create('O valor para 1h de uso não pode ser menor que o valor inicial');
2 : for I := 1 to 23 do
if tlHoras.Items[i].Values[1] < tlHoras.Items[i-1].Values[1] then
Raise Exception.Create('O valor das horas não pode dimuir');
end;}
Paginas.ActivePageIndex := Paginas.ActivePageIndex + 1;
{ case Paginas.ActivePageIndex of
1 : edValor1H.SetFocus;
2 : for I := 0 to 23 do tlHoras.Nodes.Items[I].Values[1] := ((I+1)*edValor1H.Value);
3 : Load;
end;}
end;
procedure TFrmTarifa.btnOkHorasClick(Sender: TObject);
var i: integer;
begin
lbPromptHora.Style.TextColor := clGray;
lbPromptHora.Caption := 'Informe abaixo o valor total a ser cobrado conforme a quantidade de horas utilizada';
panHoras.Visible := True;
FDisableCalcHoras := True;
try
for I := 0 to 23 do
tvH.DataController.Values[I, 1] := ((I+1)*edValor1H.Value);
finally
FDisableCalcHoras := False;
end;
gridH.SetFocus;
tvH.DataController.FocusedRecordIndex := 1;
tvH.Controller.FocusedColumnIndex := 1;
tvH.Controller.EditingController.ShowEdit;
btnAvancar.Enabled := True;
Load;
tsMinutos.Enabled := True;
end;
procedure TFrmTarifa.btnOkInicioClick(Sender: TObject);
begin
ValidaMinutos;
tsHoras.Enabled := True;
Paginas.ActivePageIndex := 1;
end;
procedure TFrmTarifa.btnVoltarClick(Sender: TObject);
begin
Paginas.ActivePageIndex := Paginas.ActivePageIndex - 1;
end;
procedure TFrmTarifa.CalcHorasExtras;
var
I, R: Integer;
V : Currency;
begin
if FDisableCalcHoras then Exit;
FDisableCalcHoras := True;
try
case FRepetir of
rtTodas : R := 0;
rtUltima : R := edNumH.Value - 1;
rtDesde : R := edRepetirHora.Value - 1;
end;
for I := edNumH.Value to 23 do with tvH.DataController do begin
if R=0 then
V := Values[0, 1] else
V := Values[R, 1] - Values[R-1, 1];
V := V + Values[I-1, 1];
Values[I, 1] := V;
case FRepetir of
rtTodas : begin
Inc(R);
if R>=edNumH.Value then R := 0;
end;
rtDesde : begin
Inc(R);
if R>=edNumH.Value then R := edRepetirHora.Value - 1;
end;
end;
end;
finally
FDisableCalcHoras := False;
end;
end;
procedure TFrmTarifa.cmRemoverTempoClick(Sender: TObject);
begin
tvMin.DataController.DeleteFocused;
end;
procedure TFrmTarifa.edArrPropertiesCloseUp(Sender: TObject);
begin
FArr := StrToInt(Trim(edArr.Text));
end;
procedure TFrmTarifa.edNumHPropertiesChange(Sender: TObject);
begin
tvH.Invalidate(True);
tvMin.Invalidate(True);
AjustaOpcoesHora;
gridH.SetFocus;
end;
procedure TFrmTarifa.edRepetirHoraPropertiesChange(Sender: TObject);
begin
CalcHorasExtras;
end;
procedure TFrmTarifa.edTempoIKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = Key_Enter then btnOkInicio.Click;
end;
procedure TFrmTarifa.edValor1hKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = Key_Enter then
btnOkHoras.Click;
end;
procedure TFrmTarifa.edValorIKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=Key_Enter then
edTempoI.SetFocus;
end;
procedure TFrmTarifa.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmTarifa.FormCreate(Sender: TObject);
var I: Integer;
begin
FShowHint := False;
FMouseOverDel := False;
FRepetir := rtUltima;
FShowing := False;
FArr := 5;
edArr.ItemIndex := 1;
FDivMin := 15;
Paginas.ActivePageIndex := 0;
ActiveControl := edValorI;
// tlHoras.OptionsView.Headers := False;
FTempoI := 0;
// TL.OptionsView.Headers := False;
FDisableCalcHoras := True;
try
for I := 1 to 24 do with tvH.DataController do begin
AppendRecord;
Values[I-1, 0] := IntToStr(I) + ' h';
end;
finally
FDisableCalcHoras := False;
end;
end;
procedure TFrmTarifa.FormShow(Sender: TObject);
begin
FShowing := True;
end;
procedure TFrmTarifa.GridMouseLeave(Sender: TObject);
begin
HideHint;
end;
procedure TFrmTarifa.HideHint;
begin
HC.HideHint;
FShowHint := False;
end;
procedure TFrmTarifa.Load;
var
I, H, M, T, MR, TA : Integer;
V, VR: Currency;
Diminuiu : Boolean;
begin
tvMin.BeginUpdate;
try
while tvMin.DataController.RecordCount>0 do tvMin.DataController.DeleteRecord(0);
with tvMin.DataController do
if FTempoI < 60 then begin
I := AppendRecord;
Values[I, 0] := IntToStr(FTempoI)+'m';
Values[I, 1] := FValorI;
Values[I, 2] := FTempoI;
if FTempoI>0 then
Diminuiu := ((FValorI / (FTempoI/60)) < edValor1H.Value) else
Diminuiu := True;
MR := 60 - FTempoI;
VR := edValor1h.Value - FValorI;
TA := FTempoI;
M := FDivMin;
while M < 60 do begin
if M>FTempoI then begin
I := AppendRecord;
Values[I, 0] := IntToStr(M)+'m';
if Diminuiu then
V := (M/60) * edValor1H.Value else
V := (((M-FTempoI)/MR) * VR) + FValorI;
if Frac(V/(FArr/100))>0 then
V := (Int(V/(FArr/100)) + 1) * (FArr/100);
Values[I, 1] := V;
Values[I, 2] := M;
TA := M;
end;
M := M + FDivMin;
end;
end;
with tvMin.DataController do
for H := 1 to 24 do begin
I := AppendRecord;
Values[I, 0] := IntToStr(h)+'h';
Values[I, 1] := tvH.DataController.Values[h-1, 1];
Values[I, 2] := (h*60);
if H<24 then begin
M := FDivMin;
while (M < 60) do begin
I := AppendRecord;
Values[I, 0] := IntToStr(M)+'m';
V := tvH.DataController.Values[h-1, 1] + ((M/60) * edValor1H.Value);
if Frac(V/(FArr/100))>0 then
V := (Int(V/(FArr/100)) + 1) * (FArr/100);
Values[I, 1] := V;
Values[I, 2] := (h*60) + m;
M := M + FDivMin;
end;
end;
end;
finally
tvMin.EndUpdate;
end;
end;
procedure TFrmTarifa.LoadMin;
begin
end;
procedure TFrmTarifa.PaginasChange(Sender: TObject);
begin
btnVoltar.Visible := (Paginas.ActivePageIndex>0);
btnAvancar.Visible := (Paginas.ActivePageIndex=1);
if not FShowing then Exit;
case Paginas.ActivePageIndex of
0 : edValorI.SetFocus;
1 : if panHoras.Visible then
gridH.SetFocus else
edValor1h.SetFocus;
2 : Grid.SetFocus;
end;
if Paginas.ActivePage = tsHoras then
if panHoras.Visible then
gridH.SetFocus else
edValor1h.SetFocus;
end;
procedure TFrmTarifa.rbRepetirDesdeClick(Sender: TObject);
begin
FRepetir := rtDesde;
edRepetirHora.Enabled := True;
CalcHorasExtras;
gridH.SetFocus;
end;
procedure TFrmTarifa.rbRepetirTodasClick(Sender: TObject);
begin
FRepetir := rtTodas;
CalcHorasExtras;
gridH.Setfocus;
end;
procedure TFrmTarifa.rbRepetirUltimaClick(Sender: TObject);
begin
FRepetir := rtUltima;
CalcHorasExtras;
gridH.SetFocus;
end;
procedure TFrmTarifa.SetMouseOverDel(const AValue: Boolean);
begin
if FMouseOverDel=AValue then Exit;
if not AValue then HideHint;
FMouseOverDel := AValue;
tvMin.ViewData.Records[tvMin.DataController.FocusedRecordIndex].Invalidate(tvMinTempoStr);
end;
procedure TFrmTarifa.SetRepetir(const Value: Byte);
begin
if FRepetir=Value then Exit;
FRepetir := Value;
case FRepetir of
rtUltima : rbRepetirUltima.Checked := True;
rtTodas : rbRepetirTodas.Checked := True;
rtDesde : rbRepetirDesde.Checked := True;
end;
edRepetirHora.Enabled := (FRepetir=rtDesde);
end;
procedure TFrmTarifa.tlHorasCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas;
AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean);
begin
if aviewinfo.Focused then
ACanvas.Font.Style := [fsBold];
end;
procedure TFrmTarifa.tlHorasInitEdit(Sender, AItem: TObject;
AEdit: TcxCustomEdit);
begin
AEdit.Style.StyleController := SC;
AEdit.Style.TextStyle := [fsBold];
AEdit.StyleFocused.TextStyle := [fsBold];
end;
procedure TFrmTarifa.tvHCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
begin
if AViewInfo.GridRecord.Index >= edNumH.Value then begin
if AViewInfo.Focused then
ACanvas.Brush.Color := $00BFFFFF;
ACanvas.Font.Color := clGray;
end;
end;
procedure TFrmTarifa.tvHDataControllerRecordChanged(
ADataController: TcxCustomDataController; ARecordIndex, AItemIndex: Integer);
var Tar: Currency;
begin
if AItemIndex=2 then Exit;
if ARecordIndex=0 then
ADataController.Values[ARecordIndex, 2] := ADataController.Values[ARecordIndex, 1] else
ADataController.Values[ARecordIndex, 2] := ADataController.Values[ARecordIndex, 1] - ADataController.Values[ARecordIndex-1, 1];
CalcHorasExtras;
end;
procedure TFrmTarifa.tvHEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
AAllow := (tvH.DataController.FocusedRecordIndex < edNumH.Value);
end;
procedure TFrmTarifa.tvMinCanFocusRecord(Sender: TcxCustomGridTableView;
ARecord: TcxCustomGridRecord; var AAllow: Boolean);
var
V: Variant;
I: Integer;
begin
V := ARecord.Values[2];
if V<>null then begin
I := V;
AAllow := ((I mod 60) <> 0);
end else
AAllow := False;
end;
procedure TFrmTarifa.tvMinCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var
V: Variant;
I: Integer;
begin
V := AViewInfo.GridRecord.Values[2];
if V<>null then begin
I := V;
if ((I mod 60) = 0) then begin
ACanvas.Brush.Color := clBtnFace;
ACanvas.Font.Style := [fsBold];
if I > (edNumH.Value*60) then
ACanvas.Font.Color := $00ADADAD else
ACanvas.Font.Color := clBlack;
end else begin
if AViewInfo.Focused then
ACanvas.Brush.Color := $00BFFFFF;
if I>(edNumH.Value*60) then
ACanvas.Font.Color := $00ADADAD;
end;
end;
end;
procedure TFrmTarifa.tvMinEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
with tvMin.DataController do begin
AAllow := (FocusedRecordIndex > 0) and
(Values[FocusedRecordIndex, 2]<(edNumH.Value*60));
end;
end;
procedure TFrmTarifa.tvMinInitEdit(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit);
begin
AEdit.Style.StyleController := SC;
AEdit.Style.TextStyle := [fsBold];
AEdit.StyleFocused.TextStyle := [fsBold];
end;
procedure TFrmTarifa.tvMinInitEditValue(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var AValue: Variant);
begin
AEdit.Style.StyleController := SC;
AEdit.Style.TextStyle := [fsBold];
AEdit.StyleFocused.TextStyle := [fsBold];
end;
procedure TFrmTarifa.tvMinMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var V: Variant;
procedure SetNextFocus;
var I : Integer;
begin
with tvMin.DataController do begin
for I := FocusedRecordIndex to RecordCount - 1 do
if (Values[I, 2]<>null) and (Values[I, 2] mod 60) > 0 then begin
FocusedRecordIndex := I;
Exit;
end;
FocusedRecordIndex := 0;
end;
end;
begin
if FShowHint then begin
with tvMin.DataController do begin
DeleteFocused;
SetNextFocus;
end;
HideHint;
end;
end;
procedure TFrmTarifa.tvMinMouseLeave(Sender: TObject);
begin
SetMouseOverDel(False);
end;
procedure TFrmTarifa.tvMinMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
AHitTest: TcxCustomGridHitTest;
AGridSite: TcxGridSite;
RCH : TcxGridRecordCellHitTest;
P : TPoint;
begin
P.X := X;
P.Y := Y;
P := Grid.ClientToScreen(P);
P.Y := P.Y+22;
AGridSite := Sender as TcxGridSite;
AHitTest := tvMin.GetHitTest(X, Y);
if AHitTest<>nil then
AGridSite.Cursor := AHitTest.Cursor;
if (AHitTest is TcxGridRecordCellHitTest) then
begin
RCH := TcxGridRecordCellHitTest(AHitTest);
X := X - 15;
SetMouseOverDel((RCH.Item=tvMinTempoStr) and RCH.GridRecord.Focused and (X in [1..30]));
if FMouseOverDel then begin
AGridSite.Cursor := crHandPoint;
if not FShowHint then begin
HC.ShowHint(P.X, P.Y, 'Remover Tarifa', 'Clique aqui para remover essa tarifa/tempo');
FShowHint := True;
end;
end;
end else
SetMouseOverDel(False);
end;
procedure TFrmTarifa.tvMinTempoStrCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var V : Variant;
begin
with AViewInfo do begin
if not (Selected or Focused) then Exit;
V := GridRecord.Values[2];
if (V=null) or (V>(edNumH.Value*60)) then Exit;
ACanvas.FillRect(Bounds);
ACanvas.DrawTexT(Text, Bounds, cxAlignCenter);
if (GridRecord.Index>0) and (Selected or Focused) then
if FMouseOverDel then
ACanvas.DrawImage(dmImagens.Imagens, Bounds.Left+5, Bounds.Top, 64) else
ACanvas.DrawImage(dmImagens.Imagens, Bounds.Left+5, Bounds.Top, 79);
ADone := True;
end;
end;
procedure TFrmTarifa.ValidaMinutos;
begin
FValorI := edValorI.Value;
FTempoI := edTempoI.Value;
if (FValorI>0) and (FTempoI<1) then
Raise Exception.Create('O tempo inicial tem que ser informado');
end;
end.
|
program parcialjulio18;
const
MAX_LETRAS = 6;
TOTAL_PALABRAS = 4;
type
TLetras = 'a'..'z';
Texto = record
letras : array[1..MAX_LETRAS] of TLetras;
tope : 0 .. MAX_LETRAS;
end;
Diccionario = array[1..TOTAL_PALABRAS] of Texto;
ListaEnt = ^celda;
celda = record
elem:integer;
sig:ListaEnt;
end;
procedure LeerTexto(var t:Texto);
var tmp : char;
i : integer;
begin
i := 1;
t.tope := 0;
read(tmp);
while (not eoln) do
begin
t.letras[i] := tmp;
t.tope := t.tope + 1;
i := i +1;
read(tmp);
end;
end;
function prefijo(t1,t2:Texto):boolean;
var i : integer;
begin
i := 1;
while ((i<=t1.tope) and (t1.letras[i]=t2.letras[i])) do
i := i + 1;
if (i>t1.tope)then
prefijo := true
else
prefijo := false;
end;
function prediccion(t : Texto; dic: Diccionario): integer;
var i,indice : integer;
begin
indice:= 0;
i := 1;
while(i<=TOTAL_PALABRAS) and (indice=0)do
begin
if (prefijo(t,dic[i]))then
indice := i
else
indice := 0;
i := i + 1;
end;
prediccion := indice;
end;
function distancia(t1,t2: Texto):integer;
var dif,i:integer;
begin
dif := 0;
for i := 1 to t1.tope do
if (t1.letras[i]<>t2.letras[i])then
dif := dif + 1;
distancia := dif + abs(t1.tope-t2.tope);
end;
procedure duplicarN(n:integer;var l:ListaEnt);
var aux,aux2 : ListaEnt;
encontro : boolean;
begin
aux := l;
encontro := false;
while (aux <> nil) do
begin
if (aux^.elem <> n) then
aux := aux^.sig
else
encontro := true;
end;
if (encontro) then
begin
if (l<>nil)then
begin
aux2 := aux^.sig;
new(aux^.sig);
aux^.sig^.elem := n;
aux^.sig^.sig := aux2;
end;
end;
end;
var t1,t2 :Texto;
begin
LeerTexto(t1);
LeerTexto(t2);
end. |
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
}
unit BrazilCombo;
interface
{$I SMVersion.inc}
uses
Classes, Messages, Windows, Controls, StdCtrls;
type
{ TBrazilStateCombo }
TBrStates = (brAC, brAL, brAM, brAP, brBA, brCE, brDF, brES,
brGO, brMA, brMG, brMS, brMT, brPA, brPB, brPE,
brPI, brPR, brRJ, brRO, brRN, brRR, brRS, brSC,
brSE, brSP, brTO);
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TBrazilStateCombo = class(TCustomComboBox)
private
{ Private declarations }
FStateValue: TBrStates;
FStateNames: TStrings;
FOnChange: TNotifyEvent;
procedure SetStateValue(NewValue: TBrStates);
procedure SetStateNames(Value: TStrings);
procedure StateNamesChanged(Sender: TObject);
procedure ResetItemHeight;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
protected
{ Protected declarations }
procedure CreateWnd; override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
procedure Click; override;
procedure BuildList; virtual;
procedure DoChange; dynamic;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Text;
published
{ Published declarations }
property StateValue: TBrStates read FStateValue write SetStateValue;
property StateNames: TStrings read FStateNames write SetStateNames;
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDrag;
end;
procedure Register;
implementation
{$R *.RES}
uses Graphics, SysUtils, TypInfo;
procedure Register;
begin
RegisterComponents('SMComponents', [TBrazilStateCombo]);
end;
function GetItemHeight(Font: TFont): Integer;
var
DC: HDC;
SaveFont: HFont;
Metrics: TTextMetric;
begin
DC := GetDC(0);
try
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
Result := Metrics.tmHeight + 1;
end;
{ TBrazilStateCombo }
constructor TBrazilStateCombo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Style := csOwnerDrawFixed;
FStateValue := brAC;
FStateNames := TStringList.Create;
TStringList(FStateNames).OnChange := StateNamesChanged;
end;
destructor TBrazilStateCombo.Destroy;
begin
TStringList(FStateNames).OnChange := nil;
FStateNames.Free;
FStateNames := nil;
inherited Destroy;
end;
procedure TBrazilStateCombo.CreateWnd;
begin
inherited CreateWnd;
BuildList;
SetStateValue(FStateValue);
end;
procedure TBrazilStateCombo.BuildList;
var i: Integer;
StateName: string;
begin
Clear;
for i := Ord(Low(TBrStates)) to Ord(High(TBrStates)) do
begin
if (i <= Pred(FStateNames.Count)) and (FStateNames[i] <> '') then
StateName := FStateNames[i]
else
{ delete two first characters which prefix "cl" educated }
StateName := Copy(GetEnumName(TypeInfo(TBrStates), i), 3, MaxInt);
Items.AddObject(StateName, TObject(i));
end;
end;
procedure TBrazilStateCombo.StateNamesChanged(Sender: TObject);
begin
if HandleAllocated then
begin
FStateValue := StateValue;
RecreateWnd;
end;
end;
procedure TBrazilStateCombo.SetStateNames(Value: TStrings);
begin
FStateNames.Assign(Value);
end;
procedure TBrazilStateCombo.SetStateValue(NewValue: TBrStates);
var i: Integer;
CurrentState: TBrStates;
begin
if (ItemIndex < 0) or (NewValue <> FStateValue) then
{ change selected item }
for i := 0 to Pred(Items.Count) do
begin
CurrentState := TBrStates(Items.Objects[i]);
if CurrentState = NewValue then
begin
FStateValue := NewValue;
if ItemIndex <> i then
ItemIndex := i;
DoChange;
Break;
end;
end;
end;
procedure TBrazilStateCombo.DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState);
const
FlagWidth = 22;
var strText: string;
bmp: TBitmap;
begin
Canvas.FillRect(Rect);
Canvas.Brush.Style := bsClear;
strText := Items[Index];
if Index > -1 then
begin
bmp := TBitmap.Create;
try
bmp.Handle := LoadBitmap(hInstance, PChar(UpperCase(GetEnumName(TypeInfo(TBrStates), Index))));
if bmp <> nil then
Canvas.StretchDraw(Bounds(Rect.Left + 2, Rect.Top, bmp.Width, bmp.Height), bmp);
finally
bmp.Free
end
end;
Canvas.TextOut(Rect.Left + 36, Rect.Top, strText)
end;
procedure TBrazilStateCombo.Click;
begin
if ItemIndex >= 0 then
StateValue := TBrStates(Items.Objects[ItemIndex]);
inherited Click;
end;
procedure TBrazilStateCombo.CMFontChanged(var Message: TMessage);
begin
inherited;
ResetItemHeight;
RecreateWnd;
end;
procedure TBrazilStateCombo.ResetItemHeight;
var i: Integer;
begin
i := GetItemHeight(Font);
if i > 9 then
ItemHeight := i
else
ItemHeight := 9;
end;
procedure TBrazilStateCombo.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
end.
|
UNIT FidoUtil;
interface
USES FileUtil; {exists}
CONST
LastReadFileName = 'LASTREAD.';
TYPE
pathstr = STRING[79];
PROCEDURE UpDateLastRead( path : PathStr; MsgNum : WORD);
FUNCTION FindLastRead( path : PathStr) : WORD;
(*********************************************************)
implementation
PROCEDURE UpDateLastRead( path : PathStr; MsgNum : WORD);
VAR
outfile : FILE OF WORD;
BEGIN
{ fix backslash if necessary }
if NOT (path[length(path)] = '\') THEN
path := path + '\';
path := path + LastReadFileName;
Assign(outfile,path);
Rewrite(outfile);
Write(outfile,MsgNum);
Close(outfile);
END; { UpDateLastRead }
{ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
FUNCTION FindLastRead( path : PathStr) : WORD;
VAR
MsgNum : WORD;
outfile : FILE OF WORD;
BEGIN
{ fix backslash if necessary }
if NOT (path[length(path)] = '\') THEN
path := path + '\';
path := path + LastReadFileName;
IF exists(path) THEN
BEGIN
Assign(outfile,path);
Reset(outfile);
Read(outfile,MsgNum);
Close(outfile);
FindLastRead := MsgNum;
END
ELSE FindLastRead := 1;
END; { UpDateLastRead }
BEGIN
END. {FidoUtil} |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC GUIx Field list editor }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.Fields;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB,
FireDAC.VCLUI.OptsBase, FireDAC.VCLUI.Controls;
type
TfrmFDGUIxFormsFields = class(TfrmFDGUIxFormsOptsBase)
lbFields: TFDGUIxFormsDblListBox;
private
function GetFields: String;
procedure SetDSFields(ADataSet: TDataSet; AFields: String);
public
class function EditFields(var AFields: String; ADataSet: TDataSet;
ACaption: String): Boolean;
end;
var
frmFDGUIxFormsFields: TfrmFDGUIxFormsFields;
implementation
uses
FireDAC.Stan.Util;
{$R *.dfm}
{-------------------------------------------------------------------------------}
function TfrmFDGUIxFormsFields.GetFields: String;
var
i: Integer;
begin
Result := '';
for i := 0 to lbFields.DstItems.Count - 1 do begin
if Result <> '' then
Result := Result + ';';
Result := Result + lbFields.DstItems[i];
end;
end;
{-------------------------------------------------------------------------------}
{$WARNINGS OFF}
procedure TfrmFDGUIxFormsFields.SetDSFields(ADataSet: TDataSet; AFields: String);
var
j, i: Integer;
s: String;
begin
lbFields.DstItems.BeginUpdate;
lbFields.SrcItems.BeginUpdate;
try
lbFields.DstItems.Clear;
lbFields.SrcItems.Clear;
if ADataSet <> nil then begin
ADataSet.GetFieldNames(lbFields.SrcItems);
i := 1;
while i <= Length(AFields) do begin
s := ExtractFieldName(AFields, i);
j := lbFields.SrcItems.IndexOf(s);
if j <> -1 then begin
lbFields.SrcItems.Delete(j);
lbFields.DstItems.Add(s);
end;
end;
end;
finally
lbFields.DstItems.EndUpdate;
lbFields.SrcItems.EndUpdate;
end;
end;
{$WARNINGS ON}
{-------------------------------------------------------------------------------}
class function TfrmFDGUIxFormsFields.EditFields(var AFields: String;
ADataSet: TDataSet; ACaption: String): Boolean;
var
oFrm: TfrmFDGUIxFormsFields;
begin
oFrm := TfrmFDGUIxFormsFields.Create(nil);
try
oFrm.SetDSFields(ADataSet, AFields);
oFrm.lblPrompt.Caption := ACaption;
Result := oFrm.ShowModal = mrOK;
if Result then
AFields := oFrm.GetFields;
finally
FDFree(oFrm);
end;
end;
end.
|
unit uOlhaPasta;
interface
uses
Windows, SysUtils, ExtCtrls, classes, controls, StdCtrls, graphics,
Messages, Int64List, SyncObjs, uDirWatch;
type
TFolderEvent = procedure(Sender: TObject; aPrintName:string) of object;
TOlhaPastaThread = class(TThread)
private
fOnNewPrint : TFolderEvent;
procedure SyncNewPrint;
protected
fFilesPath : string;
fPrintName : string;
procedure doNewPrint(aPrintName:string);
procedure Execute; override;
procedure DirectoryWatchOnChange(Sender : TObject);
public
property OnNewPrint : TFolderEvent read fOnNewPrint write fOnNewPrint;
constructor Create(aFilesPath: string);
end;
implementation
{$IFNDEF NOLOG}
uses
uLogs;
{$ENDIF}
{ TOlhaPastaThread }
constructor TOlhaPastaThread.Create(aFilesPath: string);
begin
{$IFNDEF NOLOG}GLog.Log(self,[lcTrace],'Create');{$ENDIF}
fFilesPath := aFilesPath;
inherited Create(true);
end;
procedure TOlhaPastaThread.DirectoryWatchOnChange(Sender: TObject);
var
sr: TSearchRec;
pName :string;
begin
{$WARNINGS OFF}
if SysUtils.FindFirst(fFilesPath + '\*.nexprint', faArchive, sr) = 0 then begin
repeat
if sametext( ExtractFileExt(sr.Name), '.nexprint') then begin
pName := copy(sr.Name, 1, length(sr.Name)-9);
if (fileexists(fFilesPath + '\' +pName+ '.nexprint.json' )) then begin
doNewPrint(pName);
end;
end;
until FindNext(sr) <> 0;
SysUtils.FindClose(sr);
end;
{$WARNINGS ON}
end;
procedure TOlhaPastaThread.doNewPrint(aPrintName: string);
begin
fPrintName := aPrintName;
Synchronize(SyncNewPrint);
end;
procedure TOlhaPastaThread.Execute;
var
Msg : TMsg;
pmRes : integer;
sFilesPath:string;
DirectoryWatch : TDirectoryWatch;
begin
inherited;
DirectoryWatchOnChange(nil);
sFilesPath := fFilesPath;
if (sFilesPath>'')and(sFilesPath[length(sFilesPath)]<>'\') then
sFilesPath := sFilesPath + '\';
DirectoryWatch := TDirectoryWatch.Create(nil);
DirectoryWatch.Directory := sFilesPath;
DirectoryWatch.WatchSubDirs := false;
DirectoryWatch.NotifyFilters := [nfFilename];
DirectoryWatch.OnChange := DirectoryWatchOnChange;
DirectoryWatch.Active := true;
repeat
pmRes := Integer(PeekMessage(Msg, hwnd(0), 0, 0, PM_REMOVE));
if pmRes <> 0 then begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
until terminated;
DirectoryWatch.Active := false;
DirectoryWatch.Free
end;
procedure TOlhaPastaThread.SyncNewPrint;
begin
if assigned(fOnNewPrint) then
fOnNewPrint(self, fPrintName);
end;
end.
|
unit Posting;
interface
uses
Loan, Payment, SysUtils, DateUtils, System.Rtti, Math, PaymentMethod, LoanClassification;
type
TPrincipalDebit = class
strict private
FId: string;
FTerm: smallint;
FAmortization: currency;
FInterestRate: currency;
FReleaseAmount: currency;
FIsDiminishing: boolean;
FDiminishingType: TDiminishingType;
FReleaseDate: TDateTime;
FBalance: currency;
public
property Id: string read FId write FId;
property ReleaseAmount: currency read FReleaseAmount write FReleaseAmount;
property Term: smallint read FTerm write FTerm;
property InterestRate: currency read FInterestRate write FInterestRate;
property IsDiminishing: boolean read FIsDiminishing write FIsDiminishing;
property Amortization: currency read FAmortization write FAmortization;
property DiminishingType: TDiminishingType read FDiminishingType write FDiminishingType;
property ReleaseDate: TDateTime read FReleaseDate write FReleaseDate;
property Balance: currency read FBalance write FBalance;
end;
TInterestDebit = class
strict private
FIsDiminishing: boolean;
FId: string;
FInterestRate: currency;
FLastTransactionDate: TDateTime;
FBalance: currency;
FReleaseAmount: currency;
FDiminishingType: TDiminishingType;
FAdvancePayments: integer;
FIsFixed: boolean;
FReleaseDate: TDateTime;
FPostDate: TDateTime;
function GetNextScheduledPosting: TDateTime;
function GetHasAdvancePayments: boolean;
public
property Id: string read FId write FId;
property Balance: currency read FBalance write FBalance;
property IsDiminishing: boolean read FIsDiminishing write FIsDiminishing;
property IsFixed: boolean read FIsFixed write FIsFixed;
property InterestRate: currency read FInterestRate write FInterestRate;
property DiminishingType: TDiminishingType read FDiminishingType write FDiminishingType;
property ReleaseAmount: currency read FReleaseAmount write FReleaseAmount;
property LastTransactionDate: TDateTime read FLastTransactionDate write FLastTransactionDate;
property NextScheduledPosting: TDateTime read GetNextScheduledPosting;
property AdvancePayments: integer read FAdvancePayments write FAdvancePayments;
property HasAdvancePayments: boolean read GetHasAdvancePayments;
property ReleaseDate: TDateTime read FReleaseDate write FReleaseDate;
property PostDate: TDateTime read FPostDate write FPostDate;
end;
TPosting = class
private
// interest-related methods
function PostInterest(const interest: currency; const loanId: string;
const ADate: TDateTime; const source, status: string): string; overload;
function PostEntry(const refPostingId: string;
const debit, credit: currency; const eventObject, primaryKey, status: string;
const postDate, valueDate: TDateTime; const caseType: string): string;
function GetValueDate(const ACurrentDate, ANextDate: TDateTime): TDateTime; overload;
function GetValueDate(const ADate: TDateTime): TDateTime; overload;
function GetFirstDayOfValueDate(const ADate: TDateTime): TDateTime;
function MonthsBetweenEx(const ADate1, ADate2: TDateTime): integer;
procedure PostAdvancePayment(ALoan: TLoan);
public
procedure Post(const ALoan: TLoan); overload;
procedure Post(const APayment: TPayment); overload;
procedure PostInterest(const ADate: TDate; const ALoanId: string = ''); overload;
procedure PostInterest2(const ADate: TDate);
procedure PostPrincipal(const ADate: TDate);
constructor Create;
destructor Destroy; override;
end;
implementation
{ TPosting }
uses
AccountingData, IFinanceGlobal, IFinanceDialogs, AppConstants, DBUtil, Ledger;
function TPosting.PostEntry(const refPostingId: string;
const debit, credit: currency; const eventObject, primaryKey, status: string;
const postDate, valueDate: TDateTime; const caseType: string): string;
var
postingId: string;
begin
try
with dmAccounting.dstLedger do
begin
Append;
postingId := GetLedgerId;
FieldByName('posting_id').AsString := postingId;
if refPostingId <> '' then FieldByName('ref_posting_id').AsString := refPostingId;
FieldByName('loc_prefix').AsString := ifn.LocationPrefix;
if debit > 0 then FieldByName('debit_amt').AsCurrency := debit;
if credit > 0 then FieldByName('credit_amt').AsCurrency := credit;
FieldByName('pk_event_object').AsString := primaryKey;
FieldByName('event_object').AsString := eventObject;
FieldByName('status_code').AsString := status;
FieldByName('post_date').AsDateTime := postDate;
FieldByName('value_date').AsDateTime := valueDate;
if caseType <> '' then FieldByName('case_type').AsString := caseType;
Post;
end;
Result := postingId;
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
function TPosting.PostInterest(const interest: currency; const loanId: string;
const ADate: TDateTime; const source, status: string): string;
var
interestId: string;
begin
interestId := GetInterestId;
with dmAccounting.dstInterest do
begin
Append;
FieldByName('interest_id').AsString := interestId;
FieldByName('loan_id').AsString := loanId;
FieldByName('interest_amt').AsCurrency := interest;
FieldByName('interest_date').AsDateTime := ADate;
FieldByName('interest_src').AsString := source;
FieldByName('interest_status_id').AsString := status;
Post;
end;
Result := interestId;
end;
procedure TPosting.PostInterest(const ADate: TDate; const ALoanId: string);
var
refPostingId: string;
interest, credit, balance, interestRate : currency;
eventObject, primaryKey, status, caseType: string;
postDate, valueDate: TDateTime;
begin
refPostingId := '';
credit := 0;
eventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR);
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
postDate := ifn.AppDate;
status := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
// method for posting scheduled interest
dmAccounting := TdmAccounting.Create(nil);
try
try
with dmAccounting do
begin
dstLedger.Open;
dstScheduledInterest.Parameters.ParamByName('@date').Value := ADate;
dstScheduledInterest.Parameters.ParamByName('@loan_id').Value := ALoanId;
dstScheduledInterest.Open;
while not dstScheduledInterest.Eof do
begin
// post the interest in the ledger
primaryKey := dstScheduledInterest.FieldByName('interest_id').AsString;
interestRate := dstScheduledInterest.FieldByName('int_rate').AsCurrency;
balance := dstScheduledInterest.FieldByName('balance').AsCurrency;
interest := RoundTo(balance * (interestRate / 100),-2);
valuedate := dstScheduledInterest.FieldByName('interest_date').AsDateTime;
PostEntry(refPostingId, interest, credit, eventObject, primaryKey, status, postDate, valueDate, caseType);
// change the status and amount of the interest in the Interest table
dstScheduledInterest.Edit;
dstScheduledInterest.FieldByName('interest_amt').AsCurrency := interest;
dstScheduledInterest.FieldByName('interest_status_id').AsString :=
TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.T);
dstScheduledInterest.Post;
dstScheduledInterest.Next;
end;
dstLedger.UpdateBatch;
dstScheduledInterest.UpdateBatch;
end;
except
on E: Exception do
begin
dmAccounting.dstScheduledInterest.CancelBatch;
dmAccounting.dstLedger.CancelBatch;
ShowErrorBox(E.Message);
end;
end;
finally
dmAccounting.dstLedger.Close;
dmAccounting.dstScheduledInterest.Close;
dmAccounting.Free;
end;
end;
procedure TPosting.PostInterest2(const ADate: TDate);
var
refPostingId: string;
interest, credit: currency;
eventObject, primaryKey, caseType, status: string;
interestStatus, interestSource: string;
postDate, valueDate, runningDate: TDateTime;
LLoan: TInterestDebit;
ay, am, ad, ny, nm, nd: word;
days: integer;
begin
// This method is different from the other interest posting method
// Interest is posted on an on-demand basis, when the date arrives .. usually a month from last transaction date
// Previous posting was based from a "schedule" determined during loan release and payment
// This alternate method was developed to fix the February issue
refPostingId := '';
credit := 0;
eventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR);
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
postDate := ifn.AppDate;
status := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
interestStatus := TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.T);
interestSource := TRttiEnumerationType.GetName<TInterestSource>(TInterestSource.SYS);
valueDate := ADate;
LLoan := TInterestDebit.Create;
dmAccounting := TdmAccounting.Create(nil);
try
try
dmAccounting.dstInterest.Open;
dmAccounting.dstLedger.Open;
with dmAccounting.dstInterestDebit do
begin
Parameters.ParamByName('@post_date').Value := ADate;
Open;
while not Eof do
begin
LLoan.Id := FieldByName('loan_id').AsString;
LLoan.InterestRate := FieldByName('int_rate').AsCurrency / 100;
LLoan.ReleaseAmount := FieldByName('rel_amt').AsCurrency;
LLoan.IsDiminishing := FieldByName('int_comp_method').AsString = 'D';
LLoan.IsFixed := FieldByName('int_comp_method').AsString = 'F';
LLoan.DiminishingType := TDiminishingType(FieldByName('dim_type').AsInteger);
LLoan.Balance := FieldByName('balance').AsCurrency;
LLoan.LastTransactionDate := FieldByName('last_trans_date').AsDateTime;
LLoan.AdvancePayments := FieldByName('payments_advance').AsInteger;
LLoan.ReleaseDate := FieldByName('date_rel').AsDateTime;
LLoan.PostDate := ADate;
if LLoan.NextScheduledPosting = ADate then
begin
if LLoan.IsDiminishing then
begin
// note: 1 month is defined is the same day as the previous month..
// ex. 1 month from March 31 is May 1 since April only has 30 days
// although April 30 is 1 month from March 31.. interest is computed on a per day basis as day component is not the same from previous
// in this case.. previous is 31 but following day is 30
// same day means if previous month is 16 then succeeding should be 16 as well
// DecodeDate(LLoan.LastTransactionDate,ay,am,ad);
// DecodeDate(LLoan.NextScheduledPosting,ny,nm,nd);
interest := LLoan.Balance * LLoan.InterestRate
end
else interest := LLoan.ReleaseAmount * LLoan.InterestRate;
interest := RoundTo(interest,-2);
// for DIMINISHING SCHEDULED or FIXED accounts.. use the first day of the month..
{if ((LLoan.IsDiminishing) and (LLoan.DiminishingType = dtScheduled))
or (LLoan.IsFixed) then
primaryKey := PostInterest(interest,LLoan.Id,GetFirstDayOfValueDate(valueDate),interestSource,interestStatus)
else primaryKey := PostInterest(interest,LLoan.Id,valueDate,interestSource,interestStatus); }
primaryKey := PostInterest(interest,LLoan.Id,valueDate,interestSource,interestStatus);
PostEntry(refPostingId, interest, credit, eventObject, primaryKey, status, postDate, valueDate, caseType);
end
else if LLoan.IsFixed then
begin
// for Fixed accounts.. post interest on the following day.. for first month interest only
if IncDay(LLoan.ReleaseDate) = ifn.AppDate then
begin
interest := LLoan.ReleaseAmount * LLoan.InterestRate;
interest := RoundTo(interest,-2);
primaryKey := PostInterest(interest,LLoan.Id,IncDay(LLoan.ReleaseDate),interestSource,interestStatus);
PostEntry(refPostingId, interest, credit, eventObject, primaryKey, status, postDate, valueDate, caseType);
end;
end;
Next;
end;
Close;
end;
dmAccounting.dstInterest.UpdateBatch;
dmAccounting.dstLedger.UpdateBatch;
except
on E: Exception do
begin
dmAccounting.dstInterest.CancelBatch;
dmAccounting.dstLedger.CancelBatch;
ShowErrorBox(E.Message);
Abort;
end;
end;
finally
dmAccounting.dstInterest.Close;
dmAccounting.dstLedger.Close;
LLoan.Free;
dmAccounting.Free;
end;
end;
procedure TPosting.PostPrincipal(const ADate: TDate);
var
refPostingId: string;
principal, interest, balance, credit: currency;
eventObject, primaryKey, caseType, status: string;
postDate, valueDate, runningDate: TDateTime;
i, cnt: integer;
LLoan: TPrincipalDebit;
vy, vm, vd, yy, mm, dd: word;
posted: boolean;
begin
refPostingId := '';
credit := 0;
eventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.LON);
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PRC);
valuedate := GetFirstDayOfValueDate(ADate);
postDate := ifn.AppDate;
status := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
DecodeDate(ADate,yy,mm,dd);
LLoan := TPrincipalDebit.Create;
dmAccounting := TdmAccounting.Create(nil);
try
try
dmAccounting.dstLedger.Open;
with dmAccounting.dstPrincipalDebit do
begin
Parameters.ParamByName('@post_date').Value := ADate;
Open;
LLoan.Id := FieldByName('loan_id').AsString;
LLoan.Term := FieldByName('terms').AsInteger;
LLoan.Amortization := FieldByName('amort').AsCurrency;
LLoan.InterestRate := FieldByName('int_rate').AsCurrency / 100;
LLoan.ReleaseAmount := FieldByName('rel_amt').AsCurrency;
LLoan.IsDiminishing := FieldByName('int_comp_method').AsString = 'D';
LLoan.DiminishingType := TDiminishingType(FieldByName('dim_type').AsInteger);
LLoan.ReleaseDate := FieldByName('date_rel').AsDateTime;
primaryKey := LLoan.Id;
balance := LLoan.ReleaseAmount;
while not Eof do
begin
posted := false;
cnt := LLoan.Term;
i := 1;
// last condition is a hack
while (i <= cnt) and (not posted) do
begin
runningDate := IncMonth(LLoan.ReleaseDate,i);
// interest
if LLoan.isDiminishing then interest := balance * LLoan.InterestRate
else interest := LLoan.ReleaseAmount * LLoan.InterestRate;
// round off to 2 decimal places
interest := RoundTo(interest,-2);
// principal
// use the balance for the last amount to be posted..
// this ensures sum of principal is equal to the loan amount released
if i < cnt then principal := LLoan.Amortization - interest
else principal := balance;
DecodeDate(runningDate,vy,vm,vd);
// for principal entries.. use the first day of the month
if (mm = vm) and (yy = vy) then
begin
PostEntry(refPostingId, principal, credit, eventObject, primaryKey, status,
postDate, valueDate, caseType);
posted := true;
end;
// get balance
balance := balance - principal;
Inc(i);
end;
Next;
end;
Close;
end;
dmAccounting.dstLedger.UpdateBatch;
except
on E: Exception do
begin
dmAccounting.dstLedger.CancelBatch;
ShowErrorBox(E.Message);
Abort;
end;
end;
finally
dmAccounting.dstLedger.Close;
LLoan.Free;
dmAccounting.Free;
end;
end;
procedure TPosting.Post(const ALoan: TLoan);
{ var
refPostingId: string;
principal, interest, balance, credit: currency;
eventObject, primaryKey, status, caseType: string;
postDate, valueDate: TDateTime;
i, cnt: integer;
interestSource: string; }
begin
// Note: This has been discontinued as of 25 June 2018
// Posting of debit will be done on an "on-demand" basis
// That is, will happen on the 1st month for PRINCIPAL and based on last transaction date for INTEREST
// Currently only used by advanced payment.. check below
{
refPostingId := '';
credit := 0;
eventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.LON);
primaryKey := ALoan.Id;
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PRC);
// initialise value date depending on computation method
// check if this is a backlog entry.. use the last transaction day instead
if ALoan.IsBacklog then valueDate := IncDay(ln.LastTransactionDate)
else if ALoan.LoanClass.IsFixed then valueDate := IncDay(ifn.AppDate)
else valuedate := ifn.AppDate;
postDate := ifn.AppDate;
if ln.IsBacklog then balance := ALoan.Balance
else balance := ALoan.ReleaseAmount;
dmAccounting := TdmAccounting.Create(nil);
try
try
with dmAccounting.dstLedger do
begin
Open;
dmAccounting.dstInterest.Parameters.ParamByName('@loan_id').Value := ALoan.Id;
dmAccounting.dstInterest.Open;
// for backlog.. use number of months remaining
if ALoan.IsBacklog then cnt := ALoan.ApprovedTerm - MonthsBetween(ALoan.LastTransactionDate,ALoan.DateApplied)
else cnt := ALoan.ApprovedTerm;
for i := 1 to cnt do
begin
valueDate := GetValueDate(valueDate,IncMonth(ifn.AppDate,i));
// interest
// post in the Interest table instead of in the Ledger
// interest will be posted when the interest date arrives
if ALoan.LoanClass.IsDiminishing then interest := balance * ALoan.LoanClass.InterestInDecimal
else interest := ALoan.ReleaseAmount * ALoan.LoanClass.InterestInDecimal;
// round off to 2 decimal places
interest := RoundTo(interest,-2);
interestSource := TRttiEnumerationType.GetName<TInterestSource>(TInterestSource.SYS);
status := TRttiEnumerationType.GetName<TInterestStatus>(TInterestStatus.P);
// for DIMINISHING SCHEDULED accounts.. use the first day of the month..
if (ALoan.LoanClass.IsDiminishing) and (ALoan.LoanClass.DiminishingType = dtScheduled) then
PostInterest(interest,ALoan.Id,GetFirstDayOfValueDate(valueDate),interestSource,status)
else PostInterest(interest,ALoan.Id,valueDate,interestSource,status);
// principal
// use the balance for the last amount to be posted..
// this ensures sum of principal is equal to the loan amount released
if i < cnt then principal := ALoan.Amortisation - interest
else principal := balance;
status := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
// for principal entries.. use the first day of the month
PostEntry(refPostingId, principal, credit, eventObject, primaryKey, status,
postDate, GetFirstDayOfValueDate(valueDate), caseType);
// get balance
balance := balance - principal;
end;
UpdateBatch;
// commit the interest
dmAccounting.dstInterest.UpdateBatch;
end;
except
on E: Exception do
begin
dmAccounting.dstLedger.CancelBatch;
dmAccounting.dstInterest.CancelBatch;
ShowErrorBox(E.Message);
Abort;
end;
end;
finally
dmAccounting.dstLedger.Close;
dmAccounting.dstInterest.Close;
dmAccounting.Free;
end; }
// post advance payment
if ALoan.LoanClass.HasAdvancePayment then
begin
// increment the date parameter with the number of months
// this ensures interests scheduled for future posting will be posted
PostInterest(IncMonth(ifn.AppDate,ALoan.LoanClass.AdvancePayment.NumberOfMonths),ALoan.Id);
PostAdvancePayment(ALoan);
end;
end;
constructor TPosting.Create;
begin
end;
destructor TPosting.Destroy;
begin
inherited;
end;
function TPosting.GetFirstDayOfValueDate(const ADate: TDateTime): TDateTime;
var
month, day, year: word;
begin
DecodeDate(ADate,year,month,day);
Result := EncodeDate(year,month,1);
end;
function TPosting.GetValueDate(const ADate: TDateTime): TDateTime;
begin
Result := ADate;
end;
function TPosting.GetValueDate(const ACurrentDate, ANextDate: TDateTime): TDateTime;
var
month1, day1, year1: word;
month2, day2, year2: word;
LNextDate: TDateTime;
begin
LNextDate := ANextDate;
DecodeDate(ACurrentDate,year1,month1,day1);
DecodeDate(LNextDate,year2,month2,day2);
// if dates are of the same month.. increment to the next month
if month2 = month1 then
begin
LNextDate := IncMonth(LNextDate);
DecodeDate(LNextDate,year2,month2,day2);
end;
if (month2 = MonthFebruary) and (DaysBetween(LNextDate,ACurrentDate) < ifn.DaysInAMonth)then
Result := IncDay(ACurrentDate,ifn.DaysInAMonth)
// check for leap year
// if (not IsLeapYear(year1)) and (month2 = MonthFebruary) and (day1 = 29) then
// Result := ANextDate
// when day falls on a 31st.. use 30 instead
else if (day1 = 31) and (month2 <> MonthFebruary) then
Result := EncodeDate(year2,month2,30)
else Result := EncodeDate(year2,month2,day1);
end;
function TPosting.MonthsBetweenEx(const ADate1, ADate2: TDateTime): integer;
var
y1, m1, d1, y2, m2, d2: word;
begin
Result := 0;
if ADate1 > ADate2 then Exit;
DecodeDate(ADate1, y1, m1, d1);
DecodeDate(ADate2, y2, m2, d2);
if d1 < d2 then Inc(Result);
Inc(Result, m2 - m1);
if (y2 - y1) > 0 then Inc(Result);
Inc(Result, (y2 - y1) * 12);
Dec(Result);
end;
procedure TPosting.Post(const APayment: TPayment);
var
detail: TPaymentDetail;
i, iCnt, l, lCnt: integer;
LLedger: TLedger;
postingId, refPostingId, status: string;
begin
dmAccounting := TdmAccounting.Create(nil);
try
try
with dmAccounting.dstSchedule do
begin
dmAccounting.dstLedger.Open;
dmAccounting.dstSchedule.Parameters.ParamByName('@entity_id').Value := APayment.Client.Id;
dmAccounting.dstSchedule.Open;
iCnt := APayment.DetailCount - 1;
for i := 0 to iCnt do
begin
detail := APayment.Details[i];
lCnt := detail.Loan.LedgerCount - 1;
for l := 0 to lCnt do
begin
LLedger := detail.Loan.Ledger[l];
if LLedger.Posted then
begin
if LLedger.StatusChanged then
if Locate('posting_id',LLedger.PostingId,[]) then
begin
Edit;
FieldByName('status_code').AsString := LLedger.NewStatus;
Post;
end;
end
else
begin
if (not LLedger.FullPayment) or ((LLedger.FullPayment) and (detail.IsFullPayment)) then
begin
// set the refposting id
// this is only called for unscheduled posting
if LLedger.UnreferencedPayment then LLedger.RefPostingId := refPostingId;
if LLedger.StatusChanged then status := LLedger.NewStatus
else status := LLedger.CurrentStatus;
postingId := PostEntry(LLedger.RefPostingId,LLedger.Debit,LLedger.Credit,
LLedger.EventObject,LLedger.PrimaryKey,status,
ifn.AppDate,LLedger.ValueDate,LLedger.CaseType);
if (LLedger.EventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.ITR))
and (LLedger.CaseType = TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS))then
refPostingId := postingId;
end;
end;
end;
end;
UpdateBatch;
dmAccounting.dstLedger.UpdateBatch;
end;
except
on E: Exception do
begin
dmAccounting.dstSchedule.CancelBatch;
dmAccounting.dstLedger.CancelBatch;
ShowErrorBox(E.Message);
end;
end;
finally
dmAccounting.dstSchedule.Close;
dmAccounting.dstLedger.Close;
dmAccounting.Free;
end;
end;
procedure TPosting.PostAdvancePayment(ALoan: TLoan);
var
id, refNo: string;
adv: TAdvancePayment;
i, k: integer;
LLedger: array of TLedger;
debitLedger, creditLedger: TLedger;
caseType: string;
paymentType: TPaymentTypes;
payment, balance: currency;
procedure RetrieveLedger;
var
ldg: TLedger;
l: integer;
begin
try
// loop thru the dataset
with dmAccounting.dstScheduleAdvance do
begin
try
Parameters.ParamByName('@loan_id').Value := ALoan.Id;
Open;
SetLength(LLedger,RecordCount);
l := 0;
while not Eof do
begin
ldg := TLedger.Create;
ldg.PostingId := FieldByName('posting_id').AsString;
ldg.EventObject := FieldByName('event_object').AsString;
ldg.PrimaryKey := FieldByName('pk_event_object').AsString;
ldg.ValueDate := FieldByName('value_date').AsDateTime;
ldg.Debit := FieldByName('payment_due').AsSingle;
ldg.CaseType := FieldByName('case_type').AsString;
ldg.CurrentStatus := FieldByName('status_code').AsString;
ldg.HasPartial := FieldByName('has_partial').AsInteger = 1;
LLedger[l] := ldg;
Inc(l);
Next;
end;
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
finally
dmAccounting.dstScheduleAdvance.Close;
end;
end;
begin
// this method is only called for advance payment
// advance payment can only happen during loan release
dmAccounting := TdmAccounting.Create(nil);
dmAccounting.dstPayment.Open;
dmAccounting.dstPaymentDetail.Open;
dmAccounting.dstLedger.Open;
RetrieveLedger;
creditLedger := TLedger.Create;
try
try
for i:= 0 to ALoan.LoanClass.AdvancePayment.NumberOfMonths - 1 do
begin
adv := ALoan.AdvancePayment[i];
// master
with dmAccounting.dstPayment do
begin
Open;
id := GetPaymentId;
refNo := FormatDateTime('mmddyyyyhhmmsszzz',Now);
Append;
FieldByName('payment_id').AsString := id;
FieldByName('payment_date').AsDateTime := ifn.AppDate;
FieldByName('entity_id').AsString := ALoan.Client.Id;
FieldByName('loc_code').AsString := ifn.LocationCode;
FieldByName('ref_no').AsString := refNo;
FieldByName('pmt_method').AsInteger := Integer(mdCash);
FieldByName('post_date').AsDateTime := Now;
FieldByName('is_advance').AsBoolean := true;
SetCreatedFields(dmAccounting.dstPayment);
end;
// detail
with dmAccounting.dstPaymentDetail do
begin
for paymentType := TPaymentTypes.PRN to TPaymentTypes.PEN do
begin
// get the amount and casetype to be posted
case paymentType of
PRN:
begin
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.PRC);
payment := adv.Principal;
balance := adv.Balance;
end;
INT:
begin
caseType := TRttiEnumerationType.GetName<TCaseTypes>(TCaseTypes.ITS);
payment := adv.Interest;
balance := adv.Interest;
end;
PEN: Continue;
end;
// some loan class only require interest for advance payment
// check the amount prior to posting.. ignore when ZERO
if payment = 0 then Continue;
Append;
FieldByName('payment_id').AsString := id;
FieldByName('loan_id').AsString := ALoan.id;
FieldByName('payment_amt').AsCurrency := payment;
FieldByName('payment_type').AsString := TRttiEnumerationType.GetName<TPaymentTypes>(paymentType);
if paymentType = INT then FieldByName('balance').AsCurrency := 0 - balance
else FieldByName('balance').AsCurrency := balance;
Post;
// increment "k" variable until case type is found
k := 0;
debitLedger := LLedger[k];
while (debitLedger.CaseType <> caseType) or (debitLedger.StatusChanged) do
begin
Inc(k);
debitLedger := LLedger[k];
end;
creditLedger.Credit := debitLedger.Debit;
debitLedger.NewStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.CLS);
creditLedger.RefPostingId := debitLedger.PostingId;
creditLedger.EventObject := TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.PAY);
creditLedger.PrimaryKey := id;
creditLedger.CaseType := caseType;
creditLedger.ValueDate := ifn.AppDate;
creditLedger.CurrentStatus := TRttiEnumerationType.GetName<TLedgerRecordStatus>(TLedgerRecordStatus.OPN);
creditLedger.Debit := 0;
// post the entry
with creditLedger do
PostEntry(RefPostingId,0,Credit,EventObject,PrimaryKey,CurrentStatus,ValueDate,ValueDate,CaseType);
// update the status of the debit entry
end;
end;
end;
dmAccounting.dstPayment.UpdateBatch;
dmAccounting.dstPaymentDetail.UpdateBatch;
dmAccounting.dstLedger.UpdateBatch;
except
on E: Exception do
begin
dmAccounting.dstPayment.CancelBatch;
dmAccounting.dstPaymentDetail.CancelBatch;
dmAccounting.dstLedger.CancelBatch;
ShowErrorBox(E.Message);
end;
end;
finally
dmAccounting.dstPayment.Close;
dmAccounting.dstPaymentDetail.Close;
dmAccounting.dstLedger.Close;
dmAccounting.Free;
if Assigned(adv) then adv.Free;
if Assigned(debitLedger) then debitLedger.Free;
if Assigned(creditLedger) then creditLedger.Free;
end;
end;
{ TInterestDebit }
function TInterestDebit.GetHasAdvancePayments: boolean;
begin
Result := FAdvancePayments > 0;
end;
function TInterestDebit.GetNextScheduledPosting: TDateTime;
var
LNextSchedule: TDateTime;
mm, dd, yy, cm, cd, cy: word;
begin
if HasAdvancePayments then
LNextSchedule := IncMonth(FLastTransactionDate,FAdvancepayments)
else
begin
if (FIsFixed) and (IncDay(FReleaseDate) = FPostDate) then LNextSchedule := FPostDate
else
begin
LNextSchedule := IncMonth(FLastTransactionDate);
DecodeDate(FLastTransactionDate,cy,cm,cd);
DecodeDate(LNextSchedule,yy,mm,dd);
if cd <> dd then
begin
if (DaysBetween(LNextSchedule,FLastTransactionDate) < ifn.DaysInAMonth)
or (cd = 31) then
LNextSchedule := IncDay(LNextSchedule);
end;
end;
end;
Result := LNextSchedule;
end;
end.
|
(*
Name: ValidateKeymanInstalledSystemKeyboards
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 13 Jul 2007
Modified Date: 1 Dec 2012
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 13 Jul 2007 - mcdurdin - I838 - Initial version
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
26 Jun 2012 - mcdurdin - I3377 - KM9 - Update code references from 8.0 to 9.0
01 Dec 2012 - mcdurdin - I3613 - V9.0 - System shadow keyboards obsolete, strip out remaining code
01 Dec 2012 - mcdurdin - I3613 - V9.0 - System shadow keyboards obsolete, strip out remaining code
*)
unit ValidateKeymanInstalledSystemKeyboards;
interface
procedure DeleteLegacyKeymanInstalledSystemKeyboards; // I3613
implementation
uses
Windows,
Classes,
ErrorControlledRegistry,
KeymanVersion,
RegistryKeys,
SysUtils;
procedure DeleteLegacyKeymanInstalledSystemKeyboards; // I3613
var
Keys: TStringList;
I: Integer;
begin
Keys := TStringList.Create;
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_LOCAL_MACHINE;
if not OpenKey(SRegKey_KeyboardLayouts, true) then Exit;
GetKeyNames(Keys);
for I := 0 to Keys.Count - 1 do
if SameText(Copy(Keys[i], 6, 3), '5FE') and
OpenKey('\'+SRegKey_KeyboardLayouts+'\'+Keys[i], True) and
ValueExists(SRegValue_Legacy_KeyboardKeymanInstall) then
begin
if OpenKey('\'+SRegKey_KeyboardLayouts, True) then // I2890
DeleteKey(Keys[i]);
end;
finally
Free;
Keys.Free;
end;
end;
end.
|
unit Threads.SQLExecuter;
interface
uses Windows, SysUtils, Classes, Threads.Base, GMGlobals, GMConst, Math;
const QUERY_PACK_SIZE = 50;
type
TSQLExecuteThread = class(TGMThread)
private
FSQL: TStringList;
FSynch: TMultiReadExclusiveWriteSynchronizer;
function AddSemicolonAndCRLF(const s: string): string;
function GetSqlRange(n: int): string;
function DelSqlRange(start, count: int): string;
protected
property Synch: TMultiReadExclusiveWriteSynchronizer read FSynch;
procedure SafeExecute(); override;
procedure SafeExecute_ExtraStep; virtual;
function GetCount: int; virtual;
public
constructor Create();
destructor Destroy; override;
procedure Add(const s: string);
procedure AddList(sl: TStrings);
property Count: int read GetCount;
end;
implementation
{ TSQLExecuteThread }
uses GMSqlQuery, Winapi.ActiveX;
procedure TSQLExecuteThread.Add(const s: string);
begin
if Terminated then Exit;
FSynch.BeginWrite();
try
FSQL.Add(s);
finally
FSynch.EndWrite();
end;
end;
procedure TSQLExecuteThread.AddList(sl: TStrings);
begin
if Terminated then Exit;
FSynch.BeginWrite();
try
FSQL.AddStrings(sl);
finally
FSynch.EndWrite();
end;
end;
constructor TSQLExecuteThread.Create;
begin
inherited Create();
FSQL := TStringList.Create();
FSynch := TMultiReadExclusiveWriteSynchronizer.Create();
end;
destructor TSQLExecuteThread.Destroy;
begin
inherited;
try
if FSQL.Count > 0 then
FSQL.SaveToFile('sql_' + IntToStr(NowGM()) + '.sql');
except end;
FSQL.Free();
FSynch.Free();
end;
function TSQLExecuteThread.GetCount: int;
begin
FSynch.BeginRead();
try
Result := FSQL.Count;
finally
FSynch.EndRead();
end;
end;
function TSQLExecuteThread.AddSemicolonAndCRLF(const s: string): string;
begin
Result := s;
while (Result <> '') and (CharInSet(Result[Result.Length], [#13, #10, ';', ' '])) do
Delete(Result, Result.Length, 1);
Result := Result + ';'#13#10;
end;
procedure TSQLExecuteThread.SafeExecute_ExtraStep;
begin
end;
function TSQLExecuteThread.GetSqlRange(n: int): string;
var
i: int;
begin
Result := '';
FSynch.BeginRead();
try
for i := 0 to n - 1 do
Result := Result + AddSemicolonAndCRLF(FSQL[i]);
finally
FSynch.EndRead();
end;
end;
function TSQLExecuteThread.DelSqlRange(start, count: int): string;
var
i: int;
begin
FSynch.BeginWrite();
try
for i := start to start + count - 1 do
begin
if FSQL.Count = 0 then Exit;
FSQL.Delete(0);
end;
finally
FSynch.EndWrite();
end;
end;
procedure TSQLExecuteThread.SafeExecute;
var
sql: string;
n: int;
begin
CoInitialize(nil);
while not Terminated do
begin
SafeExecute_ExtraStep();
if FSQL.Count = 0 then
begin
SleepThread(100);
continue;
end;
n := Min(QUERY_PACK_SIZE, FSQL.Count);
sql := GetSqlRange(n);
try
ExecPLSQL(sql);
except
SaveStringToFile(sql, 'sqlerr_' + IntToStr(NowGM()) + '.sql');
end;
DelSqlRange(0, n);
end;
end;
end.
|
unit MetroFiler;
interface
uses
Classes, IniFiles, Graphics,
MetroBase, MetroVisCom;
type
//----------------------------------------------------------------------------
// TMetroFiler is a class with some helper routines for reading/writing
// a network and map from/to a .nwk file
//----------------------------------------------------------------------------
TMetroFiler =
class(TObject)
protected
FFileName: String;
FIniFile: TMemIniFile;
FNetworkName: String;
FFileSections: TStringList;
// auxiliary methods
public
// construction/Destruction
constructor Create(const AfileName: string);
destructor Destroy; override;
function LoadNetwork: TNetwork;
procedure WriteMapAndNetwork(AMap: TMetroMap; ANetwork: TNetwork);
function LoadMap: TMetroMap;
end;
implementation
uses
SysUtils, StrUtils,
Auxiliary;
{ TMetroFiler }
constructor TMetroFiler.Create(const AfileName: string);
begin
inherited Create;
FIniFile := TMemIniFile.Create(AFileName);
FNetworkName := FIniFile.ReadString('#Main', 'name', '???');
FFileSections := TStringList.Create;
FIniFile.ReadSections(FFileSections);
end;
destructor TMetroFiler.Destroy;
begin
FFileSections.Free;
FIniFile.Free;
inherited;
end;
function TMetroFiler.LoadMap: TMetroMap;
var
VMap: TMetroMap;
VBlankPicture, VBackgroundPicture: TBitmap;
VBackgroundName, VBackgroundFilename: String;
procedure ReadLines;
var
I, J, M: Integer;
VSectionName: String;
VLineName, VLineCode: String;
VLineColorName: String;
VLineColor: TColor;
VStation: TVisStation;
VLine: TVisLine;
VStopCode: String;
VStops: TStringList;
VLeft, VRight: String;
VX, VY: Integer;
begin
// filter out line sections (beginning with 'L_') and read their attributes
// and corresponding station lists
for I := 0 to FFileSections.Count - 1 do
begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('L_', VSectionName) then
begin
VLineCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
// read line name
VLineName := FIniFile.ReadString(VSectionName, 'name', '????');
// read line color
VLineColorName :=
FIniFile.ReadString(VSectionName, 'color', 'clBlack');
VLineColor := ColorNameToColor(VLineColorName);
// create line (with empty stationlist)
VLine := TVisLine.Create(VLineCode, nil, VLineColor);
// read stops from corresponding 'P_' section and and them to line
VStops := TStringList.Create;
FIniFile.ReadSectionValues('P_' + VLineCode, VStops);
for J := 0 to VStops.Count - 1 do
begin
VStopCode := VStops.Strings[J];
if ValidStationCode(VStopCode) then
begin
VStation := VMap.GetStation(VStopCode);
VLine.Add(VStation);
end
else
begin
// VStopCode should be of the form nnnn,nnnn ;
M := Pos(',', VStopCode);
if M <> 0 then
begin
VLeft := LeftStr(VStopCode, M - 1);
VRight := RightStr(VStopCode, Length(VStopCode) - M);
VX := StrToIntDef(VLeft, -1);
VY := StrToIntDef(VRight, -1);
if (VX <> -1) and (VX <> -1)
then VLine.Add(TVisStationDummy.Create(VX, VY))
else Assert(false,
'Ill-formed coordinates in TMetroFiler.Readlines: ' + VStopCode);
end;
end;
end{for J};
VMap.Add(VLine);
VStops.Free;
end{if};
end{for I};
end;
procedure ReadStations;
var
I: Integer;
VSectionName: String;
VStationName, VStationCode: String;
VStationKind: String;
VX, VY: Integer;
begin
// filter out station sections (beginning with 'S_') and read their name
for I := 0 to FFileSections.Count - 1 do
begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('S_', VSectionName) then
begin
VStationCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VStationName := FIniFile.ReadString(VSectionName, 'name', '???????');
VStationKind := FIniFile.ReadString(VSectionName, 'kind', '???');
VX := FIniFile.ReadInteger(VSectionName, 'x', -1);
VY := FIniFile.ReadInteger(VSectionName, 'y', -1);
if (VX <> -1) and (VY <> -1) then
begin
if VStationKind = 'stop'
then VMap.Add(TVisStationStop.Create(VStationCode, nil, VX, VY))
else if VStationKind = 'transfer'
then VMap.Add(TVisStationTransfer.Create(VStationCode, nil, VX, VY))
else Assert(false, 'Unknown station kind in TMetroFiler.LoadMap');
end{if};
end{if};
end{for};
end;
procedure ReadLandmarks;
var
I: Integer;
VSectionName: String;
VLandmarkCode: String;
VBitMapName: String;
VBitmapFileName: String;
VBitmap: TBitmap;
VX, VY: Integer;
begin
// filter out landmark sections (beginning with 'M_') and read their props
for I := 0 to FFileSections.Count - 1 do
begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('M_', VSectionName) then
begin
VLandmarkCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VBitmapName := FIniFile.ReadString(VSectionName, 'bitmap', '???');
VX := FIniFile.ReadInteger(VSectionName, 'x', -1);
VY := FIniFile.ReadInteger(VSectionName, 'y', -1);
if (VX <> -1) and (VY <> -1) and (VBitmapName <> '???') then
begin
VBitmap := TBitmap.Create;
VBitmapFileName :=
Format('../Images/Landmarks/%s.bmp', [VBitmapName]);
VBitmap.LoadFromFile(VBitmapFileName);
VMap.Add(TVisLandmark.Create(VLandmarkCode, nil, VX, VY, VBitmap))
end{if};
end{if};
end{for};
end;
procedure ReadTexts;
begin
end;
begin{Loadmap}
// Load blank picture
VBlankPicture := TBitmap.Create;
VBlankPicture.LoadFromFile('../Images/Backgrounds/blank.bmp');
// Load background picture
VBackgroundName := FIniFile.ReadString('#Main', 'background', 'blank');
VBackgroundFileName :=
Format('../Images/Backgrounds/%s.bmp', [VBackgroundName]);
VBackgroundPicture := TBitmap.Create;
VBackgroundPicture.LoadFromFile(VBackgroundFileName);
VMap := TMetroMap.Create(nil, VBlankPicture, VBackgroundPicture);
ReadStations;
ReadLines;
ReadLandmarks;
ReadTexts;
Result := VMap;
end{LoadMap};
function TMetroFiler.LoadNetwork: TNetwork;
var
VNetwork: TNetwork;
procedure ReadStations;
var
I: Integer;
VSectionName: String;
VStationName, VStationCode: String;
begin
// filter out station sections (beginning with 'S_') and read their name
for I := 0 to FFileSections.Count - 1 do
begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('S_', VSectionName) then
begin
VStationCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VStationName := FIniFile.ReadString(VSectionName, 'name', '???????');
VNetwork.AddStation(VStationCode, VStationName);
end{if};
end{for};
end;
procedure Readlines;
var
I, J, H: Integer;
VSectionName: String;
VLineName, VLineCode: String;
VLine: TLineRW;
VOneWay: Boolean;
VCircular: Boolean;
VLineOptions: TLineOptionS;
VStopCode: String;
VStop: TStationR;
VStops: TStringList;
begin
// filter out line sections (beginning with 'L_') and read their attributes
// and corresponding station lists
for I := 0 to FFileSections.Count - 1 do
begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('L_', VSectionName) then
begin
VLineCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
// read line name
VLineName := FIniFile.ReadString(VSectionName, 'name', '????');
// read line options
VLineOptions := [];
VOneWay := FIniFile.ReadBool(VSectionName, 'oneway', false);
if VOneWay then VLineOptions := VLineOptions + [loOneWay];
VCircular := FIniFile.ReadBool(VSectionName, 'circular', false);
if VCircular then VLineOptions := VLineOptions + [loCircular];
// create line (with empty stationlist)
VLine := TLineRW.Create(VLineCode, VLineName, VLineOptions);
// read stops from corresponding 'P_' section and and them to line
VStops := TStringList.Create;
FIniFile.ReadSectionValues('P_' + VLineCode, VStops);
for J := 0 to VStops.Count - 1 do
begin
VStopCode := VStops.Strings[J];
if ValidStationCode(VStopCode) then
with VNetwork.GetStationSet do
begin
H := IndexOfCode(VStopCode);
Assert( H <> -1,
Format('TMetroFiler.Readlines: Unknown stop code: %s',
[VStopCode]));
VStop := GetStation(H);
VLine.AddStop(VStop);
end
else
{skip};
end{for J};
VNetwork.AddLine(VLine);
VStops.Free;
end{if};
end{for I};
end;
begin{Loadnetwork}
VNetwork := TNetwork.CreateEmpty(FNetworkName);
ReadStations;
ReadLines;
Result := VNetwork;
end{LoadNetwork};
procedure TMetroFiler.WriteMapAndNetwork(AMap: TMetroMap;
ANetwork: TNetwork);
begin
Assert(false, 'TMetroFiler.WriteMapAndNetwork not yet implemented');
end;
end.
|
unit MainFORM;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
GhostscriptApi, Vcl.ComCtrls;
type
TfrmMain = class(TForm)
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
pnlInfo: TPanel;
Memo1: TMemo;
pnlMain: TPanel;
pnlVersion: TPanel;
lblVersion: TLabel;
btnBrowseInput: TButton;
btnBrowseOutput: TButton;
edtOutputFilename: TEdit;
edtInputFilename: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
cbConversionMethod: TComboBox;
Label4: TLabel;
btnConvert: TButton;
meStdIO: TMemo;
procedure FormCreate(Sender: TObject);
procedure btnBrowseInputClick(Sender: TObject);
procedure btnBrowseOutputClick(Sender: TObject);
procedure btnConvertClick(Sender: TObject);
private
{ Private declarations }
// function stdin(caller_handle: Pointer; buf: PAnsichar; len: Integer): Integer;
// function stdout(caller_handle: Pointer; buf: PAnsichar; len: Integer): Integer;
//function stderr(caller_handle: Pointer; buf: PAnsichar; len: Integer): Integer;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
function stderr(caller_handle: Pointer; buf: PAnsichar;
len: Integer): Integer; stdcall;
begin
frmMain.meStdIO.Lines.Text :=
frmMain.meStdIO.Lines.Text +
StringReplace(Copy(buf, 1, len), #10, #13#10, [rfReplaceAll, rfIgnoreCase]);
Result := len;
end;
function stdin(caller_handle: Pointer; buf: PAnsichar;
len: Integer): Integer; stdcall;
begin
frmMain.meStdIO.Lines.Text :=
frmMain.meStdIO.Lines.Text +
StringReplace(Copy(buf, 1, len), #10, #13#10, [rfReplaceAll, rfIgnoreCase]);
Result := len;
end;
function stdout(caller_handle: Pointer; buf: PAnsichar;
len: Integer): Integer; stdcall;
begin
frmMain.meStdIO.Lines.Text :=
frmMain.meStdIO.Lines.Text +
StringReplace(Copy(buf, 1, len), #10, #13#10, [rfReplaceAll, rfIgnoreCase]);
Result := len;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
gsVersion: TGSAPI_Revision_S;
begin
pnlMain.Enabled := LoadGSDLL;
if IsGSDLLLoaded then
begin
GSAPI_Revision(gsVersion, 16);
lblVersion.Caption := gsVersion.product + #13#10 +
gsVersion.copyright + #13#10 +
IntToStr(gsVersion.revision) + ' / ' +
IntToStr(gsVersion.revisiondate);
end;
end;
procedure TfrmMain.btnBrowseInputClick(Sender: TObject);
begin
if dlgOpen.Execute then
begin
edtInputFilename.Text := dlgOpen.FileName;
edtOutputFilename.Text := ChangeFileExt(edtInputFilename.Text, '.tif');
end;
end;
procedure TfrmMain.btnBrowseOutputClick(Sender: TObject);
begin
if dlgSave.Execute then
begin
edtOutputFilename.Text := dlgSave.FileName;
end;
end;
procedure TfrmMain.btnConvertClick(Sender: TObject);
var
gsInstance: Pointer;
apiResult, I: Integer;
argv: array of PAnsiChar;
slargv: TStringList;
begin
if (edtInputFilename.Text = '') or (edtOutputFilename.Text = '') then
Exit;
if GSAPI_New_Instance(gsInstance, nil) = 0 then
begin
GSAPI_Set_Stdio(gsInstance, @stdin, @stdout, @stderr);
apiResult := GSAPI_Set_Arg_Encoding(gsInstance, GS_ARG_ENCODING_UTF8);
if apiResult = 0 then
begin
SetLength(argv, 9);
argv[0] := '-q';
argv[1] := '-dNOPAUSE';
argv[2] := '-dBATCH';
argv[3] := PAnsiChar(AnsiString('-sDEVICE=' + cbConversionMethod.Text));
argv[4] := '-r300x300';
argv[5] := '-dPDFFitPage';
argv[6] := '-sPAPERSIZE=a4';
argv[7] := PAnsiChar(AnsiString('-sOutputFile=' + edtOutputFilename.Text));
argv[8] := PAnsiChar(AnsiString(edtInputFilename.Text));
apiResult := GSAPI_Init_With_Args(gsInstance, Length(argv), @argv[0]);
if apiResult <> 0 then
ShowMessage('GSAPI_Init_With_Args returned with error: ' + IntToStr(apiResult));
GSAPI_Exit(gsInstance);
end else
begin
ShowMessage('GSAPI_Set_Arg_Encoding returned with error: ' + IntToStr(apiResult));
end;
GSAPI_Delete_Instance(gsInstance);
end else
begin
ShowMessage('GSAPI_New_Instance returned with error: ' + IntToStr(apiResult));
end;
end;
end.
|
(*
* Copyright(c) 2019 Embarcadero Technologies, Inc.
*
* This code was generated by the TaskGen tool from file
* "CommonOptionsTask.xml"
* Version: 26.0.0.0
* Runtime Version: v4.0.30319
* Changes to this file may cause incorrect behavior and will be
* overwritten when the code is regenerated.
*)
unit CommonOptionStrs;
interface
const
sTaskName = 'commonoptions';
// PathsAndDefines
sDefines = 'Defines';
sIncludePath = 'IncludePath';
sFinalOutputDir = 'FinalOutputDir';
sIntermediateOutputDir = 'IntermediateOutputDir';
// MiscInternalOptions
sShowGeneralMessages = 'ShowGeneralMessages';
sIndexFiles = 'IndexFiles';
// CommonPackageOpts
sPackageImports = 'PackageImports';
sAllPackageLibs = 'AllPackageLibs';
sPackageLibs = 'PackageLibs';
sDesignOnlyPackage = 'DesignOnlyPackage';
sRuntimeOnlyPackage = 'RuntimeOnlyPackage';
// DelphiInternalOptions
sGenPackage = 'GenPackage';
sGenDll = 'GenDll';
sUsePackages = 'UsePackages';
sHasTypeLib = 'HasTypeLib';
sAutoGenImportAssembly = 'AutoGenImportAssembly';
sAutoRegisterTLB = 'AutoRegisterTLB';
sImageDebugInfo = 'ImageDebugInfo';
sDebugSourcePath = 'DebugSourcePath';
// OutputFilenameModifiers
sOutputExt = 'OutputExt';
sOutputName = 'OutputName';
sDllPrefixDefined = 'DllPrefixDefined';
sDllPrefix = 'DllPrefix';
sDllVersion = 'DllVersion';
sDllSuffix = 'DllSuffix';
// C++InternalOptions
sMultithreaded = 'Multithreaded';
sDynamicRTL = 'DynamicRTL';
sUsingDelphiRTL = 'UsingDelphiRTL';
sLinkCodeGuard = 'LinkCodeGuard';
sRunBCCOutOfProcess = 'RunBCCOutOfProcess';
sSubProcessesNumber = 'SubProcessesNumber';
// WindowsVersionInformation
sVerInfo_IncludeVerInfo = 'VerInfo_IncludeVerInfo';
sVerInfo_MajorVer = 'VerInfo_MajorVer';
sVerInfo_MinorVer = 'VerInfo_MinorVer';
sVerInfo_Release = 'VerInfo_Release';
sVerInfo_Build = 'VerInfo_Build';
sVerInfo_Debug = 'VerInfo_Debug';
sVerInfo_PreRelease = 'VerInfo_PreRelease';
sVerInfo_Special = 'VerInfo_Special';
sVerInfo_Private = 'VerInfo_Private';
sVerInfo_DLL = 'VerInfo_DLL';
sVerInfo_Locale = 'VerInfo_Locale';
sVerInfo_CodePage = 'VerInfo_CodePage';
sVerInfo_CompanyName = 'VerInfo_CompanyName';
sVerInfo_FileDescription = 'VerInfo_FileDescription';
sVerInfo_FileVersion = 'VerInfo_FileVersion';
sVerInfo_InternalName = 'VerInfo_InternalName';
sVerInfo_LegalCopyright = 'VerInfo_LegalCopyright';
sVerInfo_LegalTrademarks = 'VerInfo_LegalTrademarks';
sVerInfo_OriginalFilename = 'VerInfo_OriginalFilename';
sVerInfo_ProductName = 'VerInfo_ProductName';
sVerInfo_ProductVersion = 'VerInfo_ProductVersion';
sVerInfo_Comments = 'VerInfo_Comments';
sVerInfo_ProgramID = 'VerInfo_ProgramID';
sVerInfo_Keys = 'VerInfo_Keys';
sVerInfo_AutoGenVersion = 'VerInfo_AutoGenVersion';
sVerInfo_AutoIncVersion = 'VerInfo_AutoIncVersion';
sVerInfo_BundleId = 'VerInfo_BundleId';
sVerInfo_UIDeviceFamily = 'VerInfo_UIDeviceFamily';
sIcon_MainIcon = 'Icon_MainIcon';
sIcns_MainIcns = 'Icns_MainIcns';
sManifest_File = 'Manifest_File';
sAppEnableRuntimeThemes = 'AppEnableRuntimeThemes';
sAppEnableHighDPI = 'AppEnableHighDPI';
sAppDPIAwarenessMode = 'AppDPIAwarenessMode';
sAppEnableAdministrator = 'AppEnableAdministrator';
sAppExecutionLevel = 'AppExecutionLevel';
sAppExecutionLevelUIAccess = 'AppExecutionLevelUIAccess';
sCustom_Styles = 'Custom_Styles';
// DebuggerProjectOptions
sDebugger_RunParams = 'Debugger_RunParams';
sDebugger_RemoteRunParams = 'Debugger_RemoteRunParams';
sDebugger_HostApplication = 'Debugger_HostApplication';
sDebugger_RemotePath = 'Debugger_RemotePath';
sDebugger_RemoteHost = 'Debugger_RemoteHost';
sDebugger_EnvVars = 'Debugger_EnvVars';
sDebugger_SymTabs = 'Debugger_SymTabs';
sDebugger_Launcher = 'Debugger_Launcher';
sDebugger_RemoteLauncher = 'Debugger_RemoteLauncher';
sDebugger_IncludeSystemVars = 'Debugger_IncludeSystemVars';
sDebugger_UseLauncher = 'Debugger_UseLauncher';
sDebugger_UseRemoteLauncher = 'Debugger_UseRemoteLauncher';
sDebugger_CWD = 'Debugger_CWD';
sDebugger_RemoteCWD = 'Debugger_RemoteCWD';
sDebugger_RemoteDebug = 'Debugger_RemoteDebug';
sDebugger_DebugSourcePath = 'Debugger_DebugSourcePath';
sDebugger_LoadAllSymbols = 'Debugger_LoadAllSymbols';
sDebugger_LoadUnspecifiedSymbols = 'Debugger_LoadUnspecifiedSymbols';
sDebugger_SymbolSourcePath = 'Debugger_SymbolSourcePath';
// BuildEvents
sPreBuildEvent = 'PreBuildEvent';
sPreBuildEventCancelOnError = 'PreBuildEventCancelOnError';
sPreLinkEvent = 'PreLinkEvent';
sPreLinkEventCancelOnError = 'PreLinkEventCancelOnError';
sPostBuildEvent = 'PostBuildEvent';
sPostBuildEventExecuteWhen = 'PostBuildEventExecuteWhen';
sPostBuildEventExecuteWhen_Always = 'Always';
sPostBuildEventExecuteWhen_TargetOutOfDate = 'TargetOutOfDate';
sPostBuildEventCancelOnError = 'PostBuildEventCancelOnError';
// BuildTypeProperties
sPF_AutoMobileProvisionDebug = 'PF_AutoMobileProvisionDebug';
sENV_PF_AutoMobileProvisionDebug = 'ENV_PF_AutoMobileProvisionDebug';
sPF_AutoCertificateDebug = 'PF_AutoCertificateDebug';
sENV_PF_AutoCertificateDebug = 'ENV_PF_AutoCertificateDebug';
sPF_MobileProvisionDebug = 'PF_MobileProvisionDebug';
sENV_PF_MobileProvisionDebug = 'ENV_PF_MobileProvisionDebug';
sPF_MobileProvisionPathDebug = 'PF_MobileProvisionPathDebug';
sENV_PF_MobileProvisionPathDebug = 'ENV_PF_MobileProvisionPathDebug';
sPF_EntitlementExtraKeyValuesDebug = 'PF_EntitlementExtraKeyValuesDebug';
sENV_PF_EntitlementExtraKeyValuesDebug = 'ENV_PF_EntitlementExtraKeyValuesDebug';
sPF_KeyChainAccessDebug = 'PF_KeyChainAccessDebug';
sENV_PF_KeyChainAccessDebug = 'ENV_PF_KeyChainAccessDebug';
sPF_AppIdentifierDebug = 'PF_AppIdentifierDebug';
sENV_PF_AppIdentifierDebug = 'ENV_PF_AppIdentifierDebug';
sPF_CFBundleIdentifierDebug = 'PF_CFBundleIdentifierDebug';
sENV_PF_CFBundleIdentifierDebug = 'ENV_PF_CFBundleIdentifierDebug';
sPF_DevDebug = 'PF_DevDebug';
sENV_PF_DevDebug = 'ENV_PF_DevDebug';
sPF_DevTeamIdDebug = 'PF_DevTeamIdDebug';
sENV_PF_DevTeamIdDebug = 'ENV_PF_DevTeamIdDebug';
sPF_AutoMobileProvisionAdHoc = 'PF_AutoMobileProvisionAdHoc';
sENV_PF_AutoMobileProvisionAdHoc = 'ENV_PF_AutoMobileProvisionAdHoc';
sPF_AutoCertificateAdHoc = 'PF_AutoCertificateAdHoc';
sENV_PF_AutoCertificateAdHoc = 'ENV_PF_AutoCertificateAdHoc';
sENV_PF_InstallAppOnDeviceAdHoc = 'ENV_PF_InstallAppOnDeviceAdHoc';
sPF_AdHoc = 'PF_AdHoc';
sENV_PF_AdHoc = 'ENV_PF_AdHoc';
sPF_CFBundleIdentifierAdHoc = 'PF_CFBundleIdentifierAdHoc';
sENV_PF_CFBundleIdentifierAdHoc = 'ENV_PF_CFBundleIdentifierAdHoc';
sPF_EntitlementExtraKeyValuesAdhoc = 'PF_EntitlementExtraKeyValuesAdhoc';
sENV_PF_EntitlementExtraKeyValuesAdhoc = 'ENV_PF_EntitlementExtraKeyValuesAdhoc';
sPF_MobileProvisionAdHoc = 'PF_MobileProvisionAdHoc';
sENV_PF_MobileProvisionAdHoc = 'ENV_PF_MobileProvisionAdHoc';
sPF_DevAdHoc = 'PF_DevAdHoc';
sENV_PF_DevAdHoc = 'ENV_PF_DevAdHoc';
sPF_DevTeamIdAdHoc = 'PF_DevTeamIdAdHoc';
sENV_PF_DevTeamIdAdHoc = 'ENV_PF_DevTeamIdAdHoc';
sPF_AppIdentifierAdHoc = 'PF_AppIdentifierAdHoc';
sENV_PF_AppIdentifierAdHoc = 'ENV_PF_AppIdentifierAdHoc';
sPF_MobileProvisionPathAdHoc = 'PF_MobileProvisionPathAdHoc';
sENV_PF_MobileProvisionPathAdHoc = 'ENV_PF_MobileProvisionPathAdHoc';
sPF_KeyChainAccessAdhoc = 'PF_KeyChainAccessAdhoc';
sENV_PF_KeyChainAccessAdhoc = 'ENV_PF_KeyChainAccessAdhoc';
sPF_AutoMobileProvisionAppStore = 'PF_AutoMobileProvisionAppStore';
sENV_PF_AutoMobileProvisionAppStore = 'ENV_PF_AutoMobileProvisionAppStore';
sPF_AutoCertificateAppStore = 'PF_AutoCertificateAppStore';
sENV_PF_AutoCertificateAppStore = 'ENV_PF_AutoCertificateAppStore';
sPF_CFBundleIdentifierAppStore = 'PF_CFBundleIdentifierAppStore';
sENV_PF_CFBundleIdentifierAppStore = 'ENV_PF_CFBundleIdentifierAppStore';
sPF_MobileProvisionAppStore = 'PF_MobileProvisionAppStore';
sENV_PF_MobileProvisionAppStore = 'ENV_PF_MobileProvisionAppStore';
sENV_PF_AppStore = 'ENV_PF_AppStore';
sPF_AppStore = 'PF_AppStore';
sPF_DevAppStore = 'PF_DevAppStore';
sENV_PF_DevAppStore = 'ENV_PF_DevAppStore';
sPF_DevTeamIdAppStore = 'PF_DevTeamIdAppStore';
sENV_PF_DevTeamIdAppStore = 'ENV_PF_DevTeamIdAppStore';
sPF_AppIdentifierAppStore = 'PF_AppIdentifierAppStore';
sENV_PF_AppIdentifierAppStore = 'ENV_PF_AppIdentifierAppStore';
sPF_MobileProvisionPathAppStore = 'PF_MobileProvisionPathAppStore';
sENV_PF_MobileProvisionPathAppStore = 'ENV_PF_MobileProvisionPathAppStore';
sPF_EntitlementExtraKeyValuesAppStore = 'PF_EntitlementExtraKeyValuesAppStore';
sENV_PF_EntitlementExtraKeyValuesAppStore = 'ENV_PF_EntitlementExtraKeyValuesAppStore';
sPF_KeyChainAccessAppStore = 'PF_KeyChainAccessAppStore';
sENV_PF_KeyChainAccessAppStore = 'ENV_PF_KeyChainAccessAppStore';
sPF_SandBox = 'PF_SandBox';
sENV_PF_SandBox = 'ENV_PF_SandBox';
sPF_DevSandBox = 'PF_DevSandBox';
sENV_PF_DevSandBox = 'ENV_PF_DevSandBox';
sPF_AppleID = 'PF_AppleID';
sENV_PF_AppleID = 'ENV_PF_AppleID';
sPF_AppSpecificPassword = 'PF_AppSpecificPassword';
sENV_PF_AppSpecificPassword = 'ENV_PF_AppSpecificPassword';
sPF_DeveloperIDCert = 'PF_DeveloperIDCert';
sENV_PF_DeveloperIDCert = 'ENV_PF_DeveloperIDCert';
sPF_StapleTicket = 'PF_StapleTicket';
sENV_PF_StapleTicket = 'ENV_PF_StapleTicket';
sPF_KeyStore = 'PF_KeyStore';
sENV_PF_KeyStore = 'ENV_PF_KeyStore';
sPF_KeyStorePass = 'PF_KeyStorePass';
sENV_PF_KeyStorePass = 'ENV_PF_KeyStorePass';
sPF_KeyStoreSubject = 'PF_KeyStoreSubject';
sENV_PF_KeyStoreSubject = 'ENV_PF_KeyStoreSubject';
sPF_UWPDistributionType = 'PF_UWPDistributionType';
sENV_PF_UWPDistributionType = 'ENV_PF_UWPDistributionType';
sPF_UWPPackageName = 'PF_UWPPackageName';
sPF_UWPPackageDisplayName = 'PF_UWPPackageDisplayName';
sPF_UWPPublisher = 'PF_UWPPublisher';
sPF_UWPPublisherDisplayName = 'PF_UWPPublisherDisplayName';
sPF_AliasKey = 'PF_AliasKey';
sENV_PF_AliasKey = 'ENV_PF_AliasKey';
sPF_AliasKeyPass = 'PF_AliasKeyPass';
sENV_PF_AliasKeyPass = 'ENV_PF_AliasKeyPass';
// AndroidUsesPermissions
sAUP_ACCEPT_HANDOVER = 'AUP_ACCEPT_HANDOVER';
sAUP_ACCESS_COARSE_LOCATION = 'AUP_ACCESS_COARSE_LOCATION';
sAUP_ACCESS_FINE_LOCATION = 'AUP_ACCESS_FINE_LOCATION';
sAUP_ACCESS_MOCK_LOCATION = 'AUP_ACCESS_MOCK_LOCATION';
sAUP_ADD_VOICEMAIL = 'AUP_ADD_VOICEMAIL';
sAUP_ANSWER_PHONE_CALLS = 'AUP_ANSWER_PHONE_CALLS';
sAUP_AUTHENTICATE_ACCOUNTS = 'AUP_AUTHENTICATE_ACCOUNTS';
sAUP_BODY_SENSORS = 'AUP_BODY_SENSORS';
sAUP_CALL_PHONE = 'AUP_CALL_PHONE';
sAUP_CAMERA = 'AUP_CAMERA';
sAUP_GET_ACCOUNTS = 'AUP_GET_ACCOUNTS';
sAUP_MANAGE_ACCOUNTS = 'AUP_MANAGE_ACCOUNTS';
sAUP_PROCESS_OUTGOING_CALLS = 'AUP_PROCESS_OUTGOING_CALLS';
sAUP_READ_CALENDAR = 'AUP_READ_CALENDAR';
sAUP_READ_CALL_LOG = 'AUP_READ_CALL_LOG';
sAUP_READ_CONTACTS = 'AUP_READ_CONTACTS';
sAUP_READ_EXTERNAL_STORAGE = 'AUP_READ_EXTERNAL_STORAGE';
sAUP_READ_HISTORY_BOOKMARKS = 'AUP_READ_HISTORY_BOOKMARKS';
sAUP_READ_PHONE_NUMBERS = 'AUP_READ_PHONE_NUMBERS';
sAUP_READ_PHONE_STATE = 'AUP_READ_PHONE_STATE';
sAUP_READ_PROFILE = 'AUP_READ_PROFILE';
sAUP_READ_SMS = 'AUP_READ_SMS';
sAUP_READ_SOCIAL_STREAM = 'AUP_READ_SOCIAL_STREAM';
sAUP_READ_USER_DICTIONARY = 'AUP_READ_USER_DICTIONARY';
sAUP_RECEIVE_MMS = 'AUP_RECEIVE_MMS';
sAUP_RECEIVE_SMS = 'AUP_RECEIVE_SMS';
sAUP_RECEIVE_WAP_PUSH = 'AUP_RECEIVE_WAP_PUSH';
sAUP_RECORD_AUDIO = 'AUP_RECORD_AUDIO';
sAUP_SEND_SMS = 'AUP_SEND_SMS';
sAUP_SUBSCRIBED_FEEDS_WRITE = 'AUP_SUBSCRIBED_FEEDS_WRITE';
sAUP_UNINSTALL_SHORTCUT = 'AUP_UNINSTALL_SHORTCUT';
sAUP_USE_CREDENTIALS = 'AUP_USE_CREDENTIALS';
sAUP_USE_SIP = 'AUP_USE_SIP';
sAUP_WRITE_CALENDAR = 'AUP_WRITE_CALENDAR';
sAUP_WRITE_CALL_LOG = 'AUP_WRITE_CALL_LOG';
sAUP_WRITE_CONTACTS = 'AUP_WRITE_CONTACTS';
sAUP_WRITE_EXTERNAL_STORAGE = 'AUP_WRITE_EXTERNAL_STORAGE';
sAUP_WRITE_HISTORY_BOOKMARKS = 'AUP_WRITE_HISTORY_BOOKMARKS';
sAUP_WRITE_PROFILE = 'AUP_WRITE_PROFILE';
sAUP_WRITE_SMS = 'AUP_WRITE_SMS';
sAUP_WRITE_SOCIAL_STREAM = 'AUP_WRITE_SOCIAL_STREAM';
sAUP_BIND_ACCESSIBILITY_SERVICE = 'AUP_BIND_ACCESSIBILITY_SERVICE';
sAUP_BIND_AUTOFILL_SERVICE = 'AUP_BIND_AUTOFILL_SERVICE';
sAUP_BIND_CARRIER_MESSAGING_SERVICE = 'AUP_BIND_CARRIER_MESSAGING_SERVICE';
sAUP_BIND_CARRIER_SERVICES = 'AUP_BIND_CARRIER_SERVICES';
sAUP_BIND_CHOOSER_TARGET_SERVICE = 'AUP_BIND_CHOOSER_TARGET_SERVICE';
sAUP_BIND_CONDITION_PROVIDER_SERVICE = 'AUP_BIND_CONDITION_PROVIDER_SERVICE';
sAUP_BIND_DEVICE_ADMIN = 'AUP_BIND_DEVICE_ADMIN';
sAUP_BIND_DREAM_SERVICE = 'AUP_BIND_DREAM_SERVICE';
sAUP_BIND_INCALL_SERVICE = 'AUP_BIND_INCALL_SERVICE';
sAUP_BIND_INPUT_METHOD = 'AUP_BIND_INPUT_METHOD';
sAUP_BIND_MIDI_DEVICE_SERVICE = 'AUP_BIND_MIDI_DEVICE_SERVICE';
sAUP_BIND_NFC_SERVICE = 'AUP_BIND_NFC_SERVICE';
sAUP_BIND_NOTIFICATION_LISTENER_SERVICE = 'AUP_BIND_NOTIFICATION_LISTENER_SERVICE';
sAUP_BIND_PRINT_SERVICE = 'AUP_BIND_PRINT_SERVICE';
sAUP_BIND_QUICK_SETTINGS_TILE = 'AUP_BIND_QUICK_SETTINGS_TILE';
sAUP_BIND_REMOTEVIEWS = 'AUP_BIND_REMOTEVIEWS';
sAUP_BIND_SCREENING_SERVICE = 'AUP_BIND_SCREENING_SERVICE';
sAUP_BIND_TELECOM_CONNECTION_SERVICE = 'AUP_BIND_TELECOM_CONNECTION_SERVICE';
sAUP_BIND_TEXT_SERVICE = 'AUP_BIND_TEXT_SERVICE';
sAUP_BIND_TV_INPUT = 'AUP_BIND_TV_INPUT';
sAUP_BIND_VISUAL_VOICEMAIL_SERVICE = 'AUP_BIND_VISUAL_VOICEMAIL_SERVICE';
sAUP_BIND_VOICE_INTERACTION = 'AUP_BIND_VOICE_INTERACTION';
sAUP_BIND_VPN_SERVICE = 'AUP_BIND_VPN_SERVICE';
sAUP_BIND_VR_LISTENER_SERVICE = 'AUP_BIND_VR_LISTENER_SERVICE';
sAUP_BIND_WALLPAPER = 'AUP_BIND_WALLPAPER';
sAUP_CLEAR_APP_CACHE = 'AUP_CLEAR_APP_CACHE';
sAUP_MANAGE_DOCUMENTS = 'AUP_MANAGE_DOCUMENTS';
sAUP_READ_VOICEMAIL = 'AUP_READ_VOICEMAIL';
sAUP_REQUEST_INSTALL_PACKAGES = 'AUP_REQUEST_INSTALL_PACKAGES';
sAUP_SYSTEM_ALERT_WINDOW = 'AUP_SYSTEM_ALERT_WINDOW';
sAUP_WRITE_SETTINGS = 'AUP_WRITE_SETTINGS';
sAUP_WRITE_VOICEMAIL = 'AUP_WRITE_VOICEMAIL';
sAUP_ACCESS_LOCATION_EXTRA_COMMANDS = 'AUP_ACCESS_LOCATION_EXTRA_COMMANDS';
sAUP_ACCESS_NETWORK_STATE = 'AUP_ACCESS_NETWORK_STATE';
sAUP_ACCESS_NOTIFICATION_POLICY = 'AUP_ACCESS_NOTIFICATION_POLICY';
sAUP_ACCESS_WIFI_STATE = 'AUP_ACCESS_WIFI_STATE';
sAUP_BATTERY_STATS = 'AUP_BATTERY_STATS';
sAUP_BLUETOOTH = 'AUP_BLUETOOTH';
sAUP_BLUETOOTH_ADMIN = 'AUP_BLUETOOTH_ADMIN';
sAUP_BROADCAST_STICKY = 'AUP_BROADCAST_STICKY';
sAUP_CHANGE_CONFIGURATION = 'AUP_CHANGE_CONFIGURATION';
sAUP_CHANGE_NETWORK_STATE = 'AUP_CHANGE_NETWORK_STATE';
sAUP_CHANGE_WIFI_MULTICAST_STATE = 'AUP_CHANGE_WIFI_MULTICAST_STATE';
sAUP_CHANGE_WIFI_STATE = 'AUP_CHANGE_WIFI_STATE';
sAUP_DISABLE_KEYGUARD = 'AUP_DISABLE_KEYGUARD';
sAUP_EXPAND_STATUS_BAR = 'AUP_EXPAND_STATUS_BAR';
sAUP_FLASHLIGHT = 'AUP_FLASHLIGHT';
sAUP_FOREGROUND_SERVICE = 'AUP_FOREGROUND_SERVICE';
sAUP_GET_PACKAGE_SIZE = 'AUP_GET_PACKAGE_SIZE';
sAUP_GET_TASKS = 'AUP_GET_TASKS';
sAUP_GLOBAL_SEARCH = 'AUP_GLOBAL_SEARCH';
sAUP_INSTALL_SHORTCUT = 'AUP_INSTALL_SHORTCUT';
sAUP_INSTANT_APP_FOREGROUND_SERVICE = 'AUP_INSTANT_APP_FOREGROUND_SERVICE';
sAUP_INTERNET = 'AUP_INTERNET';
sAUP_KILL_BACKGROUND_PROCESSES = 'AUP_KILL_BACKGROUND_PROCESSES';
sAUP_MANAGE_OWN_CALLS = 'AUP_MANAGE_OWN_CALLS';
sAUP_MODIFY_AUDIO_SETTINGS = 'AUP_MODIFY_AUDIO_SETTINGS';
sAUP_NFC = 'AUP_NFC';
sAUP_NFC_TRANSACTION_EVENT = 'AUP_NFC_TRANSACTION_EVENT';
sAUP_PACKAGE_USAGE_STATS = 'AUP_PACKAGE_USAGE_STATS';
sAUP_READ_GSERVICES = 'AUP_READ_GSERVICES';
sAUP_READ_SYNC_SETTINGS = 'AUP_READ_SYNC_SETTINGS';
sAUP_READ_SYNC_STATS = 'AUP_READ_SYNC_STATS';
sAUP_RECEIVE_BOOT_COMPLETED = 'AUP_RECEIVE_BOOT_COMPLETED';
sAUP_REORDER_TASKS = 'AUP_REORDER_TASKS';
sAUP_REQUEST_COMPANION_RUN_IN_BACKGROUND = 'AUP_REQUEST_COMPANION_RUN_IN_BACKGROUND';
sAUP_REQUEST_COMPANION_USE_DATA_IN_BACKGROUND = 'AUP_REQUEST_COMPANION_USE_DATA_IN_BACKGROUND';
sAUP_REQUEST_DELETE_PACKAGES = 'AUP_REQUEST_DELETE_PACKAGES';
sAUP_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = 'AUP_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS';
sAUP_SET_ALARM = 'AUP_SET_ALARM';
sAUP_SET_WALLPAPER = 'AUP_SET_WALLPAPER';
sAUP_SET_WALLPAPER_HINTS = 'AUP_SET_WALLPAPER_HINTS';
sAUP_SUBSCRIBED_FEEDS_READ = 'AUP_SUBSCRIBED_FEEDS_READ';
sAUP_TRANSMIT_IR = 'AUP_TRANSMIT_IR';
sAUP_USE_BIOMETRIC = 'AUP_USE_BIOMETRIC';
sAUP_USE_FINGERPRINT = 'AUP_USE_FINGERPRINT';
sAUP_COM_VENDING_BILLING = 'AUP_COM_VENDING_BILLING';
sAUP_VIBRATE = 'AUP_VIBRATE';
sAUP_WAKE_LOCK = 'AUP_WAKE_LOCK';
sAUP_WRITE_SYNC_SETTINGS = 'AUP_WRITE_SYNC_SETTINGS';
sAUP_WRITE_USER_DICTIONARY = 'AUP_WRITE_USER_DICTIONARY';
// EntitlementList
sEL_ReadOnlyMovies = 'EL_ReadOnlyMovies';
sEL_ReadWriteMovies = 'EL_ReadWriteMovies';
sEL_ReadOnlyMusic = 'EL_ReadOnlyMusic';
sEL_ReadWriteMusic = 'EL_ReadWriteMusic';
sEL_ReadOnlyPictures = 'EL_ReadOnlyPictures';
sEL_ReadWritePictures = 'EL_ReadWritePictures';
sEL_CaptureCamera = 'EL_CaptureCamera';
sEL_RecordingMicrophone = 'EL_RecordingMicrophone';
sEL_USBDevices = 'EL_USBDevices';
sEL_ReadWriteDownloads = 'EL_ReadWriteDownloads';
sEL_ReadOnlyFileDialog = 'EL_ReadOnlyFileDialog';
sEL_ReadWriteFileDialog = 'EL_ReadWriteFileDialog';
sEL_ChildProcessInheritance = 'EL_ChildProcessInheritance';
sEL_OutgoingNetwork = 'EL_OutgoingNetwork';
sEL_IncomingNetwork = 'EL_IncomingNetwork';
sEL_ReadWriteAddressBook = 'EL_ReadWriteAddressBook';
sEL_ReadWriteCalendars = 'EL_ReadWriteCalendars';
sEL_Location = 'EL_Location';
sEL_Printing = 'EL_Printing';
sEL_AllowJit = 'EL_AllowJit';
sEL_AllowUnsignedExecutableMemory = 'EL_AllowUnsignedExecutableMemory';
sEL_AllowDYLDEnvironmentVariables = 'EL_AllowDYLDEnvironmentVariables';
sEL_DisableLibraryValidation = 'EL_DisableLibraryValidation';
sEL_DisableExecutablePageProtection = 'EL_DisableExecutablePageProtection';
sEL_DebuggingTool = 'EL_DebuggingTool';
sEL_AudioInput = 'EL_AudioInput';
sEL_PhotosLibrary = 'EL_PhotosLibrary';
sEL_AppleEvents = 'EL_AppleEvents';
sEL_ApsEnvironment = 'EL_ApsEnvironment';
sEL_AdMob = 'EL_AdMob';
sEL_Maps = 'EL_Maps';
sEL_SecureFileSharing = 'EL_SecureFileSharing';
sIOSTransportSecFeat = 'IOSTransportSecFeat';
// iOSArtwork
siPhone_AppIcon57 = 'iPhone_AppIcon57';
siPhone_AppIcon60 = 'iPhone_AppIcon60';
siPhone_AppIcon87 = 'iPhone_AppIcon87';
siPhone_AppIcon114 = 'iPhone_AppIcon114';
siPhone_AppIcon120 = 'iPhone_AppIcon120';
siPhone_AppIcon180 = 'iPhone_AppIcon180';
siPhone_Launch320 = 'iPhone_Launch320';
siPhone_Launch640 = 'iPhone_Launch640';
siPhone_Launch640x1136 = 'iPhone_Launch640x1136';
siPhone_Launch750 = 'iPhone_Launch750';
siPhone_Launch828 = 'iPhone_Launch828';
siPhone_Launch1125 = 'iPhone_Launch1125';
siPhone_Launch1136x640 = 'iPhone_Launch1136x640';
siPhone_Launch1242 = 'iPhone_Launch1242';
siPhone_Launch1242x2688 = 'iPhone_Launch1242x2688';
siPhone_Launch1334 = 'iPhone_Launch1334';
siPhone_Launch1792 = 'iPhone_Launch1792';
siPhone_Launch2208 = 'iPhone_Launch2208';
siPhone_Launch2436 = 'iPhone_Launch2436';
siPhone_Launch2688x1242 = 'iPhone_Launch2688x1242';
siPhone_Spotlight29 = 'iPhone_Spotlight29';
siPhone_Spotlight40 = 'iPhone_Spotlight40';
siPhone_Spotlight58 = 'iPhone_Spotlight58';
siPhone_Spotlight80 = 'iPhone_Spotlight80';
siPhone_Spotlight120 = 'iPhone_Spotlight120';
siOS_AppStore512 = 'iOS_AppStore512';
siOS_AppStore1024 = 'iOS_AppStore1024';
siPad_AppIcon72 = 'iPad_AppIcon72';
siPad_AppIcon76 = 'iPad_AppIcon76';
siPad_AppIcon144 = 'iPad_AppIcon144';
siPad_AppIcon152 = 'iPad_AppIcon152';
siPad_AppIcon167 = 'iPad_AppIcon167';
siPad_Launch768 = 'iPad_Launch768';
siPad_Launch768x1024 = 'iPad_Launch768x1024';
siPad_Launch1024 = 'iPad_Launch1024';
siPad_Launch1024x768 = 'iPad_Launch1024x768';
siPad_Launch1536 = 'iPad_Launch1536';
siPad_Launch1536x2048 = 'iPad_Launch1536x2048';
siPad_Launch1668 = 'iPad_Launch1668';
siPad_Launch1668x2388 = 'iPad_Launch1668x2388';
siPad_Launch2048 = 'iPad_Launch2048';
siPad_Launch2048x1536 = 'iPad_Launch2048x1536';
siPad_Launch2048x2732 = 'iPad_Launch2048x2732';
siPad_Launch2224 = 'iPad_Launch2224';
siPad_Launch2388x1668 = 'iPad_Launch2388x1668';
siPad_Launch2732x2048 = 'iPad_Launch2732x2048';
siPad_SpotLight40 = 'iPad_SpotLight40';
siPad_SpotLight50 = 'iPad_SpotLight50';
siPad_SpotLight80 = 'iPad_SpotLight80';
siPad_SpotLight100 = 'iPad_SpotLight100';
siPad_Setting29 = 'iPad_Setting29';
siPad_Setting58 = 'iPad_Setting58';
// BuildType
sBT_BuildType = 'BT_BuildType';
// AndroidArtwork
sAndroid_LauncherIcon36 = 'Android_LauncherIcon36';
sAndroid_LauncherIcon48 = 'Android_LauncherIcon48';
sAndroid_LauncherIcon72 = 'Android_LauncherIcon72';
sAndroid_LauncherIcon96 = 'Android_LauncherIcon96';
sAndroid_LauncherIcon144 = 'Android_LauncherIcon144';
sIncludeAndroid_Splash = 'IncludeAndroid_Splash';
sAndroid_SplashImage426 = 'Android_SplashImage426';
sAndroid_SplashImage470 = 'Android_SplashImage470';
sAndroid_SplashImage640 = 'Android_SplashImage640';
sAndroid_SplashImage960 = 'Android_SplashImage960';
sAndroid_SplashTileMode = 'Android_SplashTileMode';
sAndroid_SplashGravity = 'Android_SplashGravity';
sAndroid_NotificationIcon24 = 'Android_NotificationIcon24';
sAndroid_NotificationIcon36 = 'Android_NotificationIcon36';
sAndroid_NotificationIcon48 = 'Android_NotificationIcon48';
sAndroid_NotificationIcon72 = 'Android_NotificationIcon72';
sAndroid_NotificationIcon96 = 'Android_NotificationIcon96';
sIncludeAndroid_NotificationAccentColor = 'IncludeAndroid_NotificationAccentColor';
sAndroid_NotificationAccentColor = 'Android_NotificationAccentColor';
// AndroidFirebase
sAndroid_AppId = 'Android_AppId';
sAndroid_GcmDefaultSenderId = 'Android_GcmDefaultSenderId';
sAndroid_GcmDefaultNotificationChannelId = 'Android_GcmDefaultNotificationChannelId';
// UWPArtwork
sUWP_CppLogo44 = 'UWP_CppLogo44';
sUWP_CppLogo150 = 'UWP_CppLogo150';
sUWP_DelphiLogo44 = 'UWP_DelphiLogo44';
sUWP_DelphiLogo150 = 'UWP_DelphiLogo150';
// Miscellaneous
sSanitizedProjectName = 'SanitizedProjectName';
// Orientation
sOrientationPortrait = 'OrientationPortrait';
sOrientationPortraitUpsideDown = 'OrientationPortraitUpsideDown';
sOrientationLandscapeLeft = 'OrientationLandscapeLeft';
sOrientationLandscapeRight = 'OrientationLandscapeRight';
implementation
end.
|
Program Loop;
Var
i: Integer;
Begin
Writeln('The multiplication table of 3');
For i:=1 to 10 do
Begin
Write(i:2);
Write(' X 3 = ');
Writeln(i*3:2);
End;
End. |
unit uODBase;
interface
uses
Classes, ORFn, uConst;
{ Order Checking }
function AddFillerAppID(const AnID: string): Boolean;
procedure ClearFillerAppList;
{ Ordering Environment }
procedure SetOrderFormIDOnCreate(AFormID: Integer);
function OrderFormIDOnCreate: Integer;
procedure SetOrderEventTypeOnCreate(AType: Char);
function OrderEventTypeOnCreate: Char;
procedure SetOrderEventIDOnCreate(AnEvtID: integer);
function OrderEventIDOnCreate: integer;
procedure SetOrderEventNameOnCreate(AnEvtNm: string);
function OrderEventNameOnCreate: string;
//CQ 20854 - Display Supplies Only - JCS
procedure SetOrderFormDlgIDOnCreate(AnID: String);
function OrderFormDlgIDOnCreate: String;
function GetKeyVars: string;
procedure PopKeyVars(NumLevels: Integer = 1);
procedure PushKeyVars(const NewVals: string);
procedure ExpandOrderObjects(var Txt: string; var ContainsObjects: boolean; msg: string = '');
procedure CheckForAutoDCDietOrders(EvtID: integer; DispGrp: integer; CurrentText: string;
var CancelText: string; Sender: TObject; tubefeeding: boolean = false);
implementation
uses
dShared, Windows, rTemplates, SysUtils, StdCtrls, fOrders, rOrders;
var
uOrderEventType: Char;
uOrderEventID: Integer;
uOrderEventName: string;
uOrderFormID: Integer;
uFillerAppID: TStringList;
uKeyVarList: TStringList;
//CQ 20854 - Display Supplies Only - JCS
uOrderEventDlgID: String;
{ Order Checking }
function AddFillerAppID(const AnID: string): Boolean;
begin
Result := False;
if uFillerAppID.IndexOf(AnID) < 0 then
begin
Result := True;
uFillerAppID.Add(AnID);
end;
end;
procedure ClearFillerAppList;
begin
uFillerAppID.Clear;
end;
{ Ordering Environment }
procedure SetOrderFormIDOnCreate(AFormID: Integer);
begin
uOrderFormID := AFormID;
end;
function OrderFormIDOnCreate: Integer;
begin
Result := uOrderFormID;
end;
procedure SetOrderEventTypeOnCreate(AType: Char);
begin
uOrderEventType := AType;
end;
function OrderEventTypeOnCreate: Char;
begin
Result := uOrderEventType;
end;
procedure SetOrderEventIDOnCreate(AnEvtID: Integer);
begin
uOrderEventID := AnEvtID;
end;
procedure SetOrderEventNameOnCreate(AnEvtNm: string);
begin
uOrderEventName := AnEvtNm;
end;
function OrderEventNameOnCreate: string;
begin
Result := uOrderEventName;
end;
function OrderEventIDOnCreate: integer;
begin
Result := uOrderEventID;
end;
//CQ 20854 - Display Supplies Only - JCS
procedure SetOrderFormDlgIDOnCreate(AnID: String);
begin
uOrderEventDlgID := AnID;
end;
//CQ 20854 - Display Supplies Only - JCS
function OrderFormDlgIDOnCreate: String;
begin
Result :=uOrderEventDlgID;
end;
function GetKeyVars: string;
begin
Result := '';
with uKeyVarList do if Count > 0 then Result := Strings[Count - 1];
end;
procedure PopKeyVars(NumLevels: Integer = 1);
begin
with uKeyVarList do while (NumLevels > 0) and (Count > 0) do
begin
Delete(Count - 1);
Dec(NumLevels);
end;
end;
procedure PushKeyVars(const NewVals: string);
var
i: Integer;
x: string;
begin
if uKeyVarList.Count > 0 then x := uKeyVarList[uKeyVarList.Count - 1] else x := '';
for i := 1 to MAX_KEYVARS do
if Piece(NewVals, U, i) <> '' then SetPiece(x, U, i, Piece(NewVals, U, i));
uKeyVarList.Add(x);
end;
procedure ExpandOrderObjects(var Txt: string; var ContainsObjects: boolean; msg: string = '');
var
ObjList: TStringList;
Err: TStringList;
i, j, k, oLen: integer;
obj, ObjTxt: string;
const
CRDelim = #13;
TC_BOILER_ERR = 'Order Boilerplate Object Error';
TX_BOILER_ERR = 'Contact IRM and inform them about this error.' + CRLF +
'Make sure you give them the name of the quick' + CRLF +
'order that you are processing.' ;
begin
ObjList := TStringList.Create;
try
Err := nil;
if(not dmodShared.BoilerplateOK(Txt, CRDelim, ObjList, Err)) and (assigned(Err)) then
begin
try
Err.Add(CRLF + TX_BOILER_ERR);
InfoBox(Err.Text, TC_BOILER_ERR, MB_OK + MB_ICONERROR);
finally
Err.Free;
end;
end;
if(ObjList.Count > 0) then
begin
ContainsObjects := True;
GetTemplateText(ObjList);
i := 0;
while (i < ObjList.Count) do
begin
if(pos(ObjMarker, ObjList[i]) = 1) then
begin
obj := copy(ObjList[i], ObjMarkerLen+1, MaxInt);
if(obj = '') then break;
j := i + 1;
while (j < ObjList.Count) and (pos(ObjMarker, ObjList[j]) = 0) do
inc(j);
if((j - i) > 2) then
begin
ObjTxt := '';
for k := i+1 to j-1 do
ObjTxt := ObjTxt + #13 + ObjList[k];
end
else
ObjTxt := ObjList[i+1];
i := j;
obj := '|' + obj + '|';
oLen := length(obj);
repeat
j := pos(obj, Txt);
if(j > 0) then
begin
delete(Txt, j, OLen);
insert(ObjTxt, Txt, j);
end;
until(j = 0);
end
else
inc(i);
end
end;
finally
ObjList.Free;
end;
end;
// Check for diet orders that will be auto-DCd on release because of start/stop overlaps.
// Moved here for visibility because it also needs to be checked on an auto-accept order.
procedure CheckForAutoDCDietOrders(EvtID: integer; DispGrp: integer; CurrentText: string;
var CancelText: string; Sender: TObject; tubefeeding: boolean = false);
const
TX_CX_CUR = 'A new diet order will CANCEL and REPLACE this current diet now unless' + CRLF +
'you specify a start date for when the new diet should replace the current' + CRLF +
'diet:' + CRLF + CRLF;
TX_CX_FUT = 'A new diet order with no expiration date will CANCEL and REPLACE these diets:' + CRLF + CRLF;
TX_CX_DELAYED1 = 'There are other delayed diet orders for this release event:';
TX_CX_DELAYED2 = 'This new diet order may cancel and replace those other diets' + CRLF +
'IMMEDIATELY ON RELEASE, unless you either:' + CRLF + CRLF +
'1. Specify an expiration date/time for this order that will' + CRLF +
' be prior to the start date/time of those other orders; or' + CRLF + CRLF +
'2. Specify a later start date/time for this order for when you' + CRLF +
' would like it to cancel and replace those other orders.';
var
i: integer;
AStringList: TStringList;
AList: TList;
x, PtEvtIFN, PtEvtName: string;
//AResponse: TResponse;
begin
if EvtID = 0 then // check current and future released diets
begin
x := CurrentText;
if Piece(x, #13, 1) <> 'Current Diet: ' then
begin
AStringList := TStringList.Create;
try
AStringList.Text := x;
if tubefeeding = false then CancelText := TX_CX_CUR + #9 + Piece(AStringList[0], ':', 1) + ':' + CRLF + CRLF
+ #9 + Copy(AStringList[0], 16, 99) + CRLF
else CancelText := Piece(AStringList[0], ':', 1) + ':' + CRLF + CRLF
+ #9 + Copy(AStringList[0], 16, 99) + CRLF;
if AStringList.Count > 1 then
begin
if tubefeeding = false then CancelText := CancelText + CRLF + CRLF +
TX_CX_FUT + #9 + Piece(AStringList[1], ':', 1) + ':' + CRLF + CRLF
+ #9 + Copy(AStringList[1], 22, 99) + CRLF
else CancelText := CancelText + CRLF + CRLF +
'Future Orders:' + #9 + Piece(AStringList[1], ':', 1) + ':' + CRLF + CRLF
+ #9 + Copy(AStringList[1], 22, 99) + CRLF;
if AStringList.Count > 2 then
for i := 2 to AStringList.Count - 1 do
CancelText := CancelText + #9 + TrimLeft(AStringList[i]) + CRLF;
end;
finally
AStringList.Free;
end;
end;
end
else if Sender is TButton then // delayed orders code here - on accept only
begin
//AResponse := Responses.FindResponseByName('STOP', 1);
//if (AResponse <> nil) and (AResponse.EValue <> '') then exit;
AList := TList.Create;
try
PtEvtIFN := IntToStr(frmOrders.TheCurrentView.EventDelay.PtEventIFN);
PtEvtName := frmOrders.TheCurrentView.EventDelay.EventName;
LoadOrdersAbbr(AList, frmOrders.TheCurrentView, PtEvtIFN);
for i := AList.Count - 1 downto 0 do
begin
if TOrder(Alist.Items[i]).DGroup <> DispGrp then
begin
TOrder(AList.Items[i]).Free;
AList.Delete(i);
end;
end;
if AList.Count > 0 then
begin
x := '';
RetrieveOrderFields(AList, 0, 0);
CancelText := TX_CX_DELAYED1 + CRLF + CRLF + 'Release event: ' + PtEvtName;
for i := 0 to AList.Count - 1 do
with TOrder(AList.Items[i]) do
begin
x := x + #9 + Text + CRLF;
(* if StartTime <> '' then
x := #9 + x + 'Start: ' + StartTime + CRLF
else
x := #9 + x + 'Ordered: ' + FormatFMDateTime('mmm dd,yyyy@hh:nn', OrderTime) + CRLF;*)
end;
CancelText := CancelText + CRLF + CRLF + x;
CancelText := CancelText + CRLF + CRLF + TX_CX_DELAYED2;
end;
finally
with AList do for i := 0 to Count - 1 do TOrder(Items[i]).Free;
AList.Free;
end;
end;
end;
initialization
uOrderEventType := #0;
uOrderFormID := 0;
uOrderEventName := '';
uFillerAppID := TStringList.Create;
uKeyVarList := TStringList.Create;
finalization
uFillerAppID.Free;
uKeyVarList.Free;
end.
|
unit FC.Trade.ViewTradersDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, StdCtrls, ExtendControls, ExtCtrls, ComCtrls,
FC.Definitions, ActnList;
type
TfmViewTradersDialog = class(TfmDialogClose_B)
Label1: TLabel;
lvTraders: TExtendListView;
buProperties: TButton;
ActionList1: TActionList;
acTraderProperties: TAction;
acDeleteTrader: TAction;
Button1: TButton;
Button2: TButton;
accAddTrader: TAction;
procedure accAddTraderExecute(Sender: TObject);
procedure acDeleteTraderUpdate(Sender: TObject);
procedure acDeleteTraderExecute(Sender: TObject);
procedure lvTradersDblClick(Sender: TObject);
procedure buOKDialogKey(Sender: TObject; var Key: Word);
procedure lvTradersEdited(Sender: TObject; Item: TListItem; var S: string);
procedure acTraderPropertiesExecute(Sender: TObject);
procedure acTraderPropertiesUpdate(Sender: TObject);
private
FProject: IStockProject;
procedure Fill;
function CurrentTrader: IStockTrader;
public
constructor Create(aProject: IStockProject); reintroduce;
end;
implementation
uses
FC.Singletons,
FC.Trade.CreateTraderDialog;
{$R *.dfm}
type
TTraderListItem = class (TListItem)
public
Trader: IStockTrader;
end;
{ TfmViewTradersDialog }
procedure TfmViewTradersDialog.Fill;
var
aListItem: TTraderListItem;
aTrader: IStockTrader;
i: Integer;
begin
lvTraders.Items.BeginUpdate;
try
lvTraders.Items.Clear;
for i := 0 to FProject.TraderCount-1 do
begin
aTrader:=FProject.GetTrader(i);
aListItem:=TTraderListItem.Create(lvTraders.Items);
lvTraders.Items.AddItem(aListItem);
aListItem.Caption:=aTrader.GetName;
aListItem.Trader:=aTrader;
end;
finally
lvTraders.Items.EndUpdate;
end;
if lvTraders.Items.Count=1 then
lvTraders.Items[0].Selected:=true;
end;
procedure TfmViewTradersDialog.acTraderPropertiesUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=lvTraders.Selected<>nil;
end;
constructor TfmViewTradersDialog.Create(aProject: IStockProject);
begin
inherited Create(nil);
Assert(aProject<>nil);
FProject:=aProject;
Fill;
end;
function TfmViewTradersDialog.CurrentTrader: IStockTrader;
begin
result:=TTraderListItem(lvTraders.Selected).Trader;
end;
procedure TfmViewTradersDialog.acTraderPropertiesExecute(Sender: TObject);
begin
CurrentTrader.ShowPropertyWindow;
end;
procedure TfmViewTradersDialog.lvTradersEdited(Sender: TObject; Item: TListItem; var S: string);
begin
TTraderListItem(Item).Trader.SetName(S);
end;
procedure TfmViewTradersDialog.buOKDialogKey(Sender: TObject; var Key: Word);
begin
if (Key=VK_RETURN) then
if lvTraders.IsEditing then
begin
key:=0;
//Как сделать EndEdit?
buOK.SetFocus;
lvTraders.SetFocus;
end;
end;
procedure TfmViewTradersDialog.lvTradersDblClick(Sender: TObject);
begin
acTraderProperties.Execute;
end;
procedure TfmViewTradersDialog.accAddTraderExecute(Sender: TObject);
var
aDialog : TfmCreateTraderDialog;
aTrader : IStockTrader;
begin
aDialog:=TfmCreateTraderDialog.Create(nil);
try
//Запуск диалога
if aDialog.ShowModal=mrOK then
begin
aTrader:=FC.Singletons.TraderFactory.CreateTrader(aDialog.SelectedTrader.IID);
aTrader.SetProject(FProject);
if aTrader.ShowPropertyWindow then
begin
FProject.AddTrader(aTrader);
Fill;
end
else begin
aTrader.SetProject(nil);
aTrader.Dispose;
aTrader:=nil;
end;
end;
finally
aDialog.Free;
end;
end;
procedure TfmViewTradersDialog.acDeleteTraderExecute(Sender: TObject);
begin
CurrentTrader.GetProject.RemoveTrader(CurrentTrader);
lvTraders.Selected.Free;
end;
procedure TfmViewTradersDialog.acDeleteTraderUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=lvTraders.Selected<>nil;
end;
end.
|
unit AssignRights;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzLstBox,
RzChkLst, Role, Right, RzCmboBx;
type
TfrmAssignRights = class(TfrmBasePopupDetail)
chlRights: TRzCheckList;
procedure chlRightsChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
private
{ Private declarations }
Role: TRole;
procedure PopulateRightsList;
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; var ARole: TRole); reintroduce; overload;
end;
implementation
{$R *.dfm}
uses
SecurityData;
{ TfrmAssignRights }
constructor TfrmAssignRights.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
procedure TfrmAssignRights.BindToObject;
begin
inherited;
end;
procedure TfrmAssignRights.Cancel;
begin
end;
procedure TfrmAssignRights.chlRightsChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
begin
(chlRights.Items.Objects[Index] as TRight).AssignedNewValue := NewState = cbChecked;
end;
constructor TfrmAssignRights.Create(AOwner: TComponent; var ARole: TRole);
begin
Create(AOwner);
Role := ARole;
// caption
lblCaption.Caption := 'Assigned rights to ' + ARole.Name;
PopulateRightsList;
end;
procedure TfrmAssignRights.PopulateRightsList;
var
LRight: TRight;
begin
with dmSecurity.dstRoleRights, chlRights do
begin
try
// open the datasource
Parameters.ParamByName('@role_code').Value := Role.Code;
Open;
while not Eof do
begin
LRight := TRight.Create;
LRight.Code := FieldByName('privilege_code_master').AsString;
LRight.Name := FieldByName('privilege_name').AsString;
LRight.AssignedOldValue := FieldByName('assigned').AsInteger = 1;
LRight.AssignedNewValue := FieldByName('assigned').AsInteger = 1;
AddItem(LRight.Name,LRight);
ItemChecked[Items.Count-1] := LRight.AssignedOldValue;
Next;
end;
finally
Close;
end;
end;
end;
procedure TfrmAssignRights.Save;
var
i, cnt: integer;
begin
cnt := chlRights.Count - 1;
for i := 0 to cnt do Role.Rights[i] := chlRights.Items.Objects[i] as TRight;
end;
function TfrmAssignRights.ValidEntry: boolean;
begin
Result := true;
end;
end.
|
unit IdCoderMessageDigest;
interface
uses
Classes,
IdCoder;
type
T64BitRecord = array[0..7] of byte;
T128BitRecord = array[0..15] of byte;
T4x4LongWordRecord = array[0..3] of LongWord;
T4x4x4LongWordRecord = array[0..3] of T4x4LongWordRecord;
T16x4LongWordRecord = array[0..15] of LongWord;
T160BitRecord = array[0..19] of byte;
T384BitRecord = array[0..47] of byte;
{ RSA-MD2
Copyright: R.L. Rivest, A. Shamir, and L. Adleman (RSA)
Licensing: "Free of licensing" from RFC 1115
"Free for non-commercial use" from RFC 1319
RFCs: 1115, 1319
Digest Size : 16 bytes / 128 bits
Used In: PEM III (RFC 1423), DASS (RFC 1507), Randomness Recs. (RFC
1750), PKCS #1 (RFC 2313), PKCS #7 (RFC 2315), OpenPGP
Format (RFC 2440), X.509 PKI Cert & CRL (RFC 2459), Secure
HTTP (RFC 2660)
}
TIdCoderMD2 = class(TIdCoder)
protected
FBuffer: T128BitRecord;
FChecksum: T128BitRecord;
FCount: Integer;
FCheckSumScore: Byte;
FState: T128BitRecord;
FX: T384BitRecord;
procedure Coder; override;
procedure CompleteCoding; override;
public
constructor Create(AOwner: TComponent); override;
procedure Reset; override;
procedure FillSamples(AStringList: TStrings); virtual;
procedure SetBufferSize(ASize: LongWord); override;
end;
{ RSA-MD4
Copyright: R.L. Rivest, A. Shamir, and L. Adleman (RSA)
Licensing: Free - "public domain" - as of RFC 1186
RFCs: 1186, 1320
Digest Size : 16B / 128b
Used In: Kerberos v5 (RFC 1510), Randomness Recs. (RFC 1750), S/KEY
one-time password (RFC 1760), One-time password (RFC 1938,
2289), PKCS #1 (RFC 2313)
}
TIdCoderMD4 = class(TIdCoder)
protected
FBitsProcessed: LongWord;
FBuffer: T4x4LongWordRecord;
FCount: T64BitRecord;
FDone: Boolean;
procedure Coder; override;
procedure CompleteCoding; override;
function func_f(x, y, z: LongWord): LongWord; virtual;
function func_g(x, y, z: LongWord): LongWord; virtual;
function func_h(x, y, z: LongWord): LongWord; virtual;
public
constructor Create(AOwner: TComponent); override;
procedure Reset; override;
procedure FillSamples(AStringList: TStrings); virtual;
procedure SetBufferSize(ASize: LongWord); override;
end;
{ RSA-MD5
Copyright: R.L. Rivest, A. Shamir, and L. Adleman (RSA)
Licensing: Free - "public domain" - as of RFC 1321
RFCs: 1321
Digest Size : 16B / 128b
Used In: SNMP (RFC 1352), PEM III (RFC 1423), SNMPv2 (RFC 1446,
1910), Kerberos v5 (RFC 1510), Randomness Recs. (RFC 1750),
SNTP (RFC 1361), IP Auth. Head. (RFC 1826, 1828), One-time
password (RFC 1938, 2289), Scalable Multicast Key
Distribution (RFC 1949), PGP Message Exchange Formats
(RFC 1991), IP Mobility Support (RFC 2002), RADIUS
(RFC 2058, 2138), Domain Name Security System (RFC 2065),
RIP-2 MD5 Auth. (RFC 2082), IMAP / POP AUTH (RFC 2095, 2195),
SLP (RFC 2165), OSPF v2 (RFC 2178, 2328, 2329, 2370), TLS v1
(RFC 2246), SNMPv3 (RFC 2264, 2274, 2570, 2574), S/MIME v2
(RFC 2311), PKCS #1 (RFC 2313), PKCS #7 (RFC 2315), IKE
(RFC 2409), OpenPGP Format (RFC 2440), One-time password
SASL (RFC 2444), X.509 PKI Cert & CRL (RFC 2459), RSA/MD5
KEYs & SIGs in DNS (RFC 2537), Cryptographic Message Syntax
(RFC 2630), S/MIME v3 (RFC 2633), Secure HTTP (RFC 2660),
Level Two Tunneling Protocol (RFC 2661)
}
TIdCoderMD5 = class(TIdCoderMD4)
protected
procedure Coder; override;
function func_g(x, y, z: LongWord): LongWord; override;
function func_i(x, y, z: LongWord): LongWord; virtual;
public
constructor Create(AOwner: TComponent); override;
procedure FillSamples(AStringList: TStrings); override;
end;
{ NIST-SHA1
Copyright: National Institute of Standards and Technology (NIST)
Licensing:
RFCs / Oth.: FIPS 180
Digest Size:
Used In: One-time password (RFC 1938, 2289), TLS v1 (RFC 2246),
SNMPv3 (RFC 2264, 2274, 2570, 2574), S/MIME v2 (RFC 2311),
IKE (RFC 2409), OpenPGP Format (RFC 2440), One-time
password SASL (RFC 2444), X.509 PKI Cert & CRL (RFC 2459),
Cryptographic Message Syntax (RFC 2630), Diffie-Hellman Key
Agreement (RFC 2631), S/MIME v3 (RFC 2633), Enhanced
Security Services for S/MIME (RFC 2634), Secure HTTP
(RFC 2660)
}
{ RIPEMD
Copyright:
Licensing:
RFCs / Oth.:
Digest Size:
Used In: OpenPGP Format (RFC 2440)
}
{ TIGER
Copyright:
Licensing:
RFCs / Oth.:
Digest Size:
Used In: OpenPGP Format (RFC 2440)
}
{ HAVAL
Copyright:
Licensing:
RFCs / Oth.:
Digest Size:
Used In: OpenPGP Format (RFC 2440)
}
implementation
uses
IdGlobal,
IdMIMETypes;
const
MD2_PI_SUBST: array[0..255] of byte = (
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240,
6, 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217,
188, 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66,
111, 24, 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73,
160, 251, 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178,
7, 63, 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154,
90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25,
48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198,
79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116,
4, 241, 69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101,
230, 45, 168, 2, 27, 96, 37, 173, 174, 176, 185, 246, 28, 70,
97, 105, 52, 64, 126, 15, 85, 71, 163, 35, 221, 81, 175, 58,
195, 92, 249, 206, 186, 197, 234, 38, 44, 83, 13, 110, 133, 40,
132, 9, 211, 223, 205, 244, 65, 129, 77, 82, 106, 220, 55, 200,
108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74, 120, 136,
149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57,
242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117,
75, 10, 49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51,
159, 17, 131, 20);
constructor TIdCoderMD2.Create;
var
i: Integer;
begin
inherited Create(AOwner);
InternSetBufferSize(16);
FCount := 0;
i := 0;
FAddCRLF := False;
repeat
FState[i] := 0;
FChecksum[i] := 0;
Inc(i);
until i = 16;
end;
procedure TIdCoderMD2.Reset;
var
i: Integer;
begin
FCount := 0;
i := 0;
repeat
FState[i] := 0;
FChecksum[i] := 0;
Inc(i);
until i = 16;
FInCompletion := False;
end;
procedure TIdCoderMD2.SetBufferSize;
begin
end;
procedure TIdCoderMD2.Coder;
var
i, j, k: Byte;
t: Byte;
const
NumRounds = 18;
begin
for J := Low(FChecksum) to High(FChecksum) do
begin
FCheckSumScore := FChecksum[j] xor MD2_PI_SUBST[Byte(FCBuffer[J + 1])
xor FCheckSumScore];
FChecksum[j] := FCheckSumScore;
end;
i := 0;
for J := 0 to 15 do
begin
FX[i + 16] := Byte(FCBuffer[i + 1]);
FX[i + 32] := FX[i + 16] xor FX[i];
Inc(i);
end;
T := 0;
for J := 0 to NumRounds - 1 do
begin
for K := Low(FX) to High(FX) do
begin
T := FX[k] xor MD2_PI_SUBST[T];
FX[k] := T;
end;
Inc(T, J);
end;
System.Move(FX[0], FState[0], 16);
FCBufferedData := 0;
end;
procedure TIdCoderMD2.CompleteCoding;
var
index, padLen: Integer;
padding: T128BitRecord;
s: string;
begin
FInCompletion := True;
index := FCBufferedData;
padLen := 16 - index;
padding := FBuffer;
FillChar(padding[index], padLen, padLen);
System.Move(padding[16 - padLen], FCBuffer[17 - padLen], padLen);
Coder;
System.Move(FChecksum[0], FCBuffer[1], FCBufferSize);
Coder;
SetLength(s, FCBufferSize);
UniqueString(s);
System.Move(FState[0], s[1], FCBufferSize);
OutputString(s);
end;
procedure TIdCoderMD2.FillSamples(AStringList: TStrings);
begin
with AStringList do
begin
Add(''); {Do not localize}
Add(' 8350E5A3E24C153DF2275C9F80692773'); {Do not localize}
Add('a'); {Do not localize}
Add(' 32EC01EC4A6DAC72C0AB96FB34C0B5D1'); {Do not localize}
Add('abc'); {Do not localize}
Add(' DA853B0D3F88D99B30283A69E6DED6BB'); {Do not localize}
Add('message digest'); {Do not localize}
Add(' AB4F496BFB2A530B219FF33031FE06B0'); {Do not localize}
Add('abcdefghijklmnopqrstuvwxyz'); {Do not localize}
Add(' 4E8DDFF3650292AB5A4108C3AA47940B'); {Do not localize}
Add('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
{Do not localize}
Add(' DA33DEF2A42DF13975352846C30338CD'); {Do not localize}
Add('12345678901234567890123456789012345678901234567890123456789012345678901234567890'); {Do not localize}
Add(' D5976F79D83D3A0DC9806C3C66F3EFD8'); {Do not localize}
end;
end;
const
MD4_INIT_VALUES: T4x4LongWordRecord = (
$67452301, $EFCDAB89, $98BADCFE, $10325476);
constructor TIdCoderMD4.Create;
begin
inherited;
InternSetBufferSize(64);
FBuffer := MD4_INIT_VALUES;
FillChar(FCount, 8, 0);
FDone := False;
FAddCRLF := False;
FBitsProcessed := 0;
end;
procedure TIdCoderMD4.Reset;
begin
FBuffer := MD4_INIT_VALUES;
FillChar(FCount, 8, 0);
FDone := False;
FInCompletion := False;
FBitsProcessed := 0;
end;
procedure TIdCoderMD4.SetBufferSize;
begin
end;
procedure TIdCoderMD4.Coder;
var
A, B, C, D, i: LongWord;
buff: T4x4x4LongWordRecord;
begin
A := FBuffer[0];
B := FBuffer[1];
C := FBuffer[2];
D := FBuffer[3];
System.Move(FCBuffer[1], buff[0], SizeOf(buff));
for i := 0 to 3 do
begin
A := ROL((A + func_f(B, C, D) + buff[i, 0]), 3);
D := ROL((D + func_f(A, B, C) + buff[i, 1]), 7);
C := ROL((C + func_f(D, A, B) + buff[i, 2]), 11);
B := ROL((B + func_f(C, D, A) + buff[i, 3]), 19);
end;
for i := 0 to 3 do
begin
A := ROL((A + func_g(B, C, D) + buff[0, i]) + $5A827999, 3);
D := ROL((D + func_g(A, B, C) + buff[1, i]) + $5A827999, 5);
C := ROL((C + func_g(D, A, B) + buff[2, i]) + $5A827999, 9);
B := ROL((B + func_g(C, D, A) + buff[3, i]) + $5A827999, 13);
end;
A := ROL((A + func_h(B, C, D) + T16x4LongWordRecord(buff)[0]) + $6ED9EBA1, 3);
D := ROL((D + func_h(A, B, C) + T16x4LongWordRecord(buff)[8]) + $6ED9EBA1, 9);
C := ROL((C + func_h(D, A, B) + T16x4LongWordRecord(buff)[4]) + $6ED9EBA1,
11);
B := ROL((B + func_h(C, D, A) + T16x4LongWordRecord(buff)[12]) + $6ED9EBA1,
15);
A := ROL((A + func_h(B, C, D) + T16x4LongWordRecord(buff)[2]) + $6ED9EBA1, 3);
D := ROL((D + func_h(A, B, C) + T16x4LongWordRecord(buff)[10]) + $6ED9EBA1,
9);
C := ROL((C + func_h(D, A, B) + T16x4LongWordRecord(buff)[6]) + $6ED9EBA1,
11);
B := ROL((B + func_h(C, D, A) + T16x4LongWordRecord(buff)[14]) + $6ED9EBA1,
15);
A := ROL((A + func_h(B, C, D) + T16x4LongWordRecord(buff)[1]) + $6ED9EBA1, 3);
D := ROL((D + func_h(A, B, C) + T16x4LongWordRecord(buff)[9]) + $6ED9EBA1, 9);
C := ROL((C + func_h(D, A, B) + T16x4LongWordRecord(buff)[5]) + $6ED9EBA1,
11);
B := ROL((B + func_h(C, D, A) + T16x4LongWordRecord(buff)[13]) + $6ED9EBA1,
15);
A := ROL((A + func_h(B, C, D) + T16x4LongWordRecord(buff)[3]) + $6ED9EBA1, 3);
D := ROL((D + func_h(A, B, C) + T16x4LongWordRecord(buff)[11]) + $6ED9EBA1,
9);
C := ROL((C + func_h(D, A, B) + T16x4LongWordRecord(buff)[7]) + $6ED9EBA1,
11);
B := ROL((B + func_h(C, D, A) + T16x4LongWordRecord(buff)[15]) + $6ED9EBA1,
15);
Inc(FBuffer[0], A);
Inc(FBuffer[1], B);
Inc(FBuffer[2], C);
Inc(FBuffer[3], D);
FCBufferedData := 0;
end;
procedure TIdCoderMD4.CompleteCoding;
var
bCount: LongWord;
s: string;
begin
FInCompletion := True;
if FCBufferedData >= FCBufferSize then
begin
Coder;
end;
Inc(FCBufferedData);
FCBuffer[FCBufferedData] := Chr($80);
bCount := FCBufferSize - FCBufferedData;
if bCount < 8 then
begin
FillChar(FCBuffer[FCBufferedData], bCount, 0);
FCBufferedData := FCBufferSize;
Coder;
bCount := FCBufferSize;
end;
if bCount > FCBufferSize then
begin
FillChar(FCBuffer[FCBufferedData + 1], FCBufferSize - FCBufferedData, 0);
Coder;
Dec(bCount, FCBufferSize);
FillChar(FCBuffer[1], FCBufferSize, 0);
FCBufferedData := FCBufferSize;
while bCount > FCBufferSize do
begin
Coder;
Dec(bCount, FCBufferSize);
end;
end;
FillChar(FCBuffer[FCBufferedData + 1], bCount - 8, 0);
bCount := ByteCount.L shl 3;
System.Move(bCount, FCBuffer[FCBufferSize - 7], 4);
bCount := (ByteCount.H shl 3) or (ByteCount.L shr 29);
System.Move(bCount, FCBuffer[FCBufferSize - 3], 4);
FCBufferedData := FCBufferSize;
Coder;
SetLength(s, 16);
UniqueString(s);
System.Move(FBuffer[0], s[1], 16);
OutputString(s);
end;
procedure TIdCoderMD4.FillSamples(AStringList: TStrings);
begin
with AStringList do
begin
Add('');
Add(' 31D6CFE0D16AE931B73C59D7E0C089C0'); {Do not localize}
Add('a'); {Do not localize}
Add(' BDE52CB31DE33E46245E05FBDBD6FB24'); {Do not localize}
Add('abc'); {Do not localize}
Add(' A448017AAF21D8525FC10AE87AA6729D'); {Do not localize}
Add('message digest'); {Do not localize}
Add(' D9130A8164549FE818874806E1C7014B'); {Do not localize}
Add('abcdefghijklmnopqrstuvwxyz'); {Do not localize}
Add(' D79E1C308AA5BBCDEEA8ED63DF412DA9'); {Do not localize}
Add('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
{Do not localize}
Add(' 043F8582F241DB351CE627E153E7F0E4'); {Do not localize}
Add('12345678901234567890123456789012345678901234567890123456789012345678901234567890'); {Do not localize}
Add(' E33B4DDC9C38F2199C3E7B164FCC0536'); {Do not localize}
end;
end;
function TIdCoderMD4.func_f(x, y, z: LongWord): LongWord;
begin
result := (x and y) or ((not x) and z);
end;
function TIdCoderMD4.func_g(x, y, z: LongWord): LongWord;
begin
result := (x and y) or (x and z) or (y and z);
end;
function TIdCoderMD4.func_h(x, y, z: LongWord): LongWord;
begin
result := x xor y xor z;
end;
const
MD5_SINE: array[1..64] of LongWord = (
{ Round 1. }
$D76AA478, $E8C7B756, $242070DB, $C1BDCEEE, $F57C0FAF, $4787C62A,
$A8304613, $FD469501, $698098D8, $8B44F7AF, $FFFF5BB1, $895CD7BE,
$6B901122, $FD987193, $A679438E, $49B40821,
{ Round 2. }
$F61E2562, $C040B340, $265E5A51, $E9B6C7AA, $D62F105D, $02441453,
$D8A1E681, $E7D3FBC8, $21E1CDE6, $C33707D6, $F4D50D87, $455A14ED,
$A9E3E905, $FCEFA3F8, $676F02D9, $8D2A4C8A,
{ Round 3. }
$FFFA3942, $8771F681, $6D9D6122, $FDE5380C, $A4BEEA44, $4BDECFA9,
$F6BB4B60, $BEBFBC70, $289B7EC6, $EAA127FA, $D4EF3085, $04881D05,
$D9D4D039, $E6DB99E5, $1FA27CF8, $C4AC5665,
{ Round 4. }
$F4292244, $432AFF97, $AB9423A7, $FC93A039, $655B59C3, $8F0CCC92,
$FFEFF47D, $85845DD1, $6FA87E4F, $FE2CE6E0, $A3014314, $4E0811A1,
$F7537E82, $BD3AF235, $2AD7D2BB, $EB86D391
);
constructor TIdCoderMD5.Create;
begin
inherited Create(AOwner);
InternSetBufferSize(64);
end;
procedure TIdCoderMD5.Coder;
var
A, B, C, D: LongWord;
buff: T16x4LongWordRecord;
begin
A := FBuffer[0];
B := FBuffer[1];
C := FBuffer[2];
D := FBuffer[3];
System.Move(FCBuffer[1], buff[0], SizeOf(buff));
A := B + ROL((A + func_f(B, C, D) + buff[0] + MD5_SINE[1]), 7);
D := A + ROL((D + func_f(A, B, C) + buff[1] + MD5_SINE[2]), 12);
C := D + ROL((C + func_f(D, A, B) + buff[2] + MD5_SINE[3]), 17);
B := C + ROL((B + func_f(C, D, A) + buff[3] + MD5_SINE[4]), 22);
A := B + ROL((A + func_f(B, C, D) + buff[4] + MD5_SINE[5]), 7);
D := A + ROL((D + func_f(A, B, C) + buff[5] + MD5_SINE[6]), 12);
C := D + ROL((C + func_f(D, A, B) + buff[6] + MD5_SINE[7]), 17);
B := C + ROL((B + func_f(C, D, A) + buff[7] + MD5_SINE[8]), 22);
A := B + ROL((A + func_f(B, C, D) + buff[8] + MD5_SINE[9]), 7);
D := A + ROL((D + func_f(A, B, C) + buff[9] + MD5_SINE[10]), 12);
C := D + ROL((C + func_f(D, A, B) + buff[10] + MD5_SINE[11]), 17);
B := C + ROL((B + func_f(C, D, A) + buff[11] + MD5_SINE[12]), 22);
A := B + ROL((A + func_f(B, C, D) + buff[12] + MD5_SINE[13]), 7);
D := A + ROL((D + func_f(A, B, C) + buff[13] + MD5_SINE[14]), 12);
C := D + ROL((C + func_f(D, A, B) + buff[14] + MD5_SINE[15]), 17);
B := C + ROL((B + func_f(C, D, A) + buff[15] + MD5_SINE[16]), 22);
A := B + ROL((A + func_g(B, C, D) + buff[1] + MD5_SINE[17]), 5);
D := A + ROL((D + func_g(A, B, C) + buff[6] + MD5_SINE[18]), 9);
C := D + ROL((C + func_g(D, A, B) + buff[11] + MD5_SINE[19]), 14);
B := C + ROL((B + func_g(C, D, A) + buff[0] + MD5_SINE[20]), 20);
A := B + ROL((A + func_g(B, C, D) + buff[5] + MD5_SINE[21]), 5);
D := A + ROL((D + func_g(A, B, C) + buff[10] + MD5_SINE[22]), 9);
C := D + ROL((C + func_g(D, A, B) + buff[15] + MD5_SINE[23]), 14);
B := C + ROL((B + func_g(C, D, A) + buff[4] + MD5_SINE[24]), 20);
A := B + ROL((A + func_g(B, C, D) + buff[9] + MD5_SINE[25]), 5);
D := A + ROL((D + func_g(A, B, C) + buff[14] + MD5_SINE[26]), 9);
C := D + ROL((C + func_g(D, A, B) + buff[3] + MD5_SINE[27]), 14);
B := C + ROL((B + func_g(C, D, A) + buff[8] + MD5_SINE[28]), 20);
A := B + ROL((A + func_g(B, C, D) + buff[13] + MD5_SINE[29]), 5);
D := A + ROL((D + func_g(A, B, C) + buff[2] + MD5_SINE[30]), 9);
C := D + ROL((C + func_g(D, A, B) + buff[7] + MD5_SINE[31]), 14);
B := C + ROL((B + func_g(C, D, A) + buff[12] + MD5_SINE[32]), 20);
A := B + ROL((A + func_h(B, C, D) + buff[5] + MD5_SINE[33]), 4);
D := A + ROL((D + func_h(A, B, C) + buff[8] + MD5_SINE[34]), 11);
C := D + ROL((C + func_h(D, A, B) + buff[11] + MD5_SINE[35]), 16);
B := C + ROL((B + func_h(C, D, A) + buff[14] + MD5_SINE[36]), 23);
A := B + ROL((A + func_h(B, C, D) + buff[1] + MD5_SINE[37]), 4);
D := A + ROL((D + func_h(A, B, C) + buff[4] + MD5_SINE[38]), 11);
C := D + ROL((C + func_h(D, A, B) + buff[7] + MD5_SINE[39]), 16);
B := C + ROL((B + func_h(C, D, A) + buff[10] + MD5_SINE[40]), 23);
A := B + ROL((A + func_h(B, C, D) + buff[13] + MD5_SINE[41]), 4);
D := A + ROL((D + func_h(A, B, C) + buff[0] + MD5_SINE[42]), 11);
C := D + ROL((C + func_h(D, A, B) + buff[3] + MD5_SINE[43]), 16);
B := C + ROL((B + func_h(C, D, A) + buff[6] + MD5_SINE[44]), 23);
A := B + ROL((A + func_h(B, C, D) + buff[9] + MD5_SINE[45]), 4);
D := A + ROL((D + func_h(A, B, C) + buff[12] + MD5_SINE[46]), 11);
C := D + ROL((C + func_h(D, A, B) + buff[15] + MD5_SINE[47]), 16);
B := C + ROL((B + func_h(C, D, A) + buff[2] + MD5_SINE[48]), 23);
A := B + ROL((A + func_i(B, C, D) + buff[0] + MD5_SINE[49]), 6);
D := A + ROL((D + func_i(A, B, C) + buff[7] + MD5_SINE[50]), 10);
C := D + ROL((C + func_i(D, A, B) + buff[14] + MD5_SINE[51]), 15);
B := C + ROL((B + func_i(C, D, A) + buff[5] + MD5_SINE[52]), 21);
A := B + ROL((A + func_i(B, C, D) + buff[12] + MD5_SINE[53]), 6);
D := A + ROL((D + func_i(A, B, C) + buff[3] + MD5_SINE[54]), 10);
C := D + ROL((C + func_i(D, A, B) + buff[10] + MD5_SINE[55]), 15);
B := C + ROL((B + func_i(C, D, A) + buff[1] + MD5_SINE[56]), 21);
A := B + ROL((A + func_i(B, C, D) + buff[8] + MD5_SINE[57]), 6);
D := A + ROL((D + func_i(A, B, C) + buff[15] + MD5_SINE[58]), 10);
C := D + ROL((C + func_i(D, A, B) + buff[6] + MD5_SINE[59]), 15);
B := C + ROL((B + func_i(C, D, A) + buff[13] + MD5_SINE[60]), 21);
A := B + ROL((A + func_i(B, C, D) + buff[4] + MD5_SINE[61]), 6);
D := A + ROL((D + func_i(A, B, C) + buff[11] + MD5_SINE[62]), 10);
C := D + ROL((C + func_i(D, A, B) + buff[2] + MD5_SINE[63]), 15);
B := C + ROL((B + func_i(C, D, A) + buff[9] + MD5_SINE[64]), 21);
Inc(FBuffer[0], A);
Inc(FBuffer[1], B);
Inc(FBuffer[2], C);
Inc(FBuffer[3], D);
FCBufferedData := 0;
end;
function TIdCoderMD5.func_g(x, y, z: LongWord): LongWord;
begin
result := (x and z) or (y and (not z));
end;
function TIdCoderMD5.func_i(x, y, z: LongWord): LongWord;
begin
result := y xor (x or (not z));
end;
procedure TIdCoderMD5.FillSamples(AStringList: TStrings);
begin
with AStringList do
begin
Add('');
Add(' d41d8cd98f00b204e9800998ecf8427e'); {Do not localize}
Add('a'); {Do not localize}
Add(' 0cc175b9c0f1b6a831c399e269772661'); {Do not localize}
Add('abc'); {Do not localize}
Add(' 900150983cd24fb0d6963f7d28e17f72'); {Do not localize}
Add('message digest'); {Do not localize}
Add(' f96b697d7cb7938d525a2f31aaf161d0'); {Do not localize}
Add('abcdefghijklmnopqrstuvwxyz'); {Do not localize}
Add(' c3fcd3d76192e4007dfb496cca67e13b'); {Do not localize}
Add('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
{Do not localize}
Add(' d174ab98d277d9f5a5611c2c9f419d9f'); {Do not localize}
Add('12345678901234567890123456789012345678901234567890123456789012345678901234567890'); {Do not localize}
Add(' 57edf4a22be3c955ac49da2e2107b67a'); {Do not localize}
end;
end;
initialization
RegisterCoderClass(TIdCoderMD2, CT_CREATION, CP_FALLBACK,
'', MIMEEncRSAMD2);
RegisterCoderClass(TIdCoderMD2, CT_REALISATION, CP_FALLBACK,
'', MIMEEncRSAMD2);
RegisterCoderClass(TIdCoderMD4, CT_CREATION, CP_FALLBACK,
'', MIMEEncRSAMD4);
RegisterCoderClass(TIdCoderMD4, CT_REALISATION, CP_FALLBACK,
'', MIMEEncRSAMD4);
RegisterCoderClass(TIdCoderMD5, CT_CREATION, CP_FALLBACK,
'', MIMEEncRSAMD5);
RegisterCoderClass(TIdCoderMD5, CT_REALISATION, CP_FALLBACK,
'', MIMEEncRSAMD5);
end.
|
unit netaddrutils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, character, Math;
type
TAddrOctets = array[0..3] of Byte;
function IsInteger(Value: String): Boolean;
function IsAddress(Address: String): Boolean;
function AddressToOctets(Address: String; var Octets: TAddrOctets): Boolean;
function OctetsToInt(Octets: TAddrOctets): UInt32;
function AddressToInt(Address: String; var Int: UInt32): Boolean;
function IntToAddress(Int: UInt32): String;
function IntAddrToIntNetwork(IntAddr: UInt32; Prefix: Integer): UInt32;
implementation
function IsInteger(Value: String): Boolean;
var
I: Integer;
begin
Result := Length(Value) > 0;
for I := 1 to Length(Value) do begin
if not IsNumber(Value[I]) then begin
Result := False;
Exit;
end;
end;
end;
function IsAddress(Address: String): Boolean;
var
Octets: TAddrOctets;
begin
Octets[0] := 0;
Result := AddressToOctets(Address, Octets);
end;
function AddressToOctets(Address: String; var Octets: TAddrOctets): Boolean;
var
OctetN, CharPos: Integer;
S: String;
begin
Result := False;
OctetN := 0;
CharPos := Pos('.', Address);
while (CharPos > 0) do begin
S := Copy(Address, 1, CharPos - 1);
Delete(Address, 1, CharPos);
if IsInteger(S) and (OctetN <= 3) then
Octets[OctetN] := StrToInt(S)
else
Exit;
CharPos := Pos('.', Address);
if (CharPos = 0) and (Length(Address) > 0) then
CharPos := Length(Address) + 1;
Inc(OctetN);
end;
Result := (OctetN = 4) and (Address = '');
end;
function OctetsToInt(Octets: TAddrOctets): UInt32;
begin
Result := (Octets[0] * 16777216) + (Octets[1] * 65536) + (Octets[2] * 256) + Octets[3];
end;
function AddressToInt(Address: String; var Int: UInt32): Boolean;
var
Octets: TAddrOctets;
begin
Octets[0] := 0;
FillChar(Octets, SizeOf(TAddrOctets), 0);
Result := AddressToOctets(Address, Octets);
if Result then
Int := OctetsToInt(Octets);
end;
function IntToAddress(Int: UInt32): String;
begin
Result := Format('%d.%d.%d.%d', [hi(hi(Int)), lo(hi(Int)), hi(lo(Int)), lo(lo(Int))]);
end;
function IntAddrToIntNetwork(IntAddr: UInt32; Prefix: Integer): UInt32;
begin
Result := IntAddr and Trunc(intpower(2, 32) - intpower(2, 32 - Prefix));
end;
end.
|
unit ksLoadingIndicator;
interface
{$I ksComponents.inc}
uses FMX.Forms, Classes, FMX.Controls, FMX.Objects, ksTypes, FMX.Graphics,
FMX.StdCtrls, FMX.Layouts
{$IFDEF IOS}
, iOSapi.UIKit, iOSapi.Foundation
{$ENDIF}
;
type
[ComponentPlatformsAttribute(
pidWin32 or
pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF}
)]
TksLoadingIndicator = class(TLayout)
private
FRectangle: TRectangle;
FBackground: TRectangle;
FLoadingText: string;
FFadeBackground: Boolean;
FIsModal: Boolean;
//FLabel: TLabel;
FOpacity: single;
FAnimated: Boolean;
FAnimator: TAniIndicator;
procedure SetIsModal(const Value: Boolean);
procedure SetFadeBackground(const Value: Boolean);
procedure SetOpacity(const Value: single);
procedure SetAnimated(const Value: Boolean);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ShowLoading;
procedure HideLoading;
published
property Animated: Boolean read FAnimated write SetAnimated;
property IsModal: Boolean read FIsModal write SetIsModal default False;
property LoadingText: string read FLoadingText write FLoadingText;
property FadeBackground: Boolean read FFadeBackground write SetFadeBackground default False;
property Opacity: single read FOpacity write SetOpacity;
end;
procedure ShowLoadingIndicator(AForm: TCommonCustomForm;
AOpacity: single); overload;
procedure ShowLoadingIndicator(AForm: TCommonCustomForm;
const AFade: Boolean = False;
const AModal: Boolean = False;
const AOpacity: single = 1); overload;
procedure HideLoadingIndicator(AForm: TCommonCustomForm);
function IsLoadingIndicatorVisible(AForm: TCommonCustomForm): Boolean;
function FindLoadingIndicator(AForm: TCommonCustomForm): TksLoadingIndicator;
implementation
uses
System.UIConsts, FMX.Types, SysUtils, Types, FMX.Ani
{$IFDEF IOS}
,iOSapi.CoreGraphics, FMX.Helpers.iOS
{$ENDIF}
;
function FindLoadingIndicator(AForm: TCommonCustomForm): TksLoadingIndicator;
var
ICount: integer;
begin
Result := nil;
if AForm = nil then
Exit;
for ICount := AForm.ComponentCount-1 downto 0 do
begin
if AForm.Components[ICount] is TksLoadingIndicator then
begin
Result := (AForm.Components[ICount] as TksLoadingIndicator);
Exit;
end;
end;
end;
function IsLoadingIndicatorVisible(AForm: TCommonCustomForm): Boolean;
var
ALoading: TksLoadingIndicator;
begin
Result := False;
ALoading := FindLoadingIndicator(AForm);
if ALoading <> nil then
begin
if ALoading.Parent = AForm then
Result := True;
end;
end;
procedure ShowLoadingIndicator(AForm: TCommonCustomForm;
AOpacity: single); overload;
begin
ShowLoadingIndicator(AForm, False, False, AOpacity);
end;
procedure ShowLoadingIndicator(AForm: TCommonCustomForm;
const AFade: Boolean = False;
const AModal: Boolean = False;
const AOpacity: single = 1);
var
ALoadingIndicator: TksLoadingIndicator;
begin
Application.ProcessMessages;
try
ALoadingIndicator := FindLoadingIndicator(AForm);
if ALoadingIndicator = nil then
ALoadingIndicator := TksLoadingIndicator.Create(AForm);
ALoadingIndicator.FadeBackground := AFade;
ALoadingIndicator.IsModal := AModal;
ALoadingIndicator.Opacity := AOpacity;
ALoadingIndicator.Animated := True;
AForm.AddObject(ALoadingIndicator);
ALoadingIndicator.BringToFront;
except
//
end;
end;
procedure HideLoadingIndicator(AForm: TCommonCustomForm);
var
ALoadingIndicator: TksLoadingIndicator;
begin
if AForm = nil then
Exit;
try
ALoadingIndicator := FindLoadingIndicator(AForm);
if ALoadingIndicator <> nil then
AForm.RemoveObject(ALoadingIndicator);
except
//
end;
end;
{ TksLoadingIndicator }
constructor TksLoadingIndicator.Create(AOwner: TComponent);
begin
inherited;
Align := TAlignLayout.Contents;
HitTest := False;
FLoadingText := 'LOADING';
FFadeBackground := False;
FIsModal := False;
FBackground := TRectangle.Create(Self);
FBackground.Align := TAlignLayout.Client;
FBackground.Stroke.Kind := TBrushKind.None;
FBackground.Fill.Kind := TBrushKind.Solid;
FBackground.Fill.Color := claBlack;
FBackground.HitTest := False;
FBackground.Opacity := 0.3;
AddObject(FBackground);
{ FRectangle := TRectangle.Create(Self);
FRectangle.Align := TAlignLayout.Center;
FRectangle.Stroke.Kind := TBrushKind.Solid;
FRectangle.Stroke.Color := claBlack;
FRectangle.Fill.Color := claWhite;
FRectangle.Width := 50;
FRectangle.Height := 50;
FRectangle.XRadius := 5;
FRectangle.YRadius := 5;
FRectangle.Opacity := FOpacity; }
{ FLabel := TLabel.Create(Self);
FLabel.Align := TAlignLayout.Client;
FLabel.TextSettings.FontColor := claWhite;
FLabel.Text := FLoadingText;
FLabel.TextSettings.HorzAlign := TTextAlign.Center;
FLabel.TextSettings.VertAlign := TTextAlign.Center;
FLabel.StyledSettings := []; }
FAnimator := TAniIndicator.Create(Self);
FAnimator.Align := TAlignLayout.Client;
FAnimator.
AddObject(FRectangle);
//AddObject(FLabel);
AddObject(FAnimator);
end;
destructor TksLoadingIndicator.Destroy;
begin
inherited;
end;
procedure TksLoadingIndicator.HideLoading;
begin
HideLoadingIndicator(Owner as TForm);
end;
procedure TksLoadingIndicator.SetAnimated(const Value: Boolean);
begin
FAnimated := Value;
FAnimator.Enabled := Value;
end;
procedure TksLoadingIndicator.SetFadeBackground(const Value: Boolean);
begin
FFadeBackground := Value;
case Value of
True: FBackground.Opacity := 0.3;
False: FBackground.Opacity := 0;
end;
end;
procedure TksLoadingIndicator.SetIsModal(const Value: Boolean);
begin
FIsModal := Value;
FBackground.HitTest := Value;
end;
procedure TksLoadingIndicator.SetOpacity(const Value: single);
begin
FOpacity := Value;
//FRectangle.Opacity := Value;
end;
procedure TksLoadingIndicator.ShowLoading;
begin
ShowLoadingIndicator(Owner as TForm);
end;
end.
|
unit TMSrvCtrl;
{
Aestan Tray Menu
Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu
for more information.
This work is hereby released into the Public Domain. To view a copy of the
public domain dedication, visit:
http://creativecommons.org/licenses/publicdomain/
or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
California 94305, USA.
This unit contains the TTMService class, which can be used to control
Windows services.
}
{
NOTE:
This unit is a replacement of the TSrvCtrl component, which was originally
used by AeTrayMenu. However, this component had a lot of features ATM
didn't need, and most of all, TSrvCtrl was only for non-commercial use.
Some of this code has been inspired by the TSrvCtrl component, though,
and therefore I'd like to thank the original authors:
* GSC (www.gsc.hu)
* TMEDIA (www.tmedia.de)
>>PLEASE DO NOT REMOVE THIS NOTE<<
}
interface
uses
Windows, SysUtils, Classes, WinSvc;
type
{ Indicates the status of the service }
TServiceState = (svsStopped = $00000001, svsStartPending, svsStopPending,
svsRunning, svsContinuePending, svsPausePending, svsPaused);
TServiceControl = (svcStop, svcPauseContinue);
TServiceControls = set of TServiceControl;
EServiceException = class(Exception)
public
constructor Create(AErrorCode: Integer); overload;
end;
{ This class can control Windows services.
Note: if you make calls to methods or use properties that need a handle to
the service (in other words: that need TTMService to be activated),
while TTMService hasn't been activated (yet), an exception will be raised. }
TTMService = class
private
FServiceName: String;
FServiceHandle: SC_HANDLE;
FSCManagerHandle: SC_HANDLE;
procedure SetServiceName(const Value: String);
function GetDisplayName: String;
function GetState: TServiceState;
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
function GetControlsAccepted: TServiceControls;
protected
property SCManagerHandle: SC_HANDLE read FSCManagerHandle;
property ServiceHandle: SC_HANDLE read FServiceHandle;
procedure ControlService(ControlCode: DWORD); virtual;
procedure GetServiceConfig(var Config: TQueryServiceConfig);
procedure GetServiceStatus(var Status: TServiceStatus);
procedure VerifyActive;
public
{ Read to determine whether TTMService has an active/open handle to
the service.
Setting Active to true does the same as calling Open; setting to false
is equivalent to calling Close. }
property Active: Boolean read GetActive write SetActive;
{ Can be used to see if the service accepts a specific control code/action }
property ControlsAccepted: TServiceControls read GetControlsAccepted;
{ Can be used to retrieve the "display name" of the service }
property DisplayName: String read GetDisplayName;
{ Can be used to retrieve the status of the service }
property State: TServiceState read GetState;
{ The name of the service (*not* the display name). If TTMService has
already been activated/opened, it will first disconnect and then
store the property. You always have to activate the TTMService yourself,
since this will *not* be done for you automatically. }
property ServiceName: String read FServiceName write SetServiceName;
{ Opens a handle to the specified service. If TTMService has already been
activated, Close is called first, and then the handle is opened. }
procedure Open; virtual;
{ Closes the handle to the service. If TTMService is inactive, nothing
is done. }
procedure Close; virtual;
{ Starts the service. }
procedure Start; virtual;
{ Continues a paused service.}
procedure Continue; virtual;
{ Stops the service. }
procedure Stop; virtual;
{ Suspends/pauses the service. }
procedure Pause; virtual;
constructor Create; virtual;
destructor Destroy; override;
end; //ttmservice
implementation
uses
Forms;
resourcestring
SNoServiceOpen = 'No service has been opened yet!';
{ EServiceException }
constructor EServiceException.Create(AErrorCode: Integer);
begin
inherited Create(SysErrorMessage(AErrorCode));
end;
{ TTMService }
procedure TTMService.Close;
begin
VerifyActive;
if not CloseServiceHandle(ServiceHandle) then
raise EServiceException.Create(GetLastError);
FServiceHandle := 0;
if not CloseServiceHandle(SCManagerHandle) then
raise EServiceException.Create(GetLastError);
FSCManagerHandle := 0;
end;
procedure TTMService.Continue;
begin
ControlService(SERVICE_CONTROL_CONTINUE);
end;
procedure TTMService.ControlService(ControlCode: Cardinal);
var
ServiceStatus: TServiceStatus;
begin
VerifyActive;
if not WinSvc.ControlService(ServiceHandle, ControlCode, ServiceStatus) then
raise EServiceException.Create(GetLastError);
end;
constructor TTMService.Create;
begin
inherited Create;
end;
destructor TTMService.Destroy;
begin
if Active then
Close;
inherited Destroy;
end;
function TTMService.GetActive: Boolean;
begin
Result := (SCManagerHandle <> 0) and (ServiceHandle <> 0);
end;
function TTMService.GetControlsAccepted: TServiceControls;
var
Status: TServiceStatus;
begin
GetServiceStatus(Status);
with Status do
begin
if (dwControlsAccepted and SERVICE_ACCEPT_STOP) = SERVICE_ACCEPT_STOP then
Include(Result, svcStop);
if (dwControlsAccepted and SERVICE_ACCEPT_PAUSE_CONTINUE) = SERVICE_ACCEPT_PAUSE_CONTINUE then
Include(Result, svcPauseContinue);
end; //with config
end;
function TTMService.GetDisplayName: String;
var
Config: TQueryServiceConfig;
begin
GetServiceConfig(Config);
Result := Config.lpDisplayName;
end;
procedure TTMService.GetServiceConfig(var Config: TQueryServiceConfig);
var
BufferSizeNeeded, ErrorCode: Cardinal;
Buffer: PQueryServiceConfig;
begin
VerifyActive;
Buffer := nil;
if not QueryServiceConfig(ServiceHandle, Buffer, 0, BufferSizeNeeded) then
begin
ErrorCode := GetLastError;
if ErrorCode = ERROR_INSUFFICIENT_BUFFER then
begin
GetMem(Buffer, BufferSizeNeeded);
try
if not QueryServiceConfig(ServiceHandle, Buffer, BufferSizeNeeded,
BufferSizeNeeded) then
raise EServiceException.Create(GetLastError);
Config := Buffer^;
finally
FreeMem(Buffer);
end; //try..finally
end
else //if errorcode = error_insufficient_buffer
raise EServiceException.Create(ErrorCode);
end; //if not queryserviceconfig(<empty buffer>)
end;
procedure TTMService.GetServiceStatus(var Status: TServiceStatus);
begin
VerifyActive;
if not QueryServiceStatus(ServiceHandle, Status) then
raise EServiceException.Create(GetLastError);
end;
function TTMService.GetState: TServiceState;
var
Status: TServiceStatus;
begin
GetServiceStatus(Status);
Result := TServiceState(Status.dwCurrentState);
end;
procedure TTMService.Open;
begin
if Active then
Close;
//Open the service control manager
FSCManagerHandle := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
if FSCManagerHandle = 0 then
raise EServiceException.Create(GetLastError);
//Open the service
try
FServiceHandle := OpenService(SCManagerHandle, PChar(ServiceName),
SERVICE_PAUSE_CONTINUE or SERVICE_QUERY_CONFIG or SERVICE_QUERY_STATUS or
SERVICE_START or SERVICE_STOP);
if ServiceHandle = 0 then
raise EServiceException.Create(GetLastError);
except
//Clean up the service control manager handle
CloseServiceHandle(SCManagerHandle);
raise;
end;
end;
procedure TTMService.Pause;
begin
ControlService(SERVICE_CONTROL_PAUSE);
end;
procedure TTMService.SetActive(const Value: Boolean);
begin
if Value then
Open
else
Close;
end;
procedure TTMService.SetServiceName(const Value: String);
begin
FServiceName := Value;
end;
procedure TTMService.Start;
var
Parameters: PChar;
begin
Parameters := nil;
if not StartService(ServiceHandle, 0, Parameters) then
raise EServiceException.Create(GetLastError);
end;
procedure TTMService.Stop;
begin
ControlService(SERVICE_CONTROL_STOP);
end;
procedure TTMService.VerifyActive;
begin
if not Active then
raise EServiceException.Create(SNoServiceOpen);
end;
end.
|
unit uObjectHPGLDrawing;
interface
uses SysUtils, Types, Contnrs, uMyTypes, uObjectFeaturePolyLine, Math;
type
THPGLDrawing = class(TObject)
private
objPolylines: TObjectList;
objMinX, objMinY, objMaxX, objMaxY: double;
objInternalPolylinePointer: integer; // ukazatel na aktualnu polyline (pri ziskavani polylineov cez GetNextPolyline)
function objGetPolyline(Index: Integer): TFeaturePolyLineObject;
public
constructor Create(filePath: string; rodicPanel: TObject; sizeFactor: double = 1);
destructor Destroy;
property Polylines[Index: Integer]: TFeaturePolyLineObject read objGetPolyline;
function CountPolylines: integer;
function GetNextPolyline: TFeaturePolyLineObject;
property MinX: double read objMinX;
property MinY: double read objMinY;
property MaxX: double read objMaxX;
property MaxY: double read objMaxY;
published
end;
implementation
uses uMain, uDebug;
{ THPGLDrawing }
function THPGLDrawing.CountPolylines: integer;
begin
result := objPolylines.Count;
end;
constructor THPGLDrawing.Create(filePath: string; rodicPanel: TObject; sizeFactor: double = 1);
var
f: TextFile;
riadok: string;
newFeaIndex: integer;
x,y: double;
separatorPos, riadokLength: byte;
begin
inherited Create;
objMinX := 9999999;
objMinY := 9999999;
objMaxX := -9999999;
objMaxY := -9999999;
objInternalPolylinePointer := 0;
objPolylines := TObjectList.Create;
if FileExists(filePath) then
try
newFeaIndex := -1;
AssignFile(f, filePath);
Reset(f);
while not EOF(f) do begin
Readln(f, riadok);
if Copy(riadok, 0, 2) = 'PU' then begin
separatorPos := Max(Pos(' ', riadok) , Pos(',', riadok)); // hladame separator X a Y suradnice - moze to byt aj ciarka a aj medzera, ak Pos nenajde, vracia nulu
riadokLength := Length(riadok);
x := StrToInt( Copy(riadok, 3, separatorPos-3));
y := StrToInt( Copy(riadok, separatorPos+1, (riadokLength-separatorPos-1)));
newFeaIndex := objPolylines.Add(TFeaturePolyLineObject.Create(rodicPanel));
(objPolylines.Items[newFeaIndex] as TFeaturePolyLineObject).AddVertex( x/40*sizeFactor, y/40*sizeFactor );
objMinX := Min(objMinX, x);
objMinY := Min(objMinY, y);
objMaxX := Max(objMaxX, x);
objMaxY := Max(objMaxY, y);
end;
if Copy(riadok, 0, 2) = 'PD' then begin
separatorPos := Max(Pos(' ', riadok) , Pos(',', riadok)); // hladame separator X a Y suradnice - moze to byt aj ciarka a aj medzera, ak Pos nenajde, vracia nulu
riadokLength := Length(riadok);
x := StrToInt( Copy(riadok, 3, separatorPos-3));
y := StrToInt( Copy(riadok, separatorPos+1, (riadokLength-separatorPos-1)));
(objPolylines.Items[newFeaIndex] as TFeaturePolyLineObject).AddVertex( x/40*sizeFactor, y/40*sizeFactor );
objMinX := Min(objMinX, x);
objMinY := Min(objMinY, y);
objMaxX := Max(objMaxX, x);
objMaxY := Max(objMaxY, y);
end;
end;
// ak na zaver ostal nejaky objekt polyline len s jednym bodom (napr.vytvoreny poslednym "Pen Up") tak ho zmazeme
if ((objPolylines.Items[newFeaIndex] as TFeaturePolyLineObject).VertexCount = 1) then
objPolylines.Delete(newFeaIndex);
finally
Close(f);
end;
objMinX := objMinX * sizeFactor;
objMinY := objMinY * sizeFactor;
objMaxX := objMaxX * sizeFactor;
objMaxY := objMaxY * sizeFactor;
end;
destructor THPGLDrawing.Destroy;
begin
FreeAndNil(objPolylines);
inherited Destroy;
end;
function THPGLDrawing.GetNextPolyline: TFeaturePolyLineObject;
begin
if objInternalPolylinePointer < objPolylines.Count then begin
result := (objPolylines.Items[objInternalPolylinePointer] as TFeaturePolyLineObject);
Inc(objInternalPolylinePointer);
end;
end;
function THPGLDrawing.objGetPolyline(Index: Integer): TFeaturePolyLineObject;
begin
//
end;
end.
|
unit SSPTypes;
interface uses SysUtils, Types, Classes;
type
ISSPAny = interface ['{E2D2281E-4B43-49D3-A059-02382B614F9B}']
function getType (): shortint ;
function toString (): WideString ;
function asUTF8String (): AnsiString ;
function asString (): WideString ;
function asInt (): int64 ;
function asInt8 (): shortint ;
function asInt16 (): smallint ;
function asInt32 (): longint ;
function asInt64 (): int64 ;
function asFloat (): double ;
function asFloat32 (): single ;
function asFloat64 (): double ;
function asDecimal (): double ;
function asDecimalString(): AnsiString ;
function asByteArray (): TByteDynArray;
function size (): integer ;
function insert ( index: integer ; value: ISSPAny): integer ; overload;
function add ( value: ISSPAny): integer ; overload;
function add (const name: WideString; value: ISSPAny): integer ; overload;
function update ( index: integer ; value: ISSPAny): ISSPAny ; overload;
function update (const name: WideString; value: ISSPAny): ISSPAny ; overload;
function remove ( index: integer ): ISSPAny ; overload;
function remove (const name: WideString ): ISSPAny ; overload;
function indexOf(const name: WideString ): integer ; overload;
function nameOf ( index: integer ): WideString; overload;
function item ( index: integer ): ISSPAny ; overload;
function item (const name: WideString ): ISSPAny ; overload;
procedure writeTo(dest: TStream); overload;
function equals (obj: IInterface): boolean; overload;
end;
ISSPAnyEntry = interface ['{1D0F32BD-2E60-4C2E-8534-65786547799E}']
function key (): WideString;
function value(): ISSPAny ;
end;
TSSPAbstractAny = class(TInterfacedObject, ISSPAny)
protected
function newAbstractError(): EAbstractError;
public
function getType (): shortint ; virtual; //abstract;
function toString (): WideString ; virtual; //abstract;
function asUTF8String (): AnsiString ; virtual; //abstract;
function asString (): WideString ; virtual; //abstract;
function asInt (): int64 ; virtual; //abstract;
function asInt8 (): shortint ; virtual; //abstract;
function asInt16 (): smallint ; virtual; //abstract;
function asInt32 (): longint ; virtual; //abstract;
function asInt64 (): int64 ; virtual; //abstract;
function asFloat (): double ; virtual; //abstract;
function asFloat32 (): single ; virtual; //abstract;
function asFloat64 (): double ; virtual; //abstract;
function asDecimal (): double ; virtual; //abstract;
function asDecimalString(): AnsiString ; virtual; //abstract;
function asByteArray (): TByteDynArray; virtual; //abstract;
function size (): integer ; virtual; //abstract;
function insert ( index: integer ; value: ISSPAny): integer ; overload; virtual; //abstract;
function add ( value: ISSPAny): integer ; overload; virtual; //abstract;
function add (const name: WideString; value: ISSPAny): integer ; overload; virtual; //abstract;
function update ( index: integer ; value: ISSPAny): ISSPAny ; overload; virtual; //abstract;
function update (const name: WideString; value: ISSPAny): ISSPAny ; overload; virtual; //abstract;
function remove ( index: integer ): ISSPAny ; overload; virtual; //abstract;
function remove (const name: WideString ): ISSPAny ; overload; virtual; //abstract;
function indexOf(const name: WideString ): integer ; overload; virtual; //abstract;
function nameOf ( index: integer ): WideString; overload; virtual; //abstract;
function item ( index: integer ): ISSPAny ; overload; virtual; //abstract;
function item (const name: WideString ): ISSPAny ; overload; virtual; //abstract;
procedure writeTo(dest: TStream); overload; virtual; //abstract;
function equals (obj: IInterface): boolean; overload; virtual; //abstract;
end;
TSSPString = class(TSSPAbstractAny)
protected
_value: WideString;
public
constructor create(const value: WideString);
function getType (): shortint ; override;
function toString (): WideString ; override;
function asUTF8String (): AnsiString ; override;
function asString (): WideString ; override;
function size (): integer ; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPInt = class(TSSPAbstractAny)
protected
_type : shortint;
_value: int64 ;
public
constructor create(value: int64); overload;
constructor create(type_: shortint; value: int64); overload;
function getType (): shortint ; override;
function toString (): WideString ; override;
function asInt (): int64 ; override;
function asInt8 (): shortint ; override;
function asInt16 (): smallint ; override;
function asInt32 (): longint ; override;
function asInt64 (): int64 ; override;
function asString (): WideString ; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPFloat = class(TSSPAbstractAny)
protected
_type : shortint;
_value: double ;
public
constructor create(value: double); overload;
constructor create(type_: shortint; value: double); overload;
function getType (): shortint ; override;
function toString (): WideString ; override;
function asFloat (): double ; override;
function asFloat32 (): single ; override;
function asFloat64 (): double ; override;
function asString (): WideString ; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPDecimal = class(TSSPAbstractAny)
protected
_value: AnsiString;
public
constructor create(const value: AnsiString);
function getType (): shortint ; override;
function toString (): WideString ; override;
function asDecimal (): double ; override;
function asDecimalString(): AnsiString ; override;
function asString (): WideString ; override;
function asUTF8String (): AnsiString ; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPByteArray = class(TSSPAbstractAny)
protected
_value: TByteDynArray;
public
constructor create(const value: TByteDynArray);
function getType (): shortint ; override;
function toString (): WideString ; override;
function asByteArray (): TByteDynArray; override;
function asUTF8String (): AnsiString ; override;
function size (): integer ; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPArray = class(TSSPAbstractAny)
protected
_value: IInterfaceList;
public
constructor create(); overload;
constructor create(const value: IInterfaceList); overload;
function getType (): shortint ; override;
function toString (): WideString ; override;
function size (): integer ; override;
function insert ( index: integer ; value: ISSPAny): integer ; overload; override;
function add ( value: ISSPAny): integer ; overload; override;
function update ( index: integer ; value: ISSPAny): ISSPAny ; overload; override;
function remove ( index: integer ): ISSPAny ; overload; override;
function item ( index: integer ): ISSPAny ; overload; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPObject = class(TSSPAbstractAny)
protected
_names : TStrings;
_values: IInterfaceList ;
public
constructor create();
destructor destroy; override;
function getType (): shortint ; override;
function toString (): WideString ; override;
function size (): integer ; override;
function add (const name: WideString; value: ISSPAny): integer ; overload; override;
function update ( index: integer ; value: ISSPAny): ISSPAny ; overload; override;
function update (const name: WideString; value: ISSPAny): ISSPAny ; overload; override;
function remove ( index: integer ): ISSPAny ; overload; override;
function remove (const name: WideString ): ISSPAny ; overload; override;
function indexOf(const name: WideString ): integer ; overload; override;
function nameOf ( index: integer ): WideString; overload; override;
function item ( index: integer ): ISSPAny ; overload; override;
function item (const name: WideString ): ISSPAny ; overload; override;
procedure writeTo(dest: TStream); override;
function equals (obj: IInterface): boolean; overload; override;
end;
TSSPAnyEntry = class(TInterfacedObject, ISSPAnyEntry)
protected
_key : WideString;
_value: ISSPAny ;
public
constructor create(const key_: WideString; value_: ISSPAny);
function key (): WideString;
function value(): ISSPAny ;
end;
function newInt ( value: int64 ): ISSPAny;
function newFloat ( value: double ): ISSPAny;
function newString (const value: WideString ): ISSPAny;
function newDecimal (const value: AnsiString ): ISSPAny;
function newByteArray(const value: TByteDynArray): ISSPAny;
function newEntry (const key : WideString ;
const value: ISSPAny ): ISSPAnyEntry;
function newArray (const values: array of ISSPAny ): ISSPAny;
function newObject (const values: array of ISSPAnyEntry): ISSPAny;
implementation uses SSPHelper;
function newAbstractError(): EAbstractError;
begin
result:= EAbstractError.create('Unsupported function');
end;
function TSSPAbstractAny.newAbstractError(): EAbstractError;
begin
result:= EAbstractError.create('Unsupported function in class: ' + className);
end;
function TSSPAbstractAny.getType (): shortint ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.toString (): WideString ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asUTF8String (): AnsiString ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asString (): WideString ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asInt (): int64 ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asInt8 (): shortint ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asInt16 (): smallint ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asInt32 (): longint ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asInt64 (): int64 ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asFloat (): double ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asFloat32 (): single ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asFloat64 (): double ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asDecimal (): double ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asDecimalString(): AnsiString ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.asByteArray (): TByteDynArray; begin raise newAbstractError(); end;
function TSSPAbstractAny.size (): integer ; begin raise newAbstractError(); end;
function TSSPAbstractAny.insert ( index: integer ; value: ISSPAny): integer ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.add ( value: ISSPAny): integer ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.add (const name: WideString; value: ISSPAny): integer ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.update ( index: integer ; value: ISSPAny): ISSPAny ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.update (const name: WideString; value: ISSPAny): ISSPAny ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.remove ( index: integer ): ISSPAny ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.remove (const name: WideString ): ISSPAny ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.indexOf(const name: WideString ): integer ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.nameOf ( index: integer ): WideString;
begin raise newAbstractError(); end;
function TSSPAbstractAny.item ( index: integer ): ISSPAny ;
begin raise newAbstractError(); end;
function TSSPAbstractAny.item (const name: WideString ): ISSPAny ;
begin raise newAbstractError(); end;
procedure TSSPAbstractAny.writeTo(dest: TStream);
begin raise newAbstractError(); end;
function TSSPAbstractAny.equals (obj: IInterface): boolean;
begin raise newAbstractError(); end;
constructor TSSPString.create(const value: WideString);
begin
inherited create;
_value:= value;
end;
function TSSPString.toString (): WideString ;
begin result:= '"' + _value + '"'; end;
procedure TSSPString.writeTo(dest: TStream);
begin TSSPHelper.writeString(dest, _value); end;
function TSSPString.equals (obj: IInterface): boolean;
var other: ISSPAny;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if getType() <> other.getType() then
exit;
result:= _value = other.asString();
end;
constructor TSSPInt.create(type_: shortint; value: int64);
begin
inherited create;
_type := type_;
_value:= value;
end;
constructor TSSPInt.create(value: int64);
begin
create(TSSPHelper.getTypeOf(value), value);
end;
procedure TSSPInt.writeTo(dest: TStream);
begin TSSPHelper.writeInt(dest, _value); end;
function TSSPInt.equals (obj: IInterface): boolean;
var other: ISSPAny;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if not(other.getType() in [SSP_TYPE_INT_8, SSP_TYPE_INT_16, SSP_TYPE_INT_32, SSP_TYPE_INT_64] ) then
exit;
result:= _value = other.asInt();
end;
constructor TSSPFloat.create(type_: shortint; value: double);
begin
inherited create;
_type := type_;
_value:= value;
end;
constructor TSSPFloat.create(value: double);
begin
create(TSSPHelper.getTypeOf(value), value);
end;
procedure TSSPFloat.writeTo(dest: TStream);
begin TSSPHelper.writeFloat(dest, _value); end;
function TSSPFloat.equals (obj: IInterface): boolean;
var other: ISSPAny;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if not(other.getType() in [SSP_TYPE_FLOAT_32, SSP_TYPE_FLOAT_64]) then
exit;
result:= _value = other.asFloat();
end;
constructor TSSPDecimal.create(const value: AnsiString);
begin
inherited create;
_value:= value;
end;
procedure TSSPDecimal.writeTo(dest: TStream);
begin TSSPHelper.writeDecimalString(dest, _value); end;
function TSSPDecimal.equals (obj: IInterface): boolean;
var other: ISSPAny;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if getType() <> other.getType() then
exit;
result:= _value = other.asDecimalString();
end;
constructor TSSPByteArray.create(const value: TByteDynArray);
begin
inherited create;
_value:= value;
end;
function TSSPByteArray.toString (): WideString ;
var temp: AnsiString;
begin
setLength(temp, size() * 2);
if 0 < size() then
binToHex(pansichar(@_value[0]), pansichar(temp), size());
result:= temp;
//result:= '<' + temp + '>';
end;
procedure TSSPByteArray.writeTo(dest: TStream);
begin
if 0 = length(_value) then
TSSPHelper.writeByteArray(dest, length(_value), nil) else
TSSPHelper.writeByteArray(dest, length(_value), @(_value[0]));
end;
function TSSPByteArray.equals (obj: IInterface): boolean;
var other: ISSPAny;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if getType() <> other.getType() then
exit;
if size() <> other.size() then
exit;
result:= (0 = size()) or compareMem(@_value[0], @((other.asByteArray())[0]), size());
end;
constructor TSSPArray.create(const value: IInterfaceList);
begin
inherited create;
_value:= value;
end;
constructor TSSPArray.create();
begin
create(TInterfaceList.create());
end;
function TSSPArray.toString (): WideString ;
var i: integer;
begin
result:= '[';
if 0 < size() then
begin
result:= result + item(0).toString();
for i:= 1 to size() - 1 do
result:= result + ', ' + item(i).toString();
end;
result:= result + ']';
end;
function TSSPArray.insert ( index: integer ; value: ISSPAny): integer ;
begin
_value.insert(index, value);
result:= index;
end;
function TSSPArray.add ( value: ISSPAny): integer ;
begin
result:= _value.add(value);
end;
function TSSPArray.update ( index: integer ; value: ISSPAny): ISSPAny ;
begin
result:= _value[index] as ISSPAny;
_value[index]:= value;
end;
function TSSPArray.remove ( index: integer ): ISSPAny ;
begin
result:= _value[index] as ISSPAny;
_value.delete(index);
end;
function TSSPArray.item ( index: integer ): ISSPAny ;
begin
result:= _value[index] as ISSPAny;
end;
procedure TSSPArray.writeTo(dest: TStream);
var i: integer;
begin
TSSPHelper.writeArray(dest, size());
for i:= 0 to size() - 1 do
item(i).writeTo(dest);
end;
function TSSPArray.equals (obj: IInterface): boolean;
var other: ISSPAny;
var i: integer;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if getType() <> other.getType() then
exit;
if size() <> other.size() then
exit;
for i:= 0 to size() - 1 do
if not item(i).equals(other.item(i)) then
exit;
result:= true;
end;
constructor TSSPObject.create();
begin
inherited create;
_names := TStringList.create();
_values:= TInterfaceList.create();
end;
destructor TSSPObject.destroy;
begin
inherited;
_names.free();
_names:= nil;
end;
function TSSPObject.toString (): WideString ;
var i: integer;
begin
result:= '{';
if 0 < size() then
begin
result:= result + '"' + nameOf(0) + '": ' + item(0).toString();
for i:= 1 to size() - 1 do
result:= result + ', "' + nameOf(i) + '": ' + item(i).toString();
end;
result:= result + '}';
end;
function TSSPObject.add (const name: WideString; value: ISSPAny): integer ;
var index: integer;
begin
index:= indexOf(name);
if 0 <= index then
begin
_values[index]:= value;
result:= index;
end
else
begin
_names.add(utf8encode(name));
result:= _values.add(value);
end;
end;
function TSSPObject.update ( index: integer ; value: ISSPAny): ISSPAny ;
begin
result:= _values[index] as ISSPAny;
_values[index]:= value;
end;
function TSSPObject.update (const name: WideString; value: ISSPAny): ISSPAny ;
begin
result:= update(indexOf(name), value);
end;
function TSSPObject.remove ( index: integer ): ISSPAny ;
begin
_names.delete(index);
result:= _values[index] as ISSPAny;
_values.delete(index);
end;
function TSSPObject.remove (const name: WideString ): ISSPAny ;
begin
result:= remove(indexOf(name));
end;
function TSSPObject.indexOf(const name: WideString ): integer ;
begin
result:= _names.indexOf(utf8encode(name));
end;
function TSSPObject.nameOf ( index: integer ): WideString;
begin
result:= utf8decode(_names[index]);
end;
function TSSPObject.item ( index: integer ): ISSPAny ;
begin
result:= _values[index] as ISSPAny;
end;
function TSSPObject.item (const name: WideString ): ISSPAny ;
var index: integer;
begin
index:= indexOf(name);
if index < 0 then
result:= nil else
result:= item(index);
end;
procedure TSSPObject.writeTo(dest: TStream);
var i: integer;
begin
TSSPHelper.writeObject(dest, size());
for i:= 0 to size() - 1 do
begin
TSSPHelper.writeField(dest, nameOf(i));
item(i).writeTo(dest);
end;
end;
function TSSPObject.equals (obj: IInterface): boolean;
var other: ISSPAny;
var i: integer;
begin
result:= false;
if not assigned(obj) then
exit;
if not supports(obj, ISSPAny, other) then
exit;
if getType() <> other.getType() then
exit;
if size() <> other.size() then
exit;
for i:= 0 to size() - 1 do
if not item(i).equals(other.item(nameOf(i))) then
exit;
result:= true;
end;
function TSSPString .getType (): shortint ;
begin result:= SSP_TYPE_STRING ; end;
function TSSPString .asUTF8String (): AnsiString ;
begin result:= utf8encode (_value); end;
function TSSPString .asString (): WideString ;
begin result:= _value ; end;
function TSSPString .size (): integer ;
begin result:= length (_value); end;
function TSSPInt .getType (): shortint ;
begin result:= _type ; end;
function TSSPInt .asInt (): int64 ;
begin result:= _value ; end;
function TSSPInt .asInt8 (): shortint ;
begin result:= _value ; end;
function TSSPInt .asInt16 (): smallint ;
begin result:= _value ; end;
function TSSPInt .asInt32 (): longint ;
begin result:= _value ; end;
function TSSPInt .asInt64 (): int64 ;
begin result:= _value ; end;
function TSSPInt .asString (): WideString ;
begin result:= intToStr (_value); end;
function TSSPInt .toString (): WideString ;
begin result:= asString ( ); end;
function TSSPFloat .getType (): shortint ;
begin result:= _type ; end;
function TSSPFloat .asFloat (): double ;
begin result:= _value ; end;
function TSSPFloat .asFloat32 (): single ;
begin result:= _value ; end;
function TSSPFloat .asFloat64 (): double ;
begin result:= _value ; end;
function TSSPFloat .asString (): WideString ;
begin result:= normalFloatToStr('#0.###', _value); end;
function TSSPFloat .toString (): WideString ;
begin result:= asString ( ); end;
function TSSPDecimal .getType (): shortint ;
begin result:= SSP_TYPE_DECIMAL ; end;
function TSSPDecimal .asDecimal (): double ;
begin result:= strToFloat (_value); end;
function TSSPDecimal .asDecimalString(): AnsiString ;
begin result:= _value ; end;
function TSSPDecimal .asString (): WideString ;
begin result:= utf8decode (_value); end;
function TSSPDecimal .asUTF8String (): AnsiString ;
begin result:= _value ; end;
function TSSPDecimal .toString (): WideString ;
begin result:= asString ( ); end;
function TSSPByteArray.getType (): shortint ;
begin result:= SSP_TYPE_BYTE_ARRAY; end;
function TSSPByteArray.asByteArray (): TByteDynArray;
begin result:= _value ; end;
function TSSPByteArray.asUTF8String (): AnsiString ;
begin
setLength(result, size());
if 0 < size() then
move(_value[0], result[1], size());
end;
function TSSPByteArray.size (): integer ;
begin result:= length( _value); end;
function TSSPArray .getType (): shortint ;
begin result:= SSP_TYPE_ARRAY ; end;
function TSSPArray .size (): integer ;
begin result:= _value .count ; end;
function TSSPObject .getType (): shortint ;
begin result:= SSP_TYPE_OBJECT ; end;
function TSSPObject .size (): integer ;
begin result:= _values.count ; end;
constructor TSSPAnyEntry.create(const key_: WideString; value_: ISSPAny);
begin
inherited create();
_key := key_ ;
_value:= value_;
end;
function TSSPAnyEntry.key (): WideString;
begin result:= _key ; end;
function TSSPAnyEntry.value(): ISSPAny ;
begin result:= _value; end;
function newInt ( value: int64 ): ISSPAny;
begin result:= TSSPInt .create(value); end;
function newFloat ( value: double ): ISSPAny;
begin result:= TSSPFloat .create(value); end;
function newString (const value: WideString ): ISSPAny;
begin result:= TSSPString .create(value); end;
function newDecimal (const value: AnsiString ): ISSPAny;
begin result:= TSSPDecimal .create(value); end;
function newByteArray(const value: TByteDynArray): ISSPAny;
begin result:= TSSPByteArray.create(value); end;
function newEntry (const key : WideString ;
const value: ISSPAny ): ISSPAnyEntry;
begin result:= TSSPAnyEntry.create(key, value); end;
function newArray (const values: array of ISSPAny ): ISSPAny;
var i: integer;
begin
result:= TSSPArray.create();
for i:= 0 to length(values) - 1 do
result.add(values[i]);
end;
function newObject (const values: array of ISSPAnyEntry): ISSPAny;
var i: integer;
begin
result:= TSSPObject.create();
for i:= 0 to length(values) - 1 do
result.add(values[i].key, values[i].value);
end;
end.
|
unit UFSearchBase;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Imaging.pngimage, Data.DB, Vcl.Grids, Vcl.DBGrids, UISearchController,
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, FireDAC.Phys.MongoDBDataSet,
UDMMongo, JvExDBGrids, JvDBGrid;
type
TFSearchBase = class(TForm)
pnlBackground: TPanel;
imgTitle: TImage;
lblTitle: TLabel;
pnlDividerTitle: TPanel;
edtTextSearch: TEdit;
imgBtnClose: TImage;
imgBtnSearch: TImage;
pnlButtonsDivider: TPanel;
imgBtnAdd: TImage;
imgBtnEdit: TImage;
imgBtnDelete: TImage;
pnlFilters: TPanel;
imgBtnFilter: TImage;
DSMain: TDataSource;
DSetMain: TFDMongoDataSet;
dbgrdData: TJvDBGrid;
procedure imgBtnCloseClick(Sender: TObject);
procedure imgBtnFilterClick(Sender: TObject);
procedure imgBtnSearchClick(Sender: TObject);
procedure imgBtnAddClick(Sender: TObject);
procedure imgBtnCloseMouseEnter(Sender: TObject);
procedure imgBtnCloseMouseLeave(Sender: TObject);
procedure imgBtnSearchMouseEnter(Sender: TObject);
procedure imgBtnSearchMouseLeave(Sender: TObject);
procedure imgBtnFilterMouseEnter(Sender: TObject);
procedure imgBtnFilterMouseLeave(Sender: TObject);
procedure imgBtnAddMouseEnter(Sender: TObject);
procedure imgBtnAddMouseLeave(Sender: TObject);
procedure imgBtnEditMouseEnter(Sender: TObject);
procedure imgBtnEditMouseLeave(Sender: TObject);
procedure imgBtnDeleteMouseLeave(Sender: TObject);
procedure imgBtnDeleteMouseEnter(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbgrdDataCellClick(Column: TColumn);
private
{ Private declarations }
protected
FController : ISearchController;
public
{ Public declarations }
procedure SetController(Controller : ISearchController);
end;
var
FSearchBase: TFSearchBase;
implementation
{$R *.dfm}
procedure TFSearchBase.dbgrdDataCellClick(Column: TColumn);
begin
imgBtnEdit.Enabled := (dbgrdData.SelectedRows.Count > 0);
imgBtnDelete.Enabled := (dbgrdData.SelectedRows.Count > 0);
end;
procedure TFSearchBase.FormShow(Sender: TObject);
begin
pnlFilters.Visible := False;
dbgrdData.Height := 440;
dbgrdData.Top := 81;
end;
procedure TFSearchBase.imgBtnAddClick(Sender: TObject);
begin
FController.Add;
end;
procedure TFSearchBase.imgBtnAddMouseEnter(Sender: TObject);
begin
imgBtnAdd.Picture.LoadFromStream(TResourceStream.Create(HInstance,'AddDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnAddMouseLeave(Sender: TObject);
begin
imgBtnAdd.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Add24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnCloseClick(Sender: TObject);
begin
FController.Close;
end;
procedure TFSearchBase.imgBtnCloseMouseEnter(Sender: TObject);
begin
imgBtnClose.Picture.LoadFromStream(TResourceStream.Create(HInstance,'CloseDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnCloseMouseLeave(Sender: TObject);
begin
imgBtnClose.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Close24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnDeleteMouseEnter(Sender: TObject);
begin
imgBtnDelete.Picture.LoadFromStream(TResourceStream.Create(HInstance,'DeleteDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnDeleteMouseLeave(Sender: TObject);
begin
imgBtnDelete.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Delete24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnEditMouseEnter(Sender: TObject);
begin
imgBtnEdit.Picture.LoadFromStream(TResourceStream.Create(HInstance,'EditDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnEditMouseLeave(Sender: TObject);
begin
imgBtnEdit.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Edit24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnFilterClick(Sender: TObject);
begin
if pnlFilters.Visible then
begin
pnlFilters.Visible := False;
dbgrdData.Height := 440;
dbgrdData.Top := 81;
end
else
begin
pnlFilters.Visible := True;
dbgrdData.Height := 393;
dbgrdData.Top := 128;
end;
end;
procedure TFSearchBase.imgBtnFilterMouseEnter(Sender: TObject);
begin
imgBtnFilter.Picture.LoadFromStream(TResourceStream.Create(HInstance,'FilterDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnFilterMouseLeave(Sender: TObject);
begin
imgBtnFilter.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Filter24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnSearchClick(Sender: TObject);
begin
FController.Search(edtTextSearch.Text);
end;
procedure TFSearchBase.imgBtnSearchMouseEnter(Sender: TObject);
begin
imgBtnSearch.Picture.LoadFromStream(TResourceStream.Create(HInstance,'SearchDark24px',RT_RCDATA));
end;
procedure TFSearchBase.imgBtnSearchMouseLeave(Sender: TObject);
begin
imgBtnSearch.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Search24px',RT_RCDATA));
end;
procedure TFSearchBase.SetController(Controller: ISearchController);
begin
FController := Controller;
end;
end.
|
unit caArrays;
{$INCLUDE ca.inc}
interface
uses
Classes,
SysUtils;
const
cByteSize = SizeOf(Byte);
type
PWord = ^Word;
//----------------------------------------------------------------------------
// TcaBitArray
//----------------------------------------------------------------------------
TcaBitArray = class(TObject)
private
// Private fields
FArray: PWord;
protected
public
// Create/Destroy
constructor Create(ASize: Int64);
destructor Destroy; override;
end;
//----------------------------------------------------------------------------
// TcaBitMatrix
//----------------------------------------------------------------------------
TcaBitMatrix = class(TObject)
private
// Private fields
FBitOffset: Byte;
FCols: Integer;
FRows: Integer;
FMatrix: PWord;
FWordPtr: PWord;
// Private methods
procedure UpdateBitPosition(ACol, ARow: Integer);
procedure Initialize;
// Property methods
function GetBit(ACol, ARow: Integer): Boolean;
procedure SetBit(ACol, ARow: Integer; const AValue: Boolean);
protected
public
// Create/Destroy
constructor Create(ACols, ARows: Integer);
destructor Destroy; override;
// Properties
property Bits[ACol, ARow: Integer]: Boolean read GetBit write SetBit;
end;
//----------------------------------------------------------------------------
// TcaNibbleArray
//----------------------------------------------------------------------------
TcaNibbleArray = class(TObject)
private
protected
public
end;
implementation
const
cWordSize = SizeOf(Word);
//----------------------------------------------------------------------------
// TcaBitArray
//----------------------------------------------------------------------------
constructor TcaBitArray.Create(ASize: Int64);
begin
inherited Create;
GetMem(FArray, ASize);
end;
destructor TcaBitArray.Destroy;
begin
FreeMem(FArray);
inherited;
end;
//----------------------------------------------------------------------------
// TcaBitMatrix
//----------------------------------------------------------------------------
// Create/Destroy
constructor TcaBitMatrix.Create(ACols, ARows: Integer);
begin
inherited Create;
FCols := ACols;
FRows := ARows;
Initialize;
end;
destructor TcaBitMatrix.Destroy;
begin
FreeMem(FMatrix);
inherited;
end;
// Private methods
procedure TcaBitMatrix.Initialize;
begin
GetMem(FMatrix, FCols * FRows div cByteSize);
end;
procedure TcaBitMatrix.UpdateBitPosition(ACol, ARow: Integer);
var
BitPos: Integer;
begin
BitPos := ARow * FCols + ACol;
FWordPtr := FMatrix;
Inc(FWordPtr, BitPos div cWordSize);
FBitOffset := BitPos mod cWordSize;
end;
// Property methods
function TcaBitMatrix.GetBit(ACol, ARow: Integer): Boolean;
begin
UpdateBitPosition(ACol, ARow);
Result := (FWordPtr^ and (1 shl FBitOffset)) <> 0;
end;
procedure TcaBitMatrix.SetBit(ACol, ARow: Integer; const AValue: Boolean);
begin
UpdateBitPosition(ACol, ARow);
FWordPtr^ := FWordPtr^ or (1 shl FBitOffset);
end;
end.
|
unit DialogUnit;
interface
uses Vcl.Dialogs, System.Classes, Winapi.Windows, System.IOUtils, Vcl.ExtDlgs;
{$WARN SYMBOL_PLATFORM OFF}
type
TFileOpenDialogClass = class of TFileOpenDialog;
TOpenDialogClass = class of TOpenDialog;
TOpenFolderDialog = class(TOpenDialog)
private
procedure DoOnShow(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
end;
TExcelFilesFolderOpenDialog = class(TOpenFolderDialog)
public
constructor Create(AOwner: TComponent); override;
end;
type
TDatabaselFilesFolderOpenDialog = class(TOpenFolderDialog)
public
constructor Create(AOwner: TComponent); override;
end;
type
TPDFFilesFolderOpenDialog = class(TOpenFolderDialog)
public
constructor Create(AOwner: TComponent); override;
end;
TDialog = class(TObject)
private
class var Instance: TDialog;
public
function AddManufacturerDialog(const AValue: String): Boolean;
function CreateNewDatabaseDialog: Boolean;
procedure AutoBindNotFoundDialog;
procedure AutoBindResultDialog(ACount: Integer);
function ClearTreeDialog: Boolean;
procedure BodyNotFoundDialog(const AValue: String);
procedure CategoryNotExist(const AExternalID: string);
procedure MethodNotImplemended;
procedure ComponentsDocFilesNotFound;
procedure ParametricTableNotFound;
function DeleteRecordsDialog(const AText: string): Boolean;
procedure ErrorMessageDialog(const AErrorMessage: String);
class function NewInstance: TObject; override;
function CreateFolderDialog(const AValue: String): Integer;
function ClearBasketDialog: Boolean;
function UpdateDataBaseDialog(AVer, AMaxVersion: Double): Boolean;
function UpdateDataBaseDialog2: Boolean;
function UseDefaultMinWholeSale(AMinWholeSale: Double): Integer;
procedure DirectoryNotExistDialog(const AValue: String);
procedure ExcelFilesNotFoundDialog;
procedure DollarOrEuroCourceUnknown;
procedure NoParametersForAnalog;
procedure DuplicateNotFound;
procedure FileNameNotContainCategoryID;
procedure ParamDuplicateNotFound(ATableName: string);
procedure ProducerNotFound(const AProducer: string);
function ShowDialog(AOpenDialogClass: TOpenDialogClass;
const AInitialDir, AInitialFileName: string;
var AFileName: String): Boolean;
function SaveDataDialog: Integer;
end;
TExcelFileOpenDialog = class(TOpenDialog)
public
constructor Create(AOwner: TComponent); override;
end;
TExcelFileSaveDialog = class(TSaveDialog)
public
constructor Create(AOwner: TComponent); override;
end;
TMyOpenPictureDialog = class(TOpenPictureDialog)
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses Vcl.Forms, System.SysUtils, Winapi.ShlObj,
Winapi.Messages, ProjectConst, System.Contnrs;
var
SingletonList: TObjectList;
function TDialog.AddManufacturerDialog(const AValue: String): Boolean;
begin
Result := Application.MessageBox
(PChar(Format('В справочнике производителей не найден производитель %s.' +
#13#10 + #13#10 + 'Добавить "%s" в справочник?', [AValue, AValue])),
'Добавление производителя', MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
function TDialog.CreateNewDatabaseDialog: Boolean;
begin
Result := Application.MessageBox
(PChar('В выбранной папке не найден файл базы данных.' + #13#10 + #13#10 +
'Создать пустую базу данных?'), 'Создание базы данных',
MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
procedure TDialog.AutoBindNotFoundDialog;
begin
Application.MessageBox
(PChar('В справочнике кратких описаний не найдено ни одной подходящей записи'),
'Результат автоматической привязки', MB_OK);
end;
procedure TDialog.AutoBindResultDialog(ACount: Integer);
begin
Application.MessageBox(PChar(Format('Прикреплено описаний: %d', [ACount])),
'Результат автоматического прикрепления', MB_OK);
end;
function TDialog.ClearTreeDialog: Boolean;
begin
Result := Application.MessageBox
(PChar('Перед загрузкой данных дерево категорий будет очищено' + #13#10 +
'Все компоненты будут удалены' + #13#10 + #13#10 + 'Продолжить?'),
'Загрузка дерева категорий', MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
procedure TDialog.BodyNotFoundDialog(const AValue: String);
begin
Application.MessageBox
(PChar(Format('В справочнике корпусов не найден корпус %s', [AValue])),
'Ошибка при заполнении корпуса', MB_OK + MB_ICONSTOP);
end;
procedure TDialog.CategoryNotExist(const AExternalID: string);
begin
Application.MessageBox
(PChar(Format('Категория с идентификатором %s отсутствует', [AExternalID])),
'Ошибка', MB_OK + MB_ICONINFORMATION);
end;
procedure TDialog.MethodNotImplemended;
begin
Application.MessageBox(PChar('Данная функция пока не реализована'), 'Ошибка',
MB_OK + MB_ICONSTOP);
end;
procedure TDialog.ComponentsDocFilesNotFound;
begin
Application.MessageBox(PChar('Не найдены файлы документации'),
'Ошибка при привязке файлов документации', MB_OK + MB_ICONSTOP);
end;
procedure TDialog.ParametricTableNotFound;
begin
Application.MessageBox(PChar('Не найдены табличные наименования параметров'),
'Выбранный файл не содержит табличных наименований параметров',
MB_OK + MB_ICONSTOP);
end;
function TDialog.DeleteRecordsDialog(const AText: string): Boolean;
begin
Result := Application.MessageBox(PWideChar(AText), 'Удаление',
MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
procedure TDialog.ErrorMessageDialog(const AErrorMessage: String);
begin
Application.MessageBox(PChar(AErrorMessage), 'Ошибка', MB_OK + MB_ICONSTOP);
end;
class function TDialog.NewInstance: TObject;
begin
if not Assigned(Instance) then
begin
Instance := TDialog(inherited NewInstance);
SingletonList.Add(Instance);
end;
Result := Instance;
end;
procedure TDialog.DirectoryNotExistDialog(const AValue: String);
begin
Application.MessageBox(PChar(Format('Директория %s не существует', [AValue])),
'Директория не существует', MB_OK + MB_ICONSTOP);
end;
function TDialog.CreateFolderDialog(const AValue: String): Integer;
begin
Result := Application.MessageBox(PChar(Format('%s', [AValue])),
'Папка не существует', MB_YESNO + MB_ICONQUESTION);
end;
function TDialog.ClearBasketDialog: Boolean;
begin
Result := Application.MessageBox
(PWideChar('Вы действительно хотите очистить корзину?'), 'Очистка корзины',
MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
function TDialog.UpdateDataBaseDialog(AVer, AMaxVersion: Double): Boolean;
Var
FS: TFormatSettings;
begin
FS.DecimalSeparator := '.';
Result := Application.MessageBox
(PChar(Format('Найдена база данных версии %s' + #13#10 + #13#10 +
'Необходимо обновить базу данных до версии %s.',
[FloatToStrF(AVer, ffGeneral, 1, 8, FS), FloatToStrF(AMaxVersion, ffGeneral,
1, 8, FS)])), 'Обновление базы данных', MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
function TDialog.UpdateDataBaseDialog2: Boolean;
begin
Result := Application.MessageBox(PChar('Необходимо обновить базу данных. Продолжить?'),
'Обновление базы данных', MB_YESNO + MB_ICONQUESTION) = IDYES;
end;
function TDialog.UseDefaultMinWholeSale(AMinWholeSale: Double): Integer;
begin
Assert(AMinWholeSale >= 0);
Result := Application.MessageBox
(PWideChar(Format('Применить минимальную отповую наценку %f%%?',
[AMinWholeSale])), 'Наценка', MB_YESNOCANCEL + MB_ICONQUESTION);
end;
procedure TDialog.ExcelFilesNotFoundDialog;
begin
Application.MessageBox(PChar('Не найдено ни одного Excel файла'),
PChar(sError), MB_OK + MB_ICONSTOP);
end;
procedure TDialog.DollarOrEuroCourceUnknown;
begin
Application.MessageBox(PChar('Не известен текущий курс Доллара или Евро'),
PChar(sError), MB_OK + MB_ICONSTOP);
end;
procedure TDialog.NoParametersForAnalog;
begin
Application.MessageBox
(PChar('Не найдено ни одного параметра для поиска аналога'), PChar(sError),
MB_OK + MB_ICONSTOP);
end;
procedure TDialog.DuplicateNotFound;
begin
Application.MessageBox(PChar('Не найдено ни одного дубликата'), PChar(sError),
MB_OK + MB_ICONSTOP);
end;
procedure TDialog.FileNameNotContainCategoryID;
begin
Application.MessageBox
(PChar('Имя файла не содержит идентификатора категории загрузки (или пробела)'),
PChar(sError), MB_OK + MB_ICONSTOP);
end;
procedure TDialog.ParamDuplicateNotFound(ATableName: string);
begin
Application.MessageBox(PChar(Format('Параметр %s не имеет дубликатов',
[ATableName])), PChar(sError), MB_OK + MB_ICONSTOP);
end;
procedure TDialog.ProducerNotFound(const AProducer: string);
begin
Application.MessageBox
(PWideChar(Format('В справочнике производителей не найден производитель %s',
[AProducer])), PWideChar('Не найден производитель'), MB_OK + MB_ICONSTOP);
end;
function TDialog.ShowDialog(AOpenDialogClass: TOpenDialogClass;
const AInitialDir, AInitialFileName: string; var AFileName: String): Boolean;
var
fod: TOpenDialog;
begin
AFileName := '';
fod := AOpenDialogClass.Create(nil);
try
if not AInitialFileName.IsEmpty then
fod.FileName := AInitialFileName;
if not AInitialDir.IsEmpty then
fod.InitialDir := AInitialDir;
Result := fod.Execute(Application.ActiveFormHandle);
if Result then
begin
AFileName := fod.FileName;
end;
finally
FreeAndNil(fod);
end;
end;
function TDialog.SaveDataDialog: Integer;
begin
Result := Application.MessageBox(PWideChar(sDoYouWantToSaveChanges),
PWideChar(sSaving), MB_YESNOCANCEL + MB_ICONQUESTION);
end;
{ TExcelFilesFolderOpenDialog }
constructor TExcelFilesFolderOpenDialog.Create(AOwner: TComponent);
begin
inherited;
Self.FileName := '*.xls;*.xlsx';
end;
{ TDatabaselFilesFolderOpenDialog }
constructor TDatabaselFilesFolderOpenDialog.Create(AOwner: TComponent);
begin
inherited;
Self.FileName := '*.db';
end;
{ TPDFFilesFolderOpenDialog }
constructor TPDFFilesFolderOpenDialog.Create(AOwner: TComponent);
begin
inherited;
Self.FileName := '*.pdf;*.gif;*.jpg;*.png;*.bmp';
end;
{ TOpenFolderDialog }
constructor TOpenFolderDialog.Create(AOwner: TComponent);
begin
inherited;
// указывая имя файла как маску заставляем фильтровать по нему
Options := Options + [ofNoValidate];
// Обработчик события OnShow
OnShow := DoOnShow;
end;
procedure TOpenFolderDialog.DoOnShow(Sender: TObject);
const
// Названия констант по ссылке в MSDN, значения в Dlgs.h и WinUser.h
stc3: Integer = $442; // Лэйбл к имени текущего файла
cmb13: Integer = $47C; // Комбобокс с именем текущего файла
edt1: Integer = $480; // Поле ввода с именем текущего файла
stc2: Integer = $441; // Лэйбл к комбобоксу
cmb1: Integer = $470; // Комбобокс со списком фильтров
var
fod: TOpenDialog;
H: THandle;
begin
fod := Sender as TOpenDialog;
if Assigned(fod) then
begin
H := GetParent(fod.Handle);
// убрать первую строку надпись имя файла, эдит ввода и комбобокс
SendMessage(H, WM_USER + 100 + 5, stc3, 0);
SendMessage(H, WM_USER + 100 + 5, cmb13, 0);
SendMessage(H, WM_USER + 100 + 5, edt1, 0);
// убрать вторую строку - фильтр
SendMessage(H, WM_USER + 100 + 5, cmb1, 0);
SendMessage(H, WM_USER + 100 + 5, stc2, 0);
end;
end;
{ TExcelFileOpenDialog }
constructor TExcelFileOpenDialog.Create(AOwner: TComponent);
begin
inherited;
Filter := 'Документы (*.xls, *.xlsx)|*.xls;*.xlsx|' + 'Все файлы (*.*)|*.*';
FilterIndex := 0;
Options := [ofFileMustExist];
end;
{ TExcelFileSaveDialog }
constructor TExcelFileSaveDialog.Create(AOwner: TComponent);
begin
inherited;
Filter := 'Документы (*.xls, *.xlsx)|*.xls;*.xlsx|' + 'Все файлы (*.*)|*.*';
FilterIndex := 0;
Options := [ofFileMustExist];
end;
{ TMyOpenPictureDialog }
constructor TMyOpenPictureDialog.Create(AOwner: TComponent);
begin
inherited;
Filter := 'Изображения и pdf файлы (*.jpg,*.jpeg,*.gif,*.png,*.pdf)|*.jpg;*.jpeg;*.gif;*.png;*.pdf|'
+ 'Изображения (*.jpg,*.jpeg,*.gif,*.png,*.tif)|*.jpg;*.jpeg;*.gif;*.png;*.tif|'
+ 'Документы (*.pdf, *.doc, *.hmtl)|*.pdf;*.doc;*.hmtl|' +
'Все файлы (*.*)|*.*';
FilterIndex := 0;
Options := [ofFileMustExist];
end;
initialization
SingletonList := TObjectList.Create(True);
finalization
FreeAndNil(SingletonList);
end.
|
(* three.pas *)
(* Three Card Game Paradox *)
(* by Conor Gilmer *)
program three;
var
winning, chosen, remove:integer;
stick, twist, games, num, numRand, numA, numB, numC:cardinal;
stickR, twistR, gamesR:real;
stickpc, twistpc:real;
letter:char;
(* return a random card a number between 1 and 3 *)
function randomcard(cards:integer) : integer;
var
rvar:integer;
begin
numRand := numRand +1;
randomize;
rvar := random(cards) + 1;
(* writeln('random = ', rvar);*)
if rvar = 1 then
begin
numA := numA +1;
end
else if rvar = 2 then
begin
numB := numB +1;
end
else if rvar = 3 then
begin
numC := numC +1;
end
else
writeln('randomizer malfunctioned');
randomcard := rvar;
end;
(* play a game of selecting from three cards *)
procedure play;
begin
winning := randomcard(3);
chosen := randomcard(3);
repeat
remove := randomcard(3);
until (remove <> winning) and (remove <> chosen);
writeln('Game: ', num,' - winning = ', winning, ' | chosen = ', chosen, ' | remove = ', remove );
if winning = chosen then
begin
stick := stick + 1;
end
else
twist := twist + 1;
end;
(* Main Program Three Card Paradox *)
begin
games := 100;
writeln('Three Card Game Paradox');
for num :=1 to games do
play;
writeln('Results:');
stickR := stick;
twistR := twist;
gamesR := games;
stickpc := (stickR/gamesR) *100.0;
twistpc := (twistR/gamesR) *100.0;
writeln('Game played ', games, ' times');
writeln('Sticking wins ', stick, ' times (', stickpc:2:2, '%)');
writeln('Changing wins ', twist, ' times (', twistpc:2:2, '%)');
writeln('Verdict:');
if stick < twist then
begin
writeln('Twisting wins more!');
end
else
writeln('Sticking wins more!');
writeLn('The End.');
writeln;
writeln('How Random is the Randomizer?');
writeln('Randomizer called ', numRand, ' times');
writeln('A chosen ', numA, ' times(',((numA/numRand)*100):2:2,'%)');
writeln('B chosen ', numB, ' times(',((numB/numRand)*100):2:2,'%)');
writeln('C chosen ', numC, ' times(',((numC/numRand)*100):2:2,'%)');
writeLn('End of Randomizer analysis.');
end.
|
unit Updater;
interface
uses Classes, SysUtils, ExtCtrls, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP;
type
TStrArray = array of string;
TUpdater = class
private
IdHTTP: TIdHttp;
FCurVersion: string;
FNewVersion: string;
FVersionIndexURI: string;
FFilesList: TStringList;
FLogFile: string;
FUserName: string;
FPassword: string;
FTimer: TTimer;
FUpdateInterval: cardinal;
FSelfTimer: boolean;
FChecked: boolean;
procedure TimerProc(Sender: TObject);
procedure AddLog(LogString: string);
procedure SplitStr(const Str: string; const Sym: string; var Data: TstrArray);
function ProcessMessage: boolean;
function UpdateSelfExe: integer;
procedure SetUserName(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUpdateInterval(const Value: cardinal);
procedure SetSelfTimer(const Value: boolean);
procedure SetCurrentVersion(const Value: string);
procedure SetVersionIndexURI(const Value: string);
function GetNewVersionNo: string;
function GetEnvironmentString(Str: string): string;
public
constructor Create;
destructor Destroy; override;
function UpdateFiles: integer;
property LogFilename: string read FLogFile write FLogFile;
property VersionIndexURI: string read FVersionIndexURI write SetVersionIndexURI;
property FilesList: TStringList read FFilesList;
property Username: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property CurrentVersion: string read FCurVersion write SetCurrentVersion;
property NewVersion: string read GetNewVersionNo write FNewVersion;
property SelfTimer: boolean read FSelfTimer write SetSelfTimer;
property Checked: boolean read FChecked;
property UpdateInterval: cardinal read FUpdateInterval write SetUpdateInterval;
end;
implementation
uses StrUtils, ShellProcess, ShellApi, Windows, Messages;
constructor TUpdater.Create;
var
tmp_exe: string;
begin
FLogFile := ChangeFileExt(ParamStr(0), '.log');
UpdateSelfExe;
tmp_exe := ExtractFilePath(ParamStr(0)) + 'tmp_' + ExtractFileName(ParamStr(0));
if FileExists(tmp_exe) then
begin
Sleep(2000);
DeleteFile(PChar(tmp_exe));
end;
FCurVersion := '';
FNewVersion := '';
FVersionIndexURI := '';
IdHTTP := TIdHTTP.Create;
IdHTTP.Request.UserAgent := ExtractFileName(ParamStr(0));
FFilesList := TStringList.Create;
FTimer := TTimer.Create(nil);
FUpdateInterval := 1000;
FTimer.Interval := FUpdateInterval;
FSelfTimer := False;
FChecked := False;
FTimer.Enabled := FSelfTimer;
FTimer.OnTimer := TimerProc;
end;
function TUpdater.GetEnvironmentString(Str: string): string;
var
dest: PChar;
begin
dest := AllocMem(1024);
ExpandEnvironmentStrings(PChar(Str), dest, 1024);
result := dest;
end;
procedure TUpdater.SetCurrentVersion(const Value: string);
begin
FCurVersion := Value;
IdHTTP.Request.UserAgent := ExtractFileName(ParamStr(0)) + ' v.' + FCurVersion;
end;
procedure TUpdater.SetVersionIndexURI(const Value: string);
begin
FVersionIndexURI := Value;
IdHTTP.URL.URI := FVersionIndexURI;
end;
destructor TUpdater.Destroy;
begin
inherited;
FFilesList.Free;
IdHTTP.Free;
FTimer.Free;
end;
procedure TUpdater.SetSelfTimer(const Value: boolean);
begin
FSelfTimer := Value;
FTimer.Enabled := FSelfTimer;
end;
procedure TUpdater.TimerProc(Sender: TObject);
begin
if GetNewVersionNo > FCurVersion then
UpdateFiles;
end;
procedure TUpdater.SplitStr(const Str: string; const Sym: string; var Data: TStrArray);
var
s: string;
p, l: integer;
tmp: string;
begin
l := length(Sym);
SetLength(Data, 0);
s := lowercase(trim(str));
while (length(s) > 0) do
begin
p := pos(sym, s);
if (p > 0) then
begin
tmp := trim(copy(s, 1, p + l - 2));
if length(tmp) > 0 then
begin
SetLength(Data, Length(Data) + 1);
Data[length(Data) - 1] := Tmp;
end;
Delete(s, 1, p);
end
else
begin
if length(s) > 0 then
begin
SetLength(Data, Length(Data) + 1);
Data[length(Data) - 1] := s;
s := '';
end;
end;
end;
end;
procedure TUpdater.SetUpdateInterval(const Value: cardinal);
begin
FUpdateInterval := Value;
FTimer.Interval := FUpdateInterval;
end;
procedure TUpdater.SetUserName(const Value: string);
begin
FUserName := Value;
IdHTTP.Request.BasicAuthentication := True;
IdHTTP.Request.Username := FUserName;
end;
procedure TUpdater.SetPassword(const Value: string);
begin
FPassword := Value;
IdHTTP.Request.BasicAuthentication := True;
IdHTTP.Request.Password := FPassword;
end;
function TUpdater.GetNewVersionNo: string;
begin
try
try
FFilesList.Text := IdHTTP.Get(FVersionIndexURI);
Result := FFilesList[0];
FFilesList.Delete(0);
FChecked := True;
except
Result := '';
FFilesList.Clear;
Exit;
end;
finally
IdHTTP.Disconnect;
end;
end;
function TUpdater.UpdateFiles: integer;
var
response: TMemoryStream;
i, j, k: integer;
fileDir: string;
dfile, sfile, param, new_exe, new_exe_param: string;
depended: TStrArray;
ASource: TMemoryStream;
begin
if FFilesList.Count = 0 then
Exit;
fileDir := ExtractFilePath(ParamStr(0));
new_exe := '';
Result := 0;
response := TMemoryStream.Create;
ASource := TMemoryStream.Create;
try
for i := 0 to FFilesList.Count - 1 do
begin
SplitStr(FFilesList[i], ';', depended);
try
for j := 0 to Length(depended) - 1 do
begin
param := '';
sfile := Trim(depended[j]);
k := Pos(' ', sfile);
if k > 0 then
begin
param := Copy(sfile, k + 1, Length(sfile) - k);
sfile := Copy(sfile, 1, k - 1);
end;
dfile := filedir + AnsiReplaceStr(sfile, '/', '\');
AddLog('Try to update file: ' + dfile);
try
try
IdHTTP.Post('http://' + IdHTTP.URL.Host + ':' +
IdHTTP.URL.Port + IdHTTP.URL.Path + sfile, ASource, response);
Inc(Result);
except
AddLog('Error get file: ' + dfile);
Continue;
end;
try
if LowerCase(ExtractFileName(dfile)) =
LowerCase(ExtractFileName(ParamStr(0))) then
begin
dfile := ExtractFilePath(dfile) + 'tmp_' + ExtractFileName(dfile);
new_exe := dfile;
new_exe_param := param;
end
else if (Pos('.exe', dfile) <> 0) then
begin
if KillTask(LowerCase(ExtractFileName(dfile))) = 0 then
Sleep(1000);
end;
response.SaveToFile(dfile);
except
AddLog('Error create file: ' + dfile);
Dec(Result);
Continue;
end
finally
response.Clear;
IdHTTP.Disconnect;
ProcessMessage;
end;
end;
for j := 0 to Length(depended) - 1 do
begin
param := '';
sfile := Trim(depended[j]);
k := Pos(' ', sfile);
if k > 0 then
begin
param := Copy(sfile, k + 1, Length(sfile) - k);
sfile := Copy(sfile, 1, k - 1);
end;
dfile := filedir + AnsiReplaceStr(sfile, '/', '\');
if (Pos('.exe', dfile) <> 0) and (LowerCase(ExtractFileName(dfile)) <>
LowerCase(ExtractFileName(ParamStr(0)))) or (LowerCase(param) = 'exec') then
begin
ShellExecute(0, 'open', PChar(dfile), PChar(Param),
PChar(ExtractFilePath(dfile)), SW_HIDE);
end;
end;
except
AddLog('Error create files');
Dec(Result);
Continue;
end;
if LowerCase(ExtractFileName(new_exe)) = LowerCase('tmp_' +
ExtractFileName(ParamStr(0))) then
begin
ShellExecute(0, 'open', PChar(new_exe), PChar(new_exe_param),
PChar(ExtractFilePath(new_exe)), SW_HIDE);
ProcessTerminate(GetCurrentProcessId);
end;
end;
finally
ASource.Free;
response.Free;
SetLength(depended, 0);
end;
end;
function TUpdater.UpdateSelfExe: integer;
var
p, i: integer;
apName: string;
params: string;
begin
p := Pos('tmp_', LowerCase(ExtractFileName(ParamStr(0))));
if p <> 0 then
begin
Params := '';
for i := 1 to ParamCount do
Params := ParamStr(i) + ' ';
apName := copy(ExtractFileName(ParamStr(0)), p + length('tmp_'),
Length(ExtractFileName(ParamStr(0))) - (p + length('tmp_')) + 1);
if KillTask(LowerCase(apname)) = 0 then
Sleep(1000);
CopyFile(PChar(ParamStr(0)), PChar(ExtractFilePath(ParamStr(0)) + apname), False);
ShellExecute(0, 'open', PChar(ExtractFilePath(ParamStr(0)) + apname),
PChar(params), PChar(ExtractFilePath(ParamStr(0))), SW_HIDE);
ProcessTerminate(GetCurrentProcessId);
end;
end;
procedure TUpdater.AddLog(LogString: string);
var
F: TFileStream;
PStr: PChar;
Str: string;
LengthLogString: cardinal;
begin
Str := DateTimeToStr(Now()) + ': ' + LogString + #13#10;
LengthLogString := Length(Str);
try
if FileExists(FLogFile) then
F := TFileStream.Create(FLogFile, fmOpenWrite)
else
begin
ForceDirectories(ExtractFileDir(FLogFile));
F := TFileStream.Create(FLogFile, fmCreate);
end;
except
Exit;
end;
PStr := StrAlloc(LengthLogString + 1);
try
try
StrPCopy(PStr, Str);
F.Position := F.Size;
F.Write(PStr^, LengthLogString);
except
Exit;
end;
finally
StrDispose(PStr);
F.Free;
end;
end;
function TUpdater.ProcessMessage: boolean;
function IsKeyMsg(var Msg: TMsg): boolean;
const
CN_BASE = $BC00;
var
Wnd: HWND;
begin
Result := False;
with Msg do
if (Message >= WM_KEYFIRST) and (Message <= WM_KEYLAST) then
begin
Wnd := GetCapture;
if Wnd = 0 then
begin
Wnd := HWnd;
if SendMessage(Wnd, CN_BASE + Message, WParam, LParam) <> 0 then
Result := True;
end
else
if (longword(GetWindowLong(Wnd, GWL_HINSTANCE)) = HInstance) then
if SendMessage(Wnd, CN_BASE + Message, WParam, LParam) <> 0 then
Result := True;
end;
end;
var
Msg: TMsg;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
if Msg.Message <> WM_QUIT then
if not IsKeyMsg(Msg) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
end.
|
unit FrameForm; // contains the individual frame display
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TfmFrame = class(TFrame)
lblScore: TLabel;
lblBall1: TLabel;
bvl1: TBevel;
Bevel1: TBevel;
lblBall2: TLabel;
lblBall3: TLabel;
shp: TShape;
lblTotal: TLabel;
Bevel2: TBevel;
private
{ Private declarations }
public
procedure Populate(AScore, ATotal: integer; b1, b2, b3: string);
procedure Blank;
end;
implementation
{$R *.dfm}
{ TfmFrame }
procedure TfmFrame.Blank;
begin
lblScore.Caption := '';
lblBall1.Caption := '';
lblBall2.Caption := '';
lblBall3.Caption := '';
lblTotal.Caption := '';
end;
procedure TfmFrame.Populate(AScore, ATotal: integer; b1, b2, b3: string);
begin
lblScore.Caption := IntToStr(AScore);
lblTotal.Caption := IntToStr(ATotal + AScore);
lblBall1.Caption := b1;
lblBall2.Caption := b2;
lblBall3.Caption := b3;
end;
end.
|
unit uGameItems;
interface
uses
Classes, SysUtils,
uHTMLParser;
type
TPlanetType = (ptPlanet = 1, ptMoon = 3, ptCrashField = 2);
TGameCoords = record
Galaxy: integer;
System: integer;
Planet: integer;
PlType: TPlanetType;
procedure Clear;
procedure Inc; overload;
procedure Inc(GM, GP, SM, SP, PM, PP, cnt: integer); overload;
function Equal(c: TGameCoords): boolean;
function ToStr: string;
function FromStr(s: string): boolean;
end;
TIntAttribRec = packed record
Name: string;
Value: int64;
end;
TGameRes = packed record
Metal,
Crystal,
Deiterium: int64;
procedure Clear;
procedure Add(r: TGameRes); overload;
procedure Add(r: TGameRes; m: int64); overload;
procedure Sub(r: TGameRes);
procedure Mul(m: int64);
function Eq0: boolean;
function MoreThan(r: TGameRes): boolean;
function EkvResSumm: int64;
function ResSumm: int64;
procedure NormalizeLow(mark: int64);
end;
TLockResRec = packed record
StrategyID: integer;
Res: TGameRes;
LockFrom,
LockTo: TDateTime;
procedure Clear;
end;
TGameItem = packed record
ID: integer;
GroupName,
Name: string;
Level: integer;
BuildRes: TGameRes;
BuildTime: TDateTime;
Tag: int64;
procedure Clear;
end;
TGameItems = array of TGameItem;
TShip = packed record
ID: integer;
Name: string;
Tag: string;
Count: integer;
BuildRes: TGameRes;
BuildTime: TDateTime;
BuildMaxCount: integer;
procedure Clear;
end;
TShips = array of TShip;
TWorkPlan = packed record
Active: boolean;
Item: TGameItem;
NeedRes: TGameRes;
EndPlaningDate: TDateTime;
procedure Clear;
end;
TFleetOrder = (foNone = 0, foAtack=1, foTransport=3, foLeave=4, foState=5,
foSpy=6, foColonize=7, foRecycle=8, foDarkMateryMine = 11, foExpedition = 15);
TFleetOrderArr = array of TIntAttribRec;
TBuildCmd = (bcInsert, bcDestroy);
TCalc = class
class function ShipsBuildCost(Fleet: TFleetOrderArr): TGameRes;
class function ShipsBuildEstim(Fleet: TFleetOrderArr): TDateTime;
class function CutFleet(Fleet: TFleetOrderArr; Res: TGameRes): boolean;
class function UpdateShipBook(ships: TShips): boolean;
class function UpdateBuildingBook(ships: TGameItems): boolean;
end;
TPlanet = class
protected
FAttr: array of TIntAttribRec;
FBuildingShipsEndDT: TDateTime;
FBuildingShips: TFleetOrderArr;
FBuildingBuilds: TGameItems;
FLockResources: TLockResRec;
public
ID: int64;
Name: string;
Coords: TGameCoords;
MaxFields,
CurFields: integer;
CurRes: TGameRes;
Energy,
FreeEnergy: int64;
isMoon: boolean;
BuildingPlan: TWorkPlan;
serial: cardinal;
UpdateDT: TDateTime;
constructor Create;
procedure Clear;
procedure UpdateAttr(AName: string; AValue: int64);
procedure FinishUpdate;
function FreeFieldsCount: integer;
procedure SetBuildingShips(Fleet: TFleetOrderArr; BuildEstimate: TDateTime = 0);
procedure UpdateFromShipYard(ships: TShips);
function GetShipsCount(name: string; CountCurrent, CountBuilding: boolean): int64;
function ShipsBuilding: boolean;
function StrShipsBuilding: string;
procedure SetBuildingBuilds(Builds: TGameItems);
procedure UpdateFromBuildings(builds: TGameItems);
function GetBuildLevel(name: string): integer;
function BuildsBuilding: boolean;
function StrBuildsBuilding: string;
function HaveResources(res: TGameRes): boolean;
function isResoucesLocked: boolean;
function LockResources(StrategyID: integer; res: TGameRes; LockLen: TDateTime = 0): boolean;
end;
TImperium = class
protected
FPlanets: array of TPlanet;
FResearch: array of TIntAttribRec;
FResearching: TGameItems;
public
Valid: boolean;
LastUpdate: TDateTime;
DarkMatery: int64;
MaxExpedition,
CurExpedition,
MaxFleets,
CurFleets: integer;
ResearchingPlan: TWorkPlan;
constructor Create;
procedure Clear;
procedure ClearPlanets;
procedure ClearResearch;
procedure UpdateResearchLevel(Name: string; Level: integer);
procedure UpdateResearchList(resch: TGameItems);
function GetResearchLevel(Name: string): integer;
function ResearchCount: integer;
function AddPlanet(ID: int64): TPlanet;
function GetOrCreatePlanet(ID: int64): TPlanet;
procedure DeletePlanets(serial: cardinal = 0);
function GetPlanet(ID: int64): TPlanet;
function GetPlanetIndx(ID: int64): integer;
function GetPlanetI(indx: integer): TPlanet;
function GetPlanetC(coords: TGameCoords; isMoon: boolean = false): TPlanet;
procedure UpdatePlanetAttr(ID: int64; Name: string; Value: integer);
function PlanetsCount(CountMoons: boolean = true): integer;
function MoonsCount: integer;
function MaxPlanetsCount: integer;
function PlanetHaveResources(ID: int64; res: TGameRes): boolean;
function PlanetCanBuild(PlanetID: int64; name: string): boolean;
function UpdateResearching(resch: TGameItems): boolean;
function StrResearching: string;
function StrResearcPlan: string;
function CanResearch(name: string): boolean;
function MakeResearch: boolean;
end;
TUser = class
protected
public
ID: int64;
Name,
MainPlanetName: string;
MainPlanetCoords: TGameCoords;
Alliance: string;
Score: int64;
end;
TUserList = array of TUser;
TGalaxyMapMove = (gmvNone, gmvGalaxyLeft, gmvGalaxyRight, gmvSystemLeft, gmvSystemRight);
TEnemyPlanet = packed record
Coords: TGameCoords;
Name: string;
UserID: int64;
isEmpty,
HaveMoon,
HaveCrashField: boolean;
procedure Clear;
end;
TPlanetSystem = array of TEnemyPlanet;
TGalaxy = class
protected
public
end;
const
GalaxyMapMoveStr: array [gmvNone .. gmvSystemRight] of string = (
'',
'galaxyLeft',
'galaxyRight',
'systemLeft',
'systemRight');
BuildCmdStr: array [bcInsert .. bcDestroy] of string = (
'insert',
'destroy');
implementation
uses
uDB;
{ TImperium }
function TImperium.GetOrCreatePlanet(ID: int64): TPlanet;
begin
Result := GetPlanet(ID);
if Result = nil then
Result := AddPlanet(ID);
end;
function TImperium.AddPlanet(ID: int64): TPlanet;
begin
SetLength(FPlanets, length(FPlanets) + 1);
FPlanets[length(FPlanets) - 1] := TPlanet.Create;
FPlanets[length(FPlanets) - 1].ID := ID;
Result := FPlanets[length(FPlanets) - 1];
end;
function TImperium.CanResearch(name: string): boolean;
var
dep: TGameItems;
i: integer;
begin
Result := false;
if MakeResearch then exit;
Result := true;
dep := TMoonDB.GetInstance.GetTechDeps(name);
for i := 0 to length(dep) - 1 do
if (dep[i].GroupName = 'Исследования') and
(GetResearchLevel(dep[i].Name) < dep[i].Level) then
begin
Result := false;
exit;
end;
end;
procedure TImperium.Clear;
begin
Valid := false;
LastUpdate := 0;
DarkMatery := 0;
MaxExpedition := 0;
CurExpedition := 0;
MaxFleets := 0;
CurFleets := 0;
ClearPlanets;
ClearResearch;
ResearchingPlan.Clear;
end;
procedure TImperium.ClearPlanets;
var
i: integer;
begin
for i := 0 to length(FPlanets) - 1 do
if FPlanets[i] <> nil then FPlanets[i].Free;
SetLength(FPlanets, 0);
end;
procedure TImperium.ClearResearch;
begin
SetLength(FResearch, 0);
SetLength(FResearching, 0);
end;
constructor TImperium.Create;
begin
inherited;
Clear;
end;
procedure TImperium.DeletePlanets(serial: cardinal);
var
i,
j: Integer;
begin
for i := length(FPlanets) - 1 downto 0 do
if FPlanets[i].serial <> serial then
begin
FPlanets[i].Free;
for j := i to length(FPlanets) - 2 do
FPlanets[j] := FPlanets[j + 1];
SetLength(FPlanets, length(FPlanets) - 1);
end;
end;
function TImperium.GetPlanet(ID: int64): TPlanet;
var
i: integer;
begin
Result := nil;
for i := 0 to length(FPlanets) - 1 do
if (FPlanets[i].ID = ID) then
begin
Result := FPlanets[i];
break;
end;
end;
function TImperium.GetPlanetC(coords: TGameCoords; isMoon: boolean = false): TPlanet;
var
i: integer;
begin
Result := nil;
for i := 0 to length(FPlanets) - 1 do
if (FPlanets[i].Coords.Equal(coords)) and (FPlanets[i].isMoon = isMoon) then
begin
Result := FPlanets[i];
break;
end;
end;
function TImperium.GetPlanetI(indx: integer): TPlanet;
begin
Result := nil;
if (indx >= 0) and (indx < length(FPlanets)) then
Result := FPlanets[indx];
end;
function TImperium.GetPlanetIndx(ID: int64): integer;
var
i: integer;
begin
Result := -1;
for i := 0 to length(FPlanets) - 1 do
if (FPlanets[i].ID = ID) then
begin
Result := i;
break;
end;
end;
function TImperium.GetResearchLevel(Name: string): integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to length(FResearch) - 1 do
if FResearch[i].Name = Name then
begin
Result := FResearch[i].Value;
break;
end;
end;
function TImperium.MakeResearch: boolean;
var
i: Integer;
begin
Result := false;
for i := 0 to length(FResearching) - 1 do
if FResearching[i].BuildTime > Now then
begin
Result := true;
exit;
end;
end;
function TImperium.MaxPlanetsCount: integer;
begin
Result := GetResearchLevel('Астрофизика');
if Result = 0 then Result := 20;
if Result > 20 then Result := 20;
end;
function TImperium.MoonsCount: integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to length(FPlanets) - 1 do
if FPlanets[i].isMoon then
Result := Result + 1;
end;
function TImperium.PlanetCanBuild(PlanetID: int64; name: string): boolean;
var
pl: TPlanet;
dep: TGameItems;
i: Integer;
begin
Result := true;
pl := GetPlanet(PlanetID);
if pl = nil then exit;
// не застраивать планеты до упора
if (name <> 'Терраформер') and
(name <> 'Лунная база') and
(pl.FreeFieldsCount < 2) then
begin
Result := false;
exit;
end;
// при проведении исследований нельзя строить лабораторию и технополис
if ((name = 'Исследовательская лаборатория') or
(name = 'Технополис')) and
(MakeResearch) then
begin
Result := false;
exit;
end;
// при строительстве кораблей нельзя строить верфь и нанитку
if ((name = 'Верфь') or
(name = 'Фабрика нанитов')) and
(pl.ShipsBuilding) then
begin
Result := false;
exit;
end;
// нельзя строить то, что невозможно построить по дереву технологий
dep := TMoonDB.GetInstance.GetTechDeps(name);
for i := 0 to length(dep) - 1 do
if (dep[i].GroupName = 'Постройки') and
(pl.GetBuildLevel(dep[i].Name) < dep[i].Level) or
(dep[i].GroupName = 'Исследования') and
(GetResearchLevel(dep[i].Name) < dep[i].Level)
then
begin
Result := false;
exit;
end;
end;
function TImperium.PlanetHaveResources(ID: int64; res: TGameRes): boolean;
var
pl: TPlanet;
begin
Result := false;
pl := GetPlanet(ID);
if pl = nil then exit;
Result := pl.HaveResources(res);
end;
function TImperium.PlanetsCount(CountMoons: boolean = true): integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to length(FPlanets) - 1 do
if not FPlanets[i].isMoon or CountMoons then
Result := Result + 1;
end;
function TImperium.ResearchCount: integer;
begin
Result := length(FResearch);
end;
function TImperium.StrResearching: string;
var
i: integer;
begin
if Length(FResearching) = 0 then
begin
Result := 'none';
exit;
end;
Result := '';
for i := 0 to length(FResearching) - 1 do
Result := Result + FResearching[i].Name + ' ' +
DateTimeToStr(FResearching[i].BuildTime) + ' ';
end;
function TImperium.StrResearcPlan: string;
begin
if ResearchingPlan.EndPlaningDate < Now then
begin
Result := 'none';
exit;
end;
Result := ResearchingPlan.Item.Name + ' ' +
DateTimeToStr(ResearchingPlan.EndPlaningDate);
end;
function TImperium.UpdateResearching(resch: TGameItems): boolean;
begin
Result := true;
FResearching := resch;
end;
procedure TImperium.UpdatePlanetAttr(ID: int64; Name: string; Value: integer);
var
vPlanet: TPlanet;
begin
vPlanet := GetPlanet(ID);
if vPlanet = nil then exit;
vPlanet.UpdateAttr(Name, Value);
end;
procedure TImperium.UpdateResearchLevel(Name: string; Level: integer);
var
i: integer;
begin
for i := 0 to length(FResearch) - 1 do
if FResearch[i].Name = Name then
begin
FResearch[i].Value := Level;
exit;
end;
SetLength(FResearch, length(FResearch) + 1);
FResearch[length(FResearch) - 1].Name := Name;
FResearch[length(FResearch) - 1].Value := Level;
end;
procedure TImperium.UpdateResearchList(resch: TGameItems);
var
i: Integer;
begin
for i := 0 to length(resch) - 1 do
UpdateResearchLevel(resch[i].Name, resch[i].Level);
end;
{ TPlanet }
function TPlanet.BuildsBuilding: boolean;
var
i: Integer;
begin
Result := false;
for i := 0 to length(FBuildingBuilds) - 1 do
if FBuildingBuilds[i].BuildTime > now then
begin
Result := true;
break;
end;
end;
procedure TPlanet.Clear;
begin
ID := 0;
Name := '';
Coords.Clear;
MaxFields := 0;
CurFields := 0;
CurRes.Clear;
Energy := 0;
FreeEnergy := 0;
UpdateDT := 0;
isMoon := false;
SetLength(FAttr, 0);
FBuildingShipsEndDT := 0;
SetLength(FBuildingShips, 0);
SetLength(FBuildingBuilds, 0);
FLockResources.Clear;
BuildingPlan.Clear;
serial := 0;
end;
constructor TPlanet.Create;
begin
inherited;
Clear;
end;
procedure TPlanet.FinishUpdate;
begin
UpdateDT := Now;
end;
function TPlanet.FreeFieldsCount: integer;
begin
Result := MaxFields - CurFields;
end;
function TPlanet.GetBuildLevel(name: string): integer;
var
i: integer;
begin
Result := 0;
for i := 0 to length(FAttr) - 1 do
if FAttr[i].Name = name then
begin
Result := FAttr[i].Value;
break;
end;
end;
function TPlanet.GetShipsCount(name: string; CountCurrent,
CountBuilding: boolean): int64;
var
i: integer;
begin
Result := 0;
if CountBuilding and (FBuildingShipsEndDT > now) then
for i := 0 to length(FBuildingShips) - 1 do
if FBuildingShips[i].Name = name then
Result := Result + FBuildingShips[i].Value;
if CountCurrent then
for i := 0 to length(FAttr) - 1 do
if FAttr[i].Name = name then
Result := Result + FAttr[i].Value;
end;
function TPlanet.HaveResources(res: TGameRes): boolean;
var
r: TGameRes;
begin
r := CurRes;
if isResoucesLocked then r.Sub(FLockResources.Res);
Result := r.MoreThan(res)
end;
function TPlanet.LockResources(StrategyID: integer; res: TGameRes;
LockLen: TDateTime): boolean;
begin
Result := false;
if isResoucesLocked then exit;
FLockResources.StrategyID := StrategyID;
FLockResources.Res := res;
FLockResources.LockFrom := Now;
FLockResources.LockTo := LockLen;
Result := true;
end;
function TPlanet.isResoucesLocked: boolean;
begin
Result :=
(FLockResources.LockTo >= Now) and
(not FLockResources.Res.Eq0);
end;
procedure TPlanet.SetBuildingBuilds(Builds: TGameItems);
begin
FBuildingBuilds := Builds;
end;
procedure TPlanet.SetBuildingShips(Fleet: TFleetOrderArr; BuildEstimate: TDateTime = 0);
begin
if length(Fleet) = 0 then
begin
FBuildingShipsEndDT := 0;
SetLength(FBuildingShips, 0);
exit;
end;
FBuildingShips := Fleet;
if BuildEstimate = 0 then
FBuildingShipsEndDT := Now + TCalc.ShipsBuildEstim(Fleet)
else
FBuildingShipsEndDT := Now + BuildEstimate;
end;
function TPlanet.ShipsBuilding: boolean;
begin
Result :=
(FBuildingShipsEndDT > now) and
(length(FBuildingShips) > 0);
end;
function TPlanet.StrBuildsBuilding: string;
var
i: integer;
begin
if Length(FBuildingBuilds) = 0 then
begin
Result := 'none';
exit;
end;
Result := IntToStr(length(FBuildingBuilds)) + ' ';
for i := 0 to length(FBuildingBuilds) - 1 do
Result := Result + FBuildingBuilds[i].Name + ' ' +
DateTimeToStr(FBuildingBuilds[i].BuildTime) + ' ';
end;
function TPlanet.StrShipsBuilding: string;
var
i: integer;
begin
if Length(FBuildingShips) = 0 then
begin
Result := 'none';
exit;
end;
Result := IntToStr(length(FBuildingShips)) + ' ';
for i := 0 to length(FBuildingShips) - 1 do
Result := Result + FBuildingShips[i].Name + ' ';
if FBuildingShipsEndDT > 0 then
Result := Result + DateTimeToStr(FBuildingShipsEndDT);
end;
procedure TPlanet.UpdateAttr(AName: string; AValue: int64);
var
i: integer;
begin
for i := 0 to length(FAttr) - 1 do
if FAttr[i].Name = AName then
begin
FAttr[i].Value := AValue;
exit;
end;
SetLength(FAttr, length(FAttr) + 1);
FAttr[length(FAttr) - 1].Name := AName;
FAttr[length(FAttr) - 1].Value := AValue;
end;
procedure TPlanet.UpdateFromBuildings(builds: TGameItems);
var
i: Integer;
begin
for i := 0 to length(builds) - 1 do
UpdateAttr(builds[i].Name, builds[i].Level);
end;
procedure TPlanet.UpdateFromShipYard(ships: TShips);
var
i: Integer;
begin
for i := 0 to length(ships) - 1 do
UpdateAttr(ships[i].Name, ships[i].Count);
end;
{ TGameCoords }
procedure TGameCoords.Clear;
begin
Galaxy := 0;
System := 0;
Planet := 0;
PlType := ptPlanet;
end;
function TGameCoords.Equal(c: TGameCoords): boolean;
begin
Result :=
(c.Galaxy = Galaxy) and
(c.System = System) and
(c.Planet = Planet);
end;
function TGameCoords.FromStr(s: string): boolean;
var
sl: TStringList;
begin
Result := false;
if s = '' then exit;
try
if s[1] = '[' then s := Copy(s, 2, length(s) - 2);
sl := TStringList.Create;
sl.Delimiter := ':';
sl.DelimitedText := s;
if sl.Count = 3 then
begin
Galaxy := StrToIntDef(sl[0], -1);
System := StrToIntDef(sl[1], -1);
Planet := StrToIntDef(sl[2], -1);
if (Galaxy > 0) and (System > 0) and (Planet > 0)
then
Result := true;
end;
sl.Free;
except
end;
end;
procedure TGameCoords.Inc;
begin
Inc(1, 9, 1, 499, 1, 16, 1);
end;
procedure TGameCoords.Inc(GM, GP, SM, SP, PM, PP, cnt: integer);
begin
Planet := Planet + cnt;
while (Planet > PP) or (System > SP) or (Galaxy > GP) do
begin
if Planet > PP then
begin
Planet := PM + (Planet - PP - 1);
System := System + 1;
end;
if System > SP then
begin
System := SM + (System - SP - 1);
Galaxy := Galaxy + 1;
end;
if Galaxy > GP then Galaxy := GM + (Galaxy - GP - 1);
end;
end;
function TGameCoords.ToStr: string;
begin
Result := '[' + IntToStr(Galaxy) + ':' +
IntToStr(System) + ':' + IntToStr(Planet) + ']';
end;
{ TGameRes }
procedure TGameRes.Add(r: TGameRes);
begin
Metal := r.Metal;
Crystal := r.Crystal;
Deiterium := r.Deiterium;
end;
procedure TGameRes.Add(r: TGameRes; m: int64);
begin
Metal := r.Metal * m;
Crystal := r.Crystal * m;
Deiterium := r.Deiterium * m;
end;
procedure TGameRes.Clear;
begin
Crystal := 0;
Metal := 0;
Deiterium := 0;
end;
function TGameRes.Eq0: boolean;
begin
Result :=
(Metal = 0) and
(Crystal = 0) and
(Deiterium = 0);
end;
function TGameRes.MoreThan(r: TGameRes): boolean;
begin
Result :=
(Metal > r.Metal) and
(Crystal > r.Crystal) and
(Deiterium > r.Deiterium);
end;
procedure TGameRes.Mul(m: int64);
begin
Metal := Metal * m;
Crystal := Crystal * m;
Deiterium := Deiterium * m;
end;
procedure TGameRes.NormalizeLow(mark: int64);
begin
if Metal < mark then Metal := mark;
if Crystal < mark then Crystal := mark;
if Deiterium < mark then Deiterium := mark;
end;
function TGameRes.ResSumm: int64;
begin
Result := Metal + Crystal + Deiterium;
end;
procedure TGameRes.Sub(r: TGameRes);
begin
Metal := Metal - r.Metal;
Crystal := Crystal - r.Crystal;
Deiterium := Deiterium - r.Deiterium;
end;
function TGameRes.EkvResSumm: int64;
begin
try
Result := Metal div 4 + Crystal div 2 + Deiterium;
except
Result := 0;
end;
end;
{ TCalc }
class function TCalc.CutFleet(Fleet: TFleetOrderArr; Res: TGameRes): boolean;
begin
Result := false;
end;
class function TCalc.ShipsBuildCost(Fleet: TFleetOrderArr): TGameRes;
var
i: Integer;
begin
Result.Clear;
for i := 0 to length(Fleet) - 1 do
Result.Add(
TMoonDB.GetInstance.GetShipBook(Fleet[i].Name).BuildRes,
Fleet[i].Value);
end;
class function TCalc.ShipsBuildEstim(Fleet: TFleetOrderArr): TDateTime;
var
cnt,
i: Integer;
begin
cnt := 0;
for i := 0 to length(Fleet) -1 do
cnt := cnt + Fleet[i].Value;
Result := 1 / (24 * 60 * 60) * (cnt + 10);
end;
class function TCalc.UpdateBuildingBook(ships: TGameItems): boolean;
begin
Result := TMoonDB.GetInstance.UpdateBuildingBook(ships);
TMoonDB.GetInstance.Commit;
end;
class function TCalc.UpdateShipBook(ships: TShips): boolean;
begin
Result := TMoonDB.GetInstance.UpdateShipBook(ships);
TMoonDB.GetInstance.Commit;
end;
{ TEnemyPlanet }
procedure TEnemyPlanet.Clear;
begin
Coords.Clear;
Name := '';
UserID := 0;
isEmpty := false;
HaveMoon := false;
HaveCrashField := false;
end;
{ TShip }
procedure TShip.Clear;
begin
ID := 0;
Name := '';
Tag := '';
Count := 0;
BuildRes.Clear;
BuildTime := 0;
BuildMaxCount := 0;
end;
{ TGameItem }
procedure TGameItem.Clear;
begin
ID := 0;
GroupName := '';
Name := '';
Level := 0;
BuildRes.Clear;
BuildTime := 0;
end;
{ TLockResRec }
procedure TLockResRec.Clear;
begin
StrategyID := 0;
Res.Clear;
LockFrom := 0;
LockTo := 0;
end;
{ TPlaningItem }
procedure TWorkPlan.Clear;
begin
Active := false;
Item.Clear;
NeedRes.Clear;
EndPlaningDate := 0;
end;
end.
|
unit HKCompPacksTypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpjson;
type
TDebugType=(DTInfo, DTInfo2, DTInfo3, DTException, DTError);
TOnDebugMessage=procedure(Sender:TObject; aMessage:String;
aDebugType:TDebugType)of object;
function GetJsonStringValue(aJson:TJSONObject; aPath:String):String;
function GetJsonNumberValue(aJson:TJSONObject; aPath:String):Integer;
function GetJsonArrayValue(aJson:TJSONObject; aPath:String):TJSONArray;
function GetLogMessage(aMessage:String; aDebugType:TDebugType):String;
implementation
function GetJsonStringValue(aJson: TJSONObject; aPath: String): String;
begin
Result:='';
if (aJson.FindPath(aPath)<>nil)and(not aJson.FindPath(aPath).IsNull) then
begin
Result:=aJson.FindPath(aPath).AsString;
end;
end;
function GetJsonNumberValue(aJson: TJSONObject; aPath: String): Integer;
begin
Result:=-1;
if aJson.FindPath(aPath)<>nil then
begin
try
if not aJson.FindPath(aPath).IsNull then
begin
Result:=aJson.FindPath(aPath).AsInteger;
end
else
Result:=0;
except
Result:=0;
end;
end;
end;
function GetJsonArrayValue(aJson: TJSONObject; aPath: String): TJSONArray;
begin
Result:=nil;
if aJson.FindPath(aPath)<>nil then
begin
Result:=aJson.FindPath(aPath) as TJSONArray;
end;
end;
function GetLogMessage(aMessage: String; aDebugType: TDebugType): String;
var
lType: String;
begin
case aDebugType of
DTInfo:lType:='Info';
DTInfo2:lType:='Info';
DTInfo3:lType:='Info';
DTError:lType:='Error';
DTException:lType:='Exception';
end;
Result:=Format('%s [%s] => %s',[DateTimeToStr(Now), lType,
aMessage.Replace(#$0d,' ',[rfReplaceAll]).Replace(#$0a,' ',[rfReplaceAll])]);
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIFontComboBox.pas
// Creator : Steve McDonald
// Merger : Shen Min
// Date : 2003-04-01 V1-V3
// 2003-06-24 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIFontComboBox;
{$B-} {- Complete Boolean Evaluation }
{$R-} {- Range-Checking }
{$V-} {- Var-String Checking }
{$T-} {- Typed @ operator }
{$X+} {- Extended syntax }
{$P+} {- Open string params }
{$J+} {- Writeable structured consts }
{$H+} {- Use long strings by default }
{$W-,T-}
interface
{$I SUIPack.inc}
uses
Windows, Messages, Classes, Controls, Graphics, StdCtrls, Forms, SUIThemes,
SUIComboBox;
resourcestring
SResNotFound = 'Resource %s not found';
type
{ TsuiFontDrawComboBox }
TFontDrawComboStyle = csDropDown..csDropDownList;
TsuiFontDrawComboBox = class(TsuiCustomComboBox)
private
FStyle: TFontDrawComboStyle;
FItemHeightChanging: Boolean;
procedure SetComboStyle(Value: TFontDrawComboStyle);
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMRecreateWnd(var Message: TMessage); message CM_RECREATEWND;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure ResetItemHeight;
function MinItemHeight: Integer; virtual;
property Style: TFontDrawComboStyle read FStyle write SetComboStyle default csDropDownList;
public
constructor Create(AOwner: TComponent); override;
end;
{ TsuiFontComboBox }
TFontDevice = (fdScreen, fdPrinter, fdBoth);
TFontListOption = (foAnsiOnly, foTrueTypeOnly, foFixedPitchOnly, foNoOEMFonts, foOEMFontsOnly, foScalableOnly, foNoSymbolFonts);
TFontListOptions = set of TFontListOption;
TsuiFontComboBox = class(TsuiFontDrawComboBox)
private
FTrueTypeBMP: TBitmap;
FDeviceBMP: TBitmap;
FOnChange: TNotifyEvent;
FDevice: TFontDevice;
FUpdate: Boolean;
FUseFonts: Boolean;
FOptions: TFontListOptions;
procedure SetFontName(const NewFontName: TFontName);
function GetFontName: TFontName;
procedure SetDevice(Value: TFontDevice);
procedure SetOptions(Value: TFontListOptions);
procedure SetUseFonts(Value: Boolean);
procedure Reset;
procedure WMFontChange(var Message: TMessage); message WM_FONTCHANGE;
protected
procedure PopulateList; virtual;
procedure Change; override;
procedure Click; override;
procedure DoChange; dynamic;
procedure CreateWnd; override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
function MinItemHeight: Integer; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Text;
published
property Device: TFontDevice read FDevice write SetDevice default fdScreen;
property FontName: TFontName read GetFontName write SetFontName;
property Options: TFontListOptions read FOptions write SetOptions default [];
property UseFonts: Boolean read FUseFonts write SetUseFonts default False;
property ItemHeight;
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property Enabled;
property Font;
property Anchors;
property BiDiMode;
property Constraints;
property DragKind;
property ParentBiDiMode;
property ImeMode;
property ImeName;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Style;
property TabOrder;
property TabStop;
property Visible;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDrag;
property OnContextPopup;
property OnEndDock;
property OnStartDock;
end;
TsuiFontSizeComboBox = class(TsuiCustomComboBox)
private
PixelsPerInch : Integer;
FFontName : TFontName;
procedure SetFontName( const Value : TFontName );
procedure Build;
function GetFontSize: Integer;
procedure SetFontSize(const Value: Integer);
public
constructor Create(AOwner: TComponent); override;
published
property FontName : TFontName read FFontName write SetFontName;
property FontSize : Integer read GetFontSize write SetFontSize;
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property Enabled;
property Font;
property Anchors;
property BiDiMode;
property Constraints;
property DragKind;
property ParentBiDiMode;
property ImeMode;
property ImeName;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Style;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDrag;
property OnContextPopup;
property OnEndDock;
property OnStartDock;
end;
implementation
uses
SysUtils,
Consts,
Printers,
Dialogs,
SUIPublic,
SUIResDef;
{ Utility routines }
procedure ResourceNotFound(ResID: PChar);
var
S: string;
begin
if LongRec(ResID).Hi = 0 then
S := IntToStr(LongRec(ResID).Lo)
else
S := StrPas(ResID);
raise EResNotFound.CreateFmt(SResNotFound, [S]);
end;
function MakeModuleBitmap(Module: THandle; ResID: PChar): TBitmap;
begin
Result := TBitmap.Create;
try
if Module <> 0 then begin
if LongRec(ResID).Hi = 0 then
Result.LoadFromResourceID(Module, LongRec(ResID).Lo)
else
Result.LoadFromResourceName(Module, StrPas(ResID));
end
else begin
Result.Handle := LoadBitmap(Module, ResID);
if Result.Handle = 0 then
ResourceNotFound(ResID);
end;
except
Result.Free;
Result := nil;
end;
end;
function CreateBitmap(ResName: PChar): TBitmap;
begin
Result := MakeModuleBitmap(HInstance, ResName);
if Result = nil then
ResourceNotFound(ResName);
end;
function GetItemHeight(Font: TFont): Integer;
var
DC: HDC;
SaveFont: HFont;
Metrics: TTextMetric;
begin
DC := GetDC(0);
try
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
Result := Metrics.tmHeight + 1;
if Result = 14 then
Result := 15;
end;
{ TsuiFontDrawComboBox }
constructor TsuiFontDrawComboBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
inherited Style := csDropDownList;
FStyle := csDropDownList;
end;
procedure TsuiFontDrawComboBox.SetComboStyle(Value: TFontDrawComboStyle);
begin
if FStyle <> Value then begin
FStyle := Value;
inherited Style := Value;
end;
end;
function TsuiFontDrawComboBox.MinItemHeight: Integer;
begin
Result := GetItemHeight(Font);
if Result < 9 then
Result := 9;
end;
procedure TsuiFontDrawComboBox.ResetItemHeight;
var
H: Integer;
begin
H := MinItemHeight;
FItemHeightChanging := True;
try
inherited ItemHeight := H;
finally
FItemHeightChanging := False;
end;
if HandleAllocated then
SendMessage(Handle, CB_SETITEMHEIGHT, 0, H);
end;
procedure TsuiFontDrawComboBox.CreateParams(var Params: TCreateParams);
const
ComboBoxStyles: array[TFontDrawComboStyle] of DWORD =
(CBS_DROPDOWN, CBS_SIMPLE, CBS_DROPDOWNLIST);
begin
inherited CreateParams(Params);
with Params do
Style := (Style and not CBS_DROPDOWNLIST) or CBS_OWNERDRAWFIXED or
ComboBoxStyles[FStyle];
end;
procedure TsuiFontDrawComboBox.CreateWnd;
begin
inherited CreateWnd;
ResetItemHeight;
end;
procedure TsuiFontDrawComboBox.CMFontChanged(var Message: TMessage);
begin
inherited;
ResetItemHeight;
RecreateWnd;
end;
procedure TsuiFontDrawComboBox.CMRecreateWnd(var Message: TMessage);
begin
if not FItemHeightChanging then
inherited;
end;
{ TsuiFontComboBox }
const
WRITABLE_FONTTYPE = 256;
function IsValidFont(Box: TsuiFontComboBox; LogFont: TLogFont; FontType: Integer): Boolean;
begin
Result := True;
if (foAnsiOnly in Box.Options) then
Result := Result and (LogFont.lfCharSet = ANSI_CHARSET);
if (foTrueTypeOnly in Box.Options) then
Result := Result and (FontType and TRUETYPE_FONTTYPE = TRUETYPE_FONTTYPE);
if (foFixedPitchOnly in Box.Options) then
Result := Result and (LogFont.lfPitchAndFamily and FIXED_PITCH = FIXED_PITCH);
if (foOEMFontsOnly in Box.Options) then
Result := Result and (LogFont.lfCharSet = OEM_CHARSET);
if (foNoOEMFonts in Box.Options) then
Result := Result and (LogFont.lfCharSet <> OEM_CHARSET);
if (foNoSymbolFonts in Box.Options) then
Result := Result and (LogFont.lfCharSet <> SYMBOL_CHARSET);
if (foScalableOnly in Box.Options) then
Result := Result and (FontType and RASTER_FONTTYPE = 0);
end;
function EnumFontsProc(var EnumLogFont: TEnumLogFont;
var TextMetric: TNewTextMetric; FontType: Integer; Data: LPARAM): Integer;
export; stdcall;
var
FaceName: string;
begin
FaceName := StrPas(EnumLogFont.elfLogFont.lfFaceName);
with TsuiFontComboBox(Data) do
if (Items.IndexOf(FaceName) < 0) and
IsValidFont(TsuiFontComboBox(Data), EnumLogFont.elfLogFont, FontType) then begin
if EnumLogFont.elfLogFont.lfCharSet <> SYMBOL_CHARSET then
FontType := FontType or WRITABLE_FONTTYPE;
Items.AddObject(FaceName, TObject(FontType));
end;
Result := 1;
end;
constructor TsuiFontComboBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ItemHeight := 15;
FTrueTypeBMP := CreateBitmap('FONTCOMBO_TRUETYPE_FNT');
FDeviceBMP := CreateBitmap('FONTCOMBO_DEVICE_FNT');
FDevice := fdScreen;
Sorted := True;
inherited ItemHeight := MinItemHeight;
end;
destructor TsuiFontComboBox.Destroy;
begin
FTrueTypeBMP.Free;
FDeviceBMP.Free;
inherited Destroy;
end;
procedure TsuiFontComboBox.CreateWnd;
var
OldFont: TFontName;
begin
OldFont := FontName;
inherited CreateWnd;
FUpdate := True;
try
PopulateList;
inherited Text := '';
SetFontName(OldFont);
finally
FUpdate := False;
end;
if AnsiCompareText(FontName, OldFont) <> 0 then
DoChange;
end;
procedure TsuiFontComboBox.PopulateList;
var
DC: HDC;
begin
if not HandleAllocated then Exit;
Items.BeginUpdate;
try
Clear;
DC := GetDC(0);
try
if (FDevice = fdScreen) or (FDevice = fdBoth) then
EnumFontFamilies(DC, nil, @EnumFontsProc, Longint(Self));
if (FDevice = fdPrinter) or (FDevice = fdBoth) then
try
EnumFontFamilies(Printer.Handle, nil, @EnumFontsProc, Longint(Self));
except
{ skip any errors }
end;
finally
ReleaseDC(0, DC);
end;
finally
Items.EndUpdate;
end;
end;
procedure TsuiFontComboBox.SetFontName(const NewFontName: TFontName);
var
Item: Integer;
begin
if FontName <> NewFontName then begin
if not (csLoading in ComponentState) then begin
HandleNeeded;
{ change selected item }
for Item := 0 to Items.Count - 1 do
if AnsiCompareText(Items[Item], NewFontName) = 0 then begin
ItemIndex := Item;
DoChange;
Exit;
end;
if Style = csDropDownList then
ItemIndex := -1
else
inherited Text := NewFontName;
end
else
inherited Text := NewFontName;
DoChange;
end;
end;
function TsuiFontComboBox.GetFontName: TFontName;
begin
Result := inherited Text;
end;
procedure TsuiFontComboBox.SetOptions(Value: TFontListOptions);
begin
if Value <> Options then begin
FOptions := Value;
Reset;
end;
end;
procedure TsuiFontComboBox.SetDevice(Value: TFontDevice);
begin
if Value <> FDevice then begin
FDevice := Value;
Reset;
end;
end;
procedure TsuiFontComboBox.SetUseFonts(Value: Boolean);
begin
if Value <> FUseFonts then begin
FUseFonts := Value;
Invalidate;
end;
end;
procedure TsuiFontComboBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Bitmap: TBitmap;
BmpWidth: Integer;
Text: array[0..255] of Char;
begin
with Canvas do begin
FillRect(Rect);
BmpWidth := 20;
if (Integer(Items.Objects[Index]) and TRUETYPE_FONTTYPE) <> 0 then
Bitmap := FTrueTypeBMP
else
if (Integer(Items.Objects[Index]) and DEVICE_FONTTYPE) <> 0 then
Bitmap := FDeviceBMP
else
Bitmap := nil;
if Bitmap <> nil then begin
BmpWidth := Bitmap.Width;
BrushCopy(Bounds(Rect.Left + 2, (Rect.Top + Rect.Bottom - Bitmap.Height)
div 2, Bitmap.Width, Bitmap.Height), Bitmap, Bounds(0, 0, Bitmap.Width,
Bitmap.Height), Bitmap.TransparentColor);
end;
{ uses DrawText instead of TextOut in order to get clipping against
the combo box button }
{TextOut(Rect.Left + bmpWidth + 6, Rect.Top, Items[Index])}
StrPCopy(Text, Items[Index]);
Rect.Left := Rect.Left + BmpWidth + 6;
if FUseFonts and (Integer(Items.Objects[Index]) and WRITABLE_FONTTYPE <> 0) then
Font.Name := Items[Index];
DrawText(Handle, Text, StrLen(Text), Rect,
DrawTextBiDiModeFlags(DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX));
end;
end;
procedure TsuiFontComboBox.WMFontChange(var Message: TMessage);
begin
inherited;
Reset;
end;
function TsuiFontComboBox.MinItemHeight: Integer;
begin
Result := inherited MinItemHeight;
if Result < FTrueTypeBMP.Height - 1 then
Result := FTrueTypeBMP.Height - 1;
end;
procedure TsuiFontComboBox.Change;
var
I: Integer;
begin
inherited Change;
if Style <> csDropDownList then begin
I := Items.IndexOf(inherited Text);
if (I >= 0) and (I <> ItemIndex) then begin
ItemIndex := I;
DoChange;
end;
end;
end;
procedure TsuiFontComboBox.Click;
begin
inherited Click;
DoChange;
end;
procedure TsuiFontComboBox.DoChange;
begin
if not (csReading in ComponentState) then
if not FUpdate and Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TsuiFontComboBox.Reset;
var
SaveName: TFontName;
begin
if HandleAllocated then begin
FUpdate := True;
try
SaveName := FontName;
PopulateList;
FontName := SaveName;
finally
FUpdate := False;
if FontName <> SaveName then
DoChange;
end;
end;
end;
function EnumFontSizes( var EnumLogFont : TEnumLogFont; PTextMetric : PNewTextMetric; FontType : Integer; Data : LPARAM ) : Integer; export; stdcall;
var
s : String;
i : Integer;
v : Integer;
v2 : Integer;
begin
if (FontType and TRUETYPE_FONTTYPE)<>0 then begin
TsuiFontSizeComboBox(Data).Items.Add('8');
TsuiFontSizeComboBox(Data).Items.Add('9');
TsuiFontSizeComboBox(Data).Items.Add('10');
TsuiFontSizeComboBox(Data).Items.Add('11');
TsuiFontSizeComboBox(Data).Items.Add('12');
TsuiFontSizeComboBox(Data).Items.Add('14');
TsuiFontSizeComboBox(Data).Items.Add('16');
TsuiFontSizeComboBox(Data).Items.Add('18');
TsuiFontSizeComboBox(Data).Items.Add('20');
TsuiFontSizeComboBox(Data).Items.Add('22');
TsuiFontSizeComboBox(Data).Items.Add('24');
TsuiFontSizeComboBox(Data).Items.Add('26');
TsuiFontSizeComboBox(Data).Items.Add('28');
TsuiFontSizeComboBox(Data).Items.Add('36');
TsuiFontSizeComboBox(Data).Items.Add('48');
TsuiFontSizeComboBox(Data).Items.Add('72');
Result := 0;
end
else begin
v := Round( ( EnumLogFont.elfLogFont.lfHeight - PTextMetric.tmInternalLeading ) * 72 / TsuiFontSizeComboBox( Data ).PixelsPerInch );
s := IntToStr( v );
Result := 1;
for i := 0 to Pred( TsuiFontSizeComboBox( Data ).Items.Count ) do begin
v2 := StrToInt( TsuiFontSizeComboBox( Data ).Items[ i ] );
if v2 = v then
exit;
if v2 > v then begin
TsuiFontSizeComboBox( Data ).Items.Insert( i, s );
exit;
end;
end;
TsuiFontSizeComboBox( Data ).Items.Add( s );
end;
end;
procedure TsuiFontSizeComboBox.Build;
var
DC : HDC;
OC : TNotifyEvent;
begin
DC := GetDC( 0 );
Items.BeginUpdate;
try
Items.Clear;
if FontName <> '' then begin
PixelsPerInch := GetDeviceCaps( DC, LOGPIXELSY );
EnumFontFamilies( DC, PChar( FontName ), @EnumFontSizes, Longint( Self ) );
OC := OnClick;
OnClick := nil;
ItemIndex := Items.IndexOf( Text );
OnClick := OC;
if Assigned( OnClick ) then
OnClick( Self );
end;
finally
Items.EndUpdate;
ReleaseDC( 0, DC );
end;
end;
procedure TsuiFontSizeComboBox.SetFontName( const Value : TFontName );
begin
FFontName := Value;
Build;
end;
constructor TsuiFontSizeComboBox.Create(AOwner: TComponent);
begin
inherited;
self.Style := csDropDownList;
end;
function TsuiFontSizeComboBox.GetFontSize: Integer;
begin
try
Result := StrToInt(Items[ItemIndex]);
except
Result := 0;
end;
end;
procedure TsuiFontSizeComboBox.SetFontSize(const Value: Integer);
begin
ItemIndex := Items.IndexOf(IntToStr(Value));
end;
end.
|
unit NsLibSSH2Terminal;
interface
uses
StdCtrls, SysUtils, Classes, WinSock, libssh2, NsLibSSH2Session, NsLibSSH2Const,
NsLibSSH2Threads;
type
TExchangerThd = class(TThread)
private
FPoolIndex: Integer;
FExchangeSocket: TSocket;
FChannel: PLIBSSH2_CHANNEL;
// Property getters/setters
function GetPoolIndex: Integer;
procedure SetPoolIndex(Value: Integer);
function GetExchangeSocket: TSocket;
procedure SetExchangeSocket(Value: TSocket);
function GetChannel: PLIBSSH2_CHANNEL;
procedure SetChannel(Value: PLIBSSH2_CHANNEL);
function GetTerminated: Boolean;
public
destructor Destroy; override;
procedure Execute; override;
property PoolIndex: Integer read GetPoolIndex write SetPoolIndex;
property ExchangeSocket: TSocket read GetExchangeSocket write
SetExchangeSocket;
property Channel: PLIBSSH2_CHANNEL read GetChannel write SetChannel;
property Terminated: Boolean read GetTerminated;
end;
type
TNsLibSSH2Terminal = class(TComponent)
private
FSession: TNsLibSSH2Session;
FChannel: PLIBSSH2_CHANNEL;
FVariables: TStrings;
FOpened: Boolean;
FStatus: String;
FTerminal: String;
FExchangerThd: TExchangerThd;
procedure PostVarsToServer;
// Property getters/setters
function GetTerminal: String;
procedure SetTerminal(Value: String);
function GetSession: TNsLibSSH2Session;
procedure SetSession(Value: TNsLibSSH2Session);
function GetVariables: TStrings;
procedure SetVariables(Value: TStrings);
function GetOpened: Boolean;
function GetStatus: String;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Open: Boolean;
procedure Close;
property Terminal: String read GetTerminal write SetTerminal;
property Session: TNsLibSSH2Session read GetSession write SetSession;
property Variables: TStrings read GetVariables write SetVariables;
property Opened: Boolean read GetOpened;
property Status: String read GetStatus;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NeferSky', [TNsLibSSH2Terminal]);
end;
//---------------------------------------------------------------------------
{ TNsLibSSH2Terminal }
// Public
constructor TNsLibSSH2Terminal.Create(AOwner: TComponent);
begin
inherited;
FSession := nil;
FChannel := nil;
FVariables.Clear;
FTerminal := 'xterm';
FSession := nil;
FOpened := False;
FStatus := ST_DISCONNECTED;
end;
//---------------------------------------------------------------------------
destructor TNsLibSSH2Terminal.Destroy;
begin
if Opened then Close;
FVariables.Clear;
inherited;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Terminal.Open: Boolean;
var
rc: Integer;
begin
Result := False;
if FSession = nil then
raise Exception.Create(ER_SESSION_UNAVAILABLE);
{ // Unclear why the channel is not created by the first time,
// that's why i have to make several attempts.
// I use the SafeCounter to prevent an infinite loop.
SafeCounter := 0;
repeat
Inc(SafeCounter);
}
FChannel := libssh2_channel_open_session(FSession.Session);
{ // Just waiting. It's a kind of magic.
Sleep(1000);
until (FExchangeChannel <> nil) or (SafeCounter > MAX_CONNECTION_ATTEMPTS);
}
if (FChannel = nil) then
begin
FStatus := ER_CHANNEL_OPEN;
Exit;
end;
PostVarsToServer;
rc := libssh2_channel_request_pty(FChannel, PAnsiChar(FTerminal));
if (rc <> 0) then
begin
FStatus := ER_FAILED_PTY;
Close;
end;
rc := libssh2_channel_shell(FChannel);
if (rc <> 0) then
begin
FStatus := ER_REQUEST_SHELL;
Exit;
end;
{ FListenSocket := Socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (FListenSocket = INVALID_SOCKET) then
begin
FListenSocket := INVALID_SOCKET;
FStatus := ER_OPEN_SOCKET;
Exit;
end;
ExchangerThd := TExchangerThd.Create(True);
ExchangerThd.FreeOnTerminate := True;
ExchangerThd.ExchangeSocket := FExchangeSocket;
ExchangerThd.Channel := FExchangeChannel;
}
{ /* At this point the shell can be interacted with using
* libssh2_channel_read()
* libssh2_channel_read_stderr()
* libssh2_channel_write()
* libssh2_channel_write_stderr()
*
* Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking()
* If the server send EOF, libssh2_channel_eof() will return non-0
* To send EOF to the server use: libssh2_channel_send_eof()
* A channel can be closed with: libssh2_channel_close()
* A channel can be freed with: libssh2_channel_free()
*/
}
FStatus := ST_CONNECTED;
FOpened := True;
Result := Opened;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Terminal.Close;
begin
if FChannel <> nil then
begin
libssh2_channel_close(FChannel);
libssh2_channel_free(FChannel);
FChannel := nil;
end;
FStatus := ST_DISCONNECTED;
FOpened := False;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Terminal.PostVarsToServer;
var
i, rc: Integer;
Variable: String;
VarKey, VarVal: PAnsiChar;
begin
if FVariables.Count <= 0 then Exit;
for i := 0 to FVariables.Count - 1 do
begin
Variable := FVariables[i];
VarKey := PAnsiChar(Variable);
VarVal := PAnsiChar(Variable);
rc := libssh2_channel_setenv(FChannel, VarKey, VarVal);
if rc <> 0 then Continue;
end;
end;
//---------------------------------------------------------------------------
// Public
function TNsLibSSH2Terminal.GetOpened: Boolean;
begin
Result := FOpened;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Terminal.GetSession: TNsLibSSH2Session;
begin
Result := FSession;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Terminal.GetStatus: String;
begin
Result := FStatus;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Terminal.GetTerminal: String;
begin
Result := FTerminal;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Terminal.GetVariables: TStrings;
begin
Result := FVariables;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Terminal.SetSession(Value: TNsLibSSH2Session);
begin
if FSession <> Value then
FSession := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Terminal.SetTerminal(Value: String);
begin
if FTerminal <> Value then
FTerminal := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Terminal.SetVariables(Value: TStrings);
begin
FVariables.Assign(Value);
end;
//---------------------------------------------------------------------------
{ TExchangerThd }
procedure TExchangerThd.Execute;
var
i: Integer;
wr: ssize_t;
rc: Integer;
tv: timeval;
fds: tfdset;
Len: ssize_t;
Buffer: array[0..16384] of Char;
begin
while not Terminated do
begin
FD_ZERO(fds);
FD_SET(FExchangeSocket, fds);
tv.tv_sec := 0;
tv.tv_usec := 100000;
rc := Select(0, @fds, nil, nil, @tv);
if (rc = -1) then
Terminate;
if ((rc <> 0) and FD_ISSET(FExchangeSocket, fds)) then
begin
FillChar(Buffer, 16385, 0);
Len := Recv(FExchangeSocket, Buffer[0], SizeOf(Buffer), 0);
if (Len <= 0) then
Terminate;
wr := 0;
while (wr < Len) do
begin
i := libssh2_channel_write(Channel, @Buffer[wr], Len - wr);
if (LIBSSH2_ERROR_EAGAIN = i) then
Continue;
if (i < 0) then
Terminate;
wr := wr + i;
end;
end;
while True do
begin
FillChar(Buffer, 16385, 0);
Len := libssh2_channel_read(Channel, @Buffer[0], SizeOf(Buffer));
if (LIBSSH2_ERROR_EAGAIN = Len) then
Break
else if (Len < 0) then
Terminate;
wr := 0;
while (wr < Len) do
begin
i := Send(FExchangeSocket, Buffer[wr], Len - wr, 0);
if (i <= 0) then
Terminate;
wr := wr + i;
end;
if (libssh2_channel_eof(Channel) = 1) then
Terminate;
end;
end;
end;
//---------------------------------------------------------------------------
destructor TExchangerThd.Destroy;
begin
if (Channel <> nil) then
begin
libssh2_channel_close(Channel);
libssh2_channel_wait_closed(Channel);
libssh2_channel_free(Channel);
end;
if FExchangeSocket <> INVALID_SOCKET then
begin
CloseSocket(FExchangeSocket);
FExchangeSocket := INVALID_SOCKET;
end;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetChannel: PLIBSSH2_CHANNEL;
begin
Result := FChannel;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetExchangeSocket: TSocket;
begin
Result := FExchangeSocket;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetPoolIndex: Integer;
begin
Result := FPoolIndex;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetTerminated: Boolean;
begin
Result := Self.Terminated;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetChannel(Value: PLIBSSH2_CHANNEL);
begin
if FChannel <> Value then
FChannel := Value;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetExchangeSocket(Value: TSocket);
begin
if FExchangeSocket <> Value then
FExchangeSocket := Value;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetPoolIndex(Value: Integer);
begin
if FPoolIndex <> Value then
FPoolIndex := Value;
end;
end.
|
unit Processor.PascalUnit;
interface
uses
System.SysUtils,
System.StrUtils;
type
TPascalUnitProcessor = class
const
Aphostrophe = '''';
private
class function FindSignature(const aSource, FieldName: string)
: integer; static;
class function TextLength(const aSource: string; aTextStartIdx: integer)
: integer; static;
public
class var OldVersion: string;
class function ProcessUnit(const aSource: string; const aNewVersion: string)
: string; static;
end;
implementation
uses
Processor.Utils;
class function TPascalUnitProcessor.FindSignature(const aSource,
FieldName: string): integer;
var
idx1: integer;
i: integer;
begin
idx1 := aSource.IndexOf(FieldName);
if idx1 >= 0 then
begin
i := aSource.IndexOf(Aphostrophe, idx1);
if i >= 0 then
Exit(i + 1);
end;
Result := -1;
end;
class function TPascalUnitProcessor.TextLength(const aSource: string;
aTextStartIdx: integer): integer;
var
j: integer;
begin
if aTextStartIdx > 0 then
begin
j := aSource.IndexOf(Aphostrophe, aTextStartIdx);
if j > aTextStartIdx then
Exit(j - aTextStartIdx);
end;
Result := 0;
end;
class function TPascalUnitProcessor.ProcessUnit(const aSource: string;
const aNewVersion: string): string;
var
idx2: integer;
len2: integer;
aReleaseVersion: string;
aNewSource: string;
begin
idx2 := FindSignature(aSource, 'Version');
len2 := TextLength(aSource, idx2);
aReleaseVersion := aSource.Substring(idx2, len2);
if len2 > 0 then
begin
OldVersion := aReleaseVersion;
aNewSource := aSource.Substring(0, idx2) + aNewVersion +
aSource.Substring(idx2 + len2, 99999);
if aSource <> aNewSource then
Result := aNewSource;
end
else
Result := aSource;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DBXDBMetaData;
interface
uses
DbxMetaDataProvider, DB, DBClient;
type
TDBXDBMetaData = class
private
class function ToFieldType(DataType: Integer): TFieldType; static;
public
class procedure AddParams(Params: TParams; MetaDataTable: TDBXMetadataTable); static;
class procedure AddClientDataSetFields(ClientDataSet: TClientDataSet; MetaDataTable: TDBXMetadataTable); static;
end;
implementation
uses
DBXCommon, DBXTypedTableStorage, DBXTestResStrs;
{ TDBXDBMetaData }
class function TDBXDBMetaData.ToFieldType(DataType: Integer): TFieldType;
begin
case DataType of
TDBXDataTypes.BooleanType:
Result := ftBoolean;
TDBXDataTypes.UInt8Type:
Result := ftByte;
TDBXDataTypes.Int8Type:
Result := ftShortint;
TDBXDataTypes.UInt16Type:
Result := ftWord;
TDBXDataTypes.Int16Type:
Result := ftSmallint;
TDBXDataTypes.Int32Type:
Result := ftInteger;
TDBXDataTypes.Int64Type:
Result := ftLargeint;
TDBXDataTypes.SingleType:
Result := ftSingle;
TDBXDataTypes.DoubleType:
Result := ftFloat;
TDBXDataTypes.WideStringType:
Result := ftWideString;
TDBXDataTypes.AnsiStringType:
Result := ftString;
TDBXDataTypes.DateType:
Result := ftDate;
TDBXDataTypes.TimeStampType:
Result := ftTimeStamp;
TDBXDataTypes.TimeStampOffsetType:
Result := ftTimeStampOffset;
TDBXDataTypes.BlobType:
Result := ftBlob;
TDBXDataTypes.BcdType:
Result := ftFMTBcd;
TDBXDataTypes.CurrencyType:
Result := ftBcd;
TDBXDataTypes.BytesType:
Result := ftBytes;
TDBXDataTypes.TimeType:
Result := ftTime;
TDBXDataTypes.BinaryBlobType:
Result := ftStream;
TDBXDataTypes.VarBytesType:
Result := ftVarBytes;
else
raise TDBXError.Create(SUnexpectedMetaDataType);
end;
end;
class procedure TDBXDBMetaData.AddClientDataSetFields(
ClientDataSet: TClientDataSet;
MetaDataTable: TDBXMetadataTable);
var
Columns: TDBXColumnsTableStorage;
FieldDef: TFieldDef;
Ordinal: Integer;
begin
Columns := MetaDataTable.ColumnsStorage;
Columns.First;
Ordinal := 0;
ClientDataSet.Close;
while Columns.InBounds do
begin
FieldDef := ClientDataSet.FieldDefs.AddFieldDef;
FieldDef.Name := Columns.ColumnName;
FieldDef.DisplayName := Columns.ColumnName;
FieldDef.DataType := ToFieldType(Columns.DbxDataType);
FieldDef.FieldNo := Ordinal;
FieldDef.Size := Columns.Precision;
//Midas will throw an invalid field type error if size > 65531
if ((FieldDef.DataType = ftString) or (FieldDef.DataType = ftWideString))
and (FieldDef.Size > 65531) then
begin
FieldDef.DataType := ftBlob;
FieldDef.Size := 0;
end;
if Columns.DbxDataType = TDBXDataTypes.WideStringType then
begin
if Columns.Precision <= 0 then
FieldDef.Size := 128 // default size (make constant)
else
FieldDef.Size := columns.Precision;
end;
Inc(Ordinal);
Columns.Next;
end;
ClientDataSet.CreateDataSet;
end;
class procedure TDBXDBMetaData.AddParams(Params: TParams;
MetaDataTable: TDBXMetadataTable);
var
Columns: TDBXColumnsTableStorage;
Param: TParam;
begin
Columns := MetaDataTable.ColumnsStorage;
Columns.First;
Params.Clear;
while Columns.InBounds do
begin
Param := TParam.Create(Params);
Param.Name := Columns.ColumnName;
Param.DisplayName := Columns.ColumnName;
Param.DataType := ToFieldType(Columns.DbxDataType);
Param.ParamType := ptInput;
Param.Precision := Columns.Precision;
Param.NumericScale := Columns.Scale;
Param.Size := Columns.Precision;
Columns.Next;
end;
end;
end.
|
{$MODE FPC}
{$PACKRECORDS C}
unit mosquitto;
{*
Copyright (c) 2010-2019 Roger Light <roger@atchoo.org>
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Roger Light - initial implementation and documentation.
*}
{*
* Free Pascal header conversion
* Copyright (c) 2018-2019 Karoly Balogh <charlie@amigaspirit.hu>
*
* http://github.com/chainq/mosquitto-p
*}
interface
uses
ctypes;
{ This is a kludge, because apparently GCC is confused about
how C booleans should work, and optimizes code away inside
libmosquitto on some platforms, which breaks the 'non zero
means true in C' assumption of FPC. (CB) }
type
cbool = boolean; { longbool in ctypes }
pcbool = ^cbool;
const
{$IFDEF HASUNIX}
{$IFDEF DARWIN}
{$LINKLIB mosquitto}
libmosq_NAME = 'libmosquitto.dynlib';
{$ELSE}
libmosq_NAME = 'libmosquitto.so';
{$ENDIF}
{$ELSE}
{$IFDEF MSWINDOWS}
libmosq_NAME = 'mosquitto.dll';
{$ELSE}
{$ERROR Unsupported platform.}
{$ENDIF MSWINDOWS}
{$ENDIF HASUNIX}
const
LIBMOSQUITTO_MAJOR = 1;
LIBMOSQUITTO_MINOR = 5;
LIBMOSQUITTO_REVISION = 8;
{* LIBMOSQUITTO_VERSION_NUMBER looks like 1002001 for e.g. version 1.2.1. *}
LIBMOSQUITTO_VERSION_NUMBER = (LIBMOSQUITTO_MAJOR*1000000+LIBMOSQUITTO_MINOR*1000+LIBMOSQUITTO_REVISION);
{* Log types *}
const
MOSQ_LOG_NONE = $00;
MOSQ_LOG_INFO = $01;
MOSQ_LOG_NOTICE = $02;
MOSQ_LOG_WARNING = $04;
MOSQ_LOG_ERR = $08;
MOSQ_LOG_DEBUG = $10;
MOSQ_LOG_SUBSCRIBE = $20;
MOSQ_LOG_UNSUBSCRIBE = $40;
MOSQ_LOG_WEBSOCKETS = $80;
MOSQ_LOG_ALL = $FFFF;
{* Error values *}
const
MOSQ_ERR_CONN_PENDING = -1;
MOSQ_ERR_SUCCESS = 0;
MOSQ_ERR_NOMEM = 1;
MOSQ_ERR_PROTOCOL = 2;
MOSQ_ERR_INVAL = 3;
MOSQ_ERR_NO_CONN = 4;
MOSQ_ERR_CONN_REFUSED = 5;
MOSQ_ERR_NOT_FOUND = 6;
MOSQ_ERR_CONN_LOST = 7;
MOSQ_ERR_TLS = 8;
MOSQ_ERR_PAYLOAD_SIZE = 9;
MOSQ_ERR_NOT_SUPPORTED = 10;
MOSQ_ERR_AUTH = 11;
MOSQ_ERR_ACL_DENIED = 12;
MOSQ_ERR_UNKNOWN = 13;
MOSQ_ERR_ERRNO = 14;
MOSQ_ERR_EAI = 15;
MOSQ_ERR_PROXY = 16;
MOSQ_ERR_PLUGIN_DEFER = 17;
MOSQ_ERR_MALFORMED_UTF8 = 18;
MOSQ_ERR_KEEPALIVE = 19;
MOSQ_ERR_LOOKUP = 20;
{* Error values *}
const
MOSQ_OPT_PROTOCOL_VERSION = 1;
MOSQ_OPT_SSL_CTX = 2;
MOSQ_OPT_SSL_CTX_WITH_DEFAULTS = 3;
{* MQTT specification restricts client ids to a maximum of 23 characters *}
const
MOSQ_MQTT_ID_MAX_LENGTH = 23;
const
MQTT_PROTOCOL_V31 = 3;
MQTT_PROTOCOL_V311 = 4;
type
PPmosquitto_message = ^Pmosquitto_message;
Pmosquitto_message = ^Tmosquitto_message;
Tmosquitto_message = record
mid: cint;
topic: pchar;
payload: pointer;
payloadlen: cint;
qos: cint;
retain: cbool;
end;
type
Pmosquitto = ^Tmosquitto;
Tmosquitto = type array of byte;
{*
* Topic: Threads
* libmosquitto provides thread safe operation, with the exception of
* <mosquitto_lib_init> which is not thread safe.
*
* If your application uses threads you must use <mosquitto_threaded_set> to
* tell the library this is the case, otherwise it makes some optimisations
* for the single threaded case that may result in unexpected behaviour for
* the multi threaded case.
*}
{***************************************************
* Important note
*
* The following functions that deal with network operations will return
* MOSQ_ERR_SUCCESS on success, but this does not mean that the operation has
* taken place. An attempt will be made to write the network data, but if the
* socket is not available for writing at that time then the packet will not be
* sent. To ensure the packet is sent, call mosquitto_loop() (which must also
* be called to process incoming network data).
* This is especially important when disconnecting a client that has a will. If
* the broker does not receive the DISCONNECT command, it will assume that the
* client has disconnected unexpectedly and send the will.
*
* mosquitto_connect()
* mosquitto_disconnect()
* mosquitto_subscribe()
* mosquitto_unsubscribe()
* mosquitto_publish()
***************************************************}
{*
* Function: mosquitto_lib_version
*
* Can be used to obtain version information for the mosquitto library.
* This allows the application to compare the library version against the
* version it was compiled against by using the LIBMOSQUITTO_MAJOR,
* LIBMOSQUITTO_MINOR and LIBMOSQUITTO_REVISION defines.
*
* Parameters:
* major - an integer pointer. If not NULL, the major version of the
* library will be returned in this variable.
* minor - an integer pointer. If not NULL, the minor version of the
* library will be returned in this variable.
* revision - an integer pointer. If not NULL, the revision of the library will
* be returned in this variable.
*
* Returns:
* LIBMOSQUITTO_VERSION_NUMBER, which is a unique number based on the major,
* minor and revision values.
* See Also:
* <mosquitto_lib_cleanup>, <mosquitto_lib_init>
*}
function mosquitto_lib_version(major: pcint; minor: pcint; revision: pcint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_lib_init
*
* Must be called before any other mosquitto functions.
*
* This function is *not* thread safe.
*
* Returns:
* MOSQ_ERR_SUCCESS - always
*
* See Also:
* <mosquitto_lib_cleanup>, <mosquitto_lib_version>
*}
function mosquitto_lib_init: cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_lib_cleanup
*
* Call to free resources associated with the library.
*
* Returns:
* MOSQ_ERR_SUCCESS - always
*
* See Also:
* <mosquitto_lib_init>, <mosquitto_lib_version>
*}
function mosquitto_lib_cleanup: cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_new
*
* Create a new mosquitto client instance.
*
* Parameters:
* id - String to use as the client id. If NULL, a random client id
* will be generated. If id is NULL, clean_session must be true.
* clean_session - set to true to instruct the broker to clean all messages
* and subscriptions on disconnect, false to instruct it to
* keep them. See the man page mqtt(7) for more details.
* Note that a client will never discard its own outgoing
* messages on disconnect. Calling <mosquitto_connect> or
* <mosquitto_reconnect> will cause the messages to be resent.
* Use <mosquitto_reinitialise> to reset a client to its
* original state.
* Must be set to true if the id parameter is NULL.
* obj - A user pointer that will be passed as an argument to any
* callbacks that are specified.
*
* Returns:
* Pointer to a struct mosquitto on success.
* NULL on failure. Interrogate errno to determine the cause for the failure:
* - ENOMEM on out of memory.
* - EINVAL on invalid input parameters.
*
* See Also:
* <mosquitto_reinitialise>, <mosquitto_destroy>, <mosquitto_user_data_set>
*}
function mosquitto_new(const id: PChar; clean_session: cbool; obj: Pointer): Pmosquitto; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_destroy
*
* Use to free memory associated with a mosquitto client instance.
*
* Parameters:
* mosq - a struct mosquitto pointer to free.
*
* See Also:
* <mosquitto_new>, <mosquitto_reinitialise>
*}
procedure mosquitto_destroy(mosq: Pmosquitto); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_reinitialise
*
* This function allows an existing mosquitto client to be reused. Call on a
* mosquitto instance to close any open network connections, free memory
* and reinitialise the client with the new parameters. The end result is the
* same as the output of <mosquitto_new>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* id - string to use as the client id. If NULL, a random client id
* will be generated. If id is NULL, clean_session must be true.
* clean_session - set to true to instruct the broker to clean all messages
* and subscriptions on disconnect, false to instruct it to
* keep them. See the man page mqtt(7) for more details.
* Must be set to true if the id parameter is NULL.
* obj - A user pointer that will be passed as an argument to any
* callbacks that are specified.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* See Also:
* <mosquitto_new>, <mosquitto_destroy>
*}
function mosquitto_reinitialise(mosq: Pmosquitto; const id: Pchar; clean_session: cbool; obj: Pointer): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_will_set
*
* Configure will information for a mosquitto instance. By default, clients do
* not have a will. This must be called before calling <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* topic - the topic on which to publish the will.
* payloadlen - the size of the payload (bytes). Valid values are between 0 and
* 268,435,455.
* payload - pointer to the data to send. If payloadlen > 0 this must be a
* valid memory location.
* qos - integer value 0, 1 or 2 indicating the Quality of Service to be
* used for the will.
* retain - set to true to make the will a retained message.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
* MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8.
*}
function mosquitto_will_set(mosq: Pmosquitto; const topic: pchar; payloadlen: cint; const payload: pointer; qos: cint; retain: cbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_will_clear
*
* Remove a previously configured will. This must be called before calling
* <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
*}
function mosquitto_will_clear(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_username_pw_set
*
* Configure username and password for a mosquitton instance. This is only
* supported by brokers that implement the MQTT spec v3.1. By default, no
* username or password will be sent.
* If username is NULL, the password argument is ignored.
* This must be called before calling mosquitto_connect().
*
* This is must be called before calling <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* username - the username to send as a string, or NULL to disable
* authentication.
* password - the password to send as a string. Set to NULL when username is
* valid in order to send just a username.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*}
function mosquitto_username_pw_set(mosq: Pmosquitto; const username: pchar; const password: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect
*
* Connect to an MQTT broker.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the hostname or ip address of the broker to connect to.
* port - the network port to connect to. Usually 1883.
* keepalive - the number of seconds after which the broker should send a PING
* message to the client if no other messages have been exchanged
* in that time.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect_bind>, <mosquitto_connect_async>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
*}
function mosquitto_connect(mosq: Pmosquitto; const host: pchar; port: cint; keepalive: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_bind
*
* Connect to an MQTT broker. This extends the functionality of
* <mosquitto_connect> by adding the bind_address parameter. Use this function
* if you need to restrict network communication over a particular interface.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the hostname or ip address of the broker to connect to.
* port - the network port to connect to. Usually 1883.
* keepalive - the number of seconds after which the broker should send a PING
* message to the client if no other messages have been exchanged
* in that time.
* bind_address - the hostname or ip address of the local network interface to
* bind to.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect>, <mosquitto_connect_async>, <mosquitto_connect_bind_async>
*}
function mosquitto_connect_bind(mosq: Pmosquitto; const host: pchar; port: cint; keepalive: cint; const bind_address: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_async
*
* Connect to an MQTT broker. This is a non-blocking call. If you use
* <mosquitto_connect_async> your client must use the threaded interface
* <mosquitto_loop_start>. If you need to use <mosquitto_loop>, you must use
* <mosquitto_connect> to connect the client.
*
* May be called before or after <mosquitto_loop_start>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the hostname or ip address of the broker to connect to.
* port - the network port to connect to. Usually 1883.
* keepalive - the number of seconds after which the broker should send a PING
* message to the client if no other messages have been exchanged
* in that time.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect_bind_async>, <mosquitto_connect>, <mosquitto_reconnect>, <mosquitto_disconnect>, <mosquitto_tls_set>
*}
function mosquitto_connect_async(mosq: Pmosquitto; const host: pchar; port: cint; keepalive: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_bind_async
*
* Connect to an MQTT broker. This is a non-blocking call. If you use
* <mosquitto_connect_bind_async> your client must use the threaded interface
* <mosquitto_loop_start>. If you need to use <mosquitto_loop>, you must use
* <mosquitto_connect> to connect the client.
*
* This extends the functionality of <mosquitto_connect_async> by adding the
* bind_address parameter. Use this function if you need to restrict network
* communication over a particular interface.
*
* May be called before or after <mosquitto_loop_start>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the hostname or ip address of the broker to connect to.
* port - the network port to connect to. Usually 1883.
* keepalive - the number of seconds after which the broker should send a PING
* message to the client if no other messages have been exchanged
* in that time.
* bind_address - the hostname or ip address of the local network interface to
* bind to.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
*}
function mosquitto_connect_bind_async(mosq: Pmosquitto; const host: pchar; port: cint; keepalive: cint; const bind_address: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_srv
*
* Connect to an MQTT broker. This is a non-blocking call. If you use
* <mosquitto_connect_async> your client must use the threaded interface
* <mosquitto_loop_start>. If you need to use <mosquitto_loop>, you must use
* <mosquitto_connect> to connect the client.
*
* This extends the functionality of <mosquitto_connect_async> by adding the
* bind_address parameter. Use this function if you need to restrict network
* communication over a particular interface.
*
* May be called before or after <mosquitto_loop_start>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the hostname or ip address of the broker to connect to.
* keepalive - the number of seconds after which the broker should send a PING
* message to the client if no other messages have been exchanged
* in that time.
* bind_address - the hostname or ip address of the local network interface to
* bind to.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect_async>, <mosquitto_connect>, <mosquitto_connect_bind>
*}
function mosquitto_connect_srv(mosq: Pmosquitto; const host: pchar; keepalive: cint; const bind_address: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_reconnect
*
* Reconnect to a broker.
*
* This function provides an easy way of reconnecting to a broker after a
* connection has been lost. It uses the values that were provided in the
* <mosquitto_connect> call. It must not be called before
* <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect>, <mosquitto_disconnect>, <mosquitto_reconnect_async>
*}
function mosquitto_reconnect(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_reconnect_async
*
* Reconnect to a broker. Non blocking version of <mosquitto_reconnect>.
*
* This function provides an easy way of reconnecting to a broker after a
* connection has been lost. It uses the values that were provided in the
* <mosquitto_connect> or <mosquitto_connect_async> calls. It must not be
* called before <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_connect>, <mosquitto_disconnect>
*}
function mosquitto_reconnect_async(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_disconnect
*
* Disconnect from the broker.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
*}
function mosquitto_disconnect(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_publish
*
* Publish a message on a given topic.
*
* Parameters:
* mosq - a valid mosquitto instance.
* mid - pointer to an int. If not NULL, the function will set this
* to the message id of this particular message. This can be then
* used with the publish callback to determine when the message
* has been sent.
* Note that although the MQTT protocol doesn't use message ids
* for messages with QoS=0, libmosquitto assigns them message ids
* so they can be tracked with this parameter.
* topic - null terminated string of the topic to publish to.
* payloadlen - the size of the payload (bytes). Valid values are between 0 and
* 268,435,455.
* payload - pointer to the data to send. If payloadlen > 0 this must be a
* valid memory location.
* qos - integer value 0, 1 or 2 indicating the Quality of Service to be
* used for the message.
* retain - set to true to make the message retained.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the
* broker.
* MOSQ_ERR_PAYLOAD_SIZE - if payloadlen is too large.
* MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8
* See Also:
* <mosquitto_max_inflight_messages_set>
*}
function mosquitto_publish(mosq: Pmosquitto; mid: pcint; const topic: pchar; payloadlen: cint; const payload: pointer; qos: cint; retain: cbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_subscribe
*
* Subscribe to a topic.
*
* Parameters:
* mosq - a valid mosquitto instance.
* mid - a pointer to an int. If not NULL, the function will set this to
* the message id of this particular message. This can be then used
* with the subscribe callback to determine when the message has been
* sent.
* sub - the subscription pattern.
* qos - the requested Quality of Service for this subscription.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8
*}
function mosquitto_subscribe(mosq: Pmosquitto; mid: pcint; const sub: pchar; qos: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_unsubscribe
*
* Unsubscribe from a topic.
*
* Parameters:
* mosq - a valid mosquitto instance.
* mid - a pointer to an int. If not NULL, the function will set this to
* the message id of this particular message. This can be then used
* with the unsubscribe callback to determine when the message has been
* sent.
* sub - the unsubscription pattern.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8
*}
function mosquitto_unsubscribe(mosq: Pmosquitto; mid: pcint; const sub: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_message_copy
*
* Copy the contents of a mosquitto message to another message.
* Useful for preserving a message received in the on_message() callback.
*
* Parameters:
* dst - a pointer to a valid mosquitto_message struct to copy to.
* src - a pointer to a valid mosquitto_message struct to copy from.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* See Also:
* <mosquitto_message_free>
*}
function mosquitto_message_copy(dst: Pmosquitto_message; const src: Pmosquitto_message): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_message_free
*
* Completely free a mosquitto_message struct.
*
* Parameters:
* message - pointer to a mosquitto_message pointer to free.
*
* See Also:
* <mosquitto_message_copy>, <mosquitto_message_free_contents>
*}
procedure mosquitto_message_free(message: PPmosquitto_message); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_message_free_contents
*
* Free a mosquitto_message struct contents, leaving the struct unaffected.
*
* Parameters:
* message - pointer to a mosquitto_message struct to free its contents.
*
* See Also:
* <mosquitto_message_copy>, <mosquitto_message_free>
*}
procedure mosquitto_message_free_contents(mosquitto_message: Pmosquitto_message); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop
*
* The main network loop for the client. You must call this frequently in order
* to keep communications between the client and broker working. If incoming
* data is present it will then be processed. Outgoing commands, from e.g.
* <mosquitto_publish>, are normally sent immediately that their function is
* called, but this is not always possible. <mosquitto_loop> will also attempt
* to send any remaining outgoing messages, which also includes commands that
* are part of the flow for messages with QoS>0.
*
* An alternative approach is to use <mosquitto_loop_start> to run the client
* loop in its own thread.
*
* This calls select() to monitor the client network socket. If you want to
* integrate mosquitto client operation with your own select() call, use
* <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write> and
* <mosquitto_loop_misc>.
*
* Threads:
*
* Parameters:
* mosq - a valid mosquitto instance.
* timeout - Maximum number of milliseconds to wait for network activity
* in the select() call before timing out. Set to 0 for instant
* return. Set negative to use the default of 1000ms.
* max_packets - this parameter is currently unused and should be set to 1 for
* future compatibility.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
* MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the
* broker.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
* See Also:
* <mosquitto_loop_forever>, <mosquitto_loop_start>, <mosquitto_loop_stop>
*}
function mosquitto_loop(mosq: Pmosquitto; timeout: cint; max_packets: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_forever
*
* This function call loop() for you in an infinite blocking loop. It is useful
* for the case where you only want to run the MQTT client loop in your
* program.
*
* It handles reconnecting in case server connection is lost. If you call
* mosquitto_disconnect() in a callback it will return.
*
* Parameters:
* mosq - a valid mosquitto instance.
* timeout - Maximum number of milliseconds to wait for network activity
* in the select() call before timing out. Set to 0 for instant
* return. Set negative to use the default of 1000ms.
* max_packets - this parameter is currently unused and should be set to 1 for
* future compatibility.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
* MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the
* broker.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_loop>, <mosquitto_loop_start>
*}
function mosquitto_loop_forever(mosq: Pmosquitto; timeout: cint; max_packets: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_start
*
* This is part of the threaded client interface. Call this once to start a new
* thread to process network traffic. This provides an alternative to
* repeatedly calling <mosquitto_loop> yourself.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
*
* See Also:
* <mosquitto_connect_async>, <mosquitto_loop>, <mosquitto_loop_forever>, <mosquitto_loop_stop>
*}
function mosquitto_loop_start(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_stop
*
* This is part of the threaded client interface. Call this once to stop the
* network thread previously created with <mosquitto_loop_start>. This call
* will block until the network thread finishes. For the network thread to end,
* you must have previously called <mosquitto_disconnect> or have set the force
* parameter to true.
*
* Parameters:
* mosq - a valid mosquitto instance.
* force - set to true to force thread cancellation. If false,
* <mosquitto_disconnect> must have already been called.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOT_SUPPORTED - if thread support is not available.
*
* See Also:
* <mosquitto_loop>, <mosquitto_loop_start>
*}
function mosquitto_loop_stop(mosq: Pmosquitto; force: cbool): cint; cdecl external libmosq_NAME;
{*
* Function: mosquitto_socket
*
* Return the socket handle for a mosquitto instance. Useful if you want to
* include a mosquitto client in your own select() calls.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* The socket for the mosquitto client or -1 on failure.
*}
function mosquitto_socket(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_read
*
* Carry out network read operations.
* This should only be used if you are not using mosquitto_loop() and are
* monitoring the client network socket for activity yourself.
*
* Parameters:
* mosq - a valid mosquitto instance.
* max_packets - this parameter is currently unused and should be set to 1 for
* future compatibility.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
* MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the
* broker.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_socket>, <mosquitto_loop_write>, <mosquitto_loop_misc>
*}
function mosquitto_loop_read(mosq: Pmosquitto; max_packets: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_write
*
* Carry out network write operations.
* This should only be used if you are not using mosquitto_loop() and are
* monitoring the client network socket for activity yourself.
*
* Parameters:
* mosq - a valid mosquitto instance.
* max_packets - this parameter is currently unused and should be set to 1 for
* future compatibility.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
* MOSQ_ERR_CONN_LOST - if the connection to the broker was lost.
* MOSQ_ERR_PROTOCOL - if there is a protocol error communicating with the
* broker.
* MOSQ_ERR_ERRNO - if a system call returned an error. The variable errno
* contains the error code, even on Windows.
* Use strerror_r() where available or FormatMessage() on
* Windows.
*
* See Also:
* <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_misc>, <mosquitto_want_write>
*}
function mosquitto_loop_write(mosq: Pmosquitto; max_packets: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_loop_misc
*
* Carry out miscellaneous operations required as part of the network loop.
* This should only be used if you are not using mosquitto_loop() and are
* monitoring the client network socket for activity yourself.
*
* This function deals with handling PINGs and checking whether messages need
* to be retried, so should be called fairly frequently.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NO_CONN - if the client isn't connected to a broker.
*
* See Also:
* <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
*}
function mosquitto_loop_misc(mosq: Pmosquitto): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_want_write
*
* Returns true if there is data ready to be written on the socket.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* See Also:
* <mosquitto_socket>, <mosquitto_loop_read>, <mosquitto_loop_write>
*}
function mosquitto_want_write(mosq: Pmosquitto): cbool; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_threaded_set
*
* Used to tell the library that your application is using threads, but not
* using <mosquitto_loop_start>. The library operates slightly differently when
* not in threaded mode in order to simplify its operation. If you are managing
* your own threads and do not use this function you will experience crashes
* due to race conditions.
*
* When using <mosquitto_loop_start>, this is set automatically.
*
* Parameters:
* mosq - a valid mosquitto instance.
* threaded - true if your application is using threads, false otherwise.
*}
function mosquitto_threaded_set(mosq: Pmosquitto; threaded: cbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_opts_set
*
* Used to set options for the client.
*
* Parameters:
* mosq - a valid mosquitto instance.
* option - the option to set.
* value - the option specific value.
*
* Options:
* MOSQ_OPT_PROTOCOL_VERSION
* Value must be an int, set to either MQTT_PROTOCOL_V31 or
* MQTT_PROTOCOL_V311. Must be set before the client connects.
* Defaults to MQTT_PROTOCOL_V31.
*
* MOSQ_OPT_SSL_CTX
* Pass an openssl SSL_CTX to be used when creating TLS connections
* rather than libmosquitto creating its own. This must be called
* before connecting to have any effect. If you use this option, the
* onus is on you to ensure that you are using secure settings.
* Setting to NULL means that libmosquitto will use its own SSL_CTX
* if TLS is to be used.
* This option is only available for openssl 1.1.0 and higher.
*
* MOSQ_OPT_SSL_CTX_WITH_DEFAULTS
* Value must be an int set to 1 or 0. If set to 1, then the user
* specified SSL_CTX passed in using MOSQ_OPT_SSL_CTX will have the
* default options applied to it. This means that you only need to
* change the values that are relevant to you. If you use this
* option then you must configure the TLS options as normal, i.e.
* you should use <mosquitto_tls_set> to configure the cafile/capath
* as a minimum.
* This option is only available for openssl 1.1.0 and higher.
*}
function mosquitto_opts_set(mosq: Pmosquitto; option: cint; value: pointer): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_tls_set
*
* Configure the client for certificate based SSL/TLS support. Must be called
* before <mosquitto_connect>.
*
* Cannot be used in conjunction with <mosquitto_tls_psk_set>.
*
* Define the Certificate Authority certificates to be trusted (ie. the server
* certificate must be signed with one of these certificates) using cafile.
*
* If the server you are connecting to requires clients to provide a
* certificate, define certfile and keyfile with your client certificate and
* private key. If your private key is encrypted, provide a password callback
* function or you will have to enter the password at the command line.
*
* Parameters:
* mosq - a valid mosquitto instance.
* cafile - path to a file containing the PEM encoded trusted CA
* certificate files. Either cafile or capath must not be NULL.
* capath - path to a directory containing the PEM encoded trusted CA
* certificate files. See mosquitto.conf for more details on
* configuring this directory. Either cafile or capath must not
* be NULL.
* certfile - path to a file containing the PEM encoded certificate file
* for this client. If NULL, keyfile must also be NULL and no
* client certificate will be used.
* keyfile - path to a file containing the PEM encoded private key for
* this client. If NULL, certfile must also be NULL and no
* client certificate will be used.
* pw_callback - if keyfile is encrypted, set pw_callback to allow your client
* to pass the correct password for decryption. If set to NULL,
* the password must be entered on the command line.
* Your callback must write the password into "buf", which is
* "size" bytes long. The return value must be the length of the
* password. "userdata" will be set to the calling mosquitto
* instance. The mosquitto userdata member variable can be
* retrieved using <mosquitto_userdata>.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* See Also:
* <mosquitto_tls_opts_set>, <mosquitto_tls_psk_set>,
* <mosquitto_tls_insecure_set>, <mosquitto_userdata>
*}
type
Tpw_callback = function(buf: pchar; size: cint; rwflag: cint; userdata: pointer): cint; cdecl;
function mosquitto_tls_set(mosq: Pmosquitto;
const cafile: pchar; const capath: pchar;
const certfile: pchar; const keyfile: pchar;
pw_callback: Tpw_callback): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_tls_insecure_set
*
* Configure verification of the server hostname in the server certificate. If
* value is set to true, it is impossible to guarantee that the host you are
* connecting to is not impersonating your server. This can be useful in
* initial server testing, but makes it possible for a malicious third party to
* impersonate your server through DNS spoofing, for example.
* Do not use this function in a real system. Setting value to true makes the
* connection encryption pointless.
* Must be called before <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* value - if set to false, the default, certificate hostname checking is
* performed. If set to true, no hostname checking is performed and
* the connection is insecure.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
*
* See Also:
* <mosquitto_tls_set>
*}
function mosquitto_tls_insecure_set(mosq: Pmosquitto; value: cbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_tls_opts_set
*
* Set advanced SSL/TLS options. Must be called before <mosquitto_connect>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* cert_reqs - an integer defining the verification requirements the client
* will impose on the server. This can be one of:
* * SSL_VERIFY_NONE (0): the server will not be verified in any way.
* * SSL_VERIFY_PEER (1): the server certificate will be verified
* and the connection aborted if the verification fails.
* The default and recommended value is SSL_VERIFY_PEER. Using
* SSL_VERIFY_NONE provides no security.
* tls_version - the version of the SSL/TLS protocol to use as a string. If NULL,
* the default value is used. The default value and the
* available values depend on the version of openssl that the
* library was compiled against. For openssl >= 1.0.1, the
* available options are tlsv1.2, tlsv1.1 and tlsv1, with tlv1.2
* as the default. For openssl < 1.0.1, only tlsv1 is available.
* ciphers - a string describing the ciphers available for use. See the
* "openssl ciphers" tool for more information. If NULL, the
* default ciphers will be used.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* See Also:
* <mosquitto_tls_set>
*}
function mosquitto_tls_opts_set(mosq: Pmosquitto; cert_reqs: cint; const tls_version: pchar; const ciphers: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_tls_psk_set
*
* Configure the client for pre-shared-key based TLS support. Must be called
* before <mosquitto_connect>.
*
* Cannot be used in conjunction with <mosquitto_tls_set>.
*
* Parameters:
* mosq - a valid mosquitto instance.
* psk - the pre-shared-key in hex format with no leading "0x".
* identity - the identity of this client. May be used as the username
* depending on the server settings.
* ciphers - a string describing the PSK ciphers available for use. See the
* "openssl ciphers" tool for more information. If NULL, the
* default ciphers will be used.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*
* See Also:
* <mosquitto_tls_set>
*}
function mosquitto_tls_psk_set(mosq: Pmosquitto; const psk: pchar; const identity: pchar; const ciphers: pchar): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_callback_set
*
* Set the connect callback. This is called when the broker sends a CONNACK
* message in response to a connection.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_connect - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, int rc)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* rc - the return code of the connection response, one of:
*
* * 0 - success
* * 1 - connection refused (unacceptable protocol version)
* * 2 - connection refused (identifier rejected)
* * 3 - connection refused (broker unavailable)
* * 4-255 - reserved for future use
*}
type
Ton_connect_callback = procedure(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl;
procedure mosquitto_connect_callback_set(mosq: Pmosquitto; on_connect: Ton_connect_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connect_with_flags_callback_set
*
* Set the connect callback. This is called when the broker sends a CONNACK
* message in response to a connection.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_connect - a callback function in the following form:
* void callback(struct mosquitto *mosq, void *obj, int rc)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* rc - the return code of the connection response, one of:
* flags - the connect flags.
*
* * 0 - success
* * 1 - connection refused (unacceptable protocol version)
* * 2 - connection refused (identifier rejected)
* * 3 - connection refused (broker unavailable)
* * 4-255 - reserved for future use
*}
type
Ton_connect_with_flags_callback = procedure(mosq: Pmosquitto; obj: pointer; _unknown1: cint; _unknown2: cint); cdecl;
procedure mosquitto_connect_with_flags_callback_set(mosq: Pmosquitto; on_connect: Ton_connect_with_flags_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_disconnect_callback_set
*
* Set the disconnect callback. This is called when the broker has received the
* DISCONNECT command and has disconnected the client.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_disconnect - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* rc - integer value indicating the reason for the disconnect. A value of 0
* means the client has called <mosquitto_disconnect>. Any other value
* indicates that the disconnect is unexpected.
*}
type
Ton_disconnect_callback = procedure(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl;
procedure mosquitto_disconnect_callback_set(mosq: Pmosquitto; on_disconnect: Ton_disconnect_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_publish_callback_set
*
* Set the publish callback. This is called when a message initiated with
* <mosquitto_publish> has been sent to the broker successfully.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_publish - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, int mid)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* mid - the message id of the sent message.
*}
type
Ton_publish_callback = procedure(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl;
procedure mosquitto_publish_callback_set(mosq: Pmosquitto; on_publish: Ton_publish_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_message_callback_set
*
* Set the message callback. This is called when a message is received from the
* broker.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_message - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, const struct mosquitto_message *message)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* message - the message data. This variable and associated memory will be
* freed by the library after the callback completes. The client
* should make copies of any of the data it requires.
*
* See Also:
* <mosquitto_message_copy>
*}
type
Ton_message_callback = procedure(mosq: Pmosquitto; obj: pointer; const message: Pmosquitto_message); cdecl;
procedure mosquitto_message_callback_set(mosq: Pmosquitto; on_message: Ton_message_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_subscribe_callback_set
*
* Set the subscribe callback. This is called when the broker responds to a
* subscription request.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_subscribe - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, int mid, int qos_count, const int *granted_qos)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* mid - the message id of the subscribe message.
* qos_count - the number of granted subscriptions (size of granted_qos).
* granted_qos - an array of integers indicating the granted QoS for each of
* the subscriptions.
*}
type
Ton_subscribe_callback = procedure(mosq: Pmosquitto; obj: pointer; mid: cint; qos_count: cint; const granted_qos: pcint); cdecl;
procedure mosquitto_subscribe_callback_set(mosq: Pmosquitto; on_subscribe: Ton_subscribe_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_unsubscribe_callback_set
*
* Set the unsubscribe callback. This is called when the broker responds to a
* unsubscription request.
*
* Parameters:
* mosq - a valid mosquitto instance.
* on_unsubscribe - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, int mid)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* mid - the message id of the unsubscribe message.
*}
type
Ton_unsubscribe_callback = procedure(mosq: Pmosquitto; obj: pointer; mid: cint); cdecl;
procedure mosquitto_unsubscribe_callback_set(mosq: Pmosquitto; on_unsubscribe: Ton_unsubscribe_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_log_callback_set
*
* Set the logging callback. This should be used if you want event logging
* information from the client library.
*
* mosq - a valid mosquitto instance.
* on_log - a callback function in the following form:
* void callback(mosq: Pmosquitto, void *obj, int level, const char *str)
*
* Callback Parameters:
* mosq - the mosquitto instance making the callback.
* obj - the user data provided in <mosquitto_new>
* level - the log message level from the values:
* MOSQ_LOG_INFO
* MOSQ_LOG_NOTICE
* MOSQ_LOG_WARNING
* MOSQ_LOG_ERR
* MOSQ_LOG_DEBUG
* str - the message string.
*}
type
Ton_log_callback = procedure(mosq: Pmosquitto; obj: pointer; level: cint; const str: pchar); cdecl;
procedure mosquitto_log_callback_set(mosq: Pmosquitto; on_log: Ton_log_callback); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_reconnect_delay_set
*
* Control the behaviour of the client when it has unexpectedly disconnected in
* <mosquitto_loop_forever> or after <mosquitto_loop_start>. The default
* behaviour if this function is not used is to repeatedly attempt to reconnect
* with a delay of 1 second until the connection succeeds.
*
* Use reconnect_delay parameter to change the delay between successive
* reconnection attempts. You may also enable exponential backoff of the time
* between reconnections by setting reconnect_exponential_backoff to true and
* set an upper bound on the delay with reconnect_delay_max.
*
* Example 1:
* delay=2, delay_max=10, exponential_backoff=False
* Delays would be: 2, 4, 6, 8, 10, 10, ...
*
* Example 2:
* delay=3, delay_max=30, exponential_backoff=True
* Delays would be: 3, 6, 12, 24, 30, 30, ...
*
* Parameters:
* mosq - a valid mosquitto instance.
* reconnect_delay - the number of seconds to wait between
* reconnects.
* reconnect_delay_max - the maximum number of seconds to wait
* between reconnects.
* reconnect_exponential_backoff - use exponential backoff between
* reconnect attempts. Set to true to enable
* exponential backoff.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
*}
function mosquitto_reconnect_delay_set(mosq: Pmosquitto; reconnect_delay: cuint; reconnect_delay_max: cuint; reconnect_exponential_backoff: cbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_max_inflight_messages_set
*
* Set the number of QoS 1 and 2 messages that can be "in flight" at one time.
* An in flight message is part way through its delivery flow. Attempts to send
* further messages with <mosquitto_publish> will result in the messages being
* queued until the number of in flight messages reduces.
*
* A higher number here results in greater message throughput, but if set
* higher than the maximum in flight messages on the broker may lead to
* delays in the messages being acknowledged.
*
* Set to 0 for no maximum.
*
* Parameters:
* mosq - a valid mosquitto instance.
* max_inflight_messages - the maximum number of inflight messages. Defaults
* to 20.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success.
* MOSQ_ERR_INVAL - if the input parameters were invalid.
*}
function mosquitto_max_inflight_messages_set(mosq: Pmosquitto; max_inflight_messages: cuint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_message_retry_set
*
* This function now has no effect.
*}
procedure mosquitto_message_retry_set(mosq: Pmosquitto; message_retry: cuint); cdecl; external libmosq_NAME;
{*
* Function: mosquitto_user_data_set
*
* When <mosquitto_new> is called, the pointer given as the "obj" parameter
* will be passed to the callbacks as user data. The <mosquitto_user_data_set>
* function allows this obj parameter to be updated at any time. This function
* will not modify the memory pointed to by the current user data pointer. If
* it is dynamically allocated memory you must free it yourself.
*
* Parameters:
* mosq - a valid mosquitto instance.
* obj - A user pointer that will be passed as an argument to any callbacks
* that are specified.
*}
procedure mosquitto_user_data_set(mosq: Pmosquitto; obj: pointer); cdecl; external libmosq_NAME;
{* =============================================================================
*
* Section: SOCKS5 proxy functions
*
* =============================================================================
*}
{*
* Function: mosquitto_socks5_set
*
* Configure the client to use a SOCKS5 proxy when connecting. Must be called
* before connecting. "None" and "username/password" authentication is
* supported.
*
* Parameters:
* mosq - a valid mosquitto instance.
* host - the SOCKS5 proxy host to connect to.
* port - the SOCKS5 proxy port to use.
* username - if not NULL, use this username when authenticating with the proxy.
* password - if not NULL and username is not NULL, use this password when
* authenticating with the proxy.
*}
function mosquitto_socks5_set(mosq: Pmosquitto; const host: pchar; port: cint; const username: pchar; const password: pchar): cint; cdecl; external libmosq_NAME;
{* =============================================================================
*
* Section: Utility functions
*
* =============================================================================
*}
{*
* Function: mosquitto_strerror
*
* Call to obtain a const string description of a mosquitto error number.
*
* Parameters:
* mosq_errno - a mosquitto error number.
*
* Returns:
* A constant string describing the error.
*}
function mosquitto_strerror(mosq_errno: cint): pchar; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_connack_string
*
* Call to obtain a const string description of an MQTT connection result.
*
* Parameters:
* connack_code - an MQTT connection result.
*
* Returns:
* A constant string describing the result.
*}
function mosquitto_connack_string(connack_code: cint): pchar; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_sub_topic_tokenise
*
* Tokenise a topic or subscription string into an array of strings
* representing the topic hierarchy.
*
* For example:
*
* subtopic: "a/deep/topic/hierarchy"
*
* Would result in:
*
* topics[0] = "a"
* topics[1] = "deep"
* topics[2] = "topic"
* topics[3] = "hierarchy"
*
* and:
*
* subtopic: "/a/deep/topic/hierarchy/"
*
* Would result in:
*
* topics[0] = NULL
* topics[1] = "a"
* topics[2] = "deep"
* topics[3] = "topic"
* topics[4] = "hierarchy"
*
* Parameters:
* subtopic - the subscription/topic to tokenise
* topics - a pointer to store the array of strings
* count - an int pointer to store the number of items in the topics array.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
* MOSQ_ERR_MALFORMED_UTF8 - if the topic is not valid UTF-8
*
* Example:
*
* > char **topics;
* > int topic_count;
* > int i;
* >
* > mosquitto_sub_topic_tokenise("$SYS/broker/uptime", &topics, &topic_count);
* >
* > for(i=0; i<token_count; i++)(
* > printf("%d: %s\n", i, topics[i]);
* > )
*
* See Also:
* <mosquitto_sub_topic_tokens_free>
*}
function mosquitto_sub_topic_tokenise(const subtopic: pchar; var topics: ppchar; count: pcint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_sub_topic_tokens_free
*
* Free memory that was allocated in <mosquitto_sub_topic_tokenise>.
*
* Parameters:
* topics - pointer to string array.
* count - count of items in string array.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* MOSQ_ERR_INVAL - if the input parameters were invalid.
*
* See Also:
* <mosquitto_sub_topic_tokenise>
*}
function mosquitto_sub_topic_tokens_free(var topics: ppchar; count: cint): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_topic_matches_sub
* Function: mosquitto_topic_matches_sub2
*
* Check whether a topic matches a subscription.
*
* For example:
*
* foo/bar would match the subscription foo/# or +/bar
* non/matching would not match the subscription non/+/+
*
* Parameters:
* sub - subscription string to check topic against.
* sublen - length in bytes of sub string
* topic - topic to check.
* topiclen - length in bytes of topic string
* result - bool pointer to hold result. Will be set to true if the topic
* matches the subscription.
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* MOSQ_ERR_INVAL - if the input parameters were invalid.
* MOSQ_ERR_NOMEM - if an out of memory condition occurred.
*}
function mosquitto_topic_matches_sub(const sub: pchar; const topic: pchar; result: pcbool): cint; cdecl; external libmosq_NAME;
function mosquitto_topic_matches_sub2(const sub: pchar; sublen: csize_t; const topic: pchar; topiclen: csize_t; result: pcbool): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_pub_topic_check
*
* Check whether a topic to be used for publishing is valid.
*
* This searches for + or # in a topic and checks its length.
*
* This check is already carried out in <mosquitto_publish> and
* <mosquitto_will_set>, there is no need to call it directly before them. It
* may be useful if you wish to check the validity of a topic in advance of
* making a connection for example.
*
* Parameters:
* topic - the topic to check
* topiclen - length of the topic in bytes
*
* Returns:
* MOSQ_ERR_SUCCESS - for a valid topic
* MOSQ_ERR_INVAL - if the topic contains a + or a #, or if it is too long.
* MOSQ_ERR_MALFORMED_UTF8 - if sub or topic is not valid UTF-8
*
* See Also:
* <mosquitto_sub_topic_check>
*}
function mosquitto_pub_topic_check(const topic: pchar): cint; cdecl; external libmosq_NAME;
function mosquitto_pub_topic_check2(const topic: pchar; topiclen: csize_t): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_sub_topic_check
*
* Check whether a topic to be used for subscribing is valid.
*
* This searches for + or # in a topic and checks that they aren't in invalid
* positions, such as with foo/#/bar, foo/+bar or foo/bar#, and checks its
* length.
*
* This check is already carried out in <mosquitto_subscribe> and
* <mosquitto_unsubscribe>, there is no need to call it directly before them.
* It may be useful if you wish to check the validity of a topic in advance of
* making a connection for example.
*
* Parameters:
* topic - the topic to check
* topiclen - the length in bytes of the topic
*
* Returns:
* MOSQ_ERR_SUCCESS - for a valid topic
* MOSQ_ERR_INVAL - if the topic contains a + or a # that is in an
* invalid position, or if it is too long.
* MOSQ_ERR_MALFORMED_UTF8 - if topic is not valid UTF-8
*
* See Also:
* <mosquitto_sub_topic_check>
*}
function mosquitto_sub_topic_check(const topic: pchar): cint; cdecl; external libmosq_NAME;
function mosquitto_sub_topic_check2(const topic: pchar; topiclen: csize_t): cint; cdecl; external libmosq_NAME;
type
Plibmosquitto_will = ^Tlibmosquitto_will;
Tlibmosquitto_will = record
topic: pchar;
payload: pointer;
payloadlen: cint;
qos: cint;
retain: cbool;
end;
type
Plibmosquitto_auth = ^Tlibmosquitto_auth;
Tlibmosquitto_auth = record
username: pchar;
password: pchar;
end;
type
Ttls_pw_callback = function(buf: pchar; size: cint; rwflag: cint; userdata: pointer): cint; cdecl;
type
Plibmosquitto_tls = ^Tlibmosquitto_tls;
Tlibmosquitto_tls = record
cafile: pchar;
capath: pchar;
certfile: pchar;
keyfile: pchar;
ciphers: pchar;
tls_version: pchar;
pw_callback: Ttls_pw_callback;
cert_reqs: cint;
end;
{*
* Function: mosquitto_subscribe_simple
*
* Helper function to make subscribing to a topic and retrieving some messages
* very straightforward.
*
* This connects to a broker, subscribes to a topic, waits for msg_count
* messages to be received, then returns after disconnecting cleanly.
*
* Parameters:
* messages - pointer to a "struct mosquitto_message *". The received
* messages will be returned here. On error, this will be set to
* NULL.
* msg_count - the number of messages to retrieve.
* want_retained - if set to true, stale retained messages will be treated as
* normal messages with regards to msg_count. If set to
* false, they will be ignored.
* topic - the subscription topic to use (wildcards are allowed).
* qos - the qos to use for the subscription.
* host - the broker to connect to.
* port - the network port the broker is listening on.
* client_id - the client id to use, or NULL if a random client id should be
* generated.
* keepalive - the MQTT keepalive value.
* clean_session - the MQTT clean session flag.
* username - the username string, or NULL for no username authentication.
* password - the password string, or NULL for an empty password.
* will - a libmosquitto_will struct containing will information, or NULL for
* no will.
* tls - a libmosquitto_tls struct containing TLS related parameters, or NULL
* for no use of TLS.
*
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* >0 - on error.
*}
function mosquitto_subscribe_simple(messages: PPmosquitto_message;
msg_count: cint;
want_retained: cbool;
const topic: pchar;
qos: cint;
const host: pchar;
port: cint;
const client_id: pchar;
keepalive: cint;
clean_session: cbool;
const username: pchar;
const password: pchar;
const will: Plibmosquitto_will;
const tls: Plibmosquitto_tls): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_subscribe_callback
*
* Helper function to make subscribing to a topic and processing some messages
* very straightforward.
*
* This connects to a broker, subscribes to a topic, then passes received
* messages to a user provided callback. If the callback returns a 1, it then
* disconnects cleanly and returns.
*
* Parameters:
* callback - a callback function in the following form:
* int callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
* Note that this is the same as the normal on_message callback,
* except that it returns an int.
* userdata - user provided pointer that will be passed to the callback.
* topic - the subscription topic to use (wildcards are allowed).
* qos - the qos to use for the subscription.
* host - the broker to connect to.
* port - the network port the broker is listening on.
* client_id - the client id to use, or NULL if a random client id should be
* generated.
* keepalive - the MQTT keepalive value.
* clean_session - the MQTT clean session flag.
* username - the username string, or NULL for no username authentication.
* password - the password string, or NULL for an empty password.
* will - a libmosquitto_will struct containing will information, or NULL for
* no will.
* tls - a libmosquitto_tls struct containing TLS related parameters, or NULL
* for no use of TLS.
*
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* >0 - on error.
*}
function mosquitto_subscribe_callback(callback: Ton_message_callback;
userdata: pointer;
const topic: pchar;
qos: cint;
const host: pchar;
port: cint;
const client_id: pchar;
keepalive: cint;
clean_session: cbool;
const username: pchar;
const password: pchar;
const will: Plibmosquitto_will;
const tls: Plibmosquitto_tls): cint; cdecl; external libmosq_NAME;
{*
* Function: mosquitto_validate_utf8
*
* Helper function to validate whether a UTF-8 string is valid, according to
* the UTF-8 spec and the MQTT additions.
*
* Parameters:
* str - a string to check
* len - the length of the string in bytes
*
* Returns:
* MOSQ_ERR_SUCCESS - on success
* MOSQ_ERR_INVAL - if str is NULL or len<0 or len>65536
* MOSQ_ERR_MALFORMED_UTF8 - if str is not valid UTF-8
*}
function mosquitto_validate_utf8(const str: pchar; len: cint): cint; cdecl; external libmosq_NAME;
{* Function: mosquitto_userdata
*
* Retrieve the "userdata" variable for a mosquitto client.
*
* Parameters:
* mosq - a valid mosquitto instance.
*
* Returns:
* A pointer to the userdata member variable.
*}
function mosquitto_userdata(mosq: Pmosquitto): pointer; cdecl; external libmosq_NAME;
implementation
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uDB, Vcl.StdCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids,
System.Actions, Vcl.ActnList, Vcl.ComCtrls, uController.Interfaces;
type
TOperacao = (opNone, opInsert, opUpdate, opView);
TForm1 = class(TForm)
Button1: TButton;
ActionList1: TActionList;
actInsert: TAction;
actEdit: TAction;
actDelete: TAction;
actLocate: TAction;
actView: TAction;
actSave: TAction;
actCancel: TAction;
actClose: TAction;
DS: TDataSource;
PageControl1: TPageControl;
TabLista: TTabSheet;
TabEdicao: TTabSheet;
Grid: TDBGrid;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
edtLocate: TEdit;
Button6: TButton;
Button7: TButton;
procedure FormCreate(Sender: TObject);
procedure actInsertExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actLocateExecute(Sender: TObject);
procedure actViewExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure actCancelExecute(Sender: TObject);
procedure actCloseExecute(Sender: TObject);
procedure edtLocateExit(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FCtrl: iPessoaController;
FOperacao: TOperacao;
procedure Status;
function doSave: Boolean;
procedure TesteConexao;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
uController.Pessoa;
{$R *.dfm}
procedure TForm1.actCancelExecute(Sender: TObject);
begin
FOperacao := opNone;
PageControl1.ActivePage := TabLista;
end;
procedure TForm1.actCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TForm1.actDeleteExecute(Sender: TObject);
begin
//
end;
procedure TForm1.actEditExecute(Sender: TObject);
begin
FOperacao := opUpdate;
PageControl1.ActivePage := TabEdicao;
end;
procedure TForm1.actInsertExecute(Sender: TObject);
begin
FOperacao := opInsert;
PageControl1.ActivePage := TabEdicao;
end;
procedure TForm1.actLocateExecute(Sender: TObject);
begin
// FCtrl.Model.Id(1);
FCtrl.get(StrToIntDef(edtLocate.Text,0));
end;
function TForm1.doSave: Boolean;
begin
Result := True;
end;
procedure TForm1.edtLocateExit(Sender: TObject);
begin
actLocateExecute(nil);
end;
procedure TForm1.actSaveExecute(Sender: TObject);
begin
if doSave then begin
FOperacao := opNone;
PageControl1.ActivePage := TabLista;
end;
end;
procedure TForm1.actViewExecute(Sender: TObject);
begin
FOperacao := opView;
PageControl1.ActivePage := TabEdicao;
end;
procedure TForm1.TesteConexao;
begin
try
TDB.getInstance.Conexao.Connected := True;
ShowMessage('Conectado');
TDB.getInstance.Conexao.Connected := False;
except on E: Exception do
ShowMessage(E.Message);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FOperacao := opNone;
PageControl1.ActivePage := TabLista;
FCtrl := TPessoaController.New(DS);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
// TesteConexao;
FCtrl.get(0);
end;
procedure TForm1.Status;
begin
actLocate.Enabled := (FOperacao = opNone);
actInsert.Enabled := (FOperacao = opNone);
actEdit.Enabled := (FOperacao = opNone) and (DS.DataSet <> nil) and (not DS.DataSet.IsEmpty);
actView.Enabled := (FOperacao = opNone) and (DS.DataSet <> nil) and (not DS.DataSet.IsEmpty);
actDelete.Enabled := (FOperacao = opNone) and (DS.DataSet <> nil) and (not DS.DataSet.IsEmpty);
actSave.Enabled := (FOperacao in [opInsert, opUpdate]);
actCancel.Enabled := (FOperacao in [opInsert, opUpdate, opView]);
actClose.Enabled := (FOperacao = opNone);
end;
end.
|
{ $Log: C:\PROGRAM FILES\GP-VERSION LITE\Archives\Reve64\Source\CBConversionUtils.paV
{
{ Rev 1.0 28/09/03 20:28:22 Dgrava
{ Initial Revision
}
{
Rev 1.2 10-3-2003 21:46:23 DGrava
Little enhancements.
}
{
Rev 1.1 6-2-2003 11:48:01 DGrava
Introduction of QuickEval component.
}
{
Rev 1.0 24-1-2003 21:12:22 DGrava
Eerste Check in.
Versie 0.27
}
unit CBConversionUtils;
{This unit contains routines to convert between a native board and
a CB type board.}
interface
uses
CBTypes, ReveTypes;
const
STDBOARD : TCBBoard = (
(4, 0, 12, 0, 20, 0, 28, 0),
(0, 8, 0, 16, 0, 24, 0, 32),
(3, 0, 11, 0, 19, 0, 27, 0),
(0, 7, 0, 15, 0, 23, 0, 31),
(2, 0, 10, 0, 18, 0, 26, 0),
(0, 6, 0, 14, 0, 22, 0, 30),
(1, 0, 9, 0, 17, 0, 25, 0),
(0, 5, 0, 13, 0, 21, 0, 29)
);
procedure SetCBSquare (var aCBBoard : TCBBoard; aSquare : Integer; aPieceValue : Integer);
function GetCBSquare (var aCBBoard : TCBBoard; aSquare : Integer) : Integer;
procedure FillBoard (var aBoard : TBoardStruct; var aCBBoard : TCBBoard);
procedure FillCBBoard (var aCBBoard : TCBBoard; var aBoard: TBoardStruct);
implementation
{Sets the piece (aPieceValue) on the CB type board. aSquare is in standard
notation.
This routine is not optimized for speed.}
procedure SetCBSquare (var aCBBoard : TCBBoard; aSquare : Integer; aPieceValue : Integer);
var
i, j : Integer;
begin
for i := Low(TCBBoard) to High(TCBBoard) do begin
for j := Low(TCBBoard) to High (TCBBoard) do begin
if (STDBOARD[i,j] = aSquare) then begin
aCBBoard[i,j] := aPieceValue;
Break;
end;
end;
end;
end; // StdToCBBoard
{Returns the piece/value for a square in standard notation on CBBoard type board.}
function GetCBSquare (var aCBBoard : TCBBoard; aSquare : Integer) : Integer;
var
i, j : Integer;
begin
result := CB_FREE;
for i := Low(TCBBoard) to High(TCBBoard) do begin
for j := Low(TCBBoard) to High (TCBBoard) do begin
if (STDBOARD[i,j] = aSquare) then begin
result := aCBBoard[i,j];
break;
end;
end;
end;
end; // GetCBSquare
{Converts a CBboard to a standard board.}
procedure FillBoard (var aBoard : TBoardStruct; var aCBBoard : TCBBoard);
var
i : Integer;
begin
with aBoard do begin
for i := Low(TBoard) to High(TBoard) do begin
Board[i] := GetCBSquare(aCBBoard, i);
end; // for
end; // with
end; // FillBoard
{Converts a standard board to a CBBoard.}
procedure FillCBBoard (var aCBBoard : TCBBoard; var aBoard: TBoardStruct);
var
i : Integer;
begin
for i := Low(TBoard) to High(TBoard) do begin
SetCBSquare(aCBBoard, i, aBoard.Board[i]);
end;
end; //FillCBBoard
{ $Log
25-11-2002, DG : Created.
}
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzDlgBlockBlob;
interface
uses
Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections, Vcl.Graphics,
Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit;
type
TAzBlockBlob = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
lblBlobName: TLabel;
edtBlobName: TEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edtContentType: TEdit;
edtLanguage: TEdit;
edtMD5: TEdit;
edtEncoding: TEdit;
edtFilename: TEdit;
lblContentLocation: TLabel;
btnFile: TButton;
vleMeta: TValueListEditor;
btnAddMetadata: TButton;
btnDelMetadata: TButton;
procedure btnFileClick(Sender: TObject);
procedure btnAddMetadataClick(Sender: TObject);
procedure btnDelMetadataClick(Sender: TObject);
procedure edtBlobNameChange(Sender: TObject);
private
{ Private declarations }
procedure SetBlobName(const Name: string);
procedure SetContentType(const Name: string);
procedure SetContentLanguage(const Name: string);
procedure SetContentMD5(const Name: string);
procedure SetContentEncoding(const Name: string);
public
{ Public declarations }
function GetBlobName: String;
function GetContentType: String;
function GetContentLanguage: String;
function GetContentMD5: String;
function GetContentEncoding: String;
function GetContentLocation: String;
procedure AssignMetadata(const meta: TDictionary<String, String>);
procedure PopulateWithMetadata(const meta: TDictionary<String, String>);
procedure SetOKCaption(const Name: string);
function RawMetadata: TStrings;
property BlobName: string read GetBlobName write SetBlobName;
property ContentType: string read GetContentType write SetContentType;
property ContentLanguage: string read GetContentLanguage write SetContentLanguage;
property ContentEncoding: string read GetContentEncoding write SetContentEncoding;
property ContentMD5: string read GetContentMD5 write SetContentMD5;
end;
implementation
uses Data.DBXClientResStrs, Vcl.Dialogs, System.SysUtils;
{$R *.dfm}
procedure TAzBlockBlob.AssignMetadata(
const meta: TDictionary<String, String>);
var
I, Count: Integer;
key, value: String;
begin
meta.Clear;
Count := vleMeta.Strings.Count;
for I := 0 to Count - 1 do
begin
key := vleMeta.Strings.Names[I];
value := vleMeta.Strings.ValueFromIndex[I];
if (Length(key) > 0) and (Length(value) > 0) then
meta.Add(key, value);
end;
end;
procedure TAzBlockBlob.btnAddMetadataClick(Sender: TObject);
begin
vleMeta.InsertRow('', '', true);
vleMeta.SetFocus;
end;
procedure TAzBlockBlob.btnDelMetadataClick(Sender: TObject);
var
row: Integer;
begin
row := vleMeta.Row;
if (row > 0) and (row < vleMeta.RowCount) then
vleMeta.DeleteRow(row);
end;
procedure TAzBlockBlob.btnFileClick(Sender: TObject);
var
foDlg: TOpenDialog;
fs: TFileStream;
begin
foDlg := TOpenDialog.Create(self);
if foDlg.Execute(Handle) then
begin
fs := TFileStream.Create(foDlg.FileName, fmOpenRead);
try
if fs.Size >= 64*1024*1024 then
MessageDlg(SMaxSize, mtError, [mbOK], 0)
else
edtFilename.Text := foDlg.FileName;
finally
fs.Free;
end;
end;
foDlg.Free;
end;
procedure TAzBlockBlob.edtBlobNameChange(Sender: TObject);
begin
OKBtn.Enabled := Length(edtBlobName.Text) > 0;
end;
function TAzBlockBlob.GetBlobName: String;
begin
Result := edtBlobName.Text;
end;
function TAzBlockBlob.GetContentEncoding: String;
begin
Result := edtEncoding.Text;
end;
function TAzBlockBlob.GetContentLanguage: String;
begin
Result := edtLanguage.Text;
end;
function TAzBlockBlob.GetContentLocation: String;
begin
Result := edtFilename.Text;
end;
function TAzBlockBlob.GetContentMD5: String;
begin
Result := edtMD5.Text;
end;
function TAzBlockBlob.GetContentType: String;
begin
Result := edtContentType.Text;
end;
procedure TAzBlockBlob.PopulateWithMetadata(
const meta: TDictionary<String, String>);
var
keys: TArray<String>;
I, Count: Integer;
begin
vleMeta.Strings.Clear;
keys := meta.Keys.ToArray;
Count := meta.Keys.Count;
for I := 0 to Count - 1 do
vleMeta.Values[keys[I]] := meta.Items[keys[I]];
end;
function TAzBlockBlob.RawMetadata: TStrings;
begin
Result := vleMeta.Strings
end;
procedure TAzBlockBlob.SetBlobName(const Name: string);
begin
edtBlobName.Text := Name;
edtBlobName.Enabled := Length(Name) = 0;
end;
procedure TAzBlockBlob.SetContentEncoding(const Name: string);
begin
edtEncoding.Text := Name;
end;
procedure TAzBlockBlob.SetContentLanguage(const Name: string);
begin
edtLanguage.Text := Name;
end;
procedure TAzBlockBlob.SetContentMD5(const Name: string);
begin
edtMD5.Text := Name;
end;
procedure TAzBlockBlob.SetContentType(const Name: string);
begin
edtContentType.Text := Name;
end;
procedure TAzBlockBlob.SetOKCaption(const Name: string);
begin
if Length(Name) = 0 then
OKBtn.Caption := 'OK'
else
OKBtn.Caption := Name;
end;
end.
|
//
//
//События вызываемые по нажатию кнопочек
//
//
unit uSmartMethods;
interface
uses Windows, SysUtils, ClipBrd, Vcl.Buttons, Vcl.Controls, ShellApi,
mmsystem;
type clsSmartMethods= Class
public
procedure CopyToClipboard(Sender: TObject);
procedure OpenURL(Sender: TObject);
procedure OpenMail(Sender: TObject);
procedure AttachedFile(Sender: TObject);
procedure GeneratePass(Sender: TObject);
// procedure EditField(Sender: TObject);
End;
function GetEditFromTag(Sender: TObject): String;
implementation
{$R sounds.res}
uses uMain, uLog, uGenerator, Logic, uCustomEdit;
procedure clsSmartMethods.CopyToClipboard(Sender: TObject);
begin
try
if GetEditFromTag(Sender) = '' then Exit;
Clipboard.Clear;
Clipboard.AsText:=GetEditFromTag(Sender);
if Boolean(xmlCfg.GetValue('PlaySounds', True)) then
PlaySound('zoom', hInstance, SND_ASYNC or SND_NODEFAULT or SND_RESOURCE);
except
on E : Exception do ErrorLog(e, 'SmartMethodCopyToClipboard');
end;
end;
procedure clsSmartMethods.OpenURL(Sender: TObject);
var
url: String;
begin
log(GetEditFromTag(Sender));
try
url:= GetEditFromTag(Sender);
if url = '' then Exit;
if not ((Pos('www', url) = 1) or
(Pos('http', url) = 1)) then url:= 'www.' + Url;
ShellExecute(frmMain.Handle, '', PWideChar(url), nil, nil, SW_SHOW);
if Boolean(xmlCfg.GetValue('PlaySounds', True)) then
PlaySound('link', hInstance, SND_ASYNC or SND_NODEFAULT or SND_RESOURCE);
except
on E : Exception do ErrorLog(e, 'SmartMethodOpenURL');
end;
end;
procedure clsSmartMethods.OpenMail(Sender: TObject);
begin
try
if GetEditFromTag(Sender) = '' then Exit;
ShellExecute(frmMain.Handle, '', PwideChar('mailto:'+ GetEditFromTag(Sender)), nil, nil, SW_SHOW);
except
on E : Exception do ErrorLog(e, 'SmartMethodOpenMail');
end;
end;
procedure clsSmartMethods.AttachedFile(Sender: TObject);
begin
//
end;
procedure clsSmartMethods.GeneratePass(Sender: TObject);
begin
try
if (not Assigned(frmGenerator)) then frmGenerator:= TfrmGenerator.Create(nil);
if frmGenerator.ShowModal = mrOk then
TEditMultiline(Pointer((Sender as TSpeedButton).Tag)).Text:= frmGenerator.lblResult.Caption;
finally
FreeAndNil(frmGenerator);
end;
end;
function GetEditFromTag(Sender: TObject): String;
begin
result:=TEditMultiline(Pointer((Sender as TSpeedButton).Tag)).Text
end;
end.
|
{**********************************************************}
{ }
{ AddrBook 1.0 }
{ ---- Sample for Using TinyDB }
{ }
{ Author: DayDream Studio }
{ Email: webmaster@tinydb.com }
{ URL: http://www.TinyDB.com }
{ }
{**********************************************************}
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, Menus, ActnList, ComCtrls,
StdCtrls, ExtCtrls, ToolWin, ImgList, TinyDB, Db,
CardFrm;
type
TMainForm = class(TForm)
MainMenu: TMainMenu;
ActionList: TActionList;
NewCardAction: TAction;
FileMenu: TMenuItem;
FileNewMemberItem: TMenuItem;
CoolBar1: TCoolBar;
ToolBar: TToolBar;
ListView: TListView;
StatusBar: TStatusBar;
NewMemberToolButton: TToolButton;
Panel1: TPanel;
Panel2: TPanel;
ImageList: TImageList;
PropertyToolButton: TToolButton;
DeleteCardToolButton: TToolButton;
PropertyAction: TAction;
DeleteCardAction: TAction;
FileN1Item: TMenuItem;
FileN3Item: TMenuItem;
FilePropertyItem: TMenuItem;
FileDeleteCardItem: TMenuItem;
FileExitItem: TMenuItem;
ViewMenu: TMenuItem;
HelpMenu: TMenuItem;
ViewToolBarItem: TMenuItem;
ViewStatusBarItem: TMenuItem;
ViewN1Item: TMenuItem;
ViewLargeIconItem: TMenuItem;
ViewSmallIconItem: TMenuItem;
ViewListItem: TMenuItem;
ViewReportItem: TMenuItem;
ViewN2Item: TMenuItem;
ViewRefreshItem: TMenuItem;
HelpAboutItem: TMenuItem;
Splitter1: TSplitter;
TreeView: TTreeView;
NewFolderAction: TAction;
FileNewFolderItem: TMenuItem;
ToolButton1: TToolButton;
FolderTinyTable: TTinyTable;
TinyDatabase: TTinyDatabase;
CardTinyTable: TTinyTable;
TreeViewPopupMenu: TPopupMenu;
TreePopNewFolderItem: TMenuItem;
TreePopNewCardItem: TMenuItem;
TreePopN1Item: TMenuItem;
TreePopDeleteFolderItem: TMenuItem;
ListViewPopupMenu: TPopupMenu;
ListPopNewCardItem: TMenuItem;
ListPopDeleteCardItem: TMenuItem;
ListPopPropertyItem: TMenuItem;
Panel3: TPanel;
Label1: TLabel;
NameSearchPanel: TPanel;
NameSearchEdit: TEdit;
EncryptAction: TAction;
FileEncryptItem: TMenuItem;
FileN2Item: TMenuItem;
EncryptToolButton: TToolButton;
procedure NewCardActionExecute(Sender: TObject);
procedure PropertyActionExecute(Sender: TObject);
procedure DeleteCardActionExecute(Sender: TObject);
procedure FileExitItemClick(Sender: TObject);
procedure ViewToolBarItemClick(Sender: TObject);
procedure ViewStatusBarItemClick(Sender: TObject);
procedure ViewLargeIconItemClick(Sender: TObject);
procedure ViewRefreshItemClick(Sender: TObject);
procedure HelpAboutItemClick(Sender: TObject);
procedure NewFolderActionExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure FormDestroy(Sender: TObject);
procedure TreePopDeleteFolderItemClick(Sender: TObject);
procedure TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
procedure TreeViewPopupMenuPopup(Sender: TObject);
procedure TreeViewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ListViewPopupMenuPopup(Sender: TObject);
procedure TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: String);
procedure NameSearchPanelResize(Sender: TObject);
procedure ListViewChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure NameSearchEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EncryptActionExecute(Sender: TObject);
private
{ Private declarations }
FPassword: string;
function GetDBFileName: string;
function CreateDatabase: Boolean;
function OpenDatabase: Boolean;
procedure FillFolderTreeView;
procedure FillListView(FolderID: Integer);
procedure UpdateListItem(ListItem: TListItem; CardData: TCardFormData);
procedure LoadCardData(var CardData: TCardFormData);
procedure SaveCardData(CardData: TCardFormData);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses StrRes, InputFrm, ChgPwdFrm, AboutFrm;
{$R *.DFM}
procedure KillMessage(Wnd: HWnd; Msg: Integer);
var
M: TMsg;
begin
M.Message := 0;
if PeekMessage(M, Wnd, Msg, Msg, pm_Remove) and (M.Message = WM_QUIT) then
PostQuitMessage(M.wparam);
end;
function TMainForm.GetDBFileName: string;
begin
Result := ExtractFilePath(Application.ExeName) + 'AddrData.dat';
end;
function TMainForm.CreateDatabase: Boolean;
var
DBFileName: string;
begin
Result := True;
DBFileName := GetDBFileName;
try
TinyDatabase.CreateDatabase(DBFileName, True, clNormal, 'ZLIB', False, 'MyEncAlgo', '');
TinyDatabase.DatabaseName := DBFileName;
TinyDatabase.CreateTable('Card', [
FieldItem('ID', ftAutoInc),
FieldItem('FolderID', ftInteger),
FieldItem('Name', ftString, 32),
FieldItem('Nickname', ftString, 32),
FieldItem('Emails', ftMemo),
FieldItem('HandTel', ftString, 20),
FieldItem('BP', ftString, 20),
FieldItem('Oicq', ftString, 20),
FieldItem('Icq', ftString, 20),
FieldItem('Sex', ftInteger),
FieldItem('Birthday', ftDate),
FieldItem('UseBirth', ftBoolean),
FieldItem('Constellation', ftInteger),
FieldItem('BloodType', ftInteger),
FieldItem('Taste', ftString, 127),
FieldItem('Homepage', ftString, 127),
FieldItem('HomeZip', ftString, 6),
FieldItem('HomeAddr', ftString, 255),
FieldItem('HomeTel1', ftString, 32),
FieldItem('HomeTel2', ftString, 32),
FieldItem('HomeFax', ftString, 32),
FieldItem('CorpZip', ftString, 6),
FieldItem('CorpAddr', ftString, 255),
FieldItem('CorpJob', ftString, 32),
FieldItem('CorpDept', ftString, 32),
FieldItem('CorpTel1', ftString, 32),
FieldItem('CorpTel2', ftString, 32),
FieldItem('CorpFax', ftString, 32),
FieldItem('CorpHomepage', ftString, 255),
FieldItem('ExtMemo', ftMemo)
] );
TinyDatabase.CreateTable('Folder', [
FieldItem('ID', ftAutoInc),
FieldItem('ParentID', ftInteger),
FieldItem('Name', ftString, 32)
] );
TinyDatabase.CreateIndex('Card', 'ByFolderID', [], ['FolderID']);
TinyDatabase.CreateIndex('Card', 'ByName', [], ['Name']);
TinyDatabase.CreateIndex('Folder', 'ByParentID', [], ['ParentID']);
FolderTinyTable.DatabaseName := DBFileName;
FolderTinyTable.TableName := 'Folder';
FolderTinyTable.Open;
FolderTinyTable.AppendRecord([0, 0, '<' + SDefaultStr + '>']);
FolderTinyTable.Close;
except
DeleteFile(DBFileName);
Result := False;
end;
end;
function TMainForm.OpenDatabase: Boolean;
var
DBFileName: string;
Password: string;
Count: Integer;
begin
TinyDatabase.Close;
DBFileName := GetDBFileName;
TinyDatabase.DatabaseName := DBFileName;
TinyDatabase.Open;
Count := 1;
while not TinyDatabase.CanAccess and (Count <= 3) do
begin
if ShowInputForm(Password, Self.Caption, SInputPassword, True) then
begin
TinyDatabase.Password := Password;
if not TinyDatabase.CanAccess then
begin
MessageBox(Application.Handle, PChar(SPasswordWrong), PChar(Application.Title), 48);
Inc(Count);
end;
end else
begin
TinyDatabase.DatabaseName := '';
Break;
end;
end;
if (TinyDatabase.DatabaseName <> '') and (TinyDatabase.CanAccess) then
begin
FPassword := Password;
FolderTinyTable.DatabaseName := DBFileName;
FolderTinyTable.TableName := 'Folder';
FolderTinyTable.Open;
CardTinyTable.DatabaseName := DBFileName;
CardTinyTable.TableName := 'Card';
CardTinyTable.Open;
Result := True;
end else
Result := False;
end;
procedure TMainForm.FillFolderTreeView;
procedure FillTreeNode(TreeNode: TTreeNode);
var
I, FolderID: Integer;
Node: TTreeNode;
begin
FolderID := Integer(TreeNode.Data);
FolderTinyTable.Filter := 'ParentID=' + IntToStr(FolderID);
FolderTinyTable.Filtered := True;
FolderTinyTable.First;
for I := 0 to FolderTinyTable.RecordCount - 1 do
begin
Node := TreeView.Items.AddChild(TreeNode, FolderTinyTable.FieldByName('Name').AsString);
Node.Data := Pointer(FolderTinyTable.FieldByName('ID').AsInteger);
Node.ImageIndex := 1;
Node.SelectedIndex := 1;
FolderTinyTable.Next;
end;
for I := 0 to TreeNode.Count - 1 do
begin
FillTreeNode(TreeNode.Item[I]);
end;
end;
begin
TreeView.Items.BeginUpdate;
TreeView.Items.Clear;
with TreeView.Items.Add(nil, SAddressBook) do
begin
Data := Pointer(0);
ImageIndex := 0;
SelectedIndex := 0;
end;
FillTreeNode(TreeView.Items[0]);
TreeView.FullExpand;
TreeView.Items.EndUpdate;
TreeView.Items[1].Selected := True;
end;
procedure TMainForm.FillListView(FolderID: Integer);
var
I: Integer;
ListItem: TListItem;
List: TStrings;
Email: string;
begin
List := TStringList.Create;
ListView.Items.BeginUpdate;
ListView.Items.Clear;
try
CardTinyTable.Filter := 'FolderID=' + IntToStr(FolderID);
CardTinyTable.Filtered := True;
CardTinyTable.First;
for I := 0 to CardTinyTable.RecordCount - 1 do
begin
ListItem := ListView.Items.Add;
ListItem.Data := Pointer(CardTinyTable.FieldByName('ID').AsInteger);
ListItem.Caption := CardTinyTable.FieldByName('Name').AsString;
List.Clear;
List.CommaText := CardTinyTable.FieldByName('Emails').AsString;
if List.Count > 0 then Email := List[0]
else Email := '';
ListItem.SubItems.Add(Email);
ListItem.SubItems.Add(CardTinyTable.FieldByName('HandTel').AsString);
ListItem.ImageIndex := 2;
CardTinyTable.Next;
end;
finally
ListView.Items.EndUpdate;
List.Free;
end;
StatusBar.SimpleText := IntToStr(ListView.Items.Count) + ' Items';
end;
procedure TMainForm.UpdateListItem(ListItem: TListItem; CardData: TCardFormData);
var
List: TStrings;
Email: string;
begin
List := TStringList.Create;
try
ListItem.Caption := CardData.Name;
List.CommaText := CardData.Emails;
if List.Count > 0 then Email := List[0]
else Email := '';
ListItem.SubItems[0] := Email;
ListItem.SubItems[1] := CardData.HandTel;
finally
List.Free;
end;
end;
procedure TMainForm.LoadCardData(var CardData: TCardFormData);
begin
with CardData do
begin
Name := CardTinyTable.FieldByName('Name').AsString;
Nickname := CardTinyTable.FieldByName('Nickname').AsString;
Emails := CardTinyTable.FieldByName('Emails').AsString;
HandTel := CardTinyTable.FieldByName('HandTel').AsString;
BP := CardTinyTable.FieldByName('BP').AsString;
Oicq := CardTinyTable.FieldByName('Oicq').AsString;
Icq := CardTinyTable.FieldByName('Icq').AsString;
Sex := CardTinyTable.FieldByName('Sex').AsInteger;
Birthday := CardTinyTable.FieldByName('Birthday').AsDateTime;
UseBirth := CardTinyTable.FieldByName('UseBirth').AsBoolean;
Constellation := CardTinyTable.FieldByName('Constellation').AsInteger;
BloodType := CardTinyTable.FieldByName('BloodType').AsInteger;
Taste := CardTinyTable.FieldByName('Taste').AsString;
Homepage := CardTinyTable.FieldByName('Homepage').AsString;
HomeZip := CardTinyTable.FieldByName('HomeZip').AsString;
HomeAddr := CardTinyTable.FieldByName('HomeAddr').AsString;
HomeTel1 := CardTinyTable.FieldByName('HomeTel1').AsString;
HomeTel2 := CardTinyTable.FieldByName('HomeTel2').AsString;
HomeFax := CardTinyTable.FieldByName('HomeFax').AsString;
CorpZip := CardTinyTable.FieldByName('CorpZip').AsString;
CorpAddr := CardTinyTable.FieldByName('CorpAddr').AsString;
CorpJob := CardTinyTable.FieldByName('CorpJob').AsString;
CorpDept := CardTinyTable.FieldByName('CorpDept').AsString;
CorpTel1 := CardTinyTable.FieldByName('CorpTel1').AsString;
CorpTel2 := CardTinyTable.FieldByName('CorpTel2').AsString;
CorpFax := CardTinyTable.FieldByName('CorpFax').AsString;
CorpHomepage := CardTinyTable.FieldByName('CorpHomepage').AsString;
ExtMemo := CardTinyTable.FieldByName('ExtMemo').AsString;
end;
end;
procedure TMainForm.SaveCardData(CardData: TCardFormData);
begin
with CardData do
begin
CardTinyTable.FieldByName('Name').AsString := Name;
CardTinyTable.FieldByName('Nickname').AsString := Nickname;
CardTinyTable.FieldByName('Emails').AsString := Emails;
CardTinyTable.FieldByName('HandTel').AsString := HandTel;
CardTinyTable.FieldByName('BP').AsString := BP;
CardTinyTable.FieldByName('Oicq').AsString := Oicq;
CardTinyTable.FieldByName('Icq').AsString := Icq;
CardTinyTable.FieldByName('Sex').AsInteger := Sex;
CardTinyTable.FieldByName('Birthday').AsDateTime := Birthday;
CardTinyTable.FieldByName('UseBirth').AsBoolean := UseBirth;
CardTinyTable.FieldByName('Constellation').AsInteger := Constellation;
CardTinyTable.FieldByName('BloodType').AsInteger := BloodType;
CardTinyTable.FieldByName('Taste').AsString := Taste;
CardTinyTable.FieldByName('Homepage').AsString := Homepage;
CardTinyTable.FieldByName('HomeZip').AsString := HomeZip;
CardTinyTable.FieldByName('HomeAddr').AsString := HomeAddr;
CardTinyTable.FieldByName('HomeTel1').AsString := HomeTel1;
CardTinyTable.FieldByName('HomeTel2').AsString := HomeTel2;
CardTinyTable.FieldByName('HomeFax').AsString := HomeFax;
CardTinyTable.FieldByName('CorpZip').AsString := CorpZip;
CardTinyTable.FieldByName('CorpAddr').AsString := CorpAddr;
CardTinyTable.FieldByName('CorpJob').AsString := CorpJob;
CardTinyTable.FieldByName('CorpDept').AsString := CorpDept;
CardTinyTable.FieldByName('CorpTel1').AsString := CorpTel1;
CardTinyTable.FieldByName('CorpTel2').AsString := CorpTel2;
CardTinyTable.FieldByName('CorpFax').AsString := CorpFax;
CardTinyTable.FieldByName('CorpHomepage').AsString := CorpHomepage;
CardTinyTable.FieldByName('ExtMemo').AsString := ExtMemo;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
DBFileName: string;
begin
DBFileName := GetDBFileName;
if not FileExists(DBFileName) then
begin
if not CreateDatabase then
begin
MessageBox(Application.Handle, PChar(SFailToCreateDb), PChar(Application.Title), 16);
Application.Terminate;
end;
end;
if not OpenDatabase then
begin
Application.Terminate;
end;
FillFolderTreeView;
NameSearchEdit.Text := '';
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
CardTinyTable.Close;
FolderTinyTable.Close;
end;
procedure TMainForm.NewCardActionExecute(Sender: TObject);
var
CardData: TCardFormData;
FolderID: Integer;
begin
if TreeView.Selected = nil then
TreeView.Items[1].Selected := True;
if TreeView.Selected.AbsoluteIndex = 0 then
TreeView.Items[1].Selected := True;
FolderID := Integer(TreeView.Selected.Data);
if FolderID < 1 then FolderID := 1;
CardData.UseBirth := False;
if ShowCardForm(CardData) then
begin
CardTinyTable.Filtered := False;
CardTinyTable.Append;
CardTinyTable.FieldByName('FolderID').AsInteger := FolderID;
SaveCardData(CardData);
CardTinyTable.Post;
FillListView(FolderID);
end;
end;
procedure TMainForm.NewFolderActionExecute(Sender: TObject);
var
ParentID: Integer;
FolderName: string;
TreeNode: TTreeNode;
begin
if TreeView.Selected = nil then Exit;
ParentID := Integer(TreeView.Selected.Data);
if ShowInputForm(FolderName, SNewFolder, SFolderName) then
begin
FolderTinyTable.Filtered := False;
FolderTinyTable.Append;
FolderTinyTable.FieldByName('ParentID').AsInteger := ParentID;
FolderTinyTable.FieldByName('Name').AsString := FolderName;
FolderTinyTable.Post;
TreeNode := TreeView.Items.AddChild(TreeView.Selected, FolderName);
TreeNode.Data := Pointer(FolderTinyTable.FieldByName('ID').AsInteger);
TreeNode.ImageIndex := 1;
TreeNode.SelectedIndex := 1;
TreeNode.MakeVisible;
TreeNode.Selected := True;
end;
end;
procedure TMainForm.PropertyActionExecute(Sender: TObject);
var
ListItem: TListItem;
CardID: Integer;
CardData: TCardFormData;
begin
if ListView.Selected = nil then Exit;
ListItem := ListView.Selected;
CardID := Integer(ListItem.Data);
CardTinyTable.Filtered := False;
CardTinyTable.IndexName := '';
if CardTinyTable.FindKey([CardID]) then
begin
LoadCardData(CardData);
if ShowCardForm(CardData) then
begin
CardTinyTable.Edit;
SaveCardData(CardData);
CardTinyTable.Post;
UpdateListItem(ListItem, CardData);
end;
end;
end;
procedure TMainForm.DeleteCardActionExecute(Sender: TObject);
var
CardID: Integer;
R: Integer;
begin
if ListView.Selected = nil then Exit;
R := MessageBox(Application.Handle, PChar(SQueryDeleteCard), PChar(Application.Title), 36);
if R = ID_NO then Exit;
CardID := Integer(ListView.Selected.Data);
CardTinyTable.Filtered := False;
CardTinyTable.IndexName := '';
if CardTinyTable.FindKey([CardID]) then
begin
CardTinyTable.Delete;
ListView.Selected.Delete;
end;
end;
procedure TMainForm.EncryptActionExecute(Sender: TObject);
var
Data: TChgPwdFormData;
begin
Data.CheckPwd := TinyDatabase.Encrypted;
if ShowChgPwdForm(Data) then
begin
if TinyDatabase.ChangePassword(Data.Password, Data.CheckPwd) then
begin
MessageBox(Handle, PChar(SChgPwdSucc), PChar(Application.Title), 48)
end else
MessageBox(Handle, PChar(SChgPwdFail), PChar(Application.Title), 48);
end;
end;
procedure TMainForm.FileExitItemClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.ViewToolBarItemClick(Sender: TObject);
begin
ViewToolBarItem.Checked := not ViewToolBarItem.Checked;
ToolBar.Visible := ViewToolBarItem.Checked;
end;
procedure TMainForm.ViewStatusBarItemClick(Sender: TObject);
begin
ViewStatusBarItem.Checked := not ViewStatusBarItem.Checked;
StatusBar.Visible := ViewStatusBarItem.Checked;
end;
procedure TMainForm.ViewLargeIconItemClick(Sender: TObject);
begin
(Sender as TMenuItem).Checked := True;
ListView.ViewStyle := TViewStyle((Sender as TMenuItem).Tag);
end;
procedure TMainForm.ViewRefreshItemClick(Sender: TObject);
begin
if TreeView.Selected = nil then Exit;
FillListView(Integer(TreeView.Selected.Data));
end;
procedure TMainForm.HelpAboutItemClick(Sender: TObject);
begin
ShowAboutForm;
end;
{$WRITEABLECONST ON}
procedure TMainForm.TreeViewChange(Sender: TObject; Node: TTreeNode);
const
OldFolderID: Integer = -1;
var
FolderID: Integer;
begin
FolderID := Integer(Node.Data);
if FolderID = OldFolderID then Exit;
OldFolderID := FolderID;
FillListView(FolderID);
end;
procedure TMainForm.TreePopDeleteFolderItemClick(Sender: TObject);
var
TreeNode: TTreeNode;
FolderID, R: Integer;
begin
if TreeView.Selected = nil then Exit;
TreeNode := TreeView.Selected;
if TreeNode.AbsoluteIndex in [0,1] then Exit;
R := MessageBox(Application.Handle, PChar(SQueryDeleteFolder), PChar(Application.Title), 36);
if R = ID_NO then Exit;
FolderID := Integer(TreeNode.Data);
FolderTinyTable.Filtered := False;
FolderTinyTable.IndexName := '';
if FolderTinyTable.FindKey([FolderID]) then
begin
FolderTinyTable.Delete;
CardTinyTable.Filtered := False;
CardTinyTable.IndexName := 'ByFolderID';
while CardTinyTable.FindKey([FolderID]) do
begin
CardTinyTable.Delete;
end;
TreeNode.Delete;
end;
end;
procedure TMainForm.TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
begin
if Node.AbsoluteIndex in [0, 1] then AllowEdit := False
else AllowEdit := True;
end;
procedure TMainForm.TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: String);
var
FolderID: Integer;
begin
FolderID := Integer(Node.Data);
FolderTinyTable.Filtered := False;
FolderTinyTable.IndexName := '';
if FolderTinyTable.FindKey([FolderID]) then
begin
FolderTinyTable.Edit;
FolderTinyTable.FieldByName('Name').AsString := S;
FolderTinyTable.Post;
Node.Text := FolderTinyTable.FieldByName('Name').AsString;
end;
end;
procedure TMainForm.TreeViewMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Node: TTreeNode;
HitTest: THitTests;
begin
HitTest := TreeView.GetHitTestInfoAt(X, Y);
if (htOnIcon in HitTest) or (htOnLabel in HitTest)then
begin
Node := TreeView.GetNodeAt(X, Y);
if Node <> nil then Node.Selected := True;
end;
end;
procedure TMainForm.TreeViewPopupMenuPopup(Sender: TObject);
begin
TreePopDeleteFolderItem.Enabled := not (TreeView.Selected.AbsoluteIndex in [0,1]);
end;
procedure TMainForm.ListViewPopupMenuPopup(Sender: TObject);
var
Selected: Boolean;
begin
Selected := (ListView.Selected <> nil);
ListPopDeleteCardItem.Enabled := Selected;
ListPopPropertyItem.Enabled := Selected;
end;
procedure TMainForm.ListViewChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
NameSearchEdit.Text := Item.Caption;
end;
procedure TMainForm.NameSearchPanelResize(Sender: TObject);
begin
NameSearchEdit.Width := NameSearchPanel.ClientWidth;
end;
procedure TMainForm.NameSearchEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
I: Integer;
begin
if Key = VK_RETURN then
begin
KillMessage(Handle, WM_CHAR);
NameSearchEdit.SelectAll;
for I := 0 to ListView.Items.Count - 1 do
begin
if CompareText(ListView.Items[I].Caption, NameSearchEdit.Text) = 0 then
begin
ListView.Items[I].MakeVisible(False);
ListView.Items[I].Selected := True;
NameSearchEdit.SelectAll;
Exit;
end;
end;
MessageBeep(0);
end;
end;
end.
|
unit Nathan.Firebird.Validator.Syntax.Keywords.Types;
interface
{$M+}
type
// TDetail = record
// Kind: Integer;
// Value: string;
// end;
TFb25TokenKind = (
fb25None,
fb25Whitespaces,
fb25Starter,
fb25Operator,
fb25Variable,
fb25TerminatorCharacter,
fb25BracketOpen,
fb25BracketClose,
fb25SquareOpen,
fb25SquareClose,
fb25RoundBracketOpen,
fb25RoundBracketClose,
fb25ApostropheOpen,
fb25ApostropheClose,
fb25Arguments,
fb25LineBreak);
{$M-}
const
/// <summary>
/// Open and close brackets.
/// </summary>
Firebird25Brackets: TArray<String> = ['(', ')', '[', ']'];
/// <summary>
/// Keywords at the beginning of the DDL (Data Definition Statements) statement.
/// https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl.html
/// </summary>
Firebird25DDLBeginning: TArray<String> = ['ALTER', 'COMMENT', 'CREATE', 'DECLARE', 'DROP', 'RECREATE', 'SET'];
/// <summary>
/// Other (remaining) reserved keywords.
/// </summary>
{$REGION 'Firebird 2.5 Keywords'}
Firebird25Keywords: TArray<String> = [
'!<',
'^<',
'^=',
'^>',
',',
':=',
'!=',
'!>',
'(',
')',
'<',
'<=',
'<>',
'=',
'>',
'>=',
'||',
'~<',
'~=',
'~>',
'ABS',
'ACCENT',
'ACOS',
'ACTION',
'ACTIVE',
'ADD',
'ADMIN',
'AFTER',
'ALL',
'ALTER',
'ALWAYS',
'AND',
'ANY',
'AS',
'ASC',
'ASCENDING',
'ASCII_CHAR',
'ASCII_VAL',
'ASIN',
'AT',
'ATAN',
'ATAN2',
'AUTO',
'AUTONOMOUS',
'AVG',
'BACKUP',
'BEFORE',
'BEGIN',
'BETWEEN',
'BIGINT',
'BIN_AND',
'BIN_NOT',
'BIN_OR',
'BIN_SHL',
'BIN_SHR',
'BIN_XOR',
'BIT_LENGTH',
'BLOB',
'BLOCK',
'BOTH',
'BREAK',
'BY',
'CALLER',
'CASCADE',
'CASE',
'CAST',
'CEIL',
'CEILING',
'CHAR',
'CHAR_LENGTH',
'CHAR_TO_UUID',
'CHARACTER',
'CHARACTER_LENGTH',
'CHECK',
'CLOSE',
'COALESCE',
'COLLATE',
'COLLATION',
'COLUMN',
'COMMENT',
'COMMIT',
'COMMITTED',
'COMMON',
'COMPUTED',
'CONDITIONAL',
'CONNECT',
'CONSTRAINT',
'CONTAINING',
'COS',
'COSH',
'COT',
'COUNT',
'CREATE',
'CROSS',
'CSTRING',
'CURRENT',
'CURRENT_CONNECTION',
'CURRENT_DATE',
'CURRENT_ROLE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_TRANSACTION',
'CURRENT_USER',
'CURSOR',
'DATA',
'DATABASE',
'DATE',
'DATEADD',
'DATEDIFF',
'DAY',
'DEC',
'DECIMAL',
'DECLARE',
'DECODE',
'DEFAULT',
'DELETE',
'DELETING',
'DESC',
'DESCENDING',
'DESCRIPTOR',
'DIFFERENCE',
'DISCONNECT',
'DISTINCT',
'DO',
'DOMAIN',
'DOUBLE',
'DROP',
'ELSE',
'END',
'ENTRY_POINT',
'ESCAPE',
'EXCEPTION',
'EXECUTE',
'EXISTS',
'EXIT',
'EXP',
'EXTERNAL',
'EXTRACT',
'FETCH',
'FILE',
'FILTER',
'FIRST',
'FIRSTNAME',
'FLOAT',
'FLOOR',
'FOR',
'FOREIGN',
'FREE_IT',
'FROM',
'FULL',
'FUNCTION',
'GDSCODE',
'GEN_ID',
'GEN_UUID',
'GENERATED',
'GENERATOR',
'GLOBAL',
'GRANT',
'GRANTED',
'GROUP',
'HASH',
'HAVING',
'HOUR',
'IF',
'IGNORE',
'IIF',
'IN',
'INACTIVE',
'INDEX',
'INNER',
'INPUT_TYPE',
'INSENSITIVE',
'INSERT',
'INSERTING',
'INT',
'INTEGER',
'INTO',
'IS',
'ISOLATION',
'JOIN',
'KEY',
'LAST',
'LASTNAME',
'LEADING',
'LEAVE',
'LEFT',
'LENGTH',
'LEVEL',
'LIKE',
'LIMBO',
'LIST',
'LN',
'LOCK',
'LOG',
'LOG10',
'LONG',
'LOWER',
'LPAD',
'MANUAL',
'MAPPING',
'MATCHED',
'MATCHING',
'MAX',
'MAXIMUM_SEGMENT',
'MAXVALUE',
'MERGE',
'MIDDLENAME',
'MILLISECOND',
'MIN',
'MINUTE',
'MINVALUE',
'MOD',
'MODULE_NAME',
'MONTH',
'NAMES',
'NATIONAL',
'NATURAL',
'NCHAR',
'NEXT',
'NO',
'NOT',
'NULL',
'NULLIF',
'NULLS',
'NUMERIC',
'OCTET_LENGTH',
'OF',
'ON',
'ONLY',
'OPEN',
'OPTION',
'OR',
'ORDER',
'OS_NAME',
'OUTER',
'OUTPUT_TYPE',
'OVERFLOW',
'OVERLAY',
'PAD',
'PAGE',
'PAGE_SIZE',
'PAGES',
'PARAMETER',
'PASSWORD',
'PI',
'PLACING',
'PLAN',
'POSITION',
'POST_EVENT',
'POWER',
'PRECISION',
'PRESERVE',
'PRIMARY',
'PRIVILEGES',
'PROCEDURE',
'PROTECTED',
'RAND',
'RDB$DB_KEY',
'READ',
'REAL',
'RECORD_VERSION',
'RECREATE',
'RECURSIVE',
'REFERENCES',
'RELEASE',
'REPLACE',
'REQUESTS',
'RESERV',
'RESERVING',
'RESTART',
'RESTRICT',
'RETAIN',
'RETURNING',
'RETURNING_VALUES',
'RETURNS',
'REVERSE',
'REVOKE',
'RIGHT',
'ROLE',
'ROLLBACK',
'ROUND',
'ROW_COUNT',
'ROWS',
'RPAD',
'SAVEPOINT',
'SCALAR_ARRAY',
'SCHEMA',
'SECOND',
'SEGMENT',
'SELECT',
'SENSITIVE',
'SEQUENCE',
'SET',
'SHADOW',
'SHARED',
'SIGN',
'SIMILAR',
'SIN',
'SINGULAR',
'SINH',
'SIZE',
'SKIP',
'SMALLINT',
'SNAPSHOT',
'SOME',
'SORT',
'SOURCE',
'SPACE',
'SQLCODE',
'SQLSTATE (2.5.1)',
'SQRT',
'STABILITY',
'START',
'STARTING',
'STARTS',
'STATEMENT',
'STATISTICS',
'SUB_TYPE',
'SUBSTRING',
'SUM',
'SUSPEND',
'TABLE',
'TAN',
'TANH',
'TEMPORARY',
'THEN',
'TIME',
'TIMEOUT',
'TIMESTAMP',
'TO',
'TRAILING',
'TRANSACTION',
'TRIGGER',
'TRIM',
'TRUNC',
'TWO_PHASE',
'TYPE',
'UNCOMMITTED',
'UNDO',
'UNION',
'UNIQUE',
'UPDATE',
'UPDATING',
'UPPER',
'USER',
'USING',
'UUID_TO_CHAR',
'VALUE',
'VALUES',
'VARCHAR',
'VARIABLE',
'VARYING',
'VIEW',
'WAIT',
'WEEK',
'WEEKDAY',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'WORK',
'WRITE',
'YEAR',
'YEARDAY'];
{$ENDREGION}
{$REGION 'Firebird 2.5 Reserved Words'}
Firebird25ReservedWords: TArray<String> = [
'ADD',
'ADMIN',
'ALL',
'ALTER',
'AND',
'ANY',
'AS',
'AT',
'AVG',
'BEGIN',
'BETWEEN',
'BIGINT',
'BIT_LENGTH',
'BLOB',
'BOTH',
'BY',
'CASE',
'CAST',
'CHAR',
'CHAR_LENGTH',
'CHARACTER',
'CHARACTER_LENGTH',
'CHECK',
'CLOSE',
'COLLATE',
'COLUMN',
'COMMIT',
'CONNECT',
'CONSTRAINT',
'COUNT',
'CREATE',
'CROSS',
'CURRENT',
'CURRENT_CONNECTION',
'CURRENT_DATE',
'CURRENT_ROLE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_TRANSACTION',
'CURRENT_USER',
'CURSOR',
'DATE',
'DAY',
'DEC',
'DECIMAL',
'DECLARE',
'DEFAULT',
'DELETE',
'DISCONNECT',
'DISTINCT',
'DOUBLE',
'DROP',
'ELSE',
'END',
'ESCAPE',
'EXECUTE',
'EXISTS',
'EXTERNAL',
'EXTRACT',
'FETCH',
'FILTER',
'FLOAT',
'FOR',
'FOREIGN',
'FROM',
'FULL',
'FUNCTION',
'GDSCODE',
'GLOBAL',
'GRANT',
'GROUP',
'HAVING',
'HOUR',
'IN',
'INDEX',
'INNER',
'INSENSITIVE',
'INSERT',
'INT',
'INTEGER',
'INTO',
'IS',
'JOIN',
'LEADING',
'LEFT',
'LIKE',
'LONG',
'LOWER',
'MAX',
'MAXIMUM_SEGMENT',
'MERGE',
'MIN',
'MINUTE',
'MONTH',
'NATIONAL',
'NATURAL',
'NCHAR',
'NO',
'NOT',
'NULL',
'NUMERIC',
'OCTET_LENGTH',
'OF',
'ON',
'ONLY',
'OPEN',
'OR',
'ORDER',
'OUTER',
'PARAMETER',
'PLAN',
'POSITION',
'POST_EVENT',
'PRECISION',
'PRIMARY',
'PROCEDURE',
'RDB$DB_KEY',
'REAL',
'RECORD_VERSION',
'RECREATE',
'RECURSIVE',
'REFERENCES',
'RELEASE',
'RETURNING_VALUES',
'RETURNS',
'REVOKE',
'RIGHT',
'ROLLBACK',
'ROW_COUNT',
'ROWS',
'SAVEPOINT',
'SECOND',
'SELECT',
'SENSITIVE',
'SET',
'SIMILAR',
'SMALLINT',
'SOME',
'SQLCODE',
'SQLSTATE (2.5.1)',
'START',
'SUM',
'TABLE',
'THEN',
'TIME',
'TIMESTAMP',
'TO',
'TRAILING',
'TRIGGER',
'TRIM',
'UNION',
'UNIQUE',
'UPDATE',
'UPPER',
'USER',
'USING',
'VALUE',
'VALUES',
'VARCHAR',
'VARIABLE',
'VARYING',
'VIEW',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'YEAR'];
{$ENDREGION}
/// <summary>
/// Terminator Character
/// The default terminator symbol for the Firebird database is the semicolon (;).
/// Statements will only be executed if they end with a semicolon.
/// However, you may use isql to change the symbol to any printable character,
/// or characters, from the first 127 characters of the ASCII subset,
/// by using the SET TERM command.
/// Semicolon = ;
/// Tile = ~
/// Roof = ^
/// </summary>
Firebird25DDLTerminatorCharacter: TArray<String> = [';', '~', '^'];
// Details: array[0..1] of TDetail = ((Kind: 0; Value: 'alter'), (Kind: 0; Value: 'create'));
implementation
end.
|
unit ncHttp;
interface
uses
SysUtils, Classes, IdTCPConnection, IdTCPClient, IdHTTP;
function httpPost(aURL, aParams: String): String;
function httpGet(aURL: String): String;
function MesmaURL(A, B: String): Boolean;
implementation
uses uNR_chaveseg;
function MesmaURL(A, B: String): Boolean;
function NormURL(S: String): String;
begin
if pos('http://', S)=1 then
Delete(S, 1, 7);
if pos('www.', S)=1 then
Delete(S, 1, 4);
if Copy(S, Length(S), 1)='/' then
Delete(S, Length(S), 1);
end;
begin
A := LowerCase(A);
B := LowerCase(B);
Result := SameText(NormURL(A), NormURL(B));
end;
function httpPost(aURL, aParams: String): String;
var
H : TidHttp;
sl : TStrings;
i : integer;
begin
try
H := TidHttp.Create(nil);
sl := TStringList.Create;
try
H.HandleRedirects := True;
sl.Text := aParams;
for I := 0 to sl.Count - 1 do
sl.ValueFromIndex[i] := AnsiToUTF8(sl.ValueFromIndex[i]);
Result := H.Post(aUrl, sl);
finally
H.Free;
sl.Free;
end;
except
end;
end;
function httpGet(aURL: String): String;
var
H : TidHttp;
begin
try
H := TidHttp.Create(nil);
try
H.HandleRedirects := True;
Result := H.Get(aUrl);
finally
H.Free;
end;
except
end;
end;
end.
|
unit SoundRepository;
interface
uses
WaveStorage, IOUtils, SysUtils, Types, Classes;
type
TSoundRepository = class
private
FWaves: TWaveCollection;
FVoice: String;
FSoundsNames: TStringList;
private
procedure LoadWaves();
public
constructor Create();
destructor Destroy(); override;
function GetVoice(): String;
procedure SetVoice(AVoice: String);
function GetSoundsNames(): TArray<String>;
function GetSoundByName(AName: String): TWave;
published
property Voice: String read GetVoice write SetVoice;
property SoundsNames: TArray<String> read GetSoundsNames;
end;
implementation
constructor TSoundRepository.Create;
begin
FWaves := TWaveCollection.Create(nil);
FSoundsNames := TStringList.Create;
end;
destructor TSoundRepository.Destroy;
begin
inherited;
FreeAndNil(FWaves);
FreeAndNil(FSoundsNames);
end;
function TSoundRepository.GetSoundByName(AName: String): TWave;
var
Index: Integer;
begin
Index := FSoundsNames.IndexOf(AName);
if (Index <> -1) then
begin
Result := FWaves.Waves.Items[Index].Wave;
end
else
begin
Result := nil;
end;
end;
function TSoundRepository.GetSoundsNames: TArray<String>;
begin
Result := FSoundsNames.ToStringArray;
end;
function TSoundRepository.GetVoice: String;
begin
Result := FVoice;
end;
procedure TSoundRepository.LoadWaves;
var
Filenames: TStringDynArray;
Filename: String;
WaveFile: TWaveFile;
WaveItem: TWaveItem;
begin
FWaves.Waves.Clear;
FSoundsNames.Clear;
Filenames := TDirectory.GetFiles(ExpandFileName(FVoice));
for Filename in Filenames do
begin
if (ExtractFileExt(Filename) = '.wav') then
begin
WaveFile := TWaveFile.Create(Filename, fmOpenRead);
WaveItem := FWaves.Waves.Add;
WaveItem.Wave.Assign(WaveFile);
WaveItem.Name := StringReplace(ExtractFileName(Filename), '.wav', '', [rfReplaceAll, rfIgnoreCase]);
FreeAndNil(WaveFile);
end;
end;
FWaves.ExportWaveNames(FSoundsNames);
end;
procedure TSoundRepository.SetVoice(AVoice: String);
begin
FVoice := AVoice;
LoadWaves;
end;
end.
|
(* ***************************************************************************
SkRegExpConst.pas (SkRegExp regular expression library)
**************************************************************************** *)
(*
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Original Code is SkRegExpConst.pas(for SkRegExp Library).
The Initial Developer of the Original Code is Shuichi Komiya.
E-mail: shu AT k DOT email DOT ne DOT jp
URL: http://komish.com/softlib/skregexp.htm
Portions created by Shuichi Komiya are
Copyright (C) 2007-2011 Shuichi Komiya. All Rights Reserved.
*)
unit SkRegExpConst;
interface
{$DEFINE JapaneseMessage}
resourcestring
{$IFDEF JapaneseMessage}
{ Error Message Japanese }
{ Complile error messages }
sNotRecognized = '%s認識できない正規表現です';
sHexDigitIsRequired = '%s16進数が必要です';
sCodePointRangeOver = '%sコードポイントの範囲を超えています';
sLoopOfMatchAheadNotSpecified = '先読みでの繰り返しは指定できません';
sUnmatchedBigPar = '%s [ がマッチしません';
sMissingRightBraceOnEscx = '%s } がありません';
sQuantifierIsTooLarge = '%s繰り返しの数が大きすぎます';
sCantDoMaxLessMin = '%s最大値より最小値のほうが大きいです';
sPosixClassUnkown = '[:%s:] はPOSIXクラスではありません';
sInvalideBigParRange = '文字クラスの範囲指定が違います [%s]';
sGroupNameIsEmpty = '%sグループ名がありません';
sGroupNumberIsEmpty = '%sグループ番号がありません';
sNoEndOfGroup = '%sグループが終了していません';
sUnmatchedSmallPar = '%s ( がマッチしません';
sOptionNotCompleted = '%sオプションの指定が終了していません';
sPropertyUnknown = '{%s} はプロパティではありません';
sInvalidProperty = '%sプロパティが不正です';
sMissingRightBrace = '%s ] がありません';
sQuestPosInaccurate = '?の位置が不正です';
sLoopOfLengthZeroCannotSpecified = '%s長さゼロの繰り返しはできません';
sRegExpNotCompleted = '%s正規表現が正しく終了していません';
sInvalidCharactorClass = '%s不正な文字クラスです';
sCannotCallMultipleDefineGroupName = '多重定義されたグループ名<%s>の部分式は呼び出せません';
sInvalidGroupNumber = 'グループ番号<%d>はこの位置からは参照できません';
sInvalidGroupName = 'グループ名<%s>の書式が間違っています';
sInvalidCharInGroupName = 'グループ名の中に不正な文字があります';
sBehindMatchNotGroup = '%s戻り読み内でグループは使えません';
sNeverEndingRecursion = '%s終了しないかもしない再帰があります';
sBehindMatchNotVariableLength = '%s戻り読み内で可変長文字列は使えません';
sInvalideCondition = '%s条件式が不正です';
sContainsTooManyBranches = '条件構文の分岐が多すぎます';
sNotTerminated = '%s正規表現が終了していません';
sInvalidEscapeCharacterSyntax = '%sエスケープ文字の書式が間違っています';
sPosixClassSupportedOnlyClass = '%sPOSIX文字クラスが使えるのは文字クラスの中だけです';
// end of compile error
{ Runtime error messages }
sFatalError = '致命的エラー';
sExecFuncNotCall = 'Execメソッドが実行されていません';
sEOLRangeOver = '改行文字に指定できるは2文字以内です';
sUnmatchedCurlyBracket = '%s { がマッチしません';
sRangeOverGroupNumber = 'グループ番号<%d>は範囲を越えています';
sMissingGroupName = 'グループ名<%s>は存在しません';
sNotFoundOldCode = 'BUG: not found OldCode';
{$ELSE}
{ Error Message English }
{ Complile error messages }
sNotRecognized = '%s not recognized';
sHexDigitIsRequired = '%sHex-digit is required';
sCodePointRangeOver = '%sCodepoint range over';
sLoopOfMatchAheadNotSpecified = 'Loop of match ahead not specified';
sUnmatchedBigPar = '%sUnmatched [';
sMissingRightBraceOnEscx = '%sMissing right brace on \x{}';
sQuantifierIsTooLarge = '%sQuantifier is too large';
sCantDoMaxLessMin = '%sCan''t do {n,m} with n > m';
sPosixClassUnkown = 'Posix class [:%s:] unknown';
sInvalideBigParRange = 'Invalid [] range [%s]';
sGroupNameIsEmpty = '%sgroup name is empty';
sGroupNumberIsEmpty = '%sGroup number is empty';
sNoEndOfGroup = '%sNo end of group';
sUnmatchedSmallPar = '%sUnmatched (';
sOptionNotCompleted = '%sOption not completed';
sPropertyUnknown = 'Property {%s} unkown';
sInvalidProperty = '%sInvalide property';
sMissingRightBrace = '%sMissing right brace';
sQuestPosInaccurate = '%s? position is inaccurate';
sLoopOfLengthZeroCannotSpecified = '%sLoop of Length zero cannot specified';
sRegExpNotCompleted = '%sRegular expression not completed';
sInvalidCharactorClass = '%sInvalid charactor class';
sCannotCallMultipleDefineGroupName =
'Multiple define group name <%s> can not call'; // check!
sInvalidGroupNumber = 'Invalid group number <%d>';
sInvalidGroupName = 'Invalid group name <%s>';
sInvalidCharInGroupName = '%sInvalid char in group name';
sBehindMatchNotGroup = '%sBehind match not group';
sNeverEndingRecursion = '%sNever ending recursion';
sBehindMatchNotVariableLength = '%sBehind match not variable length';
sInvalideCondition = '%sInvalid Condition';
sContainsTooManyBranches = 'Contains too many Branches';
sNotTerminated = '%sNot terminated';
sInvalidEscapeCharacterSyntax = '%sInvalid escape charactoer syntax';
sPosixClassSupportedOnlyClass = '%sPOSIX named classes are supported only within a class';
.
// end of compile error
{ Runtime error messages }
sFatalError = 'Fatal error';
sExecFuncNotCall = 'Exec function not call';
sEOLRangeOver = 'EOL range over';
sUnmatchedCurlyBracket = '%sUnmatched {';
sRangeOverGroupNumber = 'Range over group number <%d>';
sMissingGroupName = 'Missing group number <%s>';
sNotFoundOldCode = 'BUG: not found OldCode';
{$ENDIF} // end of error message
{$IFDEF DEBUG}
{ for debug }
sLiteral = 'EXACT <%s> ';
sAnyChar = 'ANY ';
sWordChar = 'WORD ';
sNegativeWordChar = 'NWORD ';
sDigitChar = 'DIGIT ';
sNegativeDigitChar = 'NDIGIT ';
sHexDigitChar = 'HEXD ';
sNegativeHexDigitChar = 'NHEXD ';
sSpaceChar = 'SPACE ';
sNegativeSpaceChar = 'NSPACE ';
sHorizontalSpaceChar = 'HSPACE ';
sNegativeHorizontalSpaceChar = 'NHSPACE ';
sVerticalSpaceChar = 'VSPACE ';
sNegativeVerticalSpaceChar = 'NVSPACE ';
sLineBreakChar = 'LINEBREK ';
sMsgRange = 'RANGE ';
sCombiningSequence = 'COMBSQ ';
sBoundaryCode = 'BOUND ';
sNegativeBoundaryCode = 'NBOUND ';
sFmtGroupReference = 'REF%d ';
sFmtGroupNameReference = 'REF[%s]';
sHeadOfLineCode = 'BOL';
sEndOfLineCode = 'EOL';
sTextHeadCode = 'SBOS';
sTextTailCode = 'SEOL';
sTextEndCode = 'EOS';
sPropertyCode = 'POSIXB';
sNegativePropertyCode = 'NPOSIXB';
// 1.1.0 add
sIfThenReference = 'Cond<%d>';
sIfThenNamedReference = 'CondName<%s>';
sGlobalPos = 'GPOS: ';
sFmtDumpLeadCodeExist = 'LeadChar: ';
sFmtDumpLeadCodeNotExist = 'LeadChar : No';
sBinCode_Raise = 'bug: not define operator';
sFmtDumpNFA_Start = '%2d : ';
sFmtDumpNFA_End = '%2d : ';
sFmtDumpNFA_EndStr = 'END';
sFmtDumpNFA_Status = '%2d : ';
sFmtDumpNFA_Empty = 'NOTHING (%d) :';
sFmtDumpNFA_LoopExit = 'LOOPEXIT (%d) :';
sFmtDumpNFA_LoopEnd = 'LOOPEND (%d) :';
sFmtDumpNFA_Star = 'STAR (%d) %s:';
sFmtDumpNFA_Plus = 'PLUS (%d) %s:';
sFmtDumpNFA_Bound = 'BOUND (%d) :';
sFmtDumpNFA_Loop = 'LOOP%s [%d, %d] (%d) :';
sFmtDumpNFA_Quest = 'QUEST (%d) :';
sFmtDumpNFA_AheadMatch = 'AMATCH (%d) :';
sFmtDumpNFA_AheadNoMatch = 'NAMATCH (%d) :';
sFmtDumpNFA_BehindMatch = 'BMATCH (%d) :';
sFmtDumpNFA_BehindNoMatch = 'NBMATCH (%d) :';
sFmtDumpNFA_MatchEnd = 'EOMATCH (%d) :';
sFmtDumpNFA_GroupStart = 'OPEN%d (%d) :';
sFmtDumpNFA_GroupEnd = 'CLOSE%d (%d) :';
sFmtDumpNFA_NoBackTrackBegin = 'NBACKTRB (%d) :';
sFmtDumpNFA_Null = '%s (%d) :';
// 0.9.4 add
sFmtDumpNFA_GoSub = 'GOSUB [%d] (%d) :';
// 1.1.0 add
sFmtDumpNFA_IfMatch = 'IFMATCH (%d) :';
// 1.1.0 add
sFmtDumpNFA_IfThen = 'IFTHEN (%d) :';
sFmtDumpNFA_KeepPattern = 'KEEPL (%d) :';
// 1.3.0 add
sFmtDumpNFA_Fail = 'FAIL (%d) :';
//
sBinCode_Union = 'Union "|"';
sBinCode_Concat = 'Concat';
sBinCode_Emply = 'Empty';
sBinCode_Plus = 'Plus "+"';
sBinCode_Star = 'Star "*"';
sBinCode_Loop = 'Repeat ';
sBinCode_Quest = 'Quest "?"';
sBinCode_Bound = 'Bound';
sBinCode_LHead = 'Line head';
sBinCode_LTail = 'Line tail';
sBinCode_Group = 'Group';
sBinCode_AheadMatch = 'Ahead match';
sBinCode_BehindMatch = 'Behind match';
sBinCode_AheadNoMatch = 'Ahead no match';
sBinCode_BehindNoMatch = 'Behind no match';
sBinCode_NoBackTrack = 'No backtrack';
// 0.9.4 add
sBinCode_GroupCall = 'Call';
// 1.1.0 add
sBinCode_IfMatch = 'IfMatch';
sBinCode_IfThen = 'IfThen';
sBinCode_KeepPattern = 'KeepLeft';
// 1.3.0 add
sBinCode_Fail = 'Fail';
{$ENDIF} // end of Debug;
implementation
end.
|
unit Unit_Row_SubTitles;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMXTee.Control,
FMXTee.Grid, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts;
type
TForm43 = class(TForm)
TeeGrid1: TTeeGrid;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form43: TForm43;
implementation
{$R *.fmx}
uses
Tee.Grid.Data.Strings, Tee.Grid.Bands, Tee.Format, Unit_Sample;
function NewTitle(const AText:String):TTitleBand;
begin
result:=TTitleBand.Create(nil);
result.Text:=AText;
result.Format.Brush.Show;
result.Format.Brush.Color:=TAlphaColors.Brown;
result.Format.Font.Color:=TAlphaColors.White;
end;
procedure TForm43.FormCreate(Sender: TObject);
var Data : TStringsData;
begin
// Use a TStringsData for this example, just for simplicity
Data:=TStringsData.Create;
Data.Resize(5,20);
// Fill sample values
FillSamples(Data);
TeeGrid1.Data:=Data;
// Add custom sub-title bands
TeeGrid1.Rows.SubBands[0]:=NewTitle('North');
TeeGrid1.Rows.SubBands[6]:=NewTitle('East');
TeeGrid1.Rows.SubBands[11]:=NewTitle('South');
TeeGrid1.Rows.SubBands[18]:=NewTitle('West');
end;
end.
|
unit ufrmSysGridColPercent;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.Menus, Vcl.Samples.Spin,
Vcl.AppEvnts,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.Memo,
Ths.Erp.Helper.ComboBox,
ufrmBase, ufrmBaseInputDB
, Ths.Erp.Database.Table.View.SysViewTables
, Ths.Erp.Database.Table.View.SysViewColumns
;
type
TfrmSysGridColPercent = class(TfrmBaseInputDB)
cbbColumnName: TComboBox;
cbbTableName: TComboBox;
edtColorBar: TEdit;
edtColorBarBack: TEdit;
edtColorBarText: TEdit;
edtColorBarTextActive: TEdit;
edtMaxValue: TEdit;
imgExample: TImage;
lblColorBar: TLabel;
lblColorBarBack: TLabel;
lblColorBarText: TLabel;
lblColorBarTextActive: TLabel;
lblColumnName: TLabel;
lblMaxValue: TLabel;
lblTableName: TLabel;
procedure FormCreate(Sender: TObject);override;
procedure RefreshData();override;
procedure btnAcceptClick(Sender: TObject);override;
procedure cbbTableNameChange(Sender: TObject);
procedure edtColorBarDblClick(Sender: TObject);
procedure edtColorBarBackDblClick(Sender: TObject);
procedure edtColorBarTextDblClick(Sender: TObject);
procedure edtColorBarTextActiveDblClick(Sender: TObject);
private
vSysViewTables: TSysViewTables;
vSysViewColumns: TSysViewColumns;
procedure SetColor(color: TColor; editColor: TEdit);
procedure DrawBar;
public
destructor Destroy; override;
protected
published
procedure FormShow(Sender: TObject); override;
end;
implementation
uses
Ths.Erp.Database.Table.SysGridColPercent
, Ths.Erp.Database.Singleton
, Ths.Erp.Functions
, Ths.Erp.Constants
;
{$R *.dfm}
procedure TfrmSysGridColPercent.cbbTableNameChange(Sender: TObject);
begin
fillComboBoxData(cbbColumnName, vSysViewColumns, vSysViewColumns.ColumnName.FieldName, ' AND ' + vSysViewColumns.TableName1.FieldName + '=' + QuotedStr(cbbTableName.Text) + ' ORDER BY ' + vSysViewColumns.OrdinalPosition.FieldName + ' ASC ');
end;
destructor TfrmSysGridColPercent.Destroy;
begin
if Assigned(vSysViewTables) then
vSysViewTables.Free;
if Assigned(vSysViewColumns) then
vSysViewColumns.Free;
inherited;
end;
procedure TfrmSysGridColPercent.DrawBar;
var
x1, x2, y1, y2: Integer;
rect: TRect;
vTemp: string;
begin
vTemp := 'Example %40';
with imgExample do
begin
Canvas.Pen.Style := psSolid;
Canvas.Pen.Width := 1;
Canvas.Pen.Color := StringToColor(edtColorBarBack.Text);
Canvas.Brush.Color := StringToColor(edtColorBarBack.Text);
x1 := 0; x2 := Width; y1 := 0; y2 := Height;
Canvas.Rectangle( x1, y1, x2, y2 );
Canvas.Pen.Color := StringToColor(edtColorBar.Text);
Canvas.Brush.Color := StringToColor(edtColorBar.Text);
x1 := 1; x2 := trunc(Width*0.40); y1 := 1; y2 := Height;
Canvas.Rectangle( x1, y1, x2, y2 );
Canvas.Brush.Style := bsClear;
Canvas.Font.Color := StringToColor( edtColorBarText.Text );
//Canvas.Brush.Color := StringToColor(edtcolor_bar_text.Text);
rect.Left := (imgExample.Width - Canvas.TextWidth(vTemp)) div 2;
rect.Right := rect.Left + Canvas.TextWidth(vTemp);
rect.Top := (imgExample.Height - Canvas.TextHeight(vTemp)) div 2;
rect.Bottom := rect.Top + Canvas.TextHeight(vTemp);
Canvas.TextRect(rect, vTemp);
Repaint;
end;
end;
procedure TfrmSysGridColPercent.edtColorBarDblClick(Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtColorBar.Text, 0)), edtColorBar);
end;
procedure TfrmSysGridColPercent.edtColorBarBackDblClick(Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtColorBarBack.Text, 0)), edtColorBarBack);
end;
procedure TfrmSysGridColPercent.edtColorBarTextDblClick(Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtColorBarText.Text, 0)), edtColorBarText);
end;
procedure TfrmSysGridColPercent.edtColorBarTextActiveDblClick(
Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtColorBarTextActive.Text, 0)), edtColorBarTextActive);
end;
procedure TfrmSysGridColPercent.FormCreate(Sender: TObject);
begin
TSysGridColPercent(Table).TableName1.SetControlProperty(Table.TableName, cbbTableName);
TSysGridColPercent(Table).ColumnName.SetControlProperty(Table.TableName, cbbColumnName);
TSysGridColPercent(Table).MaxValue.SetControlProperty(Table.TableName, edtMaxValue);
TSysGridColPercent(Table).ColorBar.SetControlProperty(Table.TableName, edtColorBar);
TSysGridColPercent(Table).ColorBarBack.SetControlProperty(Table.TableName, edtColorBarBack);
TSysGridColPercent(Table).ColorBarText.SetControlProperty(Table.TableName, edtColorBarText);
TSysGridColPercent(Table).ColorBarTextActive.SetControlProperty(Table.TableName, edtColorBarTextActive);
inherited;
cbbTableName.CharCase := ecNormal;
cbbColumnName.CharCase := ecNormal;
vSysViewTables := TSysViewTables.Create(Table.Database);
vSysViewColumns := TSysViewColumns.Create(Table.Database);
fillComboBoxData(cbbTableName, vSysViewTables, vSysViewTables.TableName1.FieldName, '');
cbbTableNameChange(cbbTableName);
end;
procedure TfrmSysGridColPercent.FormShow(Sender: TObject);
begin
inherited;
edtColorBar.ReadOnly := True;
edtColorBarBack.ReadOnly := True;
edtColorBarText.ReadOnly := True;
edtColorBarTextActive.ReadOnly := True;
end;
procedure TfrmSysGridColPercent.RefreshData();
begin
cbbTableName.ItemIndex := cbbTableName.Items.IndexOf(TSysGridColPercent(Table).TableName1.Value);
cbbTableNameChange(cbbTableName);
cbbColumnName.ItemIndex := cbbColumnName.Items.IndexOf(TSysGridColPercent(Table).ColumnName.Value);
edtMaxValue.Text := TSysGridColPercent(Table).MaxValue.Value;
edtColorBar.Text := TSysGridColPercent(Table).ColorBar.Value;
edtColorBarBack.Text := TSysGridColPercent(Table).ColorBarBack.Value;
edtColorBarText.Text := TSysGridColPercent(Table).ColorBarText.Value;
edtColorBarTextActive.Text := TSysGridColPercent(Table).ColorBarTextActive.Value;
SetColor(StrToIntDef(edtColorBar.Text, 0), edtColorBar);
SetColor(StrToIntDef(edtColorBarBack.Text, 0), edtColorBarBack);
SetColor(StrToIntDef(edtColorBarText.Text, 0), edtColorBarText);
SetColor(StrToIntDef(edtColorBarTextActive.Text, 0), edtColorBarTextActive);
DrawBar;
end;
procedure TfrmSysGridColPercent.SetColor(color: TColor; editColor: TEdit);
begin
editColor.Text := IntToStr(color);
editColor.Color := color;
editColor.thsColorActive := color;
editColor.thsColorRequiredInput := color;
editColor.Repaint;
DrawBar;
end;
procedure TfrmSysGridColPercent.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
if cbbTableName.Items.IndexOf(cbbTableName.Text) = -1 then
raise Exception.Create( TranslateText('Listede olmayan bir Tablo Adư giremezsiniz!', '#1', LngMsgError, LngSystem) );
if cbbColumnName.Items.IndexOf(cbbColumnName.Text) = -1 then
raise Exception.Create(TranslateText('Listede olmayan bir Kolon Adư giremezsiniz!', '#1', LngMsgError, LngSystem) );
TSysGridColPercent(Table).TableName1.Value := cbbTableName.Text;
TSysGridColPercent(Table).ColumnName.Value := cbbColumnName.Text;
TSysGridColPercent(Table).MaxValue.Value := edtMaxValue.Text;
TSysGridColPercent(Table).ColorBar.Value := edtColorBar.Text;
TSysGridColPercent(Table).ColorBarBack.Value := edtColorBarBack.Text;
TSysGridColPercent(Table).ColorBarText.Value := edtColorBarText.Text;
TSysGridColPercent(Table).ColorBarTextActive.Value := edtColorBarTextActive.Text;
inherited;
end;
end
else
begin
inherited;
edtColorBar.ReadOnly := True;
edtColorBarBack.ReadOnly := True;
edtColorBarText.ReadOnly := True;
edtColorBarTextActive.ReadOnly := True;
end;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Kingston;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TKingstonSMARTSupport = class(TSMARTSupport)
private
function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite;
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;
end;
implementation
{ TKingstonSMARTSupport }
function TKingstonSMARTSupport.GetTypeName: String;
begin
result := 'SmartKingston';
end;
function TKingstonSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TKingstonSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TKingstonSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
// 2015/11/29
result :=
(SMARTList.Count >= 10) and
(SMARTList[0].Id = $01) and
(SMARTList[1].Id = $02) and
(SMARTList[2].Id = $03) and
(SMARTList[3].Id = $05) and
(SMARTList[4].Id = $07) and
(SMARTList[5].Id = $08) and
(SMARTList[6].Id = $09) and
(SMARTList[7].Id = $0A) and
(SMARTList[8].Id = $0C) and
(SMARTList[9].Id = $A8);
end;
function TKingstonSMARTSupport.ErrorCheckedGetLife(
const SMARTList: TSMARTValueList): Integer;
begin
result := SMARTList[SMARTList.GetIndexByID($E7)].Current;
end;
function TKingstonSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
const
WriteID1 = $F1;
WriteID2 = $E9;
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 TKingstonSMARTSupport.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 TKingstonSMARTSupport.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 = $E9;
begin
try
result.InValue.ValueInMiB :=
LBAToMB(SMARTList.GetRAWByID(WriteID1));
result.InValue.TrueHostWriteFalseNANDWrite :=
HostWrite;
except
try
result.InValue.ValueInMiB :=
GBToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID2));
result.InValue.TrueHostWriteFalseNANDWrite :=
NANDWrite;
except
result.InValue.ValueInMiB := 0;
end;
end;
end;
end.
|
unit ncaFrmConfig_Gaveta;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseOpcaoImgTxtCheckBox,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer,
cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxLabel, cxCheckBox,
dxGDIPlusClasses, Vcl.ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel,
LMDCustomBevelPanel, LMDSimplePanel, cxTextEdit, LMDThemedComboBox,
LMDCustomComboBox, LMDPrinterComboBox;
type
TFrmConfig_Gaveta = class(TFrmBaseOpcaoImgTxtCheckBox)
lbImp: TcxLabel;
edImp: TLMDPrinterComboBox;
lbF11: TcxLabel;
edCmd: TcxTextEdit;
lbCmd: TcxLabel;
procedure CBClick(Sender: TObject);
private
{ Private declarations }
public
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
function NumItens: Integer; override;
procedure Atualiza;
{ Public declarations }
end;
var
FrmConfig_Gaveta: TFrmConfig_Gaveta;
implementation
{$R *.dfm}
uses ncaConfigRecibo;
{ TFrmConfig_Gaveta }
resourcestring
rsImpNecessario = 'É necessário informar a impressora onde a gaveta está conectada';
rsCmdNecessario = 'É necessário informar o comando a ser enviado para a impressora ' +
'para que ela faça a abertura da gaveta. Faça contato com a Nextar '+
'para saber qual é o comando correto para seu modelo de impressora.';
function TFrmConfig_Gaveta.Alterou: Boolean;
begin
Result :=
(gRecibo.MostrarGaveta <> CB.Checked) or
(gRecibo.Values['imp_gaveta'] <> edImp.Text) or
(gRecibo.StrAbreGaveta <> edCmd.Text);
end;
procedure TFrmConfig_Gaveta.Atualiza;
begin
lbDescr.Enabled := CB.Checked;
lbImp.Enabled := CB.Checked;
edImp.Enabled := CB.Checked;
lbCmd.Enabled := CB.Checked;
edCmd.Enabled := CB.Checked;
lbF11.Enabled := CB.Checked;
end;
procedure TFrmConfig_Gaveta.CBClick(Sender: TObject);
begin
inherited;
Atualiza;
end;
procedure TFrmConfig_Gaveta.Ler;
begin
inherited;
CB.Checked := gRecibo.MostrarGaveta;
edImp.ItemIndex := edImp.Items.IndexOf(gRecibo.Values['imp_gaveta']);
edCmd.Text := gRecibo.CmdAbreGaveta;
Atualiza;
end;
function TFrmConfig_Gaveta.NumItens: Integer;
begin
Result := 3;
end;
procedure TFrmConfig_Gaveta.Renumera;
begin
CB.Caption := IntToStr(InicioNumItem) + '. ' + CB.Caption;
lbImp.Caption := IntToStr(InicioNumItem+1) + '. ' + lbImp.Caption;
lbCmd.Caption := IntToStr(InicioNumItem+2) + '. ' + lbCmd.Caption;
end;
procedure TFrmConfig_Gaveta.Salvar;
begin
inherited;
if CB.Checked then begin
if edImp.Text='' then
raise Exception.Create(rsImpNecessario);
if Trim(edCmd.Text)='' then
raise Exception.Create(rsCmdNecessario);
end;
gRecibo.MostrarGaveta := CB.Checked;
gRecibo.Values['imp_gaveta'] := edImp.Text;
gRecibo.CmdAbreGaveta := edCmd.Text;
gRecibo.Save;
end;
end.
|
unit CPortX;
interface
uses
Windows, Messages, SysUtils, Variants, Classes,
Dialogs,
CPort, CPortCtl;
//**********************************************************************//
// //
// 例外通知用のクラス //
// //
//**********************************************************************//
type
EAppError = class(Exception);
type
TRecvMsgEvent = procedure(Sender: TObject; RecvStr: string) of object;
//**********************************************************************//
// //
// CommXの拡張クラス //
// //
//**********************************************************************//
type
TCPortX = class(TComPort)
private
{ Private 宣言 }
FActive: boolean;
FDelimiter: string;
FRecvMsg: string;
FOnRecvMsg: TRecvMsgEvent;
// FTriggersOnRxChar: boolean;
procedure SetBaudRate(const Value: string);
procedure SetDataBits(const Value: string);
procedure SetFlowControl(const Value: string);
procedure SetParity(const Value: string);
procedure SetStopBits(const Value: string);
procedure SetDelimiter(const Value: string);
procedure DoRecvMsg;
procedure RecvOnRxChar(Sender: TObject; count: integer);
function GetBaudRate: string;
function GetDataBits: string;
function GetFlowControl: string;
function GetStopBits: string;
function GetParity: string;
public
{ Public 宣言 }
property Active: boolean read FActive write FActive;
property BaudRate: string read GetBaudRate write SetBaudRate;
property DataBits: string read GetDataBits write SetDataBits;
property Delimiter: string read FDelimiter write SetDelimiter;
// property Delimiter;
property FlowControl: string read GetFlowControl write SetFlowControl;
property RecvMsg: string read FRecvMsg;
property Parity: string read GetParity write SetParity;
property StopBits: string read GetStopBits write SetStopBits;
// property TriggersOnRxChar: boolean read FTriggersOnRxChar write SetTriggersOnRxChar;
property OnRecvMsg: TRecvMsgEvent read FOnRecvMsg write FOnRecvMsg;
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Open();
procedure Close;
procedure Clear();
function RecvStr(Len: integer):string;
procedure SendStr(str: string);
end;
implementation
/////////////////////////////////////////////////////////////////////////////////////////////
//
// Commポートの処理
//
/////////////////////////////////////////////////////////////////////////////////////////////
constructor TCPortX.Create(Owner: TComponent);
begin
Inherited;
try
with Timeouts do
begin
// (受信トータルタイムアウト) = ReadTotalMultiplier * (受信予定バイト数) + ReadTotalConstant
ReadInterval := 500; // 0.5秒(ms)(0でタイムアウトなし)
ReadTotalMultiplier := 10; // 入力タイムアウトの乗数 mSec/Byte : 1バイトに対するタイムアウト乗数(0でタイムアウトなし)
ReadTotalConstant := 500; // 入力タイムアウトの定数 : 0バイト時のタイムアウト定数(0でタイムアウトなし)
// (送信トータルタイムアウト) = WriteTotalMultiplier * (送信予定バイト数) + WriteTotalConstant
WriteTotalMultiplier := 10; // Write : 1バイトに対するタイムアウト乗数(0でタイムアウトなし)
WriteTotalConstant := 100; // Write : 0バイト時のタイムアウト定数(0でタイムアウトなし)
end;
OnRxChar := RecvOnRxChar;
finally
end;
end;
destructor TCPortX.Destroy;
begin
Inherited;
end;
procedure TCPortX.Open();
begin
if FDelimiter = '' then
TriggersOnRxChar := false
else
TriggersOnRxChar := true;
FActive := true;
inherited;
end;
procedure TCPortX.Close();
begin
Inherited;
FActive := false;
end;
procedure TCPortX.Clear();
begin
ClearBuffer(true,true);
end;
function TCPortX.RecvStr(Len: integer):string;
var
buf: string;
j : Integer ;
begin
Result := '';
j := ReadStr(buf, Len);
try
Result := Copy(buf, 1, j);
except
Result := '';
end;
end;
procedure TCPortX.RecvOnRxChar(Sender: TObject; count: integer);
begin
ReadStr(FRecvMsg, count);
DoRecvMsg;
end;
procedure TCPortX.DoRecvMsg;
begin
if Assigned(FOnRecvMsg) then
FOnRecvMsg(self, FRecvMsg);
end;
function TCPortX.GetBaudRate: string;
begin
result := BaudRateToStr(inherited BaudRate);
end;
function TCPortX.GetDataBits: string;
begin
result := DataBitsToStr(inherited DataBits);
end;
function TCPortX.GetFlowControl: string;
begin
result := FlowControlToStr(inherited FlowControl.FlowControl);
end;
function TCPortX.GetParity: string;
begin
result := ParityToStr(inherited Parity.Bits);
end;
function TCPortX.GetStopBits: string;
begin
result := StopBitsToStr(inherited StopBits);
end;
procedure TCPortX.SendStr(str: string);
begin
WriteStr(Str);
end;
procedure TCPortX.SetBaudRate(const Value: string);
begin
inherited Baudrate := StrToBaudRate(value);
end;
procedure TCPortX.SetDataBits(const Value: string);
begin
inherited DataBits := StrToDataBits(Value);
end;
procedure TCPortX.SetDelimiter(const Value: string);
begin
FDelimiter := Value;
if Fdelimiter = '' then
TriggersOnRxChar :=false
else
begin
TriggersOnRxChar :=true;
EventChar := FDelimiter[1];
end;
end;
procedure TCPortX.SetFlowControl(const Value: string);
begin
inherited FlowControl.FlowControl := StrToFlowControl(Value);
end;
procedure TCPortX.SetParity(const Value: string);
begin
inherited Parity.Bits := StrToParity(Value);
end;
procedure TCPortX.SetStopBits(const Value: string);
begin
inherited StopBits := StrToStopBits(VAlue);
end;
end.
|
unit Server_impl;
{This file was generated on 16 Jun 2000 17:01:40 GMT by version 03.03.03.C1.04}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file server.idl. }
{Delphi Pascal unit : Server_impl }
{derived from IDL module : Server }
interface
uses
SysUtils,
CORBA,
Server_i,
Server_c;
type
TIMyTest = class;
TMyTestFactory = class;
TIMyTest = class(TInterfacedObject, Server_i.IMyTest)
protected
{******************************}
{*** User variables go here ***}
{******************************}
public
constructor Create;
function Get_X : Integer;
end;
TMyTestFactory = class(TInterfacedObject, Server_i.MyTestFactory)
protected
{******************************}
{*** User variables go here ***}
{******************************}
public
constructor Create;
function CreateInstance ( const InstanceName : AnsiString): Server_i.IMyTest;
end;
implementation
constructor TIMyTest.Create;
begin
inherited;
{ *************************** }
{ *** User code goes here *** }
{ *************************** }
end;
function TIMyTest.Get_X : Integer;
begin
{ *************************** }
{ *** User code goes here *** }
{ *************************** }
end;
constructor TMyTestFactory.Create;
begin
inherited;
{ *************************** }
{ *** User code goes here *** }
{ *************************** }
end;
function TMyTestFactory.CreateInstance ( const InstanceName : AnsiString): Server_i.IMyTest;
begin
{ *************************** }
{ *** User code goes here *** }
{ *************************** }
end;
initialization
end. |
unit uEngineConfig;
{$DEFINE TEST}
interface
uses
System.Classes,System.SysUtils,System.Json,FMX.Graphics, uEngineResource,
uEngine2DClasses;
Type
TResourceType = (rtImage,rtText);
TBaseConfig = class
protected
FSourceName : String; //精灵名
FType : TResourceType; //精灵类型
FResManager : TEngineResManager;
public
property SourceName : String read FSourceName write FSourceName;
property ResourceType : TResourceType read FType write FType;
Property Resmanager : TEngineResManager Read FResManager Write FResManager;
end;
TImageConfig = class(TBaseConfig)
private
Type
TBasePlay = class
protected
FAnimationCount : Integer;
FFilePath : String;
FResManager : TEngineResManager;
// procedure SetFilePath(value : String);virtual;abstract;
public
Constructor Create(AResManager : TEngineResManager);
procedure LoadFromJsonObject(AJson :TJsonObject);virtual;
property AnimationCount : Integer read FAnimationCount write FAnimationCount;
// property FilePath : String write SetFilePath;
end;
TNormalPlay = class(TBasePlay)
private
FIndexList : TStringList;
FAnimationList : TStringList;
FAnimationInterval : Integer;
FDelayInterval : Integer;
FLoop : boolean;
FControlName : String;
function GetBitmap(index:Integer):TBitmap;
// procedure SetFilePath(value : String); override;
public
Constructor Create(AResManager : TEngineResManager);
Destructor Destroy;override;
procedure LoadFromJsonObject(AJson :TJsonObject); override;
property Item[index:Integer] : TBitmap read GetBitmap;
property AnimationInterval : Integer read FAnimationInterval write FAnimationInterval;
property DelayInterval : Integer read FDelayInterval write FDelayInterval;
property Loop : boolean read FLoop write FLoop default false;
property ControlName : String read FControlName;
end;
//目前默认mousemove 的时候最多切换一张图
TMouseMovePlay = class(TBasePlay)
private
FBitmap : TBitmap;
// procedure SetFilePath(value:String);override;
public
Constructor Create(AResManager : TEngineResManager);
Destructor Destroy;override;
property Item : TBitmap read FBitmap;
end;
private
FNormalBitmap : TBitmap; // 静态的时候显示的图片....
// FCurNormalIndex : Integer;
FNormalPlayControler : TNormalPlay;
FMouseMovePlayControler : TMouseMovePlay;
FNormalPlayManager : T2DNameList<TNormalPlay>;
FOnSwitchStatus : TGetStrProc;
FFinishProc : TProc;
// function GetCurNormalPlayControl : TNormalPlay;
public
Constructor Create(AJson :TJsonObject;AResManager : TEngineResManager);
Destructor Destroy;override;
Procedure SetNormalImg(inName : String);overload; // 设置下正常显示的图片的名称..
procedure SetNormalImg(AIndex : Integer);overload; // 多图模式,切换图片
procedure LoadNormalControler(AJson : TJsonArray;AIndex : Integer = 0);
procedure SwitchNormalControlerByName(AName : String;AFinishProc : TProc);
property NormalBitmap :TBitmap Read FNormalBitmap Write FNormalBitmap;
property NormalPlayControler : TNormalPlay read FNormalPlayControler write FNormalPlayControler; // GetCurNormalPlayControl;
property MouseMovePlayControler : TMouseMovePlay read FMouseMovePlayControler;
property FinishProc : TProc read FFinishProc write FFinishProc;
property OnSwitchStatus : TGetStrProc read FOnSwitchStatus write FOnSwitchStatus;
end;
const DRAW_INTERVAL = 40; // unit : ms
implementation
{ TImageConfig.TNormalPlay }
constructor TImageConfig.TNormalPlay.Create(AResManager : TEngineResManager);
begin
inherited Create(AResManager);
FIndexList := TStringList.Create;
FAnimationList := TStringList.Create(true);
end;
destructor TImageConfig.TNormalPlay.Destroy;
begin
FIndexList.DisposeOf;
FAnimationList.DisposeOf;
inherited;
end;
function TImageConfig.TNormalPlay.GetBitmap(index: Integer): TBitmap;
var
LBmp : TBitmap;
LKey : String;
LPos : Integer;
begin
if index > FIndexList.Count then
begin
result := nil;
exit;
end;
LKey := FIndexList.Strings[index];
LPos := FAnimationList.IndexOf(LKey);
if LPos = -1 then
begin
LBmp := TBitmap.Create;
// LBmp.LoadFromFile('res/'+LKey);
FResManager.LoadResource(LBmp,LKey);
FAnimationList.AddObject(LKey,LBmp);
end else
begin
LBmp := FAnimationList.Objects[LPos] as TBitmap;
end;
result := LBmp;
end;
procedure TImageConfig.TNormalPlay.LoadFromJsonObject(AJson: TJsonObject);
begin
if AJson <> nil then
begin
FControlName := AJson.Values['Name'].Value;
FAnimationCount := StrToIntDef(AJson.Values['Count'].Value,1);
FFilePath := AJson.Values['FilePath'].Value;
FResManager.LoadResource(FIndexList,FFilePath);
FAnimationInterval := StrToIntDef(AJson.Values['Interval'].Value,300);
FDelayInterval := StrToIntDef(AJson.Values['Delay'].Value,0);
FLoop := UpperCase(AJson.Values['Loop'].Value) = 'TRUE';
end;
end;
{ TImageConfig }
constructor TImageConfig.Create(AJson: TJsonObject;AResManager : TEngineResManager);
begin
FResManager := AResManager;
FNormalBitmap := TBitmap.Create;
FNormalPlayManager := T2DNameList<TNormalPlay>.Create;
// FNormalPlayControler := TNormalPlay.Create(AResManager);
FMouseMovePlayControler := TMouseMovePlay.Create(AResManager);
end;
destructor TImageConfig.Destroy;
begin
FNormalBitmap.DisposeOf;
FNormalPlayManager.DisposeOf;
// FNormalPlayControler.DisposeOf;
FMouseMovePlayControler.DisposeOf;
inherited;
end;
//function TImageConfig.GetCurNormalPlayControl: TNormalPlay;
//begin
// if FCurNormalIndex < FNormalPlayManager.ItemCount then
// result := FNormalPlayManager.Items[FCurNormalIndex] else
// result := nil;
//end;
procedure TImageConfig.LoadNormalControler(AJson: TJsonArray;AIndex : Integer = 0);
var
i: Integer;
LNormalControl : TNormalPlay;
LObject : TJsonObject;
begin
for i := 0 to AJson.Size-1 do
begin
LObject := TJsonObject(AJson.Get(i));
LNormalControl := TNormalPlay.Create(FResManager);
LNormalControl.LoadFromJsonObject(LObject);
FNormalPlayManager.Add(LNormalControl.ControlName,LNormalControl);
end;
if AIndex < FNormalPlayManager.ItemCount then
FNormalPlayControler := FNormalPlayManager.Items[AIndex];
end;
procedure TImageConfig.SetNormalImg(AIndex: Integer);
var
LBmp : TBitmap;
begin
LBmp := FNormalPlayControler.Item[AIndex];
FNormalBitmap.Assign(LBmp);
end;
procedure TImageConfig.SwitchNormalControlerByName(AName: String;AFinishProc : TProc);
begin
if FNormalPlayManager.Contains(AName) then
FNormalPlayControler := FNormalPlayManager.Has(AName);
FFinishProc := AFinishProc;
if Assigned(FOnSwitchStatus) then
FOnSwitchStatus('switch');
end;
Procedure TImageConfig.SetNormalImg(inName: string);
begin
if FResManager <> nil then
begin
FResManager.LoadResource(FNormalBitmap, inName);
end;
end;
{ TImageConfig.TMouseMovePlay }
constructor TImageConfig.TMouseMovePlay.Create(AResManager : TEngineResManager);
begin
inherited Create(AResManager);
FBitmap := TBitmap.Create;
FAnimationCount := 0;
end;
destructor TImageConfig.TMouseMovePlay.Destroy;
begin
if Assigned(FBitmap) then
FBitmap.DisposeOf;
inherited;
end;
//procedure TImageConfig.TMouseMovePlay.SetFilePath(value: String);
//begin
// FFilePath := value;
// if FileExists(FFilePath) then
// begin
// FBitmap.LoadFromFile(FFilePath);
// FAnimationCount := 1;
// end;
//end;
{ TImageConfig.TBasePlay }
constructor TImageConfig.TBasePlay.Create(AResManager: TEngineResManager);
begin
FResManager := AResManager;
end;
procedure TImageConfig.TBasePlay.LoadFromJsonObject(AJson: TJsonObject);
begin
end;
end.
|
unit FindUnit.FileCache;
interface
uses
FindUnit.PasParser,
FindUnit.SearchStringCache,
Interf.SearchStringCache,
System.Classes,
System.Generics.Collections,
System.SyncObjs;
type
TUnitsController = class(TObject)
private
FFullMatchSearchCache: ISearchStringCache;
FMatchSearchCache: ISearchStringCache;
FUnits: TDictionary<string, TPasFile>;
FReady: Boolean;
FRc: TCriticalSection;
procedure SetUnits(const Value: TDictionary<string, TPasFile>);
public
constructor Create;
destructor Destroy; override;
function GetFindInfo(const SearchString: string): TStringList;
function GetFindInfoFullMatch(const SearchString: string): TStringList;
function GetPasFile(FilePath: string): TPasFile;
function ExtractPasFile(FilePath: string): TPasFile;
property Units: TDictionary<string, TPasFile> read FUnits write SetUnits;
property Ready: Boolean read FReady write FReady;
end;
implementation
uses
FindUnit.SearchString;
{ TUnitUpdateController }
constructor TUnitsController.Create;
begin
FFullMatchSearchCache := TSearchStringCache.Create;
FRc := TCriticalSection.Create;
inherited;
end;
destructor TUnitsController.Destroy;
begin
FRc.Free;
FUnits.Free;
inherited;
end;
function TUnitsController.ExtractPasFile(FilePath: string): TPasFile;
var
Item: TPair<string, TPasFile>;
begin
FRc.Acquire;
try
Item := FUnits.ExtractPair(FilePath);
Result := Item.Value;
finally
FRc.Release;
end;
end;
function TUnitsController.GetFindInfo(const SearchString: string): TStringList;
var
Search: TSearchString;
begin
Search := TSearchString.Create(FUnits);
try
Search.MatchCache := FMatchSearchCache;
Result := Search.GetMatch(SearchString);
finally
Search.Free;
end;
end;
function TUnitsController.GetFindInfoFullMatch(const SearchString: string): TStringList;
var
Search: TSearchString;
begin
Search := TSearchString.Create(FUnits);
try
Search.FullMatchCache := FFullMatchSearchCache;
Result := Search.GetFullMatch(SearchString);
finally
Search.Free;
end;
end;
function TUnitsController.GetPasFile(FilePath: string): TPasFile;
begin
FRc.Acquire;
try
FUnits.TryGetValue(FilePath, Result);
finally
FRc.Release;
end;
end;
procedure TUnitsController.SetUnits(const Value: TDictionary<string, TPasFile>);
begin
FUnits := Value;
FMatchSearchCache := TSearchStringCache.Create;
FFullMatchSearchCache := TSearchStringCache.Create;
end;
end.
|
{$INCLUDE ..\cDefines.inc}
unit cTypes;
{ }
{ Type base class v3.04 }
{ }
{ This unit is copyright © 1999-2002 by David Butler (david@e.co.za) }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cTypes.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Revision history: }
{ 1999/11/12 0.01 Split cTypes from cDataStruct and cHolder. }
{ Default implementations for Assign, IsEqual }
{ 2001/07/30 1.02 Removed interfaces in AType (each interface adds four }
{ bytes to the instance size). }
{ 2001/08/20 2.03 Merged cTypes and cDataStructs to allow object }
{ interface implementation in base classes. }
{ 2002/05/15 3.04 Split cTypes from cDataStructs. }
{ }
interface
uses
{ Delphi }
SysUtils,
{ Fundamentals }
cUtils;
{ }
{ Note on class naming convention: }
{ Classes with the A-prefix are abstract base classes. They define the }
{ interface for the type and must never be instanciated. }
{ }
{ }
{ AType }
{ Abstract base class for data structures. }
{ }
{ Provides an interface for commonly used data operations such as }
{ assigning, comparing and duplicating. }
{ }
{ Duplicate creates a new instance of the object (using CreateInstance) and }
{ then copies the content (using Assign). Implementations do not have to }
{ override Duplicate if both CreateInstance and Assign are implemented. }
{ Assign's default implementation calls the protected AssignTo. }
{ }
{ Clear sets an instance's content (value) to an empty/zero state. This }
{ state should be similar to the state of a new instance created using }
{ CreateInstance. }
{ }
{ IsEqual compares content of instances. After a call to Assign, an }
{ equivalent call to IsEqual should return True. }
{ }
{ Compare is the ranking function used by sorting and searching. }
{ }
type
AType = class
protected
procedure TypeError(const Msg: String; const Error: Exception = nil;
const ErrorClass: ExceptClass = nil); virtual;
procedure MethodNotImplementedError(const Method: String);
procedure Init; virtual;
procedure AssignTo(const Dest: TObject); virtual;
function GetAsString: String; virtual;
procedure SetAsString(const S: String); virtual;
public
constructor Create;
class function CreateInstance: AType; virtual;
function Duplicate: TObject; virtual;
procedure Assign(const Source: TObject); virtual;
procedure Clear; virtual;
function IsEmpty: Boolean; virtual;
function IsEqual(const V: TObject): Boolean; virtual;
function Compare(const V: TObject): TCompareResult; virtual;
function HashValue: LongWord; virtual;
property AsString: String read GetAsString write SetAsString;
end;
EType = class(Exception);
TypeClass = class of AType;
ATypeArray = Array of AType;
TypeClassArray = Array of TypeClass;
{ }
{ AType helper functions }
{ }
function TypeDuplicate(const V: TObject): TObject;
procedure TypeAssign(const A, B: TObject);
procedure TypeClear(const V: TObject);
function TypeIsEqual(const A, B: TObject): Boolean;
function TypeCompare(const A, B: TObject): TCompareResult;
function TypeHashValue(const A: TObject): LongWord;
function TypeGetAsString(const V: TObject): String;
procedure TypeSetAsString(const V: TObject; const S: String);
implementation
{ }
{ AType }
{ }
constructor AType.Create;
begin
inherited Create;
Init;
end;
procedure AType.Init;
begin
end;
procedure AType.TypeError(const Msg: String; const Error: Exception;
const ErrorClass: ExceptClass);
var S: String;
begin
S := Msg;
if Assigned(Error) then
S := S + ': ' + Error.Message;
if Assigned(ErrorClass) then
raise ErrorClass.Create(S)
else
raise EType.Create(S);
end;
procedure AType.MethodNotImplementedError(const Method: String);
begin
TypeError('Method ' + ClassName + '.' + Method + ' not implemented');
end;
class function AType.CreateInstance: AType;
begin
Result := AType(TypeClass(self).Create);
end;
procedure AType.Clear;
begin
MethodNotImplementedError('Clear');
end;
{$WARNINGS OFF}
function AType.IsEmpty: Boolean;
begin
MethodNotImplementedError('IsEmpty');
end;
{$WARNINGS ON}
function AType.Duplicate: TObject;
begin
try
Result := CreateInstance;
try
AType(Result).Assign(self);
except
FreeAndNil(Result);
raise;
end;
except
on E: Exception do TypeError('Duplicate failed', E);
end;
end;
procedure AType.Assign(const Source: TObject);
var R : Boolean;
begin
if Source is AType then
try
AType(Source).AssignTo(self);
R := True;
except
R := False;
end else
R := False;
if not R then
TypeError(ClassName + ' cannot assign from ' + ObjectClassName(Source));
end;
procedure AType.AssignTo(const Dest: TObject);
begin
TypeError(ClassName + ' cannot assign to ' + ObjectClassName(Dest));
end;
{$WARNINGS OFF}
function AType.IsEqual(const V: TObject): Boolean;
begin
TypeError(ClassName + ' cannot compare with ' + ObjectClassName(V));
end;
function AType.Compare(const V: TObject): TCompareResult;
begin
TypeError(ClassName + ' cannot compare with ' + ObjectClassName(V));
end;
function AType.HashValue: LongWord;
begin
try
Result := HashStr(GetAsString, MaxLongWord, True);
except
on E : Exception do TypeError('Hash error', E);
end;
end;
{$WARNINGS ON}
function AType.GetAsString: String;
begin
MethodNotImplementedError('GetAsString');
end;
procedure AType.SetAsString(const S: String);
begin
MethodNotImplementedError('SetAsString');
end;
{ }
{ AType helper functions }
{ }
function TypeGetAsString(const V: TObject): String;
begin
if V is AType then
Result := AType(V).GetAsString
else
raise EType.Create(ObjectClassName(V) + ' cannot convert to string');
end;
procedure TypeSetAsString(const V: TObject; const S: String);
begin
if V is AType then
AType(V).SetAsString(S)
else
raise EType.Create(ObjectClassName(V) + ' cannot set as string');
end;
function TypeDuplicate(const V: TObject): TObject;
begin
if V is AType then
Result := AType(V).Duplicate else
if not Assigned(V) then
Result := nil
else
raise EType.Create(ObjectClassName(V) + ' cannot duplicate');
end;
procedure TypeClear(const V: TObject);
begin
if V is AType then
AType(V).Clear else
if Assigned(V) then
raise EType.Create(ObjectClassName(V) + ' cannot clear');
end;
function TypeIsEqual(const A, B: TObject): Boolean;
begin
if A = B then
Result := True else
if not Assigned(A) or not Assigned(B) then
Result := False else
if A is AType then
Result := AType(A).IsEqual(B) else
if B is AType then
Result := AType(B).IsEqual(A)
else
raise EType.Create(ObjectClassName(A) + ' and ' + ObjectClassName(B) +
' cannot compare');
end;
function TypeCompare(const A, B: TObject): TCompareResult;
begin
if A = B then
Result := crEqual else
if A is AType then
Result := AType(A).Compare(B) else
if B is AType then
Result := ReverseCompareResult(AType(B).Compare(A))
else
Result := crUndefined;
end;
procedure TypeAssign(const A, B: TObject);
begin
if A = B then
exit else
if A is AType then
AType(A).Assign(B) else
if B is AType then
AType(B).AssignTo(A)
else
raise EType.Create(ObjectClassName(A) + ' cannot assign ' +
ObjectClassName(B));
end;
function TypeHashValue(const A: TObject): LongWord;
begin
if not Assigned(A) then
Result := 0 else
if A is AType then
Result := AType(A).HashValue
else
raise EType.Create(A.ClassName + ' cannot calculate hash value');
end;
end.
|
unit adot.XML.XPath;
interface
uses
Xml.XMLDoc,
Xml.XMLIntf,
Xml.xmldom,
Xml.omnixmldom,
//Xml.adomxmldom,
System.SysUtils,
System.Masks;
type
(*
Example:
XPath: TXPath;
Node: IDOMNode;
begin
XPath.Init; { creates new XML document with vendor supporting XPath }
XPath.Document.LoadFromXML(XMLString);
if XPath.Find('/Project/PropertyGroup[DCC_Define=''RELEASE;$(DCC_Define)'']', Node) then
if XPath.Find(Node, 'DCC_MapFile[.=''3'']') then
Exit;
end;
*)
TXPath = record
private
FDoc: IXMLDocument;
function FindSelect(Node: IDomNode): IDomNodeSelect;
public
procedure Init; overload;
procedure Init(Doc: TXMLDocument); overload;
procedure Init(Doc: IXMLDocument); overload;
class function Create: TXPath; overload; static;
class function Create(Doc: TXMLDocument): TXPath; overload; static;
class function Create(Doc: IXMLDocument): TXPath; overload; static;
function Find(Where: IDomNode; const XPath: string; out Res: IDomNode): boolean; overload;
function Find(Where: IDomNode; const XPath: string; out Res: IDOMNodeList): boolean; overload;
function Find(Where: IDomNode; const XPath: string): boolean; overload;
function Find(const XPath: string; out Res: IDomNode): boolean; overload;
function Find(const XPath: string; out Res: IDOMNodeList): boolean; overload;
function Find(const XPath: string): boolean; overload;
class operator Implicit(const a : IXMLDocument) : TXPath;
class operator Implicit(const a : TXMLDocument) : TXPath;
class operator Explicit(const a : IXMLDocument) : TXPath;
class operator Explicit(const a : TXMLDocument) : TXPath;
property Document: IXMLDocument read FDoc;
end;
implementation
{ TXPath }
class function TXPath.Create: TXPath;
begin
result.Init;
end;
class function TXPath.Create(Doc: IXMLDocument): TXPath;
begin
result.Init(Doc);
end;
class function TXPath.Create(Doc: TXMLDocument): TXPath;
begin
result.Init(Doc);
end;
procedure TXPath.Init;
var
Doc: TXMLDocument;
begin
Doc := TXMLDocument.Create(nil);
(*
Following XPath query works with OmniXML, but fails with ADOM (tested with Delphi 10.2):
XPath: /Project/PropertyGroup[DCC_MapFile='3'] - works
*)
Doc.DOMVendor := DOMVendors.Find(sOmniXmlVendor);
//Doc.DOMVendor := DOMVendors.Find(sAdom4XmlVendor);
Init(Doc);
end;
procedure TXPath.Init(Doc: IXMLDocument);
begin
FDoc := Doc;
end;
procedure TXPath.Init(Doc: TXMLDocument);
begin
FDoc := Doc;
end;
class operator TXPath.Explicit(const a: IXMLDocument): TXPath;
begin
result.Init(a);
end;
class operator TXPath.Explicit(const a: TXMLDocument): TXPath;
begin
result.Init(a);
end;
class operator TXPath.Implicit(const a: IXMLDocument): TXPath;
begin
result.Init(a);
end;
class operator TXPath.Implicit(const a: TXMLDocument): TXPath;
begin
result.Init(a);
end;
function TXPath.Find(Where: IDomNode; const XPath: string): boolean;
var
Res: IDomNode;
begin
result := Find(Where, XPath, Res);
end;
function TXPath.FindSelect(Node: IDomNode): IDomNodeSelect;
begin
if not Supports(Node, IDomNodeSelect, result) then
raise Exception.Create('IDomNodeSelect is not supported');
end;
function TXPath.Find(Where: IDomNode; const XPath: string; out Res: IDOMNodeList): boolean;
var
Select: IDomNodeSelect;
begin
Res := nil;
Result := False;
if not Assigned(Where) then
Exit;
Select := FindSelect(Where);
Res := Select.selectNodes(XPath);
Result := Assigned(Res);
end;
function TXPath.Find(Where: IDomNode; const XPath: string; out Res: IDomNode): boolean;
var
Select: IDomNodeSelect;
begin
Res := nil;
Result := False;
if not Assigned(Where) then
Exit;
Select := FindSelect(Where);
Res := Select.selectNode(XPath);
Result := Assigned(Res);
end;
function TXPath.Find(const XPath: string): boolean;
begin
result := Find(FDoc.DocumentElement.DOMNode, XPath);
end;
function TXPath.Find(const XPath: string; out Res: IDOMNodeList): boolean;
begin
result := Find(FDoc.DocumentElement.DOMNode, XPath, Res);
end;
function TXPath.Find(const XPath: string; out Res: IDomNode): boolean;
begin
result := Find(FDoc.DocumentElement.DOMNode, XPath, Res);
end;
end.
|
unit Fonetiza.Utils;
interface
type
TFonetizaUtils = class
public
function SomarCaracteres(const AValue: string): string;
function SubstituirConteudos(const AValue: string; const AConteudo: TArray<TArray<string>>): string;
function RemoverCaracteresDuplicados(const AValue: string): string;
function RemoverCaracteresEspeciais(const AValue: string): string;
function RemoverConteudos(const AValue: string; const AConteudo: TArray<string>): string;
function RemoverAcentuacoes(const AValue: string): string;
end;
implementation
{ TFonetizaUtils }
uses System.StrUtils, System.SysUtils, System.Generics.Collections;
function TFonetizaUtils.RemoverAcentuacoes(const AValue: string): string;
type
USAscii20127 = type AnsiString(20127);
begin
Result := string(USAscii20127(AValue));
end;
function TFonetizaUtils.RemoverCaracteresDuplicados(const AValue: string): string;
var
I: Integer;
LChar: Char;
begin
LChar := ' ';
for I := 1 to AValue.Length do
begin
if ((AValue[I] <> LChar) or (AValue[I] = ' ') or ((AValue[I] >= '0') and (AValue[I] <= '9')) or ((AValue[I] = 'S') and (AValue[I - 1] = 'S') and ((I > 1) and (AValue[I - 2] <> 'S')))) then
Result := Result + AValue[I];
LChar := AValue[I];
end;
Result := Result.Trim;
end;
function TFonetizaUtils.RemoverCaracteresEspeciais(const AValue: string): string;
var
LCaracter: Char;
begin
for LCaracter in AValue do
if CharInSet(LCaracter, ['A' .. 'Z', '0' .. '9']) or (LCaracter = ' ') or (LCaracter = '_') or (LCaracter = '&') then
Result := Result + LCaracter;
end;
function TFonetizaUtils.RemoverConteudos(const AValue: string; const AConteudo: TArray<string>): string;
var
LPalavra: string;
LPalavras: TArray<string>;
begin
LPalavras := AValue.Split([' ']);
for LPalavra in LPalavras do
begin
if MatchStr(LPalavra, AConteudo) then
Continue;
if not Result.Trim.IsEmpty then
Result := Result + ' ';
Result := Result + LPalavra;
end;
end;
function TFonetizaUtils.SomarCaracteres(const AValue: string): string;
var
LSoma, LValor: Integer;
LPalavras: TList<string>;
LPalavra: string;
I: Integer;
begin
I := 0;
LSoma := 0;
LPalavras := TList<string>.Create();
try
LPalavras.AddRange(AValue.Split([' ']));
while I < LPalavras.Count do
begin
LPalavra := LPalavras.Items[I];
if LPalavra.Equals('E') then
begin
LPalavras.Delete(I);
Dec(I);
end
else
begin
if LPalavra.Equals('MIL') then
begin
if LSoma = 0 then
LSoma := 1000
else
begin
LSoma := LSoma * 1000;
LPalavras.Delete(I);
Dec(I);
end;
end
else
begin
LValor := StrToIntDef(LPalavra, 0);
if LValor <> 0 then
begin
if LSoma <> 0 then
begin
LPalavras.Delete(I - 1);
Dec(I);
end;
LSoma := LSoma + LValor;
end
else
begin
if LSoma <> 0 then
LPalavras.Items[I - 1] := LSoma.ToString;
LSoma := 0;
end;
end;
end;
Inc(I);
end;
if LSoma <> 0 then
LPalavras.Items[Pred(LPalavras.Count)] := LSoma.ToString;
for LPalavra in LPalavras do
begin
if not Result.IsEmpty then
Result := Result + ' ';
Result := Result + LPalavra;
end;
finally
LPalavras.Free;
end;
end;
function TFonetizaUtils.SubstituirConteudos(const AValue: string; const AConteudo: TArray<TArray<string>>): string;
var
LPalavra, LResultado: string;
LConteudo, LPalavras: TArray<string>;
begin
LPalavras := AValue.Split([' ']);
for LPalavra in LPalavras do
begin
LResultado := LPalavra;
for LConteudo in AConteudo do
begin
if LConteudo[0].Equals(LPalavra) then
begin
LResultado := LConteudo[1];
Break;
end;
end;
if not Result.Trim.IsEmpty then
Result := Result + ' ';
Result := Result + LResultado;
end;
end;
end.
|
unit LuaTrayIcon;
interface
Uses Classes, Controls, Contnrs, LuaPas, LuaControl, Forms, ExtCtrls, TypInfo, LuaCanvas;
function CreateTrayIcon(L: Plua_State): Integer; cdecl;
type
TLuaTrayIcon = class(TTrayIcon)
LuaCtl: TLuaControl;
LuaCanvas: TLuaCanvas;
public
destructor Destroy; override;
end;
// ***********************************************
implementation
Uses LuaProperties, Lua, Dialogs, SysUtils, LuaForm, LCLClasses;
function TrayIconShow(L: Plua_State): Integer; cdecl;
var
lTrayIcon: TTrayIcon;
begin
CheckArg(L, 1);
lTrayIcon := TLuaTrayIcon(GetLuaObject(L, 1));
lTrayIcon.Show;
Result := 0;
end;
function TrayIconHide(L: Plua_State): Integer; cdecl;
var
lTrayIcon: TTrayIcon;
begin
CheckArg(L, 1);
lTrayIcon := TLuaTrayIcon(GetLuaObject(L, 1));
lTrayIcon.Hide;
Result := 0;
end;
function TrayIconShowBalloonHint(L: Plua_State): Integer; cdecl;
var
lTrayIcon: TTrayIcon;
begin
CheckArg(L, 1);
lTrayIcon := TLuaTrayIcon(GetLuaObject(L, 1));
lTrayIcon.ShowBalloonHint;
Result := 0;
end;
function TrayIconLoad(L:Plua_State): Integer; cdecl;
var
Frm: TTrayIcon;
Str: String;
Buf: Pointer;
Size: Integer;
Bm: TImage;
ST: TMemoryStream;
begin
Result := 0;
Frm := TTrayIcon(GetLuaObject(L, 1));
Str := lua_tostring(L,2);
if (fileExists(Str)) then begin
Frm.Icon.LoadFromFile(Str);
end;
end;
function TrayIconGetCanvas(L: Plua_State): Integer; cdecl;
var lC:TLuaTrayIcon;
begin
lC := TLuaTrayIcon(GetLuaObject(L, 1));
lC.LuaCanvas.ToTable(L, -1, lC.Canvas);
result := 1;
end;
destructor TLuaTrayIcon.Destroy;
begin
if (LuaCanvas<>nil) then LuaCanvas.Free;
inherited Destroy;
end;
procedure ToTable(L:Plua_State; Index:Integer; Sender:TObject);
begin
SetDefaultMethods(L, Index, Sender);
LuaSetTableFunction(L, Index, 'Show', TrayIconShow);
LuaSetTableFunction(L, Index, 'Hide', TrayIconHide);
LuaSetTableFunction(L, Index, 'ShowBalloonHint', TrayIconShowBalloonHint);
LuaSetTableFunction(L, Index, 'Icon', TrayIconLoad);
if (Sender.InheritsFrom(TCustomControl) or Sender.InheritsFrom(TGraphicControl) or Sender.InheritsFrom(TLCLComponent)) then
LuaSetTableFunction(L, Index, 'GetCanvas', TrayIconGetCanvas);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
function CreateTrayIcon(L: Plua_State): Integer; cdecl;
var
lTrayIcon:TLuaTrayIcon;
Parent:TComponent;
Name:String;
begin
GetControlParents(L,Parent,Name);
lTrayIcon := TLuaTrayIcon.Create(Parent);
lTrayIcon.LuaCtl := TLuaControl.Create(lTrayIcon,L,@Totable);
if (lua_gettop(L)>0) and (GetLuaObject(L, -1) = nil) then
SetPropertiesFromLuaTable(L, TObject(lTrayIcon),-1)
else
lTrayIcon.Name := Name;
if (lTrayIcon.InheritsFrom(TCustomControl) or lTrayIcon.InheritsFrom(TGraphicControl) or lTrayIcon.InheritsFrom(TLCLComponent)) then
lTrayIcon.LuaCanvas := TLuaCanvas.Create;
ToTable(L, -1, lTrayIcon);
Result := 1;
end;
end.
|
unit DescriptionsExcelDataModule;
interface
uses
System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer,
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, CustomExcelTable,
ProducerInterface, DescriptionsInterface;
{$WARN SYMBOL_PLATFORM OFF}
type
TDescriptionsExcelTable = class(TCustomExcelTable)
private
FClone: TFDMemTable;
FDescriptionsInt: IDescriptions;
FProducerInt: IProducer;
procedure Do_AfterOpen(Sender: TDataSet);
function GetComponentName: TField;
function GetComponentType: TField;
function GetDescription: TField;
function GetIDProducer: TField;
function GetProducer: TField;
protected
function CheckDescription: Boolean;
procedure CreateFieldDefs; override;
procedure SetFieldsInfo; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CheckRecord: Boolean; override;
property ComponentName: TField read GetComponentName;
property ComponentType: TField read GetComponentType;
property Description: TField read GetDescription;
property DescriptionsInt: IDescriptions read FDescriptionsInt
write FDescriptionsInt;
property IDProducer: TField read GetIDProducer;
property Producer: TField read GetProducer;
property ProducerInt: IProducer read FProducerInt write FProducerInt;
end;
TDescriptionsExcelDM = class(TExcelDM)
private
function GetExcelTable: TDescriptionsExcelTable;
{ Private declarations }
protected
function CreateExcelTable: TCustomExcelTable; override;
public
property ExcelTable: TDescriptionsExcelTable read GetExcelTable;
{ Public declarations }
end;
implementation
{ %CLASSGROUP 'Vcl.Controls.TControl' }
uses System.Math, System.Variants, FieldInfoUnit, ProgressInfo, ErrorType,
RecordCheck;
{$R *.dfm}
constructor TDescriptionsExcelTable.Create(AOwner: TComponent);
begin
inherited;
AfterOpen := Do_AfterOpen;
end;
destructor TDescriptionsExcelTable.Destroy;
begin
FreeAndNil(FClone);
inherited;
end;
function TDescriptionsExcelTable.CheckDescription: Boolean;
var
AProducerID: Integer;
ARecordCheck: TRecordCheck;
OK: Boolean;
rc: TRecordCheck;
begin
Assert(ProducerInt <> nil);
Assert(DescriptionsInt <> nil);
ARecordCheck.ErrorType := etError;
ARecordCheck.Row := ExcelRow.AsInteger;
// Ищем производителя
AProducerID := ProducerInt.GetProducerID(Producer.Value);
Result := AProducerID > 0;
// Если не нашли
if not Result then
begin
ARecordCheck.Col := Producer.Index + 1;
ARecordCheck.ErrorMessage := Producer.AsString;
ARecordCheck.Description :=
'Производитель с таким наименованием не найден в справочнике производителей';
ProcessErrors(ARecordCheck);
Exit;
end;
// Запоминаем код производителя
Edit;
IDProducer.Value := AProducerID;
Post;
// А может быть в Excel файле это уже встречалось ранее?
OK := FClone.LocateEx(ComponentName.FieldName, ComponentName.Value,
[lxoCaseInsensitive]);
Assert(OK); // Хотя бы один раз встречаться должно
Result := FClone.RecNo = RecNo;
// Если в Excel файле это встречается один раз
if not Result then
begin
// Если в Excel файле это встречается несколько раз
if FClone.FieldByName(Description.FieldName).AsString = Description.AsString
then
begin
ARecordCheck.Description :=
'Такое описание уже есть в загружаемых данных';
end
else
begin
ARecordCheck.ErrorType := etWarring;
ARecordCheck.Description :=
'Компонент с таким наименованием уже встречался в загружаемых данных';
end;
ARecordCheck.Col := ComponentName.Index + 1;
ARecordCheck.ErrorMessage := ComponentName.AsString;
ProcessErrors(ARecordCheck);
Exit;
end;
// Продолжаем проверку
rc := DescriptionsInt.Check(ComponentName.Value, Description.Value,
IDProducer.Value);
if rc.ErrorType = etNone then
Exit;
rc.Row := ExcelRow.AsInteger;
rc.Col := ComponentName.Index + 1;
ProcessErrors(rc);
end;
function TDescriptionsExcelTable.CheckRecord: Boolean;
begin
Result := inherited;
if Result then
begin
Result := CheckDescription;
end;
end;
procedure TDescriptionsExcelTable.CreateFieldDefs;
begin
inherited;
// при проверке будем заполнять код производителя
FieldDefs.Add('IDProducer', ftInteger);
end;
procedure TDescriptionsExcelTable.Do_AfterOpen(Sender: TDataSet);
begin
Assert(FClone = nil);
FClone := TFDMemTable.Create(Self);
FClone.CloneCursor(Self);
end;
function TDescriptionsExcelTable.GetComponentName: TField;
begin
Result := FieldByName('ComponentName');
end;
function TDescriptionsExcelTable.GetComponentType: TField;
begin
Result := FieldByName('ComponentType');
end;
function TDescriptionsExcelTable.GetDescription: TField;
begin
Result := FieldByName('Description');
end;
function TDescriptionsExcelTable.GetIDProducer: TField;
begin
Result := FieldByName('IDProducer');
end;
function TDescriptionsExcelTable.GetProducer: TField;
begin
Result := FieldByName('Producer');
end;
procedure TDescriptionsExcelTable.SetFieldsInfo;
begin
FieldsInfo.Add(TFieldInfo.Create('ComponentName', True,
'Наименование компонента не должно быть пустым'));
FieldsInfo.Add(TFieldInfo.Create('Producer', True,
'Наименование производителя не должно быть пустым'));
FieldsInfo.Add(TFieldInfo.Create('Description', True,
'Описание компонента не должно быть пустым', False, 3000));
FieldsInfo.Add(TFieldInfo.Create('ComponentType', True,
'Тип компонента не должен быть пустым'));
end;
function TDescriptionsExcelDM.CreateExcelTable: TCustomExcelTable;
begin
Result := TDescriptionsExcelTable.Create(Self);
end;
function TDescriptionsExcelDM.GetExcelTable: TDescriptionsExcelTable;
begin
Result := CustomExcelTable as TDescriptionsExcelTable;
end;
end.
|
unit HandlingQueryUnit;
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,
ProgressInfo, NotifyEvents, ProcRefUnit;
type
THandlingQuery = class(TQueryBase, IHandling)
private
FOnProgress: TNotifyEventsEx;
FPI: TProgressInfo;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CallOnProcessEvent;
procedure Process(AProcRef: TProcRef;
ANotifyEventRef: TNotifyEventRef); overload;
property OnProgress: TNotifyEventsEx read FOnProgress;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor THandlingQuery.Create(AOwner: TComponent);
begin
inherited;
FPI := TProgressInfo.Create;
FOnProgress := TNotifyEventsEx.Create(Self);
end;
destructor THandlingQuery.Destroy;
begin
FreeAndNil(FPI);
inherited;
end;
procedure THandlingQuery.CallOnProcessEvent;
begin
Assert(FDQuery.Active);
Assert(FPI <> nil);
FPI.TotalRecords := FDQuery.RecordCount;
FPI.ProcessRecords := FDQuery.RecNo;
OnProgress.CallEventHandlers(FPI)
end;
procedure THandlingQuery.Process(AProcRef: TProcRef;
ANotifyEventRef: TNotifyEventRef);
var
ne: TNotifyEventR;
begin
Assert(Assigned(AProcRef));
// Подписываем кого-то на событие
ne := TNotifyEventR.Create(OnProgress, ANotifyEventRef);
try
// Вызываем метод, обрабатывающий нашу таблицу
AProcRef(Self);
finally
// Отписываем кого-то от события
FreeAndNil(ne);
end;
end;
end.
|
unit MetroVisCom;
interface
uses
Classes, Contnrs, Graphics, IniFiles,
Planner, VisCom;
type
TVisLine = class; // forward
//============================================================================
// TVisStation is an abstract base class for visualization of stations.
// It has:
// - X, Y coordinates
// - more ???
//============================================================================
TVisStation =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer);
// primitive queries--------------------------------------------------------
function X: Integer;
function Y: Integer;
end;
//============================================================================
// TVisStationStop visualizes a normal stop on a line. It has:
// - a reference to the line on which it occurs.
//============================================================================
TVisStationStop =
class(TVisStation)
protected
FLine: TVisLine; // shared
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer);
// primitive queries
function CanSelect: Boolean; override;
// pre: true
// ret: true
function CanMark(AMark:String): Boolean; override;
// pre: true
// ret: AMark in {'mkStart', 'mkVia', 'mkFinish'}
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// commands ----------------------------------------------------------------
procedure SetLine(ALine: TVisLine);
// pre: true
// effect: FLine = ALine
procedure Draw(AMap: TMap); override;
// effect: draws a stop in a style that depends on the line
end;
//============================================================================
// TVisStationTransfer visualizes a transfer station.
//============================================================================
TVisStationTransfer =
class(TVisStation)
// primitive queries
function CanSelect: Boolean; override;
// pre: true
// ret: true
function CanMark(AMark:String): Boolean; override;
// pre: true
// ret: AMark in {mkStart, mkVia, mkFinish}
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws a transfer station on the map
end;
//============================================================================
// TVisStationDummy is not really a visualisation of a station. It only serves
// to force a line to pass through a particular position on the map.
//============================================================================
TVisStationDummy =
class(TVisStation)
// construction/destruction
constructor Create(AX, AY: Integer);
// primitive queries
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: false
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: skip
end;
//============================================================================
// TVisLine visualizes a metro line. It has:
// - a list of TVisStations
// - a color
//============================================================================
TVisLine =
class(TVisCom)
protected
FColor: TColor;
FList: TObjectList; // shared references to VisStations
public
// construction/destruction
constructor Create(ACode: String; AData: TObject; AColor: TColor);
// effect: inherited Create;
// post: AbstrStationList = [], GetColor = AColor
destructor Destroy; override;
// primitive queries
function CanSelect: Boolean; override;
// pre: true
// ret: true
function CanMark(AMark: String): Boolean; override;
// pre: true
// ret: (AMark = 'mkLine')
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function GetColor: TColor;
function StationCount: Integer;
// pre: true
// ret: |AbstrStationList|
function GetStation(I: Integer): TVisStation;
// pre: 0 <= I < StationCount
// ret: AbstrStationList[I]
// commands ----------------------------------------------------------------
procedure Add(AStation: TVisStation);
// pre: true
// post: AbstrStationlist = old AbstrStationList ++ [AStation]
// if AStation is TVisStationStop, then set its line to self
procedure Delete(AStation: TVisStation);
procedure Draw(AMap: TMap); override;
procedure DrawFromTo(AMap: TMap; AFrom, ATo: TVisStation);
// model variables ---------------------------------------------------------
// AbstrStationList: seq of TVisStation
end;
//============================================================================
// TVisLandmark
//============================================================================
TVisLandmark =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FBitmap: TBitmap;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap);
// primitive queries -------------------------------------------------------
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function X: Integer;
function Y: Integer;
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws the bitmap on AMap
end;
//============================================================================
// TVisLandmark
//============================================================================
TVisFlag =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FVisible: Boolean;
FBitmap: TBitmap;
public
// construction/destruction-------------------------------------------------
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap);
// primitive queries -------------------------------------------------------
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: false
function X: Integer;
function Y: Integer;
function Visible: Boolean;
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws the bitmap on AMap
procedure MoveTo(AX, AY: Integer);
procedure Show;
procedure Hide;
end;
//============================================================================
// TVisText visualizes a text on the map.
// It has at least the following features:
// - X, Y coordinates
// - the text to be visualized
// - a TextPos value indicating the relative positions of the (X,Y) point
// and the text
//============================================================================
TTextPos = (tpNorth, tpNorthEast, tpEast, tpSouthEast, tpSouth, tpSouthWest,
tpWest, tpNorthWest);
TVisText =
class(TVisCom)
protected
FX: Integer;
FY: Integer;
FText: String;
FTextPos: TTextPos;
public
// construction/destruction
constructor Create(ACode: String; AData: TObject; AX, AY: Integer;
AText: String; ATextPos: TTextPos);
// primitive queries -------------------------------------------------------
function Contains(AMap: TMap; AX, AY: Integer): Boolean; override;
// pre: true
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
function X: Integer;
function Y: Integer;
function Text: String;
function TextPos: TTextPos;
// commands ----------------------------------------------------------------
procedure Draw(AMap: TMap); override;
// effect: draws Text on AMap;
// position of (X,Y) w.r.t. Text is determined by TextPos
end;
//============================================================================
// TMetroMap is a specialization of TMap.
// It serves to visualize a metro network.
//
//============================================================================
TMetroMap =
class(TMap)
protected
FStartFlag: TVisFlag;
FStopFlag: TVisFlag;
procedure SetStartFlag(AFlag: TVisFlag); virtual;
procedure SetStopFlag(AFlag: TVisFlag); virtual;
public
// construction/destruction
// primitive queries -------------------------------------------------------
// derived queries ---------------------------------------------------------
function GetStation(ACode: String): TVisStation;
// pre: HasStation(ACode: String)
// ret: S such that (S.GetCode = ACode) and (S is TVisStation)
function GetLine(ACode: String): TVisLine;
// pre: HasLine(ACode: String)
// ret: S such that (S.GetCode = ACode) and (S is TVisLine)
function StationContaining(AX, AY: Integer): String;
// pre: true
// ret: code of TVisstation containing (AX, AY), '' otherwise
// preconditions -----------------------------------------------------------
function HasStation(ACode: String): Boolean;
// pre: true
// ret: (exists I: 0 <= I < VisComCount:
// (GetVisCom(I).GetCode = ACode) and (GetVisCom(I) is TVisStation) )
function HasLine(ACode: String): Boolean;
// pre: true
// ret: (exists I: 0 <= I < VisComCount:
// (GetVisCom(I).GetCode = ACode) and (GetVisCom(I) is TVisLine) )
// commands ----------------------------------------------------------------
procedure HideAll; override;
procedure ShowAll; override;
procedure MarkStartStation(AStationCode: String);
procedure MarkStopStation(AStationCode: String);
procedure ClearFlags;
procedure ClearSelectedLines;
procedure ShowFlags;
procedure ShowStations;
procedure ShowLines;
procedure ShowSelectedLines;
procedure ShowLandmarks;
procedure ShowTexts;
procedure ShowRoute(ARoute: TRouteR);
property StartFlag: TVisFlag read FStartFlag write SetStartFlag;
property StopFlag: TVisFlag read FStopFlag write SetStopFlag;
// public invariants -------------------------------------------------------
end;
implementation //===============================================================
uses Math, SysUtils;
{ TVisStation }
constructor TVisStation.Create(ACode: String; AData: TObject;
AX, AY: Integer);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
end;
function TVisStation.X: Integer;
begin
Result := FX;
end;
function TVisStation.Y: Integer;
begin
Result := FY;
end;
{ TVisStationStop }
function TVisStationStop.CanMark(AMark: String): Boolean;
begin
Result := (AMark = 'mkStart') or (AMark = 'mkVia') or (AMark = 'mkFinish');
end;
function TVisStationStop.CanSelect: Boolean;
begin
Result := true;
end;
function TVisStationStop.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
// Hardcoded and sloppy <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := (X - 6 <= AX) and (AX <= X + 6) and (Y - 6 <= AY) and (AY <= Y + 6);
end;
constructor TVisStationStop.Create(ACode: String; AData: TObject;
AX, AY: Integer);
begin
inherited Create(ACode, AData, AX, AY);
FLine := nil;
end;
procedure TVisStationStop.Draw(AMap: TMap);
var
VR: Integer;
begin
Assert(FLine <> nil,
Format('TVisStationStop.Draw.pre: station code = %s', [FCode]));
VR := 4; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< should not be hardcoded
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Width := 0;
Brush.Color := FLine.GetColor;
Ellipse(X - VR, Y - VR, X + VR, Y + VR);
end;
end;
procedure TVisStationStop.SetLine(ALine: TVisLine);
begin
Fline := ALine;
end;
{ TVisStationTransfer }
function TVisStationTransfer.CanMark(AMark: String): Boolean;
begin
Result := (AMark = 'mkStart') or (AMark = 'mkVia') or (AMark = 'mkFinish');
end;
function TVisStationTransfer.CanSelect: Boolean;
begin
Result := true;
end;
function TVisStationTransfer.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
// Hardcoded and sloppy <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := (X - 6 <= AX) and (AX <= X + 6) and (Y - 6 <= AY) and (AY <= Y + 6);
end;
procedure TVisStationTransfer.Draw(AMap: TMap);
var
VR: Integer;
begin
VR := 6; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< should not be hardcoded
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Width := 1;
Pen.Color := clBlack;
Brush.Color := clWhite;
Ellipse(X - VR, Y - VR, X + VR, Y + VR);
end;
end;
{ TVisStationDummy }
function TVisStationDummy.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
Result := false;
end;
constructor TVisStationDummy.Create(AX, AY: Integer);
begin
inherited Create('', nil, AX, AY);
end;
procedure TVisStationDummy.Draw(AMap: TMap);
begin
{skip}
end;
{ TVisLine }
procedure TVisLine.Add(AStation: TVisStation);
begin
FList.Add(AStation);
if AStation is TVisStationStop
then (AStation as TVisStationStop).SetLine(Self);
end;
function TVisLine.CanMark(AMark: String): Boolean;
begin
Result := AMark = 'mkLine';
end;
function TVisLine.CanSelect: Boolean;
begin
Result := true;
end;
function TVisLine.Contains(AMap: TMap; AX, AY: Integer): Boolean;
function OnSegment(AX,AY: Integer; AStation1,AStation2: TVisStation): Boolean;
var
X1, Y1, X2, Y2: Integer;
VA, VB, VC: Integer;
D: Real;
begin
X1 := AStation1.X;
Y1 := AStation1.Y;
X2 := AStation2.X;
Y2 := AStation2.Y;
if (Min(X1,X2) <= AX) and (AX <= Max(X1,X2)) and
(Min(Y1,Y2) <= AY) and (AY <= Max(Y1,Y2))
then
begin
// compute distance D from (AX,AY) to straight line through the two
// stations:
VA := (Y2 - Y1);
VB := (X1 - X2);
VC := Y1 * (X2 - X1) - X1 * (Y2 - Y1);
D := (VA*AX + VB*AY +VC)/ Sqrt(Sqr(VA)+Sqr(VB));
Result := (-1 <= D) and (D <= 1); // "close enough"
end
else
Result := false;
end;
var
I: Integer;
begin
Result := false;
if StationCount > 1 then
for I := 1 to StationCount - 1 do
if OnSegment(AX, AY, GetStation(I-1), GetStation(I))
then
begin
Result := true;
Exit
end;
end;
constructor TVisLine.Create(ACode: String; AData: TObject; AColor: TColor);
begin
inherited Create(ACode, AData);
FColor := AColor;
FList := TObjectlist.Create(false);
end;
procedure TVisLine.Delete(AStation: TVisStation);
begin
FList.Remove(AStation);
end;
destructor TVisLine.Destroy;
begin
FList.Free;
inherited;
end;
procedure TVisLine.Draw(AMap: TMap);
var
I: Integer;
begin
if StationCount > 0 then
begin
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Color := GetColor;
Pen.Width := 5;
MoveTo(GetStation(0).X, GetStation(0).Y);
for I := 1 to StationCount - 1 do
LineTo(GetStation(I).X, GetStation(I).Y);
end;
end;
end;
procedure TVisLine.DrawFromTo(AMap: TMap; AFrom, ATo: TVisStation);
var
I, L, H, M: Integer;
begin
L := FList.IndexOf(AFrom);
H := FList.IndexOf(ATo);
if H < L then
begin {swap}
M := L; L := H; H := M;
end;
with AMap.Picture.Bitmap.Canvas do
begin
Pen.Color := GetColor;
Pen.Width := 5;
MoveTo(GetStation(L).X, GetStation(L).Y);
for I := L + 1 to H do
LineTo(GetStation(I).X, GetStation(I).Y);
end;
end;
function TVisLine.GetColor: TColor;
begin
Result := FColor;
end;
function TVisLine.GetStation(I: Integer): TVisStation;
begin
Assert((0 <= I) and (I < StationCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := FList.Items[I] as TVisStation;
end;
function TVisLine.StationCount: Integer;
begin
Result := FList.Count;
end;
{ TVisLandmark }
function TVisLandmark.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
Result := (X <= AX) and (AX <= X + FBitmap.Width) and
(Y <= AY) and (AY <= Y + FBitmap.Height);
end;
constructor TVisLandmark.Create(ACode: String; AData: TObject; AX,
AY: Integer; ABitmap: TBitmap);
begin
inherited Create(ACode, Adata);
FX := AX;
FY := AY;
FBitmap := ABitmap;
end;
procedure TVisLandmark.Draw(AMap: TMap);
begin
AMap.Picture.Bitmap.Canvas.Draw(FX, FY, FBitmap);
end;
function TVisLandmark.X: Integer;
begin
Result := FX;
end;
function TVisLandmark.Y: Integer;
begin
Result := FY;
end;
{ TVisText }
function TVisText.Contains(AMap: TMap; AX, AY: Integer): Boolean;
var
H, W: Integer;
VLeft, VTop: Integer;
begin
with AMap.Picture.Bitmap.Canvas do
begin
H := TextHeight(Text);
W := TextWidth(Text);
case TextPos of
tpNorth:
begin
VLeft := X - W div 2;
VTop := Y + 3;
end;
tpNorthEast:
begin
VLeft := X - W - 3;
VTop := Y + 3;
end;
tpEast:
begin
VLeft := X - W - 3;
VTop := Y - H div 2;
end;
tpSouthEast:
begin
VLeft := X - W - 3;
VTop := Y - H - 3;
end;
tpSouth:
begin
VLeft := X - W div 2;
VTop := Y - H - 3;
end;
tpSouthWest:
begin
VLeft := X + 3;
VTop := Y - H - 3;
end;
tpWest:
begin
VLeft := X + 3;
VTop := Y - H div 2;
end;
tpNorthWest:
begin
VLeft := X + 3;
VTop := Y + 3;
end;
end{case};
end{with};
Result := (VLeft <= AX) and (AX <= VLeft + W) and
(VTop <= AY) and (AY <= VTop + H);
end;
constructor TVisText.Create(ACode: String; AData: TObject; AX, AY: Integer;
AText: String; ATextPos: TTextPos);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
FText := AText;
FTextPos := ATextPos;
end;
procedure TVisText.Draw(AMap: TMap);
var
H, W: Integer;
VLeft, VTop: Integer;
begin
with AMap.Picture.Bitmap.Canvas do
begin
H := TextHeight(Text);
W := TextWidth(Text);
case TextPos of
tpNorth:
begin
VLeft := X - W div 2;
VTop := Y + 3;
end;
tpNorthEast:
begin
VLeft := X - W - 3;
VTop := Y + 3;
end;
tpEast:
begin
VLeft := X - W - 3;
VTop := Y - H div 2;
end;
tpSouthEast:
begin
VLeft := X - W - 3;
VTop := Y - H - 3;
end;
tpSouth:
begin
VLeft := X - W div 2;
VTop := Y - H - 3;
end;
tpSouthWest:
begin
VLeft := X + 3;
VTop := Y - H - 3;
end;
tpWest:
begin
VLeft := X + 3;
VTop := Y - H div 2;
end;
tpNorthWest:
begin
VLeft := X + 3;
VTop := Y + 3;
end;
end{case};
Brush.Color := clYellow;
TextOut(VLeft, VTop, Text);
end{with}
end;
function TVisText.Text: String;
begin
Result := FText;
end;
function TVisText.TextPos: TTextPos;
begin
Result := FTextPos;
end;
function TVisText.X: Integer;
begin
Result := FX;
end;
function TVisText.Y: Integer;
begin
Result := FY;
end;
{ TMetroMap }
procedure TMetroMap.ClearFlags;
begin
FStartFlag.Hide;
FStopFlag.Hide;
end;
procedure TMetroMap.ClearSelectedLines;
var
I: Integer;
VVisCom: TVisCom;
begin
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if VVisCom is TVisLine
then VVisCom.UnSelect;
end;
end;
function TMetroMap.GetLine(ACode: String): TVisLine;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLine) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisLine;
end;
function TMetroMap.GetStation(ACode: String): TVisStation;
var
I: Integer;
begin
Result := nil;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisStation) and (GetVisCom(I).GetCode = ACode)
then Result := GetVisCom(I) as TVisStation;
end;
function TMetroMap.HasLine(ACode: String): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisLine) and (GetVisCom(I).GetCode = ACode)
then Result := true;
end;
function TMetroMap.HasStation(ACode: String): Boolean;
var
I: Integer;
begin
Result := false;
for I := 0 to VisComCount - 1 do
if (GetVisCom(I) is TVisStation) and (GetVisCom(I).GetCode = ACode)
then Result := true;
end;
procedure TMetroMap.HideAll;
begin
if BackgroundShown
then Picture.Assign(FBackgroundPicture)
else Picture.Assign(FBlankPicture);
end;
procedure TMetroMap.MarkStartStation(AStationCode: String);
var
VStation: TVisStation;
begin
VStation := GetStation(AStationCode);
if VStation <> nil then
begin
FStartFlag.MoveTo(VStation.X, VStation.Y);
FStartFlag.Show;
end;
end;
procedure TMetroMap.MarkStopStation(AStationCode: String);
var
VStation: TVisStation;
begin
VStation := GetStation(AStationCode);
if VStation <> nil then
begin
FStopFlag.MoveTo(VStation.X, VStation.Y);
FStopFlag.Show;
end;
end;
procedure TMetroMap.SetStartFlag(AFlag: TVisFlag);
begin
FStartFlag := AFlag;
end;
procedure TMetroMap.SetStopFlag(AFlag: TVisFlag);
begin
FStopFlag := AFlag;
end;
procedure TMetroMap.ShowAll;
begin
// N.B.: order is important
ShowLines;
ShowStations;
ShowLandmarks;
ShowFlags;
end;
procedure TMetroMap.ShowFlags;
begin
if FStartFlag.Visible then FStartFlag.Draw(Self);
if FStopFlag.Visible then FStopFlag.Draw(Self);
end;
procedure TMetroMap.ShowLandmarks;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisLandmark
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowLines;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisLine
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowRoute(ARoute: TRouteR);
var
I: Integer;
VVisLine: TVisLine;
VFromStation, VToStation: TVisStation;
begin
with ARoute do
for I := 0 to SegmentCount - 1 do
with GetSegment(I) do
begin
VVisLine := GetLine(Line.GetCode);
VFromStation := GetStation(FromStation.GetCode);
VToStation := GetStation(ToStation.GetCode);
VVisLine.DrawFromTo(Self, VFromStation, VToStation);
end;
end;
procedure TMetroMap.ShowSelectedLines;
var
I: Integer;
VVisCom: TVisCom;
begin
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisLine) and (VVisCom.IsSelected)
then VVisCom.Draw(Self);
end;
end;
procedure TMetroMap.ShowStations;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisStation
then GetVisCom(I).Draw(Self);
end;
procedure TMetroMap.ShowTexts;
var
I: Integer;
begin
for I := 0 to VisComCount - 1 do
if GetVisCom(I) is TVisText
then GetVisCom(I).Draw(Self);
end;
function TMetroMap.StationContaining(AX, AY: Integer): String;
var
I: Integer;
VVisCom: TVisCom;
begin
Result := '';
for I := 0 to VisComCount - 1 do
begin
VVisCom := GetVisCom(I);
if (VVisCom is TVisStation) and VVisCom.CanSelect and
VVisCom.Contains(Self, AX, AY)
then
Result := VVisCom.GetCode;
end{for};
end;
{ TVisFlag }
function TVisFlag.Contains(AMap: TMap; AX, AY: Integer): Boolean;
begin
Result := false;
end;
constructor TVisFlag.Create(ACode: String; AData: TObject; AX, AY: Integer;
ABitmap: TBitmap);
begin
inherited Create(ACode, AData);
FX := AX;
FY := AY;
FVisible := false;
FBitmap := ABitmap;
end;
procedure TVisFlag.Draw(AMap: TMap);
begin
AMap.Picture.Bitmap.Canvas.Draw(FX - 24, FY - 32, FBitmap);
end;
procedure TVisFlag.Hide;
begin
FVisible := false;
end;
procedure TVisFlag.MoveTo(AX, AY: Integer);
begin
FX := AX;
FY := AY;
end;
procedure TVisFlag.Show;
begin
FVisible := true;
end;
function TVisFlag.Visible: Boolean;
begin
Result := FVisible;
end;
function TVisFlag.X: Integer;
begin
Result := FX;
end;
function TVisFlag.Y: Integer;
begin
Result := FY;
end;
end.
|
(**
This module contains often used code for use through out this application.
@Version 1.0
@Author David Hoyle
@Date 05 Jan 2018
**)
unit ITHelper.TestingHelperUtils;
interface
{$INCLUDE 'CompilerDefinitions.inc'}
Uses
SysUtils,
{$IFNDEF CONSOLE_TESTRUNNER} ToolsAPI, {$ENDIF}
Windows,
Graphics,
Classes,
Contnrs,
Menus;
Type
(** An enumerate to define the type of information to be returned from
GetProcInfo. **)
TProcInfoType = (pitEXE, pitParam, pitDir);
(** An enumerate to defien which message should be cleared from the IDE
message window. **)
TClearMessage = (cmCompiler, cmSearch, cmTool, cmGroup);
(** A set of the above message types. **)
TClearMessages = Set of TClearMessage;
(** A record to hold version information. **)
TVersionInfo = Record
iMajor : Integer;
iMinor : Integer;
iBugfix : Integer;
iBuild : Integer;
End;
{$IFNDEF CONSOLE_TESTRUNNER}
Function ProjectGroup: IOTAProjectGroup;
Function ActiveProject : IOTAProject;
Function ProjectModule(Const Project : IOTAProject) : IOTAModule;
Function ActiveSourceEditor : IOTASourceEditor;
Function SourceEditor(Const Module : IOTAMOdule) : IOTASourceEditor;
Function EditorAsString(Const SourceEditor : IOTASourceEditor) : String;
Procedure OutputText(Const Writer : IOTAEditWriter; Const iIndent : Integer; Const strText : String);
Function GetProjectName(Const Project : IOTAProject) : String;
Procedure OutputMessage(Const strText : String); Overload;
Procedure OutputMessage(Const strFileName, strText, strPrefix : String; Const iLine,
iCol : Integer); Overload;
Function ExpandMacro(Const strPath : String; Const strFileName : String) : String;
Procedure OutputMessage(Const strText : String; Const strGroupName : String); Overload;
Procedure ShowMessages(Const strGroupName : String = '');
Function AddImageToIDE(Const strImageName : String; Const iMaskColour : TColor) : Integer;
Function CreateMenuItem(Const strName, strCaption, strParentMenu : String;
Const ClickProc, UpdateProc : TNotifyEvent; Const boolBefore, boolChildMenu : Boolean;
Const strShortCut : String; Const iMaskColour : TColor = clLime) : TMenuItem;
Procedure PatchActionShortcuts(Sender : TObject);
Procedure ClearMessages(Const Msg : TClearMessages);
Procedure ShowHelperMessages(Const boolITHGroup : Boolean);
{$ENDIF}
Procedure BuildNumber(Var VersionInfo : TVersionInfo);
Function GetProcInfo(Const strText : String; Const ProcInfoType : TProcInfoType) : String;
Function ResolvePath(Const strFName, strPath : String) : String;
Function Actions : TObjectList;
Function ITHHTMLHelpFile(Const strContext : String = '') : String;
//{$IFNDEF D2005}
//Const
// (** HTML Constant to display a Topic **)
// HH_DISPLAY_TOPIC = $0000;
// (** HTML Constant to display a the Table of Contents **)
// HH_DISPLAY_TOC = $0001;
// (** HTML Constant to close all HTML files **)
// HH_CLOSE_ALL = $0012;
//
//Function HtmlHelp(hwndCaller: HWND; pszFile: PChar; uCommand: UINT;
// dwData: DWORD): HWND; StdCall; external 'HHCTRL.OCX' Name 'HtmlHelpA';
//{$ENDIF}
//
Implementation
Uses
Forms,
Controls,
ActnList,
{$IFNDEF CONSOLE_TESTRUNNER}
ITHelper.CustomMessages,
{$ENDIF}
ComCtrls,
ITHelper.ResourceStrings;
Var
(** A private variable to is used to hold action reference so that they
can be removed from the IDE. **)
FOTAActions : TObjectList;
Const
(** A constant string for the build message window page. **)
strBuild = 'Build';
{$IFNDEF CONSOLE_TESTRUNNER}
Function FindMenuItem(Const strParentMenu: String): TMenuItem; Forward;
{$ENDIF}
(**
This function returns a reference to the Experts actions.
@precon None.
@postcon Returns a reference to the Experts actions.
@return a TObjectList
**)
Function Actions : TObjectList;
Begin
Result := FOTAActions;
End;
{$IFNDEF CONSOLE_TESTRUNNER}
(**
This method returns the active project in the IDE else returns Nil if there is
no active project.
@precon None.
@postcon Returns the active project in the IDE else returns Nil if there is
no active project.
@return an IOTAProject
**)
Function ActiveProject : IOTAProject;
var
G : IOTAProjectGroup;
Begin
Result := Nil;
G := ProjectGroup;
If G <> Nil Then
Result := G.ActiveProject;
End;
(**
This method returns the Source Editor interface for the active source editor
else returns nil.
@precon None.
@postcon Returns the Source Editor interface for the active source editor
else returns nil.
@return an IOTASourceEditor
**)
Function ActiveSourceEditor : IOTASourceEditor;
Var
CM : IOTAModule;
Begin
Result := Nil;
If BorlandIDEServices = Nil Then
Exit;
CM := (BorlandIDEServices as IOTAModuleServices).CurrentModule;
Result := SourceEditor(CM);
End;
(**
This method adds an image from the projects resource (bitmap) to the IDEs image list. The image name in
the resource must end in Image as this is appended to the given name. An integer for the position of
that image in the IDEs image list is returned.
@precon None.
@postcon The named image is loaded from the projects resource and put into the IDEs image list and its
index returned.
@Note Different technicals are used for the different IDE version.
@Note The way described in Delphi 2010s ToppsAPI file causes an exception and there is not used.
@param strImageName as a String as a constant
@param iMaskColour as a TColor as a constant
@return an Integer
**)
Function AddImageToIDE(Const strImageName : String; Const iMaskColour : TColor) : Integer;
Const
strImageResNameSuffix = 'Image';
Var
NTAS : INTAServices;
ilImages : TImageList;
BM : TBitMap;
begin
Result := -1;
If FindResource(hInstance, PChar(strImageName + strImageResNameSuffix), RT_BITMAP) > 0 Then
Begin
NTAS := (BorlandIDEServices As INTAServices);
// Create image in IDE image list
ilImages := TImageList.Create(Nil);
Try
BM := TBitMap.Create;
Try
BM.LoadFromResourceName(hInstance, strImageName + strImageResNameSuffix);
{$IFDEF D2005}
ilImages.AddMasked(BM, iMaskColour);
// EXCEPTION: Operation not allowed on sorted list
// Result := NTAS.AddImages(ilImages, 'OTATemplateImages');
Result := NTAS.AddImages(ilImages);
{$ELSE}
Result := NTAS.AddMasked(BM, iMaskColour);
{$ENDIF}
Finally
BM.Free;
End;
Finally
ilImages.Free;
End;
End;
end;
{$ENDIF}
(**
This method extracts the Major, Minor, Bugfix and Build version numbers from
this modules resource information.
@precon None.
@postcon Returns the version information in the var parameter.
@param VersionInfo as a TVersionInfo as a reference
**)
Procedure BuildNumber(Var VersionInfo: TVersionInfo);
Const
iWordMask = $FFFF;
iWordShift = 16;
Var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
strBuffer: Array [0 .. MAX_PATH] Of Char;
Begin
GetModuleFileName(hInstance, strBuffer, MAX_PATH);
VerInfoSize := GetFileVersionInfoSize(strBuffer, Dummy);
If VerInfoSize <> 0 Then
Begin
GetMem(VerInfo, VerInfoSize);
Try
GetFileVersionInfo(strBuffer, 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
VersionInfo.iMajor := VerValue^.dwFileVersionMS Shr iWordShift;
VersionInfo.iMinor := VerValue^.dwFileVersionMS And iWordMask;
VersionInfo.iBugfix := VerValue^.dwFileVersionLS Shr iWordShift;
VersionInfo.iBuild := VerValue^.dwFileVersionLS And iWordMask;
Finally
FreeMem(VerInfo, VerInfoSize);
End;
End;
End;
{$IFNDEF CONSOLE_TESTRUNNER}
(**
This method clears the IDE message window of the given message types.
@precon None.
@postcon Clears the IDE message window of the given message types.
@param Msg as a TClearMessages as a constant
**)
Procedure ClearMessages(Const Msg : TClearMessages);
Var
MS : IOTAMessageServices;
Group : IOTAMessageGroup;
Begin
If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then
Begin
If cmCompiler In Msg Then
MS.ClearCompilerMessages;
If cmSearch In Msg Then
MS.ClearSearchMessages;
If cmTool In Msg Then
MS.ClearToolMessages;
If cmGroup In Msg Then
Begin
Group := MS.GetGroup(strITHelperGroup);
If Assigned(Group) Then
Begin
MS.ClearMessageGroup(Group);
MS.ClearToolMessages(Group);
End;
End;
End;
End;
(**
This method does the following: Adds an image to the IDE if found in the project resource, creates a
menu item, creates an action in the IDE for the menu if one is required, associated the action with the
menu and adds the menu to the IDE as a sibiling or underneath the parent item as required.
@precon None.
@postcon Returns a reference to the menu.
@note You should always keep a reference to the Main menu item you create so you can remove you
menus from the IDE.
@param strName as a String as a constant
@param strCaption as a String as a constant
@param strParentMenu as a String as a constant
@param ClickProc as a TNotifyEvent as a constant
@param UpdateProc as a TNotifyEvent as a constant
@param boolBefore as a Boolean as a constant
@param boolChildMenu as a Boolean as a constant
@param strShortCut as a String as a constant
@param iMaskColour as a TColor as a constant
@return a TMenuItem
**)
Function CreateMenuItem(Const strName, strCaption, strParentMenu : String;
Const ClickProc, UpdateProc : TNotifyEvent; Const boolBefore, boolChildMenu : Boolean;
Const strShortCut : String; Const iMaskColour : TColor = clLime) : TMenuItem;
Const
strActionNameSuffix = 'Action';
strITHelperMenuCategory = 'ITHelperMenus';
strMenuNameSuffix = 'Menu';
Var
NTAS : INTAServices;
CA : TAction;
//{$IFNDEF D2005}
miMenuItem : TMenuItem;
//{$ENDIF}
iImageIndex : Integer;
begin
NTAS := (BorlandIDEServices As INTAServices);
// Add Image to IDE
iImageIndex := AddImageToIDE(strName, iMaskColour);
// Create the IDE action (cached for removal later)
CA := Nil;
Result := TMenuItem.Create(NTAS.MainMenu);
If Assigned(ClickProc) Then
Begin
CA := TAction.Create(NTAS.ActionList);
CA.ActionList := NTAS.ActionList;
CA.Name := strName + strActionNameSuffix;
CA.Caption := strCaption;
CA.OnExecute := ClickProc;
CA.OnUpdate := UpdateProc;
CA.ShortCut := TextToShortCut(strShortCut);
CA.Tag := TextToShortCut(strShortCut);
CA.ImageIndex := iImageIndex;
CA.Category := strITHelperMenuCategory;
FOTAActions.Add(CA);
End Else
If strCaption <> '' Then
Begin
Result.Caption := strCaption;
Result.ShortCut := TextToShortCut(strShortCut);
Result.ImageIndex := iImageIndex;
End Else
Result.Caption := '-';
// Create menu (removed through parent menu)
Result.Action := CA;
Result.Name := strName + strMenuNameSuffix;
// Create Action and Menu.
//{$IFDEF D2005}
// This is the new way to do it BUT doesn't create icons for the menu.
//NTAS.AddActionMenu(strParentMenu + 'Menu', CA, Result, boolBefore, boolChildMenu);
//{$ELSE}
miMenuItem := FindMenuItem(strParentMenu + strMenuNameSuffix);
If miMenuItem <> Nil Then
Begin
If Not boolChildMenu Then
Begin
If boolBefore Then
miMenuItem.Parent.Insert(miMenuItem.MenuIndex, Result)
Else
miMenuItem.Parent.Insert(miMenuItem.MenuIndex + 1, Result);
End Else
miMenuItem.Add(Result);
End;
//{$ENDIF}
end;
(**
This method returns the editor code as a string from the given source editor reference.
@precon SourceEditor must be a valid instance.
@postcon returns the editor code as a string from the given source editor reference.
@param SourceEditor as an IOTASourceEditor as a constant
@return a String
**)
Function EditorAsString(Const SourceEditor : IOTASourceEditor) : String;
Const
iBufferCapacity = 8 * 8 * 8;
Var
Reader : IOTAEditReader;
iRead : Integer;
iPosition : Integer;
strBuffer : AnsiString;
strTmp : AnsiString;
Begin
Result := '';
Reader := SourceEditor.CreateReader;
Try
iPosition := 0;
Repeat
SetLength(strBuffer, iBufferCapacity);
iRead := Reader.GetText(iPosition, PAnsiChar(strBuffer), iBufferCapacity);
SetLength(strBuffer, iRead);
Inc(iPosition, iRead);
strTmp := strTmp + strBuffer;
Until iRead < iBufferCapacity;
Result := UTF8ToUnicodeString(strTmp);
Finally
Reader := Nil;
End;
End;
(**
This function returns the passed path / filename with any of the below macros expanded. {$PROJPATH$}
The project path including the trailing backslash {$PROJDRIVE$} The project drive including the colon.
@precon Project must be a valid instance.
@postcon Returns the passed path / filename with any macros expanded.
@param strPath as a String as a constant
@param strFileName as a String as a constant
@return a String
**)
Function ExpandMacro(Const strPath : String; Const strFileName : String) : String;
Const
strPROJPATHMacroName = '{$PROJPATH$}';
strPROJDRIVEMacroName = '{$PROJDRIVE$}';
Begin
Result := strPath;
Result := StringReplace(Result, strPROJPATHMacroName, ExtractFilePath(strFileName),
[rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, strPROJDRIVEMacroName, ExtractFileDrive(strFileName),
[rfReplaceAll, rfIgnoreCase]);
End;
(**
This method finds and returns a reference to the named menu item in the IDE else returns nil.
@precon None.
@postcon Finds and returns a reference to the named menu item in the IDE else returns nil.
@param strParentMenu as a String as a constant
@return a TMenuItem
**)
function FindMenuItem(Const strParentMenu : String): TMenuItem;
(**
This method iterates the submenus of a main menu item.
@precon Menu must be a valid menu item.
@postcon Iterates the submenus of a main menu item.
@param Menu as a TMenuItem as a constant
@return a TMenuItem
**)
Function IterateSubMenus(Const Menu : TMenuItem) : TMenuItem;
Var
iSubMenu : Integer;
Begin
Result := Nil;
For iSubMenu := 0 To Menu.Count - 1 Do
Begin
If CompareText(strParentMenu, Menu[iSubMenu].Name) = 0 Then
Result := Menu[iSubMenu]
Else
Result := IterateSubMenus(Menu[iSubMenu]);
If Result <> Nil Then
Break;
End;
End;
Var
iMenu : Integer;
NTAS : INTAServices;
Items : TMenuItem;
begin
Result := Nil;
NTAS := (BorlandIDEServices As INTAServices);
For iMenu := 0 To NTAS.MainMenu.Items.Count - 1 Do
Begin
Items := NTAS.MainMenu.Items;
If CompareText(strParentMenu, Items[iMenu].Name) = 0 Then
Result := Items[iMenu]
Else
Result := IterateSubMenus(Items);
If Result <> Nil Then
Break;
End;
end;
{$ENDIF}
(**
This function returns either the EXE, Params or Working Directory of the external tool information.
strText should be 3 fields of information, EXE, Params and Working Dir separated by pipes (|).
@precon None.
@postcon Returns either the EXE, Params or Working Directory of the external tool information.
@param strText as a String as a constant
@param ProcInfoType as a TProcInfoType as a constant
@return a String
**)
Function GetProcInfo(Const strText : String; Const ProcInfoType : TProcInfoType) : String;
Var
iPos : Integer;
strNewText : String;
Begin
Result := '';
strNewText := strText;
iPos := Pos('|', strNewText);
If iPos > 0 Then
Begin
Result := Copy(strNewText, 1, iPos - 1);
If ProcInfoType = pitEXE Then
Exit;
Delete(strNewText, 1, iPos);
iPos := Pos('|', strNewText);
If iPos > 0 Then
Begin
Result := Copy(strNewText, 1, iPos - 1);
If ProcInfoType = pitParam Then Exit;
Delete(strNewText, 1, iPos);
Result := strNewText;
End;
End;
End;
{$IFNDEF CONSOLE_TESTRUNNER}
(**
This function returns a project name with the DPRP or DPK extension.
@precon Project must be a valid instance of a IOTAProject interface.
@postcon Returns a project name with the DPRP or DPK extension.
@param Project as an IOTAProject as a constant
@return a String
**)
Function GetProjectName(Const Project : IOTAProject) : String;
Const
strDPRExt = '.dpr';
strDPKExt = '.dpk';
Var
i : Integer;
strExt: String;
Begin
Result := ExtractFileName(Project.FileName);
For i := 0 To Project.ModuleFileCount - 1 Do
Begin
strExt := LowerCase(ExtractFileExt(Project.ModuleFileEditors[i].FileName));
If (strExt = strDPRExt) Or (strExt = strDPKExt) Then
Begin
Result := ChangeFileExt(Result, strExt);
Break;
End;
End;
End;
{$ENDIF}
(**
This function returns the ITHelpers HTML Help file with an optional page reference.
@precon None.
@postcon Returns the ITHelpers HTML Help file with an optional page reference.
@param strContext as a String as a constant
@return a String
**)
Function ITHHTMLHelpFile(Const strContext : String = '') : String;
Const
strITHelperCHMFileName = 'ITHelper.chm';
strHTMLContext = '::/%s.html';
Var
iSize: Cardinal;
Begin
SetLength(Result, MAX_PATH);
iSize := GetModuleFileName(hInstance, PChar(Result), MAX_PATH);
SetLength(Result, iSize);
Result := ExtractFilePath(Result) + strITHelperCHMFileName;
If strContext <> '' Then
Result := Result + Format(strHTMLContext, [strContext]);
End;
{$IFNDEF CONSOLE_TESTRUNNER}
(**
This method outputs the given message to the IDEs message window.
@precon None.
@postcon Outputs the given message to the IDEs message window.
@param strText as a String as a constant
**)
Procedure OutputMessage(Const strText : String);
Begin
(BorlandIDEServices As IOTAMessageServices).AddTitleMessage(strText);
End;
(**
This method outputs the given message to the named message group.
@precon None.
@postcon Outputs the given message to the named message group.
@param strText as a String as a constant
@param strGroupName as a String as a constant
**)
Procedure OutputMessage(Const strText : String; Const strGroupName : String);
Var
MS : IOTAMessageServices;
Group : IOTAMessageGroup;
Begin
If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then
Begin
Group := MS.GetGroup(strGroupName);
If Group = Nil Then
Group := MS.AddMessageGroup(strGroupName);
MS.AddTitleMessage(strText, Group);
End;
End;
(**
This method outputs the given message with file and cursor position to the IDEs message window so that
if the message is double clicked then the position in the file will be displayed by the IDE.
@precon None.
@postcon Displays a tool message in the IDE.
@param strFileName as a String as a constant
@param strText as a String as a constant
@param strPrefix as a String as a constant
@param iLine as an Integer as a constant
@param iCol as an Integer as a constant
**)
Procedure OutputMessage(Const strFileName, strText, strPrefix : String; Const iLine, iCol : Integer);
Begin
(BorlandIDEServices As IOTAMessageServices).AddToolMessage(strFileName,
strText, strPrefix, iLine, iCol);
End;
(**
This method outputs text to the given IOTAEditWriter interface.
@precon Writer must be a valid instance.
@postcon Outputs text to the given IOTAEditWriter interface.
@param Writer as an IOTAEditWriter as a constant
@param iIndent as an Integer as a constant
@param strText as a String as a constant
**)
Procedure OutputText(Const Writer : IOTAEditWriter; Const iIndent : Integer; Const strText : String);
Begin
{$IFNDEF D2009}
Writer.Insert(PAnsiChar(StringOfChar(#32, iIndent) + strText));
{$ELSE}
Writer.Insert(PAnsiChar(AnsiString(StringOfChar(#32, iIndent) + strText)));
{$ENDIF}
End;
(**
This method can be called (and should from Delphi 7 IDE and lower) to patch
the shortcuts to the menu / action items as they are lost be the IDE. A copy
of the shortcut is stored in the TAG property of the action.
@precon None.
@postcon Patches the action shortcuts for added action item.
@param Sender as a TObject
**)
Procedure PatchActionShortcuts(Sender : TObject);
Var
iAction : Integer;
A : TAction;
Begin
For iAction := 0 To FOTAActions.Count - 1 Do
Begin
A := FOTAActions[iAction] As TAction;
A.ShortCut := A.Tag;
End;
End;
(**
This method returns the current project group reference or nil if there is no
project group open.
@precon None.
@postcon Returns the current project group reference or nil if there is no
project group open.
@return an IOTAProjectGroup
**)
Function ProjectGroup: IOTAProjectGroup;
Var
AModuleServices: IOTAModuleServices;
AModule: IOTAModule;
i: integer;
AProjectGroup: IOTAProjectGroup;
Begin
Result := Nil;
AModuleServices := (BorlandIDEServices as IOTAModuleServices);
For i := 0 To AModuleServices.ModuleCount - 1 Do
Begin
AModule := AModuleServices.Modules[i];
If (AModule.QueryInterface(IOTAProjectGroup, AProjectGroup) = S_OK) Then
Break;
End;
Result := AProjectGroup;
end;
(**
This method returns the project module for the given project.
@precon Project must be a valid instance.
@postcon Returns the project module for the given project.
@param Project as an IOTAProject as a constant
@return an IOTAModule
**)
Function ProjectModule(Const Project : IOTAProject) : IOTAModule;
Var
AModuleServices: IOTAModuleServices;
AModule: IOTAModule;
i: integer;
AProject: IOTAProject;
Begin
Result := Nil;
AModuleServices := (BorlandIDEServices as IOTAModuleServices);
For i := 0 To AModuleServices.ModuleCount - 1 Do
Begin
AModule := AModuleServices.Modules[i];
If (AModule.QueryInterface(IOTAProject, AProject) = S_OK) And
(Project = AProject) Then
Break;
End;
Result := AProject;
End;
(**
This method removes any tool bar buttons that correpsond to actions from this
expert so that there are no access violations once it is removed.
@precon None.
@postcon Removes any tool bar buttons that correpsond to actions from this
expert so that there are no access violations once it is removed.
**)
Procedure RemoveToolbarButtonsAssociatedWithActions;
(**
This function checks to see whether the given action is in our action list and returns true if it is.
@precon None.
@postcon Checks to see whether the given action is in our action list and returns true if it is.
@param Action as a TBasicAction as a constant
@return a Boolean
**)
Function IsCustomAction(Const Action : TBasicAction) : Boolean;
Var
i: Integer;
Begin
Result := False;
For i := 0 To FOTAActions.Count - 1 Do
If Action = FOTAActions[i] Then
Begin
Result := True;
Break;
End;
End;
(**
This method iterates over the buttons on a toolbar and removed the button if its action corresponds
to an action from this expert.
@precon None.
@postcon Iterates over the buttons on a toolbar and removed the button if its action corresponds to
an action from this expert.
@param TB as a TToolbar as a constant
**)
Procedure RemoveAction(Const TB : TToolbar);
Var
i: Integer;
Begin
If TB <> Nil Then
For i := TB.ButtonCount - 1 DownTo 0 Do
Begin
If IsCustomAction(TB.Buttons[i].Action) Then
TB.RemoveControl(TB.Buttons[i]);
End;
End;
Var
NTAS : INTAServices;
Begin
NTAS := (BorlandIDEServices As INTAServices);
RemoveAction(NTAS.ToolBar[sCustomToolBar]);
RemoveAction(NTAS.Toolbar[sStandardToolBar]);
RemoveAction(NTAS.Toolbar[sDebugToolBar]);
RemoveAction(NTAS.Toolbar[sViewToolBar]);
RemoveAction(NTAS.Toolbar[sDesktopToolBar]);
{$IFDEF D0006}
RemoveAction(NTAS.Toolbar[sInternetToolBar]);
RemoveAction(NTAS.Toolbar[sCORBAToolBar]);
{$IFDEF D2009}
RemoveAction(NTAS.Toolbar[sAlignToolbar]);
RemoveAction(NTAS.Toolbar[sBrowserToolbar]);
RemoveAction(NTAS.Toolbar[sHTMLDesignToolbar]);
RemoveAction(NTAS.Toolbar[sHTMLFormatToolbar]);
RemoveAction(NTAS.Toolbar[sHTMLTableToolbar]);
RemoveAction(NTAS.Toolbar[sPersonalityToolBar]);
RemoveAction(NTAS.Toolbar[sPositionToolbar]);
RemoveAction(NTAS.Toolbar[sSpacingToolbar]);
{$ENDIF}
{$ENDIF}
End;
{$ENDIF}
(**
This function resolve the path of the file name with respect to the
path given to produce a full path to the file name.
@precon None.
@postcon Resolve the path of the file name with respect to the
path given to produce a full path to the file name
@param strFName as a String as a constant
@param strPath as a String as a constant
@return a String
**)
Function ResolvePath(Const strFName, strPath : String) : String;
Const
strSingleDot = '.\';
strDoubleDot = '..\';
Var
strFileName : String;
strPathName :String;
Begin
strFileName := strFName;
strPathName := strPath;
If strFileName[1] = '.' Then
Begin
Repeat
If Copy(strFileName, 1, Length(strSingleDot)) = strSingleDot Then
strFileName := Copy(strFileName, Length(strSingleDot) + 1,
Length(strFileName) - Length(strSingleDot));
If Copy(strFileName, 1, Length(strDoubleDot)) = strDoubleDot Then
Begin
strFileName := Copy(strFileName, Length(strDoubleDot) + 1,
Length(strFileName) - Length(strDoubleDot));
strPathName := ExtractFilePath(Copy(strPathName, 1, Length(strPathName) - 1));
End;
Until strFileName[1] <> '.';
Result := strPathName + strFileName;
End Else
Begin
If ExtractFilePath(strFileName) = '' Then
Result := strPathName + strFileName
Else
Result := strFileName;
End;
End;
{$IFNDEF CONSOLE_TESTRUNNER}
(**
This method displays the package`s message tab.
@precon None.
@postcon Displays the package`s message tab.
@param boolITHGroup as a Boolean as a constant
**)
Procedure ShowHelperMessages(Const boolITHGroup : Boolean);
Var
MS : IOTAMessageServices;
G : IOTAMessageGroup;
Begin
If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then
Begin
G := Nil;
If boolITHGroup Then
G := MS.GetGroup(strITHelperGroup)
Else
G := MS.GetGroup(strBuild);
If Application.MainForm.Visible Then
MS.ShowMessageView(G);
End;
End;
(**
This method displays the named message group in the IDE. If no group is provided then the main message
window is displayed.
@precon None.
@postcon Displays the named message group in the IDE.
@param strGroupName as a String as a constant
**)
Procedure ShowMessages(Const strGroupName : String = '');
Var
MS : IOTAMessageServices;
G : IOTAMessageGroup;
Begin
If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then
Begin
G := MS.GetGroup(strGroupName);
MS.ShowMessageView(G);
End;
End;
(**
This method returns the source editor for the given module.
@precon Module must be a valid instance.
@postcon Returns the source editor for the given module.
@param Module as an IOTAMOdule as a constant
@return an IOTASourceEditor
**)
Function SourceEditor(Const Module : IOTAMOdule) : IOTASourceEditor;
Var
iFileCount : Integer;
i : Integer;
Begin
Result := Nil;
If Assigned(Module) Then
Begin
iFileCount := Module.GetModuleFileCount;
For i := 0 To iFileCount - 1 Do
If Module.GetModuleFileEditor(i).QueryInterface(IOTASourceEditor, Result) = S_OK Then
Break;
End;
End;
{$ENDIF}
(** Creates an object list for storing all action reference so they can be
removed from the IDE. **)
Initialization
FOTAActions := TObjectList.Create(True);
(** Frees the actions and in doing so removes them from the IDE. **)
Finalization
{$IFNDEF CONSOLE_TESTRUNNER}
RemoveToolbarButtonsAssociatedWithActions;
{$ENDIF}
FOTAActions.Free;
end.
|
unit HMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, OnScheme, StdCtrls, OnFocusButton, OnOneInstance,
Tmax_session, OnLineLabel, OnShapeLabel, OnEditBaseCtrl, OnEditStdCtrl,
OnEditBtnCtrl, OnTmaxPersonEdit, OnEditNumCtl, Grids, DBGrids, OnGrDBGrid,
Buttons, OnSkinBtn, PeJeonLabel, OnTmaxInsaData, OnInsaCommon,
Db, Tmax_DataSetText, OnDBGrid, peoutlookbtn, OnEditMemo,NotesHana_TLB;
type
TFM_Main = class(TForm)
SF_Main : TOnSchemeForm;
PA_MainPanel : TPanel;
SB_Help : TStatusBar;
ONE_App : TOnOnceInstance;
ED_empno: TTMaxPersonPopupEdit;
L_Deptname: TOnShapeLabel;
L_Payclname: TOnShapeLabel;
L_payraname: TOnShapeLabel;
Shape5: TShape;
OnSectionLabel4: TOnSectionLabel;
L_jobgun: TOnShapeLabel;
L_jobkind: TOnShapeLabel;
L_empdate: TOnMaskEdit;
L_paycldate: TOnMaskEdit;
DBSet1: TTMaxDataSet;
DataSource1: TDataSource;
DBSet_dml: TTMaxDataSet;
BT_Exit: TOnFocusButton;
TDS1: TTMaxDataSet;
TMaxDataSet_HInsa: TTMaxDataSet;
Notebook1: TNotebook;
Panel1: TPanel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
CB_ShowClass2: TCheckBox;
Label18: TLabel;
LT_Count: TPanel;
Label16: TLabel;
L_Total1: TLabel;
L_Yes1: TLabel;
L_duname: TLabel;
Label20: TLabel;
LT_Self: TPanel;
Label15: TLabel;
Label17: TLabel;
SG_Image1: TStringGrid;
SG_HiddenData1: TStringGrid;
Panel7: TPanel;
SG_Score1: TStringGrid;
P_ControlButton1: TPanel;
SB_S1: TSpeedButton;
SB_A1: TSpeedButton;
SB_B1: TSpeedButton;
SB_C1: TSpeedButton;
SB_D1: TSpeedButton;
L_eempno: TLabel;
CB_empno: TLabel;
Label14: TLabel;
Label5: TLabel;
Panel2: TPanel;
Label7: TLabel;
L_Total2: TLabel;
L_Yes2: TLabel;
Label10: TLabel;
Label21: TLabel;
Panel3: TPanel;
Label13: TLabel;
Label19: TLabel;
SG_Image2: TStringGrid;
SG_HiddenData2: TStringGrid;
Panel4: TPanel;
SG_Score2: TStringGrid;
P_ControlButton2: TPanel;
SB_S2: TSpeedButton;
SB_A2: TSpeedButton;
SB_B2: TSpeedButton;
SB_C2: TSpeedButton;
SB_D2: TSpeedButton;
Bt_Confirm: TOnFocusButton;
BT_Save1: TOnFocusButton;
Label3: TLabel;
Memo_E1: TOnMemo;
BT_VIEWClose: TOnFocusButton;
OnFocusButton2: TOnFocusButton;
L_Title: TPanel;
L_Self1: TPanel;
L_First1: TPanel;
Label99: TLabel;
Panel5: TPanel;
L_Self2: TPanel;
L_First2: TPanel;
Label1: TLabel;
CB_ShowClass1: TCheckBox;
Insa_Data: TOnTMaxInsaData;
Insa_Session: TTMaxSession;
Panel11: TPanel;
Label12: TLabel;
Label22: TLabel;
Panel6: TPanel;
Panel8: TPanel;
Label2: TLabel;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormShow(Sender: TObject);
procedure BT_ExitClick(Sender: TObject);
procedure SG_Image1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure SB_S1Click(Sender: TObject);
procedure BT_Save1Click(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure SG_Image2DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure Bt_ConfirmClick(Sender: TObject);
procedure Bt_OConfirmClick(Sender: TObject);
procedure Bt_AddClick(Sender: TObject);
procedure OnFocusButton1Click(Sender: TObject);
procedure OnFocusButton2Click(Sender: TObject);
procedure Notebook1PageChanged(Sender: TObject);
procedure BT_VIEWCloseClick(Sender: TObject);
procedure SG_Score1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure SG_Score1Enter(Sender: TObject);
procedure CB_ShowClass1Click(Sender: TObject);
procedure SB_S2Click(Sender: TObject);
procedure SG_Score2DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure PageControl1Enter(Sender: TObject);
procedure SG_Score2Enter(Sender: TObject);
procedure CB_ShowClass2Click(Sender: TObject);
private
{ Private declarations }
FL_Start : Boolean;
FL_E1opinionyn : Boolean;
sRabasdate : string;
procedure Common_data;
procedure Leadership_data;
procedure ShowSum1;
procedure ShowSum2;
function Csel_gfd(p_loc: Integer): String;
public
{ Public declarations }
var_Ekind: String; // 역량종류
Pjobkind : String;
Inter : ILotusNotes_Hana;
Pempno, Pkorname, Password, Ppermission: string;
var_empno : String; //피평가자 사번
var_korname : String; //피평가자 성명
end;
var
FM_Main: TFM_Main;
DetailCnt : Integer;
Csel_SQL : String;
E1ValconYN,E2ValconYN : String;
Le1korname,Le1empno : String;
const
SScore = '100';
AScore = '90';
BScore = '80';
CScore = '70';
DScore = '60';
var_ScrS = '100';
var_ScrA = '90';
var_ScrB = '80';
var_ScrC = '70';
var_ScrD = '60';
var_GrdS = 'S';
var_GrdA = 'A';
var_GrdB = 'B';
var_GrdC = 'C';
var_GrdD = 'D';
implementation
//uses HSubForm,Hinsa_TmaxDM, UOpinon;
uses Hinsa_TmaxDM;
{$R *.DFM}
procedure TFM_Main.FormCreate(Sender: TObject);
begin
FL_Start := True;
end;
procedure TFM_Main.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := True;
//
end;
procedure TFM_Main.FormShow(Sender: TObject);
var SqlText :string;
begin
sRabasdate := '20051231';
var_empno := '1569';
//최종완료 여부를 체크 한후 버튼 설정을 한다.
SqlText := 'select nvl(RVALCONYN,''N'') '+
'from pesremas '+
'where rabasdate = '''+sRabasdate+'''' +
'and empno = '''+var_empno+'''';
with DataModule_Tmax.TMaxDataSet_HInsa do
begin
Close;
ServiceName := 'PTA1010B_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 2000);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount > 0 then
begin
showmessage('aa');
if Csel_gfd(1) = 'N' then
begin
Bt_Confirm.Enabled := true;
BT_Save1.Enabled := true;
end
else
begin
//이미 상향평가 처리되었습니다.
Bt_Confirm.Enabled := false;
BT_Save1.Enabled := false;
end;
end;
close;
end;
Notebook1.PageIndex := 0;
PageControl1.ActivePage := TabSheet1;
//공동역량를 조회한다.
Common_data;
Leadership_data;
end;
procedure TFM_Main.Common_data;
var
SqlText: String;
i, j : Integer;
begin
Application.ProcessMessages;
//만일 1차 평가자 완료처리 된 자료는 저장처리및 변경처리 못하도록 막는다.
//
//
for i := 0 to SG_HiddenData1.ColCount - 1 do
for j := SG_HiddenData1.FixedRows to SG_HiddenData1.RowCount -1 do
SG_HiddenData1.Cells[i, j] := '';
SG_HiddenData1.RowCount := SG_HiddenData1.FixedRows+1;
SqlText := 'SELECT nvl(to_char(a.itemno),''0'')||'';''||'+
' nvl(c.itemname,'' '')||'';''||'+
' nvl(to_char(a.imageno),''0'')||'';''||'+
' nvl(a.imagedesc,'' '')||'';''||'+
' nvl(to_char(b.score),''0'')||'';''||'+
' ''00''||'';''||'+
' nvl(b.empno,'' '')'+
' FROM petacd a, petdl b, petac C' + // 능력태도평가표이미지, 능력태도자기평가, 능력태도평가표항목
' WHERE a.rabasdate = '''+sRabasdate+'''' +
' AND a.evcno = 1' + // 평가표번호
' AND a.ekind = ''공통역량''' + // 평가구분
' AND a.rabasdate = c.rabasdate' +
' AND a.evcno = c.evcno' + // 평가표번호
' AND a.ekind = c.ekind' +
' AND a.itemno = c.itemno' +
' AND a.rabasdate = b.rabasdate(+)' +
' AND a.ekind = b.ekind(+)' +
' AND b.empno(+) = '''+var_empno+'''' + // 피평가자사번
' AND a.itemno = b.itemno(+)' +
' AND a.imageno = b.imageno(+)' +
' ORDER BY a.itemno, a.imageno';
with DataModule_Tmax.TMaxDataSet_HInsa do
begin
Close;
ServiceName := 'PTA1010B_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 2000);
ClearParamInfo;
SQL.Text := SqlText;
Open;
end;
// memo1.text := SqlText;
showmessage(inttostr(DataModule_Tmax.TMaxDataSet_HInsa.RecordCount));
if DataModule_Tmax.TMaxDataSet_HInsa.RecordCount > 0 then
begin
showmessage('dhk');
end;
while not DataModule_Tmax.TMaxDataSet_HInsa.EOF do
begin
if SG_HiddenData1.Cells[0, SG_HiddenData1.RowCount-1] <> '' then
SG_HiddenData1.RowCount := SG_HiddenData1.RowCount + 1;
SG_HiddenData1.Cells[0, SG_HiddenData1.RowCount-1] := Csel_gfd(1); // 평가항목번호
SG_HiddenData1.Cells[1, SG_HiddenData1.RowCount-1]:= Csel_gfd(2); // 평가항목명
SG_HiddenData1.Cells[2, SG_HiddenData1.RowCount-1] := Csel_gfd(3); // 평가이미지번호
SG_HiddenData1.Cells[3, SG_HiddenData1.RowCount-1]:= Csel_gfd(4); // 평가이미지내용
SG_HiddenData1.Cells[7, SG_HiddenData1.RowCount-1] := Csel_gfd(6); // 1차평가점수
SG_HiddenData1.Cells[20, SG_HiddenData1.RowCount-1] := Csel_gfd(5); //자기평가점수
DataModule_Tmax.TMaxDataSet_HInsa.Next;
end;
// 점수등록현황
ShowSum1;
for i := 0 to SG_Image1.ColCount - 1 do
for j := 0 to SG_Image1.RowCount -1 do
SG_Image1.Cells[i, j] := '';
SG_Image1.RowCount := SG_Image1.FixedRows+1;
for i := 0 to SG_Score1.ColCount - 1 do
for j := 0 to SG_Score1.RowCount -1 do
SG_Score1.Cells[i, j] := '';
SG_Score1.RowCount := SG_Score1.FixedRows+1;
SG_HiddenData1.Tag := -1;
for i := SG_HiddenData1.FixedRows to SG_HiddenData1.RowCount-1 do
begin
if SG_HiddenData1.Tag = -1 then
SG_HiddenData1.Tag := i;
if SG_Image1.Cells[SG_Image1.FixedCols, SG_Image1.RowCount-1] <> '' then
begin
SG_Image1.RowCount := SG_Image1.RowCount + 1;
SG_Score1.RowCount := SG_Score1.RowCount + 1;
end;
SG_Image1.Cells[1, SG_Image1.RowCount-1] := SG_HiddenData1.Cells[3, i];
SG_Image1.Cells[0, SG_Image1.RowCount-1] := SG_HiddenData1.Cells[1, i];
SG_Image1.Cells[2, SG_Image1.RowCount-1] := SG_HiddenData1.Cells[20, i];
//showmessage(SG_Image1.Cells[2, SG_Image1.RowCount-1]);
SG_Score1.Cells[0, SG_Score1.RowCount-1] := '';
SG_Score1.Cells[1, SG_Score1.RowCount-1] := '';
SG_Score1.Cells[2, SG_Score1.RowCount-1] := '';
SG_Score1.Cells[3, SG_Score1.RowCount-1] := '';
SG_Score1.Cells[4, SG_Score1.RowCount-1] := '';
//버튼상태반영
if trim(SG_HiddenData1.Cells[7, i]) = var_ScrS then SG_Score1.Cells[0 , SG_Score1.RowCount-1] := var_GrdS
else if trim(SG_HiddenData1.Cells[7, i]) = var_ScrA then SG_Score1.Cells[1 , SG_Score1.RowCount-1] := var_GrdA
else if trim(SG_HiddenData1.Cells[7, i]) = var_ScrB then SG_Score1.Cells[2, SG_Score1.RowCount-1] := var_GrdB
else if trim(SG_HiddenData1.Cells[7, i]) = var_ScrC then SG_Score1.Cells[3 , SG_Score1.RowCount-1] := var_GrdC
else if trim(SG_HiddenData1.Cells[7, i]) = var_ScrD then SG_Score1.Cells[4, SG_Score1.RowCount-1] := var_GrdD;
end;
SG_Image1.SetFocus;
end;
procedure TFM_Main.Leadership_data;
var
SqlText: String;
i, j : Integer;
begin
Application.ProcessMessages;
for i := 0 to SG_HiddenData2.ColCount - 1 do
for j := SG_HiddenData2.FixedRows to SG_HiddenData2.RowCount -1 do
SG_HiddenData2.Cells[i, j] := '';
SG_HiddenData2.RowCount := SG_HiddenData2.FixedRows+1;
SqlText := 'SELECT nvl(to_char(a.itemno),''0'')||'';''||'+
' nvl(c.itemname,'' '')||'';''||'+
' nvl(to_char(a.imageno),''0'')||'';''||'+
' nvl(a.imagedesc,'' '')||'';''||'+
' nvl(to_char(b.score),''0'')||'';''||'+
' nvl(to_char(b.e1score),''0'')||'';''||'+
' nvl(b.empno,'' '')'+
' FROM petacd a, petds b, petac C' + // 능력태도평가표이미지, 능력태도자기평가, 능력태도평가표항목
' WHERE a.rabasdate = '''+sRabasdate+'''' +
' AND a.evcno = 1' + // 평가표번호
' AND a.ekind = ''리더십역량''' + // 평가구분
' AND a.rabasdate = c.rabasdate' +
' AND a.evcno = c.evcno' + // 평가표번호
' AND a.ekind = c.ekind' +
' AND a.itemno = c.itemno' +
' AND a.rabasdate = b.rabasdate(+)' +
' AND a.ekind = b.ekind(+)' +
' AND b.empno(+) = '''+var_empno+'''' + // 피평가자사번
' AND a.itemno = b.itemno(+)' +
' AND a.imageno = b.imageno(+)' +
' ORDER BY a.itemno, a.imageno';
with DataModule_Tmax.TMaxDataSet_HInsa do
begin
Close;
ServiceName := 'PTA1010B_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 2000);
ClearParamInfo;
SQL.Text := SqlText;
Open;
end;
while not DataModule_Tmax.TMaxDataSet_HInsa.EOF do
begin
if SG_HiddenData2.Cells[0, SG_HiddenData2.RowCount-1] <> '' then
SG_HiddenData2.RowCount := SG_HiddenData2.RowCount + 1;
SG_HiddenData2.Cells[0, SG_HiddenData2.RowCount-1] := Csel_gfd(1); // 평가항목번호
SG_HiddenData2.Cells[1, SG_HiddenData2.RowCount-1]:= Csel_gfd(2); // 평가항목명
SG_HiddenData2.Cells[2, SG_HiddenData2.RowCount-1] := Csel_gfd(3); // 평가이미지번호
SG_HiddenData2.Cells[3, SG_HiddenData2.RowCount-1]:= Csel_gfd(4); // 평가이미지내용
SG_HiddenData2.Cells[7, SG_HiddenData2.RowCount-1] := Csel_gfd(6); // 1차평가점수
SG_HiddenData2.Cells[20, SG_HiddenData2.RowCount-1] := Csel_gfd(5); //자기평가점수
DataModule_Tmax.TMaxDataSet_HInsa.Next;
end;
// 점수등록현황
ShowSum2;
for i := 0 to SG_Image2.ColCount - 1 do
for j := 0 to SG_Image2.RowCount -1 do
SG_Image2.Cells[i, j] := '';
SG_Image2.RowCount := SG_Image2.FixedRows+1;
for i := 0 to SG_Score2.ColCount - 1 do
for j := 0 to SG_Score2.RowCount -1 do
SG_Score2.Cells[i, j] := '';
SG_Score2.RowCount := SG_Score2.FixedRows+1;
SG_HiddenData2.Tag := -1;
for i := SG_HiddenData2.FixedRows to SG_HiddenData2.RowCount-1 do
begin
if SG_HiddenData2.Tag = -1 then
SG_HiddenData2.Tag := i;
if SG_Image2.Cells[SG_Image1.FixedCols, SG_Image2.RowCount-1] <> '' then
begin
SG_Image2.RowCount := SG_Image2.RowCount + 1;
SG_Score2.RowCount := SG_Score2.RowCount + 1;
end;
SG_Image2.Cells[1, SG_Image2.RowCount-1] := SG_HiddenData2.Cells[3, i];
SG_Image2.Cells[0, SG_Image2.RowCount-1] := SG_HiddenData2.Cells[1, i];
SG_Image2.Cells[2, SG_Image2.RowCount-1] := SG_HiddenData2.Cells[20, i];
SG_Score2.Cells[0 , SG_Score2.RowCount-1] := '';
SG_Score2.Cells[1 , SG_Score2.RowCount-1] := '';
SG_Score2.Cells[2 , SG_Score2.RowCount-1] := '';
SG_Score2.Cells[3 , SG_Score2.RowCount-1] := '';
SG_Score2.Cells[4 , SG_Score2.RowCount-1] := '';
//버튼상태반영
if trim(SG_HiddenData2.Cells[7, i]) = var_ScrS then SG_Score2.Cells[0 , SG_Score2.RowCount-1] := var_GrdS
else if trim(SG_HiddenData2.Cells[7, i]) = var_ScrA then SG_Score2.Cells[1 , SG_Score2.RowCount-1] := var_GrdA
else if trim(SG_HiddenData2.Cells[7, i]) = var_ScrB then SG_Score2.Cells[2, SG_Score2.RowCount-1] := var_GrdB
else if trim(SG_HiddenData2.Cells[7, i]) = var_ScrC then SG_Score2.Cells[3 , SG_Score2.RowCount-1] := var_GrdC
else if trim(SG_HiddenData2.Cells[7, i]) = var_ScrD then SG_Score2.Cells[4, SG_Score2.RowCount-1] := var_GrdD;
end;
//SG_Image2.SetFocus;
end;
function TFM_Main.Csel_gfd(p_loc: Integer): String;
var
v_cnt, v_tmp: Integer;
v_data: String;
begin
Result := '';
v_data := DataModule_Tmax.TMaxDataSet_HInsa.FieldByName('SEL_DATA').AsString;
v_cnt := 1;
while v_cnt < p_loc do
begin
v_tmp := Pos(';',v_data);
if not(v_tmp > 0) then Exit;
v_cnt := v_cnt + 1;
Delete(v_data, 1, v_tmp);
end;
v_tmp := Pos(';',v_data) - 1;
if v_tmp < 0 then v_tmp := Length(v_data);
Result := Copy(v_data,1,v_tmp);
end;
procedure TFM_Main.BT_ExitClick(Sender: TObject);
begin
close;
end;
procedure TFM_Main.SG_Image1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
lsBuffer : String;
liLeft, liTop : Integer;
begin
if gdSelected in State then
begin
SG_Image1.Canvas.Brush.Color := $00CFFBFC;//$00FFE8D0;//$00FFF9EC;//$00CFFBFC;
SG_Image1.Canvas.Font.Color := clBlack;
SG_Image1.Canvas.Font.Size := 9;
end;
lsBuffer := SG_Image1.Cells[ACol, ARow];
SG_Image1.Canvas.FillRect(Rect);
{
if SG_Image1.VisibleRowCount < SG_Image1.RowCount then
SG_Image1.ColWidths[mSELFSCORE_IDX] := iWidth_SelfScore - 16
else
SG_Image1.ColWidths[mSELFSCORE_IDX] := iWidth_SelfScore;
}
if ACol = 0 then
begin
SG_Image1.Canvas.FillRect(Rect);
Rect.Top := (((Rect.Bottom - Rect.Top) - SG_Image1.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
DrawText(SG_Image1.Canvas.Handle, PChar(lsBuffer),
StrLen(PChar(lsBuffer)), Rect, DT_Center or DT_WORDBREAK);
end
else if (ACol = 2) or(ACol = 3)or (ACol = 4) or (ACol = 5) then
begin
liLeft := (((Rect.Right - Rect.Left)
- SG_Image1.Canvas.TextWidth(lsBuffer)) div 2) + Rect.Left;
liTop := (((Rect.Bottom - Rect.Top)
- SG_Image1.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
SG_Image1.Canvas.Font.Style := [fsBold];
SG_Image1.Canvas.Font.Size := 10;
SG_Image1.Canvas.TextOut(liLeft, liTop, lsBuffer);
end
else
begin
Rect.Top := Rect.Top + 2; // 실제 Text가 그려지는 영역의 크기를 약간 줄인다
Rect.Left := Rect.Left + 2;
Rect.Right := Rect.Right - 10;
DrawText(SG_Image1.Canvas.Handle, PChar(lsBuffer),
StrLen(PChar(lsBuffer)), Rect, DT_LEFT or DT_WORDBREAK);
end;
// 선택된 row가 화면에 보이게 위치를 바꾼다
if SG_Image1.Row < SG_Image1.TopRow then // 현재 row 가 화면위에 있다
SG_Image1.Row := SG_Image1.TopRow
else if SG_Image1.Row > (SG_Image1.TopRow + SG_Image1.VisibleRowCount-1) then // 현재 row 가 화면밑에 있다
SG_Image1.Row := SG_Image1.TopRow + SG_Image1.VisibleRowCount-1;
SG_Score1.TopRow := SG_Image1.TopRow;
SG_Score1.Row := SG_Image1.Row;
// 버튼의 top 위치를 계산
P_ControlButton1.Top := (SG_Image1.Row - SG_Image1.TopRow) *
(SG_Image1.DefaultRowHeight + SG_Image1.GridLineWidth) + 2;
// 점수를 버튼에 반영
SB_S1.Down := False;
SB_A1.Down := False;
SB_B1.Down := False;
SB_C1.Down := False;
SB_D1.Down := False;
//버튼상태반영
if trim(SG_HiddenData1.Cells[7, SG_HiddenData1.Tag + SG_Image1.Row]) = var_ScrS then SB_S1.Down := True
else if trim(SG_HiddenData1.Cells[7, SG_HiddenData1.Tag + SG_Image1.Row]) = var_ScrA then SB_A1.Down := True
else if trim(SG_HiddenData1.Cells[7, SG_HiddenData1.Tag + SG_Image1.Row]) = var_ScrB then SB_B1.Down := True
else if trim(SG_HiddenData1.Cells[7, SG_HiddenData1.Tag + SG_Image1.Row]) = var_ScrC then SB_C1.Down := True
else if trim(SG_HiddenData1.Cells[7, SG_HiddenData1.Tag + SG_Image1.Row]) = var_ScrD then SB_D1.Down := True;
P_ControlButton1.Visible := True;
end;
procedure TFM_Main.SB_S1Click(Sender: TObject);
var
lsScore : String;
begin
if TSpeedButton(Sender).Caption = var_GrdS then lsScore := var_ScrS
else if TSpeedButton(Sender).Caption = var_GrdA then lsScore := var_ScrA
else if TSpeedButton(Sender).Caption = var_GrdB then lsScore := var_ScrB
else if TSpeedButton(Sender).Caption = var_GrdC then lsScore := var_ScrC
else if TSpeedButton(Sender).Caption = var_GrdD then lsScore := var_ScrD else lsScore := '0';
// 버튼이 눌려지면 SG_HiddenData에 변경된 값과 변경여부를 'Y'로 고친다.
if TSpeedButton(Sender).Down = True then
begin
SG_HiddenData1.Cells[7, SG_HiddenData1.Tag+SG_Image1.Row] := lsScore;
SG_Score1.Cells[0, SG_Image1.Row]:= '';
SG_Score1.Cells[1, SG_Image1.Row]:= '';
SG_Score1.Cells[2, SG_Image1.Row]:= '';
SG_Score1.Cells[3, SG_Image1.Row]:= '';
SG_Score1.Cells[4, SG_Image1.Row]:= '';
if SB_S1.Down then SG_Score1.Cells[0, SG_Image1.Row]:= var_GrdS
else if SB_A1.Down then SG_Score1.Cells[1, SG_Image1.Row]:= var_GrdA
else if SB_B1.Down then SG_Score1.Cells[2, SG_Image1.Row]:= var_GrdB
else if SB_C1.Down then SG_Score1.Cells[3, SG_Image1.Row]:= var_GrdC
else SG_Score1.Cells[4, SG_Image1.Row]:= var_GrdD ;
end else
begin
SG_HiddenData1.Cells[7, SG_HiddenData1.Tag+SG_Image1.Row] := '';
SG_Score1.Cells[0 , SG_Image1.Row] := '';
SG_Score1.Cells[1 , SG_Image1.Row] := '';
SG_Score1.Cells[2 , SG_Image1.Row] := '';
SG_Score1.Cells[3 , SG_Image1.Row] := '';
SG_Score1.Cells[4 , SG_Image1.Row] := '';
end;
ShowSum1;
end;
procedure TFM_Main.BT_Save1Click(Sender: TObject);
var
i, j: Integer;
SqlText: String;
begin
if PageControl1.ActivePage = TabSheet1 then
begin
//공통역량평가 내역을 저장처리 한다.
{
for i := 0 to SG_HiddenData1.RowCount -1 do
begin
if trim(SG_HiddenData1.Cells[7, i]) = '' then
begin
showmessage('평가점수를 부여하지 않은 항목명이 존재합니다.' +#13+#13+
'평가점수를 부여하신 후 저장처리 하십시오.');
exit;
end;
end;
}
for i := SG_HiddenData1.FixedRows to SG_HiddenData1.RowCount-1 do
begin
SqlText := 'UPDATE petds ' + // 능력태도자기평가
' SET e1score = '+SG_HiddenData1.Cells[7, i]+' ' +
' WHERE rabasdate = '''+srabasdate+'''' +
' AND empno = '''+var_empno+'''' + // 평가자
' AND ekind = ''공통역량''' +
' AND itemno = '+SG_HiddenData1.Cells[0, i]+'' +
' AND imageno = '+SG_HiddenData1.Cells[2, i]+'';
DataModule_Tmax.Cupd_SQL := SqlText;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Exit;
end;
end;
MessageDlg('입력하신 평가자료를 저장하였습니다.',mtInformation,[mbOk],0);
Common_data;
end
else if PageControl1.ActivePage = TabSheet2 then
begin
{
for i := 0 to SG_HiddenData2.RowCount -1 do
begin
if trim(SG_HiddenData2.Cells[7, i]) = '' then
begin
showmessage('평가점수를 부여하지 않은 항목명이 존재합니다.' +#13+#13+
'평가점수를 부여하신 후 저장처리 하십시오.');
exit;
end;
end;
}
for i := SG_HiddenData2.FixedRows to SG_HiddenData2.RowCount-1 do
begin
SqlText := 'UPDATE petds ' +
' SET e1score = '+SG_HiddenData2.Cells[7, i]+' ' +
' WHERE rabasdate = '''+srabasdate+'''' +
' AND empno = '''+var_empno+'''' + // 평가자
' AND ekind = ''리더십역량''' +
' AND itemno = '+SG_HiddenData2.Cells[0, i]+'' +
' AND imageno = '+SG_HiddenData2.Cells[2, i]+'';
DataModule_Tmax.Cupd_SQL := SqlText;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Exit;
end;
end;
MessageDlg('입력하신 평가자료를 저장하였습니다.',mtInformation,[mbOk],0);
Leadership_data;
end;
end;
procedure TFM_Main.PageControl1Change(Sender: TObject);
begin
if PageControl1.ActivePage = TabSheet1 then
begin
// L_score1.Visible := true;
// L_score2.Visible := false;
SG_Image1.SetFocus;
BT_Save1.Caption := '공통역량 업적평가저장';
end
else
begin
// L_score2.Visible := true;
// L_score1.Visible := false;
SG_Image2.SetFocus;
BT_Save1.Caption := '리더십역량 업적평가저장';
end;
end;
procedure TFM_Main.SG_Image2DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
lsBuffer : String;
liLeft, liTop : Integer;
begin
if gdSelected in State then
begin
SG_Image2.Canvas.Brush.Color := $00CFFBFC;//$00FFE8D0;//$00FFF9EC;//$00CFFBFC;
SG_Image2.Canvas.Font.Color := clBlack;
SG_Image2.Canvas.Font.Size := 9;
end;
lsBuffer := SG_Image2.Cells[ACol, ARow];
SG_Image2.Canvas.FillRect(Rect);
if ACol = 0 then
begin
SG_Image2.Canvas.FillRect(Rect);
Rect.Top := (((Rect.Bottom - Rect.Top) - SG_Image2.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
DrawText(SG_Image2.Canvas.Handle, PChar(lsBuffer),
StrLen(PChar(lsBuffer)), Rect, DT_Center or DT_WORDBREAK);
end
else if (ACol = 2) or(ACol = 3)or (ACol = 4) or (ACol = 5) then
begin
liLeft := (((Rect.Right - Rect.Left)
- SG_Image2.Canvas.TextWidth(lsBuffer)) div 2) + Rect.Left;
liTop := (((Rect.Bottom - Rect.Top)
- SG_Image2.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
SG_Image2.Canvas.Font.Style := [fsBold];
SG_Image2.Canvas.Font.Size := 10;
SG_Image2.Canvas.TextOut(liLeft, liTop, lsBuffer);
end
else
begin
Rect.Top := Rect.Top + 2; // 실제 Text가 그려지는 영역의 크기를 약간 줄인다
Rect.Left := Rect.Left + 2;
Rect.Right := Rect.Right - 10;
DrawText(SG_Image2.Canvas.Handle, PChar(lsBuffer),
StrLen(PChar(lsBuffer)), Rect, DT_LEFT or DT_WORDBREAK);
end;
// 선택된 row가 화면에 보이게 위치를 바꾼다
if SG_Image2.Row < SG_Image2.TopRow then // 현재 row 가 화면위에 있다
SG_Image2.Row := SG_Image2.TopRow
else if SG_Image2.Row > (SG_Image2.TopRow + SG_Image2.VisibleRowCount-1) then // 현재 row 가 화면밑에 있다
SG_Image2.Row := SG_Image2.TopRow + SG_Image2.VisibleRowCount-1;
SG_Score2.TopRow := SG_Image2.TopRow;
SG_Score2.Row := SG_Image2.Row;
// 버튼의 top 위치를 계산
P_ControlButton2.Top := (SG_Image2.Row - SG_Image2.TopRow) *
(SG_Image2.DefaultRowHeight + SG_Image2.GridLineWidth) + 2;
// 점수를 버튼에 반영
SB_S2.Down := False;
SB_A2.Down := False;
SB_B2.Down := False;
SB_C2.Down := False;
SB_D2.Down := False;
//버튼상태반영
if trim(SG_HiddenData2.Cells[7, SG_HiddenData2.Tag + SG_Image2.Row]) = var_ScrS then SB_S2.Down := True
else if trim(SG_HiddenData2.Cells[7, SG_HiddenData2.Tag + SG_Image2.Row]) = var_ScrA then SB_A2.Down := True
else if trim(SG_HiddenData2.Cells[7, SG_HiddenData2.Tag + SG_Image2.Row]) = var_ScrB then SB_B2.Down := True
else if trim(SG_HiddenData2.Cells[7, SG_HiddenData2.Tag + SG_Image2.Row]) = var_ScrC then SB_C2.Down := True
else if trim(SG_HiddenData2.Cells[7, SG_HiddenData2.Tag + SG_Image2.Row]) = var_ScrD then SB_D2.Down := True;
P_ControlButton2.Visible := True;
end;
procedure TFM_Main.Bt_ConfirmClick(Sender: TObject);
var SqlText : string;
isum : Double;
begin
SqlText := 'SELECT count(0) cnt'+
' FROM petacd a, petds b, petac C'+
' WHERE a.rabasdate = '''+srabasdate+''''+
' AND a.evcno = 1'+
' AND a.ekind in(''공통역량'',''리더십역량'')'+
' AND a.rabasdate = c.rabasdate'+
' AND a.evcno = c.evcno'+
' AND a.ekind = c.ekind'+
' AND a.itemno = c.itemno'+
' AND a.rabasdate = b.rabasdate(+)'+
' AND a.ekind = b.ekind(+)'+
' AND b.empno(+) = '''+var_empno+''''+
' and nvl(b.e1score,0) = 0 '+
' AND a.itemno = b.itemno(+)'+
' AND a.imageno = b.imageno(+)'+
' ORDER BY a.itemno, a.imageno';
with DataModule_Tmax.TMaxDataSet_HInsa do
begin
Close;
ServiceName := 'PTA1010B_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 2000);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount > 0 then
begin
if trim(FieldByName('SEL_DATA').AsString) > '0' then
begin
showmessage('팀장역량 1차평가 저장처리를 할 수 없습니다.'+#13+
'공통역량, 리더십역량에 대한 역량평가가 저장처리 되었는지 확인하시기 바랍니다.');
close;
exit;
end;
end
else
begin
showmessage('공통역량, 리더십역량 등록여부 체크중 오류가 발생했습니다.');
exit;
end;
end;
if MessageBox(handle,PChar('최종완료를 하시면 등록하신 내역을 수정하실 수 없습니다.'+#13+#13+
'등록하신 내역에 대해 모두 확인을 마치셨으면 최종완료를 하시기 바랍니다.'+#13+#13+
'최종완료를 하시겠습니까?'), '확 인', MB_YESNO or MB_DEFBUTTON2) <> IDYES then
begin
if TComponent(Sender).Name = 'Bt_Exit' then Bt_Exit.Hint := 'OK';
system.Exit;
end;
//1차최종평가점수를 계산한다.
isum := StrToFloat(L_First1.Caption);
isum := isum + StrToFloat(L_First2.Caption);
iSum := (Round(iSum/2*10000)/10000);
//피평가자 평가완료 여부 'Y'로 update
SqlText := 'update petremas '+
'set E1VALCONYN =''Y'''+
' ,E1SCORE = '+ FloatToStr(isum) +
' ,e1valcondate = SUBSTR(TO_CHAR(SYSDATE,''YYYYMMDDHH24MISSD''),1,8), '+
'e1valobjyn= ''N'', e2valobjyn = ''N'''+
' WHERE rabasdate = '''+srabasdate+''''+
' AND empno = '''+var_empno+'''';
with DBSet_dml do
begin
Close;
ServiceName := 'PET1010A_dml';
ClearFieldInfo;
SQL.Text := SqlText;
Execute;
Bt_Confirm.Enabled := false;
BT_Save1.Enabled := false;
MessageDlg('[1차평가 최종완료 ]처리 되었습니다.', mtInformation, [mbOK], 0);
end;
end;
procedure TFM_Main.Bt_OConfirmClick(Sender: TObject);
begin
// FL_E1opinionyn:= true;
end;
procedure TFM_Main.Bt_AddClick(Sender: TObject);
begin
//
end;
procedure TFM_Main.OnFocusButton1Click(Sender: TObject);
begin
Notebook1.PageIndex := 1;
end;
procedure TFM_Main.OnFocusButton2Click(Sender: TObject);
begin
//평가자 의견등록
if Length(Memo_E1.Text) > 600 then
begin
MessageDlg('[저장오류] 300자 이내로 의견을 등록주십시요.', mtWarning, [mbOK], 0);
System.Exit;
end;
with DBSet_dml do
begin
Close;
ClearFieldInfo;
ServiceName := 'PET1010A_dml';
SQL.Clear;
SQL.Text := Format('UPDATE petremas '+
' SET e1valview = ''%s'' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' ',
[Memo_E1.Text,sRabasdate,var_empno]);
Execute;
end;
end;
procedure TFM_Main.Notebook1PageChanged(Sender: TObject);
var SqlText : String;
begin
{
if Notebook1.PageIndex = 1 then
begin
SqlText := 'SELECT E1VALVIEW '+
' FROM petremas '+
' WHERE rabasdate ='''+srabasdate+''' '+
' AND empno ='''+var_empno+''' '+
' AND e1empno ='''+Gsempno+'''';
with TMaxDataSet_HInsa do
begin
Close;
ServiceName := 'PTA1010B_common';
ClearFieldInfo;
AddField('E1VALVIEW', ftString, 2000);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount > 0 then
Memo_E1.text := FieldByName('E1VALVIEW').AsString;
close;
end;
end;
}
end;
procedure TFM_Main.BT_VIEWCloseClick(Sender: TObject);
begin
Notebook1.PageIndex := 0;
end;
procedure TFM_Main.SG_Score1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
liLeft : integer;
liTop : integer;
lsBuffer : String;
i : Integer;
begin
SG_Score1.Canvas.Brush.Color := SG_Image1.Color; ///$00F0FFFF;
for i := 0 to SG_Score1.ColCount -1 do
if SG_Score1.Cells[i, ARow] <> '' then
begin
SG_Score1.Canvas.Brush.Color := $00FFF9EC; //SG_Score.Font.Color;
break;
end;
if CB_ShowClass1.Checked then // 등급을 보이게...
SG_Score1.Canvas.Font.Color := SG_Image1.Font.Color
else
SG_Score1.Canvas.Font.Color := SG_Score1.Font.Color;
SG_Score1.Canvas.FillRect(Rect); // cell의 영역을 그린다
lsBuffer := SG_Score1.Cells[ACol, ARow];
liLeft := (((Rect.Right - Rect.Left)
- SG_Score1.Canvas.TextWidth(lsBuffer)) div 2) + Rect.Left;
liTop := (((Rect.Bottom - Rect.Top)
- SG_Score1.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
SG_Score1.Canvas.TextOut(liLeft, liTop, lsBuffer);
end;
procedure TFM_Main.SG_Score1Enter(Sender: TObject);
begin
SG_Image1.SetFocus;
end;
procedure TFM_Main.CB_ShowClass1Click(Sender: TObject);
begin
SG_Score1.Refresh;
end;
procedure TFM_Main.ShowSum1;
var
// i : 갯수
// j : 평가
// k : 미실시
// l : 점수 합
// m : 자기평가합
i, j, k, l, m: Integer;
begin
i := 0; j := 0; k := 0; l := 0; m := 0;
for i := 0 to SG_HiddenData1.RowCount -1 do
begin
if (SG_HiddenData1.Cells[7, i] = '0') or
(SG_HiddenData1.Cells[7, i] = '') then
inc(k) //1차 미실시
else
begin
inc(j); //1차 평가
l := l + StrToInt(SG_HiddenData1.Cells[7, i]); //1차 점수
end;
m := M + StrToIntdef(SG_HiddenData1.Cells[20, i], 0 );//자기평가합
end;
if (SG_HiddenData1.RowCount = 1) and (SG_HiddenData1.Cells[0,0] = '') then
begin
i := 0; j := 0; k := 0; l := 0;
end;
L_Total1.Caption := IntToStr(j+k)+'개';
L_Yes1.Caption := IntToStr(j);
if j+k > 0 then
L_First1.Caption :=
Formatfloat('#,##0.00', l/(j+k)) ; // 점수합 / 총갯수
if j+k > 0 then
L_Self1.Caption :=
Formatfloat('#,##0.00', m/(j+k)) ; // 자기평가점수합 / 총갯수
end;
procedure TFM_Main.ShowSum2;
var
// i : 갯수
// j : 평가
// k : 미실시
// l : 점수 합
// m : 자기평가합
i, j, k, l, m: Integer;
begin
i := 0; j := 0; k := 0; l := 0; m := 0;
for i := 0 to SG_HiddenData2.RowCount -1 do
begin
if (SG_HiddenData2.Cells[7, i] = '0') or
(SG_HiddenData2.Cells[7, i] = '') then
inc(k) //1차 미실시
else
begin
inc(j); //1차 평가
l := l + StrToInt(SG_HiddenData2.Cells[7, i]); //1차 점수
end;
m := M + StrToIntdef(SG_HiddenData2.Cells[20, i], 0 );//자기평가합
end;
if (SG_HiddenData2.RowCount = 1) and (SG_HiddenData2.Cells[0,0] = '') then
begin
i := 0; j := 0; k := 0; l := 0;
end;
L_Total2.Caption := IntToStr(j+k)+'개';
L_Yes2.Caption := IntToStr(j);
if j+k > 0 then
L_First2.Caption :=
Formatfloat('#,##0.00', l/(j+k)) ; // 점수합 / 총갯수
if j+k > 0 then
L_Self2.Caption :=
Formatfloat('#,##0.00', m/(j+k)) ; // 자기평가점수합 / 총갯수
end;
procedure TFM_Main.SB_S2Click(Sender: TObject);
var
lsScore : String;
begin
if TSpeedButton(Sender).Caption = var_GrdS then lsScore := var_ScrS
else if TSpeedButton(Sender).Caption = var_GrdA then lsScore := var_ScrA
else if TSpeedButton(Sender).Caption = var_GrdB then lsScore := var_ScrB
else if TSpeedButton(Sender).Caption = var_GrdC then lsScore := var_ScrC
else if TSpeedButton(Sender).Caption = var_GrdD then lsScore := var_ScrD else lsScore := '0';
// 버튼이 눌려지면 SG_HiddenData에 변경된 값과 변경여부를 'Y'로 고친다.
if TSpeedButton(Sender).Down = True then
begin
SG_HiddenData2.Cells[7, SG_HiddenData2.Tag+SG_Image2.Row] := lsScore;
SG_Score2.Cells[0, SG_Image2.Row]:= '';
SG_Score2.Cells[1, SG_Image2.Row]:= '';
SG_Score2.Cells[2, SG_Image2.Row]:= '';
SG_Score2.Cells[3, SG_Image2.Row]:= '';
SG_Score2.Cells[4, SG_Image2.Row]:= '';
if SB_S2.Down then SG_Score2.Cells[0, SG_Image2.Row]:= var_GrdS
else if SB_A2.Down then SG_Score2.Cells[1, SG_Image2.Row]:= var_GrdA
else if SB_B2.Down then SG_Score2.Cells[2, SG_Image2.Row]:= var_GrdB
else if SB_C2.Down then SG_Score2.Cells[3, SG_Image2.Row]:= var_GrdC
else SG_Score2.Cells[4, SG_Image2.Row]:= var_GrdD ;
end else
begin
SG_HiddenData2.Cells[7, SG_HiddenData2.Tag+SG_Image2.Row] := '';
SG_Score2.Cells[0 , SG_Image1.Row] := '';
SG_Score2.Cells[1 , SG_Image1.Row] := '';
SG_Score2.Cells[2 , SG_Image1.Row] := '';
SG_Score2.Cells[3 , SG_Image1.Row] := '';
SG_Score2.Cells[4 , SG_Image1.Row] := '';
end;
ShowSum2;
end;
procedure TFM_Main.SG_Score2DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
liLeft : integer;
liTop : integer;
lsBuffer : String;
i : Integer;
begin
SG_Score2.Canvas.Brush.Color := SG_Image2.Color; ///$00F0FFFF;
for i := 0 to SG_Score2.ColCount -1 do
if SG_Score2.Cells[i, ARow] <> '' then
begin
SG_Score2.Canvas.Brush.Color := $00FFF9EC; //SG_Score.Font.Color;
break;
end;
if CB_ShowClass2.Checked then // 등급을 보이게...
SG_Score2.Canvas.Font.Color := SG_Image2.Font.Color
else
SG_Score2.Canvas.Font.Color := SG_Score2.Font.Color;
SG_Score2.Canvas.FillRect(Rect); // cell의 영역을 그린다
lsBuffer := SG_Score2.Cells[ACol, ARow];
liLeft := (((Rect.Right - Rect.Left)
- SG_Score2.Canvas.TextWidth(lsBuffer)) div 2) + Rect.Left;
liTop := (((Rect.Bottom - Rect.Top)
- SG_Score2.Canvas.TextHeight(lsBuffer)) div 2) + Rect.Top;
SG_Score2.Canvas.TextOut(liLeft, liTop, lsBuffer);
end;
procedure TFM_Main.PageControl1Enter(Sender: TObject);
begin
SG_Image1.SetFocus;
end;
procedure TFM_Main.SG_Score2Enter(Sender: TObject);
begin
SG_Image2.SetFocus;
end;
procedure TFM_Main.CB_ShowClass2Click(Sender: TObject);
begin
SG_Score2.Refresh;
end;
end.
|
unit Vigilante.DataSet.Build;
interface
uses
System.Classes, System.Generics.Collections, Data.DB, FireDac.Comp.Client,
Vigilante.Build.Model, Vigilante.ChangeSetItem.Model, Vigilante.Aplicacao.SituacaoBuild,
Module.DataSet.VigilanteBase, Module.ValueObject.URL;
type
TBuildDataSet = class(TVigilanteDataSetBase<IBuildModel>)
private
FBuildAtual: TField;
FUltimoBuildFalha: TField;
FUltimoBuildSucesso: TField;
FURLUltimoBuild: TField;
function GetUltimoBuild: integer;
function GetUltimoBuildFalha: integer;
function GetUltimoBuildSucesso: integer;
function GetURLUltimoBuild: IURL;
protected
procedure MapearCampos; override;
procedure CriarCampos; override;
procedure ImportarDetalhes(const AModel: IBuildModel); override;
public
procedure ApenasAtualizaveis(const AFiltrar: boolean = true);
procedure CreateDataSet; override;
function ExportarRegistro: IBuildModel; override;
property UltimoBuild: integer read GetUltimoBuild;
property URLUltimoBuild: IURL read GetURLUltimoBuild;
property UltimoBuildSucesso: integer read GetUltimoBuildSucesso;
property UltimoBuildFalha: integer read GetUltimoBuildFalha;
end;
implementation
uses
System.SysUtils, Module.ValueObject.URL.Impl, Vigilante.Build.Model.Impl;
procedure TBuildDataSet.CriarCampos;
begin
inherited;
FieldDefs.Add('BuildAtual', ftInteger);
FieldDefs.Add('UltimoBuildSucesso', ftInteger);
FieldDefs.Add('UltimoBuildFalha', ftInteger);
FieldDefs.Add('URLUltimoBuild', ftString, 500);
end;
function TBuildDataSet.ExportarRegistro: IBuildModel;
begin
Result := TBuildModel.Create(Nome, URL, Situacao, Building,
FBuildAtual.AsInteger, UltimoBuildFalha, UltimoBuildSucesso,
URLUltimoBuild);
Result.DefinirID(ID);
end;
procedure TBuildDataSet.CreateDataSet;
begin
inherited;
ConfigurarCampos;
LogChanges := False;
end;
procedure TBuildDataSet.MapearCampos;
begin
inherited;
FBuildAtual := FindField('BuildAtual');
FUltimoBuildSucesso := FindField('UltimoBuildSucesso');
FUltimoBuildFalha := FindField('UltimoBuildFalha');
FURLUltimoBuild := FindField('URLUltimoBuild');
end;
procedure TBuildDataSet.ImportarDetalhes(const AModel: IBuildModel);
begin
inherited;
FBuildAtual.AsInteger := AModel.BuildAtual;
FUltimoBuildSucesso.AsInteger := AModel.UltimoBuildSucesso;
FUltimoBuildFalha.AsInteger := AModel.UltimoBuildFalha;
FURLUltimoBuild.AsString := AModel.URLUltimoBuild.AsString;
end;
procedure TBuildDataSet.ApenasAtualizaveis(const AFiltrar: boolean);
begin
Filtered := AFiltrar;
Filter := 'Atualizar = True or Atualizar is null';
if not AFiltrar then
Filter := EmptyStr;
end;
function TBuildDataSet.GetUltimoBuild: integer;
begin
Result := FBuildAtual.AsInteger;
end;
function TBuildDataSet.GetUltimoBuildFalha: integer;
begin
Result := FUltimoBuildFalha.AsInteger;
end;
function TBuildDataSet.GetUltimoBuildSucesso: integer;
begin
Result := FUltimoBuildSucesso.AsInteger;
end;
function TBuildDataSet.GetURLUltimoBuild: IURL;
begin
Result := TURL.Create(FURLUltimoBuild.AsString);
end;
end.
|
PROGRAM Frontier;
USES
CRT {ClrScr},
FileOps,
Lists;
CONST
fname = 'fx.prn';
delims = ' ,'; {space, comma}
AssetCount = 4; {At most one less than Max Assets to allow for portfolio }
Annualize = 7.21102551; { sqrt(52) - weekly data}
Precision = 10; { possible allocation shifts }
USYld = 9.00;
VAR
iter : integer;
heap : POINTER;
YldSeries,
WgtSeries,
TimeSeries : List;
avg,
vol,
wgt,
std : Item;
OptVol : REAL;
out : TEXT;
(* ---------------------------------------------------- *)
PROCEDURE WriteHeader;
BEGIN
GotoXY(1,3);
writeln(' Asset Weights');
writeln('Term 1 2 3 4 slope yield vol.');
writeln('-----------------------------------------------------------------------');
END;
(* ---------------------------------------------------- *)
PROCEDURE SetUpAccumulators;
VAR
n : INTEGER;
BEGIN
iter := 0;
FOR n := 1 TO MaxItems DO
BEGIN
Avg[n] := 0;
Std[n] := 0;
Wgt[n] := 0;
Vol[n] := 0;
END;
END;
(* ---------------------------------------------------- *)
PROCEDURE PeriodReturn(VAR list : Item; Before, Now : Item);
VAR
n : INTEGER;
BEGIN
FOR n := 1 TO AssetCount DO
list[n] := ln(Now[n]/Before[n]);
END;
(* ---------------------------------------------------- *)
FUNCTION SumWgts(wgts : Item) : REAL;
VAR
n : INTEGER;
total : REAL;
BEGIN
total := 0;
FOR n := 1 TO AssetCount DO
total := total + wgts[n];
SumWgts := total;
END {SumWgts};
(* ---------------------------------------------------- *)
PROCEDURE ShowNums(nums : Item);
VAR
n : INTEGER;
total : REAL;
BEGIN
FOR n := 1 TO AssetCount + 1 DO
Write(out,nums[n]:10:5);
END {ShowNums};
(* ---------------------------------------------------- *)
PROCEDURE AvgOneSeries(VAR a : Item;
VAR Series : List;
Asset : INTEGER);
VAR
count : INTEGER;
Data : Item;
BEGIN
a[Asset] := 0;
count := 0;
WHILE Series.GetNext(Data) DO
BEGIN
a[Asset] := a[Asset] + Data[Asset];
inc(count);
END;
a[Asset] := a[Asset] / count;
END;
(* ---------------------------------------------------- *)
PROCEDURE StdOneSeries(VAR s, a : Item;
VAR Series : List;
Asset : INTEGER);
VAR
count : INTEGER;
Data : Item;
BEGIN
s[Asset] := 0;
count := 0;
WHILE Series.GetNext(Data) DO
BEGIN
s[Asset] := s[Asset] + sqr(Data[Asset] - a[Asset]);
inc(count);
END;
s[Asset] := sqrt(s[Asset] / (count{-1}) );
END;
(* ---------------------------------------------------- *)
PROCEDURE VolOneSeries(VAR v, s : Item; Asset : INTEGER);
BEGIN
v[Asset] := s[Asset] * annualize;
END;
(* ---------------------------------------------------- *)
PROCEDURE PortVol(VAR Series : List; wgt : Item);
VAR
Data : Item;
i, Port : INTEGER;
count : INTEGER;
BEGIN
Port := AssetCount + 1;
WHILE Series.GetNext(Data) DO
BEGIN
Data[Port] := 0;
FOR i := 1 TO AssetCount DO
{ compute portfolio return }
Data[Port] := Data[Port] + wgt[i] * Data[i];
Series.ChangeCurrItem(Data);
END;
AvgOneSeries(avg,Series,Port);
StdOneSeries(std,avg,Series,Port);
VolOneSeries(vol,std, Port);
END;
(* =============================================== *)
FUNCTION PortYld(VAR Yield, wgt : Item) : REAL;
VAR
i, Port : INTEGER;
BEGIN
Port := AssetCount + 1;
Yield[Port] := 0;
FOR i := 1 TO AssetCount DO
BEGIN
{ compute portfolio yield }
Yield[Port] := Yield[Port] + wgt[i] * Yield[i];
END;
PortYld := Yield[Port];
END;
(* =============================================== *)
PROCEDURE TestFrontier(wgt : Item);
{ note: weight[AssetCount + 1] carries slope info }
CONST
PrintLine = 5;
VAR
count : INTEGER;
slope : REAL;
weight,
yield : Item;
{$B+} { Force complete BOOLEAN evaluation }
BEGIN
count := 0;
WHILE YldSeries.GetNext(yield) AND
WgtSeries.GetNext(weight) DO
BEGIN
inc(count);
slope := (PortYld(yield,wgt) - USYld) / Vol[AssetCount+ 1];
IF slope > weight[AssetCount+ 1] THEN
BEGIN
wgt[AssetCount + 1] := slope;
WgtSeries.ChangeCurrItem(wgt);
OptVol := Vol[AssetCount+ 1];
{ display progress }
IF count > 0 THEN { one year term}
BEGIN
GotoXY(1,PrintLine+Count);
write(out, 'Term ',count);
ShowNums(wgt);
write(out,Portyld(yield,wgt):8:3);
writeln(out,OptVol*100:5:2);
END;
END;
END;
END;
{$B-} { turn off complete BOOLEAN evaluation }
(* ---------------------------------------------------- *)
PROCEDURE Permute( VAR Series : LIST;
VAR wgt : Item;
Asset : INTEGER);
VAR
i : INTEGER;
BEGIN
FOR i := 0 to Precision DO
BEGIN
wgt[Asset] := i / Precision;
IF Asset = AssetCount THEN BEGIN
IF abs(SumWgts(wgt) - 1) < 0.00001 THEN BEGIN
iter := iter + 1;
IF (iter MOD 25 = 0) THEN BEGIN
GotoXY(1,2); Write(iter,' Permutations');
END;
PortVol(Series,wgt);
{ ShowNums(wgt); writeln(out,Vol[AssetCount+ 1]*100:7:3); }
{ keep track of lowest vol }
TestFrontier(wgt);
END;
END
ELSE
Permute(Series,wgt,Asset+1)
END;
END {Permute};
(* ---------------------------------------------------- *)
PROCEDURE AvgSeries(VAR a : Item; VAR Series : List);
VAR
i, count : INTEGER;
Data : Item;
BEGIN
FOR i := 1 TO AssetCount DO
a[i] := 0;
count := 0;
WHILE Series.GetNext(Data) DO
BEGIN
FOR i := 1 TO AssetCount DO
a[i] := a[i] + Data[i];
inc(count);
END;
FOR i := 1 TO AssetCount DO
a[i] := a[i] / count;
END;
(* --------------------------------------------------- *)
PROCEDURE StdSeries(VAR s, a : Item; VAR Series : List);
VAR
i, count : INTEGER;
Data : Item;
BEGIN
count := 0;
FOR i := 1 TO AssetCount DO
s[i] := 0;
WHILE Series.GetNext(Data) DO
BEGIN
FOR i := 1 TO AssetCount DO
s[i] := s[i] + sqr(Data[i] - a[i]);
inc(count);
END;
FOR i := 1 TO AssetCount DO
std[i] := sqrt(s[i] / (count{-1}) );
END;
(* ---------------------------------------------------- *)
PROCEDURE VolSeries(VAR v, s : Item);
VAR
i : INTEGER;
BEGIN
FOR i := 1 TO AssetCount DO
v[i] := s[i] * annualize;
END;
(* ---------------------------------------------------- *)
PROCEDURE ShowSeries(Series : List);
VAR
i : INTEGER;
Data : Item;
BEGIN
WHILE Series.GetNext(Data) DO
BEGIN
FOR i := 1 TO AssetCount DO
write(out,Data[i]:10:6);
writeln(out);
END;
END;
(* ---------------------------------------------------- *)
FUNCTION ParseNums( VAR list : Item;
line : STRING; NumsToGet : INTEGER) : INTEGER;
(* returns number of numbers parsed *)
VAR
i, start, stop,
Got, err : INTEGER;
numstr : STRING;
num : Real;
BEGIN
i := 1;
Got := 0;
REPEAT
WHILE (pos(line[i],delims) > 0) AND (i < length(line)) DO
inc(i);
IF i < length(line) THEN
BEGIN
Start := i;
WHILE (pos(line[i],delims) = 0) AND (i < length(line)+1) DO
inc(i);
Stop := i;
val(copy(line,start,stop-start),num,err);
IF err = 0 THEN
BEGIN
inc(Got);
list[Got] := num;
END;
END;
UNTIL (i > length(line)) OR (Got = NumsToGet);
ParseNums := Got;
END;
(* ---------------------------------------------------- *)
PROCEDURE GetData;
VAR
infile : text;
line : string;
Data : Item;
OldList,
list : Item;
First : BOOLEAN;
(* ---------------------------------------------------- *)
FUNCTION OpenFile : BOOLEAN;
BEGIN
IF Exist(fname) THEN
BEGIN
assign(infile,fname);
reset(infile);
OpenFile := TRUE;
END
ELSE
OpenFile := FALSE;
END {OpenFile};
(* ---------------------------------------------------- *)
PROCEDURE GetYields;
{expects a series of national yields, US last }
VAR
ylds : Item;
BEGIN
REPEAT
readln(infile,line);
IF (line[1] = ';') AND (pos('yield',line)>0) THEN
BEGIN
GotoXY(1,2); writeln(line);
readln(infile,line);
IF ParseNums(ylds, line, AssetCount+1) = AssetCount + 1 THEN
BEGIN
YldSeries.AddItem(ylds);
WgtSeries.AddItem(ylds); {dummy data}
END;
END;
UNTIL (pos('fx',line) > 0) OR eof(infile);
END;
(* ---------------------------------------------------- *)
BEGIN
First := TRUE;
TimeSeries.Init;
YldSeries.Init;
WgtSeries.Init;
IF OpenFile THEN
BEGIN
GetYields;
WHILE NOT eof(infile) DO
BEGIN
readln(infile,line);
IF (line[1] = ';') THEN { it's a comment }
writeln(line)
ELSE
BEGIN
IF ParseNums(list, line, AssetCount) = AssetCount THEN
IF First THEN BEGIN
First := FALSE;
OldList := list;
END
ELSE BEGIN
PeriodReturn(Data,OldList,List);
TimeSeries.AddItem(Data);
OldList := List;
END;
END;
END;
END;
END {GetData};
(* ------------------------------------------------------------- *)
BEGIN
DirectOutput(out); ClrScr;
WriteHeader;
SetupAccumulators;
GotoXY(1,1); Writeln('Getting data');
GetData;
{ ShowSeries(TimeSeries); }
(*
AvgSeries(avg,TimeSeries);
StdSeries(std,avg,TimeSeries);
VolSeries(vol, std);
ShowNums(vol); writeln(out);
ShowNums(avg); writeln(out);
*)
GotoXY(1,1);Writeln('Testing Combos');
Permute(TimeSeries,wgt,1);
GotoXY(1,2); writeln(iter,' Permutations');
GotoXY(1,1); ClrEOL; writeln('Done');
TimeSeries.Done;
YldSeries.Done;
WgtSeries.Done;
close(out);
END.
|
{Sieve of Eratosthenes – finding out all prime numbers up to N
This Pascal program finds out all the prime numbers up to a number N, by using a very efficient algorithm called The Sieve of Eratosthenes.
How it works in short is that it goes through each number up to N, and if that number is prime, it marks all of its multiples as not prime.
Thus, only the prime numbers are left unmarked and easy to recognize.}
const max_number = 2000000;
var n,i,j:longint;
is_prime:array[2..max_number] of boolean;
begin
writeln('This program finds out all prime numbers up to a number n, by using the Sieve of Eratosthenes');
write('n='); readln(n);
{we first initialize the boolean array, marking all number as potential primes}
for i := 2 to n do is_prime[i] := true;
{after initializing, we apply the sieve}
for i := 2 to n do
begin
if (is_prime[i]) then
begin
write(i,' ');
for j := 2 to trunc(n div i) do is_prime[i*j] := false; {this for loop marks all multiples up to n as being not prime}
end;
end;
end.
|
unit BufferInterpreter.ATA;
interface
uses
SysUtils,
BufferInterpreter, Device.SMART.List;
type
TATABufferInterpreter = class sealed(TBufferInterpreter)
public
function BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult; override;
function BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList; override;
function BufferToSMARTThresholdValueList(
const Buffer: TSmallBuffer): TSMARTValueList;
function LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult; override;
function LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList; override;
private
SMARTValueList: TSMARTValueList;
BufferInterpreting: TSmallBuffer;
function GetFirmwareFromBuffer: String;
function GetLBASizeFromBuffer: Cardinal;
function GetModelFromBuffer: String;
function GetSATASpeedFromBuffer: TSATASpeed;
function GetSerialFromBuffer: String;
function GetUserSizeInKBFromBuffer: UInt64;
function GetCurrentOfRow(CurrentRowStart: Integer): Byte;
function GetIDOfRow(CurrentRowStart: Integer): Byte;
function GetRAWOfRow(CurrentRowStart: Integer): UInt64;
function GetWorstOfRow(CurrentRowStart: Integer): Byte;
function GetThresholdOfRow(CurrentRowStart: Integer): Byte;
function IfValidSMARTAddToList(CurrentRow: Integer): Boolean;
procedure IfValidSMARTThresholdAddToList(CurrentRow: Integer);
function GetRotationRateFromBuffer: TRotationRate;
function GetDataSetManagementSupported: Boolean;
end;
implementation
{ TATABufferInterpreter }
function TATABufferInterpreter.GetIDOfRow
(CurrentRowStart: Integer): Byte;
begin
result := BufferInterpreting[CurrentRowStart];
end;
function TATABufferInterpreter.GetCurrentOfRow
(CurrentRowStart: Integer): Byte;
const
CurrentValuePosition = 3;
begin
result := BufferInterpreting[CurrentRowStart + CurrentValuePosition];
end;
function TATABufferInterpreter.GetWorstOfRow
(CurrentRowStart: Integer): Byte;
const
WorstValuePosition = 4;
begin
result := BufferInterpreting[CurrentRowStart + WorstValuePosition];
end;
function TATABufferInterpreter.GetThresholdOfRow
(CurrentRowStart: Integer): Byte;
const
ThresholdValuePosition = 1;
begin
result := BufferInterpreting[CurrentRowStart + ThresholdValuePosition];
end;
function TATABufferInterpreter.GetRAWOfRow
(CurrentRowStart: Integer): UInt64;
const
RAWValueStart = 5;
RAWValueLength = 6;
var
RAWStart, RAWEnd: Integer;
CurrentRAW: Integer;
begin
RAWStart := CurrentRowStart + RAWValueStart;
RAWEnd := RAWStart + RAWValueLength - 1;
result := 0;
for CurrentRAW := RAWEnd downto RAWStart do
begin
result := result shl 8;
result :=
result +
BufferInterpreting[CurrentRAW];
end;
end;
procedure TATABufferInterpreter.IfValidSMARTThresholdAddToList(
CurrentRow: Integer);
var
SMARTValueEntry: TSMARTValueEntry;
begin
SMARTValueEntry.ID := GetIDOfRow(CurrentRow);
if SMARTValueEntry.ID = 0 then
exit;
SMARTValueEntry.Threshold := GetThresholdOfRow(CurrentRow);
SMARTValueList.Add(SMARTValueEntry);
end;
function TATABufferInterpreter.IfValidSMARTAddToList(
CurrentRow: Integer): Boolean;
var
SMARTValueEntry: TSMARTValueEntry;
begin
SMARTValueEntry.ID := GetIDOfRow(CurrentRow);
if SMARTValueEntry.ID = 0 then
exit(false);
SMARTValueEntry.Current := GetCurrentOfRow(CurrentRow);
SMARTValueEntry.Worst := GetWorstOfRow(CurrentRow);
SMARTValueEntry.RAW := GetRAWOfRow(CurrentRow);
SMARTValueEntry.Threshold := 0;
SMARTValueList.Add(SMARTValueEntry);
result := true;
end;
function TATABufferInterpreter.LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult;
var
SmallBuffer: TSmallBuffer;
begin
Move(Buffer, SmallBuffer, SizeOf(SmallBuffer));
result := BufferToIdentifyDeviceResult(SmallBuffer);
end;
function TATABufferInterpreter.LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
var
SmallBuffer: TSmallBuffer;
begin
Move(Buffer, SmallBuffer, SizeOf(SmallBuffer));
result := BufferToSMARTValueList(SmallBuffer);
end;
function TATABufferInterpreter.BufferToSMARTThresholdValueList(
const Buffer: TSmallBuffer): TSMARTValueList;
const
SMARTStartPadding = 2;
SMARTValueLength = 12;
var
CurrentRow: Integer;
begin
SMARTValueList := TSMARTValueList.Create;
BufferInterpreting := Buffer;
for CurrentRow := 0 to
(Length(BufferInterpreting) - SMARTStartPadding) div SMARTValueLength do
IfValidSMARTThresholdAddToList(
(CurrentRow * SMARTValueLength) + SMARTStartPadding);
result := SMARTValueList;
end;
function TATABufferInterpreter.BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList;
const
SMARTStartPadding = 2;
SMARTValueLength = 12;
function CalculateRow(const CurrentRow: Integer): Integer;
begin
result := (CurrentRow * SMARTValueLength) + SMARTStartPadding;
end;
var
CurrentRow: Integer;
MaxRow: Integer;
begin
SMARTValueList := TSMARTValueList.Create;
BufferInterpreting := Buffer;
MaxRow :=
(Length(BufferInterpreting) - SMARTStartPadding) div SMARTValueLength;
for CurrentRow := 0 to MaxRow do
if not IfValidSMARTAddToList(CalculateRow(CurrentRow)) then
break;
result := SMARTValueList;
end;
function TATABufferInterpreter.GetModelFromBuffer: String;
const
ModelStart = 27;
ModelEnd = 46;
var
CurrentWord: Integer;
begin
result := '';
for CurrentWord := ModelStart to ModelEnd do
result :=
result +
Chr(BufferInterpreting[CurrentWord * 2 + 1]) +
Chr(BufferInterpreting[CurrentWord * 2]);
result := Trim(result);
end;
function TATABufferInterpreter.GetFirmwareFromBuffer: String;
const
FirmwareStart = 23;
FirmwareEnd = 26;
var
CurrentWord: Integer;
begin
result := '';
for CurrentWord := FirmwareStart to FirmwareEnd do
result :=
result +
Chr(BufferInterpreting[CurrentWord * 2 + 1]) +
Chr(BufferInterpreting[CurrentWord * 2]);
result := Trim(result);
end;
function TATABufferInterpreter.GetSerialFromBuffer: String;
const
SerialStart = 10;
SerialEnd = 19;
var
CurrentWord: Integer;
begin
result := '';
for CurrentWord := SerialStart to SerialEnd do
result :=
result +
Chr(BufferInterpreting[CurrentWord * 2 + 1]) +
Chr(BufferInterpreting[CurrentWord * 2]);
result := Trim(result);
end;
function TATABufferInterpreter.GetUserSizeInKBFromBuffer: UInt64;
const
UserSizeStart = 100;
UserSizeEnd = 103;
var
CurrentWord: Integer;
begin
result := 0;
for CurrentWord := UserSizeStart to UserSizeEnd do
begin
result :=
result +
BufferInterpreting[CurrentWord * 2] shl
(((CurrentWord - UserSizeStart) * 2) * 8) +
BufferInterpreting[CurrentWord * 2 + 1] shl
((((CurrentWord - UserSizeStart) * 2) + 1) * 8);
end;
result := result div 2;
end;
function TATABufferInterpreter.GetLBASizeFromBuffer: Cardinal;
const
ATA_LBA_SIZE = 512;
begin
result := ATA_LBA_SIZE;
end;
function TATABufferInterpreter.GetSATASpeedFromBuffer: TSATASpeed;
const
SataNegStart = 77;
var
SATASpeedInNum: Cardinal;
begin
SATASpeedInNum := BufferInterpreting[SataNegStart * 2 + 1] +
BufferInterpreting[SataNegStart * 2];
SATASpeedInNum := (SATASpeedInNum shr 1 and 3) + 1;
result := TSATASpeed(SATASpeedInNum);
end;
function TATABufferInterpreter.GetRotationRateFromBuffer: TRotationRate;
const
MajorVersionStart = 80;
RotationRateStart = 217;
begin
result.Supported :=
(BufferInterpreting[MajorVersionStart * 2 + 1] +
BufferInterpreting[MajorVersionStart * 2]) >= 7;
result.Value :=
BufferInterpreting[RotationRateStart * 2 + 1] +
BufferInterpreting[RotationRateStart * 2];
end;
function TATABufferInterpreter.GetDataSetManagementSupported: Boolean;
const
DataSetManagementStart = 169;
begin
result := (BufferInterpreting[DataSetManagementStart * 2] and 1) = 1;
end;
function TATABufferInterpreter.BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult;
begin
BufferInterpreting := Buffer;
result.Model := GetModelFromBuffer;
result.Firmware := GetFirmwareFromBuffer;
result.Serial := GetSerialFromBuffer;
result.UserSizeInKB := GetUserSizeInKBFromBuffer;
result.SATASpeed := GetSATASpeedFromBuffer;
result.LBASize := GetLBASizeFromBuffer;
result.RotationRate := GetRotationRateFromBuffer;
result.IsDataSetManagementSupported :=
GetDataSetManagementSupported;
end;
end.
|
unit AntifakeHelperUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils
,NVSRecordUnit
,BaseTXUnit
,EmerAPIBlockchainUnit
,fpjson
,emerapitypes
;
type
tAFRequestType=(afrtLot,afrtProduct,afrtBrand,afrtRoot,afrtRootCert,afrtParent);
tAFRequest = class;
tAntifakeCallback=procedure (Sender:tAFRequest) of object;
tAFRequest = class(tObject)
private
public
LastError:string;
cNVSName:ansistring; //current
cNVSValue:string; //current
rtype:tAFRequestType;
callback:tAntifakeCallback;
rNVSName:ansistring; //result
rNVSValue:ansistring; //result
rFirstProduct:ansistring; //result
id:string;
finished:boolean;
constructor create(aType:tAFRequestType;aCallback:tAntifakeCallback;aId:ansistring='');
procedure resolve; //next step
procedure AsyncDone(sender:TEmerAPIBlockchainThread;result:tJsonData);
end;
function AFGetProductForObject(obj:ansistring;callback:tAntifakeCallback;id:string=''):boolean; overload;
function AFGetProductForObject(obj:tNVSRecord;callback:tAntifakeCallback;id:string=''):boolean; overload;
function AFGetBrandForObject(obj:ansistring;callback:tAntifakeCallback;id:string=''):boolean; overload;
function AFGetBrandForObject(obj:tBaseTXO;callback:tAntifakeCallback;id:string=''):boolean; overload;
function addNVSValueParameter(const text,name,value:string):string;
function cutNVSValueParameter(text,name:string):string;
function getNVSValueParameter(text,name:string; allowMultyLine:boolean=true):string;
function getTextToSign(name:ansistring;value:string;SignFieldPreffix:string='*'):string;
//function getOwnerForName(name:ansistring):ansistring; //returns code58 address
function unscreenNVSValueParam(s:string):string;
function screenNVSValueParam(s:string):string;
implementation
uses MainUnit
,Localizzzeunit
;
var
AFRequests:tList;
{
function getOwnerForName(name:ansistring):ansistring; //returns code58 address
begin
//looking in the UTXOs first
end;
}
function unscreenNVSValueParam(s:string):string;
var n:integer;
sl:boolean;
begin
result:=s;
n:=1; sl:=false;
while n<=length(result) do
if sl then begin
case result[n] of
'n':result[n]:=#10;
end;
inc(n);
end else if result[n]='\' then begin sl:=true; delete(result,n,1); end else inc(n);
end;
function screenNVSValueParam(s:string):string;
var n:integer;
begin
result:=s;
n:=1;
while n<=length(result) do
if result[n]='\' then begin
result:=copy(result,1,n-1)+'\'+copy(result,n,length(result)-n+1);
inc(n);inc(n);
end else inc(n);
n:=pos(#13#10,result);
while n>0 do begin
result:=copy(result,1,n-1)+'\n'+copy(result,n+2,length(result)-n-1);
n:=pos(#13#10,result);
end;
n:=pos(#10,result);
while n>0 do begin
result:=copy(result,1,n-1)+'\n'+copy(result,n+1,length(result)-n);
n:=pos(#10,result);
end;
end;
function getPrefix(name:string):ansistring;
var //s:ansistring;
n:integer;
begin
result:='';
n:=pos(':',name);
if n<1 then exit;
result:=copy(name,1,n-1);
if result<>'af' then exit; //not chain
delete(name,1,n);
n:=pos(':',name);
if n<1 then exit;
result:=result+':' + copy(name,1,n-1);
end;
function getTextToSign(name:ansistring;value:string;SignFieldPreffix:string='*'):string;
var s:string;
n:integer;
begin
result:=trim(name)+#10;
n:=pos(#10,value);
while n>0 do begin
s:=copy(value,1,n-1);
delete(value,1,n);
if (length(s)>0) and (s[length(s)]=#13) then delete(s,length(s),1);
//if (pos(name+'=',s)=1) or (pos('*'+name+'=',s)=1) then begin
if (pos('=',s)>1) and (pos(SignFieldPreffix,s)=1) then begin
result:=result+s+#10;
end;
n:=pos(#10,value);
end;
if (length(result)>0) then delete(result,length(result),1); //cut last #10
end;
function addNVSValueParameter(const text,name,value:string):string;
begin
result:=text;
if (length(result)>0) and (result[length(result)]<>#10) then result:=result+#10;
result:=result+name+'='+screenNVSValueParam(value);
end;
function cutNVSValueParameter(text,name:string):string;
var s:string;
n:integer;
begin
//extract *XXXX= or XXX= parameter. Multiline is possible
result:='';
n:=pos(#10,text);
while n>0 do begin
//s:=copy(text,1,n-1);
s:=copy(text,1,n);
delete(text,1,n);
if (pos(name+'=',s)=1) or (pos('*'+name+'=',s)=1) then begin
//if (length(s)>0) and (s[length(s)]=#13) then delete(s,length(s),1);
//found
end else result:=result+s;
n:=pos(#10,text);
end;
end;
function getNVSValueParameter(text,name:string; allowMultyLine:boolean=true):string;
var s:string;
n:integer;
begin
//extract *XXXX= or XXX= parameter. Multiline is possible
result:='';
n:=pos(#10,text);
while n>0 do begin
s:=copy(text,1,n-1);
delete(text,1,n);
if (length(s)>0) and (s[length(s)]=#13) then delete(s,length(s),1);
if (pos(name+'=',s)=1) or (pos('*'+name+'=',s)=1) then begin
if s[1]='*' then delete(s,1,1);
delete(s,1,length(name)+1);
if result<>'' then result:=result+#10;
result:=result+s;
if not allowMultyLine then exit;
end;
n:=pos(#10,text);
end;
end;
procedure cleanupRequests;
var i:integer;
begin
//free finished requests
i:=0;
while i<AFRequests.Count do
if tAFRequest(AFRequests[i]).finished then begin
tAFRequest(AFRequests[i]).Free;
AFRequests.Delete(i);
end else inc(i);
end;
function AFGetProductForObject(obj:ansistring;callback:tAntifakeCallback;id:string=''):boolean;
begin
end;
function AFGetProductForObject(obj:tNVSRecord;callback:tAntifakeCallback;id:string=''):boolean;
begin
end;
function AFGetBrandForObject(obj:ansistring;callback:tAntifakeCallback;id:string=''):boolean;
begin
end;
function AFGetBrandForObject(obj:tBaseTXO;callback:tAntifakeCallback;id:string=''):boolean;
var r:tAFRequest;
begin
r:=tAFRequest.Create(afrtBrand,callback,id);
AFRequests.Add(r);
r.cNVSName:=obj.getNVSname;
r.cNVSValue:=obj.getNVSValue;
r.resolve;
cleanupRequests;
end;
//tAFRequest
constructor tAFRequest.create(aType:tAFRequestType;aCallback:tAntifakeCallback;aId:ansistring='');
begin
finished := false;
rType:=aType;
callback:=aCallback;
rNVSName:='';
rNVSValue:='';
rFirstProduct:='';
id:=aId;
end;
procedure tAFRequest.resolve;
var s:string;
begin
//set finished and call callback if finished
//afrtLot,afrtProduct,afrtBrand,afrtRoot,afrtRootCert,afrtParent
case rtype of
afrtBrand:begin
//brand. PARENTLOT -> PRODUCT -> BRAND
if cNVSName='' then begin
//erroneous
finished:=true;
LastError:='cNVSName=''''';
callback(self);
end else if cNVSValue='' then begin
//we should request value
emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+cNVSName+'"}'),@(AsyncDone),'getname:'+cNVSName);
end else if getPrefix(cNVSName)='af:lot' then begin
//lot. Requset PARENTLOT if have; PRODUCT overwise
s:=getNVSValueParameter(cNVSValue,'PARENTLOT');
if s<>'' then emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
else begin
s:=getNVSValueParameter(cNVSValue,'PRODUCT'); if rFirstProduct='' then rFirstProduct:=s;
if s<>'' then emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
else begin
s:=getNVSValueParameter(cNVSValue,'PARENT');
if s<>'' then emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
else begin
finished:=true;
LastError:= localizzzeString('AFCreateForPrintingForm.tAFRequest.CantResolve','tAFRequest.resolve: afrtBrand: resolving path not found for lot: ')+'"'+cNVSName+'"';
callback(self);
end;
end;
end;
end else if getPrefix(cNVSName)='af:product' then begin
//PRODUCT -> BRAND
//1. Check if BRAND field defined
//2. overwise check if PRODUCT defined (parent product)
//3. overwise chekc ParengetTextToSign(t. It could be a product or brand
//s:=getNVSValueParameter(cNVSValue,'BRAND');
s:=getNVSValueParameter(cNVSValue,'BRAND');
if s<>'' then begin
finished:=true;
rNVSName:=s;
rNVSValue:='';
callback(self);
end else begin
s:=getNVSValueParameter(cNVSValue,'PRODUCT');
if s<>'' then begin
emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
end else begin
s:=getNVSValueParameter(cNVSValue,'PARENT');
if getPrefix(s)='dpo' then begin
//it is a brand!
finished:=true;
rNVSName:=s;
rNVSValue:='';
callback(self);
end else if getPrefix(s)='af:product' then begin
emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
end else begin
finished:=true;
//LastError:='tAFRequest.resolve: afrtBrand: resolving path not found for lot "'+cNVSName+'"'; !
LastError:= localizzzeString('AFCreateForPrintingForm.tAFRequest.CantResolve','tAFRequest.resolve: afrtBrand: resolving path not found for lot: ')+'"'+cNVSName+'"';
callback(self);
end;
end;
end;
if s<>'' then emerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+s+'"}'),@(AsyncDone),'getname:'+s)
else begin
finished:=true;
//LastError:='tAFRequest.resolve: afrtBrand: resolving path not found for product "'+cNVSName+'"'; !
LastError:= localizzzeString('AFCreateForPrintingForm.tAFRequest.CantResolve','tAFRequest.resolve: afrtBrand: resolving path not found for lot: ')+'"'+cNVSName+'"';
callback(self);
end;
// end else if getPrefix(cNVSValue)='dpo' then begin
end else begin
//erroneous
finished:=true;
LastError:='tAFRequest.resolve: unknow situation for afrtBrand';
callback(self);
end;
end
else
raise exception.Create('tAFRequest.resolve: type '+inttostr(integer(rtype))+' not supported yet');
end;
end;
procedure tAFRequest.AsyncDone(sender:TEmerAPIBlockchainThread;result:tJsonData);
var e:tJsonData;
function safeString(e:tJsonData):string;
begin
if e<>nil then
if e.IsNull
then result:=''
else result:=e.asString
else result:='';
end;
begin
//if sender.id=('getname:'+trim(lastRequestedNVSname)) then begin
if pos('getname:',sender.id)=1 then begin
e:=result.FindPath('result');
if e<>nil then
if e.IsNull then begin
//name is free :-/
finished:=true;
LastError:='tAFRequest: name not found:"'+sender.id+'"';
callback(self);
end else
try
//name exists!
cNVSName:=safeString(e.FindPath('name'));
cNVSValue:=safeString(e.FindPath('value'));
if (cNVSName='') or (cNVSValue='') then begin
finished:=true;
LastError:='tAFRequest: incorrect name data in: '+result.AsJSON+' tag:'+sender.id;
callback(self);
end else resolve;
except
on e:exception do begin
finished:=true;
LastError:='tAFRequest: resolving exception "'+e.message+'" in: '+result.AsJSON+' tag:'+sender.id;
callback(self);
end;
end
else begin
finished:=true;
LastError:='tAFRequest: can''t find result in: '+result.AsJSON+' tag:'+sender.id;
callback(self);
end;
end else begin
finished:=true;
LastError:='tAFRequest: unknown tag in: '+result.AsJSON+' tag:'+sender.id;
callback(self);
end;
end;
initialization
AFRequests:=tList.create;
finalization
while AFRequests.count>0 do begin
tAFRequest(AFRequests[0]).free;
AFRequests.delete(0);
end;
AFRequests.free;
end.
|
(*
** $Id: lua.pas,v 1.3 2006/11/17 00:02:17 jfgoulet Exp $
** Lua - An Extensible Extension Language
** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
** See Copyright Notice at the end of this file
**
** Translation form C and Delphi adaptation of Code :
** Massimo Magnano, Jean-Francois Goulet 2006
*)
unit lua;
{$IFNDEF lua_h}
{$DEFINE lua_h}
{$ENDIF}
interface
uses luaconf;
const
LUA_VERSION = 'Lua 5.1';
LUA_RELEASE = 'Lua 5.1.1';
LUA_VERSION_NUM = 501;
LUA_COPYRIGHT = 'Copyright (C) 1994-2006 Lua.org, PUC-Rio';
LUA_AUTHORS = 'R. Ierusalimschy, L. H. de Figueiredo & W. Celes';
// mark for precompiled code (`<esc>Lua')
LUA_SIGNATURE =#33'Lua';
// option for multiple returns in `lua_pcall' and `lua_call'
LUA_MULTRET = -1;
//
// pseudo-indices
//
LUA_REGISTRYINDEX = -10000;
LUA_ENVIRONINDEX = -10001;
LUA_GLOBALSINDEX = -10002;
function lua_upvalueindex(I: Integer): Integer;
const
// thread status; 0 is OK
LUA_YIELD_ = 1; //lua_yield is a function
// error codes for `lua_load' and `lua_pcall'
LUA_ERRRUN = 2;
LUA_ERRSYNTAX = 3;
LUA_ERRMEM = 4;
LUA_ERRERR = 5;
type
//C Types to Delphi Types
size_t = Integer;
Psize_t = ^size_t;
lua_State = record
end;
Plua_State = ^lua_State;
lua_CFunction = function (L: Plua_State): Integer; cdecl;
(*
** functions that read/write blocks when loading/dumping Lua chunks
*)
lua_Reader = function (L: Plua_State; ud: Pointer; sz: Psize_t): PChar;
lua_Writer = function (L: Plua_State; const p: Pointer; sz: size_t; ud: Pointer): Integer;
(*
** prototype for memory-allocation functions
*)
lua_Alloc = function (ud: Pointer; ptr: Pointer; osize: size_t; nsize: size_t): Pointer;
const
(*
** basic types
*)
LUA_TNONE = -1;
LUA_TNIL = 0;
LUA_TBOOLEAN = 1;
LUA_TLIGHTUSERDATA = 2;
LUA_TNUMBER = 3;
LUA_TSTRING = 4;
LUA_TTABLE = 5;
LUA_TFUNCTION = 6;
LUA_TUSERDATA = 7;
LUA_TTHREAD = 8;
// minimum Lua stack available to a C function
LUA_MINSTACK = 20;
(*
** generic extra include file
*)
{$IFDEF LUA_USER_H}
{$INCLUDE} LUA_USER_H
{$ENDIF}
//type
//type of numbers in Lua
//lua_Number = LUA_NUMBER; see LuaConf.pas
// type for integer functions
//lua_Integer = LUA_INTEGER; see LuaConf.pas
(*
** state manipulation
*)
function lua_newstate(f: lua_Alloc; ud :Pointer): Plua_State; cdecl external 'lua.dll';
procedure lua_close(L: Plua_State); cdecl external 'lua.dll';
function lua_newthread(L: Plua_State): Plua_State; cdecl external 'lua.dll';
function lua_atpanic(L: Plua_State; panicf: lua_CFunction): lua_CFunction; cdecl external 'lua.dll';
(*
** basic stack manipulation
*)
function lua_gettop(L: Plua_State): Integer; cdecl external 'lua.dll';
procedure lua_settop(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_pushvalue(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_remove(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_insert(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_replace(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
function lua_checkstack(L: Plua_State; sz: Integer): Integer; cdecl external 'lua.dll';
procedure lua_xmove(_from, _to: Plua_State; n: Integer); cdecl external 'lua.dll';
(*
** access functions (stack -> C)
*)
function lua_isnumber(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_isstring(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_iscfunction(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_isuserdata(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_type(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_typename(L: Plua_State; tp: Integer): PChar; cdecl external 'lua.dll';
function lua_equal(L: Plua_State; idx1, idx2: Integer): Integer; cdecl external 'lua.dll';
function lua_rawequal(L: Plua_State; idx1, idx2: Integer): Integer; cdecl external 'lua.dll';
function lua_lessthan(L: Plua_State; Idx1: Integer; Idx2: Integer): Integer; cdecl external 'lua.dll';
function lua_tonumber(L: Plua_State; idx: Integer): LUA_NUMBER; cdecl external 'lua.dll';
function lua_tointeger(L: Plua_State; idx: Integer): lua_Integer; cdecl external 'lua.dll';
function lua_toboolean(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
function lua_tolstring(L: Plua_State; idx: Integer; len: Psize_t): PChar; cdecl external 'lua.dll';
function lua_objlen(L: Plua_State; idx: Integer): size_t; cdecl external 'lua.dll';
function lua_tocfunction(L: Plua_State; idx: Integer): lua_CFunction; cdecl external 'lua.dll';
function lua_touserdata(L: Plua_State; idx: Integer): Pointer; cdecl external 'lua.dll';
function lua_tothread(L: Plua_State; idx: Integer): Plua_State; cdecl external 'lua.dll';
function lua_topointer(L: Plua_State; idx: Integer): Pointer; cdecl external 'lua.dll';
(*
** push functions (C -> stack)
*)
procedure lua_pushnil(L: Plua_State); cdecl external 'lua.dll';
procedure lua_pushnumber(L: Plua_State; n: LUA_NUMBER); cdecl external 'lua.dll';
procedure lua_pushinteger(L: Plua_State; n: lua_Integer); cdecl external 'lua.dll';
procedure lua_pushlstring(L: Plua_State; const s: PChar; n: size_t); cdecl external 'lua.dll';
procedure lua_pushstring(L: Plua_State; const s: PChar); cdecl external 'lua.dll';
function lua_pushvfstring(L: Plua_State; const fmt: PChar; Argp: Pointer): PChar; cdecl external 'lua.dll';
function lua_pushfstring(L: Plua_State; const Fmt: PChar): PChar; varargs; cdecl external 'lua.dll';
procedure lua_pushcclosure(L: Plua_State; fn: lua_CFunction; n: Integer); cdecl external 'lua.dll';
procedure lua_pushboolean(L: Plua_State; b: Integer); cdecl external 'lua.dll';
procedure lua_pushlightuserdata(L: Plua_State; p: Pointer); cdecl external 'lua.dll';
function lua_pushthread(L: Plua_State): Integer; cdecl external 'lua.dll';
(*
** get functions (Lua -> stack)
*)
procedure lua_gettable(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_getfield(L: Plua_State; idx: Integer; k: PChar); cdecl external 'lua.dll';
procedure lua_rawget(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_rawgeti(L: Plua_State; idx, n: Integer); cdecl external 'lua.dll';
procedure lua_createtable(L: Plua_State; narr, nrec: Integer); cdecl external 'lua.dll';
function lua_newuserdata(L: Plua_State; sz: size_t): Pointer; cdecl external 'lua.dll';
function lua_getmetatable(L: Plua_State; objindex: Integer): Integer; cdecl external 'lua.dll';
procedure lua_getfenv(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
(*
** set functions (stack -> Lua)
*)
procedure lua_settable(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_setfield(L: Plua_State; idx: Integer; k: PChar); cdecl external 'lua.dll';
procedure lua_rawset(L: Plua_State; idx: Integer); cdecl external 'lua.dll';
procedure lua_rawseti(L: Plua_State; idx, n: Integer); cdecl external 'lua.dll';
function lua_setmetatable(L: Plua_State; objindex: Integer): Integer; cdecl external 'lua.dll';
function lua_setfenv(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
(*
** `load' and `call' functions (load and run Lua code)
*)
procedure lua_call(L: Plua_State; nargs, nresults: Integer); cdecl external 'lua.dll';
function lua_pcall(L: Plua_State; nargs, nresults, errfunc: Integer): Integer; cdecl external 'lua.dll';
function lua_cpcall(L: Plua_State; func: lua_CFunction; ud: Pointer): Integer; cdecl external 'lua.dll';
function lua_load(L: Plua_State; reader: lua_Reader; dt: Pointer;
const chunkname: PChar): Integer; cdecl external 'lua.dll';
function lua_dump(L: Plua_State; writer: lua_Writer; data: Pointer): Integer; cdecl external 'lua.dll';
(*
** coroutine functions
*)
function lua_yield(L: Plua_State; nresults: Integer): Integer; cdecl external 'lua.dll';
function lua_resume(L: Plua_State; narg: Integer): Integer; cdecl external 'lua.dll';
function lua_status(L: Plua_State): Integer; cdecl external 'lua.dll';
(*
** garbage-collection functions and options
*)
const
LUA_GCSTOP =0;
LUA_GCRESTART =1;
LUA_GCCOLLECT =2;
LUA_GCCOUNT =3;
LUA_GCCOUNTB =4;
LUA_GCSTEP =5;
LUA_GCSETPAUSE =6;
LUA_GCSETSTEPMUL =7;
function lua_gc(L: Plua_State; what, data: Integer): Integer; cdecl external 'lua.dll';
(*
** miscellaneous functions
*)
function lua_error(L: Plua_State): Integer; cdecl external 'lua.dll';
function lua_next(L: Plua_State; idx: Integer): Integer; cdecl external 'lua.dll';
procedure lua_concat(L: Plua_State; n: Integer); cdecl external 'lua.dll';
function lua_getallocf(L: Plua_State; ud: PPointer): lua_Alloc; cdecl external 'lua.dll';
procedure lua_setallocf(L: Plua_State; f: lua_Alloc; ud: Pointer); cdecl external 'lua.dll';
(*
** ===============================================================
** some useful macros
** ===============================================================
*)
procedure lua_pop(L: Plua_State; n: Integer);
procedure lua_newtable(L: Plua_State);
procedure lua_register(L: Plua_State; const n: PChar; f: lua_CFunction);
procedure lua_pushcfunction(L: Plua_State; f: lua_CFunction);
function lua_strlen(L: Plua_State; i: Integer): Integer;
function lua_isfunction(L: Plua_State; n: Integer): Boolean;
function lua_istable(L: Plua_State; n: Integer): Boolean;
function lua_islightuserdata(L: Plua_State; n: Integer): Boolean;
function lua_isnil(L: Plua_State; n: Integer): Boolean;
function lua_isboolean(L: Plua_State; n: Integer): Boolean;
function lua_isthread(L: Plua_State; n: Integer): Boolean;
function lua_isnone(L: Plua_State; n: Integer): Boolean;
function lua_isnoneornil(L: Plua_State; n: Integer): Boolean;
procedure lua_pushliteral(L: Plua_State; const s: PChar);
procedure lua_setglobal(L: Plua_State; s: PChar);
procedure lua_getglobal(L: Plua_State; s: PChar);
function lua_tostring(L: Plua_State; i: Integer): PChar;
(*
** compatibility macros and functions
*)
function lua_open : Plua_State;
procedure lua_getregistry(L: Plua_State);
function lua_getgccount(L: Plua_State): Integer;
type
lua_Chunkreader = lua_Reader;
lua_Chunkwriter = lua_Writer;
(*
** {======================================================================
** Debug API
** =======================================================================
*)
const
(*
** Event codes
*)
LUA_HOOKCALL = 0;
LUA_HOOKRET = 1;
LUA_HOOKLINE = 2;
LUA_HOOKCOUNT = 3;
LUA_HOOKTAILRET = 4;
(*
** Event masks
*)
LUA_MASKCALL = (1 shl LUA_HOOKCALL);
LUA_MASKRET = (1 shl LUA_HOOKRET);
LUA_MASKLINE = (1 shl LUA_HOOKLINE);
LUA_MASKCOUNT = (1 shl LUA_HOOKCOUNT);
type
lua_Debug = record
event: Integer;
name: PChar; (* (n) *)
namewhat: PChar; (* (n) `global', `local', `field', `method' *)
what: PChar; (* (S) `Lua', `C', `main', `tail' *)
source: PChar; (* (S) *)
currentline: Integer; (* (l) *)
nups: Integer; (* (u) number of upvalues *)
linedefined: Integer; (* (S) *)
short_src: array [0..LUA_IDSIZE - 1] of Char; (* (S) *)
(* private part *)
i_ci: Integer; (* active function *)
end;
Plua_Debug = ^lua_Debug;
// Functions to be called by the debuger in specific events
lua_Hook = procedure (L: Plua_State; ar: Plua_Debug); cdecl;
function lua_getstack(L: Plua_State; level: Integer; ar: Plua_Debug): Integer; cdecl external 'lua.dll';
function lua_getinfo(L: Plua_State; const what: PChar; ar: Plua_Debug): Integer; cdecl external 'lua.dll';
function lua_getlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PChar; cdecl external 'lua.dll';
function lua_setlocal(L: Plua_State; const ar: Plua_Debug; n: Integer): PChar; cdecl external 'lua.dll';
function lua_getupvalue(L: Plua_State; funcindex: Integer; n: Integer): PChar; cdecl external 'lua.dll';
function lua_setupvalue(L: Plua_State; funcindex: Integer; n: Integer): PChar; cdecl external 'lua.dll';
function lua_sethook(L: Plua_State; func: lua_Hook; mask, count: Integer): Integer; cdecl external 'lua.dll';
function lua_gethook(L: Plua_State): lua_Hook; cdecl external 'lua.dll';
function lua_gethookmask(L: Plua_State): Integer; cdecl external 'lua.dll';
function lua_gethookcount(L: Plua_State): Integer; cdecl external 'lua.dll';
implementation
uses SysUtils, lauxlib;
(*
** pseudo-indices
*)
function lua_upvalueindex(I: Integer): Integer;
begin
Result := (LUA_GLOBALSINDEX-i);
end;
(*
** ===============================================================
** some useful macros
** ===============================================================
*)
procedure lua_pop(L: Plua_State; n: Integer);
begin
lua_settop(L, -(n)-1);
end;
procedure lua_newtable(L: Plua_State);
begin
lua_createtable(L, 0, 0);
end;
procedure lua_register(L: Plua_State; const n: PChar; f: lua_CFunction);
begin
lua_pushcfunction(L, f);
lua_setglobal(L, n);
end;
procedure lua_pushcfunction(L: Plua_State; f: lua_CFunction);
begin
lua_pushcclosure(L, f, 0);
end;
function lua_strlen(L: Plua_State; i: Integer): Integer;
begin
Result := lua_objlen(L, i);
end;
function lua_isfunction(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TFUNCTION);
end;
function lua_istable(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TTABLE);
end;
function lua_islightuserdata(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TLIGHTUSERDATA);
end;
function lua_isnil(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TNIL);
end;
function lua_isboolean(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TBOOLEAN);
end;
function lua_isthread(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TTHREAD);
end;
function lua_isnone(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) = LUA_TNONE);
end;
function lua_isnoneornil(L: Plua_State; n: Integer): Boolean;
begin
Result := (lua_type(L, n) <= 0);
end;
procedure lua_pushliteral(L: Plua_State; const s: PChar);
begin
lua_pushlstring(L, s, StrLen(s)(* / sizeof(char) *));
end;
procedure lua_setglobal(L: Plua_State; s: PChar);
begin
lua_setfield(L, LUA_GLOBALSINDEX, s);
end;
procedure lua_getglobal(L: Plua_State; s: PChar);
begin
lua_getfield(L, LUA_GLOBALSINDEX, s);
end;
function lua_tostring(L: Plua_State; i: Integer): PChar;
begin
Result :=lua_tolstring(L, i, nil);
end;
(*
** compatibility macros and functions
*)
function lua_open: Plua_State;
begin
Result :=luaL_newstate;
end;
procedure lua_getregistry(L: Plua_State);
begin
lua_pushvalue(L, LUA_REGISTRYINDEX);
end;
function lua_getgccount(L: Plua_State): Integer;
begin
Result := lua_gc(L, LUA_GCCOUNT, 0);
end;
(* }====================================================================== *)
(******************************************************************************
* Copyright (C) 1994-2006 Lua.org, PUC-Rio. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************)
end.
|
unit Samples.Views.Main;
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.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.ListView, FMX.Layouts, FMX.Objects;
type
THeaderFooterForm = class(TForm)
Header: TToolBar;
Footer: TToolBar;
HeaderLabel: TLabel;
vsbUsers: TVertScrollBox;
btnListar: TButton;
procedure btnListarClick(Sender: TObject);
private
procedure LoadUsers;
end;
var
HeaderFooterForm: THeaderFooterForm;
implementation
{$R *.fmx}
uses Samples.Providers.Frames.User, Samples.Services.User, System.Threading;
procedure THeaderFooterForm.btnListarClick(Sender: TObject);
var
LTask: ITask;
begin
vsbUsers.BeginUpdate;
try
LTask := TTask.Create(
procedure
begin
Self.LoadUsers;
end);
LTask.Start;
finally
vsbUsers.EndUpdate;
end;
end;
procedure THeaderFooterForm.LoadUsers;
var
LFrameUser: TUserFrame;
LService: TUserService;
begin
LService := TUserService.Create(Self);
try
//LService.GetUsersRESTRequest4Delphi;
LService.GetUsersDefault;
while not LService.mtUsers.Eof do
begin
TThread.Synchronize(TThread.Current,
procedure
begin
LFrameUser := TUserFrame.Create(vsbUsers);
LFrameUser.Parent := vsbUsers;
LFrameUser.Name := 'UserFrame' + LService.mtUsers.RecNo.ToString;
LFrameUser.Align := TAlignLayout.Top;
LFrameUser.lblEmail.Text := LService.mtUsers.FieldByName('EMAIL').AsString;
LFrameUser.lblNome.Text := LService.mtUsers.FieldByName('NAME').AsString;
end);
LService.mtUsers.Next;
end;
finally
LService.Free;
end;
end;
end.
|
unit uGMV_VersionInfo;
interface
uses
Classes
, SysUtils
, Windows
;
type
TGMV_VersionInfo = class(TObject)
private
FFileName: string;
FLanguageID: DWord;
FInfo: pointer;
FInfoSize: longint;
procedure SetFileName(Value: string);
procedure OpenFile(FName: string);
procedure Close;
public
constructor Create;
destructor Destroy; override;
function GetKey(const KName: string): string;
end;
const
USEnglish = $040904E4;
vqvFmt = '\StringFileInfo\%8.8x\%s';
function getExeNameVersion: String;
implementation
//sFileName := GetModuleName(HInstance); // returns the Dll name
//sFileName := GetModuleName(0); // returns the Exe name
function getExeNameVersion: String;
begin
with TGMV_VersionInfo.Create do
try
Result := UpperCase(fFileName + ':' + getKey('FileVersion'));
finally
free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
constructor TGMV_VersionInfo.Create;
begin
inherited Create;
FLanguageID := USEnglish;
SetFileName(EmptyStr);
end;
destructor TGMV_VersionInfo.Destroy;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
inherited Destroy;
end;
procedure TGMV_VersionInfo.OpenFile(FName: string);
var
vlen: DWord;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
if Length(FName) <= 0 then
FName := GetModuleName(0); //Application.ExeName;
FInfoSize := GetFileVersionInfoSize(pchar(fname), vlen);
if FInfoSize > 0 then
begin
GetMem(FInfo, FInfoSize);
if not GetFileVersionInfo(pchar(fname), vlen, FInfoSize, FInfo) then
raise Exception.Create('Cannot retrieve Version Information for ' + fname);
end;
end;
procedure TGMV_VersionInfo.SetFileName(Value: string);
begin
FFileName := Value;
if Value = EmptyStr then
FFileName := ExtractFileName(GetModuleName(0));
OpenFile(Value);
end;
procedure TGMV_VersionInfo.Close;
begin
if FInfoSize > 0 then
FreeMem(FInfo, FInfoSize);
FInfoSize := 0;
FFileName := EmptyStr;
end;
function TGMV_VersionInfo.GetKey(const KName: string): string;
var
vptr: pchar;
vlen: DWord;
begin
Result := EmptyStr;
if FInfoSize <= 0 then
exit;
if VerQueryValue(FInfo, pchar(Format(vqvFmt, [FLanguageID, KName])), pointer(vptr), vlen) then
Result := vptr;
end;
end.
|
unit GMMP3;
interface
uses
Windows, Classes;
function GMPlaySound(stream: TMemoryStream; flags: Cardinal): bool; overload;
function GMPlaySound(const fn: string; flags: Cardinal): bool; overload;
function ConvertMp3ToWav(InStream, OutStream: TStream): bool;
implementation
uses
MMSystem, MMReg, MP3Utils, Math, SysUtils;
// ======================================================================
const
CResFileHeader: array [0 .. 7] of cardinal = ($00000000, $00000020, $0000FFFF, $0000FFFF, $00000000, $00000000, $00000000, $00000000);
type
TResEntryHeader = packed record
dwResSize: LongInt; // Size of the pure resource data
dwHdrSize: LongInt; // Size of the header (incl. this)
end;
// Resource type as Z-terminated wide string
// Resource name as Z-terminated wide string
const
CResEntryTrailer: array [0 .. 3] of cardinal = ($00000000, $00000030, $00000000, $00000000);
procedure WriteResourceHeader(Stream: TStream; ResSize: LongInt; const ResName, ResType: string);
var
reh: TResEntryHeader;
rn, rt: WideString;
begin
reh.dwResSize := ResSize;
reh.dwHdrSize := 24 + (Length(ResName) + 1 + Length(ResType) + 1) * 2;
rn := ResName;
rt := ResType;
Stream.WriteBuffer(CResFileHeader, 32);
Stream.WriteBuffer(reh, 8);
Stream.WriteBuffer(rt[1], 2 + 2 * Length(rt));
Stream.WriteBuffer(rn[1], 2 + 2 * Length(rn));
Stream.WriteBuffer(CResEntryTrailer, 16);
end;
// ======================================================================
const
// FOURCC_RIFF = $46464952; { 'RIFF' }
FOURCC_WAVE = $45564157; { 'WAVE' }
FOURCC_fmt = $20746D66; { 'fmt ' }
FOURCC_fact = $74636166; { 'fact' }
FOURCC_data = $61746164; { 'data' }
type
TMp3RiffHeader = packed record
fccRiff: FOURCC;
dwFileSize: LongInt;
fccWave: FOURCC;
fccFmt: FOURCC;
dwFmtSize: LongInt;
mp3wfx: TMpegLayer3WaveFormat;
fccFact: FOURCC;
dwFactSize: LongInt;
lSizeInSamples: LongInt;
fccData: FOURCC;
dwDataSize: LongInt;
end;
procedure Mp3RiffHeaderFromInfo(var Riff: TMp3RiffHeader; const Header: TL3FHeader; Length: LongInt);
const
CChannels: array [0 .. 3] of Word = (2, 2, 2, 1);
CFlags: array [boolean, 0 .. 1] of cardinal = ((MPEGLAYER3_FLAG_PADDING_OFF, MPEGLAYER3_FLAG_PADDING_ON),
(MPEGLAYER3_FLAG_PADDING_ISO, MPEGLAYER3_FLAG_PADDING_ISO));
CSizeMismatch: array [boolean] of Integer = (1, 2);
begin
Riff.fccRiff := FOURCC_RIFF;
Riff.dwFileSize := Header.FileSize + SizeOf(TMp3RiffHeader);
Riff.fccWave := FOURCC_WAVE;
Riff.fccFmt := FOURCC_fmt;
Riff.dwFmtSize := SizeOf(TMpegLayer3WaveFormat);
Riff.mp3wfx.wfx.wFormatTag := WAVE_FORMAT_MPEGLAYER3;
Riff.mp3wfx.wfx.nChannels := CChannels[Header.Mode];
Riff.mp3wfx.wfx.nSamplesPerSec := l3f_header_freq_hz(Header);
Riff.mp3wfx.wfx.nAvgBytesPerSec := 125 * l3f_header_rate_kbps(Header);
Riff.mp3wfx.wfx.nBlockAlign := 1;
Riff.mp3wfx.wfx.wBitsPerSample := 0;
Riff.mp3wfx.wfx.cbSize := MPEGLAYER3_WFX_EXTRA_BYTES;
Riff.mp3wfx.wID := MPEGLAYER3_ID_MPEG;
Riff.mp3wfx.fdwFlags := CFlags[Header.XingHeader > 0, Header.Padding];
Riff.mp3wfx.nBlockSize := Header.LengthInBytes;
Riff.mp3wfx.nFramesPerBlock := 1;
Riff.mp3wfx.nCodecDelay := 1105; // 1 + (Standard MDTC Filterbank) + (1 Granule)
Riff.fccFact := FOURCC_fact;
Riff.dwFactSize := 4;
Riff.lSizeInSamples := (Header.TotalFrames - CSizeMismatch[Header.XingHeader > 0]) * Header.LengthInSamples - Riff.mp3wfx.nCodecDelay;
Riff.fccData := FOURCC_data;
Riff.dwDataSize := Header.FileSize;
end;
// ======================================================================
function ConvertMp3ToWav(InStream, OutStream: TStream): bool;
var
Header: TL3FHeader;
Length: LongInt;
Mp3Hdr, OldHdr: TMp3RiffHeader;
begin
Result := false;
Length := Layer3EstimateLength(InStream, Header);
if Length = 0 then Exit;
Mp3RiffHeaderFromInfo(Mp3Hdr, Header, Length);
if Header.FileOffset >= SizeOf(TMp3RiffHeader) - 12 then
begin
InStream.Position := 0;
InStream.ReadBuffer(OldHdr, 20);
if (OldHdr.fccRiff = FOURCC_RIFF)
and (OldHdr.dwFileSize <= Header.FileOffset + Header.FileSize)
and (OldHdr.fccWave = FOURCC_WAVE)
and (OldHdr.fccFmt = FOURCC_fmt)
and (OldHdr.dwFmtSize >= SizeOf(TMpegLayer3WaveFormat)) then
begin
// файл уже сконвертирован
Exit;
end;
end;
OutStream.WriteBuffer(Mp3Hdr, SizeOf(Mp3Hdr));
InStream.Position := Header.FileOffset;
OutStream.CopyFrom(InStream, Header.FileSize);
Result := true;
end;
function GMPlaySound(stream: TMemoryStream; flags: Cardinal): bool;
var
streamWav: TMemoryStream;
begin
streamWav := TMemoryStream.Create();
try
if ConvertMp3ToWav(stream, streamWav) then
Result := PlaySound(streamWav.Memory, 0, flags or SND_MEMORY)
else
Result := PlaySound(stream.Memory, 0, flags or SND_MEMORY)
finally
streamWav.Free();
end;
end;
function GMPlaySound(const fn: string; flags: Cardinal): bool;
var
fs: TFileStream;
streamWav: TMemoryStream;
begin
try
fs := TFileStream.Create(fn, fmOpenRead or fmShareDenyNone);
streamWav := TMemoryStream.Create();
try
if ConvertMp3ToWav(fs, streamWav) then
Result := PlaySound(streamWav.Memory, 0, flags or SND_MEMORY)
else
Result := PlaySound(PChar(fn), 0, flags or SND_FILENAME)
finally
streamWav.Free();
fs.Free();
end;
except
Result := false;
end;
end;
end.
|
unit Updata;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, mxWebUpdate, ComCtrls, ExtCtrls, Buttons, ShellAPI;
type
TfrmUpdata = class(TFrame)
grpUpdataProduct: TGroupBox;
lbAuthor: TLabel;
lbProductName: TLabel;
lbEmail: TLabel;
lbYourVersion: TLabel;
lbWebVersion: TLabel;
Bevel: TBevel;
pb1: TProgressBar;
lb_File: TLabel;
btnFindUpdata: TBitBtn;
btnDownload: TBitBtn;
btnCancel: TBitBtn;
mxwbpdt1: TmxWebUpdate;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FrameResize(Sender: TObject);
procedure btnFindUpdata1Click(Sender: TObject);
procedure btnCancel1Click(Sender: TObject);
procedure mxwbpdt1AfterGetInfo(Sender: TObject);
procedure mxwbpdt1Download(Sender: TObject; Total, Downloaded: Integer;
UpdataStatus: Boolean);
procedure mxwbpdt1AfterDownload(Sender: TObject; FileName: String);
procedure mxwbpdt1AfterShowInfo(Sender: TObject;
CheckForUpdate: Boolean);
procedure mxwbpdt1BeforeDownload(Sender: TObject; FileName: String);
procedure mxwbpdt1BeforeGetInfo(Sender: TObject);
procedure mxwbpdt1BeforeShowInfo(Sender: TObject; var ShowInfo,
CheckForUpdate: Boolean);
procedure mxwbpdt1ClientFileExists(Sender: TObject;
var FileName: String; var Overwrite: Boolean);
procedure mxwbpdt1DownloadError(Sender: TObject);
procedure mxwbpdt1GetClientFileName(Sender: TObject;
var FileName: String);
procedure mxwbpdt1NoUpdateFound(Sender: TObject);
procedure mxwbpdt1UpdateAvailable(Sender: TObject; ActualVersion,
NewVersion: String; var CanUpdate: Boolean);
procedure btnDownload1Click(Sender: TObject);
procedure mxwbpdt1GetInfo(Sender: TObject; ActualVersion,
NewVersion: String);
private
{ Private declarations }
public
Form: TForm;
minWidth: Integer;
minHeight: Integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ Public declarations }
end;
var
DoError: Boolean = False;
// mxwbpdt1: TmxWebUpdate;
implementation
uses MainForm, Core;
{$R *.dfm}
constructor TfrmUpdata.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//mxwbpdt1.Create(Self);
minWidth:= (btnFindUpdata.Width + btnDownload.Width + btnCancel.Width + 48);
minHeight:=(grpUpdataProduct.Height + btnFindUpdata.Height + 40);
{обьявление параметров компонента обновления}
mxwbpdt1.TargetFolder:= DataPath;
mxwbpdt1.Options:=[uoOverwrite];
mxwbpdt1.ProductInfo.Version:= snProgramVersion;
mxwbpdt1.ProductInfo.URL:= snUpdateURL;
mxwbpdt1.OnAfterDownload:= mxwbpdt1AfterDownload;
mxwbpdt1.OnAfterGetInfo:= mxwbpdt1AfterGetInfo;
mxwbpdt1.OnAfterShowInfo:= mxwbpdt1AfterShowInfo;
mxwbpdt1.OnBeforeDownload:= mxwbpdt1BeforeDownload;
mxwbpdt1.OnBeforeGetInfo:= mxwbpdt1BeforeGetInfo;
mxwbpdt1.OnBeforeShowInfo:= mxwbpdt1BeforeShowInfo;
mxwbpdt1.OnClientFileExists:= mxwbpdt1ClientFileExists;
mxwbpdt1.OnDownload:= mxwbpdt1Download;
mxwbpdt1.OnDownloadError:= mxwbpdt1DownloadError;
mxwbpdt1.OnGetClientFileName:= mxwbpdt1GetClientFileName;
mxwbpdt1.OnGetInfo:= mxwbpdt1GetInfo;
mxwbpdt1.OnNoUpdateFound:= mxwbpdt1NoUpdateFound;
mxwbpdt1.OnUpdateAvailable:= mxwbpdt1UpdateAvailable;
end;
destructor TfrmUpdata.Destroy;
begin
mxwbpdt1.Destroy;
inherited Destroy;
end;
procedure TfrmUpdata.FrameResize(Sender: TObject);
begin
btnFindUpdata.Left:= Trunc(Self.Width - (btnFindUpdata.Width + btnDownload.Width + btnCancel.Width + 24));
btnDownload.Left:= Trunc(Self.Width - (btnDownload.Width + btnCancel.Width + 16));
btnCancel.Left:= Trunc(Self.Width - (btnCancel.Width + 8));
end;
procedure TfrmUpdata.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Form) then Form.Release();
end;
procedure TfrmUpdata.btnFindUpdata1Click(Sender: TObject);
begin
mxwbpdt1.GetInfo;
end;
procedure TfrmUpdata.btnCancel1Click(Sender: TObject);
begin
// NumLabelTpl:=nil;
if (Parent is TSomePage) then
begin
Core.CmdQueue.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID));
end;
if Assigned(Form) then Form.Close();
end;
procedure TfrmUpdata.mxwbpdt1AfterGetInfo(Sender: TObject);
var
currVersion, WebVersion: Integer;
begin
{lbProductName.Caption:=Format( 'Название продукта: %s', [ mxwbpdt1.ProductName ] );
lbAuthor.Caption:= Format( 'Авторы: %s', [ mxwbpdt1.Author ] );
lbHomePage.Caption:= lbHomePage.Caption +' ';
lbEmail.Caption:= Format( 'E-Mail: %s', [ mxwbpdt1.EMail ] );
lbYourVersion.Caption:= Format( 'Текущая версия: %s', [ mxwbpdt1.ProductInfo.Version ] );
lbWebVersion.Caption:= Format( 'Версия доступного обновления: %s', [ mxwbpdt1.ProductVersion ] );
if mxwbpdt1.ProductVersion <> mxwbpdt1.ProductInfo.Version then
btnDownload.Enabled:= True;
var
CanUpdate: Boolean;
begin
lbProductName.Caption:=Format( 'Название продукта: %s', [ mxwbpdt1.ProductName ] );
lbAuthor.Caption:= Format( 'Авторы: %s', [ mxwbpdt1.Author ] );
//lbHomePage.Caption:= lbHomePage.Caption +' ';
lbEmail.Caption:= Format( 'E-Mail: %s', [ mxwbpdt1.EMail ] );
lbYourVersion.Caption:= Format( 'Текущая версия: %s', [ mxwbpdt1.ProductInfo.Version ] );
lbWebVersion.Caption:= Format( 'Версия доступного обновления: %s', [ mxwbpdt1.ProductVersion ] );
if mxwbpdt1.ProductVersion <> mxwbpdt1.ProductInfo.Version then
begin
CanUpdate := MessageDlg( Format( 'You are using version %s, but version %s is available to ' + #13 + #10 + 'download at the author''s website.' + #13 + #10 + 'Do you want to update your application now?', [ ActualVersion, NewVersion ] ), mtWarning, [ mbYes, mbNo ], 0 ) = mrYes;
if CanUpdate then btnDownload( Self );
btnDownload.Enabled:= True;
end;}
end;
procedure TfrmUpdata.mxwbpdt1Download(Sender: TObject; Total,
Downloaded: Integer; UpdataStatus: Boolean);
begin
if UpdataStatus then
begin
pb1.Max:= Total;
pb1.Position:= Downloaded;
end;
end;
procedure TfrmUpdata.mxwbpdt1AfterDownload(Sender: TObject;
FileName: String);
begin
MessageDlg( 'Update has been downloaded.'+#10#13+'Program will be rerun!', mtInformation, [ mbOK ], 0 );
btnCancel.Enabled:= True;
{$WARNINGS OFF}
If ShellExecute( Application.MainForm.Handle, PChar( 'open' ), PChar( FileName ), PChar( '/auto_update' ), PChar( '' ), SW_SHOWNORMAL ) <= 32 Then ;//DoCannotExecute;
{$WARNINGS ON}
Application.Terminate;
end;
procedure TfrmUpdata.mxwbpdt1AfterShowInfo(Sender: TObject; CheckForUpdate: Boolean);
begin
MessageDlg( 'Update has been downloaded.', mtInformation, [ mbOK ], 0 );
end;
procedure TfrmUpdata.mxwbpdt1BeforeDownload(Sender: TObject;
FileName: String);
begin
btnCancel.Enabled:= False;
lb_File.Caption := Format( 'Downloading file %s', [ ExtractFileName( FileName ) ] );
end;
procedure TfrmUpdata.mxwbpdt1BeforeGetInfo(Sender: TObject);
begin
//
end;
procedure TfrmUpdata.mxwbpdt1BeforeShowInfo(Sender: TObject; var ShowInfo,
CheckForUpdate: Boolean);
begin
ShowInfo := MessageDlg( 'Would you like to read the information file?', mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes;
end;
procedure TfrmUpdata.mxwbpdt1ClientFileExists(Sender: TObject;
var FileName: String; var Overwrite: Boolean);
begin
Overwrite := True;//MessageDlg( Format( 'File %s already exists. Do you want to overwrite it?', [ FileName ] ), mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes;
end;
procedure TfrmUpdata.mxwbpdt1DownloadError(Sender: TObject);
begin
MessageDlg( 'Cannot download data from the web!', mtError, [ mbOK ], 0 );
DoError:= True;
btnCancel.Enabled:= True;
end;
procedure TfrmUpdata.mxwbpdt1GetClientFileName(Sender: TObject;
var FileName: String);
begin
MessageDlg( Format( 'Update will be downloaded to %s', [ FileName ] ), mtInformation, [ mbOK ], 0 );
end;
procedure TfrmUpdata.mxwbpdt1NoUpdateFound(Sender: TObject);
begin
MessageDlg( 'There is no update available!', mtError, [ mbOK ], 0 );
end;
procedure TfrmUpdata.mxwbpdt1UpdateAvailable(Sender: TObject;
ActualVersion, NewVersion: String; var CanUpdate: Boolean);
begin
CanUpdate := True; //MessageDlg( Format( 'You are using version %s, but version %s is available to ' + #13 + #10 + 'download at the author''s website.' + #13 + #10 + 'Do you want to update your application now?', [ ActualVersion, NewVersion ] ), mtWarning, [ mbYes, mbNo ], 0 ) = mrYes;
end;
procedure TfrmUpdata.btnDownload1Click(Sender: TObject);
begin
mxwbpdt1.CheckForAnUpdate;
end;
procedure TfrmUpdata.mxwbpdt1GetInfo(Sender: TObject; ActualVersion,
NewVersion: String);
var
CanUpdate: Boolean;
begin
lbProductName.Caption:=Format( 'Название продукта: %s', [ mxwbpdt1.ProductName ] );
lbAuthor.Caption:= Format( 'Авторы: %s', [ mxwbpdt1.Author ] );
//lbHomePage.Caption:= lbHomePage.Caption +' ';
lbEmail.Caption:= Format( 'E-Mail: %s', [ mxwbpdt1.EMail ] );
lbYourVersion.Caption:= Format( 'Текущая версия: %s', [ mxwbpdt1.ProductInfo.Version ] );
lbWebVersion.Caption:= Format( 'Версия доступного обновления: %s', [ mxwbpdt1.ProductVersion ] );
if (mxwbpdt1.ProductVersion <> mxwbpdt1.ProductInfo.Version) and not DoError then
begin
CanUpdate := MessageDlg( Format( 'You are using version %s, but version %s is available to ' + #13 + #10 + 'download at the author''s website.' + #13 + #10 + 'Do you want to update your application now?', [ ActualVersion, NewVersion ] ), mtWarning, [ mbYes, mbNo ], 0 ) = mrYes;
if CanUpdate then btnDownload1Click( Self );
btnDownload.Enabled:= True;
end;
end;
end.
|
unit ACompactador;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Gauges, StdCtrls, IdBaseComponent, IdZLibCompressorBase,
IdCompressorZLib, ZipMstr19, IdComponent, IdTCPConnection, IdTCPClient,
IdExplicitTLSClientServerBase, IdFTPCommon, IdFTP, DB, DBClient, Tabela;
type
TFCompactador = class(TForm)
Gauge1: TGauge;
Label1: TLabel;
Label2: TLabel;
ZM: TZipMaster19;
FTP: TIdFTP;
Aux: TSQL;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ZMProgress(Sender: TObject; details: TZMProgressDetails);
procedure FTPWork(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
private
procedure AtualizaStatus(VpaTexto : string);
procedure ConectaFTP;
procedure EnviaArquivoFTP(VpaNomArquivo : string);
function VenceuPrazoEnvioBackup : boolean;
procedure AtualizaDataUltimoEnvio;
public
function CompactaArquivo(VpaNomArquivo : String): String;
end;
var
FCompactador: TFCompactador;
implementation
uses
Constantes, FunArquivos,FunData, APrincipal, Funsql;
{$R *.DFM}
{******************************************************************************}
procedure TFCompactador.AtualizaDataUltimoEnvio;
begin
AdicionaSQLAbreTabela(Aux,'Select * from CFG_GERAL');
Aux.Edit;
aux.FieldByName('D_ENV_BAC').AsDateTime := date;
Aux.Post;
end;
{******************************************************************************}
procedure TFCompactador.AtualizaStatus(VpaTexto: string);
begin
Label1.Caption:= VpaTexto;
Label1.Refresh;
end;
{******************************************************************************}
function TFCompactador.CompactaArquivo(VpaNomArquivo : String): String;
var
VpfArquivoBackup,VpfArquivoSencundario: String;
begin
Result:= '';
Show;
Label1.Caption:= 'Compactando o arquivo';
VpfArquivoBackup := VpaNomArquivo+FormatDateTime('YYMMDD HHMMSS',now)+'.zip';
Label2.Caption:= VpfArquivoBackup;
ZM.ZipFileName := VpfArquivoBackup;
ZM.FSpecArgs.Add(VpaNomArquivo+'.DMP');
ZM.Add;
Label1.Caption:= 'Copiando o arquivo para o destino.';
if Varia.PathSecundarioBackup <> '' then
begin
NaoExisteCriaDiretorio(Varia.PathSecundarioBackup,false);
VpfArquivoSencundario :=Varia.PathSecundarioBackup+RetornaNomArquivoSemDiretorio(VpfArquivoBackup);
Label1.Caption:= 'Copiando o arquivo para o destino.';
CopyFile(PChar(VpfArquivoBackup),PChar(VpfArquivoSencundario),False);
end;
EnviaArquivoFTP(VpfArquivoBackup);
Close;
end;
{******************************************************************************}
procedure TFCompactador.ConectaFTP;
begin
AtualizaStatus('Conectando com o FTP');
FTP.Username := VARIA.UsuarioFTPEficacia;
FTP.Password := varia.SenhaFTPEficacia;
FTP.Connect;
if FTP.Connected then
begin
// transfere um arquivo texto
FTP.TransferType := ftBinary;
FTP.ChangeDir(varia.DiretorioFTPEficacia+'Dados/');
end;
end;
{******************************************************************************}
procedure TFCompactador.EnviaArquivoFTP(VpaNomArquivo: string);
begin
if config.EnviarBackupFTPEficacia then
begin
if VenceuPrazoEnvioBackup then
begin
ConectaFTP;
AtualizaStatus('Enviando arquivo FTP');
Gauge1.MaxValue := TamanhoArquivoByte(VpaNomArquivo);
FTP.Put(VpaNomArquivo,RetornaNomArquivoSemDiretorio(VpaNomArquivo));
FTP.Disconnect;
AtualizaDataUltimoEnvio;
end;
end;
end;
{******************************************************************************}
procedure TFCompactador.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:= caFree;
end;
procedure TFCompactador.FTPWork(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
Gauge1.Progress := AWorkCount;
Gauge1.Refresh;
self.Refresh;
end;
{******************************************************************************}
function TFCompactador.VenceuPrazoEnvioBackup: boolean;
begin
result := false;
case varia.PeriodicidadeEnvioBackup of
peDiario : result := DiasPorPeriodo(Varia.DatUltimoEnvioBackupEficacia,date) >=1;
peSemanal : result := DiasPorPeriodo(Varia.DatUltimoEnvioBackupEficacia,date) >=7;
peQuinzenal : result := DiasPorPeriodo(Varia.DatUltimoEnvioBackupEficacia,date) >=15;
peMensal : result := MesesPorPeriodo(Varia.DatUltimoEnvioBackupEficacia,date) >=1;
end;
end;
{******************************************************************************}
procedure TFCompactador.ZMProgress(Sender: TObject; details: TZMProgressDetails);
begin
Gauge1.Progress := details.ItemPerCent
end;
{******************************************************************************}
end.
|
unit umsrworker;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, udatabuilder, uother, utransport, umsr_defines;
type
{ TMSRWorker }
TMSRWorker = class
private
FComName: string;
FEncoderMode: integer;
FTransport: TMSRTransport;
FBuilder: TMSRDataBuilder;
public
constructor Create();
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
function GetConnectionStatus(): boolean;
//function WriteCard(Data: Integer):string;
function WriteCard(Track1, Track2, Track3: string): string;
function ReadCard(): string;
function EraseCard(): string;
function GetFirmware(): string;
procedure Reset();
property ComName: string read FComName write FComName;
property EncoderMode: integer read FEncoderMode write FEncoderMode;
end;
implementation
{ TMSRWorker }
constructor TMSRWorker.Create();
begin
FTransport := TMSRTransport.Create;
FBuilder := TMSRDataBuilder.Create;
end;
destructor TMSRWorker.Destroy;
begin
{if FTransport.Connected then
FTransport.;}
FTransport.Free;
FBuilder.Free;
inherited Destroy;
end;
procedure TMSRWorker.Connect;
begin
FTransport.Configure(Format('PortNo=%s', [ComName]));
FTransport.Connect;
end;
procedure TMSRWorker.Disconnect;
begin
FTransport.Disconnect;
end;
function TMSRWorker.GetConnectionStatus(): boolean;
begin
Result := FTransport.Connected;
end;
function TMSRWorker.WriteCard(Track1, Track2, Track3: string): string;
var
Tr1, Tr2, Tr3, EncData: TByteArray;
Cmd, Buff: array of byte;
begin
//SetLength(CMD, 2);
// SetLength(Buff, 2);
Tr1 := StrToByte(Track1);
Tr2 := StrToByte(Track2);
Tr3 := StrToByte(Track3);
FBuilder.MakeReset(CMD);
FTransport.Send(Pointer(@CMD[0]), Length(CMD));
//CMD := FBuilder.MakeSetHiCo;
case EncoderMode of
0: FBuilder.MakeSetHiCo(CMD);
1: FBuilder.MakeSetLowCo(CMD);
end;
FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
FBuilder.MakeSetBPC(CMD);
DynArrayAppend(Cmd, $07);
DynArrayAppend(Cmd, $05);
DynArrayAppend(Cmd, $05);
FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
FBuilder.MakeMSRWriteISO(CMD);
FBuilder.MakeRWStart(Buff);
DynArrayAppendByteArray(CMD, Buff);
DynArrayAppend(CMD, $1B);
DynArrayAppend(CMD, $01);
SetLength(EncData, Length(Tr1));
//EncodeTrack(7,@Tr1[0],Length(tr1),@EncData[0]);
//DynArrayAppend(CMD,Tr1);
DynArrayAppendByteArray(CMD, tr1);
DynArrayAppend(CMD, $1B);
DynArrayAppend(CMD, $02);
SetLength(EncData, Length(Tr2));
// EncodeTrack(5,@Tr1[0],Length(tr2),@EncData[0]);
DynArrayAppendByteArray(CMD, tr2);
DynArrayAppend(CMD, $1B);
DynArrayAppend(CMD, $03);
SetLength(EncData, Length(Tr3));
// EncodeTrack(5,@Tr3[0],Length(tr3),@EncData[0]);
DynArrayAppendByteArray(CMD, tr3);
DynArrayAppend(CMD, $3F);
DynArrayAppend(CMD, $1C);
Result :={ByteToString(CMD) }FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
end;
function TMSRWorker.ReadCard(): string;
var
CMD: array of byte;
begin
//SetLength(CMD, 2);
FBuilder.MakeReset(CMD);
FTransport.Send(Pointer(@CMD[0]), Length(CMD));
FBuilder.MakeMSRReadIso(CMD);
Result := FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
end;
function TMSRWorker.EraseCard(): string;
var
CMD: array of byte;
begin
//SetLength(CMD, 2);
FBuilder.MakeErase(CMD);
FTransport.Send(Pointer(@CMD[0]), Length(CMD));
FBuilder.MakeEraseAll(CMD);
Result := FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
end;
function TMSRWorker.GetFirmware(): string;
var
CMD: array of byte;
begin
//SetLength(CMD, 2);
FBuilder.MakeReset(CMD);
FTransport.Send(Pointer(@CMD[0]), Length(CMD));
FBuilder.MakeCheckFirmware(CMD);
Result := FTransport.SendData(Pointer(@CMD[0]), Length(CMD));
end;
procedure TMSRWorker.Reset();
var
CMD: array of byte;
begin
// SetLength(CMD, 2);
FBuilder.MakeReset(CMD);
FTransport.Send(Pointer(@CMD[0]), Length(CMD));
FTransport.DoCancel();
end;
end.
|
unit Unit1;
interface
type
TProductA1 = class;
TProductB1 = class;
TProductA2 = class;
TProductB2 = class;
TAbstractFactory = class
public
function printProductA: string; virtual; abstract;
function printProductB: string; virtual; abstract;
end;
TConcreteFactory2 = class(TAbstractFactory)
private
ProductA2: TProductA2;
ProductB2: TProductB2;
public
function printProductA: string; override;
function printProductB: string; override;
end;
TConcreteFactory1 = class(TAbstractFactory)
private
ProductA1: TProductA1;
ProductB1: TProductB1;
public
function printProductA: string; override;
function printProductB: string; override;
end;
TAbstractProductA = class
public
function print: string; virtual; abstract;
end;
TProductA1 = class(TAbstractProductA)
public
function print: string; override;
end;
TProductA2 = class(TAbstractProductA)
public
function print: string; override;
end;
TAbstractProductB = class
public
function print: string; virtual; abstract;
end;
TProductB1 = class(TAbstractProductB)
public
function print: string; override;
end;
TProductB2 = class(TAbstractProductB)
public
function print: string; override;
end;
implementation
{ TProductA1 }
function TProductA1.print: string;
begin
result:= 'ProductA1.print';
end;
{ TProductA2 }
function TProductA2.print: string;
begin
result:= 'ProductA2.print';
end;
{ TProductB1 }
function TProductB1.print: string;
begin
result:= 'ProductB1.print';
end;
{ TProductB2 }
function TProductB2.print: string;
begin
result:= 'ProductB2.print';
end;
{ TConcreteFactory2 }
function TConcreteFactory2.printProductA: string;
begin
ProductA2:= TProductA2.Create;
result:= ProductA2.print;
ProductA2.Destroy;
end;
function TConcreteFactory2.printProductB: string;
begin
ProductB2:=TProductB2.Create;
result:= ProductB2.print;
ProductB2.Destroy;
end;
{ TConcreteFactory1 }
function TConcreteFactory1.printProductA: string;
begin
ProductA1:=TProductA1.Create;
result:= ProductA1.print;
ProductA1.Destroy;
end;
function TConcreteFactory1.printProductB: string;
begin
ProductB1:=TProductB1.Create;
result:= ProductB1.print;
ProductB1.Destroy;
end;
end.
|
unit Window;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, MMSystem, Math,
Canvases, Walkers, RadioGroup;
type
TWindow = class
private
Wnd: HWND;
WndDC: HDC;
BmpDC: HDC; // контекст холста битмапа
ClientRect: TRect;
Canvas: IMyCanvas; // холст
Walker: IWalker; // инструмент рисования
CurSecondNum: integer; // номер текущей секунды
FramesCounter: integer; // кол-во кадров отрисованных в текущей секунде
LastFps: integer; // кол-во кадров отрисованных в предыдущей секунде
PerformanceFrequency: int64;
TimerID: DWORD;
CanvasRadioGroup: TRadioGroup;
WalkerRadioGroup: TRadioGroup;
class function WindowProc(Window: HWnd;
AMsg, WParam, LParam: LongInt): LongInt; stdcall; static;
class procedure TimerProc(
uTimerID, uMessage, dwUser, dw1, dw2: DWORD); stdcall; static;
procedure WM_Create(var Msg: TMessage); message WM_CREATE;
procedure WM_Destroy(var Msg: TMessage); message WM_DESTROY;
procedure WM_Size(var Msg: TMessage); message WM_SIZE;
procedure WM_Timer(var Msg: TMessage); message WM_TIMER;
procedure WM_MouseButton(var Msg: TMessage); message WM_LBUTTONDOWN;
procedure Paint;
public
constructor Create(ACanvasRadioGroup: TRadioGroup;
AWalkerRadioGroup: TRadioGroup);
function Execute: integer;
procedure DefaultHandler(var Msg); override;
end;
implementation
{ TWindow }
constructor TWindow.Create(ACanvasRadioGroup: TRadioGroup;
AWalkerRadioGroup: TRadioGroup);
const
WndClassName = 'DemoWndClass';
var
WndClass: TWndClass;
begin
CanvasRadioGroup := ACanvasRadioGroup;
WalkerRadioGroup := AWalkerRadioGroup;
FillChar(WndClass, SizeOf(WndClass), 0);
with WndClass do
begin
lpfnWndProc := @WindowProc;
lpszClassName := WndClassName;
hCursor := LoadCursor(0, IDC_ARROW);
hbrBackground := GetStockObject(WHITE_BRUSH);
end;
if Windows.RegisterClass(WndClass) = 0 then
begin
MessageBox(0, 'Cannot register class', 'Error', MB_ICONERROR);
Halt(255);
end;
CreateWindow(
WndClassName,
'Demo Application',
ws_OverlappedWindow,
Integer(CW_USEDEFAULT),
Integer(CW_USEDEFAULT),
Integer(CW_USEDEFAULT),
Integer(CW_USEDEFAULT),
0,
0,
HInstance,
Self); // передаём Self, чтобы поймать его в WindowProc (WM_NCCREATE)
ShowWindow(Wnd, SW_SHOWNORMAL);
UpdateWindow(Wnd);
end;
procedure TWindow.WM_Create(var Msg: TMessage);
var
bm: HBITMAP;
begin
Canvas := CanvasRadioGroup.GetCurrentItem.Create as IMyCanvas;
Walker := WalkerRadioGroup.GetCurrentItem.Create as IWalker;
GetClientRect(Wnd, ClientRect);
WndDC := GetDC(Wnd);
BmpDC := CreateCompatibleDC(WndDC);
bm := CreateCompatibleBitmap(WndDC, ClientRect.Right, ClientRect.Bottom);
DeleteObject(SelectObject(BmpDC, bm));
Canvas.SetDC(BmpDC);
QueryPerformanceFrequency(PerformanceFrequency);
TimerID := timeSetEvent(1, 1, @TimerProc, Cardinal(Self), TIME_PERIODIC);
end;
class function TWindow.WindowProc(Window: HWnd;
AMsg, WParam, LParam: LongInt): LongInt;
var
Instance: TWindow;
Msg: TMessage;
begin
if AMsg = WM_NCCREATE then
begin
Instance := PCreateStruct(LParam).lpCreateParams;
// поймали Self, привяжем его на будущее к окну через GWL_USERDATA
SetWindowLong(Window, GWL_USERDATA, Integer(Instance));
Instance.Wnd := Window;
end
else
begin
// получаем Self из GWL_USERDATA
Instance := Pointer(GetWindowLong(Window, GWL_USERDATA));
if Instance = nil then
Exit(DefWindowProc(Window, AMsg, wParam, lParam));
end;
Msg.Msg := AMsg;
Msg.WParam := WParam;
Msg.LParam := LParam;
Msg.Result := 0;
Instance.Dispatch(Msg);
Result := Msg.Result;
end;
class procedure TWindow.TimerProc(uTimerID, uMessage, dwUser, dw1, dw2: DWORD);
begin
// будем обрабатывать в главном потоке
SendMessage(TWindow(dwUser).Wnd, Messages.WM_TIMER, 0, 0);
end;
function TWindow.Execute: integer;
var
Msg: TMsg;
begin
while GetMessage(Msg, 0, 0, 0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
Result := Msg.WParam;
end;
procedure TWindow.WM_Timer(var Msg: TMessage);
begin
Paint; // рисуем на битмапе,
BitBlt(WndDC, // копируем на окно
0,
0,
ClientRect.Right,
ClientRect.Bottom,
BmpDC,
0,
0,
SRCCOPY);
end;
procedure TWindow.WM_Size(var Msg: TMessage);
var
bm: HBITMAP;
begin
ClientRect := Rect(0, 0, Msg.LParamLo, Msg.LParamHi);
// если размеры битмапа уменьшатся до нуля, потеряется информация о его
// цвето-типе, чтобы не допустить этого ограничиваем уменьшение:
bm := CreateCompatibleBitmap(BmpDC,
Max(ClientRect.Right, 1),
Max(ClientRect.Bottom, 1));
// при работе с GDI+ нельзя так просто взять и заменить битмэпку в HDC,
// поэтому приходится предварительно удалить контекст GDI+,
// заменить битпэпку и создать контекст заново:
Canvas.SetDC(0);
DeleteObject(SelectObject(BmpDC, bm));
Canvas.SetDC(BmpDC);
end;
procedure TWindow.Paint;
const
top_margin = 18; // высота поля под вывод строки с fps
var
i: integer;
step: extended;
tick: int64;
second_num: word;
pnt: TPointEx;
str: string;
begin
QueryPerformanceCounter(tick);
Walker.Angle := tick / PerformanceFrequency; // начальный угол поворота
second_num := Trunc(Walker.Angle); // номер текущей секунды
if second_num = CurSecondNum then
Inc(FramesCounter)
else
begin
CurSecondNum := second_num;
LastFps := FramesCounter;
FramesCounter := 1;
end;
Canvas.SetBrushColor(clWhite);
Canvas.FillRect(ClientRect);
Canvas.SetPen(clBlue, 2);
// центр области рисования
pnt.X := ClientRect.Right / 2;
pnt.Y := ClientRect.Bottom / 2 + top_margin div 2 - 1;
Canvas.MoveTo(pnt);
// рисуем фигуру
step := Min(ClientRect.Right, ClientRect.Bottom - top_margin) * 0.47;
for i := 1 to 12 do
begin
Walker.Forward(Canvas, step);
Walker.Turn(5 / 6 * pi);
end;
CanvasRadioGroup.Draw(Canvas, ClientRect);
WalkerRadioGroup.Draw(Canvas, ClientRect);
str := IntToStr(LastFps) + ' fps';
Canvas.TextOut(Point((ClientRect.Right - Canvas.TextWidth(str)) shr 1, 4),
str);
end;
procedure TWindow.WM_MouseButton(var Msg: TMessage);
begin
if CanvasRadioGroup.SwitchedByClick(Point(Msg.LParamLo, Msg.LParamHi)) then
begin
Canvas := CanvasRadioGroup.GetCurrentItem.Create as IMyCanvas;
Canvas.SetDC(BmpDC);
Exit;
end;
if WalkerRadioGroup.SwitchedByClick(Point(Msg.LParamLo, Msg.LParamHi)) then
Walker := WalkerRadioGroup.GetCurrentItem.Create as IWalker;
end;
procedure TWindow.WM_Destroy(var Msg: TMessage);
begin
CanvasRadioGroup.Free;
WalkerRadioGroup.Free;
timeKillEvent(TimerID);
ReleaseDC(Wnd, WndDc);
PostQuitMessage(0);
end;
procedure TWindow.DefaultHandler(var Msg);
begin
with TMessage(Msg) do
Result := DefWindowProc(Wnd, Msg, WParam, LParam);
end;
end.
|
Program Lab31;
Const
fmax = 170;
Var
n, k: Integer;
res, fact_n, fact_k, fact_nk: Real;
Procedure ReadSafeInt(Var result: Integer);
Var
safety: String;
success: Integer;
Begin
Repeat
Readln(safety);
val(safety, result, success);
Until success = 0;
End;
{ Recursive factorial function.
* Orignal c++ code can be found on https://habrahabr.ru/post/255761/ }
Function ProdTree(l, r: Integer) : Real;
Var m: Integer;
Begin
If l > r Then
ProdTree := 1
Else If l = r Then
ProdTree := l
Else If r - l = 1 Then
ProdTree := l*r
Else
Begin
m := Round((l + r) / 2);
ProdTree := ProdTree(l, m) * ProdTree(m + 1, r);
End;
End;
Function FactTree(n: Integer) : Real;
Begin
If n < 0 Then
FactTree := 0
Else If n = 0 Then
FactTree := 1
Else If (n = 1) or (n = 2) Then
FactTree := n
Else
FactTree := ProdTree(2, n);
End;
Begin
{ Enter n and k }
{ Factorial of a negative value is always a bad idea }
Repeat
writeln('Введите n');
ReadSafeInt(n);
Until (n>=0) and (n <= fmax);
{ k shouldn't be greater than n as we will need factorial of k-n later }
Repeat
writeln('Введите k меньше ', n);
ReadSafeInt(k);
Until (k>=0) and (k<=n);
{ All the arithmetics is here }
fact_n := FactTree(n);
fact_k := FactTree(k);
fact_nk := FactTree(n-k);
res := fact_n/(fact_k*fact_nk);
{ Output result }
writeln(res);
End.
|
unit utransport;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,{Forms,} Synaser, uother;
type
{ TMSRTransport }
TMSRTransport = class
private
FAnswerTimeout: integer;
FCancel: boolean;
FConfigured: boolean;
FConnected: boolean;
FConnector: TBlockSerial;
FLastError: integer;
FLastErrorDesc: string;
FPortNo: string;
public
constructor Create;
destructor Destroy;override;
procedure Connect;
procedure Disconnect;
procedure DoCancel;
function Configure(const ConnectionString: string): boolean;
procedure Send(const Data: Pointer; DataLength: integer);
function SendData(const Data: Pointer; DataLength: integer): string;
property Connector: TBlockSerial read FConnector;
property Connected: boolean read FConnected write FConnected;
property LastError: integer read FLastError write FLastError;
property Configured: boolean read FConfigured write FConfigured;
property LastErrorDesc: string read FLastErrorDesc write FLastErrorDesc;
property AnswerTimeout: integer read FAnswerTimeout write FAnswerTimeout;
end;
implementation
{ TRS232Transport }
constructor TMSRTransport.Create;
begin
FConnector := TBlockSerial.Create;
FConnected := False;
FConfigured := False;
FLastError := 0;
LastErrorDesc := '';
FAnswerTimeout := 1000;
inherited;
end;
destructor TMSRTransport.Destroy;
begin
FConnector.Free;
inherited Destroy;
end;
procedure TMSRTransport.Connect;
begin
if Configured then
begin
with FConnector do
begin
Connect(FPortNo);
LinuxLock := False;
sleep(500);
Config(9600, 8, 'N', SB1, True, False);
Sleep(300);
self.LastError := LastError;
Self.LastErrorDesc := LastErrorDesc;
if self.LastError = 0 then
Connected := True;
end;
end;
end;
procedure TMSRTransport.Disconnect;
begin
if Connected then
begin
FConnector.Flush;
FConnector.CloseSocket;
Sleep(500);
end;
end;
procedure TMSRTransport.DoCancel;
begin
if Connected then
Disconnect;
Connect;
end;
// формат типа PortNo = COM1
function TMSRTransport.Configure(const ConnectionString: string): boolean;
var
St: TStringList;
begin
Result := False;
St := TStringList.Create;
try
Split('=', ConnectionString, St);
if St.Count > 0 then
begin
FPortNo := UpperCase(St[1]);
Configured := True;
Result := True;
end;
finally
St.Free;
end;
end;
procedure TMSRTransport.Send(const Data: Pointer; DataLength: integer);
var
Answer: string;
Str: string;
WrittenBytes: integer;
begin
Answer := '';
if Connected then
begin
WrittenBytes := 0;
WrittenBytes := FConnector.SendBuffer(Data,DataLength);
//FConnector.SendString(StrData);
if FConnector.LastError <> 0 then
begin
Self.LastError := FConnector.LastError;
Self.LastErrorDesc := FConnector.LastErrorDesc;
end;
Sleep(50);
end;
end;
function TMSRTransport.SendData(const Data: Pointer; DataLength: integer): string;
var
Answer: string;
Str: string;
WrittenBytes: integer;
begin
Result := '';
Answer := '';
if Connected then
begin
WrittenBytes := 0;
WrittenBytes := FConnector.SendBuffer(Data,DataLength);
//FConnector.SendString(StrData);
if FConnector.LastError <> 0 then
begin
Self.LastError := FConnector.LastError;
Self.LastErrorDesc := FConnector.LastErrorDesc;
exit;
end;
str := '';
str := FConnector.RecvPacket(100);
if str = '' then
repeat
// application.ProcessMessages;
// Sleep(50);
str := FConnector.RecvPacket(100);
until (str <> '') {or (Cancel)};
answer := str;
while (str <> '') {or (not Cancel)} do
begin
//application.ProcessMessages;
// Sleep(50);
str := FConnector.RecvPacket(100);
answer := answer + str;
end;
Result := Answer;
if FConnector.LastError <> 0 then
begin
Self.LastError := FConnector.LastError;
Self.LastErrorDesc := FConnector.LastErrorDesc;
end;
end;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Sort Editor Dialog }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.Editor.Sort;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BI.Query,
VCLBI.Editor.ListItems, Vcl.StdCtrls, Vcl.ExtCtrls, BI.DataItem,
BI.Expressions;
type
TSortEditor = class(TForm)
Panel1: TPanel;
CBAscending: TCheckBox;
BDelete: TButton;
Splitter1: TSplitter;
CBIgnoreCase: TCheckBox;
LBAvailable: TListBox;
PanelButtons: TPanel;
PanelOk: TPanel;
BOk: TButton;
BCancel: TButton;
BAdd: TButton;
procedure FormShow(Sender: TObject);
procedure CBAscendingClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BDeleteClick(Sender: TObject);
procedure LBAvailableClick(Sender: TObject);
procedure BAddClick(Sender: TObject);
procedure CBIgnoreCaseClick(Sender: TObject);
private
{ Private declarations }
FOnChanged : TNotifyEvent;
Sort : TQuerySort;
IList : TFormListItems;
IChanging : Boolean;
procedure AddItem(const AItem:TQuerySortItem);
procedure AddItems;
function Current:TQuerySortItem;
procedure CheckedAll(Sender: TObject);
procedure CheckedItem(Sender: TObject);
procedure ExchangedItem(const Sender:TObject; const A,B:Integer);
procedure Modified;
procedure SelectedItem(Sender: TObject);
public
{ Public declarations }
class function Edit(const AOwner:TComponent;
const ASort:TQuerySort):Boolean; overload; static;
class function Edit(const AOwner: TComponent;
const AData:TDataItem;
out AItems:TSortItems):Boolean; overload; static;
class function Embedd(const AOwner:TComponent; const AParent:TWinControl;
const ASort:TQuerySort):TSortEditor; static;
procedure Refresh(const ASort:TQuerySort);
property OnChanged:TNotifyEvent read FOnChanged write FOnChanged;
end;
implementation
|
{ Pascal function that returns a power of 10 }
function pow10(exponent:byte):longint;
var p:longint; { this is the number where we will store the result }
i:byte;
begin
p := 1;
for i := 2 to exponent do
begin
p := p * 10;
end;
pow10 := p;
end;
|
unit iaStressTest.TThreadedQueue.PopItem;
interface
uses
System.Classes,
System.Generics.Collections,
System.SyncObjs;
const
POP_TIMEOUT = 20; //the lower the timeout, the more pronounced the problem
MAX_TEST_RUNTIME_SECONDS = 600;
{$IFDEF MSWINDOWS}
RESERVED_STACK_SIZE = 65536;
{$IFDEF WIN32}
MAX_WORKER_THREADS = 6000;
{$ELSE} //WIN64
MAX_WORKER_THREADS = 10000;
{$ENDIF}
{$ENDIF}
MINIMIM_TIMEOUT_REQUIRED = 20;
type
TItem = class (TObject);
TThreadCreator = Class(TThread)
public
procedure Execute(); override;
end;
TTestThread = class (TThread)
private
FQueue: TThreadedQueue<TItem>;
public
procedure AfterConstruction(); override;
procedure BeforeDestruction(); override;
procedure Execute(); override;
end;
function StressTestPopItem():Boolean;
var
pubTestCompletionCheck:TEvent;
pubSyncrhonizedStart:TEvent;
implementation
uses
System.SysUtils,
System.DateUtils,
System.Diagnostics,
System.RTTI,
System.TimeSpan,
iaTestSupport.Log;
function StressTestPopItem():Boolean;
var
vMaxTestRuntime:TTimeSpan;
vTestCompletion:TWaitResult;
vStartedTest:TDateTime;
begin
vMaxTestRuntime.Create(0, 0, MAX_TEST_RUNTIME_SECONDS);
LogIt('StressTestPopItem Start: Waiting up to [' + IntToStr(MAX_TEST_RUNTIME_SECONDS) + '] seconds for PopItem to prematurely timeout.');
if POP_TIMEOUT < MINIMIM_TIMEOUT_REQUIRED then
begin
LogIt('Test aborted, POP_TIMEOUT too short');
Exit(False);
end;
LogIt('Note: Using [' + IntToStr(POP_TIMEOUT) + '] as PopTimeout on TThreadedQueue creation');
vStartedTest := Now;
//create a bunch of threads, all continuously calling PopItem on an empty TThreadQueue
TThreadCreator.Create(False);
//wait until a PopItem fails or test times-out
vTestCompletion := pubTestCompletionCheck.WaitFor(vMaxTestRuntime);
Result := (vTestCompletion = TWaitResult.wrTimeout);
if Result then
begin
pubTestCompletionCheck.SetEvent(); //tell threads to terminate
LogIt('StressTestPopItem End: Overall maximum time limit reached for this test without an error detected...we will call this a success!');
end
else
begin
LogIt('StressTestPopItem End: After [' + IntToStr(SecondsBetween(Now, vStartedTest)) + '] seconds, a failure of PopItem was detected in at least one thread');
end;
end;
procedure TThreadCreator.Execute();
var
vThreadsCreated:Integer;
vWorkerThreads:Array[0..MAX_WORKER_THREADS-1] of TTestThread;
begin
Sleep(1000);//More than enough time to ensure the main thread completely settles-in on WaitFor()
LogIt('TThreadCreator Start: Creating up to [' + IntToStr(MAX_WORKER_THREADS) + '] threads');
{$IFDEF MSWINDOWS}
LogIt('Note: Creating threads with a StackSize of [' + IntToStr(RESERVED_STACK_SIZE) + ']');
{$ENDIF}
vThreadsCreated := 0;
while vThreadsCreated < MAX_WORKER_THREADS do
begin
if pubTestCompletionCheck.WaitFor(0) = wrSignaled then
begin
LogIt('TThreadCreator Note: aborting thread creation at [' + IntToStr(vThreadsCreated) + '] threads as a failure has already been detected.');
Break;
end;
try
vWorkerThreads[vThreadsCreated] := TTestThread.Create(True{$IFDEF MSWINDOWS}, RESERVED_STACK_SIZE{$ENDIF});
Inc(vThreadsCreated);
except on E: Exception do
begin
LogIt('TThreadCreator Note: created the maximum number of threads before experiencing system error [' + IntToStr(GetLastError) + ']');
Break;
end;
end;
end;
LogIt('Starting [' + IntToStr(vThreadsCreated) + '] worker threads');
for var i := 0 to vThreadsCreated-1 do
begin
vWorkerThreads[i].Start();
end;
LogIt('All worker threads started, now signaling synchronized start event to activate them all');
pubSyncrhonizedStart.SetEvent();
LogIt('TThreadCreator End: [' + IntToStr(vThreadsCreated) + '] worker threads started');
end;
procedure TTestThread.AfterConstruction();
begin
FQueue := TThreadedQueue<TItem>.Create(10, 10, POP_TIMEOUT);
FreeOnTerminate := True;
inherited;
end;
procedure TTestThread.BeforeDestruction();
begin
FQueue.DoShutDown();
FQueue.Free;
inherited;
end;
procedure TTestThread.Execute();
var
Item: TItem;
vWaitResult:TWaitResult;
vStopwatch:TStopwatch;
begin
pubSyncrhonizedStart.WaitFor();
while not Terminated do
begin
vStopwatch := TStopwatch.StartNew;
vWaitResult := FQueue.PopItem( Item );
vStopWatch.Stop();
if fQueue.ShutDown then Break;
if pubTestCompletionCheck.WaitFor(0) = wrSignaled then Break;
if (vWaitResult = wrTimeout) and (vStopWatch.ElapsedMilliseconds > 0) then
begin
//successful PopItem operation as we aren't adding anything into our queue
Continue;
end
else
begin
LogIt('TTestThread ERROR: TThreadedQueue.PopItem returned [' + TRttiEnumerationType.GetName(vWaitResult) + '] unexpectedly after [' + IntToStr(vStopWatch.ElapsedMilliseconds) + 'ms]');
pubTestCompletionCheck.SetEvent();
Break;
end;
end;
end;
initialization
pubTestCompletionCheck := TEvent.Create();
pubSyncrhonizedStart := TEvent.Create();
finalization
pubSyncrhonizedStart.Free();
pubTestCompletionCheck.Free();
end.
|
unit agmapproject_model;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}
interface
uses
SysUtils
,tiObject
,tiAutoMap
,tiOPFManager
,tiVisitorDB
,tiVisitorCriteria
,tiCriteria
,tiSQLParser
,mapper
,tiQuery
;
type
// ---------------------------------------------
// Generated Classes
// ---------------------------------------------
{ Generated Class: TagMapUnit}
TagMapUnit = class(TtiObject)
protected
FUnitName: String;
procedure SetUnitName(const AValue: String); virtual;
public
procedure Read; override;
procedure Save; override;
published
property UnitName: String read FUnitName write SetUnitName;
end;
{ List of TagMapUnit. TtiMappedFilteredObjectList descendant. }
TagMapUnitList = class(TtiMappedFilteredObjectList)
protected
procedure SetItems(i: integer; const AValue: TagMapUnit); reintroduce;
function GetItems(i: integer): TagMapUnit; reintroduce;
public
property Items[i:integer] : TagMapUnit read GetItems write SetItems;
procedure Add(AObject: TagMapUnit); reintroduce;
procedure Read; override;
procedure Save; override;
{ Return count (1) if successful. }
function FindByOID(const AOID: string): integer;
end;
{ Generated Class: TagMapClass}
TagMapClass = class(TtiObject)
protected
FBaseClass: String;
FBaseClassParent: String;
procedure SetBaseClass(const AValue: String); virtual;
procedure SetBaseClassParent(const AValue: String); virtual;
public
procedure Read; override;
procedure Save; override;
published
property BaseClass: String read FBaseClass write SetBaseClass;
property BaseClassParent: String read FBaseClassParent write SetBaseClassParent;
end;
{ List of TagMapClass. TtiMappedFilteredObjectList descendant. }
TagMapClassList = class(TtiMappedFilteredObjectList)
protected
procedure SetItems(i: integer; const AValue: TagMapClass); reintroduce;
function GetItems(i: integer): TagMapClass; reintroduce;
public
property Items[i:integer] : TagMapClass read GetItems write SetItems;
procedure Add(AObject: TagMapClass); reintroduce;
procedure Read; override;
procedure Save; override;
{ Return count (1) if successful. }
function FindByOID(const AOID: string): integer;
end;
{ Generated Class: TagMapClassProp}
TagMapClassProp = class(TtiObject)
protected
FPropName: String;
FPropType: String;
procedure SetPropName(const AValue: String); virtual;
procedure SetPropType(const AValue: String); virtual;
public
procedure Read; override;
procedure Save; override;
published
property PropName: String read FPropName write SetPropName;
property PropType: String read FPropType write SetPropType;
end;
{ List of TagMapClassProp. TtiMappedFilteredObjectList descendant. }
TagMapClassPropList = class(TtiMappedFilteredObjectList)
protected
procedure SetItems(i: integer; const AValue: TagMapClassProp); reintroduce;
function GetItems(i: integer): TagMapClassProp; reintroduce;
public
property Items[i:integer] : TagMapClassProp read GetItems write SetItems;
procedure Add(AObject: TagMapClassProp); reintroduce;
procedure Read; override;
procedure Save; override;
{ Return count (1) if successful. }
function FindByOID(const AOID: string): integer;
end;
{ Generated Class: TagMapPropTable}
TagMapPropTable = class(TtiObject)
protected
FMapPropName: String;
FMapPropField: String;
FMapProptype: String;
FMapPropLength: Integer;
procedure SetMapPropName(const AValue: String); virtual;
procedure SetMapPropField(const AValue: String); virtual;
procedure SetMapProptype(const AValue: String); virtual;
procedure SetMapPropLength(const AValue: Integer); virtual;
public
procedure Read; override;
procedure Save; override;
published
property MapPropName: String read FMapPropName write SetMapPropName;
property MapPropField: String read FMapPropField write SetMapPropField;
property MapProptype: String read FMapProptype write SetMapProptype;
property MapPropLength: Integer read FMapPropLength write SetMapPropLength;
end;
{ List of TagMapPropTable. TtiMappedFilteredObjectList descendant. }
TagMapPropTableList = class(TtiMappedFilteredObjectList)
protected
procedure SetItems(i: integer; const AValue: TagMapPropTable); reintroduce;
function GetItems(i: integer): TagMapPropTable; reintroduce;
public
property Items[i:integer] : TagMapPropTable read GetItems write SetItems;
procedure Add(AObject: TagMapPropTable); reintroduce;
procedure Read; override;
procedure Save; override;
{ Return count (1) if successful. }
function FindByOID(const AOID: string): integer;
end;
{ Read Visitor for TagMapUnit }
TagMapUnit_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
procedure MapRowToObject; override;
end;
{ Create Visitor for TagMapUnit }
TagMapUnit_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Update Visitor for TagMapUnit }
TagMapUnit_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Delete Visitor for TagMapUnit }
TagMapUnit_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Read Visitor for TagMapUnitList }
TagMapUnitList_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure MapRowToObject; override;
end;
{ List Create Visitor for TagMapUnitList }
TagMapUnitList_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Update Visitor for TagMapUnitList }
TagMapUnitList_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Delete Visitor for TagMapUnitList }
TagMapUnitList_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Read Visitor for TagMapClass }
TagMapClass_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
procedure MapRowToObject; override;
end;
{ Create Visitor for TagMapClass }
TagMapClass_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Update Visitor for TagMapClass }
TagMapClass_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Delete Visitor for TagMapClass }
TagMapClass_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Read Visitor for TagMapClassList }
TagMapClassList_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure MapRowToObject; override;
end;
{ List Create Visitor for TagMapClassList }
TagMapClassList_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Update Visitor for TagMapClassList }
TagMapClassList_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Delete Visitor for TagMapClassList }
TagMapClassList_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Read Visitor for TagMapClassProp }
TagMapClassProp_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
procedure MapRowToObject; override;
end;
{ Create Visitor for TagMapClassProp }
TagMapClassProp_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Update Visitor for TagMapClassProp }
TagMapClassProp_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Delete Visitor for TagMapClassProp }
TagMapClassProp_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Read Visitor for TagMapClassPropList }
TagMapClassPropList_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure MapRowToObject; override;
end;
{ List Create Visitor for TagMapClassPropList }
TagMapClassPropList_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Update Visitor for TagMapClassPropList }
TagMapClassPropList_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Delete Visitor for TagMapClassPropList }
TagMapClassPropList_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Read Visitor for TagMapPropTable }
TagMapPropTable_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
procedure MapRowToObject; override;
end;
{ Create Visitor for TagMapPropTable }
TagMapPropTable_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Update Visitor for TagMapPropTable }
TagMapPropTable_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Delete Visitor for TagMapPropTable }
TagMapPropTable_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Read Visitor for TagMapPropTableList }
TagMapPropTableList_Read = class(TtiVisitorSelect)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure MapRowToObject; override;
end;
{ List Create Visitor for TagMapPropTableList }
TagMapPropTableList_Create = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Update Visitor for TagMapPropTableList }
TagMapPropTableList_Save = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ List Delete Visitor for TagMapPropTableList }
TagMapPropTableList_Delete = class(TtiVisitorUpdate)
protected
function AcceptVisitor: Boolean; override;
procedure Init; override;
procedure SetupParams; override;
end;
{ Visitor Manager Registrations }
procedure RegisterVisitors;
{ Register Auto Mappings }
procedure RegisterMappings;
implementation
procedure RegisterMappings;
begin
end;
procedure RegisterVisitors;
begin
{ Register Visitors for TagMapUnit }
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitList_listread', TagMapUnitList_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitList_listsave', TagMapUnitList_Create);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitList_listsave', TagMapUnitList_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitList_listsave', TagMapUnitList_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitread', TagMapUnit_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitsave', TagMapUnit_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitdelete', TagMapUnit_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapUnitcreate', TagMapUnit_Create);
{ Register Visitors for TagMapClass }
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassList_listread', TagMapClassList_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassList_listsave', TagMapClassList_Create);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassList_listsave', TagMapClassList_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassList_listsave', TagMapClassList_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassread', TagMapClass_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClasssave', TagMapClass_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassdelete', TagMapClass_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClasscreate', TagMapClass_Create);
{ Register Visitors for TagMapClassProp }
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropList_listread', TagMapClassPropList_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropList_listsave', TagMapClassPropList_Create);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropList_listsave', TagMapClassPropList_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropList_listsave', TagMapClassPropList_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropread', TagMapClassProp_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropsave', TagMapClassProp_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropdelete', TagMapClassProp_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapClassPropcreate', TagMapClassProp_Create);
{ Register Visitors for TagMapPropTable }
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTableList_listread', TagMapPropTableList_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTableList_listsave', TagMapPropTableList_Create);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTableList_listsave', TagMapPropTableList_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTableList_listsave', TagMapPropTableList_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTableread', TagMapPropTable_Read);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTablesave', TagMapPropTable_Save);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTabledelete', TagMapPropTable_Delete);
GTIOPFManager.VisitorManager.RegisterVisitor('TagMapPropTablecreate', TagMapPropTable_Create);
end;
procedure TagMapUnit.SetUnitName(const AValue: String);
begin
if FUnitName <> AValue then
FUnitName := AValue;
end;
procedure TagMapUnit.Read;
begin
GTIOPFManager.VisitorManager.Execute(ClassName + 'read', self);
end;
procedure TagMapUnit.Save;
begin
Case ObjectState of
posDelete: GTIOPFManager.VisitorManager.Execute('TagMapUnitdelete', self);
posUpdate: GTIOPFManager.VisitorManager.Execute('TagMapUnitsave', self);
posCreate: GTIOPFManager.VisitorManager.Execute('TagMapUnitcreate', self);
end;
end;
{TagMapUnitList }
procedure TagMapUnitList.Add(AObject: TagMapUnit);
begin
inherited Add(AObject);
end;
function TagMapUnitList.GetItems(i: integer): TagMapUnit;
begin
result := inherited GetItems(i) as TagMapUnit;
end;
procedure TagMapUnitList.Read;
begin
GTIOPFManager.VisitorManager.Execute('TagMapUnitList_listread', self);
end;
procedure TagMapUnitList.Save;
begin
GTIOPFManager.VisitorManager.Execute('TagMapUnitList_listsave', self);
end;
procedure TagMapUnitList.SetItems(i: integer; const AValue: TagMapUnit);
begin
inherited SetItems(i, AValue);
end;
function TagMapUnitList.FindByOID(const AOID: string): integer;
begin
if self.Count > 0 then
self.Clear;
Criteria.ClearAll;
Criteria.AddEqualTo('OID', AOID);
Read;
result := Count;
end;
procedure TagMapClass.SetBaseClass(const AValue: String);
begin
if FBaseClass <> AValue then
FBaseClass := AValue;
end;
procedure TagMapClass.SetBaseClassParent(const AValue: String);
begin
if FBaseClassParent <> AValue then
FBaseClassParent := AValue;
end;
procedure TagMapClass.Read;
begin
GTIOPFManager.VisitorManager.Execute(ClassName + 'read', self);
end;
procedure TagMapClass.Save;
begin
Case ObjectState of
posDelete: GTIOPFManager.VisitorManager.Execute('TagMapClassdelete', self);
posUpdate: GTIOPFManager.VisitorManager.Execute('TagMapClasssave', self);
posCreate: GTIOPFManager.VisitorManager.Execute('TagMapClasscreate', self);
end;
end;
{TagMapClassList }
procedure TagMapClassList.Add(AObject: TagMapClass);
begin
inherited Add(AObject);
end;
function TagMapClassList.GetItems(i: integer): TagMapClass;
begin
result := inherited GetItems(i) as TagMapClass;
end;
procedure TagMapClassList.Read;
begin
GTIOPFManager.VisitorManager.Execute('TagMapClassList_listread', self);
end;
procedure TagMapClassList.Save;
begin
GTIOPFManager.VisitorManager.Execute('TagMapClassList_listsave', self);
end;
procedure TagMapClassList.SetItems(i: integer; const AValue: TagMapClass);
begin
inherited SetItems(i, AValue);
end;
function TagMapClassList.FindByOID(const AOID: string): integer;
begin
if self.Count > 0 then
self.Clear;
Criteria.ClearAll;
Criteria.AddEqualTo('OID', AOID);
Read;
result := Count;
end;
procedure TagMapClassProp.SetPropName(const AValue: String);
begin
if FPropName <> AValue then
FPropName := AValue;
end;
procedure TagMapClassProp.SetPropType(const AValue: String);
begin
if FPropType <> AValue then
FPropType := AValue;
end;
procedure TagMapClassProp.Read;
begin
GTIOPFManager.VisitorManager.Execute(ClassName + 'read', self);
end;
procedure TagMapClassProp.Save;
begin
Case ObjectState of
posDelete: GTIOPFManager.VisitorManager.Execute('TagMapClassPropdelete', self);
posUpdate: GTIOPFManager.VisitorManager.Execute('TagMapClassPropsave', self);
posCreate: GTIOPFManager.VisitorManager.Execute('TagMapClassPropcreate', self);
end;
end;
{TagMapClassPropList }
procedure TagMapClassPropList.Add(AObject: TagMapClassProp);
begin
inherited Add(AObject);
end;
function TagMapClassPropList.GetItems(i: integer): TagMapClassProp;
begin
result := inherited GetItems(i) as TagMapClassProp;
end;
procedure TagMapClassPropList.Read;
begin
GTIOPFManager.VisitorManager.Execute('TagMapClassPropList_listread', self);
end;
procedure TagMapClassPropList.Save;
begin
GTIOPFManager.VisitorManager.Execute('TagMapClassPropList_listsave', self);
end;
procedure TagMapClassPropList.SetItems(i: integer; const AValue: TagMapClassProp);
begin
inherited SetItems(i, AValue);
end;
function TagMapClassPropList.FindByOID(const AOID: string): integer;
begin
if self.Count > 0 then
self.Clear;
Criteria.ClearAll;
Criteria.AddEqualTo('OID', AOID);
Read;
result := Count;
end;
procedure TagMapPropTable.SetMapPropName(const AValue: String);
begin
if FMapPropName <> AValue then
FMapPropName := AValue;
end;
procedure TagMapPropTable.SetMapPropField(const AValue: String);
begin
if FMapPropField <> AValue then
FMapPropField := AValue;
end;
procedure TagMapPropTable.SetMapProptype(const AValue: String);
begin
if FMapProptype <> AValue then
FMapProptype := AValue;
end;
procedure TagMapPropTable.SetMapPropLength(const AValue: Integer);
begin
if FMapPropLength <> AValue then
FMapPropLength := AValue;
end;
procedure TagMapPropTable.Read;
begin
GTIOPFManager.VisitorManager.Execute(ClassName + 'read', self);
end;
procedure TagMapPropTable.Save;
begin
Case ObjectState of
posDelete: GTIOPFManager.VisitorManager.Execute('TagMapPropTabledelete', self);
posUpdate: GTIOPFManager.VisitorManager.Execute('TagMapPropTablesave', self);
posCreate: GTIOPFManager.VisitorManager.Execute('TagMapPropTablecreate', self);
end;
end;
{TagMapPropTableList }
procedure TagMapPropTableList.Add(AObject: TagMapPropTable);
begin
inherited Add(AObject);
end;
function TagMapPropTableList.GetItems(i: integer): TagMapPropTable;
begin
result := inherited GetItems(i) as TagMapPropTable;
end;
procedure TagMapPropTableList.Read;
begin
GTIOPFManager.VisitorManager.Execute('TagMapPropTableList_listread', self);
end;
procedure TagMapPropTableList.Save;
begin
GTIOPFManager.VisitorManager.Execute('TagMapPropTableList_listsave', self);
end;
procedure TagMapPropTableList.SetItems(i: integer; const AValue: TagMapPropTable);
begin
inherited SetItems(i, AValue);
end;
function TagMapPropTableList.FindByOID(const AOID: string): integer;
begin
if self.Count > 0 then
self.Clear;
Criteria.ClearAll;
Criteria.AddEqualTo('OID', AOID);
Read;
result := Count;
end;
{ TagMapUnit_Create }
function TagMapUnit_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapUnit_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapUnit_Create.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapUnit_Save }
function TagMapUnit_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapUnit_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapUnit_Save.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapUnit_Read }
function TagMapUnit_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posPK) OR (Visited.ObjectState = posClean);
end;
procedure TagMapUnit_Read.Init;
begin
Query.SQLText :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here WHERE OID = :OID' ;
end;
procedure TagMapUnit_Read.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
procedure TagMapUnit_Read.MapRowToObject;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignFromTIQuery('OID',Query);
end;
{ TagMapUnit_Delete }
function TagMapUnit_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapUnit_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapUnit_Delete.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapUnitList_Read }
function TagMapUnitList_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posEmpty);
end;
procedure TagMapUnitList_Read.Init;
var
lFiltered: ItiFiltered;
lWhere: string;
lOrder: string;
lSQL: string;
begin
if Supports(Visited, ItiFiltered, lFiltered) then
begin
if lFiltered.GetCriteria.HasCriteria then
lWhere := ' WHERE ' + tiCriteriaAsSQL(lFiltered.GetCriteria)
else
lWhere := '';
if lFiltered.GetCriteria.hasOrderBy then
lOrder := tiCriteriaOrderByAsSQL(lFiltered.GetCriteria)
else
lOrder := '';
end;
lSQL :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here %s %s ;';
Query.SQLText := gFormatSQL(Format(lSQL, [lWhere, lOrder]), TagMapUnit);
end;
procedure TagMapUnitList_Read.MapRowToObject;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit.Create;
lObj.OID.AssignFromTIQuery('OID',Query);
lObj.ObjectState := posClean;
TtiObjectList(Visited).Add(lObj);
end;
{ TagMapUnitList_Create }
function TagMapUnitList_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapUnitList_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapUnitList_Create.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapUnitList_Delete }
function TagMapUnitList_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapUnitList_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapUnitList_Delete.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapUnitList_Save }
function TagMapUnitList_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapUnitList_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapUnitList_Save.SetupParams;
var
lObj: TagMapUnit;
begin
lObj := TagMapUnit(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClass_Create }
function TagMapClass_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapClass_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapClass_Create.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClass_Save }
function TagMapClass_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapClass_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapClass_Save.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClass_Read }
function TagMapClass_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posPK) OR (Visited.ObjectState = posClean);
end;
procedure TagMapClass_Read.Init;
begin
Query.SQLText :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here WHERE OID = :OID' ;
end;
procedure TagMapClass_Read.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
procedure TagMapClass_Read.MapRowToObject;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignFromTIQuery('OID',Query);
end;
{ TagMapClass_Delete }
function TagMapClass_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapClass_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapClass_Delete.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassList_Read }
function TagMapClassList_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posEmpty);
end;
procedure TagMapClassList_Read.Init;
var
lFiltered: ItiFiltered;
lWhere: string;
lOrder: string;
lSQL: string;
begin
if Supports(Visited, ItiFiltered, lFiltered) then
begin
if lFiltered.GetCriteria.HasCriteria then
lWhere := ' WHERE ' + tiCriteriaAsSQL(lFiltered.GetCriteria)
else
lWhere := '';
if lFiltered.GetCriteria.hasOrderBy then
lOrder := tiCriteriaOrderByAsSQL(lFiltered.GetCriteria)
else
lOrder := '';
end;
lSQL :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here %s %s ;';
Query.SQLText := gFormatSQL(Format(lSQL, [lWhere, lOrder]), TagMapClass);
end;
procedure TagMapClassList_Read.MapRowToObject;
var
lObj: TagMapClass;
begin
lObj := TagMapClass.Create;
lObj.OID.AssignFromTIQuery('OID',Query);
lObj.ObjectState := posClean;
TtiObjectList(Visited).Add(lObj);
end;
{ TagMapClassList_Create }
function TagMapClassList_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapClassList_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapClassList_Create.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassList_Delete }
function TagMapClassList_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapClassList_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapClassList_Delete.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassList_Save }
function TagMapClassList_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapClassList_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapClassList_Save.SetupParams;
var
lObj: TagMapClass;
begin
lObj := TagMapClass(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassProp_Create }
function TagMapClassProp_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapClassProp_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapClassProp_Create.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassProp_Save }
function TagMapClassProp_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapClassProp_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapClassProp_Save.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassProp_Read }
function TagMapClassProp_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posPK) OR (Visited.ObjectState = posClean);
end;
procedure TagMapClassProp_Read.Init;
begin
Query.SQLText :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here WHERE OID = :OID' ;
end;
procedure TagMapClassProp_Read.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
procedure TagMapClassProp_Read.MapRowToObject;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignFromTIQuery('OID',Query);
end;
{ TagMapClassProp_Delete }
function TagMapClassProp_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapClassProp_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapClassProp_Delete.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassPropList_Read }
function TagMapClassPropList_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posEmpty);
end;
procedure TagMapClassPropList_Read.Init;
var
lFiltered: ItiFiltered;
lWhere: string;
lOrder: string;
lSQL: string;
begin
if Supports(Visited, ItiFiltered, lFiltered) then
begin
if lFiltered.GetCriteria.HasCriteria then
lWhere := ' WHERE ' + tiCriteriaAsSQL(lFiltered.GetCriteria)
else
lWhere := '';
if lFiltered.GetCriteria.hasOrderBy then
lOrder := tiCriteriaOrderByAsSQL(lFiltered.GetCriteria)
else
lOrder := '';
end;
lSQL :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here %s %s ;';
Query.SQLText := gFormatSQL(Format(lSQL, [lWhere, lOrder]), TagMapClassProp);
end;
procedure TagMapClassPropList_Read.MapRowToObject;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp.Create;
lObj.OID.AssignFromTIQuery('OID',Query);
lObj.ObjectState := posClean;
TtiObjectList(Visited).Add(lObj);
end;
{ TagMapClassPropList_Create }
function TagMapClassPropList_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapClassPropList_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapClassPropList_Create.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassPropList_Delete }
function TagMapClassPropList_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapClassPropList_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapClassPropList_Delete.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapClassPropList_Save }
function TagMapClassPropList_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapClassPropList_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapClassPropList_Save.SetupParams;
var
lObj: TagMapClassProp;
begin
lObj := TagMapClassProp(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTable_Create }
function TagMapPropTable_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapPropTable_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapPropTable_Create.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTable_Save }
function TagMapPropTable_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapPropTable_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapPropTable_Save.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTable_Read }
function TagMapPropTable_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posPK) OR (Visited.ObjectState = posClean);
end;
procedure TagMapPropTable_Read.Init;
begin
Query.SQLText :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here WHERE OID = :OID' ;
end;
procedure TagMapPropTable_Read.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
procedure TagMapPropTable_Read.MapRowToObject;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignFromTIQuery('OID',Query);
end;
{ TagMapPropTable_Delete }
function TagMapPropTable_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapPropTable_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapPropTable_Delete.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTableList_Read }
function TagMapPropTableList_Read.AcceptVisitor: Boolean;
begin
result := (Visited.ObjectState = posEmpty);
end;
procedure TagMapPropTableList_Read.Init;
var
lFiltered: ItiFiltered;
lWhere: string;
lOrder: string;
lSQL: string;
begin
if Supports(Visited, ItiFiltered, lFiltered) then
begin
if lFiltered.GetCriteria.HasCriteria then
lWhere := ' WHERE ' + tiCriteriaAsSQL(lFiltered.GetCriteria)
else
lWhere := '';
if lFiltered.GetCriteria.hasOrderBy then
lOrder := tiCriteriaOrderByAsSQL(lFiltered.GetCriteria)
else
lOrder := '';
end;
lSQL :=
'SELECT ' +
' OID, ' +
'FROM db_table_name_here %s %s ;';
Query.SQLText := gFormatSQL(Format(lSQL, [lWhere, lOrder]), TagMapPropTable);
end;
procedure TagMapPropTableList_Read.MapRowToObject;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable.Create;
lObj.OID.AssignFromTIQuery('OID',Query);
lObj.ObjectState := posClean;
TtiObjectList(Visited).Add(lObj);
end;
{ TagMapPropTableList_Create }
function TagMapPropTableList_Create.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posCreate;
end;
procedure TagMapPropTableList_Create.Init;
begin
Query.SQLText :=
'INSERT INTO db_table_name_here(' +
' OID, ' +
') VALUES (' +
' :OID, ' +
') ';
end;
procedure TagMapPropTableList_Create.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTableList_Delete }
function TagMapPropTableList_Delete.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posDelete;
end;
procedure TagMapPropTableList_Delete.Init;
begin
Query.SQLText :=
'DELETE FROM db_table_name_here ' +
'WHERE OID = :OID';
end;
procedure TagMapPropTableList_Delete.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
{ TagMapPropTableList_Save }
function TagMapPropTableList_Save.AcceptVisitor: Boolean;
begin
result := Visited.ObjectState = posUpdate;
end;
procedure TagMapPropTableList_Save.Init;
begin
Query.SQLText :=
'UPDATE db_table_name_here SET ' +
'WHERE OID = :OID' ;
end;
procedure TagMapPropTableList_Save.SetupParams;
var
lObj: TagMapPropTable;
begin
lObj := TagMapPropTable(Visited);
lObj.OID.AssignToTIQuery('OID',Query);
end;
initialization
RegisterVisitors;
RegisterMappings;
end.
|
unit coolsms;
{ handler class interface를 만들어 아래 implementation에서 구현 }
interface
uses
System.Json, IdHash, IdHMACMD5, IDGlobal, DateUtils, IdException, IdHTTP, IdSSLOpenSSL, IdMultipartFormData, Classes, System.SysUtils;
type
handler = class
private
class var api_key : String;
class var api_secret : String;
public
{ set api_key and api_secret }
class procedure setApiKey(key: String; secret: String);
{ request(post) }
class function postRequest(method: String; data: TStringList; api_type: String): TJSONObject;
{ request(get) }
class function request(method: String; data: TStringList; api_type: String): TJSONObject;
end;
implementation
{ api request를 위해 Adata 값을 md5로 encrypt }
function hashHmacMd5(const AData, AKey: string): string;
var
HMACMD5: TIdHMACMD5;
KeyBytes: TIdBytes;
DataBytes: TIdBytes;
ResBytes: TIdBytes;
i: integer;
begin
HMACMD5 := TIdHMACMD5.Create;
try
HMACMD5.Key := ToBytes(AKey);
ResBytes := HMACMD5.HashValue(ToBytes(AData));
Result := '';
for i := low(ResBytes) to high(ResBytes) do
Result := Result + inttohex(ResBytes[i], 2);
finally
HMACMD5.Free;
end;
end;
{ get random string }
function randomString(): string;
var
str: string;
begin
Randomize;
//string with all possible chars
str := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
Result := '';
repeat
Result := Result + str[Random(Length(str)) + 1];
until (Length(Result) = 10)
end;
{ image를 제외한 string data 들을 data에 delimiter로 분리해서 넣는다 }
function split(delimiter: Char; input: string; data: TIdMultiPartFormDataStream): TIdMultiPartFormDataStream ;
var
strings: TStringList;
begin
strings := TSTringList.Create;
strings.Delimiter := delimiter;
strings.DelimitedText := input;
// 해당 string data가 image가 아니면 data에 add
if strings[0] <> 'image' then
begin
data.AddFormField(strings[0], strings[1]);
end;
strings.Clear;
Result := data;
end;
{ request(POST) }
class function handler.postRequest(method: String; data: TStringList; api_type: String): TJSONObject;
var
params: TStringList;
http: TIdHTTP;
idSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL;
jsonObject: TJSONObject;
signature: String;
salt: String;
response: String;
timestamp: String;
url: String;
multi_data: TIdMultiPartFormDataStream;
data_string: String;
begin
params := TStringList.Create;
http := TIdHTTP.Create();
salt := randomString();
jsonObject := TJSonObject.Create;
idSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create;
url := 'https://rest1.coolsms.co.kr/';
try
// currrent unix time
timestamp := IntToStr(DateTimetoUnix(IncHour(Now, -9)));
signature := hashHmacMd5(timestamp + salt, handler.api_secret);
data.Values['api_key'] := handler.api_key;
data.Values['salt'] := salt;
data.Values['signature'] := signature;
data.Values['timestamp'] := timestamp;
if method.Equals('send') = TRUE then
begin
// get Development Lang & version
if CompilerVersion.ToString() = '29' then data.Values['dev_lang'] := 'XE8';
if CompilerVersion.ToString() = '28' then data.Values['dev_lang'] := 'XE7';
if CompilerVersion.ToString() = '27' then data.Values['dev_lang'] := 'XE6';
if CompilerVersion.ToString() = '26' then data.Values['dev_lang'] := 'XE5';
if CompilerVersion.ToString() = '25' then data.Values['dev_lang'] := 'XE4';
data.Values['dev_lang'] := 'Delphi ' + data.Values['dev_lang'];
// get OS Version
if data.Values['os_platform'].IsEmpty = TRUE then
begin
data.Values['os_platform'] := IntToStr(Win32MajorVersion) + '.' + IntToStr(Win32MinorVersion);
if data.Values['os_platform'] = '5.0' then data.Values['os_platform'] := '2000';
if data.Values['os_platform'] = '5.1' then data.Values['os_platform'] := 'XP';
if data.Values['os_platform'] = '5.2' then data.Values['os_platform'] := '2003 server or XP64';
if data.Values['os_platform'] = '6.0' then data.Values['os_platform'] := 'Vista/2008 server';
if data.Values['os_platform'] = '6.1' then data.Values['os_platform'] := '7/2008 server R2';
data.Values['os_platform'] := 'Windows ' + data.Values['os_platform'];
end;
data.Values['sdk_version'] := 'Delphi SDK 1.0';
end;
// api_type에 따라 요청 url 변경
if (api_type = '') or (api_type = 'sms') then
url := url + 'sms/1.5/' + method
else
url := url + api_type + '/1/' + method;
http.IOHandler := idSSLIOHandlerSocketOpenSSL;
http.Request.ContentType := 'application/x-www-form-urlencoded';
http.Request.UserAgent := 'Delphi';
// image가 있으면 TStringList가 아닌 TIdMultiPartFormDataStream으로 data를 전송한다.
if data.Values['image'].IsEmpty = FALSE then
begin
multi_data := TIdMultiPartFormDataStream.Create;
for data_string in data do
multi_data := split('=', data_string, multi_data);
multi_data.AddFile('image', data.Values['image']);
response := http.Post(url, multi_data);
end
else
begin
response := http.Post(url, data);
end;
if response.Equals('') = FALSE then
begin
// response가 있다면
jsonObject := TJSONObject.ParseJSONValue(response) as TJSONObject;
end;
jsonObject.AddPair(TJSONPair.Create('status', TJSONTrue.Create));
Result := jsonObject;
except
// http exception 처리
on E: EIdHTTPProtocolException do
begin
jsonObject := TJSONObject.ParseJSONValue(E.ErrorMessage) as TJSONObject;
jsonObject.AddPair(TJSONPair.Create('status', TJSONFalse.Create));
Result := jsonObject;
end;
// 그외 exception 처리
on E: Exception do
begin
jsonObject.AddPair(TJSONPair.Create('message', E.Message));
jsonObject.AddPair(TJSONPair.Create('status', TJSONFalse.Create));
Result := jsonObject;
end;
end;
http.Free;
end;
{ request(GET) }
class function handler.request(method: String; data: TStringList; api_type: String): TJSONObject;
var
http: TIdHTTP;
jsonObject: TJSONObject;
url: String;
signature: String;
salt: String;
timestamp: String;
data_string: String;
response: String;
begin
http := TIdHTTP.Create();
url := 'https://rest1.coolsms.co.kr/';
salt := randomString();
jsonObject := TJSONObject.Create;
try
// currrent unix time
timestamp := IntToStr(DateTimetoUnix(IncHour(Now, -9)));
signature := hashHmacMd5(timestamp + salt, handler.api_secret);
if data = nil then data := TStringList.Create;
// 기본설정
data.Values['api_key'] := handler.api_key;
data.Values['salt'] := salt;
data.Values['signature'] := signature;
data.Values['timestamp'] := timestamp;
// api_type에 따라 요청 url 변경
if (api_type = '') or (api_type = 'sms') then
url := url + 'sms/1.5/' + method + '?'
else
url := url + api_type + '/1/' + method + '?';
for data_string in data Do
url := url + data_string + '&';
delete(url, length(url), 1);
response := http.get(url);
jsonObject := TJSONObject.ParseJSONValue(response) as TJSONObject;
jsonObject.AddPair(TJSONPair.Create('status', TJSONTrue.Create));
Result := jsonObject;
except
on E: EIdHTTPProtocolException do
begin
//jsonObject.AddPair(TJSONPair.Create('John','Doe'));
jsonObject := TJSONObject.ParseJSONValue(E.ErrorMessage) as TJSONObject;
jsonObject.AddPair(TJSONPair.Create('status', TJSONFalse.Create));
Result := jsonObject;
end;
on E: Exception do
begin
jsonObject.AddPair(TJSONPair.Create('message', E.Message));
jsonObject.AddPair(TJSONPair.Create('status', TJSONFalse.Create));
Result := jsonObject;
end;
end;
http.Free;
end;
{ set api_key and api_secret }
class procedure handler.setApiKey(key: String; secret: String);
begin
api_key := key;
api_secret := secret;
end;
end.
|
unit RepChart;
interface
uses Windows, SysUtils, Messages, Classes, Graphics, Controls,
StdCtrls, ExtCtrls, Forms, Quickrpt, QRCtrls, TeEngine, Series, TeeProcs,
Chart, DBChart, QrTee;
type
TReportChart = class(TQuickRep)
TitleBand: TQRBand;
QRChart: TQRChart;
QRDBChart: TQRDBChart;
QRLabel1: TQRLabel;
procedure TitleBandBeforePrint(Sender: TQRCustomBand;
var PrintBand: Boolean);
procedure TitleBandAfterPrint(Sender: TQRCustomBand;
BandPrinted: Boolean);
private
FChart:TCustomChart;
public
constructor Create(AOwner:TComponent); override;
procedure AssignChart(AChart:TCustomChart);
end;
var
ReportChart: TReportChart;
implementation
{$R *.DFM}
constructor TReportChart.Create(AOwner:TComponent);
begin
inherited;
end;
procedure TReportChart.AssignChart(AChart:TCustomChart);
begin
FChart:=AChart;
with QRDBChart do begin
Title:=FChart.Title;
AxisVisible:=FChart.AxisVisible;
BackWall:=FChart.BackWall;
BottomWall:=FChart.BottomWall;
LeftWall:=FChart.LeftWall;
TopAxis:=FChart.TopAxis;
BottomAxis:=FChart.BottomAxis;
LeftAxis:=FChart.LeftAxis;
RightAxis:=FChart.RightAxis;
DepthAxis:=FChart.DepthAxis;
Chart3DPercent:=FChart.Chart3DPercent;
ClipPoints:=FChart.ClipPoints;
Foot:=FChart.Foot;
Frame:=FChart.Frame;
Legend:=FChart.Legend;
MaxPointsPerPage:=FChart.MaxPointsPerPage;
Page:=FChart.Page;
ScaleLastPage:=FChart.ScaleLastPage;
View3D:=FChart.View3D;
View3DOptions:=FChart.View3DOptions;
View3DWalls:=FChart.View3DWalls;
if (ReportTitle<>'') and (QRDBChart.Title.Text.Text='') then begin
QRDBChart.Title.Text.Text:=ReportTitle;
QRDBChart.Title.Visible:=true;
end;
end;
end;
procedure TReportChart.TitleBandBeforePrint(Sender: TQRCustomBand;
var PrintBand: Boolean);
begin
PrintBand:=FChart<>nil;
if not PrintBand then Exit;
if (ReportTitle<>'') and (QRDBChart.Title.Text.Text='') then begin
QRDBChart.Title.Text.Text:=ReportTitle;
QRDBChart.Title.Visible:=true;
end;
with FChart do while SeriesCount>0 do Series[0].ParentChart:=QRDBChart;
end;
procedure TReportChart.TitleBandAfterPrint(Sender: TQRCustomBand;
BandPrinted: Boolean);
begin
with QRDBChart do while SeriesCount>0 do Series[0].ParentChart:=FChart;
end;
end.
|
unit TEST_xpParse;
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* This code was inspired to expidite the creation of unit tests
* for use the Dunit test frame work.
*
* The Initial Developer of XPGen is Michael A. Johnson.
* Portions created The Initial Developer is Copyright (C) 2000.
* Portions created by The DUnit Group are Copyright (C) 2000.
* All rights reserved.
*
* Contributor(s):
* Michael A. Johnson <majohnson@golden.net>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
interface
uses
classes,
TestFramework,
parseDef,
xpParse,
SysUtils;
type
TParseNodeParams = record
NameOfClass : string;
NumPublicMethods,
NumProtectedMethods,
NumPrivateMethods : integer;
end;
MockTParseNodeClass = class(TParseNodeClass);
MockTXPStubParser = class(TXPStubParser);
TEST_TParseNodeClass = class(TTestCase)
public
procedure setUp; override;
procedure tearDown; override;
end;
TEST_TXPStubParser = class(TTestCase)
protected
testInstance: MockTXPStubParser;
procedure SetupParse(parser: MockTXPStubParser; filename: TFilename);
procedure TeardownParse(parser: MockTXPStubParser);
function HasExpectedParseNodes(parseNodeList : TList;const NodeParams : array of TParseNodeParams) : boolean;
public
procedure setUp; override;
procedure tearDown; override;
published
procedure test_Get_Token;
procedure test_Parse_Unit_Heading;
procedure test_Parse_const_Paragraph;
procedure test_Parse_type_Paragraph;
procedure test_Parse_var_paragraph;
procedure test_Parse_uses_clause;
procedure test_Parse_typedef;
procedure test_Parse_tobject_derived;
procedure test_Parse_derived;
procedure test_SyncToken;
procedure test_ParseEventDef;
end;
function Suite: ITestSuite;
implementation
uses
xpLex,
dialogs;
function Suite: ITestSuite;
begin
result := TTestSuite.create('xpGen xpParse tests');
end;
procedure TEST_TParseNodeClass.setUp;
begin
end;
procedure TEST_TParseNodeClass.tearDown;
begin
end;
procedure TEST_TXPStubParser.setUp;
begin
testInstance := MockTXPStubParser.Create;
end;
procedure TEST_TXPStubParser.tearDown;
begin
testInstance.free;
end;
procedure TEST_TXPStubParser.TEST_Get_Token;
const
{ list of tokens expected from the the test file }
ExpectedToken: array[1..20] of string =
(
'unit', 'TEST_xpParse', ';', '(',
')', '[', ']', ':', '=', '*', '/', '+', 'interface',
'uses', 'DUnit', ',', 'xpParse', ',', 'SysUtils', ';'
);
var
iter: integer;
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Get_Token.txt');
try
for iter := low(ExpectedToken) to High(ExpectedToken) do
begin
token := testInstance.Get_Token(testInstance.Lex);
check(ExpectedToken[iter] = token.Str, 'Unexpected Parse Token');
end;
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_Unit_Heading;
const
ExpectedEnum = kw_semi;
ExpectedToken = ';';
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_Unit_Heading.txt');
try
token := testInstance.Get_Token(testInstance.lex);
check(token.token_type = kw_unit,'Expected Keyword Unit');
token := testInstance.Parse_Unit_Heading(testInstance.lex);
check(expectedToken=token.Str, 'Unexpected parse token');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_const_Paragraph;
const
ExpectedEnum = kw_type;
ExpectedToken = 'type';
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_const_Paragraph.txt');
try
token := testInstance.Get_Token(testInstance.lex);
Check(token.token_type = kw_const,'Expected Keyword const');
token := testInstance.Parse_const_paragraph(testInstance.lex);
check(expectedToken = token.Str, 'Unexpected parse token');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_type_Paragraph;
const
ExpectedEnum = kw_var;
ExpectedToken = 'var';
const
ExpectedParseNodes : array[1..4] of TParseNodeParams =
(
(NameOfClass: 'EUnitIDExpected'; NumPublicMethods: 0; NumProtectedMethods: 0;NumPrivateMethods: 0),
(NameOfClass: 'EEqualExpected'; NumPublicMethods: 0; NumProtectedMethods: 0;NumPrivateMethods: 0),
(NameOfClass: 'TParseNodeClass'; NumPublicMethods: 1; NumProtectedMethods: 0;NumPrivateMethods: 0),
(NameOfClass: 'TXPStubParser'; NumPublicMethods: 1; NumProtectedMethods: 15;NumPrivateMethods: 0)
);
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_type_Paragraph.txt');
try
check(0=testInstance.fParseNodeList.count,'Unexpected Parse node count');
token := testInstance.Get_Token(testInstance.lex);
assert(kw_type = token.token_type,'Expected KW Type');
token := testInstance.Parse_type_Paragraph(testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
HasExpectedParseNodes(testInstance.fparseNodeList,ExpectedParseNodes);
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_var_paragraph;
const
ExpectedEnum = kw_semi;
ExpectedToken = ';';
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_var_paragraph.txt');
try
token := testInstance.Get_Token(testInstance.lex);
assert(token.token_type = kw_var,'Expected Keyword Unit');
token := testInstance.Parse_Unit_Heading(testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_uses_clause;
const
ExpectedEnum = kw_semi;
ExpectedToken = ';';
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_uses_clause.txt');
try
token := testInstance.Get_Token(testInstance.lex);
assert(token.token_type = kw_uses,'Expected Keyword Unit');
token := testInstance.Parse_Unit_Heading(testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_typedef;
const
ExpectedEnum = kw_end;
ExpectedToken = 'end';
const
ExpectedParseNodes : array[1..1] of TParseNodeParams =
(
(NameOfClass: 'TXPStubParser'; NumPublicMethods: 1; NumProtectedMethods: 15;NumPrivateMethods: 0)
);
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_Parse_typedef.txt');
try
check(0=testInstance.fParseNodeList.count,'Unexpected Parse node count');
token := testInstance.Get_Token(testInstance.lex);
assert(kw_ident = token.token_type,'Expected identifier');
token := testInstance.Parse_typedef(token.str,testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
HasExpectedParseNodes(testInstance.fparseNodeList,ExpectedParseNodes);
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_tobject_derived;
const
ExpectedEnum = kw_end;
ExpectedToken = 'end';
var
token: lex_token;
parseNode : TParseNodeClass;
begin
SetupParse(testInstance, 'TEST_Parse_tobject_derived.txt');
try
check(testInstance.fParseNodeList.count=0,'Unexpected Parse node count');
testInstance.NewClassNode('foo');
token := testInstance.Get_Token(testInstance.lex);
assert(token.token_type = kw_class,'Expected Keyword class');
token := testInstance.Parse_tobject_derived(token,testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
check(testInstance.fParseNodeList.count=1,'Unexpected Parse node count');
parseNode := testInstance.fParseNodeList.first;
check(4=parseNode.fPubMethodList.count,'Unexepected number of public methods');
check(3=parseNode.fPvtMethodList.count,'Unexepected number of private methods');
check(3=parseNode.fPrtMethodList.count,'Unexepected number of protected methods');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_Parse_derived;
const
ExpectedEnum = kw_end;
ExpectedToken = 'end';
var
token: lex_token;
parseNode : TParseNodeClass;
begin
SetupParse(testInstance, 'TEST_Parse_derived.txt');
try
check(testInstance.fParseNodeList.count=0,'Unexpected Parse node count');
testInstance.NewClassNode('foo');
token := testInstance.Get_Token(testInstance.lex);
assert(kw_openParen = token.token_type,'Expected Identifier');
token := testInstance.Parse_derived(token.str,testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
check(testInstance.fParseNodeList.count=1,'Unexpected Parse node count');
parseNode := testInstance.fParseNodeList.first;
check(4=parseNode.fPubMethodList.count,'Unexepected number of public methods');
check(3=parseNode.fPvtMethodList.count,'Unexepected number of private methods');
check(3=parseNode.fPrtMethodList.count,'Unexepected number of protected methods');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.TEST_SyncToken;
const
ExpectedEnum = kw_semi;
ExpectedToken = ';';
var
token: lex_token;
begin
try
SetupParse(testInstance, 'TEST_Get_Token.txt');
token := testInstance.SyncToken(expectedEnum,testInstance.lex);
check(expectedToken= token.Str, 'Unexpected parse token');
finally
TearDownParse(testInstance);
end;
end;
procedure TEST_TXPStubParser.SetupParse(parser: MockTXPStubParser;
filename: TFilename);
var
inputFile: TFileStream;
begin
InputFile := TFileStream.Create(filename, fmOpenRead);
parser.SrcStream := InputFile;
parser.lex := TLexer.create(inputFile);
end;
procedure TEST_TXPStubParser.TeardownParse(
parser: MockTXPStubParser);
begin
parser.lex.Free;
parser.SrcStream.Free;
parser.SrcStream := nil;
parser.lex := nil;
testInstance.EmptyParseNodeList;
end;
function TEST_TXPStubParser.HasExpectedParseNodes(parseNodeList: TList;
const NodeParams: array of TParseNodeParams): boolean;
var
parseNode : TParseNodeClass;
nodeIter : integer;
begin
check(high(NodeParams)-Low(NodeParams)+1=parseNodeList.count,'Unexpected number of nodes');
for nodeIter := low(NodeParams) to high(NodeParams) do
begin
ParseNode := ParseNodeList[nodeIter - low(NodeParams)];
check(NodeParams[nodeIter].NumPublicMethods=ParseNode.PubMethodList.count,'Unexpected number of public methods');
check(NodePArams[nodeIter].NumProtectedMethods=ParseNode.PrtMethodList.count,'Unexpected number of protected methods');
check(NodePArams[nodeIter].NumPrivateMethods=ParseNode.PvtMethodList.count,'Unexpected number of private methods');
end;
result := true;
end;
procedure TEST_TXPStubParser.test_ParseEventDef;
var
token: lex_token;
begin
SetupParse(testInstance, 'TEST_parseEventDef.txt');
try
token := TestInstance.SyncToken(kw_procedure,testInstance.lex);
Check(token.token_type = kw_procedure,'event type def not found');
token := TestInstance.ParseEventDef(token,testInstance.lex);
Check(token.token_type = kw_semi,'did not parse the simple event def');
token := TestInstance.SyncToken(kw_procedure,testInstance.lex);
Check(token.token_type = kw_procedure,'event type def not found');
token := TestInstance.ParseEventDef(token,testInstance.lex);
Check(token.token_type = kw_semi,'did not parse the complex event def');
finally
TearDownParse(testInstance);
end;
end;
initialization
TestFrameWork.RegisterTests('XPGEN parser tests',[
TEST_TXPStubParser.Suite,
TEST_TParseNodeClass.Suite
]);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Parser object to allow on-the-fly parsing and }
{ text insertion }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit CopyPrsr;
interface
uses Classes;
const
toEOL = Char(5);
type
{ TCopyParser }
TCopyParser = class(TObject)
private
FStream: TStream;
FOutStream: TStream;
FOrigin: Longint;
FBuffer: PChar;
FBufPtr: PChar;
FBufEnd: PChar;
FSourcePtr: PChar;
FSourceEnd: PChar;
FTokenPtr: PChar;
FStringPtr: PChar;
FSourceLine: Integer;
FSaveChar: Char;
FToken: Char;
procedure ReadBuffer;
procedure SkipBlanks(DoCopy: Boolean);
function SkipToNextToken(CopyBlanks, DoCopy: Boolean): Char;
function CopySkipTo(Length: Integer; DoCopy: Boolean): string;
function CopySkipToToken(AToken: Char; DoCopy: Boolean): string;
function CopySkipToEOL(DoCopy: Boolean): string;
function CopySkipToEOF(DoCopy: Boolean): string;
procedure UpdateOutStream(StartPos: PChar);
public
constructor Create(Stream, OutStream: TStream);
destructor Destroy; override;
procedure CheckToken(T: Char);
procedure CheckTokenSymbol(const S: string);
function CopyTo(Length: Integer): string;
function CopyToToken(AToken: Char): string;
function CopyToEOL: string;
function CopyToEOF: string;
procedure CopyTokenToOutput;
procedure Error(const Ident: string);
procedure ErrorFmt(const Ident: string; const Args: array of const);
procedure ErrorStr(const Message: string);
function NextToken: Char;
function SkipToken(CopyBlanks: Boolean): Char;
procedure SkipEOL;
function SkipTo(Length: Integer): string;
function SkipToToken(AToken: Char): string;
function SkipToEOL: string;
function SkipToEOF: string;
function SourcePos: Longint;
function TokenComponentIdent: String;
function TokenFloat: Extended;
function TokenInt: Longint;
function TokenString: string;
function TokenSymbolIs(const S: string): Boolean;
property SourceLine: Integer read FSourceLine;
property Token: Char read FToken;
end;
implementation
uses SysUtils, Consts;
{ TCopyParser }
const
ParseBufSize = 4096;
constructor TCopyParser.Create(Stream, OutStream: TStream);
begin
FStream := Stream;
FOutStream := OutStream;
GetMem(FBuffer, ParseBufSize);
FBuffer[0] := #0;
FBufPtr := FBuffer;
FBufEnd := FBuffer + ParseBufSize;
FSourcePtr := FBuffer;
FSourceEnd := FBuffer;
FTokenPtr := FBuffer;
FSourceLine := 1;
SkipToken(True);
end;
destructor TCopyParser.Destroy;
begin
if FBuffer <> nil then
begin
FStream.Seek(Longint(FTokenPtr) - Longint(FBufPtr), 1);
FreeMem(FBuffer, ParseBufSize);
end;
end;
procedure TCopyParser.CheckToken(T: Char);
begin
if Token <> T then
case T of
toSymbol:
Error(SIdentifierExpected);
toString:
Error(SStringExpected);
toInteger, toFloat:
Error(SNumberExpected);
else
ErrorFmt(SCharExpected, [T]);
end;
end;
procedure TCopyParser.CheckTokenSymbol(const S: string);
begin
if not TokenSymbolIs(S) then ErrorFmt(SSymbolExpected, [S]);
end;
function TCopyParser.CopySkipTo(Length: Integer; DoCopy: Boolean): string;
var
P: PChar;
Temp: string;
begin
Result := '';
repeat
P := FTokenPtr;
while (Length > 0) and (P^ <> #0) do
begin
Inc(P);
Dec(Length);
end;
if DoCopy and (FOutStream <> nil) then
FOutStream.WriteBuffer(FTokenPtr^, P - FTokenPtr);
SetString(Temp, FTokenPtr, P - FTokenPtr);
Result := Result + Temp;
if Length > 0 then ReadBuffer;
until (Length = 0) or (Token = toEOF);
FSourcePtr := P;
end;
function TCopyParser.CopySkipToEOL(DoCopy: Boolean): string;
var
P: PChar;
begin
P := FTokenPtr;
while not (P^ in [#13, #10, #0]) do Inc(P);
SetString(Result, FTokenPtr, P - FTokenPtr);
if P^ = #13 then Inc(P);
FSourcePtr := P;
if DoCopy then UpdateOutStream(FTokenPtr);
NextToken;
end;
function TCopyParser.CopySkipToEOF(DoCopy: Boolean): string;
var
P: PChar;
Temp: string;
begin
repeat
P := FTokenPtr;
while P^ <> #0 do Inc(P);
FSourcePtr := P;
SetString(Temp, FTokenPtr, P - FTokenPtr);
Result := Result + Temp;
if DoCopy then
begin
UpdateOutStream(FTokenPtr);
NextToken;
end else SkipToken(False);
FTokenPtr := FSourcePtr;
until Token = toEOF;
end;
function TCopyParser.CopySkipToToken(AToken: Char; DoCopy: Boolean): string;
var
S: PChar;
Temp: string;
procedure InternalSkipBlanks;
begin
while True do
begin
case FSourcePtr^ of
#0:
begin
SetString(Temp, S, FSourcePtr - S);
Result := Result + Temp;
if DoCopy then UpdateOutStream(S);
ReadBuffer;
if FSourcePtr^ = #0 then Exit;
S := FSourcePtr;
Continue;
end;
#10:
Inc(FSourceLine);
#33..#255:
Break;
end;
Inc(FSourcePtr);
end;
if DoCopy then UpdateOutStream(S);
end;
begin
Result := '';
while (Token <> AToken) and (Token <> toEOF) do
begin
S := FSourcePtr;
InternalSkipBlanks;
if S <> FSourcePtr then
begin
SetString(Temp, S, FSourcePtr - S);
Result := Result + Temp;
end;
SkipToNextToken(DoCopy, DoCopy);
if Token <> AToken then
begin
SetString(Temp, FTokenPtr, FSourcePtr - FTokenPtr);
Result := Result + Temp;
end;
end;
end;
function TCopyParser.CopyTo(Length: Integer): string;
begin
Result := CopySkipTo(Length, True);
end;
function TCopyParser.CopyToToken(AToken: Char): string;
begin
Result := CopySkipToToken(AToken, True);
end;
function TCopyParser.CopyToEOL: string;
begin
Result := CopySkipToEOL(True);
end;
function TCopyParser.CopyToEOF: string;
begin
Result := CopySkipToEOF(True);
end;
procedure TCopyParser.CopyTokenToOutput;
begin
UpdateOutStream(FTokenPtr);
end;
procedure TCopyParser.Error(const Ident: string);
begin
ErrorStr(Ident);
end;
procedure TCopyParser.ErrorFmt(const Ident: string; const Args: array of const);
begin
ErrorStr(Format(Ident, Args));
end;
procedure TCopyParser.ErrorStr(const Message: string);
begin
raise EParserError.CreateResFmt(@SParseError, [Message, FSourceLine]);
end;
function TCopyParser.NextToken: Char;
begin
Result := SkipToNextToken(True, True);
end;
function TCopyParser.SkipTo(Length: Integer): string;
begin
Result := CopySkipTo(Length, False);
end;
function TCopyParser.SkipToToken(AToken: Char): string;
begin
Result := CopySkipToToken(AToken, False);
end;
function TCopyParser.SkipToEOL: string;
begin
Result := CopySkipToEOL(False);
end;
function TCopyParser.SkipToEOF: string;
begin
Result := CopySkipToEOF(False);
end;
function TCopyParser.SkipToNextToken(CopyBlanks, DoCopy: Boolean): Char;
var
P, StartPos: PChar;
begin
SkipBlanks(CopyBlanks);
P := FSourcePtr;
FTokenPtr := P;
case P^ of
'A'..'Z', 'a'..'z', '_':
begin
Inc(P);
while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_'] do Inc(P);
Result := toSymbol;
end;
#10:
begin
Inc(P);
Inc(FSourceLine);
Result := toEOL;
end;
else
Result := P^;
if Result <> toEOF then Inc(P);
end;
StartPos := FSourcePtr;
FSourcePtr := P;
if DoCopy then UpdateOutStream(StartPos);
FToken := Result;
end;
function TCopyParser.SkipToken(CopyBlanks: Boolean): Char;
begin
Result := SkipToNextToken(CopyBlanks, False);
end;
procedure TCopyParser.ReadBuffer;
var
Count: Integer;
begin
Inc(FOrigin, FSourcePtr - FBuffer);
FSourceEnd[0] := FSaveChar;
Count := FBufPtr - FSourcePtr;
if Count <> 0 then Move(FSourcePtr[0], FBuffer[0], Count);
FBufPtr := FBuffer + Count;
Inc(FBufPtr, FStream.Read(FBufPtr[0], FBufEnd - FBufPtr));
FSourcePtr := FBuffer;
FSourceEnd := FBufPtr;
if FSourceEnd = FBufEnd then
begin
FSourceEnd := LineStart(FBuffer, FSourceEnd - 1);
if FSourceEnd = FBuffer then Error(SLineTooLong);
end;
FSaveChar := FSourceEnd[0];
FSourceEnd[0] := #0;
end;
procedure TCopyParser.SkipBlanks(DoCopy: Boolean);
var
Start: PChar;
begin
Start := FSourcePtr;
while True do
begin
case FSourcePtr^ of
#0:
begin
if DoCopy then UpdateOutStream(Start);
ReadBuffer;
if FSourcePtr^ = #0 then Exit;
Start := FSourcePtr;
Continue;
end;
#10:
Inc(FSourceLine);
#33..#255:
Break;
end;
Inc(FSourcePtr);
end;
if DoCopy then UpdateOutStream(Start);
end;
function TCopyParser.SourcePos: Longint;
begin
Result := FOrigin + (FTokenPtr - FBuffer);
end;
procedure TCopyParser.SkipEOL;
begin
if Token = toEOL then
begin
while FTokenPtr^ in [#13, #10] do Inc(FTokenPtr);
FSourcePtr := FTokenPtr;
if FSourcePtr^ <> #0 then
NextToken
else FToken := #0;
end;
end;
function TCopyParser.TokenFloat: Extended;
begin
Result := StrToFloat(TokenString);
end;
function TCopyParser.TokenInt: Longint;
begin
Result := StrToInt(TokenString);
end;
function TCopyParser.TokenString: string;
var
L: Integer;
begin
if FToken = toString then
L := FStringPtr - FTokenPtr else
L := FSourcePtr - FTokenPtr;
SetString(Result, FTokenPtr, L);
end;
function TCopyParser.TokenSymbolIs(const S: string): Boolean;
begin
Result := (Token = toSymbol) and (CompareText(S, TokenString) = 0);
end;
function TCopyParser.TokenComponentIdent: String;
var
P: PChar;
begin
CheckToken(toSymbol);
P := FSourcePtr;
while P^ = '.' do
begin
Inc(P);
if not (P^ in ['A'..'Z', 'a'..'z', '_']) then
Error(SIdentifierExpected);
repeat
Inc(P)
until not (P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_']);
end;
FSourcePtr := P;
Result := TokenString;
end;
procedure TCopyParser.UpdateOutStream(StartPos: PChar);
begin
if FOutStream <> nil then
FOutStream.WriteBuffer(StartPos^, FSourcePtr - StartPos);
end;
end.
|
(**
This module contains a class that implements the IDE notifiers so that before and after
compilation events can be handled.
@Author David Hoyle.
@Version 1.0
@Date 12 Jan 2018
**)
Unit ITHelper.IDENotifierInterface;
Interface
Uses
ToolsAPI,
Contnrs,
ITHelper.TestingHelperUtils,
ITHelper.ConfigurationForm,
ExtCtrls,
Classes,
IniFiles,
ITHelper.ExternalProcessInfo,
ITHelper.Interfaces;
{$INCLUDE 'CompilerDefinitions.inc'}
Type
(** A class to implement the IDE notifier interfaces **)
TITHelperIDENotifier = Class(TNotifierObject, IOTANotifier, IOTAIDENotifier, IOTAIDENotifier50,
IOTAIDENotifier80)
Strict Private
{ Private declarations }
FGlobalOps : IITHGlobalOptions;
FSuccessfulCompile : TTimer;
FLastSuccessfulCompile : Int64;
FShouldBuildList : TStringList;
FMsgMgr : IITHMessageManager;
Strict Protected
// IOTANotifier
// IOTAIDENotifier
Procedure FileNotification(NotifyCode: TOTAFileNotification; Const FileName: String;
Var Cancel: Boolean);
Procedure BeforeCompile(Const Project: IOTAProject; Var Cancel: Boolean); Overload;
Procedure AfterCompile(Succeeded: Boolean); Overload;
// IOTAIDENotifier50
Procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); Overload;
Procedure BeforeCompile(Const Project: IOTAProject; IsCodeInsight: Boolean;
Var Cancel: Boolean); Overload;
// IOTAIDENotifier80
Procedure AfterCompile(Const Project: IOTAProject; Succeeded: Boolean;
IsCodeInsight: Boolean); Overload;
// General Methods
Function ProcessCompileInformation(Const ProjectOps : IITHProjectOptions; Const Project: IOTAProject;
Const strWhere: String): Integer;
Procedure IncrementBuild(Const ProjectOps : IITHProjectOptions; Const Project: IOTAProject;
Const strProject: String);
Procedure CopyVersionInfoFromDependency(Const Project: IOTAProject; Const strProject: String;
Const ProjectOps: IITHProjectOptions);
Procedure ProcessAfterCompile(Const Project: IOTAProject;
Succeeded, IsCodeInsight: Boolean);
Procedure SuccessfulCompile(Sender: TObject);
Procedure ExpandProcessMacro(Const Processes: TITHProcessCollection; Const Project: IOTAProject);
Procedure ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean);
Procedure IdleHandler;
Public
{ Public declarations }
Constructor Create(Const GlobalOps: IITHGlobalOptions);
Destructor Destroy; Override;
End;
Implementation
Uses
{$IFDEF CODESITE}
CodeSiteLogging,
{$ENDIF}
ITHelper.EnabledOptions,
ITHelper.ProcessingForm,
Windows,
SysUtils,
StrUtils,
Graphics,
Forms,
{$IFDEF DXE20}
CommonOptionStrs,
{$ENDIF}
Variants,
ITHelper.CommonFunctions,
ITHelper.Types,
ITHelper.ZIPManager,
ITHelper.MessageManager,
ITHelper.VersionManager;
Type
(** A custom exception for ITHelper problems. **)
EITHException = Class(Exception);
ResourceString
(** This is the warning shown if there are no after compilation tools. **)
strAfterCompileWARNING = 'WARNING: There are no Post-Compilation tools configured (%s).';
(** This is the warning shown if there are no before compilation tools. **)
strBeforeCompileWARNING = 'WARNING: There are no Pre-Compilation tools configured (%s).';
{$IFDEF DXE20}
(** A resource string messge for broken Open Tools API version control XE2 ONLY!!!! **)
strMsgBroken = 'The Open Tools API''s ability to manipulale the build number of the ' +
'version information is broken. Althought the number can be incremented this is ' +
'not included in the EXE/DLL and this incrementation is lost when the project is ' +
'closed. Please turn off the IDE''s version numbering and use ITHelper''s own ' +
'mechanism for handling version information in the project options dialogue.';
(** A resource string messge for incrementing build number but ITHelpers version control is not
enabled. **)
strMsgIncBuildDisabled = 'You have enabled the incrementation of the build number on ' +
'successful compilation but you have not enabled ITHelper''s handling of version ' +
'information in the project options dialogue.';
(** A resource string messge for broken Open Tools API version control XE2 ONLY!!!! **)
strMsgCopyDisabled = 'You have enabled the copying of version information from an ' +
'existing executabe but you have not enabled ITHelper''s handling of version ' +
'information in the project options dialogue.';
{$ENDIF}
Const
(** This number of milliseconds in a second. **)
iMilliSecInSec = 1000;
(**
This is an null implementation for the AfterCompile interface.
@precon None.
@postcon Not implemented.
@nocheck EmptyMethod MissingCONSTInParam
@nohint Succeeded
@param Succeeded as a Boolean
**)
Procedure TITHelperIDENotifier.AfterCompile(Succeeded: Boolean);
Begin //FI:W519
End;
(**
This is an null implementation for the AfterCompile interface.
@precon None.
@postcon Not implemented.
@nocheck MissingCONSTInParam EmptyMethod
@nohint Succeeded IsCodeInsight
@param Succeeded as a Boolean
@param IsCodeInsight as a Boolean
**)
Procedure TITHelperIDENotifier.AfterCompile(Succeeded, IsCodeInsight: Boolean);
Begin
{$IFNDEF D2005} // For D7 and below
ProcessAfterCompile(ActiveProject, Succeeded, IsCodeInsight);
{$ENDIF}
End;
{$IFDEF D2005}
(**
This is an implementation for the AfterCompile interface.
@precon None.
@postcon If the compile is not from CodeInsight then the before compilation
external tools associated with the compiled project are run.
@nocheck MissingCONSTInParam
@param Project as an IOTAProject as a constant
@param Succeeded as a Boolean
@param IsCodeInsight as a Boolean
**)
Procedure TITHelperIDENotifier.AfterCompile(Const Project: IOTAProject;
Succeeded, IsCodeInsight: Boolean);
Begin // For D2005 and above
ProcessAfterCompile(Project, Succeeded, IsCodeInsight);
End;
{$ENDIF}
(**
This is an implementation for the BeforeCompile interface.
@precon None.
@postcon If the compile is not from CodeInsight then the before compilation
external tools associated with the compiled project are run.
@nocheck MissingCONSTInParam
@param Project as an IOTAProject as a constant
@param IsCodeInsight as a Boolean
@param Cancel as a Boolean as a reference
**)
Procedure TITHelperIDENotifier.BeforeCompile(Const Project: IOTAProject; IsCodeInsight: Boolean;
Var Cancel: Boolean);
ResourceString
strPreCompilation = 'Pre-Compilation';
strPreCompilationToolsFailed = 'Pre-Compilation Tools Failed (%s).';
Var
iResult: Integer;
strProject: String;
ProjectOps: IITHProjectOptions;
iInterval: Int64;
Ops: TITHEnabledOptions;
MS: IOTAMessageServices;
VersionMgr : IITHVersionManager;
Begin
If Project = Nil Then
Exit;
If IsCodeInsight Then
Exit;
ProjectOps := FGlobalOps.ProjectOptions(Project);
Try
iInterval := FGlobalOps.ClearMessages;
If iInterval > 0 Then
If FMsgMgr.LastMessage < GetTickCount - iInterval * iMilliSecInSec Then
ClearMessages([cmCompiler, cmGroup]);
If Project.ProjectBuilder.ShouldBuild Then
Begin
FShouldBuildList.Add(Project.FileName);
Ops := FGlobalOps.ProjectGroupOps;
If eoGroupEnabled In Ops Then
Begin
Try
strProject := GetProjectName(Project);
If eoCopyVersionInfo In Ops Then
CopyVersionInfoFromDependency(Project, strProject, ProjectOps);
If eoBefore In Ops Then
If Supports(BorlandIDEServices, IOTAMessageServices, MS) Then
Begin
iResult := ProcessCompileInformation(ProjectOps, Project, strPreCompilation);
If iResult > 0 Then
Begin
Cancel := True;
TfrmITHProcessing.ShowProcessing
(Format(strPreCompilationToolsFailed, [strProject]),
FGlobalOps.FontColour[ithfWarning], True);
ShowHelperMessages(FGlobalOps.GroupMessages);
End
Else If iResult < 0 Then
If ProjectOps.WarnBefore Then
Begin
FMsgMgr.AddMsg(Format(strBeforeCompileWARNING, [strProject]), fnHeader,
ithfWarning);
ShowHelperMessages(FGlobalOps.GroupMessages);
End;
End;
If eoBuildVersionResource In Ops Then
If ProjectOps.IncITHVerInfo Then
Begin
VersionMgr := TITHVersionManager.Create(FGlobalOps, ProjectOps, Project, FMsgMgr);
VersionMgr.BuildProjectVersionResource;
End;
Finally
TfrmITHProcessing.HideProcessing;
End;
End;
End;
Finally
ProjectOps := Nil;
End;
End;
(**
This is an null implementation for the BeforeCompile interface.
@precon None.
@postcon Not implemented.
@nocheck EmptyMethod
@nohint Project Cancel
@param Project as an IOTAProject as a constant
@param Cancel as a Boolean as a reference
**)
Procedure TITHelperIDENotifier.BeforeCompile(Const Project: IOTAProject;
Var Cancel: Boolean);
Begin //FI:W519
End;
(**
This method copies the version information from the first project dependency to this project IF the
option is enabled.
@precon Project must be a valid IOTAProject.
@postcon Copies the version information from the first project dependency to this project IF the
option is enabled.
@param Project as an IOTAProject as a constant
@param strProject as a String as a constant
@param ProjectOps as a IITHProjectOptions as a constant
**)
Procedure TITHelperIDENotifier.CopyVersionInfoFromDependency(Const Project: IOTAProject;
Const strProject: String; Const ProjectOps: IITHProjectOptions);
Const
strBugFix = ' abcedfghijklmnopqrstuvwxyz';
{$IFNDEF DXE20}
strMajorVersion = 'MajorVersion';
strMinorVersion = 'MinorVersion';
strRelease = 'Release';
strBuild = 'Build';
{$ENDIF}
ResourceString
strVersionDependencyFoundForProject = 'Version Dependency (%s) found for project %s.';
strDependentBuild = 'Dependent Build %d.%d%s (%d.%d.%d.%d).';
strDependencyWasNotFound = 'The dependency "%s" was not found. (%s)';
Var
iMajor, iMinor, iBugfix, iBuild: Integer;
Group: IOTAProjectGroup;
strTargetName: String;
{$IFDEF DXE20}
POC: IOTAProjectOptionsConfigurations;
AC: IOTABuildConfiguration;
{$ENDIF}
Begin
Group := ProjectGroup;
If Group = Nil Then
Exit;
strTargetName := ExpandMacro(ProjectOps.CopyVerInfo, Project.FileName);
If strTargetName <> '' Then
Begin
FMsgMgr.AddMsg(Format(strVersionDependencyFoundForProject,
[ExtractFileName(strTargetName), strProject]), fnHeader, ithfDefault);
If FileExists(strTargetName) Then
Begin
Try
BuildNumber(strTargetName, iMajor, iMinor, iBugfix, iBuild);
FMsgMgr.AddMsg(Format(strDependentBuild,
[iMajor, iMinor, strBugFix[iBugfix + 1], iMajor, iMinor, iBugfix, iBuild]),
fnHeader, ithfDefault);
{$IFDEF DXE20}
If Project.ProjectOptions.QueryInterface(IOTAProjectOptionsConfigurations, POC) = S_OK Then
Begin
AC := POC.ActiveConfiguration;
If AC.PropertyExists(sVerInfo_IncludeVerInfo) Then
If AC.AsBoolean[sVerInfo_IncludeVerInfo] Then
Raise EITHException.Create(strMsgBroken);
If Not ProjectOps.IncITHVerInfo Then
Raise EITHException.Create(strMsgCopyDisabled)
End;
{$ELSE}
If Not ProjectOps.IncITHVerInfo Then
Begin
If Project.ProjectOptions.Values[strMajorVersion] <> iMajor Then
Project.ProjectOptions.Values[strMajorVersion] := iMajor;
If Project.ProjectOptions.Values[strMinorVersion] <> iMinor Then
Project.ProjectOptions.Values[strMinorVersion] := iMinor;
If Project.ProjectOptions.Values[strRelease] <> iBugfix Then
Project.ProjectOptions.Values[strRelease] := iBugfix;
If Project.ProjectOptions.Values[strBuild] <> iBuild Then
Project.ProjectOptions.Values[strBuild] := iBuild;
End;
{$ENDIF}
If ProjectOps.IncITHVerInfo Then
Begin
If ProjectOps.Major <> iMajor Then
ProjectOps.Major := iMajor;
If ProjectOps.Minor <> iMinor Then
ProjectOps.Minor := iMinor;
If ProjectOps.Release <> iBugfix Then
ProjectOps.Release := iBugfix;
If ProjectOps.Build <> iBuild Then
ProjectOps.Build := iBuild;
End;
Except
On E: EITHException Do
FMsgMgr.AddMsg(Format(E.Message + ' (%s)', [strProject]), fnHeader, ithfWarning);
End;
ShowHelperMessages(FGlobalOps.GroupMessages);
End
Else
FMsgMgr.AddMsg(Format(strDependencyWasNotFound,
[strTargetName, strProject]), fnHeader, ithfWarning);
End;
End;
(**
A constructor for the TTestingHelperIDENotifier class.
@precon None.
@postcon Initialises the class.
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Constructor TITHelperIDENotifier.Create(Const GlobalOps: IITHGlobalOptions);
Const
iTimerIntervalInMSec = 100;
Begin
Inherited Create;
FGlobalOps := GlobalOps;
FMsgMgr := TITHMessageManager.Create(GlobalOps);
FLastSuccessfulCompile := 0;
FSuccessfulCompile := TTimer.Create(Nil);
FSuccessfulCompile.OnTimer := SuccessfulCompile;
FSuccessfulCompile.Interval := iTimerIntervalInMSec;
FSuccessfulCompile.Enabled := True;
FShouldBuildList := TStringList.Create;
FShouldBuildList.CaseSensitive := False;
End;
(**
A destructor for the TTestingHelperIDENotifier class.
@precon None.
@postcon Frees memory used by the class.
**)
Destructor TITHelperIDENotifier.Destroy;
Begin
FShouldBuildList.Free;
FSuccessfulCompile.Enabled := False;
FSuccessfulCompile.OnTimer := Nil;
FSuccessfulCompile.Free;
Inherited Destroy;
End;
(**
This method expands any macros found in the process information.
@precon Project must be a valid instance.
@postcon Expands any macros found in the process information.
@param Processes as a TITHProcessCollection as a constant
@param Project as an IOTAProject as a constant
**)
Procedure TITHelperIDENotifier.ExpandProcessMacro(Const Processes: TITHProcessCollection;
Const Project: IOTAProject);
Var
i: Integer;
P: TITHProcessInfo;
Begin
For i := 0 To Processes.Count - 1 Do
Begin
P := Processes[i];
P.FEXE := ExpandMacro(P.FEXE, Project.FileName);
P.FParams := ExpandMacro(P.FParams, Project.FileName);
P.FDir := ExpandMacro(P.FDir, Project.FileName);
Processes[i] := P;
End;
End;
(**
This method is a null implementation of the Wizards FileNotification interface.
@precon None.
@postcon None.
@nocheck EmptyMethod MissingCONSTInParam
@nohint NotifyCode FileName Cancel
@param NotifyCode as a TOTAFileNotification
@param FileName as a String as a constant
@param cancel as a Boolean as a reference
**)
Procedure TITHelperIDENotifier.FileNotification(NotifyCode: TOTAFileNotification;
Const FileName: String; Var Cancel: Boolean);
Begin //FI:W519
End;
(**
This is an on idle message handler for the DGHCreateProcess method.
@precon None.
@postcon Ensures the application processes its message queue.
**)
Procedure TITHelperIDENotifier.IdleHandler;
Begin
Application.ProcessMessages;
End;
(**
This method increments the buld number of the passed project IF this is enabled in the options.
@precon ProjectOps must be a valid instance.
@postcon Increments the buld number of the passed project IF this is enabled in the options.
@param ProjectOps as a IITHProjectOptions as a constant
@param Project as an IOTAProject as a constant
@param strProject as a String as a constant
**)
Procedure TITHelperIDENotifier.IncrementBuild(Const ProjectOps : IITHProjectOptions;
Const Project: IOTAProject; Const strProject: String);
ResourceString
strIncrementingBuildFromTo = 'Incrementing %s''s Build from %d to %d.';
{$IFNDEF DXE20}
Const
strBuild = 'Build';
{$ENDIF}
Var
iBuild: Integer;
{$IFDEF DXE20}
POC: IOTAProjectOptionsConfigurations;
AC: IOTABuildConfiguration;
{$ENDIF}
Begin
If ProjectOps.IncOnCompile Then
Begin
iBuild := -1;
{$IFDEF DXE20}
If Project.ProjectOptions.QueryInterface(IOTAProjectOptionsConfigurations, POC) = S_OK Then
Begin
AC := POC.ActiveConfiguration;
If AC.PropertyExists(sVerInfo_IncludeVerInfo) Then
If AC.AsBoolean[sVerInfo_IncludeVerInfo] Then
Raise EITHException.Create(strMsgBroken);
If Not ProjectOps.IncITHVerInfo Then
Raise EITHException.Create(strMsgIncBuildDisabled);
End;
{$ELSE}
If Not ProjectOps.IncITHVerInfo Then
iBuild := Project.ProjectOptions.Values[strBuild];
{$ENDIF}
If ProjectOps.IncITHVerInfo Then
iBuild := ProjectOps.Build;
If iBuild > -1 Then
FMsgMgr.AddMsg(Format(strIncrementingBuildFromTo,
[strProject, iBuild, iBuild + 1]), fnHeader, ithfDefault);
{$IFNDEF DXE20}
If Not ProjectOps.IncITHVerInfo Then
Project.ProjectOptions.Values[strBuild] := iBuild + 1;
{$ENDIF}
If ProjectOps.IncITHVerInfo Then
ProjectOps.Build := iBuild + 1;
End;
End;
(**
This method centralises the processing of the AfterCompile information.
This is so that its can be called from different versions of the
implementation.
@precon None.
@postcon Processes the AfterCompile information.
@nocheck MissingCONSTInParam
@param Project as an IOTAProject as a constant
@param Succeeded as a Boolean
@param IsCodeInsight as a Boolean
**)
Procedure TITHelperIDENotifier.ProcessAfterCompile(Const Project: IOTAProject;
Succeeded, IsCodeInsight: Boolean);
Const
strZIPToolFailure = 'ZIP Tool Failure (%s).';
ResourceString
strPostCompilation = 'Post-Compilation';
strPostCompilationToolsFailed = 'Post-Compilation Tools Failed (%s).';
Var
iResult: Integer;
strProject: String;
ProjectOps: IITHProjectOptions;
iIndex: Integer;
Ops: TITHEnabledOptions;
ZipMgr : IITHZipManager;
Begin
If Project = Nil Then
Exit;
If IsCodeInsight Or Not Succeeded Then
Exit;
iIndex := FShouldBuildList.IndexOf(Project.FileName);
If iIndex > -1 Then
Begin
FShouldBuildList.Delete(iIndex);
ProjectOps := FGlobalOps.ProjectOptions(Project);
Try
Ops := FGlobalOps.ProjectGroupOps;
If eoGroupEnabled In Ops Then
Try
strProject := GetProjectName(Project);
If eoIncrementBuild In Ops Then
IncrementBuild(ProjectOps, Project, strProject);
If eoZip In Ops Then
Begin
ZipMgr := TITHZIPManager.Create(Project, FGlobalOps, ProjectOps, FMsgMgr);
iResult := ZipMgr.ZipProjectInformation;
If iResult > 0 Then
Begin
TfrmITHProcessing.ShowProcessing(Format(strZIPToolFailure,
[strProject]), FGlobalOps.FontColour[ithfFailure], True);
ShowHelperMessages(FGlobalOps.GroupMessages);
Abort; //: @bug Stop IDE continuing if there was a problem - Change this to
//: return a signal to pass failure to the IDE notifier methods.
End;
End;
If eoAfter In Ops Then
Begin
iResult := ProcessCompileInformation(ProjectOps, Project, strPostCompilation);
If iResult > 0 Then
Begin
TfrmITHProcessing.ShowProcessing
(Format(strPostCompilationToolsFailed, [strProject]),
FGlobalOps.FontColour[ithfWarning], True);
ShowHelperMessages(FGlobalOps.GroupMessages);
Abort; //: @bug Stop IDE continuing if there was a problem.
End
Else If iResult < 0 Then
If ProjectOps.WarnAfter Then
Begin
FMsgMgr.AddMsg(Format(strAfterCompileWARNING, [strProject]),
fnHeader, ithfWarning);
ShowHelperMessages(FGlobalOps.GroupMessages);
End;
End;
FLastSuccessfulCompile := GetTickCount;
Finally
TfrmITHProcessing.HideProcessing;
End;
Finally
ProjectOps := Nil;
End;
End;
End;
(**
This method processes the list of external tools in the given section and runs each in a process and
captures the output. If any of the tools raises an Exit Code > 0 then this is added to the return
result.
@precon ProjectOps and Project must be a valid instances.
@postcon Processes the list of external tools in the given section and runs each in a process and
captures the output. If any of the tools raises an Exit Code > 0 then this is added to the
return result.
@param ProjectOps as a IITHProjectOptions as a constant
@param Project as an IOTAProject as a constant
@param strWhere as a String as a constant
@return an Integer
**)
Function TITHelperIDENotifier.ProcessCompileInformation(Const ProjectOps : IITHProjectOptions;
Const Project: IOTAProject; Const strWhere: String): Integer;
ResourceString
strRunning = 'Running: %s (%s %s)';
strProcessing = 'Processing %s...';
Var
Processes: TITHProcessCollection;
i, j: Integer;
strProject: String;
Begin
Result := -1; // Signifies no tools configured.
strProject := GetProjectName(Project);
Processes := TITHProcessCollection.Create;
Try
Processes.LoadFromINI(ProjectOps.INIFile, strWhere);
ExpandProcessMacro(Processes, Project);
If Processes.Count > 0 Then
Result := 0;
For i := 0 To Processes.Count - 1 Do
Begin
FMsgMgr.Clear;
If Processes[i].FEnabled Then
Begin
FMsgMgr.ParentMsg :=
FMsgMgr.AddMsg(Format(strRunning,
[ExtractFileName(Processes[i].FTitle), strProject, strWhere]), fnHeader, ithfHeader);
TfrmITHProcessing.ShowProcessing(Format(strProcessing,
[ExtractFileName(Processes[i].FTitle)]));
Inc(Result, DGHCreateProcess(Processes[i], ProcessMsgHandler, IdleHandler));
For j := 0 To FMsgMgr.Count - 1 Do
Case Result Of
0:FMsgMgr[j].ForeColour := FGlobalOps.FontColour[ithfSuccess];
Else
FMsgMgr[j].ForeColour := FGlobalOps.FontColour[ithfFailure];
End;
If Result <> 0 Then
FMsgMgr.ParentMsg.ForeColour := FGlobalOps.FontColour[ithfFailure];
ShowHelperMessages(FGlobalOps.GroupMessages);
If Result > 0 Then
Break;
End;
End;
Finally
Processes.Free;
End;
End;
(**
This is an on process Msg handler for the DGHCreateProcess method.
@precon None.
@postcon Outputs the messages from the process to the message window.
@nohint boolAbort
@param strMsg as a String as a constant
@param boolAbort as a Boolean as a reference
**)
Procedure TITHelperIDENotifier.ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean); //FI:O804
Begin
If strMsg <> '' Then
FMsgMgr.AddMsg(strMsg, fnTools, ithfDefault, FMsgMgr.ParentMsg.MessagePntr);
End;
(**
This is an on timer event handler for the SuccessfulCompile timer.
@precon None.
@postcon If the options is enabled this will switch the message view to the
helper messages 1 second after a successful compile.
@param Sender as a TObject
**)
Procedure TITHelperIDENotifier.SuccessfulCompile(Sender: TObject);
Begin
If FLastSuccessfulCompile + iMilliSecInSec > GetTickCount Then
Begin
FLastSuccessfulCompile := 0;
If FGlobalOps.SwitchToMessages Then
ShowHelperMessages(FGlobalOps.GroupMessages);
End;
End;
End.
|
unit UOrderClass;
interface
type
TOrderClass = class(TObject)
private
FIDOrder: Integer;
public
procedure SetIDOrder(const Value: Integer);
property IDOrder: Integer read FIDOrder write SetIDOrder;
end;
implementation
procedure TOrderClass.SetIDOrder(const Value: Integer);
begin
FIDOrder := Value;
end;
end.
|
{Unit F12lihatStatistik}
unit F12lihatS;
{Interface}
interface
uses typedata;
{Procedure F12lihatStatistik}
procedure F12lihatStatistik (var S : tabSimulasi; var N : integer);
{Fitur lihatStatistik yang dapat menampilkan progress dalam simulasi yang sedang berjalan}
{Implementation}
implementation
{Procedure F12lihatStatistik}
procedure F12lihatStatistik (var S : tabsimulasi; var N : integer);
{Algoritma Procedure}
begin
writeln (' | -------------------------------------------------------------------------- |');
writeln (' | STATISTIK |');
writeln (' | -------------------------------------------------------------------------- |');
writeln (' Nomor Simulasi : ', S.FS[N].Nomor);
writeln (' Tanggal : ', S.FS[N].Waktu.dd, '/', S.FS[N].Waktu.mm, '/', S.FS[N].Waktu.yy);
writeln (' Jumlah Hari Hidup : ', S.FS[N].Hidup);
writeln (' Jumlah Energi : ', S.FS[N].Energi);
writeln (' Jumlah Inventori : ', JmlI);
writeln (' Kapasitas Maksimum Inventori : ', S.FS[N].Kapasitas);
writeln (' Total Bahan Mentah Dibeli : ', S.FS[N].BeliMentah);
writeln (' Total Bahan Olahan Dibuat : ', S.FS[N].BuatOlahan);
writeln (' Total Bahan Olahan Dijual : ', S.FS[N].JualOlahan);
writeln (' Total Resep Dijual : ', S.FS[N].JualResep);
writeln (' Total Pemasukan : ', S.FS[N].Pemasukan);
writeln (' Total Pengeluaran : ', S.FS[N].Pengeluaran);
writeln (' Total Uang : ', S.FS[N].Saldo);
end;
end.
|
{$mode objfpc}
{$m+}
program Stack;
const MAX_SIZE = 100;
type
ArrayStack = class
private
arr : array[0..MAX_SIZE] of integer;
top : 0..MAX_SIZE;
public
constructor create();
function pop(): integer;
procedure push(i : integer);
end;
Node = record
val : integer;
next : ^Node;
end;
LinkedListStack = class
private
top : ^Node;
public
function pop(): integer;
procedure push(i : integer);
end;
function LinkedListStack.pop() : integer;
begin
if top = nil then
begin
writeln('nothing left in Stack');
pop := -1;
end
else
begin
writeln('poping ', top^.val);
pop := top^.val;
top := top^.next;
end;
end;
procedure LinkedListStack.push(i : integer);
var
A : ^Node;
begin
writeln('pushing ', i);
new(A);
A^.val := i;
A^.next := top;
top := A;
end;
constructor ArrayStack.create();
begin
top := 0;
end;
function ArrayStack.pop(): integer;
begin
if top > 0 then
begin
writeln('poping ', arr[top]);
pop := arr[top];
top := top -1;
end
else
begin
writeln('nothing left in Stack');
pop := -1;
end;
end;
procedure ArrayStack.push(i : integer);
begin
if top < MAX_SIZE then
begin
writeln('pushing ', i);
top := top +1;
arr[top] := i;
end
else
writeln('not enough space in Stack');
end;
var
Q : ArrayStack;
L : LinkedListStack;
a : integer;
begin
writeln('--ArrayStack--');
Q := ArrayStack.create();
Q.push(5);
Q.push(7);
Q.push(8);
Q.push(2);
Q.push(1);
Q.push(9);
repeat
a := Q.pop();
until a = -1;
writeln('--LinkedListStack--');
L := LinkedListStack.Create();
L.push(1);
L.push(2);
L.push(9);
L.push(8);
L.push(7);
L.push(9);
repeat
a := L.pop();
until a = -1;
end.
|
unit xUDPServer;
interface
uses System.Types,System.Classes, xFunction, system.SysUtils, xUDPServerBase,
xConsts, System.IniFiles, xClientType, Winapi.WinInet, winsock;
type
TUDPServer = class(TUDPServerBase)
private
FInfoServerPort: Integer;
FInfoServerIP: string;
procedure ReadINI;
procedure WriteINI;
protected
/// <summary>
/// 接收数据包
/// </summary>
procedure RevStrData(sIP: string; nPort :Integer; sStr: string); override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 服务器IP
/// </summary>
property InfoServerIP : string read FInfoServerIP write FInfoServerIP;
/// <summary>
/// 服务器端口
/// </summary>
property InfoServerPort : Integer read FInfoServerPort write FInfoServerPort;
/// <summary>
/// 连接服务器命令
/// </summary>
procedure SendConnServer;
end;
var
UDPServer : TUDPServer;
implementation
{ TTCPServer }
constructor TUDPServer.Create;
begin
inherited;
ReadINI;
end;
destructor TUDPServer.Destroy;
begin
WriteINI;
inherited;
end;
procedure TUDPServer.ReadINI;
function GetLocalIP(var LocalIp: string): Boolean;
var
HostEnt: PHostEnt;
IP: String;
Addr: PAnsiChar;
Buffer: array [0..63] of Char;
WSData: TWSADATA;
begin
Result := False;
try
WSAStartUp(2, WSData);
GetHostName(@Buffer, SizeOf(Buffer));
// Buffer:='ZhiDa16';
HostEnt := GetHostByName(@Buffer);
if HostEnt = nil then
exit;
Addr := HostEnt^.h_addr_list^;
IP := Format('%d.%d.%d.%d', [Byte(Addr[0]), Byte(Addr[1]), Byte(Addr[2]),
Byte(Addr[3])]);
LocalIp := IP;
Result := True;
finally
WSACleanup;
end;
end;
begin
with TIniFile.Create(sPubIniFileName) do
begin
FInfoServerIP := ReadString('UPDOption', 'ServerIP', '');
if FInfoServerIP = '' then
GetLocalIP(FInfoServerIP);
FInfoServerPort := ReadInteger('UPDOption', 'ServerPort', 15000);
ListenPort := ReadInteger('UPDOption', 'ListenPort', 16000);
Free;
end;
end;
procedure TUDPServer.RevStrData(sIP: string; nPort: Integer; sStr: string);
begin
inherited;
if sStr = 'GetServerInfo' then
begin
SendPacksDataUDP(sIP, ListenPort+1, FInfoServerIP + ',' + IntToStr(FInfoServerPort));
end;
end;
procedure TUDPServer.SendConnServer;
begin
SendPacksDataUDP('255.255.255.255', ListenPort+1, 'ConnectServer');
end;
procedure TUDPServer.WriteINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
WriteString('UPDOption', 'ServerIP', FInfoServerIP);
WriteInteger('UPDOption', 'ServerPort', FInfoServerPort);
Free;
end;
end;
end.
|
unit GraphsForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, TAGraph, TAChartTeeChart, TASeries,
TAChartUtils, TASources,
ComCtrls, ColorBox, StrUtils, Math, BenchmarkClassUnit;
const
{The number of kilobytes to add to the usage scores to "smooth out" the
influence of benchmarks that allocate very little memory. Many MMs have a
virtualalloc granularity of 1MB or more, and sometimes it is pure luck
whether they use one block less or one block more. The effect of this on
benchmarks that use very little memory can be dramatic. Adding a fixed number
to the memory usage alleviates this.}
MemoryScoreAdder = 20000;
type
{Record holding a result}
TBenchmarkResult = record
{The number of benchmarks run}
NumBenches: integer;
{The results}
case Integer of
1: (SpeedScore, MemoryScore, CombinedScore: double);
2: (Values: array[0..2] of Double)
end;
{Benchmark groups}
TBenchmarkGroupResult = record
{The description for the group}
GroupDescription: string;
{The categories of benchmarks inside this group}
Categories: TBenchmarkCategorySet;
{If this group is restricted to a single benchmark, the benchmark class}
SingleBenchmarkClass: TFastcodeMMBenchmarkClass;
{The results for all MMs in this group}
MMScores: array of TBenchmarkResult;
end;
TBenchmarkGroupResults = array of TBenchmarkGroupResult;
{The graphs form}
{ TfGraphs }
TfGraphs = class(TForm)
pBottom: TPanel;
bbClose: TBitBtn;
cbMemoryManager: TComboBox;
cbResults: TComboBox;
lGraph: TLabel;
lResults: TLabel;
Chart: TChart;
SaveDialog: TSaveDialog;
bSaveResults: TBitBtn;
Label1: TLabel;
cbBenchmarks: TComboBox;
cbResultType: TComboBox;
ListChartSource1: TListChartSource;
ColorListBox1: TColorListBox;
procedure GraphOptionChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure bSaveResultsClick(Sender: TObject);
private
FData: TStringList;
{The names of the memory managers}
FMMNames: TStringList;
{The names of the benchmarks}
FBenchmarkNames: TStringList;
{The benchmark class for each benchmark}
FBenchmarkClasses: array of TFastcodeMMBenchmarkClass;
{The global benchmark weight for each benchmark}
FBenchmarkWeights: array of double;
{The benchmark results in [mm][benchmark] order}
FResults: array of array of TBenchmarkResult;
{The benchmark results, per group}
FGroupResults: TBenchmarkGroupResults;
procedure LoadResults;
public
procedure BuildGraphs;
procedure LoadResultsFromFile(const AResultFile: string);
procedure LoadResultsFromStringList(const AList: TStringList);
procedure ShowSummary(Strings: TStrings);
procedure ExportTabbedSummary(Strings: TStrings);
end;
var
fGraphs: TfGraphs;
implementation
uses BenchmarkForm, IniFiles;
{$R *.lfm}
//Added for D6 - Perhaps an ifdef for delphi version is needed?
function PosEx(const SubStr, S: string; Offset: Cardinal = 1): Integer;
var
I,X: Integer;
Len, LenSubStr: Integer;
begin
if Offset = 1 then
Result := Pos(SubStr, S)
else
begin
I := Offset;
LenSubStr := Length(SubStr);
Len := Length(S) - LenSubStr + 1;
while I <= Len do
begin
if S[I] = SubStr[1] then
begin
X := 1;
while (X < LenSubStr) and (S[I + X] = SubStr[X + 1]) do
Inc(X);
if (X = LenSubStr) then
begin
Result := I;
exit;
end;
end;
Inc(I);
end;
Result := 0;
end;
end;
procedure TfGraphs.BuildGraphs;
var
LMMInd, LBenchmarkInd, LResultInd: integer;
LSeries: THorizBarSeries;
LResultName: string;
LResult: Double;
LGroup: TBenchmarkGroupResult;
LShowSummary: Boolean;
begin
{Clear current results}
Chart.Legend.Visible := True;
Chart.Series.Clear;
ListChartSource1.Clear;
{Get the benchmark group}
LGroup := FGroupResults[cbBenchmarks.ItemIndex];
{Show summary or detail?}
LShowSummary := (cbResultType.ItemIndex = 0) and (LGroup.Categories <> []);
{Step through all the memory managers}
for LMMind := 0 to FMMNames.Count - 1 do
begin
{Show this MM?}
if (cbMemoryManager.ItemIndex = 0)
or (cbMemoryManager.Text = FMMNames[LMMind]) then
begin
LSeries := THorizBarSeries.Create(Chart);
//LSeries.BarStyle := bsRectangle;
LSeries.BarOffsetPercent:= LMMind * 100 div (FMMNames.Count+1);
LSeries.BarWidthPercent:= 100 div (FMMNames.Count+1);
LSeries.BarWidthStyle:= bwPercentMin;
Chart.AddSeries(LSeries);
LSeries.ShowInLegend := True;
LSeries.SeriesColor:= RGBToColor(random(255), random(255), random(255));
LSeries.SeriesColor:= ColorListBox1.Colors[Chart.Series.Count];
LSeries.Marks.Visible := False;
LSeries.Title := FMMNames[LMMind];
{Step through all the benchmarks}
for LBenchmarkInd := 0 to FBenchmarkNames.Count - 1 do
begin
{Show this benchmark?}
if (LShowSummary and (LBenchmarkInd = 0)) //summary is index 0
or ((not LShowSummary) and (FBenchmarkClasses[LBenchmarkInd] = LGroup.SingleBenchmarkClass))
or ((not LShowSummary) and (FBenchmarkClasses[LBenchmarkInd].GetCategory in LGroup.Categories)) then
begin
{Step through all the results}
for LResultInd := 0 to 2 do
begin
{Show this result?}
if (LResultInd = cbResults.ItemIndex) or (cbResults.ItemIndex > 2) then
begin
{Add the result}
if LShowSummary then
begin
{Average result}
LResultName := 'Summary: ' + LGroup.GroupDescription;
case LResultInd of
0: LResult := LGroup.MMScores[LMMInd].SpeedScore;
1: LResult := LGroup.MMScores[LMMInd].MemoryScore;
else
LResult := LGroup.MMScores[LMMInd].CombinedScore;
end;
end
else
begin
LResultName := FBenchmarkNames[LBenchmarkInd];
{Get benchmark result}
LResult := FResults[LMMInd][LBenchmarkInd].Values[LResultInd];
end;
if cbResults.ItemIndex > 2 then
LResultName := LResultName + ' (' + cbResults.Items[LResultInd] + ')';
{Add the series}
LSeries.Add(LResult, LResultName, LSeries.SeriesColor);
if ListChartSource1.Count < LSeries.Count then
ListChartSource1.Add(LSeries.MaxXValue, LSeries.MaxXValue, LResultName);
end;
end;
end;
end;
end;
end;
end;
procedure TfGraphs.GraphOptionChange(Sender: TObject);
begin
BuildGraphs;
end;
procedure TfGraphs.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
procedure TfGraphs.FormCreate(Sender: TObject);
begin
FData := TStringList.Create;
FMMNames := TStringList.Create;
FMMNames.Sorted := True;
FMMNames.Duplicates := dupIgnore;
FBenchmarkNames := TStringList.Create;
FBenchmarkNames.Sorted := True;
FBenchmarkNames.Duplicates := dupIgnore;
end;
procedure TfGraphs.FormDestroy(Sender: TObject);
begin
FData.Free;
FMMNames.Free;
FBenchmarkNames.Free;
end;
procedure TfGraphs.LoadResults;
var
LCat: TBenchmarkCategory;
LInd, LInd2, LMMInd, LBenchInd, LScore, LOldBenchIndex, LGroupInd: integer;
LTempStr, LBenchName, LMMName: string;
LResult: TBenchmarkResult;
LTotalScore, LTotalSpeedScore, LTotalMemoryScore, LTotalWeight, LCombinedScore, LWeight: Double;
LMaxPerf, LMaxSpeedPerf, LMaxMemoryPerf: Double;
function DecodeResult(const AResultString: string;
var AMMName, ABenchmarkName: string; var AResult: TBenchmarkResult): boolean;
var
LDelimPos, LDelimPos2: integer;
begin
Result := False;
LDelimPos := Pos(';', LTempStr);
if LDelimPos > 1 then
begin
{Get the benchmark name}
ABenchmarkName := Copy(LTempStr, 1, LDelimPos - 1);
if ABenchmarkName[1] = '"' then
begin
Delete(ABenchmarkName, 1, 1);
Delete(ABenchmarkName, length(ABenchmarkName), 1);
end;
Inc(LDelimPos);
LDelimPos2 := PosEx(';', LTempStr, LDelimPos);
if LDelimPos2 > LDelimPos then
begin
{Get the mm name}
AMMName := Copy(LTempStr, LDelimPos, LDelimPos2 - LDelimPos);
LDelimPos := LDelimPos2 + 1;
{Get the ticks}
LDelimPos2 := PosEx(';', LTempStr, LDelimPos);
if LDelimPos2 > LDelimPos then
begin
LScore := StrToInt(Copy(LTempStr, LDelimPos, LDelimPos2 - LDelimPos));
if LScore > 0 then
AResult.SpeedScore := 1 / LScore
else
AResult.SpeedScore := 0;
LDelimPos := LDelimPos2 + 1;
{Get the peak memory}
LDelimPos2 := PosEx(';', LTempStr, LDelimPos);
if LDelimPos2 < 1 then
LDelimPos2 := 9999;
if LDelimPos2 > LDelimPos then
begin
LScore := StrToInt(Copy(LTempStr, LDelimPos, LDelimPos2 - LDelimPos));
if LScore > 0 then
AResult.MemoryScore := 1 / (LScore + MemoryScoreAdder)
else
AResult.MemoryScore := 0;
Result := True;
end;
end;
end;
end;
end;
procedure AddResultGroup(
const AGroupDescription: string;
ACategories: TBenchmarkCategorySet;
ASingleBenchmarkClass: TFastcodeMMBenchmarkClass = nil);
var
LInd, i: integer;
begin
LInd := length(FGroupResults);
SetLength(FGroupResults, LInd + 1);
FGroupResults[LInd].GroupDescription := AGroupDescription;
FGroupResults[LInd].Categories := ACategories;
FGroupResults[LInd].SingleBenchmarkClass := ASingleBenchmarkClass;
SetLength(FGroupResults[LInd].MMScores, FMMNames.Count);
{Clear the initial results}
for i := 0 to FMMNames.Count - 1 do
begin
FGroupResults[LInd].MMScores[i].NumBenches := 0;
FGroupResults[LInd].MMScores[i].SpeedScore := 0;
FGroupResults[LInd].MMScores[i].MemoryScore := 0;
FGroupResults[LInd].MMScores[i].CombinedScore := 0;
end;
end;
function IndexOfBenchmark(Name: String): Integer;
begin
for Result := 0 to fBenchmark.ListViewBenchmarks.Items.Count - 1 do
begin
if CompareText(fBenchmark.ListViewBenchmarks.Items[Result].Caption, Name) = 0 then
Exit;
end;
Result := -1;
end;
begin
{Get all the benchmarks and contestants}
FMMNames.Clear;
FBenchmarkNames.Clear;
for LInd := 0 to FData.Count - 1 do
begin
LTempStr := FData[LInd];
if DecodeResult(LTempStr, LMMName, LBenchName, LResult) then
begin
FMMNames.Add(LMMName);
FBenchmarkNames.Add(LBenchName);
end;
end;
{Build the list of benchmark result groups}
SetLength(FGroupResults, 0);
AddResultGroup('All', AllBenchmarkCategories);
AddResultGroup('Categories: All Single Thread', [bmSingleThreadRealloc, bmSingleThreadAllocAndFree, bmSingleThreadReplay]);
AddResultGroup('Categories: All Multithread', [bmMultiThreadRealloc, bmMultiThreadAllocAndFree, bmMultiThreadReplay]);
AddResultGroup('Categories: All Realloc', [bmSingleThreadRealloc, bmMultiThreadRealloc]);
AddResultGroup('Categories: All Alloc and Free', [bmSingleThreadAllocAndFree, bmMultiThreadAllocAndFree]);
AddResultGroup('Categories: All Replays', [bmSingleThreadReplay, bmMultiThreadReplay]);
AddResultGroup('Categories: All Memory Access Speed', [bmMemoryAccessSpeed]);
for LCat := low(TBenchmarkCategory) to high(TBenchmarkCategory) do
begin
AddResultGroup('Category: ' + BenchmarkCategoryNames[LCat], [LCat]);
end;
for LInd := 0 to high(Benchmarks) do
begin
AddResultGroup('Benchmark: ' + Benchmarks[LInd].GetBenchmarkName, [], Benchmarks[LInd]);
end;
{Set the benchmark name combo}
LOldBenchIndex := Max(0, cbBenchmarks.ItemIndex);
cbBenchmarks.Items.Clear;
for LInd := 0 to high(FGroupResults) do
begin
cbBenchmarks.Items.Add(FGroupResults[LInd].GroupDescription);
end;
{Get the class for each benchmark}
SetLength(FBenchmarkClasses, FBenchmarkNames.Count);
SetLength(FBenchmarkWeights, FBenchmarkNames.Count);
for LInd := 0 to FBenchmarkNames.Count - 1 do
begin
LBenchInd := IndexOfBenchmark(FBenchmarkNames[LInd]);
// LBenchInd := fBenchmark.lbBenchmarks.Items.IndexOf(FBenchmarkNames[LInd]);
if LBenchInd >= 0 then
begin
FBenchmarkClasses[LInd] := Benchmarks[LBenchInd];
FBenchmarkWeights[LInd] := GlobalBenchmarkWeights[LBenchInd];
end
else
begin
FBenchmarkClasses[LInd] := TFastcodeMMBenchmark;
FBenchmarkWeights[LInd] := 0;
end;
end;
{Add the contestants to the graphs}
while cbMemoryManager.Items.Count > 1 do
begin
cbMemoryManager.Items.Delete(1);
end;
for LInd := 0 to FMMNames.Count - 1 do
begin
cbMemoryManager.Items.Add(FMMNames[LInd]);
end;
{Reset the results}
Setlength(FResults, FMMNames.Count);
for LInd := 0 to FMMNames.Count - 1 do
begin
Setlength(FResults[LInd], FBenchmarkNames.Count);
for LInd2 := 0 to FBenchmarkNames.Count - 1 do
FillChar(FResults[LInd][LInd2], SizeOf(TBenchmarkResult), 0);
end;
{Read the results}
for LInd := 0 to FData.Count - 1 do
begin
LTempStr := FData[LInd];
if DecodeResult(LTempStr, LMMName, LBenchName, LResult) then
begin
LMMInd := FMMNames.IndexOf(LMMName);
LBenchInd := FBenchmarkNames.IndexOf(LBenchName);
with FResults[LMMInd][LBenchInd] do
begin
SpeedScore := SpeedScore + LResult.SpeedScore;
MemoryScore := MemoryScore + LResult.MemoryScore;
Inc(NumBenches);
end;
end;
end;
{Take the average score if a benchmark was run more than once for the same MM}
for LMMInd := 0 to FMMNames.Count - 1 do
begin
for LBenchInd := 0 to FBenchmarkNames.Count - 1 do
begin
with FResults[LMMInd][LBenchInd] do
begin
if NumBenches > 1 then
begin
SpeedScore := SpeedScore / NumBenches;
MemoryScore := MemoryScore / NumBenches;
end;
end;
end;
end;
{The maximum memory and speed score for each benchmark must be 100}
for LBenchInd := 0 to FBenchmarkNames.Count - 1 do
begin
OutputDebugString(PChar(IntToStr(LBenchInd)));
{Get the maximum value for the benchmark}
LResult.SpeedScore := 0;
LResult.MemoryScore := 0;
for LMMInd := 0 to FMMNames.Count - 1 do
begin
if FResults[LMMInd][LBenchInd].NumBenches > 0 then
begin
LResult.SpeedScore := Max(LResult.SpeedScore, FResults[LMMInd][LBenchInd].SpeedScore);
LResult.MemoryScore := Max(LResult.MemoryScore, FResults[LMMInd][LBenchInd].MemoryScore);
end;
end;
{Divide all scores by the maximum}
for LMMInd := 0 to FMMNames.Count - 1 do
begin
{Scale the results for each MM so that the best for the benchmark is 100}
if LResult.SpeedScore = 0 then
FResults[LMMInd][LBenchInd].SpeedScore := 0
else
FResults[LMMInd][LBenchInd].SpeedScore := FResults[LMMInd][LBenchInd].SpeedScore / LResult.SpeedScore * 100;
if LResult.MemoryScore = 0 then
FResults[LMMInd][LBenchInd].MemoryScore := 0
else
FResults[LMMInd][LBenchInd].MemoryScore := FResults[LMMInd][LBenchInd].MemoryScore / LResult.MemoryScore * 100;
{Calculate the relative performance for this benchmark and MM}
FResults[LMMInd][LBenchInd].CombinedScore :=
FResults[LMMInd][LBenchInd].SpeedScore * FBenchmarkClasses[LBenchInd].GetSpeedWeight
+ FResults[LMMInd][LBenchInd].MemoryScore * (1 - FBenchmarkClasses[LBenchInd].GetSpeedWeight);
end;
end;
{Calculate the performance of each MM for each group}
for LGroupInd := 0 to high(FGroupResults) do
begin
{Reset maximums}
LMaxPerf := 1;
LMaxSpeedPerf := 1;
LMaxMemoryPerf := 1;
{Step through all the MMs}
for LMMInd := 0 to FMMNames.Count - 1 do
begin
LTotalScore := 0;
LTotalSpeedScore := 0;
LTotalMemoryScore := 0;
LTotalWeight := 0;
for LBenchInd := 0 to FBenchmarkNames.Count - 1 do
begin
{Is the bench in the group?}
if ((FBenchmarkClasses[LBenchInd].GetCategory in FGroupResults[LGroupInd].Categories)
or (FBenchmarkClasses[LBenchInd] = FGroupResults[LGroupInd].SingleBenchmarkClass))
and (FResults[LMMInd][LBenchInd].NumBenches > 0) then
begin
LCombinedScore := FResults[LMMInd][LBenchInd].CombinedScore;
LWeight := FBenchmarkWeights[LBenchInd];
LTotalScore := LTotalScore + LCombinedScore * LWeight;
LTotalSpeedScore := LTotalSpeedScore + FResults[LMMInd][LBenchInd].SpeedScore * LWeight;
LTotalMemoryScore := LTotalMemoryScore + FResults[LMMInd][LBenchInd].MemoryScore * LWeight;
LTotalWeight := LTotalWeight + LWeight;
end;
end;
if LTotalWeight = 0 then // avoid potential divide by zero
LTotalWeight := 1; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{Store the results}
FGroupResults[LGroupInd].MMScores[LMMInd].CombinedScore := LTotalScore / LTotalWeight;
FGroupResults[LGroupInd].MMScores[LMMInd].SpeedScore := LTotalSpeedScore / LTotalWeight;
FGroupResults[LGroupInd].MMScores[LMMInd].MemoryScore := LTotalMemoryScore / LTotalWeight;
{Keep the top-scoring value}
LMaxPerf := Max(LMaxPerf, FGroupResults[LGroupInd].MMScores[LMMInd].CombinedScore);
LMaxSpeedPerf := Max(LMaxSpeedPerf, FGroupResults[LGroupInd].MMScores[LMMInd].SpeedScore);
LMaxMemoryPerf := Max(LMaxMemoryPerf, FGroupResults[LGroupInd].MMScores[LMMInd].MemoryScore);
end;
{Scale the scores of all MMs so that the winning MM has a score of 100}
for LMMInd := 0 to FMMNames.Count - 1 do
begin
if LMaxPerf <> 0 then
FGroupResults[LGroupInd].MMScores[LMMInd].CombinedScore := FGroupResults[LGroupInd].MMScores[LMMInd].CombinedScore / LMaxPerf * 100
else
raise Exception.Create('Fix this division by 0');
if LMaxSpeedPerf <> 0 then
FGroupResults[LGroupInd].MMScores[LMMInd].SpeedScore := FGroupResults[LGroupInd].MMScores[LMMInd].SpeedScore / LMaxSpeedPerf * 100
else
raise Exception.Create('Fix this division by 0');
if LMaxMemoryPerf <> 0 then
FGroupResults[LGroupInd].MMScores[LMMInd].MemoryScore := FGroupResults[LGroupInd].MMScores[LMMInd].MemoryScore / LMaxMemoryPerf * 100
else
raise Exception.Create('Fix this division by 0');
end;
end;
{Select a benchmark}
cbBenchmarks.ItemIndex := LOldBenchIndex;
{Select all MMs}
cbMemoryManager.ItemIndex := 0;
end;
// ----------------------------------------------------------------------------
procedure TfGraphs.LoadResultsFromFile(const AResultFile: string);
begin
if FileExists(AResultFile) then
FData.LoadFromFile(AResultFile)
else
FData.Clear;
LoadResults;
end;
// ----------------------------------------------------------------------------
procedure TfGraphs.LoadResultsFromStringList(const AList: TStringList);
begin
FData.Assign(AList);
LoadResults;
end;
procedure TfGraphs.bSaveResultsClick(Sender: TObject);
var
LLines: TStringList;
LMMInd, LBenchInd: integer;
begin
if SaveDialog.Execute then
begin
LLines := TStringList.Create;
LLines.Add('Fastcode MM Challenge Benchmark Results: ' + formatdatetime('d mmm yyyy HH:nn', now));
LLines.Add('');
try
for LBenchInd := 0 to FBenchmarkNames.Count - 1 do
begin
LLines.Add(Format('Benchmark: %s (Global Weight = %6.2f %%)',
[ FBenchmarkNames[LBenchInd], 100 * FBenchmarkWeights[LBenchInd] ]));
for LMMInd := 0 to FMMNames.Count - 1 do
begin
if FResults[LMMInd][LBenchInd].NumBenches > 0 then
begin
LLines.Add(Format(' %-11s : Speed Score =%6.1f, Memory Score =%6.1f, Combined Score =%6.1f',
[ FMMNames[LMMInd], FResults[LMMInd][LBenchInd].SpeedScore, FResults[LMMInd][LBenchInd].MemoryScore,
FResults[LMMInd][LBenchInd].CombinedScore]));
end
else
begin
LLines.Add(Format(' %-11s : Not Run', [ FMMNames[LMMInd] ]));
end;
end;
LLines.Add('');
end;
ShowSummary(LLines);
{Save it}
LLines.SaveToFile(SaveDialog.FileName);
finally
LLines.Free;
end;
end;
end;
procedure TfGraphs.ShowSummary(Strings: TStrings);
var
LMMInd: integer;
begin
Strings.Add('Average Total Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
begin
Strings.Add(Format(' %-11s : %6.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].CombinedScore]));
end;
Strings.Add('');
Strings.Add('Average Speed Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
begin
Strings.Add(Format(' %-11s : %6.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].SpeedScore]));
end;
Strings.Add('');
Strings.Add('Average Memory Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
begin
Strings.Add(Format(' %-11s : %6.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].MemoryScore ]));
end;
end;
procedure TfGraphs.ExportTabbedSummary(Strings: TStrings);
var
LMMInd: integer;
begin
Strings.Add('Average Total Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
Strings.Add(Format('%s'#9'%.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].CombinedScore ]));
Strings.Add('');
Strings.Add('Average Speed Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
Strings.Add(Format('%s'#9'%.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].SpeedScore ]));
Strings.Add('');
Strings.Add('Average Memory Performance: (Scaled so that the winner = 100%)');
for LMMInd := 0 to FMMNames.Count - 1 do
Strings.Add(Format('%s'#9'%.1f', [ FMMNames[LMMInd], FGroupResults[0].MMScores[LMMInd].MemoryScore ]));
end;
end.
|
Unit ictrl;
(***********************************************************)
(**) interface (**)
(***********************************************************)
const SaveFileName='.\sav\intrctrl.sav';
type ResetProcs = procedure of object;
type IntrCtrl=class
(***********************************************************)
(**) private (**)
(***********************************************************)
resets : array [0..20] of resetProcs;
Ndevices : byte;
(***********************************************************)
(**) public (**)
(***********************************************************)
PendingIntr:boolean; //This indicates which interrupt number is pending. Note by this you may specify any interrupt in VB.
pendingIntNo:byte; //This indicates if interrupt is pending.
interfaces_int:word;
procedure irq(channel:byte); //By this you may request an interruption.
procedure AddResets(r:resetProcs);
procedure StatusSave;
procedure StatusRestore;
constructor create; //Initialize and creates a new object.
procedure reset;
end;
(******************************************************************************)
(**) (**)
(**) implementation (**)
(**) (**)
(******************************************************************************)
Procedure IntrCtrl.irq(channel:byte);
begin
pendingintno:=channel;
pendingintr:=true;
end;
(******************************************************************************)
constructor IntrCtrl.create;
begin
PendingIntr:=false;
Ndevices:=0;
end;
(******************************************************************************)
procedure IntrCtrl.AddResets(r:resetProcs);
begin
resets[Ndevices]:=r;
inc(Ndevices);
end;
(******************************************************************************)
procedure IntrCtrl.reset;
var i:byte;
begin
for i:=0 to Ndevices-1 do resets[i];
end;
(******************************************************************************)
procedure IntrCtrl.StatusSave;
var f:file;
begin
assignfile(f,SaveFileName);
rewrite(f,1);
blockwrite(f,ndevices,1);
blockwrite(f,PendingIntr,4);
closefile(f);
end;
(******************************************************************************)
procedure IntrCtrl.StatusRestore;
var f:file;
begin
assignfile(f,SaveFileName);
system.reset(f,1);
blockread(f,ndevices,1);
blockread(f,PendingIntr,4);
closefile(f);
end;
end.
|
unit Lua;
interface
uses
Classes,Windows,LuaLib,GD_Utils;
type
TLuaState = Lua_State;
TLua = class(TObject)
private
fAutoRegister: Boolean;
CallbackList: TList;
public
LuaInstance: TLuaState; // Lua instance
constructor Create(AutoRegister: Boolean = True); overload; virtual;
destructor Destroy; override;
function DoString(Scripts: String): Integer;
function DoFile(Filename: String): Integer; virtual;// load file and execute
function ScriptError():string; //执行出错输出
Procedure Stop();
procedure RegisterFunction(FuncName: AnsiString; MethodName: AnsiString = ''; Obj: TObject = NIL); virtual; //register function
procedure AutoRegisterFunctions(Obj: TObject); // register all published functions
procedure UnregisterFunctions(Obj: TObject); // unregister all object functions
end;
implementation
type
TProc = function(L: TLuaState): Integer of object; // Lua Function
TCallback = class
FuncName:string;
Routine: TMethod; // Code and Data for the method
Exec: TProc; // Resulting execution function
end;
//
// This function is called by Lua, it extracts the object by
// pointer to the objects method by name, which is then called.
//
// @param Lua_State L Pointer to Lua instance
// @return Integer Number of result arguments on stack
//
function LuaCallBack(L: Lua_State): Integer; cdecl;
var
CallBack: TCallBack; // The Object stored in the Object Table
begin
// Retrieve first Closure Value (=Object Pointer)
CallBack := lua_topointer(L, lua_upvalueindex(1));
// Execute only if Object is valid
if (assigned(CallBack) and assigned(CallBack.Exec)) then
Result := CallBack.Exec(L)
else
Result := 0;
end;
{ TLua }
//
// Create a new Lua instance and optionally create Lua functions
//
// @param Boolean AutoRegister (optional)
// @return TLua Lua Instance
//
constructor TLua.Create(AutoRegister: Boolean = True);
begin
inherited Create;
if LoadLuaLib_Mem <> 0 then
begin
// if (not LuaLibLoaded) then
// LoadLuaLib;
LuaInstance := Lua_Open();
luaopen_base(LuaInstance);
fAutoRegister := AutoRegister;
CallBackList := TList.Create;
if (AutoRegister) then
AutoRegisterFunctions(self);
LogPrintf('脚本引擎加载完毕!',[]);
end;
end;
destructor TLua.Destroy;
begin
// Unregister all functions if previously autoregistered
if (fAutoRegister) then
UnregisterFunctions(Self);
// dispose Object List on finalization
CallBackList.Free;
// Close instance
Lua_Close(LuaInstance);
inherited;
end;
//
// Wrapper for Lua File load and Execution
//
// @param String Filename Lua Script file name
// @return Integer
//
function TLua.DoFile(Filename: String): Integer;
begin
try
Result := lual_dofile(LuaInstance, PAnsiChar(AnsiString(Filename)));
except
Result:=-1;
end;
end;
function TLua.DoString(Scripts: String): Integer;
begin
try
Result := luaL_dostring(LuaInstance, PAnsiChar(AnsiString(Scripts)));
except
Result:=-1;
end;
end;
//
// Register a new Lua Function and map it to the Objects method name
//
// @param AnsiString FuncName Lua Function Name
// @param AnsiString MethodName (optional) Objects Method name
//
procedure TLua.RegisterFunction(FuncName: AnsiString; MethodName: AnsiString = ''; Obj: TObject = NIL);
var
CallBack: TCallBack; // Callback Object
begin
// if method name not specified use Lua function name
if (MethodName = '') then
MethodName := FuncName;
// if not object specified use this object
if (Obj = NIL) then
Obj := Self;
// Add Callback Object to the Object Index
CallBack := TCallBack.Create;
CallBack.FuncName:=FuncName;
CallBack.Routine.Data := Obj;
CallBack.Routine.Code := Obj.MethodAddress(String(MethodName));
CallBack.Exec := TProc(CallBack.Routine);
CallbackList.Add(CallBack);
// prepare Closure value (Method Name)
lua_pushstring(LuaInstance, PAnsiChar(FuncName));
// prepare Closure value (CallBack Object Pointer)
lua_pushlightuserdata(LuaInstance, CallBack);
// set new Lua function with Closure value
lua_pushcclosure(LuaInstance, LuaCallBack, 1);
lua_settable(LuaInstance, LUA_GLOBALSINDEX);
end;
function TLua.ScriptError: string;
begin
Result := lua_tostring(LuaInstance, -1);
end;
procedure TLua.Stop;
begin
lua_close(LuaInstance);
end;
//
// UnRegister all new Lua Function
//
// @param TObject Object Object with prev registered lua functions
//
procedure TLua.UnregisterFunctions(Obj: TObject);
var
I: Integer;
CallBack: TCallBack;
begin
// remove obj from object list
for I := CallBackList.Count downto 1 do
begin
CallBack := CallBackList[I-1];
if (assigned(CallBack)) and (CallBack.Routine.Data = Obj) then
begin
CallBack.Free;
CallBackList.Items[I-1] := NIL;
CallBackList.Delete(I-1);
end;
end;
end;
//
// Register all published methods as Lua Functions
//
procedure TLua.AutoRegisterFunctions(Obj: TObject);
type
PPointer = ^Pointer;
PMethodRec = ^TMethodRec;
TMethodRec = packed record
wSize: Word;
pCode: Pointer;
sName: ShortString;
end;
var
MethodTable: PAnsiChar;
MethodRec: PMethodRec;
wCount: Word;
nMethod: Integer;
begin
// Get a pointer to the class's published method table
MethodTable := PAnsiChar(Pointer(PAnsiChar(Obj.ClassType) + vmtMethodTable)^);
if (MethodTable <> Nil) then
begin
// Get the count of the methods in the table
Move(MethodTable^, wCount, 2);
// Position the MethodRec pointer at the first method in the table
// (skip over the 2-byte method count)
MethodRec := PMethodRec(MethodTable + 2);
// Iterate through all the published methods of this class
for nMethod := 0 to wCount - 1 do
begin
// Add the method name to the lua functions
RegisterFunction(MethodRec.sName, MethodRec.sName, Obj);
// Skip to the next method
MethodRec := PMethodRec(PAnsiChar(MethodRec) + MethodRec.wSize);
end;
end;
end;
end. |
unit uGMV_FileEntry;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 12/20/07 12:44p $
* Developer: doma.user@domain.ext
* Site: Hines OIFO
*
* Description: File Entry
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/uGMV_FileEntry.pas $
*
* $History: uGMV_FileEntry.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSCOMMON
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/18/07 Time: 12:42p
* Updated in $/Vitals GUI 2007/Vitals-5-0-18/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsCommon
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:33p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:18p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSCOMMON
*
================================================================================
}
interface
uses
SysUtils
, Classes
, Dialogs
;
type
TGMV_FileReference = class(TObject)
private
FTypes: TStringList;
FDDNumber: string;
FFileName: string;
fLoadedLast: string; // zzzzzzandria 060801
fLoaded: Boolean; // zzzzzzandria 060801
function GetName(Index: integer): string;
public
constructor Create; virtual;
destructor Destroy; override;
procedure LoadEntries(FileNumber: string);
procedure LoadEntriesConverted(FileNumber: string);//AAN 01/22/2003 sorting problem
function LoadEntriesStartCount(FileNumber, StartNumber: string;
Count: Integer): Integer; // zzzzzzandria 060801
procedure Display;
function IndexOfIEN(IEN: string): integer;
function NameOfIEN(IEN:String):String;
property Name[Index: integer]: string read GetName;
property Loaded: Boolean read fLoaded;
// published
property Entries: TStringList read FTypes;
end;
TGMV_VitalType = class(TGMV_FileReference)
public
constructor Create; override;
destructor Destroy; override;
end;
TGMV_VitalQual = class(TGMV_FileReference)
public
constructor Create; override;
end;
TGMV_VitalCat = class(TGMV_FileReference)
public
constructor Create; override;
end;
TGMV_WardLocation = class(TGMV_FileReference)
public
constructor Create; override;
procedure LoadWards;
end;
TGMV_Teams = class(TGMV_FileReference)
public
constructor Create; override;
end;
TGMV_Clinics = class(TGMV_FileReference)
public
constructor Create; override;
end;
TGMV_NursingUnit = class(TGMV_FileReference)
public
constructor Create; override;
end;
TGMV_FileEntry = class(TObject)
private
FDDNumber: string;
FCaption: string;
FIEN: string;
FCaptionConverted:String;// AAN - sorting problem 01/21/2003
procedure SetCaption(const Value: string);
procedure SetCaptionConverted(const Value: string);// AAN - sorting problem 01/22/2003
procedure SetDDNumber(const Value: string);
procedure SetIEN(const Value: string);
function GetIENS: string;
public
constructor Create;
constructor CreateFromRPC(Data: string);
destructor Destroy; override;
function FieldData(FieldNumber: string): string;
// published
property DDNumber: string read FDDNumber write SetDDNumber;
property IEN: string read FIEN write SetIEN;
property Caption: string read FCaption write SetCaption;
property CaptionConverted: string read FCaptionConverted write SetCaptionConverted; // AAN - sorting problem 01/21/2003
property IENS: string read GetIENS;
end;
var
GMVTypes: TGMV_VitalType;
GMVQuals: TGMV_VitalQual;
GMVCats: TGMV_VitalCat;
GMVWardLocations: TGMV_WardLocation;
GMVTeams: TGMV_Teams;
GMVClinics: TGMV_CLinics;
GMVNursingUnits: TGMV_NursingUnit;
procedure CreateGMVGlobalVars;
procedure ReleaseGMVGlobalVars;
const
LOAD_LIMIT = 10;
procedure InitVitalsIENS;
implementation
uses uGMV_Common
, uGMV_Utils
, uGMV_VitalTypes
, uGMV_Engine
;
{ GMV_VitalType }
constructor TGMV_FileReference.Create;
begin
FTypes := TStringList.Create;
fLoaded := False; // zzzzzzandria 060801
fLoadedLast := ''; // zzzzzzandria 060801
end;
destructor TGMV_FileReference.Destroy;
Procedure ClearListObjects(aSL: TStringList);
var
I: integer;
begin
for I := 0 to aSL.Count - 1 do
begin
if Assigned(aSL.Objects[i]) then
begin
if aSL.Objects[i] is TGMV_FileEntry then
TGMV_FileEntry(aSL.Objects[i]).Free;
end;
end;
end;
begin
ClearListObjects(FTypes);
FreeAndNil(FTypes);
inherited;
end;
procedure TGMV_FileReference.LoadEntries(FileNumber: string);
var
i: integer;
fe: TGMV_FileEntry;
RetList: TStrings;
s, sCaption: String;
AddItem: Boolean;
begin
FDDNumber := FileNumber;
RetList := getFileEntries(FDDNumber);
try
if RetList.Count > 0 then
begin
FFileName := Copy(RetList[0], Pos('^', RetList[0]), Length(RetList[0]));
FTypes.Sorted := True; //AAN 08/08/2002
for i := 1 to RetList.Count - 1 do
begin
AddItem := true;
s := RetList[i];
if (FTypes.Duplicates = dupIgnore) or (FTypes.Duplicates = dupError) then
begin
sCaption := Piece(s, '^', 2);
AddItem := FTypes.IndexOf(sCaption) = -1;
end;
if AddItem then
begin
fe := TGMV_FileEntry.CreateFromRPC(s);
FTypes.AddObject(fe.Caption, fe);
end;
end;
end;
fLoaded := True;
finally
RetList.Free;
end;
end;
procedure TGMV_FileReference.LoadEntriesConverted(FileNumber: string);
var
i: integer;
fe: TGMV_FileEntry;
s: String;
RetList: TStrings;
begin
FDDNumber := FileNumber;
// pulling records in several steps to avoid timeouts
s := '0';
repeat
s := FileNumber + '^'+ s;
RetList := getFileEntries(s);
if RetList.Count > 0 then
begin
FFileName := Copy(RetList[0], Pos('^', RetList[0]), Length(RetList[0]));
FTypes.Sorted := True; //AAN 08/08/2002
for i := 1 to RetList.Count - 1 do
begin
fe := TGMV_FileEntry.CreateFromRPC(RetList[i]);
FTypes.AddObject(fe.CaptionConverted, fe);
s := fe.FIEN;
end;
if RetList.Count < 12 then
s := '';
end;
RetList.Free;
until s = '';
fLoaded := True;
end;
function TGMV_FileReference.LoadEntriesStartCount(FileNumber, StartNumber: string;
Count: Integer): Integer;
var
iCount, i: integer;
fe: TGMV_FileEntry;
s: String;
RetList: TStrings;
begin
FTypes.Sorted := True;
FDDNumber := FileNumber;
fLoadedLast := StartNumber;
iCount := Count;
repeat
s := FileNumber + '^'+ fLoadedLast;
RetList := getFileEntries(s);
if RetList.Count > 1 then
begin
FFileName := Copy(RetList[0], Pos('^', RetList[0]), Length(RetList[0]));
for i := 1 to RetList.Count - 1 do // zzzzzzandria 060801
begin
fe := TGMV_FileEntry.CreateFromRPC(RetList[i]);
FTypes.AddObject(fe.CaptionConverted, fe);
fLoadedLast := fe.FIEN;
dec(iCount);
if iCount = 0 then break;
end;
if i < RetList.Count-1 then
begin
s := '';
if iCount > 0 then
fLoaded := True;
end;
end
else
begin
fLoaded := True;
break;
end;
RetList.Free;
until (s = '') or (iCount=0);
Result := Count - iCount;
end;
function TGMV_FileReference.IndexOfIEN(IEN: string): integer;
var
i: integer;
begin
Result := -1;
for i := 0 to FTypes.Count - 1 do
if TGMV_FileEntry(FTypes.Objects[i]).IEN = IEN then
begin
Result := i;
Exit;
end;
end;
function TGMV_FileReference.NameOfIEN(IEN:String):String;
begin
try
result := FTypes[IndexOfIEN(IEN)];
except
Result := '';
end;
end;
procedure TGMV_FileReference.Display;
var
x: string;
i: integer;
begin
x := Self.ClassName + ' display' + #13 +
'FileName: ' + FFileName + #13 +
'Data Dictionary: ' + FDDNumber;
for i := 0 to FTypes.Count - 1 do
x := x + #13 + 'IEN: ' + TGMV_FileEntry(FTypes.Objects[i]).IEN + #9 + FTypes[i];
ShowMessage(x); {Debug tool!}
end;
function TGMV_FileReference.GetName(Index: integer): string;
var
i: integer;
begin
if Index = 0 then
Result := ''
else
begin
Result := '*No Such Entry*';
for i := 0 to FTypes.Count - 1 do
if integer(FTypes.Objects[i]) = Index then
begin
Result := FTypes[i];
Exit;
end;
end;
end;
{ TGMV_VitalType }
constructor TGMV_VitalType.Create;
begin
inherited Create;
LoadEntries('120.51');
end;
destructor TGMV_VitalType.Destroy;
begin
inherited Destroy;
end;
{ TGMV_VitalQual }
constructor TGMV_VitalQual.Create;
begin
inherited Create;
LoadEntries('120.52');
end;
{ TGMV_VitalCat }
constructor TGMV_VitalCat.Create;
begin
inherited Create;
LoadEntries('120.53');
end;
{ TGMV_WardLocation }
constructor TGMV_WardLocation.Create;
begin
inherited Create;
//LoadEntries('42');
end;
procedure TGMV_WardLocation.LoadWards;
var
i: integer;
fe: TGMV_FileEntry;
RetList: TStrings;
s,sName,sID: String;
begin
FDDNumber := '42';
RetList := getWardLocations('A');// Return ALL Wards
try
if RetList.Count > 0 then
begin
// FFileName := Copy(RetList[0], Pos('^', RetList[0]), Length(RetList[0]));
FFileName := '42';
FTypes.Sorted := True; //AAN 08/08/2002
// for i := 1 to RetList.Count - 1 do
for i := 0 to RetList.Count - 1 do
begin
s := RetList[i];
sName := piece(s,'^',2);
sID := piece(s,'^',3);
// fe := TGMV_FileEntry.CreateFromRPC(RetList[i]);
fe := TGMV_FileEntry.CreateFromRPC('42;'+sID+'^'+sName);
FTypes.AddObject(fe.Caption, fe);
end;
end;
fLoaded := True;
finally
RetList.Free;
end;
end;
{ TGMV_Teams }
constructor TGMV_Teams.Create;
begin
inherited Create;
//LoadEntries('100.21');
end;
{ TGMV_CLinics }
constructor TGMV_Clinics.Create;
begin
inherited Create;
//LoadEntries('44');
end;
{ TGMV_NursingUnit }
constructor TGMV_NursingUnit.Create;
begin
inherited Create;
//LoadEntries('211.4');
end;
{ TGMV_FileEntry }
constructor TGMV_FileEntry.Create;
begin
inherited;
end;
constructor TGMV_FileEntry.CreateFromRPC(Data: string);
begin
inherited Create;
FDDNumber := Piece(Data, ';', 1);
FIEN := Piece(Piece(Data, ';', 2), '^', 1);
FCaption := Piece(Data, '^', 2);
FCaptionConverted := ReplacePunctuation(FCaption)+' ('+FIEN+')'; //AAN 01/21/2003 - Sorting Problem
FCaptionConverted := ReplacePunctuation(FCaption); //AAN 05/21/2003 - hiding IENS
end;
destructor TGMV_FileEntry.Destroy;
begin
inherited;
end;
procedure TGMV_FileEntry.SetCaption(const Value: string);
begin
FCaption := Value;
end;
// AAN - sorting problem 01/22/2003
procedure TGMV_FileEntry.SetCaptionConverted(const Value: string);
begin
FCaptionConverted := Value;
end;
procedure TGMV_FileEntry.SetDDNumber(const Value: string);
begin
FDDNumber := Value;
end;
procedure TGMV_FileEntry.SetIEN(const Value: string);
begin
FIEN := Value;
end;
function TGMV_FileEntry.GetIENS: string;
begin
GetIENS := FIEN + ',';
end;
function TGMV_FileEntry.FieldData(FieldNumber: string): string;
begin
Result := getFileField(FDDNumber,FieldNumber,IENS);
end;
procedure InitVitalsIENS;
var
SL : TStringList;
begin
try
SL := getVitalsIDList;
if SL.Count = 11 then
begin // the order of Vitals is fixed in the routine
GMVVitalTypeIEN[vtUnknown] := SL[0];
GMVVitalTypeIEN[vtTemp] := SL[1];
GMVVitalTypeIEN[vtPulse] := SL[2];
GMVVitalTypeIEN[vtResp] := SL[3];
GMVVitalTypeIEN[vtBP] := SL[4];
GMVVitalTypeIEN[vtHeight] := SL[5];
GMVVitalTypeIEN[vtWeight] := SL[6];
GMVVitalTypeIEN[vtPain] := SL[7];
GMVVitalTypeIEN[vtPO2] := SL[8];
GMVVitalTypeIEN[vtCVP] := SL[9];
GMVVitalTypeIEN[vtCircum] := SL[10];
end;
SL.Free;
except
end;
end;
procedure CreateGMVGlobalVars;
begin
if not Assigned(GMVTypes) then
GMVTypes := TGMV_VitalType.Create;
InitVitalsIENS;//AAN 12/04/02 Fixed Vitals types code update
if not Assigned(GMVQuals) then
GMVQuals := TGMV_VitalQual.Create;
if not Assigned(GMVCats) then
GMVCats := TGMV_VitalCat.Create;
end;
procedure ReleaseGMVGlobalVars;
begin
FreeAndNil(GMVCats);
FreeAndNil(GMVQuals);
FreeAndNil(GMVTypes);
end;
end.
|
program ALGOTP1_FICHIERS_FB1_Wehrling_Axel;
uses crt, sysutils;
const
VerbeInfi='rire recevoir aller bouillir envoyer peindre habiter payer mourrir hair vouloir finir amuser ';
VerbeGroupe2='finis hais ';
VerbeIssant='finissant haissant ';
var
FichInfini,FichIssant : TextFile;
//BUT: Procedure qui crée un fichier text avec des verbes à l'infinitif.
//ENTREE: Fichier Text.
//SORTIE: Fichier Text avec une liste de verbe.
procedure CreaFichierInfinitif(var FichInfini:Textfile);
var
//Compteur est la variable qui va garder la possition de la lettre juste après le dernier espace.
i,compteur : integer;
//verifchar est la variable intermédiaire qui va servir au test pour savoir si le Caractère est un 'espace'.
verifchar:string;
//Variable qui récupére le verbe.
verbe:string;
begin
Assign(FichInfini,'FichierVerbeInfini.txt');
rewrite(FichInfini);
compteur:=1;
for i:=1 to length(VerbeInfi) do
begin
verifchar:=copy(VerbeInfi,i,1);
if (verifchar=' ') then
begin
//i est la position de l'espace, donc (i-compteur)=longueur du verbe.
//compteur quant à lui est la première lettre
verbe:=copy(VerbeInfi,compteur,i-compteur);
writeln(FichInfini,verbe);
//met le compteur sur la position de la première lettre du prochain verbe.
compteur:=i+1;
end;
end;
close(FichInfini);
end;
//BUT: Procedure qui crée un fichier text avec des verbes du 2 ème groupe au participe passé.
//ENTREE: Fichier Text.
//SORTIE: Fichier Text avec une liste de verbe.
procedure CreaFichierIssant(var FichIssant:Textfile);
var
i,compteur : integer;
verifchar:string;
verbe:string;
begin
Assign(FichIssant,'FichierVerbeIssant.txt');
rewrite(FichIssant);
compteur:=1;
for i:=1 to length(VerbeIssant) do
begin
verifchar:=copy(VerbeIssant,i,1);
if (verifchar=' ') then
begin
verbe:=copy(VerbeIssant,compteur,i-compteur);
writeln(FichIssant,verbe);
compteur:=i+1;
end;
end;
close(FichIssant);
end;
//BUT: Fonction qui vérifie si le mot existe dans la liste de verbe à l'infinitif.
//ENTREE: Une chaine de caractère.
//SORTIE: Booleen.
function VerifVerbe () : boolean;
var
//Variable qui va être comparée au mot entré par l'utilisateur.
verif, VerbeEntr : string;
//Booleen qui va prendre la valeur 'true' si le verbe entré est dans la liste de verbe.
Test, TestSave : boolean;
begin
repeat
begin
writeln('Veuillez entrer un verbe à l''infinitif.');
readln(VerbeEntr);
VerbeEntr:=lowercase(VerbeEntr);
reset(FichInfini);
Test:=false;
TestSave:=false;
While not (Eof(FichInfini)) do
begin
readln(FichInfini,verif);
if (VerbeEntr=verif) then
Test:=true
else
Test:=false;
if (Test=true) then
TestSave:=true
end;
if (TestSave=false) then
writeln('Ce verbe n''existe pas/n''est pas dans la liste!');
end;
until (TestSave=true) ;
VerifVerbe:=Test;
end;
BEGIN
clrscr;
CreaFichierInfinitif(FichInfini);
CreaFichierIssant(FichIssant);
VerifVerbe();
readln;
END.
|
unit clntfrm;
{
This is the client side of the Briefcase demo. The Connected checkbox shows
if the server is connected or not. Notice that the FileName property of the
ClientDataSet is set. This causes the ClientDataSet to load from the file
when it is opened and save to the file when it is closed. It also has the
ProviderName property set. This allows it to ApplyUpdates and retrieve data
if the file does not exist.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBClient, MConnect, StdCtrls, Db, Grids, DBGrids, ActnList, ExtCtrls;
type
TForm1 = class(TForm)
DCOMConnection1: TDCOMConnection;
ClientDataSet1: TClientDataSet;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
Button1: TButton;
CheckBox1: TCheckBox;
ActionList1: TActionList;
Action1: TAction;
Action2: TAction;
procedure Action1Update(Sender: TObject);
procedure Action2Execute(Sender: TObject);
procedure Action2Update(Sender: TObject);
procedure ClientDataSet1ReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
procedure Action1Execute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses recerror;
{$R *.dfm}
procedure TForm1.Action1Update(Sender: TObject);
begin
Action1.Checked := DCOMConnection1.Connected;
end;
procedure TForm1.Action1Execute(Sender: TObject);
begin
DCOMConnection1.Connected := not Action1.Checked;
end;
procedure TForm1.Action2Update(Sender: TObject);
begin
Action2.Enabled := ClientDataSet1.ChangeCount > 0;
end;
procedure TForm1.Action2Execute(Sender: TObject);
begin
ClientDataSet1.ApplyUpdates(-1);
end;
procedure TForm1.ClientDataSet1ReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
begin
Action := HandleReconcileError(DataSet, UpdateKind, E);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientDataSet1.Open;
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ For 16-bit applications only }
{ }
{ Copyright (c) 1995, 1996 AO ROSNO }
{ }
{*******************************************************}
unit rxStr16;
interface
{$IFNDEF WIN32}
{$I RX.INC}
type
ShortString = string;
PShortString = ^ShortString;
AnsiChar = Char;
PAnsiChar = ^AnsiChar;
{ System32 unit functions and procedures }
procedure SetLength(var S: string; NewLength: Byte);
procedure SetString(var S: string; Buffer: PChar; Len: Byte);
procedure UniqueString(var S: string);
{ SysUtils32 unit functions and procedures }
function Trim(const S: string): string;
function TrimLeft(const S: string): string;
function TrimRight(const S: string): string;
function QuotedStr(const S: string): string;
{$ENDIF WIN32}
implementation
{$IFNDEF WIN32}
uses SysUtils;
procedure SetLength(var S: string; NewLength: Byte);
begin
S[0] := Char(NewLength);
end;
procedure SetString(var S: string; Buffer: PChar; Len: Byte);
begin
S[0] := Char(Len);
if Buffer <> nil then begin
if StrLen(Buffer) < Len then Len := StrLen(Buffer);
Move(Buffer^, S[1], Len);
end;
end;
procedure UniqueString(var S: string);
begin
end;
function Trim(const S: string): string;
var
I, L: Byte;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= ' ') do Inc(I);
if I > L then Result := ''
else begin
while S[L] <= ' ' do Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
function TrimLeft(const S: string): string;
var
I, L: Byte;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= ' ') do Inc(I);
Result := Copy(S, I, 255);
end;
function TrimRight(const S: string): string;
var
I: Byte;
begin
I := Length(S);
while (I > 0) and (S[I] <= ' ') do Dec(I);
Result := Copy(S, 1, I);
end;
function QuotedStr(const S: string): string;
var
I: Byte;
begin
Result := S;
for I := Length(Result) downto 1 do
if Result[I] = '''' then Insert('''', Result, I);
Result := '''' + Result + '''';
end;
{$ENDIF WIN32}
end. |
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program NKNUMFRE;
Var
a,b,count :LongInt;
function Divisor(x,y :LongInt):LongInt;
var
t :LongInt;
begin
while (y>0) do
begin
t:=x mod y; x:=y; y:=t;
end;
Divisor:=x;
end;
function Inve(i :LongInt) :LongInt;
begin
Inve:=0;
while (i>0) do
begin
Inve:=Inve*10+(i mod 10);
i:=i div 10;
end;
end;
procedure Process;
var
i :LongInt;
begin
count:=0;
for i:=a to b do
if (Divisor(i,Inve(i))=1) then Inc(count);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
ReadLn(a,b);
Process;
Write(count);
Close(Input); Close(Output);
End. |
unit ff7edit;
interface
Uses CosmoUtil, FFLzs, Classes, SysUtils, DebugLog, FF7Ed,
PluginTypes, FF7Types, BaseUtil;
{$DEFINE TEMPDUMP}
Type
TFF7Level = class
private
FTextItems: TList;
DCmp,OCmp: TMemoryStream;
FOldMidi,FMidi: Byte;
FOffset,FSize,FStart,FFOffset:Integer;
RewriteScript: Boolean;
procedure Cleanup;
procedure Init;
function GetNumText: Integer;
function GetItem(Index:Integer): TFF7TextItem;
procedure SetItem(Index:Integer;Item:TFF7TextItem);
public
Constructor Create;
Constructor CreateFromFile(FName:String);
Constructor CreateFromStream(Strm:TStream);
Destructor Destroy; Override;
procedure LoadFromFile(FName:String);
procedure LoadFromStream(Strm:TStream);
procedure SaveToFile(FName:String);
procedure SaveToStream(Strm:TStream);
procedure Clear;
function OriginalData: TMemoryStream;
function DecompressedData: TMemoryStream;
function MakeDiff(Original:TFF7Level): TMemoryStream;
function ApplyDiff(Diff:TMemoryStream): Boolean;
property TextItems[Index:Integer]: TFF7TextItem read GetItem write SetItem; default;
property NumTextItems: Integer read GetNumText;
property MidiIndex: Byte read FMidi write FMidi;
end;
var
DefTextFactor: Integer = 13;
implementation
Constructor TFF7Level.Create;
begin
Inherited;
Init;
end;
Constructor TFF7Level.CreateFromFile(FName:String);
begin
Inherited;
Init;
LoadFromFile(FName);
end;
Constructor TFF7Level.CreateFromStream(Strm:TStream);
begin
Inherited;
Init;
LoadFromStream(Strm);
end;
Destructor TFF7Level.Destroy;
begin
Cleanup;
FTextItems.Free;
Inherited;
end;
function TFF7Level.OriginalData: TMemoryStream;
begin
Result := TMemoryStream.Create;
Result.CopyFrom(OCmp,0);
end;
function TFF7Level.DecompressedData: TMemoryStream;
begin
Result := TMemoryStream.Create;
Result.CopyFrom(DCmp,0);
end;
procedure TFF7Level.Clear;
begin
Cleanup;
end;
procedure TFF7Level.LoadFromFile(FName:String);
var
Fil: TFileStream;
begin
Fil := TFileStream.Create(FName, fmOpenRead or fmShareDenyNone);
LoadFromStream(Fil);
Fil.Free;
end;
procedure TFF7Level.LoadFromStream(Strm:TStream);
var
Decode,Txt: TMemoryStream;
Tmp: TStringList;
First,Next: String;
Scale,CurOS,Last,Cur,I: Integer;
Tbl: TList;
PI: ^Integer;
PB: PByte;
Item: PFF7TextItem;
Info: TTextInfoRec;
begin
Cleanup; DCmp := nil;
OCmp := TMemoryStream.Create;
OCmp.CopyFrom(Strm,0);
OCmp.Position := 0;
OCmp.ReadBuffer(I,4);
If I<>OCmp.Size-4 then Exit;
OCmp.Position := 0;
DCmp := LZS_DecompressS(OCmp);
Info.Factor := DefTextFactor;
Txt := FF7_ExtractText(DCmp,Tbl,Info);
Tmp := TStringList.Create;
Decode := TMemoryStream.Create;
{$IFDEF TEMPDUMP}
Txt.SaveToFile('C:\temp\text.dump');
DCmp.SaveToFile('C:\temp\file.dump');
For CurOS := 0 to Tbl.Count-1 do
Tmp.Add(IntToStr(Integer(Tbl[CurOS])));
Tmp.SaveToFile('C:\temp\table.dump');
Tmp.Clear;
{$ENDIF}
try
Log('Decompressed text.');
If Txt.Size=0 then Exit;
FOffset := Info.Offset;
FSize := Info.Size;
FStart := Info.Start;
FFOffset := Info.FileOffset;
RewriteScript := Info.UsedScriptOffset;
PB := DCmp.Memory;
Inc(PB,FOffset + FSize);
Cur := Min($FF, (DCmp.Size)-(FOffset+FSize) );
For I := 1 to Cur do begin
PI := Pointer(PB);
Inc(PB);
If PI^=AKAO_CODE then begin
Inc(PB,3);
FMidi := PB^-1;
FOldMidi := FMidi;
Break;
end;
If I=$FF then FMidi := $FF;
end;
Scale := 0;
CurOS := Tbl.Count;
If Tbl.Count>0 then begin
While (Tbl.Count>0) and ( (Integer(Tbl[0]) < 0) or (Integer(Tbl[0]) > Txt.Size) ) do
Tbl.Delete(0);
If CurOS=Tbl.Count then Scale := -Integer(Tbl[0]);
end;
If Tbl.Count<1 then Exit;
Last := Integer(Tbl[0])+Scale;
For I := 1 to Tbl.Count do begin
If I<Tbl.Count then Cur := Integer(Tbl[I]) else Cur := Txt.Size;
Inc(Cur,Scale);
Decode.Clear;
Txt.Position := Last;
If (Last < 0) or (Cur > Txt.Size) or (Cur < Last) then Break;
Decode.CopyFrom(Txt,Cur-Last);
Tmp.Clear;
Tmp.Text := (FF7_DecodeText(Decode));
First := Tmp[0]; If Tmp.Count>1 then Next := Tmp[1] else Next := '';
New(Item);
FTextItems.Add(Item);
Tmp.Delete(0);
Item^.Name := '';
Item^.Changed := False;
If BeginsWith(First,'[Begin]') then Item^.TextType := ff7MiscSpeech
else if BeginsWith(Next,'[Begin]') then begin
Item^.TextType := ff7NameSpeech;
Item^.Name := First;
end else Item^.TextType := ff7Misc;
If BeginsWith(Next,'[Begin]') then begin
First := Next; Tmp.Delete(0);
end;
Repeat
If BeginsWith(First,'[Begin]') then Delete(First,1,7);
If EndsWith(First,'[End]') then Delete(First,Length(First)-4,5);
Item^.Text := Item^.Text + #13#10 + First;
If Tmp.Count>0 then begin
First := Tmp[0]; Tmp.Delete(0);
end else Break;
Until (First = '[End of dialogue]');
If BeginsWith(Item^.Text,#13#10) then Delete(Item^.Text,1,2);
Last := Cur;
end;
finally
Tbl.Free;
Tmp.Free;
Decode.Free;
Txt.Free;
end;
end;
procedure TFF7Level.SaveToFile(FName:String);
var
Fil: TFileStream;
begin
Fil := TFileStream.Create(FName, fmCreate or fmShareDenyWrite);
SaveToStream(Fil);
Fil.Free;
end;
function PreProcess(Item:TFF7TextItem;Last:Boolean):String;
var
I: Integer;
Orig: String;
begin
Orig := Item.Text;
If EndsWith(Orig,#13#10) and Item.Changed then Delete(Orig,Length(Orig)-1,2);
If Item.TextType <> ff7Misc then Orig := '[Begin]'+Orig;
If Item.TextType = ff7NameSpeech then
Orig := Item.Name +#13#10+ Orig;
If (Not Last) and (Item.TextType <> ff7Misc) then Orig := Orig+'[End]';
Orig := Orig + #13#10'[End of dialogue]'#13#10;
Repeat
I := Pos(#13#10'[NewScreen]'#13#10,Orig);
If I<>0 then
Orig := Copy(Orig,1,I-1) + '[End]'#13#10'[Tobe...]'#13#10'[Begin]' + Copy(Orig,I+15,Length(Orig));
Until I=0;
Repeat
I := Pos('[Tobe...]',Orig);
If I<>0 then
Orig := Copy(Orig,1,I-1) + '[NewScreen]' + Copy(Orig,I+9,Length(Orig));
Until I=0;
Result := Orig;
end;
procedure TFF7Level.SaveToStream(Strm:TStream);
var
S: String;
NewD,MemS: TMemoryStream;
Old,Change,CurOS,J,I: Integer;
W: Word;
Tbl: TList;
PI: ^Integer;
PB: PByte;
Item: PFF7TextItem;
begin
NewD := TMemoryStream.Create;
Tbl := TList.Create;
Tbl.Add(Pointer(-FTextItems.Count-2));
CurOS := 0;
For I := 0 to FTextItems.Count-1 do begin
Item := FTextItems[I];
S := PreProcess(Item^,I=FTextItems.Count-1);
MemS := FF7_EncodeText(PChar(S));
If (I=FTextItems.Count-1) then MemS.Size := MemS.Size-1;
NewD.CopyFrom(MemS,0);
Tbl.Add(Pointer(CurOS));
Inc(CurOS,MemS.Size);
MemS.Free;
end;
Change := NewD.Size - FSize;
//NewBlkSize := NewD.Size;
MemS := NewD;
NewD := TMemoryStream.Create;
Dcmp.Position := 0;
NewD.Size := DCmp.Size;
NewD.CopyFrom(DCmp,FStart);
For I := 0 to Tbl.Count-1 do begin
J := Integer(Tbl[I]);
W := J + 2*Tbl.Count;
NewD.WriteBuffer(W,2);
end;
MemS.Position := 0;
NewD.CopyFrom(MemS,MemS.Size);
DCmp.Position := FOffset + FSize;
NewD.CopyFrom(DCmp,DCmp.Size - DCmp.Position);
PB := NewD.Memory;
Inc(PB,FStart + MemS.Size + 2*Tbl.Count);
If (FMidi<>$FF) and (FMidi<>FOldMidi) then
For I := 1 to 24 do begin
PI := Pointer(PB); Inc(PB);
If PI^=AKAO_CODE then begin
Inc(PB,3);
PB^ := FMidi+1;
Break;
end;
end;
MemS.Free;
Tbl.Free;
NewD.Position := 2;
NewD.ReadBuffer(J,4);
For I := 1 to J do begin
NewD.ReadBuffer(CurOS,4);
Old := NewD.Position;
If I>1 then begin
CurOS := CurOS + Change;
NewD.Seek(-4,soFromCurrent);
NewD.WriteBuffer(CurOS,4);
end else begin
NewD.Position := CurOS;
NewD.ReadBuffer(CurOS,4);
CurOS := CurOS + Change;
NewD.Seek(-4,soFromCurrent);
NewD.WriteBuffer(CurOS,4);
NewD.Position := Old;
end;
end;
NewD.Position := FFOffset;
NewD.ReadBuffer(CurOS,4);
CurOS := CurOS + Change;
NewD.Seek(-4,soFromCurrent);
If RewriteScript then NewD.WriteBuffer(CurOS,4);
MemS := DodgyCompressSO(NewD);
Strm.CopyFrom(MemS,0);
NewD.Free;
MemS.Free;
end;
procedure TFF7Level.Cleanup;
var
PItem: PFF7TextItem;
I: Integer;
begin
For I := 0 to FTextItems.Count-1 do begin
PItem := FTextItems[I];
Dispose(PItem);
end;
FTextItems.Clear;
If DCmp<>nil then DCmp.Free; DCmp := nil;
If OCmp<>nil then OCmp.Free; OCmp := nil;
end;
procedure TFF7Level.Init;
begin
FTextItems := TList.Create;
DCmp := nil; OCmp := nil;
end;
function TFF7Level.GetItem(Index:Integer): TFF7TextItem;
var
PItem: PFF7TextItem;
begin
PItem := FTextItems[Index];
Result := PItem^;
end;
procedure TFF7Level.SetItem(Index:Integer;Item:TFF7TextItem);
var
PItem: PFF7TextItem;
begin
PItem := FTextItems[Index];
PItem^ := Item;
PItem^.Changed := True;
end;
function TFF7Level.GetNumText: Integer;
begin
Result := FTextItems.Count;
end;
function TFF7Level.MakeDiff(Original:TFF7Level): TMemoryStream;
var
I: Integer;
OItem,NItem: TFF7TextItem;
WTmp,NA: Word;
begin
Result := TMemoryStream.Create;
NA := $FFFF;
If Original.NumTextItems = NumTextItems then begin
Result.WriteBuffer(Original.FOffset,4);
Result.WriteBuffer(Original.FSize,4);
Result.WriteBuffer(Original.FStart,4);
Result.WriteBuffer(Original.FFOffset,4);
I := NumTextItems;
Result.WriteBuffer(I,4);
Result.WriteBuffer(Self.MidiIndex,1);
For I := 0 to FTextItems.Count-1 do begin
OItem := Original.TextItems[I];
NItem := Self.TextItems[I];
If OItem.Name <> NItem.Name then begin
WTmp := Length(NItem.Name);
Result.WriteBuffer(WTmp,2);
Result.WriteBuffer(NItem.Name,Length(NItem.Name)+1);
end else Result.WriteBuffer(NA,2);
If OItem.Text <> NItem.Text then begin
WTmp := Length(NItem.Text);
Result.WriteBuffer(WTmp,2);
Result.WriteBuffer(PChar(NItem.Text)^,Length(NItem.Text));
end else Result.WriteBuffer(NA,2);
end;
end;
If Result.Size<=(21+4*NumTextItems) then begin
Result.Free;
Result := nil;
end;
end;
function TFF7Level.ApplyDiff(Diff:TMemoryStream): Boolean;
var
WTmp: Word;
Item: TFF7TextItem;
I,ITmp: Integer;
BTmp: Byte;
begin
Result := False;
Diff.ReadBuffer(ITmp,4);
If FOffset<>ITmp then Exit;
Diff.ReadBuffer(ITmp,4);
If FSize<>ITmp then Exit;
Diff.ReadBuffer(ITmp,4);
If FStart<>ITmp then Exit;
Diff.ReadBuffer(ITmp,4);
If FFOffset<>ITmp then Exit;
Diff.ReadBuffer(ITmp,4);
If NumTextItems<>ITmp then Exit;
Diff.ReadBuffer(BTmp,1);
MidiIndex := BTmp;
For I := 0 to FTextItems.Count-1 do begin
Item := Self.TextItems[I];
Diff.ReadBuffer(WTmp,2);
If WTmp<>$FFFF then begin
SetLength(Item.Name,WTmp);
Diff.ReadBuffer(Item.Name,WTmp+1);
end;
Diff.ReadBuffer(WTmp,2);
If WTmp<>$FFFF then begin
SetLength(Item.Text,WTmp);
Diff.ReadBuffer(PChar(Item.Text)^,WTmp);
end;
Self.TextItems[I] := Item;
end;
Result := True;
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1995, 1996 AO ROSNO }
{ Copyright (c) 1997, 1998 Master-Bank }
{ }
{*******************************************************}
unit rxDBLists;
{$I RX.INC}
{$N+,P+,S-}
interface
uses
SysUtils, Classes, DB, DBTables, rxDBUtils, rxBdeUtils,
Windows, Bde;
type
{ TBDEItems }
TBDEItemType = (bdDatabases, bdDrivers, bdLangDrivers, bdUsers, bdRepositories);
TCustomBDEItems = class(TBDEDataSet)
private
FItemType: TBDEItemType;
FSessionName: string;
FSessionLink: TDatabase;
function GetDBSession: TSession;
procedure SetSessionName(const Value: string);
procedure SetItemType(Value: TBDEItemType);
protected
function GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE}
Integer; override {$ENDIF};
procedure OpenCursor {$IFDEF RX_D3}(InfoQuery: Boolean){$ENDIF}; override;
procedure CloseCursor; override;
function CreateHandle: HDBICur; override;
property ItemType: TBDEItemType read FItemType write SetItemType
default bdDatabases;
public
{$IFDEF RX_D3}
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
{$ENDIF}
property DBSession: TSession read GetDBSession;
{$IFNDEF RX_D3}
property RecordCount: Longint read GetRecordCount;
{$ENDIF}
published
property SessionName: string read FSessionName write SetSessionName;
end;
TBDEItems = class(TCustomBDEItems)
published
property ItemType;
end;
{ TDBListDataSet }
TDBListDataSet = class(TDBDataSet)
protected
function GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE}
Integer; override {$ENDIF};
public
{$IFDEF RX_D3}
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
{$ELSE}
property RecordCount: Longint read GetRecordCount;
{$ENDIF}
end;
{ TDatabaseItems }
TDBItemType = (dtTables, dtStoredProcs, dtFiles, dtFunctions);
TCustomDatabaseItems = class(TDBListDataSet)
private
FExtended: Boolean;
FSystemItems: Boolean;
FFileMask: string;
FItemType: TDBItemType;
procedure SetFileMask(const Value: string);
procedure SetExtendedInfo(Value: Boolean);
procedure SetSystemItems(Value: Boolean);
procedure SetItemType(Value: TDBItemType);
protected
function CreateHandle: HDBICur; override;
function GetItemName: string;
property ItemType: TDBItemType read FItemType write SetItemType
default dtTables;
property ExtendedInfo: Boolean read FExtended write SetExtendedInfo
default False;
property FileMask: string read FFileMask write SetFileMask;
property SystemItems: Boolean read FSystemItems write SetSystemItems
default False;
public
property ItemName: string read GetItemName;
end;
TDatabaseItems = class(TCustomDatabaseItems)
published
property ItemType;
property ExtendedInfo;
property FileMask;
property SystemItems;
end;
{ TTableItems }
TTabItemType = (dtFields, dtIndices, dtValChecks, dtRefInt,
dtSecurity, dtFamily);
TCustomTableItems = class(TDBListDataSet)
private
FTableName: TFileName;
FItemType: TTabItemType;
FPhysTypes: Boolean;
procedure SetTableName(const Value: TFileName);
procedure SetItemType(Value: TTabItemType);
procedure SetPhysTypes(Value: Boolean);
protected
function CreateHandle: HDBICur; override;
property ItemType: TTabItemType read FItemType write SetItemType
default dtFields;
property PhysTypes: Boolean read FPhysTypes write SetPhysTypes
default False; { for dtFields only }
published
property TableName: TFileName read FTableName write SetTableName;
end;
TTableItems = class(TCustomTableItems)
published
property ItemType;
property PhysTypes;
end;
{ TDatabaseDesc }
TDatabaseDesc = class(TObject)
private
FDescription: DBDesc;
public
constructor Create(const DatabaseName: string);
property Description: DBDesc read FDescription;
end;
{ TDriverDesc }
TDriverDesc = class(TObject)
private
FDescription: DRVType;
public
constructor Create(const DriverType: string);
property Description: DRVType read FDescription;
end;
{*************************************************************************}
{$IFNDEF CBUILDER}
{ Obsolete classes, for backward compatibility only }
type
TDatabaseList = class(TCustomBDEItems);
TLangDrivList = class(TCustomBDEItems)
constructor Create(AOwner: TComponent); override;
end;
TTableList = class(TCustomDatabaseItems)
public
function GetTableName: string;
published
property ExtendedInfo;
property FileMask;
property SystemItems;
end;
TStoredProcList = class(TCustomDatabaseItems)
public
constructor Create(AOwner: TComponent); override;
published
property ExtendedInfo;
property SystemItems;
end;
TFieldList = class(TCustomTableItems);
TIndexList = class(TCustomTableItems)
constructor Create(AOwner: TComponent); override;
end;
{$ENDIF CBUILDER}
implementation
uses DBConsts, {$IFDEF RX_D3} BDEConst, {$ENDIF} RxDConst;
{ Utility routines }
function dsGetRecordCount(DataSet: TBDEDataSet): Longint;
begin
if DataSet.State = dsInactive then _DBError(SDataSetClosed);
Check(DbiGetRecordCount(DataSet.Handle, Result));
end;
type
TSessionLink = class(TDatabase)
private
FList: TCustomBDEItems;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
constructor TSessionLink.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if (AOwner <> nil) and (AOwner is TSession) then
SessionName := TSession(AOwner).SessionName;
Temporary := True;
KeepConnection := False;
end;
destructor TSessionLink.Destroy;
begin
if FList <> nil then begin
FList.FSessionLink := nil;
FList.Close;
end;
inherited Destroy;
end;
{ TCustomBDEItems }
procedure TCustomBDEItems.SetItemType(Value: TBDEItemType);
begin
if ItemType <> Value then begin
CheckInactive;
FItemType := Value;
end;
end;
function TCustomBDEItems.CreateHandle: HDBICur;
begin
case FItemType of
bdDatabases: Check(DbiOpenDatabaseList(Result));
bdDrivers: Check(DbiOpenDriverList(Result));
bdLangDrivers: Check(DbiOpenLdList(Result));
bdUsers: Check(DbiOpenUserList(Result));
bdRepositories: Check(DbiOpenRepositoryList(Result));
end;
end;
function TCustomBDEItems.GetDBSession: TSession;
begin
Result := Sessions.FindSession(SessionName);
if Result = nil then
{$IFDEF RX_D3}
Result := DBTables.Session;
{$ELSE}
Result := DB.Session;
{$ENDIF}
end;
procedure TCustomBDEItems.SetSessionName(const Value: string);
begin
CheckInactive;
FSessionName := Value;
DataEvent(dePropertyChange, 0);
end;
procedure TCustomBDEItems.OpenCursor;
var
S: TSession;
begin
S := Sessions.List[SessionName];
S.Open;
Sessions.CurrentSession := S;
FSessionLink := TSessionLink.Create(S);
try
TSessionLink(FSessionLink).FList := Self;
inherited OpenCursor{$IFDEF RX_D3}(InfoQuery){$ENDIF};
except
FSessionLink.Free;
FSessionLink := nil;
raise;
end;
end;
procedure TCustomBDEItems.CloseCursor;
begin
inherited CloseCursor;
if FSessionLink <> nil then begin
TSessionLink(FSessionLink).FList := nil;
FSessionLink.Free;
FSessionLink := nil;
end;
end;
function TCustomBDEItems.GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE} Integer {$ENDIF};
begin
Result := dsGetRecordCount(Self);
end;
{$IFDEF RX_D3}
function TCustomBDEItems.Locate(const KeyFields: string;
const KeyValues: Variant; Options: TLocateOptions): Boolean;
begin
DoBeforeScroll;
Result := DataSetLocateThrough(Self, KeyFields, KeyValues, Options);
if Result then begin
DataEvent(deDataSetChange, 0);
DoAfterScroll;
end;
end;
{$ENDIF RX_D3}
{ TDBListDataSet }
{$IFDEF RX_D3}
function TDBListDataSet.Locate(const KeyFields: string;
const KeyValues: Variant; Options: TLocateOptions): Boolean;
begin
DoBeforeScroll;
Result := DataSetLocateThrough(Self, KeyFields, KeyValues, Options);
if Result then begin
DataEvent(deDataSetChange, 0);
DoAfterScroll;
end;
end;
{$ENDIF RX_D3}
function TDBListDataSet.GetRecordCount: {$IFNDEF RX_D3} Longint {$ELSE} Integer {$ENDIF};
begin
Result := dsGetRecordCount(Self);
end;
{ TCustomDatabaseItems }
procedure TCustomDatabaseItems.SetItemType(Value: TDBItemType);
begin
if ItemType <> Value then begin
CheckInactive;
FItemType := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TCustomDatabaseItems.SetFileMask(const Value: string);
begin
if FileMask <> Value then begin
if Active and (FItemType in [dtTables, dtFiles]) then begin
DisableControls;
try
Close;
FFileMask := Value;
Open;
finally
EnableControls;
end;
end
else FFileMask := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TCustomDatabaseItems.SetExtendedInfo(Value: Boolean);
begin
if FExtended <> Value then begin
CheckInactive;
FExtended := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TCustomDatabaseItems.SetSystemItems(Value: Boolean);
begin
if FSystemItems <> Value then begin
if Active and (FItemType in [dtTables, dtStoredProcs]) then begin
DisableControls;
try
Close;
FSystemItems := Value;
Open;
finally
EnableControls;
end;
end
else FSystemItems := Value;
DataEvent(dePropertyChange, 0);
end;
end;
function TCustomDatabaseItems.CreateHandle: HDBICur;
var
WildCard: PChar;
Pattern: array[0..DBIMAXTBLNAMELEN] of Char;
begin
WildCard := nil;
if FileMask <> '' then
WildCard := AnsiToNative(DBLocale, FileMask, Pattern, SizeOf(Pattern) - 1);
case FItemType of
dtTables: Check(DbiOpenTableList(DBHandle, FExtended, FSystemItems, WildCard, Result));
dtStoredProcs:
if DataBase.IsSQLBased then
Check(DbiOpenSPList(DBHandle, FExtended, FSystemItems, nil, Result))
else DatabaseError(LoadStr(SLocalDatabase));
dtFiles: Check(DbiOpenFileList(DBHandle, WildCard, Result));
dtFunctions:
if DataBase.IsSQLBased then
Check(DbiOpenFunctionList(DBHandle, DBIFUNCOpts(FExtended), @Result))
else DatabaseError(LoadStr(SLocalDatabase));
end;
end;
function TCustomDatabaseItems.GetItemName: string;
const
sObjListNameField = 'NAME';
sFileNameField = 'FILENAME';
sTabListExtField = 'EXTENSION';
var
Temp: string;
Field: TField;
begin
Result := '';
if not Active then Exit;
if FItemType = dtFiles then Field := FindField(sFileNameField)
else Field := FindField(sObjListNameField);
if Field = nil then Exit;
Result := Field.AsString;
if FItemType in [dtTables, dtFiles] then begin
Field := FindField(sTabListExtField);
if Field = nil then Exit;
Temp := Field.AsString;
if Temp <> '' then begin
if Temp[1] <> '.' then Temp := '.' + Temp;
Result := Result + Temp;
end;
end;
end;
{ TCustomTableItems }
procedure TCustomTableItems.SetItemType(Value: TTabItemType);
begin
if ItemType <> Value then begin
CheckInactive;
FItemType := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TCustomTableItems.SetPhysTypes(Value: Boolean);
begin
if Value <> PhysTypes then begin
if Active and (ItemType = dtFields) then begin
DisableControls;
try
Close;
FPhysTypes := Value;
Open;
finally
EnableControls;
end;
end
else FPhysTypes := Value;
DataEvent(dePropertyChange, 0);
end;
end;
procedure TCustomTableItems.SetTableName(const Value: TFileName);
begin
if Value <> FTableName then begin
if Active then begin
DisableControls;
try
Close;
FTableName := Value;
if FTableName <> '' then Open;
finally
EnableControls;
end;
end
else FTableName := Value;
DataEvent(dePropertyChange, 0);
end;
end;
function TCustomTableItems.CreateHandle: HDBICur;
var
STableName: PChar;
begin
if FTableName = '' then _DBError(SNoTableName);
STableName := StrAlloc(Length(FTableName) + 1);
try
AnsiToNative(DBLocale, FTableName, STableName, Length(FTableName));
case FItemType of
dtFields:
while not CheckOpen(DbiOpenFieldList(DBHandle, STableName, nil,
FPhysTypes, Result)) do {Retry};
dtIndices:
while not CheckOpen(DbiOpenIndexList(DBHandle, STableName, nil,
Result)) do {Retry};
dtValChecks:
while not CheckOpen(DbiOpenVchkList(DBHandle, STableName, nil,
Result)) do {Retry};
dtRefInt:
while not CheckOpen(DbiOpenRintList(DBHandle, STableName, nil,
Result)) do {Retry};
dtSecurity:
while not CheckOpen(DbiOpenSecurityList(DBHandle, STableName, nil,
Result)) do {Retry};
dtFamily:
while not CheckOpen(DbiOpenFamilyList(DBHandle, STableName, nil,
Result)) do {Retry};
end;
finally
StrDispose(STableName);
end;
end;
{ TDatabaseDesc }
constructor TDatabaseDesc.Create(const DatabaseName: string);
var
Buffer: PChar;
begin
Buffer := StrPCopy(StrAlloc(Length(DatabaseName) + 1), DatabaseName);
try
Check(DbiGetDatabaseDesc(Buffer, @FDescription));
finally
StrDispose(Buffer);
end;
end;
{ TDriverDesc }
constructor TDriverDesc.Create(const DriverType: string);
var
Buffer: PChar;
begin
Buffer := StrPCopy(StrAlloc(Length(DriverType) + 1), DriverType);
try
Check(DbiGetDriverDesc(Buffer, FDescription));
finally
StrDispose(Buffer);
end;
end;
{*************************************************************************}
{$IFNDEF CBUILDER}
{ TLangDrivList }
constructor TLangDrivList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItemType := bdLangDrivers;
end;
{ TTableList }
function TTableList.GetTableName: string;
begin
Result := ItemName;
end;
{ TStoredProcList }
constructor TStoredProcList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItemType := dtStoredProcs;
end;
{ TIndexList }
constructor TIndexList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItemType := dtIndices;
end;
{$ENDIF CBUILDER}
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.